Skip to content

Conversation

RamilGaripov
Copy link
Contributor

@RamilGaripov RamilGaripov commented Jun 13, 2025

Part of ENG-433

Issues:

Dependencies

Description

  • Moving methods to hit internal PD and DQ routes from patient import to a shared location

Testing

  • Local
    • N/A
  • Staging
    • Run a small patient import job and make sure it works - link

Release Plan

  • Merge this

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Added a new context identifier for patient import processes, improving contextual information in API calls and logs.
    • Introduced a scheduled job scheduler Lambda function to enhance job scheduling capabilities within the infrastructure.
  • Refactor

    • Enhanced API query functions to require a context parameter and return the request ID, providing more detailed feedback on API operations.
    • Updated internal references and logging to use the new context identifier for consistency.
  • Chores

    • Standardized and updated import paths for improved code organization.
    • Enforced mandatory data field in patient job runtime updates to ensure data integrity.
    • Corrected the path for patient job execution to align with deployment structure.
    • Integrated the new job scheduler setup into the API stack initialization.
    • Removed legacy scheduled Lambda creation from job stack for streamlined infrastructure management.

Part of ENG-433

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

The changes update import paths for the withDefaultApiErrorHandling utility across several files, introduce and export a new patientImportContext constant, and enhance the startDocumentQuery and startPatientQuery functions to require a context parameter and return a requestId. Logging and error handling now use dynamic context values. Additionally, a runtime data schema was made stricter, a Lambda function entry path was corrected, and a new job scheduler Lambda creation was added to the API stack while removed from the jobs stack.

Changes

File(s) Change Summary
.../api/create-patient-mapping.ts,
.../api/create-patient.ts,
.../api/update-job-status.ts
Updated import path for withDefaultApiErrorHandling to a shared location.
.../patient-import-shared.ts Added and exported new constant patientImportContext.
.../steps/query/patient-import-query-local.ts Updated imports for API functions; injected patientImportContext into API calls and logging.
.../shared/api/start-document-query.ts Added context parameter to function; return type now includes requestId; updated error handling to use dynamic context.
.../shared/api/start-patient-query.ts Added context parameter to function; return type now includes requestId; updated documentation and error handling for context.
.../routes/internal/medical/patient-job.ts Made data field required in updateRuntimeDataSchema instead of optional.
.../lib/jobs/jobs-stack.ts Removed scheduled Lambda creation for job scheduler; corrected Lambda entry path from "jobs/patient/run-job" to "job/patient/run-job".
.../lib/api-stack.ts Added call to createJobsScheduler to create a scheduled Lambda in the API stack.
.../lib/jobs/jobs-scheduler.ts Added new module defining createJobsScheduler function to create scheduled Lambda for job scheduling with configuration support.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant PatientImportQueryLocal
    participant SharedApi

    Caller->>PatientImportQueryLocal: processPatientQuery()
    PatientImportQueryLocal->>SharedApi: startPatientQuery({..., context: patientImportContext})
    SharedApi-->>PatientImportQueryLocal: { requestId }
    PatientImportQueryLocal->>SharedApi: startDocumentQuery({..., context: patientImportContext })
    SharedApi-->>PatientImportQueryLocal: { requestId }
    PatientImportQueryLocal-->>Caller: (processing/logging with patientImportContext)
Loading
sequenceDiagram
    participant Caller
    participant startPatientQuery

    Caller->>startPatientQuery: startPatientQuery({ ..., context })
    startPatientQuery->>startPatientQuery: Call API with context
    startPatientQuery-->>Caller: { requestId }
Loading
sequenceDiagram
    participant Caller
    participant startDocumentQuery

    Caller->>startDocumentQuery: startDocumentQuery({ ..., context })
    startDocumentQuery->>startDocumentQuery: Call API with context
    startDocumentQuery-->>Caller: { requestId }
Loading

Possibly related PRs

Warning

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

🔧 ESLint

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

npm error code ERR_SSL_WRONG_VERSION_NUMBER
npm error errno ERR_SSL_WRONG_VERSION_NUMBER
npm error request to https://10.0.0.28:4873/punycode/-/punycode-2.3.1.tgz failed, reason: C07CEF8B467F0000: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-25T20_48_08_076Z-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 702ad2c and fb8aaaf.

📒 Files selected for processing (2)
  • packages/infra/lib/api-stack.ts (2 hunks)
  • packages/infra/lib/jobs/jobs-scheduler.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/infra/lib/api-stack.ts
  • packages/infra/lib/jobs/jobs-scheduler.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: 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-433

Signed-off-by: Ramil Garipov <ramil@metriport.com>
@RamilGaripov RamilGaripov marked this pull request as ready for review June 19, 2025 16:13
Base automatically changed from eng-433-scheduler-for-patient-job to develop June 19, 2025 20:24
Thomas Yopes added 2 commits June 19, 2025 15:27
…etriport into eng-433-moving-files

Signed-off-by: Thomas Yopes <thomasyopes@Thomass-MBP.attlocal.net>
Ref: ENG-433

Ref: #1040
Signed-off-by: Thomas Yopes <thomasyopes@Thomass-MBP.attlocal.net>
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 f4ce457 and d156d55.

📒 Files selected for processing (2)
  • packages/api/src/routes/internal/medical/patient-job.ts (1 hunks)
  • packages/infra/lib/jobs/jobs-stack.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.ts`: - Use the Onion Pattern to organize a package's code in layers - Try to use immutable code and avoid sharing state across different functions, objects, and systems - Try...

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

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

28-28: ```shell
#!/bin/bash

Display the context around the 'entry' property in jobs-stack.ts to see how paths are resolved

rg -n "entry:" -A5 -B5 packages/infra/lib/jobs/jobs-stack.ts


</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

});
if (this.waitTimeAtTheEndInMillis > 0) await sleep(this.waitTimeAtTheEndInMillis);
} catch (error) {
const { log } = out(`PatientImport processPatientQuery.local - cx ${cxId}, job ${jobId}`);
const { log } = out(
Copy link
Contributor

@thomasyopes thomasyopes Jun 19, 2025

Choose a reason for hiding this comment

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

you don't need these edits -- this is the patient import code so it doesn't need to send in its own context, can just be inline as it is

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm just replacing the string with a const. What's the big deal? 😅

Copy link
Contributor

Choose a reason for hiding this comment

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

Just unnecessary complexity. If I change the global one, I'm going to have to consider what that might mean for this error message (the fact that they're equal now is arbitrary -- the local implementation error handling might want a different context than the shard code). Generally tying things together that don't need to be is better avoided unless there's a full push it to replace it everywhere and the decision to have shared context -- in which case we'd updated all the local implementations (not just this one).

But, it's low stakes so no worries -- not a blocker by any means.

Thomas Yopes and others added 3 commits June 19, 2025 17:11
Ref: ENG-433

Ref: #1040
Signed-off-by: Thomas Yopes <thomasyopes@Thomass-MBP.attlocal.net>
Ref: ENG-433

Ref: #1040
Signed-off-by: Thomas Yopes <thomasyopes@Thomass-MBP.attlocal.net>
feat(jobs): move job scheduler starter to after api
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/infra/lib/jobs/jobs-scheduler.ts (1)

18-25: Consider extracting the hardcoded function name to a constant.

The function follows functional programming principles and immutability as required by the coding guidelines. However, the hardcoded "StartPatientJobsScheduler" could be extracted to a constant for better maintainability.

+const JOBS_SCHEDULER_LAMBDA_NAME = "StartPatientJobsScheduler";

 function getSettings(props: JobsSchedulerProps, config: NonNullable<EnvConfig["jobs"]>) {
   return {
     ...props,
-    name: "StartPatientJobsScheduler",
+    name: JOBS_SCHEDULER_LAMBDA_NAME,
     scheduleExpression: config.startPatientJobsSchedulerScheduleExpression,
     url: `http://${props.apiAddress}${config.startPatientJobsSchedulerUrl}`,
   };
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d156d55 and 702ad2c.

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

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

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

49-49: LGTM: Import follows established patterns.

The import is correctly placed alphabetically and follows the existing import structure in the file.


740-747: LGTM: Function call follows established patterns and provides proper parameters.

The createJobsScheduler call is consistent with other similar function calls in the file (like createDocQueryChecker and createCqDirectoryRebuilder) and correctly passes all required parameters according to the JobsSchedulerProps type.

packages/infra/lib/jobs/jobs-scheduler.ts (3)

1-9: LGTM: Clean imports following TypeScript best practices.

The imports are well-organized and include only necessary dependencies. The use of type-only imports where appropriate follows TypeScript conventions.


10-16: LGTM: Well-defined type interface following naming conventions.

The JobsSchedulerProps type is properly defined using PascalCase as specified in the coding guidelines, and includes all necessary properties with appropriate TypeScript types.


27-48: LGTM: Function follows functional programming principles and handles edge cases properly.

The function adheres to the coding guidelines by:

  • Using functional programming style (small, deterministic, single responsibility)
  • Properly handling the case where config.jobs is undefined by returning undefined
  • Using meaningful parameter names and TypeScript types
  • Avoiding mutation of input parameters
  • Following camelCase naming convention

The early return pattern for missing configuration is appropriate and prevents errors downstream.

@RamilGaripov RamilGaripov mentioned this pull request Jun 25, 2025
2 tasks
Thomas Yopes added 2 commits June 25, 2025 13:44
… eng-433-moving-files

Signed-off-by: Thomas Yopes <thomasyopes@Thomass-MBP.attlocal.net>
Ref: ENG-433

Ref: #1040
Signed-off-by: Thomas Yopes <thomasyopes@Thomass-MBP.attlocal.net>
@RamilGaripov RamilGaripov added this pull request to the merge queue Jun 25, 2025
Merged via the queue into develop with commit 9cebb0a Jun 25, 2025
18 checks passed
@RamilGaripov RamilGaripov deleted the eng-433-moving-files branch June 25, 2025 20:56
@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