10000 RELEASE ENG-243 Initial version of capture.wrapHandler by leite08 · Pull Request #3809 · metriport/metriport · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

RELEASE ENG-243 Initial version of capture.wrapHandler #3809

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
May 9, 2025
Merged

Conversation

leite08
Copy link
Member
@leite08 leite08 commented May 9, 2025

Issues:

Dependencies

none

Description

Testing

Check each PR.

Release Plan

  • ⚠️ Points to master
  • Merge this

Summary by CodeRabbit

  • Refactor

    • Introduced a new centralized error and context capturing utility for Lambda handlers, with initial adoption in some handlers.
    • Refactored select Lambda handlers to use the new error capturing wrapper, improving error context and consistency.
    • Enhanced logging and error messages for better clarity in select modules.
    • Modularized and improved concurrent processing and error handling in message processing for increased reliability.
  • Style

    • Added TODO comments across Lambda handlers indicating planned migration to the new error capturing utility.
  • Bug Fixes

    • Improved serialization of logged progress information for better readability in logs.
    • Clarified error messages for failed data retrieval operations.

leite08 added 7 commits May 2, 2025 11:03
Ref eng-243

Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
Ref eng-243

Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
Ref eng-243

Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
Ref eng-243

Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
Ref eng-243

Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
Ref eng-243

Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
…ndler

ENG-243 Initial version of capture.wrapHandler
Copy link
linear bot commented May 9, 2025

Copy link
coderabbitai bot commented May 9, 2025

Walkthrough

This change introduces a new capture.wrapHandler utility for AWS Lambda handlers to centralize error capturing and context enrichment. Several Lambda handlers are refactored to use this wrapper, while many others receive TODO comments indicating future migration. Additional improvements include enhanced error logging, context enrichment, and modularization of handler logic in select files.

Changes

File(s) Change Summary
packages/lambdas/src/shared/capture.ts Added wrapHandler method to the capture object for standardized Lambda error capturing and context enrichment.
packages/lambdas/src/document-downloader.ts Switched handler wrapping from Sentry to capture.wrapHandler and enriched context with cxId and orgOid.
packages/lambdas/src/fhir-to-medical-record2.ts Refactored handler to use capture.wrapHandler, removed manual try/catch, and set user/extra context via capture.
packages/lambdas/src/sqs-to-converter.ts Refactored handler to use capture.wrapHandler, modularized logic, added concurrent processing, explicit hydration timeout, and improved error/context handling.
packages/api/src/command/medical/patient/consolidated-get.ts Improved log message serialization and updated error message for consolidated data retrieval.
packages/core/src/external/aws/lambda.ts Changed default logger in getLambdaResultPayload to use a custom logger.
packages/lambdas/src/document-uploader.ts, .../acm-cert-monitor.ts, .../cda-to-visualization.ts, .../conversion-result-notifier.ts, .../cw-doc-contribution.ts, .../cw-enhanced-coverage-link-patients.ts, .../cw-session-management.ts, .../ehr-compute-resource-diff-bundles.ts, .../ehr-refresh-ehr-bundles.ts, .../ehr-start-resource-diff-bundles.ts, .../ehr-sync-patient.ts, .../elation-link-patient.ts, .../fhir-to-bundle-count.ts, .../fhir-to-bundle.ts, .../fhir-to-cda-converter.ts, .../healthie-link-patient.ts, .../hl7-notification-webhook-sender.ts, .../hl7v2-roster.ts, .../ihe-gateway-v2-inbound-document-query.ts, .../ihe-gateway-v2-inbound-document-retrieval.ts, .../ihe-gateway-v2-inbound-patient-discovery.ts, .../ihe-gateway-v2-outbound-document-query.ts, .../ihe-gateway-v2-outbound-document-retrieval.ts, .../ihe-gateway-v2-outbound-patient-discovery-write-to-s3.ts, .../ihe-gateway-v2-outbound-patient-discovery.ts, .../ihe-outbound-document-query.ts, .../ihe-outbound-document-retrieval.ts, .../ihe-outbound-patient-discovery.ts, .../patient-import-create.ts, .../patient-import-parse.ts, .../patient-import-query.ts, .../patient-import-result.ts, .../patient-import-upload-notification.ts, .../scheduled.ts, .../sqs-to-opensearch-xml.ts, .../sqs-to-sqs.ts, .../tester.ts, .../token-auth.ts, .../document-bulk-signer.ts Added TODO comments above Lambda handler exports indicating future migration to capture.wrapHandler(). No functional changes.

Sequence Diagram(s)

Centralized Lambda Handler Error Capture

sequenceDiagram
    participant AWSLambda
    participant Handler
    participant capture.wrapHandler
    participant Sentry

    AWSLambda->>capture.wrapHandler: Invoke wrapped handler
    capture.wrapHandler->>Handler: Execute handler logic
    alt Handler throws error
        capture.wrapHandler->>Sentry: Capture error and context
        capture.wrapHandler->>AWSLambda: Rethrow error
    else Handler succeeds
        capture.wrapHandler->>AWSLambda: Return handler result
    end
Loading

SQS-to-Converter Lambda (Refactored Flow)

sequenceDiagram
    participant SQS
    participant capture.wrapHandler
    participant Handler
    participant Sentry
    participant Converter
    participant Storage

    SQS->>capture.wrapHandler: Event
    capture.wrapHandler->>Handler: Process event
    Handler->>Handler: Extract and set context
    Handler->>Storage: Store preprocessed payload
    par
        Handler->>Handler: Process attachments
        Handler->>Storage: Store partitioned payloads
    and
        Handler->>Converter: Convert FHIR
    end
    Handler->>Handler: Hydrate bundle (with timeout)
    alt Hydration error
        Handler->>Sentry: Log warning
    end
    Handler->>Storage: Store hydrated/normalized bundle
    Handler->>Handler: Post-process and send result
    Handler->>capture.wrapHandler: Return or throw error
Loading

Possibly related PRs

✨ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

🧹 Nitpick comments (38)
packages/lambdas/src/token-auth.ts (1)

19-19: Track and implement migration to capture.wrapHandler
The added TODO indicates a pending refactor to replace Sentry.AWSLambda.wrapHandler with capture.wrapHandler. Please ensure this task is tracked (e.g., in an issue or backlog) and consider performing the migration now to avoid accumulating technical debt.

Would you like me to draft the implementation for wrapping this handler using capture.wrapHandler()?

packages/lambdas/src/patient-import-result.ts (1)

16-16: Track and implement migration to capture.wrapHandler
The TODO placeholder marks a future refactor to centralize error capturing via capture.wrapHandler. Ensure this work is tracked and prioritized, and consider migrating this handler in the current scope.

Can I help you generate the updated handler signature using capture.wrapHandler()?

packages/lambdas/src/ehr-compute-resource-diff-bundles.ts (1)

23-23: Track and implement migration to capture.wrapHandler
This TODO signals an upcoming change to replace Sentry.AWSLambda.wrapHandler with capture.wrapHandler. Confirm that this migration is tracked and decide if we should apply it now to maintain consistency across handlers.

Let me know if you’d like a diff for updating this export to use capture.wrapHandler().

packages/lambdas/src/ehr-start-resource-diff-bundles.ts (1)

22-22: Track and implement migration to capture.wrapHandler
The inserted TODO denotes a pending switch from Sentry.AWSLambda.wrapHandler to the centralized capture.wrapHandler. Please ensure this is captured in your release plan and consider completing the migration in this PR to stay consistent.

Would you like me to propose the updated handler wrapper implementation?

packages/lambdas/src/healthie-link-patient.ts (1)

21-21: Track and implement migration to capture.wrapHandler
This TODO comment flags a future refactor to use capture.wrapHandler instead of Sentry.AWSLambda.wrapHandler. Ensure the task is documented and consider applying the change now for uniform error handling.

Can I assist by drafting the necessary wrapper migration here?

packages/lambdas/src/hl7-notification-webhook-sender.ts (1)

19-19: Migrate handler to capture.wrapHandler()
A TODO was added to replace Sentry.AWSLambda.wrapHandler with capture.wrapHandler() for centralized error capturing and context enrichment. Since capture.wrapHandler is available, consider performing this migration now to keep consistency across all Lambda handlers.

Apply this diff:

-// TODO move to capture.wrapHandler()
-export const handler = Sentry.AWSLambda.wrapHandler(async (event: SQSEvent): Promise<void> => {
+export const handler = capture.wrapHandler(async (event: SQSEvent): Promise<void> => {

(Remove the @sentry/serverless import if it’s no longer used)

packages/lambdas/src/conversion-result-notifier.ts (1)

16-16: Migrate handler to capture.wrapHandler()
You’ve marked this handler for future migration from Sentry.AWSLambda.wrapHandler to capture.wrapHandler(). To standardize error handling and context enrichment immediately, replace the Sentry wrapper now.

Apply this diff:

-// TODO move to capture.wrapHandler()
-export const handler = Sentry.AWSLambda.wrapHandler(async (event: SQSEvent) => {
+export const handler = capture.wrapHandler(async (event: SQSEvent) => {

(Remove the @sentry/serverless import if it’s no longer needed)

packages/lambdas/src/patient-import-parse.ts (1)

17-17: Migrate handler to capture.wrapHandler()
The TODO indicates a planned switch from Sentry.AWSLambda.wrapHandler to capture.wrapHandler(). To apply consistent error capturing and avoid drift, implement this change now.

Apply this diff:

-// TODO move to capture.wrapHandler()
-export const handler = Sentry.AWSLambda.wrapHandler(
+export const handler = capture.wrapHandler(

(Prune unused @sentry/serverless import if applicable)

packages/lambdas/src/ehr-refresh-ehr-bundles.ts (1)

22-22: Migrate handler to capture.wrapHandler()
You’ve left a TODO to replace Sentry.AWSLambda.wrapHandler with capture.wrapHandler(). To unify your error handling layer and ensure enriched context, convert this handler now.

Apply this diff:

-// TODO move to capture.wrapHandler()
-export const handler = Sentry.AWSLambda.wrapHandler(async (event: SQSEvent) => {
+export const handler = capture.wrapHandler(async (event: SQSEvent) => {

(Also remove the @sentry/serverless import if it’s redundant)

packages/lambdas/src/ehr-sync-patient.ts (1)

21-21: Migrate handler to capture.wrapHandler()
A TODO marks this handler for migration from Sentry.AWSLambda.wrapHandler to capture.wrapHandler(). For consistency and centralized context enrichment, update this now.

Apply this diff:

-// TODO move to capture.wrapHandler()
-export const handler = Sentry.AWSLambda.wrapHandler(async (event: SQSEvent) => {
+export const handler = capture.wrapHandler(async (event: SQSEvent) => {

(Remove @sentry/serverless import if unused)

packages/lambdas/src/elation-link-patient.ts (1)

21-21: Include JIRA ticket reference in TODO comment.

To improve traceability and consistency across handlers, update the TODO to reference ENG-243 and clarify the migration target:

// TODO(ENG-243): migrate to `capture.wrapHandler()` instead of `Sentry.AWSLambda.wrapHandler()`
packages/lambdas/src/tester.ts (1)

19-19: Reference the ticket in the TODO comment.

For clarity and consistency, annotate the migration task with the JIRA issue and the exact replacement:

// TODO(ENG-243): switch to `capture.wrapHandler()` in place of `Sentry.AWSLambda.wrapHandler()`
packages/lambdas/src/scheduled.ts (1)

24-24: Enhance TODO with ticket and expected change.

Include the ENG-243 reference and specify the target wrapper function:

// TODO(ENG-243): replace `Sentry.AWSLambda.wrapHandler` with `capture.wrapHandler()` for unified error capturing
packages/lambdas/src/acm-cert-monitor.ts (1)

17-17: Clarify TODO with JIRA and migration details.

Update the comment to track the task and desired change:

// TODO(ENG-243): migrate handler to `capture.wrapHandler()` and remove direct Sentry wrapping
packages/lambdas/src/ihe-outbound-document-query.ts (1)

20-20: Enhance TODO comment with ticket and context.

To guide future refactoring, adjust the TODO as follows:

// TODO(ENG-243): replace `Sentry.AWSLambda.wrapHandler` with `capture.wrapHandler()` to centralize error context
packages/lambdas/src/ihe-outbound-patient-discovery.ts (1)

20-20: Suggest standardizing TODO format with JIRA reference.
For better traceability across the codebase, consider updating the comment to:

// TODO ENG-243: move to capture.wrapHandler()

This makes it clear which ticket drives the change and follows the TODO: convention.

packages/lambdas/src/ihe-gateway-v2-outbound-patient-discovery.ts (1)

14-14: Suggest standardizing TODO format with JIRA reference.
To improve consistency and traceability, please tweak the comment to:

// TODO ENG-243: move to capture.wrapHandler()
packages/lambdas/src/ihe-gateway-v2-outbound-document-query.ts (1)

14-14: Suggest standardizing TODO format with JIRA reference.
Enhance the comment for clarity and consistency:

// TODO ENG-243: move to capture.wrapHandler()
packages/lambdas/src/cw-doc-contribution.ts (1)

32-32: Suggest standardizing TODO format with JIRA reference.
For better cross-reference, update to:

// TODO ENG-243: move to capture.wrapHandler()
packages/lambdas/src/document-uploader.ts (1)

13-13: Suggest standardizing TODO format with JIRA reference.
To maintain consistency and aid tracking, consider:

// TODO ENG-243: move to capture.wrapHandler()
packages/lambdas/src/patient-import-create.ts (1)

28-28: Ensure migration to capture.wrapHandler() is tracked
A TODO has been added to migrate this handler to use the new centralized wrapper. Please confirm that there's a corresponding ticket or backlog item to complete this refactor so it doesn’t get forgotten.

Would you like me to draft the issue or implement the wrapper now?

packages/lambdas/src/hl7v2-roster.ts (1)

8-8: Ensure migration to capture.wrapHandler() is tracked
You've added a placeholder to wrap this handler in capture.wrapHandler(). Please verify there's an issue or task scheduled for this migration to avoid leaving it indefinitely as a TODO.

Shall I open the ticket or apply the wrapper directly?

packages/lambdas/src/ihe-gateway-v2-inbound-document-retrieval.ts (1)

28-29: Align handler with new capture.wrapHandler pattern
You’ve added a TODO marking this handler for migration, but it’s still a plain export async function. To centralize error capture and context enrichment, consider wrapping it with capture.wrapHandler now.

Example diff:

+ import { capture } from "./shared/capture";
- // TODO move to capture.wrapHandler()
- export async function handler(event: APIGatewayProxyEventV2) {
+ export const handler = capture.wrapHandler(async (event: APIGatewayProxyEventV2) => {
packages/lambdas/src/fhir-to-bundle.ts (1)

29-30: Consolidate error handling via capture.wrapHandler
You’ve marked the handler for refactoring but left it as a plain async function. Wrap it with capture.wrapHandler to leverage the shared error/context logic.

- // TODO move to capture.wrapHandler()
- export async function handler(
+ export const handler = capture.wrapHandler(async (

(The capture import is already present on line 9.)

packages/lambdas/src/document-bulk-signer.ts (1)

17-18: Migrate from Sentry to capture.wrapHandler
The handler is still using Sentry.AWSLambda.wrapHandler. Switch to capture.wrapHandler for unified handling and remove the unused Sentry import.

- import * as Sentry from "@sentry/serverless";
+ // import removed, using capture instead
...
- // TODO move to capture.wrapHandler()
- export const handler = Sentry.AWSLambda.wrapHandler(
+ export const handler = capture.wrapHandler(
packages/lambdas/src/cw-enhanced-coverage-link-patients.ts (1)

54-55: Standardize with capture.wrapHandler
Rather than wrapping with Sentry.AWSLambda.wrapHandler, use capture.wrapHandler to centralize your error and context enrichment. Remove the Sentry import.

- import * as Sentry from "@sentry/serverless";
+ // import removed, using capture instead
...
- // TODO move to capture.wrapHandler()
- export const handler = Sentry.AWSLambda.wrapHandler(async (event: SQSEvent) => {
+ export const handler = capture.wrapHandler(async (event: SQSEvent) => {
packages/lambdas/src/cw-session-management.ts (1)

48-49: Transition handler to capture.wrapHandler
Replace the Sentry wrapper with capture.wrapHandler to unify error reporting and remove the Sentry import.

- import * as Sentry from "@sentry/serverless";
+ // import removed, using capture instead
...
- // TODO move to capture.wrapHandler()
- export const handler = Sentry.AWSLambda.wrapHandler(async () => {
+ export const handler = capture.wrapHandler(async () => {
packages/lambdas/src/patient-import-query.ts (1)

27-28: Standardize handler wrapping with capture.wrapHandler
The added TODO correctly marks the upcoming refactor. Once the new wrapper is stable, replace the current Sentry.AWSLambda.wrapHandler call with capture.wrapHandler to unify error capture and context enrichment across all Lambdas.

Example diff:

- // TODO move to capture.wrapHandler()
-export const handler = Sentry.AWSLambda.wrapHandler(async function handler(event: SQSEvent) {
+ // TODO move to capture.wrapHandler()
+export const handler = capture.wrapHandler(async function handler(event: SQSEvent) {
packages/lambdas/src/ihe-gateway-v2-inbound-patient-discovery.ts (1)

26-27: Align handler export with capture.wrapHandler
The TODO note is on point. To centralize error handling and context enrichment, wrap the Lambda entrypoint with capture.wrapHandler(...) instead of exporting a bare async function.

Example diff:

- // TODO move to capture.wrapHandler()
-export async function handler(event: APIGatewayProxyEventV2) {
+ // TODO move to capture.wrapHandler()
+export const handler = capture.wrapHandler(async (event: APIGatewayProxyEventV2) => {

Note: you may need to adjust the return shape to match APIGatewayProxy integration.

packages/lambdas/src/ihe-outbound-document-retrieval.ts (1)

20-21: Switch to capture.wrapHandler for consistency
The TODO is a good prompt. When migrating, replace the Sentry.AWSLambda.wrapHandler( call with capture.wrapHandler( to leverage the new centralized capture logic.

Example diff:

- // TODO move to capture.wrapHandler()
-export const handler = Sentry.AWSLambda.wrapHandler(
+ // TODO move to capture.wrapHandler()
+export const handler = capture.wrapHandler(
packages/lambdas/src/sqs-to-sqs.ts (1)

22-23: Migrate to capture.wrapHandler
The added comment flags this file for the same wrapper migration. Replace the Sentry wrapper with the new capture.wrapHandler to ensure uniform error/context handling.

Example diff:

- // TODO move to capture.wrapHandler()
-export const handler = Sentry.AWSLambda.wrapHandler(async (event: SQSEvent) => {
+ // TODO move to capture.wrapHandler()
+export const handler = capture.wrapHandler(async (event: SQSEvent) => {
packages/lambdas/src/ihe-gateway-v2-outbound-document-retrieval.ts (1)

14-15: Unify with capture.wrapHandler
Good catch on the TODO. When you perform the migration, swap out Sentry.AWSLambda.wrapHandler for capture.wrapHandler to centralize capture logic and metadata enrichment.

Example diff:

- // TODO move to capture.wrapHandler()
-export const handler = Sentry.AWSLambda.wrapHandler(
+ // TODO move to capture.wrapHandler()
+export const handler = capture.wrapHandler(
packages/api/src/command/medical/patient/consolidated-get.ts (2)

98-103: Be careful with very large JSON.stringify payloads in logs

JSON.stringify(currentConsolidatedProgress) can easily reach tens / hundreds of KB if the query includes lots of resources, producing verbose CloudWatch logs and throttling the console buffer.
Consider serialising only the relevant keys (e.g. requestId, resources, dateFrom, dateTo) or adding a size guard.

-      `Patient ${patientId} consolidatedQuery is already 'processing' with params: ${JSON.stringify(
-        currentConsolidatedProgress
-      )}, skipping...`
+      `Patient ${patientId} consolidatedQuery already 'processing'. ` +
+      `params: ${JSON.stringify(_.pick(currentConsolidatedProgress, ['requestId','resources','dateFrom','dateTo']))}`

299-302: Minor: unify error message & log context

Nice rename 👍.
While you’re here, prepend the original error message (errorToString(error)) to make the CloudWatch line self-contained without having to open Sentry.

-    log(`${msg}: ${JSON.stringify(filters)}`);
+    log(`${msg}: ${errorToString(error)} | filters=${JSON.stringify(filters)}`);
packages/lambdas/src/document-downloader.ts (1)

35-40: Add missing identifiers to Sentry extras for easier triage

Good move to capture.wrapHandler.
You might also want to include lambdaName (already) and npi / fileInfo.documentUniqueId – those are usually what support / on-call engineers search for.

-    capture.setExtra({ lambdaName, cxId, orgOid });
+    capture.setExtra({ lambdaName, cxId, orgOid, npi, documentUniqueId: document?.uniqueId });
packages/lambdas/src/shared/capture.ts (2)

3-8: Import order & tree-shaking

MetriportError is pulled from @metriport/shared only for the instanceof check below, so it’s fine.
However errorToString is only used inside wrapHandler; consider moving the import next to that function to let bundlers tree-shake it out of other lambdas that don’t call wrapHandler.


90-102: Generic type parameters improve DX for callers of wrapHandler

AWSLambda.Handler defaults to (any, any), so consumers lose compile-time type safety for event / result. Expose generics so callers can retain their specific shapes:

-  wrapHandler: (handler: AWSLambda.Handler): AWSLambda.Handler => {
+  wrapHandler: <E = unknown, C = AWSLambda.Context, R = unknown>(
+    handler: AWSLambda.Handler<E, R>
+  ): AWSLambda.Handler<E, R> => {

This is backwards-compatible and requires no call-site changes.

packages/lambdas/src/fhir-to-medical-record2.ts (1)

78-81: Tiny string interpolation typo

There is an extra } after bucket: ${bucketName} which ends up in the log line.

-        `dateTo: ${dateTo}, fileName: ${fhirFileName}, bucket: ${bucketName}}`
+        `dateTo: ${dateTo}, fileName: ${fhirFileName}, bucket: ${bucketName}`
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4a6fd26 and f5ae81d.

📒 Files selected for processing (45)
  • packages/api/src/command/medical/patient/con 8000 solidated-get.ts (2 hunks)
  • packages/core/src/external/aws/lambda.ts (2 hunks)
  • packages/lambdas/src/acm-cert-monitor.ts (1 hunks)
  • packages/lambdas/src/cda-to-visualization.ts (1 hunks)
  • packages/lambdas/src/conversion-result-notifier.ts (1 hunks)
  • packages/lambdas/src/cw-doc-contribution.ts (1 hunks)
  • packages/lambdas/src/cw-enhanced-coverage-link-patients.ts (1 hunks)
  • packages/lambdas/src/cw-session-management.ts (1 hunks)
  • packages/lambdas/src/document-bulk-signer.ts (1 hunks)
  • packages/lambdas/src/document-downloader.ts (1 hunks)
  • packages/lambdas/src/document-uploader.ts (1 hunks)
  • packages/lambdas/src/ehr-compute-resource-diff-bundles.ts (1 hunks)
  • packages/lambdas/src/ehr-refresh-ehr-bundles.ts (1 hunks)
  • packages/lambdas/src/ehr-start-resource-diff-bundles.ts (1 hunks)
  • packages/lambdas/src/ehr-sync-patient.ts (1 hunks)
  • packages/lambdas/src/elation-link-patient.ts (1 hunks)
  • packages/lambdas/src/fhir-to-bundle-count.ts (1 hunks)
  • packages/lambdas/src/fhir-to-bundle.ts (1 hunks)
  • packages/lambdas/src/fhir-to-cda-converter.ts (1 hunks)
  • packages/lambdas/src/fhir-to-medical-record2.ts (2 hunks)
  • packages/lambdas/src/healthie-link-patient.ts (1 hunks)
  • packages/lambdas/src/hl7-notification-webhook-sender.ts (1 hunks)
  • packages/lambdas/src/hl7v2-roster.ts (1 hunks)
  • packages/lambdas/src/ihe-gateway-v2-inbound-document-query.ts (1 hunks)
  • packages/lambdas/src/ihe-gateway-v2-inbound-document-retrieval.ts (1 hunks)
  • packages/lambdas/src/ihe-gateway-v2-inbound-patient-discovery.ts (1 hunks)
  • packages/lambdas/src/ihe-gateway-v2-outbound-document-query.ts (1 hunks)
  • packages/lambdas/src/ihe-gateway-v2-outbound-document-retrieval.ts (1 hunks)
  • packages/lambdas/src/ihe-gateway-v2-outbound-patient-discovery-write-to-s3.ts (1 hunks)
  • packages/lambdas/src/ihe-gateway-v2-outbound-patient-discovery.ts (1 hunks)
  • packages/lambdas/src/ihe-outbound-document-query.ts (1 hunks)
  • packages/lambdas/src/ihe-outbound-document-retrieval.ts (1 hunks)
  • packages/lambdas/src/ihe-outbound-patient-discovery.ts (1 hunks)
  • packages/lambdas/src/patient-import-create.ts (1 hunks)
  • packages/lambdas/src/patient-import-parse.ts (1 hunks)
  • packages/lambdas/src/patient-import-query.ts (1 hunks)
  • packages/lambdas/src/patient-import-result.ts (1 hunks)
  • packages/lambdas/src/patient-import-upload-notification.ts (1 hunks)
  • packages/lambdas/src/scheduled.ts (1 hunks)
  • packages/lambdas/src/shared/capture.ts (2 hunks)
  • packages/lambdas/src/sqs-to-converter.ts (2 hunks)
  • packages/lambdas/src/sqs-to-opensearch-xml.ts (1 hunks)
  • packages/lambdas/src/sqs-to-sqs.ts (1 hunks)
  • packages/lambdas/src/tester.ts (1 hunks)
  • packages/lambdas/src/token-auth.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/lambdas/src/healthie-link-patient.ts
  • packages/lambdas/src/hl7v2-roster.ts
  • packages/lambdas/src/document-uploader.ts
  • packages/lambdas/src/ehr-compute-resource-diff-bundles.ts
  • packages/lambdas/src/ehr-sync-patient.ts
  • packages/lambdas/src/patient-import-parse.ts
  • packages/lambdas/src/hl7-notification-webhook-sender.ts
  • packages/lambdas/src/patient-import-query.ts
  • packages/lambdas/src/fhir-to-bundle-count.ts
  • packages/lambdas/src/acm-cert-monitor.ts
  • packages/lambdas/src/tester.ts
  • packages/lambdas/src/elation-link-patient.ts
  • packages/lambdas/src/fhir-to-cda-converter.ts
  • packages/lambdas/src/conversion-result-notifier.ts
  • packages/lambdas/src/ihe-outbound-patient-discovery.ts
  • packages/lambdas/src/sqs-to-sqs.ts
  • packages/lambdas/src/ihe-outbound-document-query.ts
  • packages/lambdas/src/ehr-refresh-ehr-bundles.ts
  • packages/lambdas/src/fhir-to-bundle.ts
  • packages/lambdas/src/ihe-outbound-document-retrieval.ts
  • packages/lambdas/src/ihe-gateway-v2-inbound-document-retrieval.ts
  • packages/lambdas/src/token-auth.ts
  • packages/lambdas/src/ihe-gateway-v2-inbound-document-query.ts
  • packages/lambdas/src/ehr-start-resource-diff-bundles.ts
  • packages/lambdas/src/cw-enhanced-coverage-link-patients.ts
  • packages/lambdas/src/ihe-gateway-v2-inbound-patient-discovery.ts
  • packages/lambdas/src/ihe-gateway-v2-outbound-patient-discovery-write-to-s3.ts
  • packages/lambdas/src/cw-session-management.ts
  • packages/lambdas/src/patient-import-result.ts
  • packages/lambdas/src/ihe-gateway-v2-outbound-patient-discovery.ts
  • packages/lambdas/src/ihe-gateway-v2-outbound-document-retrieval.ts
  • packages/lambdas/src/document-bulk-signer.ts
  • packages/lambdas/src/cda-to-visualization.ts
  • packages/core/src/external/aws/lambda.ts
  • packages/api/src/command/medical/patient/consolidated-get.ts
  • packages/lambdas/src/patient-import-create.ts
  • packages/lambdas/src/scheduled.ts
  • packages/lambdas/src/sqs-to-opensearch-xml.ts
  • packages/lambdas/src/document-downloader.ts
  • packages/lambdas/src/ihe-gateway-v2-outbound-document-query.ts
  • packages/lambdas/src/patient-import-upload-notification.ts
  • packages/lambdas/src/fhir-to-medical-record2.ts
  • packages/lambdas/src/cw-doc-contribution.ts
  • packages/lambdas/src/shared/capture.ts
  • packages/lambdas/src/sqs-to-converter.ts
🧬 Code Graph Analysis (3)
packages/lambdas/src/document-downloader.ts (1)
packages/lambdas/src/shared/capture.ts (1)
  • capture (18-103)
packages/lambdas/src/shared/capture.ts (4)
packages/lambdas/src/sqs-to-converter.ts (1)
  • handler (101-328)
packages/lambdas/src/document-downloader.ts (1)
  • handler (35-79)
packages/lambdas/src/fhir-to-medical-record2.ts (1)
  • handler (63-169)
packages/shared/src/index.ts (1)
  • errorToString (42-42)
packages/lambdas/src/sqs-to-converter.ts (3)
packages/lambdas/src/shared/capture.ts (1)
  • capture (18-103)
packages/core/src/external/cda/process-attachments.ts (1)
  • processAttachments (64-185)
packages/shared/src/index.ts (1)
  • errorToString (42-42)
🔇 Additional comments (20)
packages/lambdas/src/ihe-outbound-patient-discovery.ts (1)

20-20: Approve placeholder for future migration.
The added // TODO move to capture.wrapHandler() aligns with the overall refactoring plan to centralize error capturing via capture.wrapHandler(). No functional behavior has changed in this handler.

packages/lambdas/src/ihe-gateway-v2-outbound-patient-discovery.ts (1)

14-14: Approve placeholder for future migration.
The // TODO move to capture.wrapHandler() comment correctly marks this handler for the upcoming switch to capture.wrapHandler(), with no runtime impact.

packages/lambdas/src/ihe-gateway-v2-outbound-document-query.ts (1)

14-14: Approve placeholder for future migration.
This added // TODO move to capture.wrapHandler() is in line with the refactoring strategy and has no effect on existing behavior.

packages/lambdas/src/cw-doc-contribution.ts (1)

32-32: Approve placeholder for future migration.
The new // TODO move to capture.wrapHandler() correctly flags this handler for migration without altering its functionality.

packages/lambdas/src/document-uploader.ts (1)

13-13: Approve placeholder for future migration.
This comment properly marks the handler for later conversion to capture.wrapHandler() and introduces no behavior changes.

packages/lambdas/src/cda-to-visualization.ts (1)

35-35: Appropriate marker for future handler refactoring.

The TODO comment aligns with the PR's objective to introduce a centralized error capturing mechanism using capture.wrapHandler(). This is a preparatory step for future implementation.

packages/lambdas/src/sqs-to-opensearch-xml.ts (1)

44-44: Well-placed TODO marker for handler migration.

This comment correctly identifies a future opportunity to migrate from manual try/catch error handling to the new centralized capture.wrapHandler(). This aligns with the PR's goal of standardizing error handling across Lambda functions.

packages/lambdas/src/fhir-to-cda-converter.ts (1)

16-16: Appropriate marker for future handler refactoring.

The TODO comment correctly identifies this handler as a candidate for migration from Sentry.AWSLambda.wrapHandler to the new capture.wrapHandler() utility. This change is consistent with the PR's objective to standardize error handling.

packages/lambdas/src/patient-import-upload-notification.ts (1)

20-20: Well-placed TODO marker for handler migration.

This comment correctly identifies a future opportunity to migrate from manual error handling to the new centralized capture.wrapHandler(). Currently, this handler implements capture context via capture.setExtra() but still uses manual try/catch blocks for error handling.

packages/core/src/external/aws/lambda.ts (1)

5-5: Improved logging with structured logger.

The change from using console.log to out("getLambdaResultPayload").log aligns with the coding guidelines to avoid direct console logging. This standardized logging approach provides better context and consistency across the codebase.

The implementation correctly:

  1. Imports the required out function from the logging utility
  2. Applies it as the default parameter with appropriate context label
  3. Maintains the same function signature and behavior

Also applies to: 105-105

packages/lambdas/src/shared/capture.ts (1)

92-100: Scope leakage between warm invocations

The Sentry Lambda integration resets the scope per invocation, but only if the wrapper is the outer-most one. Because we call capture.setExtra inside our own wrapper, it’s safe.
Just double-check that other utility functions do not call capture.setExtra outside the Lambda-scope (e.g., in async void tasks after the handler resolves) or the data could leak.
No action required, just a heads-up.

packages/lambdas/src/fhir-to-medical-record2.ts (1)

63-75: Great adoption of capture.wrapHandler

The new wrapper removes a lot of duplicated try/catch plumbing and makes the handler more readable.
The extra context (lambdaName, cxId, patientId, …) will be invaluable in Sentry.
LGTM!

packages/lambdas/src/sqs-to-converter.ts (8)

31-31: Good addition of errorToString for improved error message formatting

The import of errorToString from the shared package is a good addition that helps standardize error message formatting throughout the codebase.


101-328: Great implementation of wrapHandler for centralized error handling

The refactoring to use capture.wrapHandler is a significant improvement that centralizes error capturing and reporting to Sentry. This aligns with the PR objective to automatically call captureSetExtra on Lambda handlers.


129-131: Good extraction of message attributes with improved naming

The extraction of message attributes is well done. I notice that you've renamed serverUrl to converterUrl in the variable assignment, which improves code clarity by making the purpose of the URL more explicit.


134-134: Good addition of validation for converterUrl

Adding validation for the converterUrl parameter is important for catching configuration issues early in the process.


158-170: Good extraction of attachment processing logic

The extraction of attachment processing into a separate async function improves code modularity and readability. This follows the functional programming principles mentioned in the coding guidelines.


209-226: Good use of Promise.all for concurrent processing

Using Promise.all to concurrently execute the conversion, attachment processing, and payload storage is a good performance optimization. The reordering to store the preprocessed payload before conversion also makes logical sense.


245-254: Good implementation of timeout for hydration

Adding a timeout race for hydration that rejects after 5 seconds is a great improvement for handling potentially slow hydration processes. This prevents the Lambda from hanging indefinitely on hydration operations.


268-280: Good error handling for hydration failures

The enhanced error handling for hydration failures is well-implemented. The detailed error message, proper logging with errorToString, and the decision to continue without hydration rather than failing the entire process shows thoughtful error handling.

@leite08 leite08 added this pull request to the merge queue May 9, 2025
Merged via the queue into master with commit 021944a May 9, 2025
66 checks passed
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
0