-
Notifications
You must be signed in to change notification settings - Fork 71
feat(core): add FF to enable cxs to CW v2 #4434
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
Conversation
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>
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 unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
Ref eng-513 Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
There was a problem hiding this 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” patternMost 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
: Useincludes
for brevity and consistencyElsewhere 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 preferincludes
hereMinor 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” conventionIf 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.
📒 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
Useconst
whenever possible
Useasync/await
instead of.then()
Naming: classes, enums: PascalCase
Naming: constants, variables, functions: camelCase
Naming: file names: kebab-case
Naming: Don’t use negative names, likenotEnabled
, preferisDisabled
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 ofin
- i.e.,if (data.link)
notif ('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
, preferisDisabled
- For numeric values, if the type doesn’t convey the unit, add the unit to the name
- Typescript
- Use types
- Prefer
const
instead oflet
- Avoid
any
and casting fromany
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 toundefined
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 (seeprocessAsyncError
andemptyFunction
depending on the case)- Date and Time
- Always use
buildDayjs()
to createdayjs
instances- Prefer
dayjs.duration(...)
to create duration consts and keep them asduration
- 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 intoretry.ts
detected.No further action required.
packages/core/src/command/feature-flags/types.ts (1)
45-46
: CW v2 FF added to schema — LGTMThe new entry
cxsEnabledForCommonwellV2
correctly usesffStringValuesSchema
and will flow intoStringValueFeatureFlags
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 correctThe 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
(helpersgetCxsEnabledForCommonwellV2
&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 — LGTMBoth 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", () => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
😍
Ref eng-513
[Release PRs:]
Issues:
Dependencies
Description
onError
Testing
Release Plan
Summary by CodeRabbit