Skip to content
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

use strings for MeasureReports #209

Closed
wants to merge 2 commits into from

Conversation

MontaltoNick
Copy link
Contributor

@MontaltoNick MontaltoNick commented May 21, 2024

use strings for MeasureReports

Summary by CodeRabbit

  • New Features

    • Enhanced data handling for submission reports by introducing serialized aggregates.
    • Updated serialization strategy to utilize System.Text.Json for improved efficiency.
  • Bug Fixes

    • Refined error handling in message consumption processes, adding specificity for exceptions.
  • Refactor

    • Changed the data structure of the Aggregates property in multiple classes from a list of MeasureReport objects to a list of strings, improving data processing.

Copy link
Contributor

coderabbitai bot commented Nov 5, 2024

Walkthrough

The changes in this pull request involve modifications to several files within the DotNet project. Key alterations include the removal of ARG and ENV directives in the Dockerfile for the DotNet/Account project, updates to the Aggregates property type in the SubmissionReportValue and SubmitReportValue classes, and enhancements to serialization processes in various listener and job classes. These updates aim to streamline data handling and improve the overall structure of the application while maintaining existing functionality.

Changes

File Path Change Summary
DotNet/Account/Dockerfile Removed ARGs ACCESS_TOKEN, ARTIFACTS_ENDPOINT and ENVs NUGET_CREDENTIALPROVIDER_SESSIONTOKENCACHE_ENABLED, VSS_NUGET_EXTERNAL_FEED_ENDPOINTS.
DotNet/Report/Application/Models/SubmissionReportValue.cs Changed Aggregates property type from List<MeasureReport> to List<string>.
DotNet/Report/Jobs/GenerateDataAcquisitionRequestsForPatientsToQuery.cs Added System.Text.Json using directive; updated Execute method to serialize aggregates for Kafka.
DotNet/Report/Listeners/ResourceEvaluatedListener.cs Introduced serialized aggregates in StartConsumerLoop method, replacing direct assignment.
DotNet/Submission/Application/Models/SubmitReportValue.cs Changed Aggregates property type from List<MeasureReport> to List<string>.
DotNet/Submission/Listeners/SubmitReportListener.cs Updated StartConsumerLoop for aggregate deserialization; refined error handling with new TransientException.

Possibly related PRs

Suggested reviewers

  • dvargaslantana
  • amphillipsLGC

🐰 "In the code where changes abound,
A cleaner path we have found.
With aggregates now in string form,
Our data flows, a new norm!
Docker's cleaned, the structure tight,
Hopping forward, all feels right!" 🐇


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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.

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

Copy link
Contributor

@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: 4

🧹 Outside diff range and nitpick comments (5)
DotNet/Submission/Application/Models/SubmitReportValue.cs (1)

9-9: Document the serialization format for Aggregates.

The change from List<MeasureReport> to List<string> is reasonable for serialization purposes, but please add XML documentation to specify:

  • The expected string format (JSON/XML)
  • Any validation requirements
  • Example of a valid serialized MeasureReport

Add documentation like this:

+        /// <summary>
+        /// List of serialized MeasureReport objects.
+        /// Format: JSON-serialized FHIR MeasureReport
+        /// </summary>
         public List<string> Aggregates { get; internal set; }
DotNet/Report/Application/Models/SubmissionReportValue.cs (1)

11-11: Add XML documentation for the serialization format.

Since Aggregates now stores serialized data, it would be helpful to document the expected format and any requirements for the serialized strings.

+        /// <summary>
+        /// List of serialized MeasureReport objects in JSON format.
+        /// </summary>
         public List<string> Aggregates { get; internal set; }
DotNet/Report/Listeners/ResourceEvaluatedListener.cs (1)

216-221: Consider optimizing the serialization process.

The serialization implementation is correct but could be improved for better performance and maintainability.

Consider using LINQ to make the code more concise and potentially more efficient:

-var serializedAggregates = new List<string>();
-foreach (var agg in _aggregator.Aggregate(measureReports))
-{
-    serializedAggregates.Add(JsonSerializer.Serialize(agg, new JsonSerializerOptions().ForFhir()));
-}
+var serializedAggregates = _aggregator.Aggregate(measureReports)
+    .Select(agg => JsonSerializer.Serialize(agg, new JsonSerializerOptions().ForFhir()))
+    .ToList();
DotNet/Submission/Listeners/SubmitReportListener.cs (2)

15-15: Consider standardizing on System.Text.Json throughout the codebase.

The code currently mixes Newtonsoft.Json and System.Text.Json serializers. This can lead to inconsistencies in serialization behavior and makes the code harder to maintain.

Consider migrating all serialization to use System.Text.Json, which is the modern, preferred serializer for .NET applications.


204-206: Document the rationale for string-based MeasureReport storage.

The shift from strongly-typed MeasureReport objects to strings is a significant architectural change that could affect:

  • Memory usage
  • Data validation
  • Error handling

Please add comments explaining:

  1. Why this change was made
  2. The benefits of string-based storage
  3. Any considerations for future maintainers
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b5a4bab and 31ab39c.

📒 Files selected for processing (6)
  • DotNet/Account/Dockerfile (0 hunks)
  • DotNet/Report/Application/Models/SubmissionReportValue.cs (1 hunks)
  • DotNet/Report/Jobs/GenerateDataAcquisitionRequestsForPatientsToQuery.cs (3 hunks)
  • DotNet/Report/Listeners/ResourceEvaluatedListener.cs (2 hunks)
  • DotNet/Submission/Application/Models/SubmitReportValue.cs (1 hunks)
  • DotNet/Submission/Listeners/SubmitReportListener.cs (2 hunks)
💤 Files with no reviewable changes (1)
  • DotNet/Account/Dockerfile
🧰 Additional context used
📓 Path-based instructions (5)
DotNet/Report/Application/Models/SubmissionReportValue.cs (1)

Pattern **: PRs that have "TECH-DEBT" in the title should only contain changes related to typos, unused code, linter/IDE suggestions, swagger specification updates, and logging improvements. These TECH-DEBT PRs should not affect core functionality.

DotNet/Report/Jobs/GenerateDataAcquisitionRequestsForPatientsToQuery.cs (1)

Pattern **: PRs that have "TECH-DEBT" in the title should only contain changes related to typos, unused code, linter/IDE suggestions, swagger specification updates, and logging improvements. These TECH-DEBT PRs should not affect core functionality.

DotNet/Report/Listeners/ResourceEvaluatedListener.cs (1)

Pattern **: PRs that have "TECH-DEBT" in the title should only contain changes related to typos, unused code, linter/IDE suggestions, swagger specification updates, and logging improvements. These TECH-DEBT PRs should not affect core functionality.

DotNet/Submission/Application/Models/SubmitReportValue.cs (1)

Pattern **: PRs that have "TECH-DEBT" in the title should only contain changes related to typos, unused code, linter/IDE suggestions, swagger specification updates, and logging improvements. These TECH-DEBT PRs should not affect core functionality.

DotNet/Submission/Listeners/SubmitReportListener.cs (1)

Pattern **: PRs that have "TECH-DEBT" in the title should only contain changes related to typos, unused code, linter/IDE suggestions, swagger specification updates, and logging improvements. These TECH-DEBT PRs should not affect core functionality.

🔇 Additional comments (4)
DotNet/Report/Jobs/GenerateDataAcquisitionRequestsForPatientsToQuery.cs (2)

15-15: LGTM!

The addition of System.Text.Json namespace is appropriate for the new serialization requirements.


188-188: Verify the impact of serialized aggregates.

The change from MeasureReport objects to serialized strings is correct, but we should verify that downstream consumers are prepared to handle string-based aggregates.

Let's check for consumers of SubmissionReportValue:

DotNet/Report/Listeners/ResourceEvaluatedListener.cs (2)

237-237: LGTM! Assignment of serialized aggregates.

The assignment of the serialized aggregates to the SubmissionReportValue is correct and aligns with the PR objective of using strings for MeasureReports.


Line range hint 216-237: Verify error handling for serialization failures.

The serialization process could potentially fail if the aggregates contain invalid data. Consider adding explicit error handling.

Let's check if there are any existing error handlers for serialization issues:

Consider wrapping the serialization in a try-catch block to handle potential JsonException errors and provide meaningful error messages. This would help with debugging and maintain system stability.

✅ Verification successful

Serialization errors are already handled by the global error handling mechanism

The code is already well-protected against serialization failures through a comprehensive error handling strategy:

  1. The serialization code is wrapped within a larger try-catch block that handles multiple exception types:

    • DeadLetterException for unrecoverable errors
    • TransientException for temporary failures
    • TimeoutException for timing issues
    • Generic Exception as a catch-all
  2. Any serialization failure would be caught by the generic Exception handler, which forwards the error to the _deadLetterExceptionHandler with proper audit event tracking.

  3. The error handling includes proper cleanup through the finally block that ensures consumer commitment.

The existing implementation provides sufficient protection against serialization failures, making additional error handling around the specific serialization call unnecessary and potentially redundant.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for serialization error handling patterns in the codebase
rg -A 5 "JsonException|SerializationException" 

Length of output: 48


Script:

#!/bin/bash
# Let's search for any existing try-catch blocks around JsonSerializer.Serialize
ast-grep --pattern 'try {
  $$$
  JsonSerializer.Serialize($$$)
  $$$
}'

# Also search for general error handling patterns around serialization
rg -B 2 -A 2 "JsonSerializer.Serialize"

Length of output: 28757


Script:

#!/bin/bash
# Let's check for any global error handling or try-catch patterns in the ResourceEvaluatedListener class
rg -B 5 -A 5 "try|catch|Exception" DotNet/Report/Listeners/ResourceEvaluatedListener.cs

# Also check if there's any error handling in the Aggregator class that's being used
ast-grep --pattern 'class $_Aggregator {
  $$$
  Aggregate($$$) {
    $$$
  }
}'

Length of output: 11626

@@ -6,7 +6,7 @@ public class SubmitReportValue
{
public List<string>? PatientIds { get; internal set; }
public Organization Organization { get; internal set; }
public List<MeasureReport> Aggregates { get; internal set; }
public List<string> Aggregates { get; internal set; }
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Inconsistent serialization approaches detected across the codebase

The codebase uses multiple different serialization approaches for MeasureReport:

  • FhirJsonSerializer in MeasureReportSubmissionEntryModel.cs
  • System.Text.Json.JsonSerializer in SubmitReportListener.cs
  • JsonConvert (Newtonsoft.Json) in SubmitReportListener.cs

This inconsistency could lead to serialization/deserialization mismatches and potential data integrity issues.

🔗 Analysis chain

Verify consistent serialization across the codebase.

Since this property is part of a broader change to use serialized MeasureReports, we should verify that all related components use the same serialization approach.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent serialization patterns across the codebase
# Expected: All serialization of MeasureReport should use the same approach

# Search for MeasureReport serialization patterns
echo "Checking MeasureReport serialization patterns:"
rg -A 3 "MeasureReport.*(?:JsonSerializer|SerializeToJson|JsonConvert)" 

# Search for string deserialization back to MeasureReport
echo -e "\nChecking MeasureReport deserialization patterns:"
rg -A 3 "(?:Deserialize|ParseJson).*MeasureReport"

Length of output: 1744

@@ -8,7 +8,7 @@ public class SubmissionReportValue
{
public List<string>? PatientIds { get; internal set; }
public Organization Organization { get; internal set; }
public List<MeasureReport> Aggregates { get; internal set; }
public List<string> Aggregates { get; internal set; }
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Add try-catch block for aggregate deserialization

The deserialization of MeasureReport from Aggregates is not wrapped in a try-catch block, which could lead to unhandled exceptions. Add proper error handling for the JsonSerializer.Deserialize call in SubmitReportListener.cs:

  • DotNet/Submission/Listeners/SubmitReportListener.cs: Add try-catch around the deserialization of aggregates in the foreach loop
🔗 Analysis chain

LGTM! Verify deserialization handling across consumers.

The change from List<MeasureReport> to List<string> aligns with distributed system patterns for message transport. However, ensure proper error handling during deserialization in all consuming services.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all locations where SubmissionReportValue.Aggregates is used
# to verify proper deserialization handling

# Search for direct usage of the Aggregates property
rg -l "SubmissionReportValue.*Aggregates" --type cs

# Search for JsonSerializer.Deserialize calls that might be handling these aggregates
rg -l "JsonSerializer\.Deserialize.*MeasureReport" --type cs

Length of output: 168


Script:

#!/bin/bash
# Let's examine the SubmitReportListener.cs to understand the deserialization handling
rg -A 10 -B 10 "JsonSerializer\.Deserialize.*MeasureReport" DotNet/Submission/Listeners/SubmitReportListener.cs

# Also search for any error handling patterns around deserialization
rg "try.*catch.*JsonSerializer" DotNet/Submission/Listeners/SubmitReportListener.cs

# Look for any validation or error handling related to Aggregates
rg -A 5 "Aggregates" DotNet/Submission/Listeners/SubmitReportListener.cs

Length of output: 1830

Comment on lines +168 to +174

var serializedAggregates = new List<string>();
foreach (var agg in _aggregator.Aggregate(measureReports))
{
serializedAggregates.Add(JsonSerializer.Serialize(agg, new JsonSerializerOptions().ForFhir()));
}

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding error handling for serialization.

While the serialization implementation is correct, it lacks error handling for potential serialization failures. A single failed serialization could cause the entire aggregation process to fail.

Consider wrapping the serialization in a try-catch block:

 var serializedAggregates = new List<string>();
 foreach (var agg in _aggregator.Aggregate(measureReports))
 {
-    serializedAggregates.Add(JsonSerializer.Serialize(agg, new JsonSerializerOptions().ForFhir()));
+    try 
+    {
+        serializedAggregates.Add(JsonSerializer.Serialize(agg, new JsonSerializerOptions().ForFhir()));
+    }
+    catch (JsonException ex)
+    {
+        _logger.LogError(ex, "Failed to serialize MeasureReport aggregate");
+        throw;
+    }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var serializedAggregates = new List<string>();
foreach (var agg in _aggregator.Aggregate(measureReports))
{
serializedAggregates.Add(JsonSerializer.Serialize(agg, new JsonSerializerOptions().ForFhir()));
}
var serializedAggregates = new List<string>();
foreach (var agg in _aggregator.Aggregate(measureReports))
{
try
{
serializedAggregates.Add(JsonSerializer.Serialize(agg, new JsonSerializerOptions().ForFhir()));
}
catch (JsonException ex)
{
_logger.LogError(ex, "Failed to serialize MeasureReport aggregate");
throw;
}
}

Comment on lines +204 to +206
var agg = System.Text.Json.JsonSerializer.Deserialize<MeasureReport>(aggregate, options);
fileName = $"aggregate-{agg.Measure}.json";
contents = aggregate;
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize aggregate processing to avoid full deserialization.

The current code deserializes the entire MeasureReport just to access the measure ID for the filename. This is inefficient, especially for large reports.

Consider using JsonDocument to extract just the measure ID:

- var agg = System.Text.Json.JsonSerializer.Deserialize<MeasureReport>(aggregate, options);
- fileName = $"aggregate-{agg.Measure}.json";
+ using var doc = JsonDocument.Parse(aggregate);
+ var measure = doc.RootElement.GetProperty("measure").GetString();
+ fileName = $"aggregate-{measure}.json";

This approach is more performant as it:

  1. Avoids full object deserialization
  2. Still validates JSON syntax
  3. Only extracts the needed field
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var agg = System.Text.Json.JsonSerializer.Deserialize<MeasureReport>(aggregate, options);
fileName = $"aggregate-{agg.Measure}.json";
contents = aggregate;
using var doc = JsonDocument.Parse(aggregate);
var measure = doc.RootElement.GetProperty("measure").GetString();
fileName = $"aggregate-{measure}.json";
contents = aggregate;

@MontaltoNick MontaltoNick deleted the submission_measureReport_string branch January 22, 2025 18:30
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