-
Notifications
You must be signed in to change notification settings - Fork 72
Eng 432 implement post discharge requery #4021
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
Eng 432 implement post discharge requery #4021
Conversation
Part of ENG-432 Signed-off-by: Ramil Garipov <ramil@metriport.com>
WalkthroughThis update introduces a comprehensive "discharge requery" feature for patient monitoring. It adds new backend APIs, job scheduling logic, job processing handlers (both direct and cloud/SQS-based), utility functions, infrastructure provisioning (Lambda and SQS), and analytics integration. The changes include new TypeScript modules, Express routes, Lambda handlers, infrastructure code, and supporting utilities, along with corresponding tests. Changes
Sequence Diagram(s)Discharge Requery Job Creation and ExecutionsequenceDiagram
participant HL7Source as HL7 Source
participant CoreAPI as Core API (HL7 Notification Handler)
participant API as API Service
participant SQS as Discharge Requery SQS
participant Lambda as Discharge Requery Lambda
participant Patient as Patient Data Services
HL7Source->>CoreAPI: HL7 "A03" (Discharge) Event
CoreAPI->>API: POST /internal/patient/monitoring/discharge-requery?cxId&patientId
API->>API: createDischargeRequeryJob()
API->>SQS: (Production) Send discharge requery message
SQS->>Lambda: Trigger Lambda with message
Lambda->>Patient: processDischargeRequery (direct handler)
Patient-->>Lambda: Patient query, document query, etc.
Lambda->>API: updateJobRuntimeData, failJob (as needed)
Discharge Requery Job Completion FlowsequenceDiagram
participant DocumentWebhook as Document Conversion Webhook
participant API as API Service
participant finishDischarge as finishDischargeRequery
DocumentWebhook->>API: Document conversion status update
API->>finishDischarge: finishDischargeRequery({cxId, patientId, requestId, status})
finishDischarge->>API: Mark job complete, update attempts, send analytics
alt More attempts remain
finishDischarge->>API: Schedule new discharge requery job
else No attempts remain
finishDischarge->>API: Log completion
end
Discharge Requery Job Deduplication LogicsequenceDiagram
participant API as API Service
participant JobStore as Patient Job Store
API->>JobStore: Query for existing discharge requery jobs
alt Existing jobs found
API->>JobStore: Cancel existing jobs (deduplication)
API->>JobStore: Create new job with earliest scheduledAt and largest attempts
else No existing jobs
API->>JobStore: Create new discharge requery job
end
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
npm error code ERR_SSL_WRONG_VERSION_NUMBER 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (3)
⏰ Context from checks skipped due to timeout of 90000ms (6)
✨ Finishing Touches
🪧 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 (
|
Part of ENG-432 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-432 Signed-off-by: Ramil Garipov <ramil@metriport.com>
packages/shared/src/domain/patient/patient-monitoring/discharge-requery.ts
Show resolved
Hide resolved
packages/shared/src/domain/patient/patient-monitoring/discharge-requery.ts
Outdated
Show resolved
Hide resolved
packages/api/src/command/medical/patient/patient-monitoring/discharge-requery/finish.ts
Show resolved
Hide resolved
packages/api/src/routes/internal/medical/patient-monitoring/discharge-requery.ts
Outdated
Show resolved
Hide resolved
packages/core/src/command/patient-monitoring/discharge-requery/discharge-requery-local.ts
Outdated
Show resolved
Hide resolved
packages/core/src/command/patient-monitoring/discharge-requery/discharge-requery-local.ts
Outdated
Show resolved
Hide resolved
Part of ENG-432 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-432 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-432 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-432 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-432 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-432 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-432 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: 1
♻️ Duplicate comments (2)
packages/lambdas/src/patient-monitoring/discharge-requery.ts (2)
26-26
: Address the console.log usage per coding guidelines.This console.log usage violates the coding guidelines which specify avoiding console.log in packages other than utils, infra and shared.
42-42
: Remove the timing log as suggested by human reviewer.The human reviewer (@thomasyopes) suggested removing these timing logs as "it's not like this lambda processing time is relevant". Additionally, this violates coding guidelines for console.log usage.
🧹 Nitpick comments (3)
packages/lambdas/src/patient-monitoring/discharge-requery.ts (1)
12-17
: Validate environment variable parsing.Consider adding validation for the parsed integer values to ensure they're valid numbers and within expected ranges.
const waitTimeInMillisRaw = getEnvOrFail("WAIT_TIME_IN_MILLIS"); -const waitTimeInMillis = parseInt(waitTimeInMillisRaw); +const waitTimeInMillis = parseInt(waitTimeInMillisRaw); +if (isNaN(waitTimeInMillis) || waitTimeInMillis < 0) { + throw new Error(`Invalid WAIT_TIME_IN_MILLIS: ${waitTimeInMillisRaw}`); +} const maxAttemptsRaw = getEnvOrFail("MAX_ATTEMPTS"); -const maxAttempts = parseInt(maxAttemptsRaw); +const maxAttempts = parseInt(maxAttemptsRaw); +if (isNaN(maxAttempts) || maxAttempts < 1) { + throw new Error(`Invalid MAX_ATTEMPTS: ${maxAttemptsRaw}`); +}packages/core/src/command/patient-monitoring/discharge-requery/discharge-requery-direct.ts (2)
20-24
: Move constants after imports per coding guidelines.The coding guidelines specify "Move literals to constants declared after imports when possible". Consider consolidating these constants.
+const DEFAULT_TRIGGER_CONSOLIDATED = false; +const DEFAULT_DISABLE_WEBHOOKS = true; +const DEFAULT_RERUN_PD_ON_NEW_DEMOGRAPHICS = true; +const WAIT_TIME_BETWEEN_PD_AND_DQ_MIN_MS = 80; +const WAIT_TIME_BETWEEN_PD_AND_DQ_MAX_MS = 120; -const defaultTriggerConsolidated = false; -const defaultDisableWebhooks = true; -const defaultRerunPdOnNewDemographics = true; - -const waitTimeBetweenPdAndDq = () => dayjs.duration(randomIntBetween(80, 120), "milliseconds"); +const waitTimeBetweenPdAndDq = () => + dayjs.duration(randomIntBetween(WAIT_TIME_BETWEEN_PD_AND_DQ_MIN_MS, WAIT_TIME_BETWEEN_PD_AND_DQ_MAX_MS), "milliseconds");
71-80
: Consider improving error handling for specific error types.The error handling correctly identifies
BadRequestError
andNotFoundError
but serializes the error status as JSON. Consider whether this provides sufficient context for debugging.if (error instanceof BadRequestError || error instanceof NotFoundError) { if (reportError) { await failJob({ jobId, cxId, - reason: JSON.stringify(error.status), + reason: `${error.constructor.name}: ${error.message} (status: ${error.status})`, }); } return; }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (11)
packages/api/src/command/medical/patient/patient-monitoring/discharge-requery/create.ts
(1 hunks)packages/api/src/routes/internal/medical/patient-job.ts
(1 hunks)packages/api/src/routes/internal/medical/patient-monitoring/discharge-requery.ts
(1 hunks)packages/core/src/command/job/patient/api/fail-job.ts
(1 hunks)packages/core/src/command/patient-monitoring/discharge-requery/discharge-requery-direct.ts
(1 hunks)packages/core/src/command/patient-monitoring/discharge-requery/discharge-requery-factory.ts
(1 hunks)packages/core/src/command/patient-monitoring/discharge-requery/discharge-requery.ts
(1 hunks)packages/infra/lib/patient-monitoring-nested-stack.ts
(1 hunks)packages/lambdas/src/patient-monitoring/discharge-requery.ts
(1 hunks)packages/shared/src/domain/patient/patient-monitoring/discharge-requery.ts
(1 hunks)packages/shared/src/domain/patient/patient-monitoring/utils.ts
(1 hunks)
✅ Files skipped from review due to trivial changes (1)
- packages/api/src/routes/internal/medical/patient-job.ts
🚧 Files skipped from review as they are similar to previous changes (7)
- packages/core/src/command/patient-monitoring/discharge-requery/discharge-requery-factory.ts
- packages/api/src/routes/internal/medical/patient-monitoring/discharge-requery.ts
- packages/api/src/command/medical/patient/patient-monitoring/discharge-requery/create.ts
- packages/shared/src/domain/patient/patient-monitoring/utils.ts
- packages/core/src/command/patient-monitoring/discharge-requery/discharge-requery.ts
- packages/infra/lib/patient-monitoring-nested-stack.ts
- packages/shared/src/domain/patient/patient-monitoring/discharge-requery.ts
🧰 Additional context used
📓 Path-based instructions (2)
`**/*`: Use eslint to enforce code style Use prettier to format code Max column ...
**/*
: Use eslint to enforce code style
Use prettier to format code
Max column length is 100 chars
Multi-line comments use /** */
Top-level comments go after the import (save pre-import to basic file header, like license)
Move literals to constants declared after imports when possible
File names: kebab-case
📄 Source: CodeRabbit Inference Engine (.cursorrules)
List of files the instruction was applied to:
packages/lambdas/src/patient-monitoring/discharge-requery.ts
packages/core/src/command/job/patient/api/fail-job.ts
packages/core/src/command/patient-monitoring/discharge-requery/discharge-requery-direct.ts
`**/*.ts`: - Use the Onion Pattern to organize a package's code in layers - 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
⚙️ Source: CodeRabbit Configuration File
List of files the instruction was applied to:
packages/lambdas/src/patient-monitoring/discharge-requery.ts
packages/core/src/command/job/patient/api/fail-job.ts
packages/core/src/command/patient-monitoring/discharge-requery/discharge-requery-direct.ts
🧬 Code Graph Analysis (1)
packages/core/src/command/patient-monitoring/discharge-requery/discharge-requery-direct.ts (8)
packages/shared/src/common/numbers.ts (1)
randomIntBetween
(16-24)packages/core/src/command/patient-monitoring/discharge-requery/discharge-requery.ts (3)
DischargeRequery
(13-15)ProcessDischargeRequeryRequest
(11-11)dischargeRequeryContext
(2-2)packages/shared/src/util/uuid-v7.ts (1)
uuidv7
(368-368)packages/core/src/command/shared/api/start-patient-query.ts (1)
startPatientQuery
(15-49)packages/shared/src/index.ts (3)
sleep
(13-13)BadRequestError
(40-40)NotFoundError
(42-42)packages/core/src/command/job/patient/api/fail-job.ts (1)
failJob
(19-39)packages/core/src/command/job/patient/api/update-job-runtime-data.ts (1)
updateJobRuntimeData
(20-46)packages/lambdas/src/shared/capture.ts (1)
capture
(18-103)
⏰ Context from checks skipped due to timeout of 90000ms (6)
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
packages/core/src/command/job/patient/api/fail-job.ts (1)
1-39
: LGTM! Well-implemented job failure utility.The implementation follows coding guidelines correctly:
- Proper error handling with original error as cause
- Structured logging with context
- Network retry resilience with
executeWithNetworkRetries
- Good TypeScript typing with extending base parameters
- Clear documentation with JSDoc comments
packages/core/src/command/patient-monitoring/discharge-requery/discharge-requery-direct.ts (1)
40-47
: LGTM! Proper UUID generation and patient query initialization.The implementation correctly generates a UUID v7 for the data pipeline request ID and calls the patient query with appropriate default parameters.
} catch (error) { | ||
if (reportError) { | ||
await failJob({ | ||
jobId, | ||
cxId, | ||
reason: "Error processing discharge requery", | ||
}); | ||
} | ||
|
||
capture.setExtra({ | ||
cxId, | ||
jobId, | ||
patientId, | ||
context: `${dischargeRequeryContext}.processDischargeRequery`, | ||
error, | ||
}); | ||
|
||
log(`Error processing discharge requery: ${error}`); | ||
throw error; | ||
} |
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.
🛠️ Refactor suggestion
Improve error context and avoid potential double error reporting.
The outer catch block might duplicate error reporting if the inner catch block already handled specific errors. Consider adding more context to distinguish between different failure scenarios.
} catch (error) {
+ const errorMsg = errorToString(error);
+ log(`Error in processDischargeRequery: ${errorMsg}`);
+
if (reportError) {
await failJob({
jobId,
cxId,
- reason: "Error processing discharge requery",
+ reason: `Unexpected error during discharge requery: ${errorMsg}`,
});
}
capture.setExtra({
cxId,
jobId,
patientId,
context: `${dischargeRequeryContext}.processDischargeRequery`,
- error,
+ error: errorMsg,
});
- log(`Error processing discharge requery: ${error}`);
throw error;
}
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In
packages/core/src/command/patient-monitoring/discharge-requery/discharge-requery-direct.ts
between lines 93 and 112, the outer catch block may cause duplicate error
reporting if the inner catch block already handled errors. To fix this, enhance
the error context by adding distinguishing information about the failure
scenario before reporting, and implement a mechanism to check if the error has
been previously handled to avoid double reporting. Adjust the capture and
logging calls accordingly to reflect this improved context.
Part of ENG-432 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: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
packages/core/src/command/job/patient/api/fail-job.ts
(1 hunks)packages/core/src/command/patient-monitoring/discharge-requery/discharge-requery-direct.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/core/src/command/patient-monitoring/discharge-requery/discharge-requery-direct.ts
🧰 Additional context used
📓 Path-based instructions (2)
`**/*`: Use eslint to enforce code style Use prettier to format code Max column ...
**/*
: Use eslint to enforce code style
Use prettier to format code
Max column length is 100 chars
Multi-line comments use /** */
Top-level comments go after the import (save pre-import to basic file header, like license)
Move literals to constants declared after imports when possible
File names: kebab-case
📄 Source: CodeRabbit Inference Engine (.cursorrules)
List of files the instruction was applied to:
packages/core/src/command/job/patient/api/fail-job.ts
`**/*.ts`: - Use the Onion Pattern to organize a package's code in layers - 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
⚙️ Source: CodeRabbit Configuration File
List of files the instruction was applied to:
packages/core/src/command/job/patient/api/fail-job.ts
🧬 Code Graph Analysis (1)
packages/core/src/command/job/patient/api/fail-job.ts (3)
packages/core/src/command/job/patient/api/shared.ts (1)
JobBaseParams
(5-5)packages/shared/src/net/retry.ts (1)
executeWithNetworkRetries
(108-135)packages/shared/src/common/response.ts (1)
logAxiosResponse
(17-23)
⏰ Context from checks skipped due to timeout of 90000ms (6)
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: Analyze (javascript)
🔇 Additional comments (3)
packages/core/src/command/job/patient/api/fail-job.ts (3)
1-6
: LGTM: Clean import structureThe imports are well-organized and follow the coding guidelines properly.
8-11
: LGTM: Proper type definitionThe
FailJobParams
type correctly extendsJobBaseParams
and adds the required fields. Good use of TypeScript intersection types.
21-42
: LGTM: Solid implementation with proper error handlingThe function implementation follows coding guidelines excellently:
- Uses destructuring parameters as recommended
- Implements proper error handling with cause preservation
- Uses
async/await
instead of.then()
- Uses
const
instead oflet
- Static error message with dynamic data in
additionalInfo
- Proper logging without multi-line strings or objects as parameters
- Uses network retry logic appropriately
Part of ENG-432 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-432 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-432 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-432 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Issues:
Dependencies
Description
Testing
[Release PRs:]
Check each PR.
Release Plan
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Documentation