Skip to content

Conversation

RamilGaripov
Copy link
Contributor

@RamilGaripov RamilGaripov commented Aug 22, 2025

Issues:

Dependencies

Description

  • Doc downloader lambda to use CW v2 when needed
  • Improved commonwell-sdk layout

Testing

  • N/A. This will be tested in the downstream

Release Plan

  • Merge this

Summary by CodeRabbit

  • New Features
    • Added optional pre- and post-request hooks in the SDK client.
    • Introduced a unified CommonWell base client with transaction ID tracking.
    • Enabled Document Downloader to use CommonWell v1 or v2 at runtime via feature flag.
  • Refactor
    • Consolidated HTTP setup and interceptors by having CommonWell and Member clients extend a shared base.
  • Chores
    • Passed feature flags table to Lambdas with env vars and read access.
    • Upgraded Metriport SDK dependencies.

Part of ENG-513

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

linear bot commented Aug 22, 2025

ENG-513 Update API code

Copy link

coderabbitai bot commented Aug 22, 2025

Walkthrough

Introduces request/response hooks in CommonWellOptions, adds a new CommonWellBase for shared Axios/TLS handling and transaction ID tracking, refactors CommonWell and CommonWellMember to extend the base, updates lambdas to select CommonWell v1 or v2 at runtime via a feature flag, and wires feature flags into Lambda environments.

Changes

Cohort / File(s) Summary
SDK options hooks
packages/commonwell-sdk/src/client/common.ts
Adds optional preRequestHook and postRequestHook to CommonWellOptions; imports Axios types for hook signatures.
SDK base client
packages/commonwell-sdk/src/client/commonwell-base.ts
Adds CommonWellBase class: creates Axios with HTTPS agent, selects base URL by APIMode, applies timeout, interceptors capture x-trace-id; exposes api instance and lastTransactionId getter.
SDK refactor to base: Member
packages/commonwell-sdk/src/client/commonwell-member.ts
Refactors CommonWellMember to extend CommonWellBase; removes its own Axios/agent/interceptors and static URLs; relies on base for HTTP and transaction ID.
SDK refactor to base: Core client
packages/commonwell-sdk/src/client/commonwell.ts
Refactors CommonWell to extend CommonWellBase; removes per-class Axios setup, lastTransactionId, and static URLs; delegates HTTP to base.
Infra: feature flags to Lambdas
packages/infra/lib/lambdas-nested-stack.ts
Passes featureFlagsTable to DocumentDownloader; grants read access; sets FEATURE_FLAGS_TABLE_NAME env in DocumentDownloader and consolidated lambdas.
Lambdas deps bump
packages/lambdas/package.json
Upgrades @metriport/api-sdk to ^18.0.0-alpha.3 and @metriport/commonwell-sdk to 6.0.2-alpha.1.
Document Downloader v1/v2 switch
packages/lambdas/src/document-downloader.ts
Adds runtime branch: chooses CommonWell v1 or v2 via isCommonwellV2EnabledForCx; fetches cert/key and flag in parallel; adapts factories and local runners; makes makeCommonWellAPI internal and v1-typed.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client as Caller
  participant CWBase as CommonWellBase
  participant Axios as Axios Instance
  participant API as CommonWell API

  Client->>CWBase: call api.request(config)
  Note over CWBase: Request interceptor
  CWBase->>Axios: preRequestHook(config)?
  Axios->>API: HTTPS request
  API-->>Axios: Response (headers: x-trace-id)
  Note over CWBase: Response interceptor
  Axios-->>CWBase: Response/Error
  CWBase->>CWBase: Store lastTransactionId from headers
  CWBase-->>Client: Response or throw Error
Loading
sequenceDiagram
  autonumber
  participant Handler as DocumentDownloader Lambda
  participant FF as FeatureFlags (DynamoDB)
  participant Secrets as Cert/Key Store
  participant CWv1 as CommonWell v1
  participant CWv2 as CommonWell v2
  participant RunnerV1 as DocumentDownloaderLocal (v1)
  participant RunnerV2 as DocumentDownloaderLocalV2 (v2)

  Handler->>FF: isCommonwellV2EnabledForCx(cxId)
  par Fetch credentials
    Handler->>Secrets: get cwOrgCertificate
    Handler->>Secrets: get cwOrgPrivateKey
  end
  alt V2 enabled
    Handler->>CWv2: new CommonWell({...}, apiMode)
    Handler->>RunnerV2: run(CWv2.api, query)
    RunnerV2-->>Handler: result
  else V2 disabled
    Handler->>CWv1: new CommonWell({...})
    Handler->>RunnerV1: run(CWv1.api, queryMeta)
    RunnerV1-->>Handler: result
  end
  Handler-->>Handler: return result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch eng-513-cw-v2-migration-2

🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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-513

Signed-off-by: RamilGaripov <ramil@metriport.com>
@RamilGaripov RamilGaripov changed the title fix(lambdas): doc downloader lambda uses CW v2 and v1 ENG-513: doc downloader lambda uses CW v2 and v1 Aug 22, 2025
Part of ENG-513

Signed-off-by: RamilGaripov <ramil@metriport.com>
Part of ENG-513

Signed-off-by: RamilGaripov <ramil@metriport.com>
Part of ENG-513

Signed-off-by: RamilGaripov <ramil@metriport.com>
Part of ENG-513

Signed-off-by: RamilGaripov <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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/commonwell-sdk/src/client/commonwell-member.ts (2)

86-101: Encode all path segments used in URLs (memberId, id, thumbprint, purpose).

Avoid malformed requests and potential path traversal by encoding dynamic segments. Apply this diff:

-      `${CommonWellMember.MEMBER_ENDPOINT}/${this.memberId}/org`,
+      `${CommonWellMember.MEMBER_ENDPOINT}/${encodeURIComponent(this.memberId)}/org`,
@@
-        `${CommonWellMember.MEMBER_ENDPOINT}/${this.memberId}/org/${id}/`,
+        `${CommonWellMember.MEMBER_ENDPOINT}/${encodeURIComponent(this.memberId)}/org/${encodeURIComponent(id)}/`,
@@
-      const resp = await this.api.get(`${CommonWellMember.MEMBER_ENDPOINT}/${this.memberId}/org`, {
+      const resp = await this.api.get(`${CommonWellMember.MEMBER_ENDPOINT}/${encodeURIComponent(this.memberId)}/org`, {
@@
-      `${CommonWellMember.MEMBER_ENDPOINT}/${this.memberId}/org/${id}/`,
+      `${CommonWellMember.MEMBER_ENDPOINT}/${encodeURIComponent(this.memberId)}/org/${encodeURIComponent(id)}/`,
@@
-      `${CommonWellMember.MEMBER_ENDPOINT}/${this.memberId}/org/${id}/certificate`,
+      `${CommonWellMember.MEMBER_ENDPOINT}/${encodeURIComponent(this.memberId)}/org/${encodeURIComponent(id)}/certificate`,
@@
-      `${CommonWellMember.MEMBER_ENDPOINT}/${this.memberId}/org/${id}/certificate`,
+      `${CommonWellMember.MEMBER_ENDPOINT}/${encodeURIComponent(this.memberId)}/org/${encodeURIComponent(id)}/certificate`,
@@
-      `${CommonWellMember.MEMBER_ENDPOINT}/${this.memberId}/org/${id}/certificate/${thumbprint}/purpose/${purpose}`,
+      `${CommonWellMember.MEMBER_ENDPOINT}/${encodeURIComponent(this.memberId)}/org/${encodeURIComponent(id)}/certificate/${encodeURIComponent(thumbprint)}/purpose/${encodeURIComponent(purpose)}`,
@@
-      `${CommonWellMember.MEMBER_ENDPOINT}/${this.memberId}/org/${id}/certificate`,
+      `${CommonWellMember.MEMBER_ENDPOINT}/${encodeURIComponent(this.memberId)}/org/${encodeURIComponent(id)}/certificate`,
@@
-      `${CommonWellMember.MEMBER_ENDPOINT}/${this.memberId}/org/${id}/certificate/${thumbprint}`,
+      `${CommonWellMember.MEMBER_ENDPOINT}/${encodeURIComponent(this.memberId)}/org/${encodeURIComponent(id)}/certificate/${encodeURIComponent(thumbprint)}`,
@@
-      `${CommonWellMember.MEMBER_ENDPOINT}/${this.memberId}/org/${id}/certificate/${thumbprint}/purpose/${purpose}`,
+      `${CommonWellMember.MEMBER_ENDPOINT}/${encodeURIComponent(this.memberId)}/org/${encodeURIComponent(id)}/certificate/${encodeURIComponent(thumbprint)}/purpose/${encodeURIComponent(purpose)}`,

Also applies to: 111-127, 141-160, 171-190, 202-222, 234-254, 267-283, 295-311, 324-341, 353-369


182-186: Don’t rely on http-status “classes”; use a simple range check for 2xx.

Prevents subtle breakage if the library API changes or isn’t present. Safer and clearer.

-    if (httpStatus[`${status}_CLASS`] === httpStatus.classes.SUCCESSFUL) {
+    if (status >= 200 && status < 300) {
       return organizationSchema.parse(resp.data);
     }
🧹 Nitpick comments (7)
packages/lambdas/package.json (1)

35-37: Alpha versions published; optional engine alignment

  • Confirmed @metriport/api-sdk@18.0.0-alpha.3 and @metriport/commonwell-sdk@6.0.2-alpha.1 exist on NPM (npm view returned matching versions).
  • Optional: add an "engines": { "node": ">=18" } field in packages/lambdas/package.json to reflect the AWS Lambda Node.js 18+ runtime.
packages/commonwell-sdk/src/client/common.ts (1)

29-29: Clarify JSDoc wording

“after the request is sent” → “after a response is received”.

-  /** Function to run after the request is sent. */
+  /** Function to run after a response is received. */
packages/lambdas/src/document-downloader.ts (1)

49-53: Remove unsafe type assertions on getSecret()

getSecret() may resolve to string | undefined. You already validate after the await; keep the actual type to avoid masking issues.

-const [cwOrgCertificate, cwOrgPrivateKey, isV2Enabled] = await Promise.all([
-  getSecret(cwOrgCertificateSecret) as Promise<string>,
-  getSecret(cwOrgPrivateKeySecret) as Promise<string>,
-  isCommonwellV2EnabledForCx(cxId),
-]);
+const [cwOrgCertificate, cwOrgPrivateKey, isV2Enabled] = await Promise.all([
+  getSecret(cwOrgCertificateSecret),
+  getSecret(cwOrgPrivateKeySecret),
+  isCommonwellV2EnabledForCx(cxId),
+]);
packages/commonwell-sdk/src/client/commonwell.ts (1)

173-176: Typo in error message

“parametrs” → “parameters”.

-        throw new Error("Programming error, 'id' is required when providing separated parametrs");
+        throw new Error("Programming error, 'id' is required when providing separated parameters");
packages/commonwell-sdk/src/client/commonwell-member.ts (1)

116-118: Endpoint consistency: trailing slashes vary.

Some endpoints include a trailing slash while others don’t. Consider standardizing to avoid accidental 301/308s.

Also applies to: 175-177, 214-216, 246-248, 275-277, 303-305, 332-334, 361-363

packages/commonwell-sdk/src/client/commonwell-base.ts (2)

21-32: JSDoc parameters mention memberName/memberId but constructor doesn’t accept them.

Clean up the docblock to avoid confusion.

-   * @param memberName      The name of the member.
-   * @param memberId        The ID of the member (not the OID).

45-45: Enable HTTP keep-alive on the HTTPS agent.

Improves Lambda performance and reduces TLS handshakes.

-    this.httpsAgent = new Agent({ cert: orgCert, key: rsaPrivateKey });
+    this.httpsAgent = new Agent({ cert: orgCert, key: rsaPrivateKey, keepAlive: true });
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 56cd8a2 and 31e0846.

⛔ Files ignored due to path filters (1)
  • packages/lambdas/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (7)
  • packages/commonwell-sdk/src/client/common.ts (2 hunks)
  • packages/commonwell-sdk/src/client/commonwell-base.ts (1 hunks)
  • packages/commonwell-sdk/src/client/commonwell-member.ts (4 hunks)
  • packages/commonwell-sdk/src/client/commonwell.ts (3 hunks)
  • packages/infra/lib/lambdas-nested-stack.ts (5 hunks)
  • packages/lambdas/package.json (1 hunks)
  • packages/lambdas/src/document-downloader.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursorrules)

**/*.{js,jsx,ts,tsx}: 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 const whenever possible
Use async/await instead of .then()
Naming: classes, enums: PascalCase
Naming: constants, variables, functions: camelCase
Naming: file names: kebab-case
Naming: Don’t use negative names, like notEnabled, prefer isDisabled
If possible, use decomposing objects for function parameters
Prefer Nullish Coalesce (??) than the OR operator (||) when you want 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)
While handling errors, keep the stack trace around: if you create a new Error (e.g., MetriportError), make sure to pass the original error as the new one’s cause so the stack trace is available upstream.
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

Files:

  • packages/commonwell-sdk/src/client/commonwell-base.ts
  • packages/commonwell-sdk/src/client/common.ts
  • packages/infra/lib/lambdas-nested-stack.ts
  • packages/commonwell-sdk/src/client/commonwell-member.ts
  • packages/lambdas/src/document-downloader.ts
  • packages/commonwell-sdk/src/client/commonwell.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursorrules)

Use types whenever possible

Files:

  • packages/commonwell-sdk/src/client/commonwell-base.ts
  • packages/commonwell-sdk/src/client/common.ts
  • packages/infra/lib/lambdas-nested-stack.ts
  • packages/commonwell-sdk/src/client/commonwell-member.ts
  • packages/lambdas/src/document-downloader.ts
  • packages/commonwell-sdk/src/client/commonwell.ts
**/*.ts

⚙️ CodeRabbit configuration file

**/*.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
  • U...

Files:

  • packages/commonwell-sdk/src/client/commonwell-base.ts
  • packages/commonwell-sdk/src/client/common.ts
  • packages/infra/lib/lambdas-nested-stack.ts
  • packages/commonwell-sdk/src/client/commonwell-member.ts
  • packages/lambdas/src/document-downloader.ts
  • packages/commonwell-sdk/src/client/commonwell.ts
🧠 Learnings (14)
📓 Common learnings
Learnt from: RamilGaripov
PR: metriport/metriport#4176
File: packages/fhir-converter/src/lib/handlebars-converter/handlebars-helpers.js:296-320
Timestamp: 2025-07-17T21:24:37.077Z
Learning: RamilGaripov prefers to maintain consistency with existing patterns in a file rather than making isolated fixes to coding guideline violations like var vs const declarations, when the pattern is already established throughout the codebase.
📚 Learning: 2025-03-19T13:58:17.253Z
Learnt from: leite08
PR: metriport/metriport#3463
File: packages/api-sdk/src/medical/models/patient.ts:1-1
Timestamp: 2025-03-19T13:58:17.253Z
Learning: When changes are made to SDK packages (`api-sdk`, `commonwell-sdk`, `carequality-sdk`) or `packages/shared` in the Metriport codebase, alpha versions need to be published to NPM before merging the PR.

Applied to files:

  • packages/lambdas/package.json
📚 Learning: 2025-07-15T19:00:17.445Z
Learnt from: leite08
PR: metriport/metriport#4190
File: packages/shared/package.json:3-3
Timestamp: 2025-07-15T19:00:17.445Z
Learning: The connect-widget package in the Metriport codebase is no longer being updated, so alpha version references in its package.json can be left as-is during release processes.

Applied to files:

  • packages/lambdas/package.json
📚 Learning: 2025-08-13T16:08:03.706Z
Learnt from: RadmirGari
PR: metriport/metriport#4324
File: packages/core/src/domain/address.ts:7-7
Timestamp: 2025-08-13T16:08:03.706Z
Learning: In the Metriport codebase, packages/core legitimately depends on metriport/api-sdk and imports from it in multiple places. This is an established architectural pattern and is properly declared as a dependency in core's package.json.

Applied to files:

  • packages/lambdas/package.json
📚 Learning: 2025-08-20T22:28:47.373Z
Learnt from: leite08
PR: metriport/metriport#0
File: :0-0
Timestamp: 2025-08-20T22:28:47.373Z
Learning: In the Metriport codebase, form-data dependencies with version ">=4.0.4" are intentionally added to package.json files (even when not directly used) to force NPM to use secure versions and address Dependabot security alerts for transitive dependencies.

Applied to files:

  • packages/lambdas/package.json
📚 Learning: 2025-08-20T22:19:04.553Z
Learnt from: leite08
PR: metriport/metriport#0
File: :0-0
Timestamp: 2025-08-20T22:19:04.553Z
Learning: In the Metriport codebase, during CommonWell SDK major version upgrades (like v5 to v6), it's expected and intentional to maintain both versions simultaneously - the new version (metriport/commonwell-sdk) and an aliased v1 version (metriport/commonwell-sdk-v1) for backward compatibility during migration periods.

Applied to files:

  • packages/lambdas/package.json
📚 Learning: 2025-08-25T17:52:19.940Z
Learnt from: RamilGaripov
PR: metriport/metriport#4412
File: packages/commonwell-sdk/src/client/commonwell-member.ts:231-233
Timestamp: 2025-08-25T17:52:19.940Z
Learning: In packages/commonwell-sdk/src/client/commonwell-member.ts, the getOneOrg method currently returns undefined for all non-404 HTTP errors (instead of throwing MetriportError) as a temporary workaround while waiting for the service provider to fix issues on their end. This is tracked in TODO ENG-668 and will be reverted later once the external dependency is resolved.

Applied to files:

  • packages/commonwell-sdk/src/client/commonwell-base.ts
  • packages/commonwell-sdk/src/client/commonwell-member.ts
  • packages/lambdas/src/document-downloader.ts
  • packages/commonwell-sdk/src/client/commonwell.ts
📚 Learning: 2025-08-26T23:48:06.638Z
Learnt from: RadmirGari
PR: metriport/metriport#4448
File: packages/infra/lib/lambdas-nested-stack.ts:1049-1054
Timestamp: 2025-08-26T23:48:06.638Z
Learning: In packages/infra/lib/lambdas-nested-stack.ts, the API_URL environment variable for HL7 roster upload lambdas is correctly set to config.loadBalancerDnsName without needing an explicit https:// scheme prefix. The configuration works as intended.

Applied to files:

  • packages/infra/lib/lambdas-nested-stack.ts
📚 Learning: 2025-08-21T20:18:02.196Z
Learnt from: RamilGaripov
PR: metriport/metriport#4436
File: packages/core/src/command/feature-flags/types.ts:45-46
Timestamp: 2025-08-21T20:18:02.196Z
Learning: In the Metriport feature flags system, new schema keys in packages/core/src/command/feature-flags/types.ts are handled for backward compatibility through the initialFeatureFlags pattern in ffs-on-dynamodb.ts rather than adding schema-level defaults with .default(). This maintains consistency across all feature flag handling.

Applied to files:

  • packages/infra/lib/lambdas-nested-stack.ts
📚 Learning: 2025-04-01T20:57:29.282Z
Learnt from: leite08
PR: metriport/metriport#3550
File: packages/api/src/external/commonwell/__tests__/patient.test.ts:5-5
Timestamp: 2025-04-01T20:57:29.282Z
Learning: PR #3574 is the follow-up PR that moves the domain feature flags from packages/api/src/aws/app-config.ts to packages/core/src/command/feature-flags/domain-ffs.ts.

Applied to files:

  • packages/infra/lib/lambdas-nested-stack.ts
📚 Learning: 2025-05-08T19:41:36.533Z
Learnt from: thomasyopes
PR: metriport/metriport#3788
File: packages/api/src/external/ehr/shared/utils/bundle.ts:83-93
Timestamp: 2025-05-08T19:41:36.533Z
Learning: In the Metriport codebase, the team prefers to let errors bubble up naturally in some cases rather than adding explicit error handling at every layer, as demonstrated in the refreshEhrBundle function in the bundle.ts file.

Applied to files:

  • packages/commonwell-sdk/src/client/commonwell-member.ts
📚 Learning: 2025-05-27T16:10:48.223Z
Learnt from: lucasdellabella
PR: metriport/metriport#3866
File: packages/core/src/command/hl7v2-subscriptions/hl7v2-roster-generator.ts:142-151
Timestamp: 2025-05-27T16:10:48.223Z
Learning: In packages/core/src/command/hl7v2-subscriptions/hl7v2-roster-generator.ts, the user prefers to let axios errors bubble up naturally rather than adding try-catch blocks that re-throw with MetriportError wrappers, especially when the calling code already has retry mechanisms in place via simpleExecuteWithRetries.

Applied to files:

  • packages/commonwell-sdk/src/client/commonwell.ts
📚 Learning: 2025-06-18T21:05:22.256Z
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.

Applied to files:

  • packages/commonwell-sdk/src/client/commonwell.ts
📚 Learning: 2025-08-25T17:52:19.445Z
Learnt from: RamilGaripov
PR: metriport/metriport#4412
File: packages/api/src/external/commonwell-v2/command/organization/organization.ts:89-98
Timestamp: 2025-08-25T17:52:19.445Z
Learning: In packages/api/src/external/commonwell-v2/command/organization/organization.ts, when setting organizationId, homeCommunityId, and patientIdAssignAuthority fields for CommonWell v2 SDK, raw OID values (org.oid) can be used directly without the "urn:oid:" prefix - the SDK handles any necessary formatting internally.

Applied to files:

  • packages/commonwell-sdk/src/client/commonwell.ts
🧬 Code graph analysis (4)
packages/commonwell-sdk/src/client/commonwell-base.ts (1)
packages/commonwell-sdk/src/client/common.ts (2)
  • CommonWellOptions (21-30)
  • DEFAULT_AXIOS_TIMEOUT_SECONDS (4-4)
packages/commonwell-sdk/src/client/commonwell-member.ts (3)
packages/commonwell-sdk/src/index.ts (2)
  • CommonWellMember (4-4)
  • CommonWellMemberAPI (5-5)
packages/commonwell-sdk/src/client/commonwell-base.ts (1)
  • CommonWellBase (12-97)
packages/commonwell-sdk/src/client/commonwell-member-api.ts (1)
  • CommonWellMemberAPI (11-57)
packages/lambdas/src/document-downloader.ts (3)
packages/core/src/command/feature-flags/domain-ffs.ts (1)
  • isCommonwellV2EnabledForCx (323-326)
packages/core/src/external/commonwell-v1/document/document-downloader-local.ts (1)
  • DocumentDownloaderLocal (36-320)
packages/core/src/external/commonwell-v2/document/document-downloader-local-v2.ts (1)
  • DocumentDownloaderLocalV2 (30-329)
packages/commonwell-sdk/src/client/commonwell.ts (2)
packages/commonwell-sdk/src/client/commonwell-base.ts (1)
  • CommonWellBase (12-97)
packages/commonwell-sdk/src/client/commonwell-api.ts (1)
  • CommonWellAPI (76-134)
🔇 Additional comments (5)
packages/infra/lib/lambdas-nested-stack.ts (1)

150-151: Feature flags wiring for DocumentDownloader looks correct

Env var FEATURE_FLAGS_TABLE_NAME is set and read permissions are granted to the lambda. This matches the runtime use of isCommonwellV2EnabledForCx.

Also applies to: 406-407, 418-418, 435-436, 458-459

packages/lambdas/src/document-downloader.ts (2)

62-86: V1 fallback path looks sound

Query meta creation and downloader wiring match existing behavior. No issues spotted.


112-121: Local helper visibility change is fine

Making makeCommonWellAPI non-exported and returning the v1 interface keeps the public surface minimal.

packages/commonwell-sdk/src/client/commonwell.ts (1)

91-103: HTTP base refactor and 500-retry handling look correct

Delegation to CommonWellBase and conditional retries on 500s are implemented cleanly.

Also applies to: 551-562

packages/commonwell-sdk/src/client/commonwell-member.ts (1)

187-189: Confirm temporary ENG-668 behavior is still desired.

getOneOrg returns undefined for any non-404 non-2xx. If the upstream has stabilized, consider reverting to throwing a MetriportError.

Would you like me to open a follow-up to flip this once ENG-668 is resolved?

Comment on lines +26 to +29
/** Function to run before the request is sent. */
preRequestHook?: (request: InternalAxiosRequestConfig) => void;
/** Function to run after the request is sent. */
postRequestHook?: (response: AxiosResponse) => void;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

postRequestHook is defined but not invoked anywhere

postRequestHook is never called by the HTTP client (see CommonWellBase). Either wire it into the response interceptors or drop it to avoid dead config.

Suggested change in CommonWellBase (outside this file) to invoke the hook on both success and error:

-    this.api.interceptors.response.use(
-      this.axiosSuccessfulResponse(this),
-      this.axiosErrorResponse(this)
-    );
+    this.api.interceptors.response.use(
+      this.axiosSuccessfulResponse(this, options.postRequestHook),
+      this.axiosErrorResponse(this, options.postRequestHook)
+    );
@@
-  private axiosSuccessfulResponse(_this: CommonWellBase) {
-    return (response: AxiosResponse): AxiosResponse => {
+  private axiosSuccessfulResponse(
+    _this: CommonWellBase,
+    postRequestHook?: CommonWellOptions["postRequestHook"]
+  ) {
+    return (response: AxiosResponse): AxiosResponse => {
       _this && _this.postRequest(response);
+      postRequestHook?.(response);
       return response;
     };
   }
-  private axiosErrorResponse(_this: CommonWellBase) {
+  private axiosErrorResponse(
+    _this: CommonWellBase,
+    postRequestHook?: CommonWellOptions["postRequestHook"]
+  ) {
     //eslint-disable-next-line @typescript-eslint/no-explicit-any
-    return (error: any): AxiosResponse => {
+    return (error: any): AxiosResponse => {
       _this && _this.postRequest(error.response);
+      if (error?.response) postRequestHook?.(error.response);
       throw error;
     };
   }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In packages/commonwell-sdk/src/client/common.ts around lines 26 to 29,
postRequestHook is declared but never invoked by the HTTP client; modify the
HTTP client (CommonWellBase) to call postRequestHook with the AxiosResponse on
successful responses and also call it (with the error response if available) in
the response error handler so the hook runs for both success and failure; ensure
you check for hook existence before calling and preserve existing error
propagation (rethrow) after invoking the hook.

Comment on lines +54 to +59
options.preRequestHook &&
this.api.interceptors.request.use(this.axiosPreRequest(this, options.preRequestHook));
this.api.interceptors.response.use(
this.axiosSuccessfulResponse(this),
this.axiosErrorResponse(this)
);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Wire postRequestHook and fix error interceptor return type.

Currently postRequestHook is unused, and the error interceptor declares an incorrect return type. Use the hook on both success/error paths and Promise.reject for errors.

-    options.preRequestHook &&
-      this.api.interceptors.request.use(this.axiosPreRequest(this, options.preRequestHook));
-    this.api.interceptors.response.use(
-      this.axiosSuccessfulResponse(this),
-      this.axiosErrorResponse(this)
-    );
+    if (options.preRequestHook) {
+      this.api.interceptors.request.use(this.axiosPreRequest(this, options.preRequestHook));
+    }
+    this.api.interceptors.response.use(
+      this.axiosSuccessfulResponse(this, options.postRequestHook),
+      this.axiosErrorResponse(this, options.postRequestHook)
+    );
@@
-  private axiosSuccessfulResponse(_this: CommonWellBase) {
-    return (response: AxiosResponse): AxiosResponse => {
-      _this && _this.postRequest(response);
-      return response;
-    };
-  }
-  private axiosErrorResponse(_this: CommonWellBase) {
-    //eslint-disable-next-line @typescript-eslint/no-explicit-any
-    return (error: any): AxiosResponse => {
-      _this && _this.postRequest(error.response);
-      throw error;
-    };
-  }
+  private axiosSuccessfulResponse(
+    _this: CommonWellBase,
+    postRequestHook?: CommonWellOptions["postRequestHook"]
+  ) {
+    return (response: AxiosResponse): AxiosResponse => {
+      if (_this) _this.postRequest(response);
+      postRequestHook?.(response);
+      return response;
+    };
+  }
+  private axiosErrorResponse(
+    _this: CommonWellBase,
+    postRequestHook?: CommonWellOptions["postRequestHook"]
+  ) {
+    //eslint-disable-next-line @typescript-eslint/no-explicit-any
+    return (error: any) => {
+      const resp = error?.response as AxiosResponse | undefined;
+      if (_this && resp) _this.postRequest(resp);
+      if (resp) postRequestHook?.(resp);
+      return Promise.reject(error);
+    };
+  }

Also applies to: 84-96

🤖 Prompt for AI Agents
In packages/commonwell-sdk/src/client/commonwell-base.ts around lines 54-59 (and
also apply same change to lines 84-96), the postRequestHook is never called and
the error interceptor returns the wrong type; update the response interceptors
so both the success and error handlers invoke options.postRequestHook (if
provided) with the request/response context, and change the error handler to
return Promise.reject(error) instead of returning the error value; ensure you
pass the instance/context and the response or error to the hook and that the
error path re-throws via Promise.reject to preserve the rejected promise chain.

Comment on lines +88 to 98
// V2
const commonWell = new CommonWell({
orgCert: cwOrgCertificateSecret,
rsaPrivateKey: cwOrgPrivateKeySecret,
orgName,
addOidPrefix(orgOid)
);
const queryMeta = organizationQueryMeta(orgName, { npi: npi });
oid: orgOid,
homeCommunityId: orgOid,
npi,
apiMode,
});

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

V2 path passes secret ARNs instead of secret values; also missing client timeout

You fetched the cert/key values into cwOrgCertificate/cwOrgPrivateKey, but the V2 constructor uses the env names/ARNs. Also, V1 sets a 4‑minute Axios timeout; V2 falls back to the 120s default. Pass the resolved secrets and align the timeout.

-  const commonWell = new CommonWell({
-    orgCert: cwOrgCertificateSecret,
-    rsaPrivateKey: cwOrgPrivateKeySecret,
+  const commonWell = new CommonWell({
+    orgCert: cwOrgCertificate,
+    rsaPrivateKey: cwOrgPrivateKey,
     orgName,
     oid: orgOid,
     homeCommunityId: orgOid,
     npi,
     apiMode,
+    options: { timeout: timeout.asMilliseconds() },
   });
@@
-  const docDownloader = new DocumentDownloaderLocalV2({
+  const docDownloader = new DocumentDownloaderLocalV2({
     region,
     bucketName,
     commonWell: { api: commonWell },
     capture,
   });

Also applies to: 99-104

Base automatically changed from eng-513-cw-v2-migration-1 to develop August 29, 2025 19:42
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