10000 ENG-191 Only load the bundle when converting by leite08 · Pull Request #3692 · metriport/metriport · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

ENG-191 Only load the bundle when converting #3692

New issu 8000 e

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

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

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 5, 2025

Conversation

leite08
Copy link
Member
@leite08 leite08 commented Apr 21, 2025

Dependencies

none

Description

Only load the bundle upon recreate consolidated when converting (creating a MR).

Testing

  • Local
    • none
  • Staging
    • trigger DQ, consolidated gets updated at the end
    • trigger DQ, ask for MR in PDF, it gets generated
  • Sandbox
    • none
  • Production
    • none

Release Plan

  • Merge this

Summary by CodeRabbit

  • New Features
    • Added telemetry reporting for consolidated query processing to enhance analytics.
    • Introduced support for request-specific tracking in patient consolidation queries.
  • Bug Fixes
    • Improved the reliability of patient consolidation retrieval, ensuring correct handling when no conversion type is specified.
  • Chores
    • Removed obsolete analytics tracking and parameters from consolidation retrieval to streamline processing.

< 8000 div class="ml-n3 timeline-comment unminimized-comment comment previewable-edit js-task-list-container js-comment timeline-comment--caret" data-body-version="e77793910c803f44a030d9a6359ffd1ee9611797f3a4d1c8341e33c82ff058d0">
Copy link
linear bot commented Apr 21, 2025

Copy link
coderabbitai bot commented Apr 21, 2025

Walkthrough

The function recreateConsolidated in the patient consolidation module was updated to introduce conditional logic for retrieving consolidated data. Now, if a conversionType parameter is provided, the function proceeds as before by calling getConsolidated. If conversionType is not provided, it instead constructs a payload and uses a connector built by buildConsolidatedSnapshotConnector to execute the consolidation retrieval synchronously. The function's signature remains unchanged, and existing error handling and logging are preserved.

The getConsolidated function was updated to include an optional requestId parameter, which is propagated through its callers and included in payloads sent to connectors and downstream functions. Analytics tracking and elapsed time measurement code were removed from getConsolidated.

Telemetry reporting was added to the handleBundleToMedicalRecord function by introducing an optional requestId parameter and emitting an analytics event after bundle construction, reporting consolidated query metrics including elapsed time and resource count.

In the local snapshot retrieval command, analytics imports and usage were added. The code was refactored to extract patient and requestId from parameters, replaced direct references to normalizedBundle with resultBundle, adjusted S3 upload result handling, and emitted an analytics event after processing, reporting consolidated query details.

A new function getConsolidatedQueryByRequestId was added to the patient domain module to retrieve a consolidated query by requestId from a patient's data.

Changes

File(s) Change Summary
packages/api/src/command/medical/patient/consolidated-recreate.ts Modified recreateConsolidated to conditionally choose between getConsolidated and connector-based retrieval, depending on the presence of conversionType.
packages/api/src/command/medical/patient/consolidated-get.ts Added optional requestId parameter to GetConsolidatedPatientData type and getConsolidatedPatientData function; passed requestId through calls; removed analytics tracking and elapsed time measurement.
packages/api/src/command/medical/patient/convert-fhir-bundle.ts Added optional requestId parameter to handleBundleToMedicalRecord; added telemetry reporting via analytics event after bundle construction.
packages/core/src/command/consolidated/get-snapshot-local.ts Added imports for analytics and getConsolidatedQueryByRequestId; extracted patient and requestId from params; replaced normalizedBundle with resultBundle; adjusted S3 upload result handling; emitted analytics event after processing with consolidated query metrics.
packages/core/src/domain/patient.ts Added exported function getConsolidatedQueryByRequestId to retrieve a consolidated query by requestId from a patient's data.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant recreateConsolidated
    participant getConsolidated
    participant Connector

    Caller->>recreateConsolidated: Call with patient, conversionType?
    alt conversionType is provided
        recreateConsolidated->>getConsolidated: getConsolidated(patient, conversionType, requestId?)
        getConsolidated-->>recreateConsolidated: Return result
    else conversionType is not provided
        recreateConsolidated->>Connector: buildConsolidatedSnapshotConnector()
        recreateConsolidated->>Connector: execute(payload with patient, isAsync: false)
        Connector-->>recreateConsolidated: Return result
    end
    recreateConsolidated-->>Caller: Return consolidated data or error
Loading

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 78bf361 and 65acf46.

📒 Files selected for processing (5)
  • packages/api/src/command/medical/patient/consolidated-get.ts (5 hunks)
  • packages/api/src/command/medical/patient/consolidated-recreate.ts (2 hunks)
  • packages/api/src/command/medical/patient/convert-fhir-bundle.ts (3 hunks)
  • packages/core/src/command/consolidated/get-snapshot-local.ts (7 hunks)
  • packages/core/src/domain/patient.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • packages/core/src/domain/patient.ts
  • packages/api/src/command/medical/patient/convert-fhir-bundle.ts
  • packages/api/src/command/medical/patient/consolidated-recreate.ts
  • packages/api/src/command/medical/patient/consolidated-get.ts
  • packages/core/src/command/consolidated/get-snapshot-local.ts

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate 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.

@leite08 leite08 marked this pull request as ready for review April 21, 2025 15:56
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: 0

🧹 Nitpick comments (1)
packages/api/src/command/medical/patient/consolidated-recreate.ts (1)

39-48: Conditional handling aligns with PR objective.

This change ensures the bundle is only loaded when necessary during conversion by implementing two distinct paths:

  1. When conversionType is provided - use getConsolidated as before
  2. When conversionType is absent - create a sync request via the snapshot connector

The implementation follows the functional programming style recommended in the coding guidelines and maintains proper error handling.

However, consider updating the error message on line 50 to be more generic since it references "Post-DQ getConsolidated" which only directly applies to the first branch.

-    processAsyncError(`Post-DQ getConsolidated`, log)(err);
+    processAsyncError(`Failed to retrieve consolidated data`, log)(err);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0c06f4d and bfad4a5.

📒 Files selected for processing (2)
  • commitlint.config.js (1 hunks)
  • packages/api/src/command/medical/patient/consolidated-recreate.ts (2 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/api/src/command/medical/patient/consolidated-recreate.ts
🧬 Code Graph Analysis (1)
packages/api/src/command/medical/patient/consolidated-recreate.ts (1)
packages/core/src/command/consolidated/consolidated-get.ts (1)
  • getConsolidated (22-40)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
commitlint.config.js (1)

16-16: Adding the period variant for consistency is sensible.

This addition allows for more flexibility in commit message formatting while maintaining semantic meaning. It accommodates both "Ref ENG-" and "Ref. ENG-" formats, making the configuration more robust.

packages/api/src/command/medical/patient/consolidated-recreate.ts (1)

3-4: New imports support conditional bundle loading functionality.

These imports enable the implementation of the alternative path for retrieving consolidation when no conversion type is specified.

@leite08 leite08 force-pushed the eng-141-recreate-consolidate-doesnt-load-bundle branch 2 times, most recently from 62ac756 to 082d50e Compare April 28, 2025 14:29
Copy link
linear bot commented Apr 30, 2025

@leite08 leite08 force-pushed the eng-141-recreate-consolidate-doesnt-load-bundle branch 2 times, most recently from ae0ee26 to 8764dee Compare April 30, 2025 19:22
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: 0

🧹 Nitpick comments (1)
packages/core/src/command/consolidated/get-snapshot-local.ts (1)

64-64: Consider removing this variable assignment

Adding resultBundle as an alias for normalizedBundle doesn't add much clarity since it's just a direct assignment. Consider using normalizedBundle consistently instead to reduce cognitive load.

-    const resultBundle = normalizedBundle;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8764dee and 980be4f.

📒 Files selected for processing (3)
  • packages/api/src/command/medical/patient/consolidated-get 10000 .ts (1 hunks)
  • packages/api/src/command/medical/patient/convert-fhir-bundle.ts (2 hunks)
  • packages/core/src/command/consolidated/get-snapshot-local.ts (6 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/api/src/command/medical/patient/convert-fhir-bundle.ts
  • packages/core/src/command/consolidated/get-snapshot-local.ts
  • packages/api/src/command/medical/patient/consolidated-get.ts
🧬 Code Graph Analysis (1)
packages/core/src/command/consolidated/get-snapshot-local.ts (1)
packages/core/src/external/analytics/posthog.ts (1)
  • analytics (23-39)
🔇 Additional comments (7)
packages/api/src/command/medical/patient/convert-fhir-bundle.ts (2)

14-14: LGTM: Added analytics import

The import of analytics and EventTypes is correctly placed and follows the import order convention.


85-93: Well-placed analytics tracking for telemetry

Good addition of analytics tracking after bundle processing is complete. This provides valuable telemetry about consolidated queries with appropriate context (patientId, conversionType, and resource count).

The analytics event is triggered at an appropriate point in the execution flow, after the bundle has been fully processed and we know its final state. This aligns with the PR objective of optimizing bundle handling during conversion.

packages/core/src/command/consolidated/get-snapshot-local.ts (4)

11-11: LGTM: Added analytics import

The import of analytics and EventTypes is correctly placed and follows the project conventions.


67-67: Consistent use of resultBundle variable

The usage of resultBundle is consistent throughout the file, replacing previous references to normalizedBundle. This change is connected to the introduction of the resultBundle variable.

Also applies to: 78-78, 103-103


87-87: Fixed bundle reference in Promise.all result

This change correctly captures the third upload result as resultS3Info (instead of the second as dedupedS3Info), fixing a potential bug in the original code. The correct S3 info is now used for the bundle location and filename.

Also applies to: 108-108


126-135: Well-placed analytics tracking for consolidated operations

Good addition of analytics tracking after successful bundle processing. This provides valuable telemetry with appropriate context (patientId, conversion type as "bundle", and resource count).

This change complements the analytics tracking added in the convert-fhir-bundle.ts file, ensuring comprehensive telemetry for both bundle processing and conversion operations.

packages/api/src/command/medical/patient/consolidated-get.ts (1)

256-261: Simplified data retrieval flow

The function now always fetches a fresh bundle using getConsolidatedPatientData instead of conditionally using a passed-in bundle. This simplification aligns with the PR's objective of only loading bundles when converting.

This change:

  1. Makes the code more consistent and easier to maintain
  2. Supports the optimization of bundle handling during MR creation
  3. Works well with the analytics tracking moved to more appropriate places in the processing flow

leite08 added 2 commits April 30, 2025 19:02
Ref eng-141

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

Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
@leite08 leite08 force-pushed the eng-141-recreate-consolidate-doesnt-load-bundle branch from 980be4f to 4f84264 Compare April 30, 2025 22:03
Comment on lines -273 to -288
const currentConsolidatedProgress = patient.data.consolidatedQueries?.find(
q => q.requestId === requestId
);

const defaultAnalyticsProps = {
distinctId: patient.cxId,
event: EventTypes.consolidatedQuery,
properties: {
patientId: patient.id,
conversionType: "bundle",
duration: elapsedTimeFromNow(currentConsolidatedProgress?.startedAt),
resourceCount: bundle.entry?.length,
},
};

analytics(defaultAnalyticsProps);
Copy link
Member Author

Choose a reason for hiding this comment

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

moved to get-snapshot-local.ts

Comment on lines -302 to -309
analytics({
...defaultAnalyticsProps,
properties: {
...defaultAnalyticsProps.properties,
duration: elapsedTimeFromNow(currentConsolidatedProgress?.startedAt),
conversionType,
},
});
Copy link
Member Author
@leite08 leite08 Apr 30, 2025

Choose a reason for hiding this comment

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

moved to handleBundleToMedicalRecord - convert-fhir-bundle.ts

Ref eng-141

Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
@leite08 leite08 force-pushed the eng-141-recreate-consolidate-doesnt-load-bundle branch from 78bf361 to 65acf46 Compare April 30, 2025 22:30
@leite08 leite08 added this pull request to the merge queue May 5, 2025
Merged via the queue into develop with commit f7ab8e5 May 5, 2025
15 checks passed
@leite08 leite08 deleted the eng-141-recreate-consolidate-doesnt-load-bundle branch May 5, 2025 15:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants
0