-
Notifications
You must be signed in to change notification settings - Fork 72
fix(core): remove rendered files on xml redownload #4344
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
fix(core): remove rendered files on xml redownload #4344
Conversation
Part of ENG-836 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Caution Review failedThe pull request is closed. WalkthroughReorganizes imports and error handling, adds MTOM/CID and S3 utilities, parses ITI-39 responses via schema, computes decoded document sizes and, on mismatch with S3, deletes rendered HTML/PDF artifacts. Also removes one exported helper and adds a utility to produce render file paths. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant DRProcessor
participant IHEGateway
participant MTOMParser
participant S3
Client->>DRProcessor: processDRResponse(request)
DRProcessor->>IHEGateway: send ITI-39 request
IHEGateway-->>DRProcessor: SOAP + MTOM response
DRProcessor->>MTOMParser: parse MTOM & validate (iti39Schema)
MTOMParser-->>DRProcessor: documentResponses[]
loop for each document
DRProcessor->>S3: headObject(document file)
S3-->>DRProcessor: fileInfo (exists, size)
DRProcessor->>DRProcessor: decode bytes -> newFileSize
alt newFileSize != fileInfo.size
DRProcessor->>S3: deleteFiles(createDocumentRenderFilePaths(fileName))
end
DRProcessor->>S3: store/update document file (if needed)
end
DRProcessor-->>Client: result or handled error
Estimated code review effort🎯 4 (Complex) | ⏱️ ~35 minutes Possibly related PRs
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (2)
✨ 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 comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
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: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
packages/core/src/external/carequality/ihe-gateway-v2/outbound/xca/process/dr-response.ts
(2 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
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/core/src/external/carequality/ihe-gateway-v2/outbound/xca/process/dr-response.ts
**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursorrules)
Use types whenever possible
Files:
packages/core/src/external/carequality/ihe-gateway-v2/outbound/xca/process/dr-response.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/core/src/external/carequality/ihe-gateway-v2/outbound/xca/process/dr-response.ts
🧠 Learnings (3)
📓 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-05-20T21:26:26.804Z
Learnt from: leite08
PR: metriport/metriport#3814
File: packages/api/src/routes/internal/medical/patient-consolidated.ts:141-174
Timestamp: 2025-05-20T21:26:26.804Z
Learning: The functionality introduced in packages/api/src/routes/internal/medical/patient-consolidated.ts is planned to be refactored in downstream PR #3857, including improvements to error handling and validation.
Applied to files:
packages/core/src/external/carequality/ihe-gateway-v2/outbound/xca/process/dr-response.ts
📚 Learning: 2025-06-06T16:45:31.832Z
Learnt from: thomasyopes
PR: metriport/metriport#3970
File: packages/api/src/external/ehr/athenahealth/command/write-back/medication.ts:17-17
Timestamp: 2025-06-06T16:45:31.832Z
Learning: The writeMedicationToChart function in packages/api/src/external/ehr/athenahealth/command/write-back/medication.ts returns a response that is not currently used by any consumers, so changes to its return type are not breaking changes in practice.
Applied to files:
packages/core/src/external/carequality/ihe-gateway-v2/outbound/xca/process/dr-response.ts
🧬 Code Graph Analysis (1)
packages/core/src/external/carequality/ihe-gateway-v2/outbound/xca/process/dr-response.ts (2)
packages/core/src/external/sftp/client.ts (1)
log
(261-263)packages/mllp-server/src/utils.ts (1)
s3Utils
(18-18)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: check-pr / lint-build-test
- GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
packages/core/src/external/carequality/ihe-gateway-v2/outbound/xca/process/dr-response.ts (1)
117-117
: deleteFiles handles missing S3 objects gracefullyAWS S3’s deleteObjects API doesn’t error when keys don’t exist, and our
deleteFiles
wrapper only logs and rethrows on genuine AWS errors. No additional error handling is needed around this call.
packages/core/src/external/carequality/ihe-gateway-v2/outbound/xca/process/dr-response.ts
Outdated
Show resolved
Hide resolved
Part of ENG-836 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-836 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-836 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-836 Signed-off-by: Ramil Garipov <ramil@metriport.com>
packages/api/src/external/commonwell/document/document-query.ts
Outdated
Show resolved
Hide resolved
packages/core/src/external/carequality/ihe-gateway-v2/outbound/xca/process/dr-response.ts
Outdated
Show resolved
Hide resolved
Part of ENG-836 Signed-off-by: Ramil Garipov <ramil@metriport.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: 3
🔭 Outside diff range comments (1)
packages/api/src/command/medical/document/document-query-storage-info.ts (1)
32-48
: Make the mapper sync; drop unnecessary async and simplify callersThe returned function does no async work. Making it sync removes Promise churn and lets you simplify getS3Info’s mapping.
-function getDocToFileFunction(patient: Pick<Patient, "cxId" | "id">) { - // TODO convert the input from CW Document to a Metriport shape - return async (doc: Document): Promise<SimpleFile> => { +function getDocToFileFunction(patient: Pick<Patient, "cxId" | "id">) { + // TODO convert the input from CW Document to a Metriport shape + return (doc: Document): SimpleFile => { const fileName = createDocumentFilePath( patient.cxId, patient.id, doc.id, doc.content?.mimeType ); return { docId: doc.id, fileName, fileLocation: s3BucketName, fileContentType: doc.content?.mimeType, }; }; }And in getS3Info:
- const docToFile = getDocToFileFunction(patient); - const s3Info = await Promise.allSettled( - documents - .map(d => docToFile(d)) - .map(async (filePromise: Promise<SimpleFile>): Promise<S3Info> => { - const file = await filePromise; + const docToFile = getDocToFileFunction(patient); + const s3Info = await Promise.allSettled( + documents + .map(docToFile) + .map(async (file: SimpleFile): Promise<S3Info> => { try { const { exists: fileExists, size: fileSize, contentType: fileContentType, } = await s3Utils.getFileInfoFromS3(file.fileName, file.fileLocation); return { docId: file.docId, fileExists, fileSize, fileContentType, fileName: file.fileName, fileLocation: file.fileLocation, }; } catch (error) { errors.push({ error, message: String(error), docId: file.docId, }); throw error; } }) );
🧹 Nitpick comments (2)
packages/api/src/external/commonwell/document/document-query.ts (1)
492-493
: Consider reusing a shared S3Utils instanceMinor: instantiate S3Utils at module scope (or reuse a shared instance) to avoid per-call construction and to simplify testing via DI (as done in the Carequality DR flow with setS3UtilsInstance).
packages/core/src/external/carequality/ihe-gateway-v2/outbound/xca/process/dr-response.ts (1)
276-281
: Logging: avoid JSON.stringify in logs; use errorToStringPer guidelines, don’t JSON.stringify errors into logs. Use errorToString for a concise, single-line message.
- log(`Error processing DR response ${JSON.stringify(error)}`); + log(`Error processing DR response: ${errorToString(error)}`);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
packages/api/src/command/medical/document/document-query-storage-info.ts
(1 hunks)packages/api/src/external/commonwell/document/document-query.ts
(6 hunks)packages/core/src/domain/document/filename.ts
(1 hunks)packages/core/src/external/carequality/ihe-gateway-v2/outbound/xca/process/dr-response.ts
(2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.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/core/src/domain/document/filename.ts
packages/api/src/command/medical/document/document-query-storage-info.ts
packages/api/src/external/commonwell/document/document-query.ts
packages/core/src/external/carequality/ihe-gateway-v2/outbound/xca/process/dr-response.ts
🧬 Code Graph Analysis (2)
packages/api/src/external/commonwell/document/document-query.ts (4)
packages/mllp-server/src/utils.ts (1)
s3Utils
(18-18)packages/core/src/external/aws/s3.ts (1)
S3Utils
(140-570)packages/api/src/command/medical/document/document-query-storage-info.ts (1)
getS3Info
(62-109)packages/core/src/domain/document/filename.ts (1)
createDocumentRenderFilePaths
(24-28)
packages/core/src/external/carequality/ihe-gateway-v2/outbound/xca/process/dr-response.ts (2)
packages/core/src/domain/document/filename.ts (1)
createDocumentRenderFilePaths
(24-28)packages/mllp-server/src/utils.ts (1)
s3Utils
(18-18)
🔇 Additional comments (1)
packages/api/src/command/medical/document/document-query-storage-info.ts (1)
32-32
: No external references to getDocToFileFunction remain
Verified viarg -n --glob '!*node_modules*' '\bgetDocToFileFunction\b' | sed '/document-query-storage-info\.ts/d'
—no matches found outsidedocument-query-storage-info.ts
.
packages/core/src/external/carequality/ihe-gateway-v2/outbound/xca/process/dr-response.ts
Show resolved
Hide resolved
Part of ENG-836 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-836 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-836
Issues:
Description
Testing
Release Plan
Summary by CodeRabbit
New Features
Improvements
Bug Fixes
Refactor