8000 feat(api): adding internal route to recreate consolidated bundle by RamilGaripov · Pull Request #3841 · metriport/metriport · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat(api): adding internal route to recreate consolidated bundle #3841

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

Conversation

RamilGaripov
Copy link
Contributor
@RamilGaripov RamilGaripov commented May 15, 2025

Part of ENG-303

Issues:

Description

  • adding internal route to recreate consolidated bundle

Testing

  • Local
    • Recreate consolidated on a local patient and confirm on S3
  • Staging
    • Recreate consolidated and confirm on s3
  • Production
    • Recreate consolidated and confirm on s3

Release Plan

  • Merge this

Summary by CodeRabbit

  • New Features
    • Introduced a new POST endpoint to forcefully recreate a patient's consolidated data bundle, providing immediate feedback on the operation's status.
    • Added a bulk processing script to trigger consolidated data recreation for multiple patients with progress tracking and error logging.
  • Chores
    • Improved internal modularity to support new endpoint functionality.

Part of ENG-303

Signed-off-by: Ramil Garipov <ramil@metriport.com>
Copy link
linear bot commented May 15, 2025

Copy link
coderabbitai bot commented May 15, 2025

"""

Walkthrough

A new internal POST API endpoint was added to forcefully recreate a patient's consolidated data bundle. The function appendProgressToProcessingQueries was made exportable for external use. A new CLI utility script was introduced to bulk recreate consolidated data for multiple patients with concurrency control, logging, and error handling.

Changes

File(s) Change Summary
packages/api/src/command/medical/patient/consolidated-get.ts Changed appendProgressToProcessingQueries from a local to an exported function.
packages/api/src/routes/internal/medical/patient.ts Added POST /internal/patient/:id/consolidated/refresh endpoint to force recreate a patient's consolidated bundle.
packages/utils/src/consolidated/bulk-recreate-consolidated.ts Added CLI script to bulk recreate consolidated data for multiple patients with concurrency, logging, and error handling.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API_Router
    participant PatientDB
    participant ConsolidatedLogic

    Client->>API_Router: POST /internal/patient/:id/consolidated/refresh?cxId=...
    API_Router->>PatientDB: Retrieve patient by id and cxId
    API_Router->>API_Router: Generate requestId (UUIDv7)
    API_Router->>ConsolidatedLogic: recreateConsolidated(patient, "internal", requestId)
    alt Success
        API_Router-->>Client: 200 OK with { requestId }
    else Failure
        API_Router-->>Client: Error response with MetriportError including patientId and cxId
    end
Loading

Possibly related PRs


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2ab2066 and a01f806.

📒 Files selected for processing (2)
  • packages/api/src/routes/internal/medical/patient.ts (4 hunks)
  • packages/utils/src/consolidated/bulk-recreate-consolidated.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/utils/src/consolidated/bulk-recreate-consolidated.ts
  • packages/api/src/routes/internal/medical/patient.ts

🪧 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 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.

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: 0

🧹 Nitpick comments (1)
packages/api/src/routes/internal/medical/patient.ts (1)

1164-1219: New endpoint implementation follows good practices

The endpoint correctly:

  1. Validates required parameters
  2. Fetches the patient record
  3. Creates a tracking request with proper status
  4. Implements error handling with try/catch
  5. Updates consolidated query progress for both success and failure cases
  6. Returns a meaningful response

This implementation ensures the consolidated bundle recreation process is properly tracked and errors are handled gracefully.

One suggestion: Consider adding logging statements at key points in this process (especially start, success, and failure) to aid in debugging and observability.

  try {
+    const { log } = out(`Recreating consolidated bundle - patient ${patient.id}, requestId ${requestId}`);
+    log('Starting consolidated bundle recreation');
    await recreateConsolidated({ patient, context: "internal", requestId });
    await updateConsolidatedQueryProgress({
      patient,
      requestId,
      progress: { status: "completed" },
    });
+    log('Consolidated bundle recreation completed successfully');
  } catch (err) {
+    const { log } = out(`Error recreating consolidated bundle - patient ${patient.id}, requestId ${requestId}`);
+    log(`Failed to recreate consolidated bundle: ${errorToString(err)}`);
    await updateConsolidatedQueryProgress({
      patient,
      requestId,
      progress: { status: "failed" },
    });
  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 40cb00e and 3a74217.

📒 Files selected for processing (2)
  • packages/api/src/command/medical/patient/consolidated-get.ts (1 hunks)
  • packages/api/src/routes/internal/medical/patient.ts (5 hunks)
🧰 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/api/src/command/medical/patient/consolidated-get.ts
  • packages/api/src/routes/internal/medical/patient.ts
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
packages/api/src/command/medical/patient/consolidated-get.ts (1)

154-167: Good refactoring: Making this utility function exportable improves code reusability

The change to export this function allows it to be used by the new consolidated bundle recreation endpoint. This follows good software design principles by enabling reuse of existing code rather than duplicating functionality.

packages/api/src/routes/internal/medical/patient.ts (1)

1-1: Appropriate imports added to support the new endpoint

The new imports properly include all the necessary dependencies for the consolidated bundle recreation functionality: uuidv7, updateConsolidatedQueryProgress, appendProgressToProcessingQueries, recreateConsolidated, and storeQueryInit.

Also applies to: 27-27, 38-47, 61-61

Comment on lines 1164 to 1173
/**
* POST /internal/patient/:id/recreate-consolidated
*
* Forcefully recreates the consolidated bundle for a patient.
*
* @param req.query.cxId The customer ID.
* @param req.params.id The patient ID.
*/
router.post(
"/:id/recreate-consolidated",
Copy link
Contributor

Choose a reason for hiding this comment

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

possibly should be /:id/consolidated/refresh

Part of ENG-303

Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-303

Signed-off-by: Ramil Garipov <ramil@metriport.com>
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: 2

🧹 Nitpick comments (7)
packages/utils/src/consolidated/bulk-recreate-consolidated.ts (7)

42-46: Consider making delay times configurable via command line arguments

The delay times are hardcoded and the comment on line 43 mentions infrastructure scaling without clear guidance. For better flexibility, consider making these parameters configurable via command line arguments using Commander.

- const minimumDelayTime = dayjs.duration(1, "seconds"); // to get to 1s need to be ABSOLUTELY sure the infra will take it (scale it out if needed)
- const defaultDelayTime = dayjs.duration(10, "seconds");
- const confirmationTime = dayjs.duration(10, "seconds");
- const numberOfParallelExecutions = 5;

+ const minimumDelayTime = dayjs.duration(
+   Number(process.env.MIN_DELAY_SECONDS) || 1, 
+   "seconds"
+ );
+ const defaultDelayTime = dayjs.duration(
+   Number(process.env.DEFAULT_DELAY_SECONDS) || 10, 
+   "seconds"
+ );
+ const confirmationTime = dayjs.duration(
+   Number(process.env.CONFIRMATION_SECONDS) || 10, 
+   "seconds"
+ );
+ const numberOfParallelExecutions = Number(process.env.PARALLEL_EXECUTIONS) || 5;

+ program
+   .option('-m, --min-delay <seconds>', 'minimum delay between requests in seconds', String(minimumDelayTime.asSeconds()))
+   .option('-d, --default-delay <seconds>', 'default delay between requests in seconds', String(defaultDelayTime.asSeconds()))
+   .option('-c, --confirmation-time <seconds>', 'confirmation wait time in seconds', String(confirmationTime.asSeconds()))
+   .option('-p, --parallel <number>', 'number of parallel executions', String(numberOfParallelExecutions));

55-56: Update CLI description to match script's purpose

The current description mentions "coverage/density data" but this script is about recreating consolidated data.

- .description("CLI to get coverage/density data multiple patients.")
+ .description("CLI to recreate consolidated data for multiple patients.")

81-82: Consider adding jitter to the delay time

When making multiple parallel requests, adding a small random jitter can help prevent request bursts. The executeAsynchronously function supports this via the minJitterMillis and maxJitterMillis options.

- await sleep(delayTime);
+ const jitter = Math.floor(Math.random() * 1000); // Add up to 1 second of jitter
+ await sleep(delayTime + jitter);
+ log(`...sleeping for ${delayTime + jitter} ms (including ${jitter}ms jitter)`);

Alternatively, use the jitter options in executeAsynchronously:

  {
-   numberOfParallelExecutions 
+   numberOfParallelExecutions,
+   minJitterMillis: 0,
+   maxJitterMillis: 1000
  }

94-95: Format elapsed time for better readability

Converting milliseconds to a more human-readable format would make the output more user-friendly.

- const ellapsed = Date.now() - startedAt;
- log(`>>> Done recreating consolidated for all ${patientIds.length} patients in ${ellapsed} ms`);
+ const ellapsedMs = Date.now() - startedAt;
+ const ellapsedFormatted = dayjs.duration(ellapsedMs).format("HH:mm:ss.SSS");
+ log(`>>> Done recreating consolidated for all ${patientIds.length} patients in ${ellapsedFormatted} (${ellapsedMs} ms)`);

119-120: Remove ESLint disable comment by properly typing the error

Instead of disabling the ESLint rule, consider properly typing the error.

-  //eslint-disable-next-line @typescript-eslint/no-explicit-any
-  } catch (error) {
+  } catch (error: unknown) {

58-97: Incorporate additional error handling and validation

The script could benefit from validating the patientIds array before processing and better error reporting.

8000
async function main() {
  initRunsFolder();
  program.parse();
  const { log } = out("");

+  // Validate patientIds
+  if (patientIds.length === 0) {
+    log(">>> No patient IDs provided. Please add patient IDs to the patientIds array.");
+    process.exit(1);
+  }
+
+  // Validate invalid IDs (e.g., empty strings, non-string values)
+  const invalidIds = patientIds.filter(id => typeof id !== "string" || id.trim() === "");
+  if (invalidIds.length > 0) {
+    log(`>>> Found ${invalidIds.length} invalid patient IDs. Please check your patientIds array.`);
+    process.exit(1);
+  }

  const startedAt = Date.now();
  log(`>>> Starting with ${patientIds.length} patient IDs...`);

  const { orgName } = await getCxData(cxId, undefined, false);
  await displayWarningAndConfirmation(patientIds.length, orgName, log);

  const errorFileName = getOutputFileName(orgName) + ".error";
  initFile(errorFileName);

+  // Create a progress file to track completion
+  const progressFileName = getOutputFileName(orgName) + ".progress";
+  initFile(progressFileName);
+  const appendProgress = (message: string) => {
+    fs.appendFileSync(progressFileName, `${message}\n`);
+  };
+  appendProgress(`Started processing ${patientIds.length} patients at ${new Date().toISOString()}`);

  log(`>>> Running it...`);

  let ptIndex = 0;
  await executeAsynchronously(
    patientIds,
    async patientId => {
      await recreateConsolidatedForPatient(patientId, cxId, errorFileName, log);
      log(`>>> Progress: ${++ptIndex}/${patientIds.length} patients complete`);
+      appendProgress(`Completed patient ${patientId} (${ptIndex}/${patientIds.length}) at ${new Date().toISOString()}`);
      const delayTime = getDelayTime({ log, minimumDelayTime, defaultDelayTime });
      log(`...sleeping for ${delayTime} ms`);
      await sleep(delayTime);
    },
    { numberOfParallelExecutions }
  );
  if (patientsWithErrors.length > 0) {
    log(
      `>>> Patients with errors (${patientsWithErrors.length}): ${patientsWithErrors.join(", ")}`
    );
    log(`>>> See file ${errorFileName} for more details.`);
+    appendProgress(`Completed with ${patientsWithErrors.length} errors at ${new Date().toISOString()}`);
  } else {
    log(`>>> No patient with errors!`);
+    appendProgress(`Completed successfully at ${new Date().toISOString()}`);
  }
  const ellapsed = Date.now() - startedAt;
  log(`>>> Done recreating consolidated for all ${patientIds.length} patients in ${ellapsed} ms`);
+  appendProgress(`Total execution time: ${ellapsed} ms`);
  process.exit(0);
}

1-16: Follow onion pattern and improve imports organization

According to your coding guidelines, you should use the Onion Pattern for organizing code. Consider reorganizing imports into groups: external packages first, then internal packages organized from outer to inner layers.

import * as dotenv from "dotenv";
dotenv.config();
// keep that ^ on top

+ // External packages
import axios from "axios";
import { Command } from "commander";
import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";

+ // Core utilities
import { executeAsynchronously } from "@metriport/core/util/concurrency";
import { out } from "@metriport/core/util/log";
import { errorToString, getEnvVarOrFail, sleep } from "@metriport/shared";

+ // Local utilities
import { getDelayTime } from "../shared/duration";
import { initFile } from "../shared/file";
import { buildGetDirPathInside, initRunsFolder } from "../shared/folder";
import { getCxData } from "../shared/get-cx-data";
import { logErrorToFile } from "../shared/log";
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5d030e5 and 81c7d11.

📒 Files selected for processing (1)
  • packages/utils/src/consolidated/bulk-recreate-consolidated.ts (1 hunks)
🧰 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/consolidated/bulk-recreate-consolidated.ts
🧬 Code Graph Analysis (1)
packages/utils/src/consolidated/bulk-recreate-consolidated.ts (3)
packages/core/src/util/concurrency.ts (1)
  • executeAsynchronously (83-130)
packages/utils/src/shared/duration.ts (1)
  • getDelayTime (20-49)
packages/shared/src/index.ts (2)
  • sleep (13-13)
  • errorToString (42-42)
🔇 Additional comments (2)
packages/utils/src/consolidated/bulk-recreate-consolidated.ts (2)

35-37: Initialize patientIds array with your target patient IDs before running

This array needs to be manually populated with the list of patient IDs for which you want to recreate consolidated data, as mentioned in the script's documentation.


17-33: Well-documented script with clear usage instructions

The code includes comprehensive documentation explaining the purpose, usage, and behavior of the script. This is excellent for maintainability and onboarding new developers.

Part of ENG-303

Signed-off-by: Ramil Garipov <ramil@metriport.com>
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: 3

🧹 Nitpick comments (5)
packages/utils/src/consolidated/bulk-recreate-consolidated.ts (5)

116-125: Consider adding more specific error handling

The current error handling catches all errors without specific handling for different error types. Consider adding more detailed error handling for specific scenarios like network errors, authentication issues, etc.

  try {
    await api.post(`/internal/patient/${patientId}/recreate-consolidated?cxId=${cxId}`);
    log(`>>> Done recreate consolidated for patient ${patientId}...`);
    //eslint-disable-next-line @typescript-eslint/no-explicit-any
  } catch (error) {
+    // Specific handling for axios errors
+    if (axios.isAxiosError(error)) {
+      const statusCode = error.response?.status;
+      const errorDetails = error.response?.data;
+      const msg = `ERROR processing patient ${patientId} (Status: ${statusCode}): `;
+      log(`${msg}${errorToString(error)}`);
+      patientsWithErrors.push(patientId);
+      logErrorToFile(errorFileName, msg, error as Error, { statusCode, errorDetails });
+    } else {
      const msg = `ERROR processing patient ${patientId}: `;
      log(`${msg}${errorToString(error)}`);
      patientsWithErrors.push(patientId);
      logErrorToFile(errorFileName, msg, error as Error);
+    }
  }

74-85: Consider adding retry logic for failed API calls

For robustness, consider implementing retry logic for failed API calls, especially for transient issues like network problems.

  let ptIndex = 0;
  await executeAsynchronously(
    patientIds,
    async patientId => {
-      await recreateConsolidatedForPatient(patientId, cxId, errorFileName, log);
+      // Implement retry logic
+      const maxRetries = 3;
+      let retries = 0;
+      let success = false;
+      
+      while (!success && retries < maxRetries) {
+        try {
+          await recreateConsolidatedForPatient(patientId, cxId, errorFileName, log);
+          success = true;
+        } catch (error) {
+          retries++;
+          if (retries < maxRetries) {
+            log(`Retry ${retries}/${maxRetries} for patient ${patientId}`);
+            await sleep(2000 * retries); // Exponential backoff
+          } else {
+            throw error;
+          }
+        }
+      }
      log(`>>> Progress: ${++ptIndex}/${patientIds.length} patients complete`);
      const delayTime = getDelayTime({ log, minimumDelayTime, defaultDelayTime });
      log(`...sleeping for ${delayTime} ms`);
      await sleep(delayTime);
    },
    { numberOfParallelExecutions }
  );

94-95: Add human-readable time format for elapsed time

Convert the elapsed time from milliseconds to a more human-readable format.

-  const ellapsed = Date.now() - startedAt;
-  log(`>>> Done recreating consolidated for all ${patientIds.length} patients in ${ellapsed} ms`);
+  const elapsed = Date.now() - startedAt;
+  const elapsedSeconds = (elapsed / 1000).toFixed(2);
+  log(`>>> Done recreating consolidated for all ${patientIds.length} patients in ${elapsedSeconds} seconds`);

116-117: Add more detailed logging for API calls

Add more detailed logging about the API call being made including the URL for better debugging.

  try {
-    await api.post(`/internal/patient/${patientId}/recreate-consolidated?cxId=${cxId}`);
+    const url = `/internal/patient/${patientId}/recreate-consolidated?cxId=${cxId}`;
+    log(`>>> Making API call to recreate consolidated for patient ${patientId}`);
+    await api.post(url);
    log(`>>> Done recreate consolidated for patient ${patientId}...`);

128-129: Add newline at end of file

Add a newline at the end of the file to comply with standard formatting practices.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 81c7d11 and 0753476.

📒 Files selected for processing (1)
  • packages/utils/src/consolidated/bulk-recreate-consolidated.ts (1 hunks)
🧰 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/consolidated/bulk-recreate-consolidated.ts
🧬 Code Graph Analysis (1)
packages/utils/src/consolidated/bulk-recreate-consolidated.ts (3)
packages/core/src/util/concurrency.ts (1)
  • executeAsynchronously (83-130)
packages/utils/src/shared/duration.ts (1)
  • getDelayTime (20-49)
packages/shared/src/index.ts (2)
  • sleep (13-13)
  • errorToString (42-42)
🔇 Additional comments (2)
packages/utils/src/consolidated/bulk-recreate-consolidated.ts (2)

104-107: LGTM: Warning message is correctly updated

The warning message now accurately reflects the script's purpose of recreating consolidated data.


122-122: LGTM: Multi-line log issue is fixed

The log statement now correctly concatenates the error message to avoid multi-line logs, as per coding guidelines.

Part of ENG-303

Signed-off-by: Ramil Garipov <ramil@metriport.com>
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: 0

🧹 Nitpick comments (2)
packages/utils/src/consolidated/bulk-recreate-consolidated.ts (2)

101-101: Fix typo in variable name

There's a spelling error in the variable name.

- const ellapsed = Date.now() - startedAt;
+ const elapsed = Date.now() - startedAt;

81-91: Consider adding a retry mechanism for failed requests

While the current implementation handles errors appropriately, for production reliability, consider implementing a retry mechanism with exponential backoff for transient failures.

You could enhance the recreateConsolidatedForPatient function to include retry logic:

async function recreateConsolidatedForPatient(
  patientId: string,
  cxId: string,
  errorFileName: string,
  log: typeof console.log,
  maxRetries = 3
) {
  let retries = 0;
  while (retries <= maxRetries) {
    try {
      await api.post(`/internal/patient/${patientId}/recreate-consolidated?cxId=${cxId}`);
      log(`>>> Done recreate consolidated for patient ${patientId}...`);
      return; // Success, exit the function
    } catch (error) {
      retries++;
      if (retries <= maxRetries) {
        const backoffTime = Math.min(1000 * 2 ** retries, 30000); // Exponential backoff with 30s max
        log(`Retry ${retries}/${maxRetries} for patient ${patientId} after ${backoffTime}ms`);
        await sleep(backoffTime);
      } else {
        // All retries failed
        const msg = `ERROR processing patient ${patientId} after ${maxRetries} retries: `;
        log(`${msg}${errorToString(error)}`);
        patientsWithErrors.push(patientId);
        logErrorToFile(errorFileName, msg, error as Error);
      }
    }
  }
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0753476 and 33eeca2.

📒 Files selected for processing (2)
  • packages/api/src/routes/internal/medical/patient.ts (4 hunks)
  • packages/utils/src/consolidated/bulk-recreate-consolidated.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/api/src/routes/internal/medical/patient.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/consolidated/bulk-recreate-consolidated.ts
🧬 Code Graph Analysis (1)
packages/utils/src/consolidated/bulk-recreate-consolidated.ts (3)
packages/core/src/util/concurrency.ts (1)
  • executeAsynchronously (83-130)
packages/utils/src/shared/duration.ts (1)
  • getDelayTime (20-49)
packages/shared/src/index.ts (2)
  • sleep (13-13)
  • errorToString (42-42)
🔇 Additional comments (7)
packages/utils/src/consolidated/bulk-recreate-consolidated.ts (7)

1-18: Well-structured imports and configuration

The imports and initial setup follow best practices with dotenv configuration at the top, followed by logical grouping of imports. The dayjs extension setup is also correctly placed.


19-33: Clear and comprehensive documentation

The documentation clearly explains the script's purpose, usage instructions, and behavior. This makes the code maintainable and easy for other developers to understand.


35-51: Good configuration setup with appropriate constants

The configuration is well-structured with clear naming conventions. Constants are used for delay times and concurrency settings, making the code more maintainable.


64-67: Effective validation of input parameters

Good implementation of validation for empty patientIds array with a clear error message and early exit.


81-91: Well-implemented concurrency with progress tracking

The use of executeAsynchronously with a reasonable number of parallel executions (5) is a good approach to balance performance and system load. Progress tracking provides valuable feedback during execution.


105-114: Clear warning and confirmation mechanism

The implementation provides users with clear information about what action is about to be performed and gives them time to cancel if needed.


116-132: Good error handling with appropriate logging

The function properly handles errors, logs them to both console and file, and tracks affected patient IDs for summary reporting. The log format follows the coding guidelines by avoiding multi-line logs.

Part of ENG-303

Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-303

Signed-off-by: Ramil Garipov <ramil@metriport.com>
@RamilGaripov RamilGaripov enabled auto-merge May 15, 2025 18:25
@RamilGaripov RamilGaripov added this pull request to the merge queue May 15, 2025
Merged via the queue into develop with commit cf9d709 May 15, 2025
15 checks passed
@RamilGaripov RamilGaripov deleted the eng-303-add-internal-route-to-recreate-consolidated branch May 15, 2025 18:28
@RamilGaripov RamilGaripov mentioned this pull request May 15, 2025
1 task
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