Skip to content

Conversation

thomasyopes
Copy link
Contributor

@thomasyopes thomasyopes commented Jun 14, 2025

Ref: ENG-306

Ref: #1040

Issues:

Description

  • switching lambda code to parse sqs messages

Release Plan

  • Merge this

Summary by CodeRabbit

  • New Features

    • Enhanced input validation for all Surescripts Lambda handlers, ensuring incoming messages conform to expected formats.
    • Improved error handling and observability with enriched context metadata for monitoring and tracing.
  • Refactor

    • Updated Lambda handlers to process AWS SQS events instead of direct object inputs, streamlining message handling and validation across services.
    • Introduced a utility to parse and validate message bodies against schemas for consistent data handling.

Ref: ENG-306

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

linear bot commented Jun 14, 2025

Copy link

coderabbitai bot commented Jun 14, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes refactor several Lambda handler functions to process AWS SQS events instead of direct typed parameters. Each handler now extracts and validates a single message from the SQS event using Zod schemas before invoking the core business logic. Utility functions for message parsing and schema validation are introduced, and additional context is provided for tracing and observability.

Changes

File(s) Change Summary
packages/lambdas/src/shared/sqs.ts Added parseBody utility for Zod-based schema validation of SQS message bodies.
packages/lambdas/src/surescripts/receive-response.ts Refactored handler to accept SQSEvent, extract/validate message, and enhance capture context.
packages/lambdas/src/surescripts/receive-verification.ts Changed handler to process SQSEvent, extract/validate message, and set Lambda context.
packages/lambdas/src/surescripts/send-batch-request.ts Updated handler to accept SQSEvent, extract/validate message with schema, and add Lambda context.
packages/lambdas/src/surescripts/send-patient-request.ts Modified handler to process SQSEvent, extract/validate message, and provide Lambda context.
packages/lambdas/src/surescripts/verify-request-in-history.ts Changed handler to accept SQSEvent, extract/validate message, and add Lambda context for capture.
packages/lambdas/src/surescripts/sftp-action.ts Renamed local variable from handler to sftpActionHandler without changing logic or flow.

Sequence Diagram(s)

sequenceDiagram
    participant SQS as AWS SQS
    participant Lambda as Lambda Handler
    participant Utils as Utility Functions
    participant Zod as Zod Schema
    participant Core as Core Logic

    SQS->>Lambda: Send SQSEvent
    Lambda->>Utils: getSingleMessageOrFail(event)
    Utils-->>Lambda: SQS Message
    Lambda->>Utils: parseBody(schema, message.body)
    Utils->>Zod: schema.parse(JSON.parse(body))
    Zod-->>Utils: Validated Data
    Utils-->>Lambda: Typed Data
    Lambda->>Core: Invoke business logic with typed data
    Core-->>Lambda: (Result/void)
Loading

Possibly related PRs

  • feat(ss): swithc to fifo stuff #4031: Adds the same parseBody utility and refactors Lambda handlers to process AWS SQS events with message extraction and Zod validation, indicating a direct relation.

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: C06CEBFCF87F0000: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-14T05_31_54_799Z-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 854ff6e and 2883b82.

📒 Files selected for processing (6)
  • packages/lambdas/src/surescripts/receive-response.ts (1 hunks)
  • packages/lambdas/src/surescripts/receive-verification.ts (1 hunks)
  • packages/lambdas/src/surescripts/send-batch-request.ts (1 hunks)
  • packages/lambdas/src/surescripts/send-patient-request.ts (1 hunks)
  • packages/lambdas/src/surescripts/sftp-action.ts (1 hunks)
  • packages/lambdas/src/surescripts/verify-request-in-history.ts (1 hunks)
✨ 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.

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

🧹 Nitpick comments (4)
packages/lambdas/src/surescripts/send-patient-request.ts (1)

29-33: Schema should be strict() to reject unexpected keys

Adding .strict() (or .passthrough() explicitly) documents the contract and prevents silent acceptance of unknown fields that could mask upstream issues.

-const surescriptsPatientRequestSchema = z.object({
+const surescriptsPatientRequestSchema = z
+  .object({
     patientId: z.string(),
     cxId: z.string(),
     facilityId: z.string(),
-});
+  })
+  .strict();
packages/lambdas/src/surescripts/send-batch-request.ts (1)

29-33: Use clearer, validated array schema

z.string().array() works but is less idiomatic and doesn’t ensure the list isn’t empty. Prefer z.array(z.string()).min(1) for readability and stronger validation.

-const surescriptsBatchRequestSchema = z.object({
-  patientIds: z.string().array(),
+const surescriptsBatchRequestSchema = z.object({
+  patientIds: z.array(z.string()).min(1),
   cxId: z.string(),
   facilityId: z.string(),
 }).strict();
packages/lambdas/src/surescripts/receive-response.ts (2)

15-17: Trim oversized context sent to Sentry

capture.setExtra({ event, context: lambdaName }); serialises the full SQS event, which can exceed Sentry’s 100 kB limit and increase cost/noise.
Consider logging only metadata (messageId, body length, queueArn, etc.) or attaching the raw body under a breadcrumbs/attachment instead.


16-18: Redundant null-check after getSingleMessageOrFail

getSingleMessageOrFail already throws when no message is found, so the if (!message) return; branch is dead code.

-  const message = getSingleMessageOrFail(event.Records, lambdaName);
-  if (!message) return;
+  const message = getSingleMessageOrFail(event.Records, lambdaName);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 066c056 and 854ff6e.

📒 Files selected for processing (6)
  • packages/lambdas/src/shared/sqs.ts (2 hunks)
  • packages/lambdas/src/surescripts/receive-response.ts (1 hunks)
  • packages/lambdas/src/surescripts/receive-verification.ts (1 hunks)
  • packages/lambdas/src/surescripts/send-batch-request.ts (1 hunks)
  • packages/lambdas/src/surescripts/send-patient-request.ts (1 hunks)
  • packages/lambdas/src/surescripts/verify-request-in-history.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/shared/sqs.ts
  • packages/lambdas/src/surescripts/send-patient-request.ts
  • packages/lambdas/src/surescripts/receive-verification.ts
  • packages/lambdas/src/surescripts/receive-response.ts
  • packages/lambdas/src/surescripts/send-batch-request.ts
  • packages/lambdas/src/surescripts/verify-request-in-history.ts
🧬 Code Graph Analysis (3)
packages/lambdas/src/shared/sqs.ts (1)
packages/shared/src/index.ts (1)
  • MetriportError (41-41)
packages/lambdas/src/surescripts/send-patient-request.ts (4)
packages/lambdas/src/shared/sqs.ts (2)
  • getSingleMessageOrFail (63-84)
  • parseBody (86-95)
packages/core/src/external/surescripts/types.ts (1)
  • SurescriptsPatientRequest (36-38)
packages/lambdas/src/surescripts/shared.ts (1)
  • makeSurescriptsClient (6-15)
packages/core/src/external/surescripts/command/send-patient-request/send-patient-request-direct.ts (1)
  • SurescriptsSendPatientRequestHandlerDirect (7-17)
packages/lambdas/src/surescripts/send-batch-request.ts (7)
packages/lambdas/src/surescripts/receive-verification.ts (1)
  • handler (14-23)
packages/lambdas/src/surescripts/receive-response.ts (1)
  • handler (14-23)
packages/lambdas/src/surescripts/send-patient-request.ts (1)
  • handler (15-27)
packages/lambdas/src/shared/sqs.ts (2)
  • getSingleMessageOrFail (63-84)
  • parseBody (86-95)
packages/core/src/external/surescripts/types.ts (1)
  • SurescriptsBatchRequest (44-46)
packages/lambdas/src/surescripts/shared.ts (1)
  • makeSurescriptsClient (6-15)
packages/core/src/external/surescripts/command/send-batch-request/send-batch-request-direct.ts (1)
  • SurescriptsSendBatchRequestHandlerDirect (7-17)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
packages/lambdas/src/shared/sqs.ts (1)

86-95: 🛠️ Refactor suggestion

Guard against invalid JSON before it takes down the Lambda

JSON.parse will throw a SyntaxError that bypasses the unified MetriportError flow, causing the whole invocation to fail without context. Wrap the parse in a try / catch and re-throw a MetriportError so downstream monitoring sees a consistent error type.

-  const bodyAsJson = JSON.parse(bodyString);
+  let bodyAsJson: unknown;
+  try {
+    bodyAsJson = JSON.parse(bodyString);
+  } catch (err) {
+    throw new MetriportError("Body is not valid JSON", err as Error);
+  }
⛔ Skipped due to learnings
Learnt from: thomasyopes
PR: metriport/metriport#3608
File: packages/lambdas/src/ehr-compute-resource-diff-bundles.ts:58-62
Timestamp: 2025-04-23T19:00:49.707Z
Learning: For Lambda functions in the metriport codebase, the team prefers to let the default Lambda error handling catch JSON parsing errors rather than adding explicit try/catch blocks.

Comment on lines +15 to +17
export const handler = capture.wrapHandler(async (event: SQSEvent) => {
capture.setExtra({ event, context: lambdaName });
const message = getSingleMessageOrFail(event.Records, lambdaName);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid shipping PHI to Sentry/Datadog – don’t attach the raw event

capture.setExtra({ event, context: lambdaName }) serialises the full SQS event, including the message body that contains patientId, potentially leaking regulated data to external observability tooling. Emit only non-sensitive identifiers (e.g., messageId, receiptHandle) instead.

-  capture.setExtra({ event, context: lambdaName });
+  capture.setExtra({
+    context: lambdaName,
+    messageIds: event.Records.map((r) => r.messageId),
+  });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const handler = capture.wrapHandler(async (event: SQSEvent) => {
capture.setExtra({ event, context: lambdaName });
const message = getSingleMessageOrFail(event.Records, lambdaName);
export const handler = capture.wrapHandler(async (event: SQSEvent) => {
capture.setExtra({
context: lambdaName,
messageIds: event.Records.map((r) => r.messageId),
});
const message = getSingleMessageOrFail(event.Records, lambdaName);
🤖 Prompt for AI Agents
In packages/lambdas/src/surescripts/send-patient-request.ts around lines 15 to
17, avoid attaching the full SQS event to capture.setExtra as it includes
sensitive patient information. Instead, extract and pass only non-sensitive
identifiers like messageId and receiptHandle from the event records to
capture.setExtra to prevent leaking PHI to external monitoring tools.

Comment on lines +14 to +16
export const handler = capture.wrapHandler(async (event: SQSEvent) => {
capture.setExtra({ event, context: lambdaName });
const message = getSingleMessageOrFail(event.Records, lambdaName);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Potential PHI leakage – raw event is captured

Same concern as other handlers: the event body contains transmissionId that may link to patient data. Limit the payload you forward to capture.

🤖 Prompt for AI Agents
In packages/lambdas/src/surescripts/receive-verification.ts around lines 14 to
16, the raw event is being passed to capture.setExtra, which may expose
sensitive patient-related data like transmissionId. Modify the code to extract
only non-sensitive, necessary fields from the event before passing them to
capture.setExtra, avoiding forwarding the entire event object to prevent
potential PHI leakage.

Comment on lines +14 to +16
export const handler = capture.wrapHandler(async (event: SQSEvent) => {
capture.setExtra({ event, context: lambdaName });
const message = getSingleMessageOrFail(event.Records, lambdaName);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Restrict captured context to non-sensitive metadata

Forwarding the full SQS event risks exposing patient identifiers. Trim the data to the minimal fields required for debugging.

🤖 Prompt for AI Agents
In packages/lambdas/src/surescripts/verify-request-in-history.ts around lines 14
to 16, the current code forwards the entire SQS event to capture.setExtra, which
may expose sensitive patient identifiers. Modify the code to extract and forward
only the minimal necessary metadata fields from the event for debugging
purposes, avoiding any sensitive or personally identifiable information.

Comment on lines +15 to +17
export const handler = capture.wrapHandler(async (event: SQSEvent) => {
capture.setExtra({ event, context: lambdaName });
const message = getSingleMessageOrFail(event.Records, lambdaName);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Sanitise event before attaching to telemetry

As with the other lambdas, avoid pushing the raw SQS event (contains patient IDs) to external logging/monitoring systems.

🤖 Prompt for AI Agents
In packages/lambdas/src/surescripts/send-batch-request.ts around lines 15 to 17,
the raw SQS event containing sensitive patient IDs is being attached directly to
telemetry. To fix this, sanitize the event data by removing or masking patient
IDs before passing it to capture.setExtra. Ensure only non-sensitive information
is included in the telemetry to protect patient privacy.

Thomas Yopes added 2 commits June 13, 2025 22:25
Ref: ENG-306

Ref: #1040
Signed-off-by: Thomas Yopes <thomasyopes@Thomass-MBP.attlocal.net>
… eng-306-patch

Signed-off-by: Thomas Yopes <thomasyopes@Thomass-MBP.attlocal.net>
@thomasyopes thomasyopes enabled auto-merge June 14, 2025 05:26
@thomasyopes thomasyopes added this pull request to the merge queue Jun 14, 2025
Merged via the queue into develop with commit 2f5fa79 Jun 14, 2025
12 checks passed
@thomasyopes thomasyopes deleted the eng-306-patch branch June 14, 2025 05:28
@coderabbitai coderabbitai bot mentioned this pull request Jul 18, 2025
6 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