-
Notifications
You must be signed in to change notification settings - Fork 68
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
feat(api): adding internal route to recreate consolidated bundle #3841
Conversation
Part of ENG-303 Signed-off-by: Ramil Garipov <ramil@metriport.com>
""" WalkthroughA new internal POST API endpoint was added to forcefully recreate a patient's consolidated data bundle. The function Changes
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
Possibly related PRs
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 practicesThe endpoint correctly:
- Validates required parameters
- Fetches the patient record
- Creates a tracking request with proper status
- Implements error handling with try/catch
- Updates consolidated query progress for both success and failure cases
- 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
📒 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
, preferisDisabled
- For numeric values, if the type doesn’t convey the unit, add the unit to the name
- Typescript
- Use types
- Prefer
const
instead oflet
- Avoid
any
and casting fromany
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 toundefined
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 (seeprocessAsyncError
andemptyFunction
depending on the case)- Date and Time
- Always use
buildDayjs()
to createdayjs
instances- Prefer
dayjs.duration(...)
to create duration consts and keep them asduration
- 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)
notif ('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
andconsole.error
in packages other than utils, infra and shared,
and try to useout().log
instead- Avoid multi-line logs
- don't send objects as a second parameter to
console.log()
orout().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 reusabilityThe 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 endpointThe new imports properly include all the necessary dependencies for the consolidated bundle recreation functionality:
uuidv7
,updateConsolidatedQueryProgress
,appendProgressToProcessingQueries
,recreateConsolidated
, andstoreQueryInit
.Also applies to: 27-27, 38-47, 61-61
/** | ||
* 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", |
There was a problem hiding this comment.
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>
There was a problem hiding this 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 argumentsThe 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 purposeThe 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 timeWhen making multiple parallel requests, adding a small random jitter can help prevent request bursts. The
executeAsynchronously
function supports this via theminJitterMillis
andmaxJitterMillis
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 readabilityConverting 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 errorInstead 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 validationThe script could benefit from validating the patientIds array before processing and better error reporting.
8000async 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 organizationAccording 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
📒 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
, preferisDisabled
- For numeric values, if the type doesn’t convey the unit, add the unit to the name
- Typescript
- Use types
- Prefer
const
instead oflet
- Avoid
any
and casting fromany
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 toundefined
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 (seeprocessAsyncError
andemptyFunction
depending on the case)- Date and Time
- Always use
buildDayjs()
to createdayjs
instances- Prefer
dayjs.duration(...)
to create duration consts and keep them asduration
- 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)
notif ('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
andconsole.error
in packages other than utils, infra and shared,
and try to useout().log
instead- Avoid multi-line logs
- don't send objects as a second parameter to
console.log()
orout().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 runningThis 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 instructionsThe 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>
There was a problem hiding this 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 handlingThe 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 callsFor 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 timeConvert 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 callsAdd 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 fileAdd 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
📒 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
, preferisDisabled
- For numeric values, if the type doesn’t convey the unit, add the unit to the name
- Typescript
- Use types
- Prefer
const
instead oflet
- Avoid
any
and casting fromany
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 toundefined
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 (seeprocessAsyncError
andemptyFunction
depending on the case)- Date and Time
- Always use
buildDayjs()
to createdayjs
instances- Prefer
dayjs.duration(...)
to create duration consts and keep them asduration
- 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)
notif ('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
andconsole.error
in packages other than utils, infra and shared,
and try to useout().log
instead- Avoid multi-line logs
- don't send objects as a second parameter to
console.log()
orout().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 updatedThe warning message now accurately reflects the script's purpose of recreating consolidated data.
122-122
: LGTM: Multi-line log issue is fixedThe 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>
There was a problem hiding this 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 nameThere'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 requestsWhile 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
📒 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
, preferisDisabled
- For numeric values, if the type doesn’t convey the unit, add the unit to the name
- Typescript
- Use types
- Prefer
const
instead oflet
- Avoid
any
and casting fromany
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 toundefined
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 (seeprocessAsyncError
andemptyFunction
depending on the case)- Date and Time
- Always use
buildDayjs()
to createdayjs
instances- Prefer
dayjs.duration(...)
to create duration consts and keep them asduration
- 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)
notif ('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
andconsole.error
in packages other than utils, infra and shared,
and try to useout().log
instead- Avoid multi-line logs
- don't send objects as a second parameter to
console.log()
orout().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 configurationThe 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 documentationThe 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 constantsThe 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 parametersGood implementation of validation for empty patientIds array with a clear error message and early exit.
81-91
: Well-implemented concurrency with progress trackingThe 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 mechanismThe 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 loggingThe 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>
Part of ENG-303
Issues:
Description
Testing
Release Plan
Summary by CodeRabbit