Skip to content

Conversation

RamilGaripov
Copy link
Contributor

@RamilGaripov RamilGaripov commented Aug 21, 2025

Ref eng-513

[Release PRs:]

Issues:

Dependencies

Description

  • Added FFs to for CW v2
  • Added some tests for onError
  • Removed public organization routes

Testing

  • N/A

Release Plan

  • Merge this

Summary by CodeRabbit

  • New Features
    • Introduced a new feature flag to control access for select customers.
    • Enhanced retry utility with an optional on-error callback for better observability.
  • Refactor
    • Removed the deprecated Organization endpoint from the public medical API; other medical endpoints are unchanged.
  • Tests
    • Expanded test coverage for retry behavior, validating on-error handling across failure and success scenarios.
  • Chores
    • Updated feature flag schemas and defaults to include the new control.

Ref eng-513

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

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

linear bot commented Aug 21, 2025

ENG-513 Update API code

Copy link

coderabbitai bot commented Aug 21, 2025

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-migration-to-cw-v2

🪧 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 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.

Ref eng-513

Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.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: 2

🧹 Nitpick comments (10)
packages/shared/src/common/__tests__/retry.test.ts (2)

167-187: Order-sensitive verification suggestion.

Consider adding a test to ensure onError executes before shouldRetry (this is part of the documented contract), which would guard against future regressions.

Apply this diff to add the test:

@@
     describe("onError", () => {
+      it("calls onError before shouldRetry", async () => {
+        const order: string[] = [];
+        const onError = jest.fn(() => order.push("onError"));
+        const shouldRetry = jest.fn((_r: unknown, _e: unknown) => {
+          order.push("shouldRetry");
+          return false;
+        });
+        const error = new Error("test error");
+        fn.mockImplementation(() => {
+          throw error;
+        });
+        await expect(async () =>
+          executeWithRetries(fn, {
+            initialDelay: 1,
+            maxAttempts: 1,
+            onError,
+            shouldRetry,
+          })
+        ).rejects.toThrow();
+        expect(order).toEqual(["onError", "shouldRetry"]);
+      });

119-188: Add resilience test if we decide to make onError non-fatal.

If we adopt the production change to isolate onError exceptions (see comment in retry.ts), add this test to prevent regressions. It will fail until the production change is made.

Apply this diff to add the test:

@@
     describe("onError", () => {
+      it("still retries and surfaces the original error even if onError throws", async () => {
+        const original = new Error("original");
+        const onError = jest.fn(() => {
+          throw new Error("onError failed");
+        });
+        fn.mockImplementation(() => {
+          throw original;
+        });
+        await expect(async () =>
+          executeWithRetries(fn, {
+            initialDelay: 1,
+            maxAttempts: 2,
+            onError,
+          })
+        ).rejects.toThrow(original);
+        expect(onError).toHaveBeenCalledTimes(2);
+      });
packages/shared/src/common/retry.ts (3)

42-47: Clarify the onError contract; ensure it cannot affect outcomes.

The comment promises that onError “doesn't change” outcomes. To uphold this contract even if a caller’s callback throws, either: (a) explicitly document that onError must not throw, or (b) make the implementation resilient (preferred; see next comment). If sticking with documentation-only, tighten the wording.

Apply this diff to clarify the doc:

   /**
-   * Function to be called when an error occurs. It doesn't change whether shouldRetry is called
-   * or not, nor does it change the result of that function.
-   * It's called before shouldRetry.
+   * Callback invoked on each caught error, before `shouldRetry`.
+   * It must be side-effect-only; its own failure MUST NOT influence retry decisions or the final
+   * outcome. The implementation ignores any exception raised by this callback.
    */

117-117: Make onError non-fatal to preserve retry semantics if the callback throws.

Right now, if a user-supplied onError throws, it aborts the retry flow and violates the stated contract. Wrap it defensively and log.

Apply this diff:

-      onError?.(error);
+      try {
+        onError?.(error);
+      } catch (onErrorErr) {
+        // Ensure callback failures do not affect retry flow.
+        log(`[${context}] onError handler threw: ${errorToString(onErrorErr)}`);
+      }

90-93: Optional: expose attempt to onError for richer diagnostics.

Consider evolving the signature to onError?: (error: unknown, attempt: number) => void. This provides context without requiring consumers to track state externally. Would be a minor breaking change; consider a follow-up with deprecation path.

packages/core/src/command/feature-flags/types.ts (1)

45-45: Nit: align flag name with prevailing “cxsWith…Enabled” pattern

Most CX-scoped flags here read as “cxsWithXEnabled” (e.g., cxsWithEpicEnabled, cxsWithDemoAugEnabled). Consider renaming to improve consistency and grep-ability:

Apply within this file:

-  cxsEnabledForCommonwellV2: ffStringValuesSchema,
+  cxsWithCommonwellV2Enabled: ffStringValuesSchema,

And propagate the same key rename to:

  • packages/core/src/command/feature-flags/ffs-on-dynamodb.ts (initialFeatureFlags)
  • packages/core/src/command/feature-flags/domain-ffs.ts (string key used by getCxsWithFeatureFlagEnabled)

I can provide a full repo-safe rename plan if you want.

packages/core/src/command/feature-flags/ffs-on-dynamodb.ts (1)

68-69: Nit (only if you adopt the naming tweak in types.ts)

If you choose to rename to cxsWithCommonwellV2Enabled, mirror it here:

-  cxsEnabledForCommonwellV2: { enabled: false, values: [] },
+  cxsWithCommonwellV2Enabled: { enabled: false, values: [] },
packages/core/src/command/feature-flags/domain-ffs.ts (3)

306-309: Use includes for brevity and consistency

Elsewhere in this file (e.g., Lines 115–118) we use includes. Align here for consistency.

 export async function isQuestFeatureFlagEnabledForCx(cxId: string): Promise<boolean> {
   const cxIdsWithQuestEnabled = await getCxsWithQuestFeatureFlag();
-  return cxIdsWithQuestEnabled.some(i => i === cxId);
+  return cxIdsWithQuestEnabled.includes(cxId);
 }

315-317: Also prefer includes here

Minor readability/style tweak to match other helpers that already use includes.

 export async function isCommonwellV2EnabledForCx(cxId: string): Promise<boolean> {
   const cxIdsWithCommonwellV2Enabled = await getCxsEnabledForCommonwellV2();
-  return cxIdsWithCommonwellV2Enabled.some(i => i === cxId);
+  return cxIdsWithCommonwellV2Enabled.includes(cxId);
 }

311-318: Optional: align helper/key naming with “With…Enabled” convention

If you accept the schema key rename suggestion, consider aligning these names for consistency:

-export async function getCxsEnabledForCommonwellV2(): Promise<string[]> {
-  return getCxsWithFeatureFlagEnabled("cxsEnabledForCommonwellV2");
-}
+export async function getCxsWithCommonwellV2Enabled(): Promise<string[]> {
+  return getCxsWithFeatureFlagEnabled("cxsWithCommonwellV2Enabled");
+}

-export async function isCommonwellV2EnabledForCx(cxId: string): Promise<boolean> {
-  const cxIdsWithCommonwellV2Enabled = await getCxsEnabledForCommonwellV2();
+export async function isCommonwellV2EnabledForCx(cxId: string): Promise<boolean> {
+  const cxIdsWithCommonwellV2Enabled = await getCxsWithCommonwellV2Enabled();
   return cxIdsWithCommonwellV2Enabled.includes(cxId);
 }

I can generate a repo-wide rename script to keep everything in sync if desired.

📜 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 ace3b09 and da3ade1.

📒 Files selected for processing (7)
  • packages/api/src/routes/medical/index.ts (0 hunks)
  • packages/api/src/routes/medical/organization.ts (0 hunks)
  • packages/core/src/command/feature-flags/domain-ffs.ts (1 hunks)
  • packages/core/src/command/feature-flags/ffs-on-dynamodb.ts (1 hunks)
  • packages/core/src/command/feature-flags/types.ts (1 hunks)
  • packages/shared/src/common/__tests__/retry.test.ts (1 hunks)
  • packages/shared/src/common/retry.ts (5 hunks)
💤 Files with no reviewable changes (2)
  • packages/api/src/routes/medical/index.ts
  • packages/api/src/routes/medical/organization.ts
🧰 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/shared/src/common/__tests__/retry.test.ts
  • packages/core/src/command/feature-flags/ffs-on-dynamodb.ts
  • packages/core/src/command/feature-flags/domain-ffs.ts
  • packages/core/src/command/feature-flags/types.ts
  • packages/shared/src/common/retry.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursorrules)

Use types whenever possible

Files:

  • packages/shared/src/common/__tests__/retry.test.ts
  • packages/core/src/command/feature-flags/ffs-on-dynamodb.ts
  • packages/core/src/command/feature-flags/domain-ffs.ts
  • packages/core/src/command/feature-flags/types.ts
  • packages/shared/src/common/retry.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/shared/src/common/__tests__/retry.test.ts
  • packages/core/src/command/feature-flags/ffs-on-dynamodb.ts
  • packages/core/src/command/feature-flags/domain-ffs.ts
  • packages/core/src/command/feature-flags/types.ts
  • packages/shared/src/common/retry.ts
🧠 Learnings (4)
📓 Common learnings
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.
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-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/core/src/command/feature-flags/ffs-on-dynamodb.ts
  • packages/core/src/command/feature-flags/domain-ffs.ts
  • packages/core/src/command/feature-flags/types.ts
📚 Learning: 2025-04-01T19:59:22.396Z
Learnt from: leite08
PR: metriport/metriport#3550
File: packages/api/src/external/commonwell/__tests__/patient.test.ts:5-5
Timestamp: 2025-04-01T19:59:22.396Z
Learning: The file at `packages/api/src/aws/app-config.ts` contains domain feature flags (not AWS AppConfig specific functionality) and is planned to be moved to the domain folder in packages/core in a future PR.

Applied to files:

  • packages/core/src/command/feature-flags/ffs-on-dynamodb.ts
  • packages/core/src/command/feature-flags/domain-ffs.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 app-config.ts to the domain folder in packages/core.

Applied to files:

  • packages/core/src/command/feature-flags/domain-ffs.ts
🧬 Code graph analysis (1)
packages/shared/src/common/__tests__/retry.test.ts (1)
packages/shared/src/common/retry.ts (1)
  • executeWithRetries (79-143)
🔇 Additional comments (9)
packages/shared/src/common/__tests__/retry.test.ts (3)

119-134: Good coverage: validates baseline without onError provided.

This confirms the core retry behavior remains unchanged when no callback is supplied. No changes needed.


136-153: Strong behavioral check: onError is invoked on every failure.

The assertions correctly verify call count and payload for each attempt. Nice.


155-165: Positive-path assertion is appropriate.

Verifies that a successful first attempt avoids onError invocation. Looks good.

packages/shared/src/common/retry.ts (2)

18-21: Sane default for onError.

Defaulting to emptyFunction avoids undefined checks at call sites and keeps behavior predictable when users omit the callback.


4-4: emptyFunction export verified

  • packages/shared/src/common/general.ts exports emptyFunction (line 4).
  • packages/shared/src/index.ts re-exports emptyFunction (line 7).
  • No circular import from general.ts back into retry.ts detected.

No further action required.

packages/core/src/command/feature-flags/types.ts (1)

45-46: CW v2 FF added to schema — LGTM

The new entry cxsEnabledForCommonwellV2 correctly uses ffStringValuesSchema and will flow into StringValueFeatureFlags via the merge. Matches the usage introduced in domain helpers.

packages/core/src/command/feature-flags/ffs-on-dynamodb.ts (2)

68-69: Initial FF entry added — default-off with empty values is correct

The addition of cxsEnabledForCommonwellV2: { enabled: false, values: [] } is consistent with other CX-scoped flags and safe for rollout.


68-69: Verify feature flag integration & test coverage

  • The new flag key cxsEnabledForCommonwellV2 is correctly referenced in:
    • packages/core/src/command/feature-flags/types.ts (schema definition)
    • packages/core/src/command/feature-flags/ffs-on-dynamodb.ts (DynamoDB defaults)
    • packages/core/src/command/feature-flags/domain-ffs.ts (helpers getCxsEnabledForCommonwellV2 & isCommonwellV2EnabledForCx)
  • No existing test files mention or exercise these new helper functions. Consider adding unit tests for:
    • getCxsEnabledForCommonwellV2
    • isCommonwellV2EnabledForCx
  • Manually verify that the FF admin UI and any export endpoints surface the cxsEnabledForCommonwellV2 key as expected.
packages/core/src/command/feature-flags/domain-ffs.ts (1)

311-318: CW v2 domain helpers — LGTM

Both helpers follow the established pattern (thin wrappers on getCxsWithFeatureFlagEnabled). Types line up with the schema change and the initial FF entry.

@@ -115,6 +115,77 @@ describe("retry", () => {
})
);
});

describe("onError", () => {
Copy link
Member

Choose a reason for hiding this comment

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

😍

@RamilGaripov RamilGaripov added this pull request to the merge queue Aug 21, 2025
Merged via the queue into develop with commit 2876cc1 Aug 21, 2025
20 checks passed
@RamilGaripov RamilGaripov deleted the eng-513-migration-to-cw-v2 branch August 21, 2025 17:24
@coderabbitai coderabbitai bot mentioned this pull request Aug 22, 2025
1 task
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