Skip to content

Conversation

RamilGaripov
Copy link
Contributor

@RamilGaripov RamilGaripov commented Jun 13, 2025

Issues:

Dependencies

Description

  • Added the discharge requery flow to the system
  • TBD: Refer to the diagram in this document for reference

Testing

  • Local
    • Postman endpoint tests
      • Create a new discharge requery job
        • New db rows look good
        • Jobs get deduplicated when new ones created
      • Trigger job execution
        • PD starts
        • DQ starts
  • Staging
    • Send an ADT to the MLLP on staging and test the entire flow
  • Production
    • Monitor performance in production

[Release PRs:]

Check each PR.

Release Plan

  • Merge this

Summary by CodeRabbit

  • New Features

    • Introduced a discharge requery workflow for patient monitoring, including job creation, scheduling with retry backoff, and status tracking.
    • Added internal API endpoints for managing and running discharge requery jobs.
    • Integrated AWS Lambda and SQS queue infrastructure for processing discharge requery tasks.
    • Added environment-based handler selection for discharge requery processing.
    • Enhanced analytics with new event types related to discharge requery processes.
  • Bug Fixes

    • Improved job deduplication, cancellation, and error handling in the discharge requery process.
  • Tests

    • Added comprehensive unit tests for discharge requery job creation, scheduling utilities, and workflow logic.
  • Documentation

    • Updated and added detailed comments for new features and workflow steps.

Part of ENG-432

Signed-off-by: Ramil Garipov <ramil@metriport.com>
Copy link

linear bot commented Jun 13, 2025

Copy link

coderabbitai bot commented Jun 13, 2025

Walkthrough

This 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

File(s) / Path(s) Change Summary
api/src/command/medical/document/process-doc-query-webhook.ts Adds call to finishDischargeRequery in handleConversionWebhook to finalize discharge requery jobs based on conversion status.
api/src/command/medical/patient/patient-monitoring/discharge-requery/finish.ts Adds finishDischargeRequery function to complete discharge requery jobs, update attempts, runtime data, and analytics.
api/src/command/medical/patient/patient-monitoring/discharge-requery/create.ts Introduces logic to create and deduplicate discharge requery jobs, schedule execution, and handle remaining attempts.
api/src/command/medical/patient/patient-monitoring/discharge-requery/initialize.ts Adds runDischargeRequeryJob to initialize and execute discharge requery jobs.
api/src/command/medical/patient/patient-monitoring/discharge-requery/tests/create.test.ts Adds tests for discharge requery job creation, deduplication, and scheduling logic.
api/src/routes/internal/medical/patient-monitoring/discharge-requery.ts New internal POST endpoint to create discharge requery jobs for a patient.
api/src/routes/internal/medical/patient-monitoring/job.ts New internal POST endpoint to run discharge requery jobs.
api/src/routes/internal/medical/patient-monitoring/index.ts Adds router for patient monitoring internal endpoints.
api/src/routes/internal/medical/patient.ts Registers patient monitoring routes under /monitoring.
api/src/routes/internal/medical/patient-job.ts JSDoc comment formatting change only.
core/src/command/hl7-notification/hl7-notification-webhook-sender-direct.ts Adds logic to trigger discharge requery job creation on HL7 "A03" (discharge) events via internal API.
core/src/command/job/patient/api/update-job-runtime-data.ts Makes context a required parameter for updating job runtime data, improving contextual logging and error reporting.
core/src/command/job/patient/api/fail-job.ts Adds failJob function to mark jobs as failed via API.
core/src/command/patient-monitoring/discharge-requery/discharge-requery.ts Introduces types, schemas, and interface for discharge requery processing.
core/src/command/patient-monitoring/discharge-requery/discharge-requery-direct.ts Implements direct (local) discharge requery handler for development/testing.
core/src/command/patient-monitoring/discharge-requery/discharge-requery-cloud.ts Implements cloud (SQS-based) discharge requery handler for production.
core/src/command/patient-monitoring/discharge-requery/discharge-requery-factory.ts Adds factory to select discharge requery handler based on environment.
external/analytics/posthog.ts Adds "dischargeRequery" event type to analytics.
core/src/util/config.ts Adds method to retrieve discharge requery queue URL from environment.
infra/lib/api-stack.ts Integrates new PatientMonitoringNestedStack (Lambda + SQS) into API stack and passes resources to API service.
infra/lib/api-stack/api-service.ts Adds support for injecting discharge requery SQS queue URL and permissions into API service.
infra/lib/patient-monitoring-nested-stack.ts Adds nested stack to provision Lambda and SQS FIFO queue for discharge requery processing, with alarm and secret integration.
lambdas/src/patient-monitoring/discharge-requery.ts Implements Lambda handler to process discharge requery SQS messages, invoke direct processor, and manage retries.
shared/src/domain/job/types.ts Extends JobParamsOps type to allow number values.
shared/src/domain/patient/patient-monitoring/discharge-requery.ts Adds types, schemas, and parser for discharge requery jobs and runtime data.
shared/src/domain/patient/patient-monitoring/utils.ts Adds scheduling utilities for retry backoff, attempt picking, and scheduling calculations.
shared/src/domain/patient/patient-monitoring/tests/utils.test.ts Adds tests for scheduling and utility functions related to discharge requery.

Sequence Diagram(s)

Discharge Requery Job Creation and Execution

sequenceDiagram
    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)
Loading

Discharge Requery Job Completion Flow

sequenceDiagram
    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
Loading

Discharge Requery Job Deduplication Logic

sequenceDiagram
    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
Loading

Possibly related PRs

  • 2330 Bulk import v1 #3412: Modifies handleConversionWebhook in process-doc-query-webhook.ts to add asynchronous calls including finishSinglePatientImport. Related to discharge requery job finalization logic in the same webhook handler.

Warning

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

🔧 ESLint

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

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


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d01cdfa and 328f517.

📒 Files selected for processing (3)
  • packages/api/src/command/medical/patient/patient-monitoring/discharge-requery/__tests__/create.test.ts (1 hunks)
  • packages/api/src/command/medical/patient/patient-monitoring/discharge-requery/finish.ts (1 hunks)
  • packages/shared/src/domain/patient/patient-monitoring/discharge-requery.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/api/src/command/medical/patient/patient-monitoring/discharge-requery/finish.ts
  • packages/api/src/command/medical/patient/patient-monitoring/discharge-requery/tests/create.test.ts
  • packages/shared/src/domain/patient/patient-monitoring/discharge-requery.ts
⏰ 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)
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

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>
Part of ENG-432

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

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: 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 and NotFoundError 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

📥 Commits

Reviewing files that changed from the base of the PR and between dc8db7c and bd29d36.

📒 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, 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

⚙️ 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.

Comment on lines 93 to 112
} 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;
}
Copy link

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>
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bd29d36 and b9b31a8.

📒 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, 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

⚙️ 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 structure

The imports are well-organized and follow the coding guidelines properly.


8-11: LGTM: Proper type definition

The FailJobParams type correctly extends JobBaseParams and adds the required fields. Good use of TypeScript intersection types.


21-42: LGTM: Solid implementation with proper error handling

The 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 of let
  • 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>
@RamilGaripov RamilGaripov added this pull request to the merge queue Jun 26, 2025
Merged via the queue into develop with commit 331b539 Jun 26, 2025
22 checks passed
@RamilGaripov RamilGaripov deleted the eng-432-implement-post-discharge-requery branch June 26, 2025 01:34
@RamilGaripov RamilGaripov mentioned this pull request Jun 26, 2025
3 tasks
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.

2 participants