8000 RELEASE ENG-268 Util script by leite08 · Pull Request #3925 · metriport/metriport · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

RELEASE ENG-268 Util script #3925

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
May 30, 2025
Merged

RELEASE ENG-268 Util script #3925

merged 7 commits into from
May 30, 2025

Conversation

leite08
Copy link
Member
@leite08 leite08 commented May 30, 2025

Issues:

Dependencies

none

Description

Testing

Check each PR.

Release Plan

  • ⚠️ Points to master
  • Merge this

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Introduced a script to ingest patient data from a CSV file into OpenSearch, with detailed progress and error reporting.
  • Chores
    • Removed a log statement related to patient index initialization and count.
    • Increased timeout duration for patient data ingestion process to improve reliability.

keshavsaharia and others added 4 commits 8000 May 30, 2025 03:30
Backmerge master into develop
Backmerge master into develop
Ref eng-268

Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
ENG-268 Add script to ingest pts from CSV
Copy link
linear bot commented May 30, 2025

Copy link
coderabbitai bot commented May 30, 2025

Walkthrough

A log statement was removed from the patient ingestion route, leaving the logic unchanged. Additionally, a new TypeScript script was added to ingest patient data from a CSV file into OpenSearch, with support for chunked processing, error handling, and concurrency control. The Lambda function timeout setting was increased from 3 to 5 minutes.

Changes

File(s) Change Summary
packages/api/src/routes/internal/medical/patient-consolidated.ts Removed a log statement related to index initialization and patient ID count prior to ingestion.
packages/utils/src/open-search/ingest-patients.ts Added a new script for ingesting patient data from CSV into OpenSearch, including chunked requests and error handling.
packages/infra/lib/lambdas-nested-stack-settings.ts Increased Lambda timeout from 3 minutes to 5 minutes in consolidated ingestion connector settings.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Script
    participant API

    User->>Script: Run ingest-patients.ts with CSV file
    Script->>Script: Parse CSV, normalize IDs, group by customer
    loop For each chunk of 100 patients (5 concurrent)
        Script->>API: POST /internal/medical/patient-consolidated (with patient IDs)
        API-->>Script: Responds with ingestion result
        alt Failure
            Script->>Script: Log error, record failed chunk
        end
    end
    Script->>User: Output summary and error report
Loading

Possibly related PRs

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error code ERR_SSL_WRONG_VERSION_NUMBER
npm error errno ERR_SSL_WRONG_VERSION_NUMBER
npm error request to https://10.0.0.28:4873/punycode/-/punycode-2.3.1.tgz failed, reason: C03C852B267F0000:error:0A00010B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:354:
npm error
npm error A complete log of this run can be found in: /.npm/_logs/2025-05-30T17_09_56_058Z-debug-0.log


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 08c4cae and 56b30df.

📒 Files selected for processing (2)
  • packages/infra/lib/lambdas-nested-stack-settings.ts (1 hunks)
  • packages/utils/src/open-search/ingest-patients.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/utils/src/open-search/ingest-patients.ts
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.ts`: - Use the Onion Pattern to organize a package's code in layers - Try to use immutable code and avoid sharing state across different functions, objects, and systems - Try...

**/*.ts: - Use the Onion Pattern to organize a package's code in layers

  • Try to use immutable code and avoid sharing state across different functions, objects, and systems
  • Try to build code that's idempotent whenever possible
  • Prefer functional programming style functions: small, deterministic, 1 input, 1 output
  • Minimize coupling / dependencies
  • Avoid modifying objects received as parameter
  • Only add comments to code to explain why something was done, not how it works
  • Naming
    • classes, enums: PascalCase
    • constants, variables, functions: camelCase
    • file names: kebab-case
    • table and column names: snake_case
    • Use meaningful names, so whoever is reading the code understands what it means
    • Don’t use negative names, like notEnabled, prefer isDisabled
    • For numeric values, if the type doesn’t convey the unit, add the unit to the name
  • Typescript
    • Use types
    • Prefer const instead of let
    • Avoid any and casting from any to other types
    • Type predicates: only applicable to narrow down the type, not to force a complete type conversion
    • Prefer deconstructing parameters for functions instead of multiple parameters that might be of
      the same type
    • Don’t use null inside the app, only on code interacting with external interfaces/services,
      like DB and HTTP; convert to undefined before sending inwards into the code
    • Use async/await instead of .then()
    • Use the strict equality operator ===, don’t use abstract equality operator ==
    • When calling a Promise-returning function asynchronously (i.e., not awaiting), use .catch() to
      handle errors (see processAsyncError and emptyFunction depending on the case)
    • Date and Time
      • Always use buildDayjs() to create dayjs instances
      • Prefer dayjs.duration(...) to create duration consts and keep them as duration
  • Prefer Nullish Coalesce (??) than the OR operator (||) to provide a default value
  • Avoid creating arrow functions
  • Use truthy syntax instead of in - i.e., if (data.link) not if ('link' in data)
  • Error handling
    • Pass the original error as the new one’s cause so the stack trace is persisted
    • Error messages should have a static message - add dynamic data to MetriportError's additionalInfo prop
    • Avoid sending multiple events to Sentry for a single error
  • Global constants and variables
    • Move literals to constants declared after imports when possible (avoid magic numbers)
    • Avoid shared, global objects
  • Avoid using console.log and console.error in packages other than utils, infra and shared,
    and try to use out().log instead
  • Avoid multi-line logs
    • don't send objects as a second parameter to console.log() or out().log()
    • don't create multi-line strings when using JSON.stringify()
  • Use eslint to enforce code style
  • Use prettier to format code
  • max column length is 100 chars
  • multi-line comments use /** */
  • scripts: top-level comments go after the import
  • packages/infra/lib/lambdas-nested-stack-settings.ts
🔇 Additional comments (1)
packages/infra/lib/lambdas-nested-stack-settings.ts (1)

5-5:

❓ Verification inconclusive

Verify the timeout increase is backed by performance data.

The Lambda timeout has been increased from 3 to 5 minutes, which will proportionally increase AWS costs. This change also affects related queue settings (alarm threshold now 15 minutes, visibility timeout now 11 seconds).

Please ensure this increase is justified by actual performance metrics showing that the previous 3-minute timeout was insufficient for the ingestion operations.

Consider documenting the rationale for this timeout increase in a comment or commit message for future reference.


🏁 Script executed:

#!/bin/bash
# Description: Check if there are performance metrics or monitoring data that justify the timeout increase

# Search for any performance-related comments, monitoring, or metrics in the codebase
rg -i "timeout|performance|duration|slow" --type ts -A 3 -B 3 | grep -i "consolidat\|ingest"

# Look for any CloudWatch alarms or monitoring related to consolidated ingestion
rg -i "cloudwatch|alarm|metric" --type ts -A 2 -B 2 | grep -i "consolidat\|ingest"

# Check for any related documentation or comments about ingestion performance
fd README.md --exec grep -l "ingest\|consolidat" {} \;

Length of output: 61144


Verify Lambda timeout increase rationale

I didn’t find any existing performance metrics, CloudWatch alarms or documentation in the codebase to justify raising the timeout from 3 → 5 minutes (and the derived 15 min alarm / 11 s visibility settings).

• Confirm this change is backed by real ingest performance data showing the 3 min limit was insufficient.
• Add a comment or update documentation/commit message with the findings (e.g. average execution times, timeout errors observed).

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@leite08 leite08 marked this pull request as ready for review May 30, 2025 14:26
Copy link
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/utils/src/open-search/ingest-patients.ts (2)

56-70: Consider improving type safety for CSV data processing.

The use of any type is documented with eslint-disable, but consider creating a more specific interface for the CSV data structure to improve type safety.

Define a more specific interface:

+interface CsvRow {
+  [key: string]: string | undefined;
+}

-      // eslint-disable-next-line @typescript-eslint/no-explicit-any
-      .on("data", (data: any) => {
+      .on("data", (data: CsvRow) => {

127-145: Consider improving function return type and parameter structure.

While the function works correctly, consider improving the design to better follow functional programming principles and error handling guidelines.

Consider using a Result-like pattern for better error handling:

+interface MappingResult {
+  success: boolean;
+  data?: PatientRecord;
+  errors?: Array<{ field: string; error: string }>;
+}

-export function mapCsvToIds(csvPatient: {
-  cxId: string | undefined;
-  cx_id: string | undefined;
-  cxid: string | undefined;
-  id: string | undefined;
-  patientId: string | undefined;
-  patientid: string | undefined;
-}): PatientRecord | Array<{ field: string; error: string }> {
+export function mapCsvToIds(csvPatient: Record<string, string | undefined>): MappingResult {
   const cxIdRaw = csvPatient.cxId ?? csvPatient.cx_id ?? csvPatient.cxid ?? csvPatient.id;
   const cxId = cxIdRaw ? normalizeExternalIdUtils(cxIdRaw) : undefined;

   const patientIdRaw = csvPatient.patientId ?? csvPatient.patientid ?? csvPatient.id;
   const patientId = patientIdRaw ? normalizeExternalIdUtils(patientIdRaw) : undefined;

   if (!cxId || !patientId) {
-    return [{ field: "general", error: "Missing required fields" }];
+    return { 
+      success: false, 
+      errors: [{ field: "general", error: "Missing required fields" }] 
+    };
   }
-  return { cxId, patientId };
+  return { success: true, data: { cxId, patientId } };
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8dff995 and 08c4cae.

📒 Files selected for processing (2)
  • packages/api/src/routes/internal/medical/patient-consolidated.ts (0 hunks)
  • packages/utils/src/open-search/ingest-patients.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/api/src/routes/internal/medical/patient-consolidated.ts
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.ts`: - Use the Onion Pattern to organize a package's code in layers - Try to use immutable code and avoid sharing state across different functions, objects, and systems - Try...

**/*.ts: - Use the Onion Pattern to organize a package's code in layers

  • Try to use immutable code and avoid sharing state across different functions, objects, and systems
  • Try to build code that's idempotent whenever possible
  • Prefer functional programming style functions: small, deterministic, 1 input, 1 output
  • Minimize coupling / dependencies
  • Avoid modifying objects received as parameter
  • Only add comments to code to explain why something was done, not how it works
  • Naming
    • classes, enums: PascalCase
    • constants, variables, functions: camelCase
    • file names: kebab-case
    • table and column names: snake_case
    • Use meaningful names, so whoever is reading the code understands what it means
    • Don’t use negative names, like notEnabled, prefer isDisabled
    • For numeric values, if the type doesn’t convey the unit, add the unit to the name
  • Typescript
    • Use types
    • Prefer const instead of let
    • Avoid any and casting from any to other types
    • Type predicates: only applicable to narrow down the type, not to force a complete type conversion
    • Prefer deconstructing parameters for functions instead of multiple parameters that might be of
      the same type
    • Don’t use null inside the app, only on code interacting with external interfaces/services,
      like DB and HTTP; convert to undefined before sending inwards into the code
    • Use async/await instead of .then()
    • Use the strict equality operator ===, don’t use abstract equality operator ==
    • When calling a Promise-returning function asynchronously (i.e., not awaiting), use .catch() to
      handle errors (see processAsyncError and emptyFunction depending on the case)
    • Date and Time
      • Always use buildDayjs() to create dayjs instances
      • Prefer dayjs.duration(...) to create duration consts and keep them as duration
  • Prefer Nullish Coalesce (??) than the OR operator (||) to provide a default value
  • Avoid creating arrow functions
  • Use truthy syntax instead of in - i.e., if (data.link) not if ('link' in data)
  • Error handling
    • Pass the original error as the new one’s cause so the stack trace is persisted
    • Error messages should have a static message - add dynamic data to MetriportError's additionalInfo prop
    • Avoid sending multiple events to Sentry for a single error
  • Global constants and variables
    • Move literals to constants declared after imports when possible (avoid magic numbers)
    • Avoid shared, global objects
  • Avoid using console.log and console.error in packages other than utils, infra and shared,
    and try to use out().log instead
  • Avoid multi-line logs
    • don't send objects as a second parameter to console.log() or out().log()
    • don't create multi-line strings when using JSON.stringify()
  • Use eslint to enforce code style
  • Use prettier to format code
  • max column length is 100 chars
  • multi-line comments use /** */
  • scripts: top-level comments go after the import
  • packages/utils/src/open-search/ingest-patients.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: Analyze (javascript)
  • GitHub Check: api / deploy
🔇 Additional comments (5)
packages/utils/src/open-search/ingest-patients.ts (5)

1-12: LGTM: Proper import organization and configuration.

The imports are well-organized with dotenv configuration correctly placed at the top, and all necessary dependencies are imported following the established patterns.


23-25: Good constant declarations following guidelines.

Constants are properly declared after imports using meaningful names and camelCase convention as specified in the coding guidelines.


89-113: LGTM: Excellent implementation of concurrent processing with proper error handling.

The implementation correctly uses executeAsynchronously for controlled concurrency, implements network retries, and properly captures failed ingestions for later analysis. The error handling preserves error details while continuing processing.


147-149: LGTM: Proper module execution pattern.

The script correctly uses the standard Node.js pattern to execute the main function only when the file is run directly.


36-37: 🛠️ Refactor suggestion

Replace console.log with out().log for consistency.

The coding guidelines specify to avoid console.log in packages and use out().log instead. Since this is a script in the utils package, consider using the standard logging utility.

Import the logging utility at the top:

+import { out } from "@metriport/core/util/log";

Then replace console.log statements throughout the file:

-  console.log(`############ Starting... ############`);
+  out().log(`############ Starting... ############`);

Apply this pattern to all other console.log statements in the file.

Also applies to: 73-74, 76-76, 79-79, 87-87, 93-93, 109-109, 116-118, 122-124

⛔ Skipped due to learnings
Learnt from: thomasyopes
PR: metriport/metriport#3466
File: packages/api/src/routes/ehr/shared.ts:122-147
Timestamp: 2025-03-17T17:01:17.227Z
Learning: Avoid using console.log and console.error in packages other than utils, infra and shared, and try to use out().log instead according to Metriport's coding guidelines.
Learnt from: leite08
PR: metriport/metriport#3489
File: packages/api/src/routes/ehr/elation/appointment-webhook.ts:32-36
Timestamp: 2025-03-21T00:21:26.928Z
Learning: Use `out().log` instead of `console.log` for logging in packages other than utils, infra and shared.
Learnt from: leite08
PR: metriport/metriport#3857
File: packages/utils/src/consolidated/filter-consolidated.ts:39-68
Timestamp: 2025-05-27T23:51:45.100Z
Learning: Utility scripts in the packages/utils directory don't require comprehensive error handling or logging changes (like switching from console.log to out().log), as they are meant for local/developer environments, not production code.

@leite08 leite08 marked this pull request as draft May 30, 2025 15:18
leite08 added 3 commits May 30, 2025 12:33
Ref eng-268

Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
Ref eng-268

Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
@leite08 leite08 added this pull request to the merge queue May 30, 2025
Merged via the queue into master with commit 8677b7a May 30, 2025
69 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants
0