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

feat(app): Change FCE MediaTypes #1729

Merged
merged 11 commits into from
Feb 3, 2025
Merged

Conversation

oskogstad
Copy link
Collaborator

@oskogstad oskogstad commented Jan 23, 2025

Description

Changing FCE media types (breaks the API)

This PR is step 1 of 2(?), the app needs to allow for the new media types before we yank out the old ones in the DB lookup type.
Tests have been modified to [Theory] and check both types, and checks for conversion from old to new when storing in DB.

Related Issue(s)

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)

Documentation

  • Documentation is updated (either in docs-directory, Altinnpedia or a separate linked PR in altinn-studio-docs., if applicable)

Copy link
Contributor

coderabbitai bot commented Jan 23, 2025

Warning

Rate limit exceeded

@oskogstad has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 17 minutes and 16 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 0d6e800 and de7718c.

📒 Files selected for processing (3)
  • src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/ContentValueDtoValidator.cs (3 hunks)
  • src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/DialogContentInputConverter.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/TransmissionContentInputConverter.cs (1 hunks)
📝 Walkthrough

Walkthrough

This pull request updates the media type definitions used in the system. It introduces two new constants in the MediaTypes class, changing existing constants' suffixes from "+json" to "-url" and updating the type parameter. A new migration class is added to adjust media type entries in the database, ensuring stored values reflect the new definitions while maintaining the ability to revert to previous settings. Additionally, the validation logic for media types is enhanced to include deprecated versions for backward compatibility.

Changes

File Path Change Summary
src/Digdir.Domain.../MediaTypes.cs Added constants EmbeddableMarkdownDeprecated and LegacyEmbeddableHtmlDeprecated; updated constants EmbeddableMarkdown and LegacyEmbeddableHtml to use a -url;type=text/… suffix instead of +json.
src/Digdir.Domain.../Migrations/20250203085824_ChangeFCEMediaTypes.cs Added a new migration class ChangeFCEMediaTypes that updates media type fields in database tables via the Up method and reverts changes in the Down method with raw SQL.
src/Digdir.Domain.../ContentValueDtoValidator.cs Updated media type validation logic to include EmbeddableMarkdownDeprecated and LegacyEmbeddableHtmlDeprecated for backward compatibility in the ContentValueDtoValidator class.
src/Digdir.Domain.../DialogContentInputConverter.cs Modified Convert method to use MapDeprecatedMediaType() for setting MediaType in IntermediateDialogContent.
src/Digdir.Domain.../TransmissionContentInputConverter.cs Modified Convert method to use MapDeprecatedMediaType() for setting MediaType in IntermediateTransmissionContent.

Possibly related issues

  • Change mediatype for FCEs #1728: The issue discusses changing FCE media types from misleading +json types to -url types. The changes in this PR align with the objectives by updating both code constants and database values accordingly.

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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.

@oskogstad oskogstad changed the title feat(app): Clearifying changes to FCE MediaTypes feat(app): Clarifying changes to FCE MediaTypes Jan 23, 2025
@oskogstad oskogstad marked this pull request as ready for review January 28, 2025 19:15
@oskogstad oskogstad requested a review from a team as a code owner January 28, 2025 19:15
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: 2

🧹 Nitpick comments (7)
tests/Digdir.Domain.Dialogporten.Application.Integration.Tests/Features/V1/ServiceOwner/Dialogs/Commands/CreateDialogTests.cs (2)

285-285: Consider using a constant from test helpers.

The media type constant is used in test data creation. Consider moving this to a test helper class to maintain consistency across test files.

-        MediaType = MediaTypes.LegacyHtml,
+        MediaType = TestConstants.MediaTypes.LegacyHtml,

Line range hint 390-425: Comprehensive test coverage with database verification.

The test effectively verifies:

  1. Dialog creation with different media types
  2. Proper conversion of deprecated media types in the database
  3. Correct association with dialog ID

Consider adding a test case for MediaTypes.EmbeddableMarkdown to ensure complete coverage of supported media types.

 [Theory]
 [InlineData(MediaTypes.LegacyEmbeddableHtml)]
#pragma warning disable CS0618 // Type or member is obsolete
 [InlineData(MediaTypes.LegacyEmbeddableHtmlDeprecated)]
+[InlineData(MediaTypes.EmbeddableMarkdown)]
#pragma warning restore CS0618 // Type or member is obsolete
src/Digdir.Domain.Dialogporten.WebApi/Common/Authorization/AuthorizationPolicy.cs (1)

21-21: Add XML documentation for the new scope constant.

Consider adding XML documentation to explain:

  • The purpose of this scope
  • When it should be used
  • Any migration plans (since it's for legacy content)
+    /// <summary>
+    /// Authorization scope for accessing legacy HTML content.
+    /// Part of the media type migration process - see issue #1728.
+    /// </summary>
     public const string LegacyHtmlScope = "digdir:dialogporten.serviceprovider.legacyhtml";
src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/ContentValueDtoValidator.cs (2)

71-95: Consider extracting temporary media type additions to a configuration.

The temporary media type additions (referencing issue #1749) are hardcoded. Consider extracting these to a configuration that can be easily updated when the migration is complete.

+private static readonly string[] TemporaryMediaTypes = [
+    MediaTypes.EmbeddableMarkdown,
+    MediaTypes.EmbeddableMarkdownDeprecated
+];

 private static string[] GetAllowedDialogContentMediaTypes(DialogContentType contentType, IUser? user)
     => contentType.Id switch
     {
         DialogContentType.Values.AdditionalInfo when UserHasLegacyHtmlScope(user)
             => contentType.AllowedMediaTypes.Append(MediaTypes.LegacyHtml).ToArray(),
         DialogContentType.Values.MainContentReference when UserHasLegacyHtmlScope(user)
             => contentType.AllowedMediaTypes
                 .Append(MediaTypes.LegacyEmbeddableHtmlDeprecated)
                 .Append(MediaTypes.LegacyEmbeddableHtml)
-                .Append(MediaTypes.EmbeddableMarkdown)
-                .Append(MediaTypes.EmbeddableMarkdownDeprecated)
+                .Concat(TemporaryMediaTypes)
                 .ToArray(),
         DialogContentType.Values.MainContentReference
             => contentType.AllowedMediaTypes
-                .Append(MediaTypes.EmbeddableMarkdown)
-                .Append(MediaTypes.EmbeddableMarkdownDeprecated)
+                .Concat(TemporaryMediaTypes)
                 .ToArray(),
         _ => contentType.AllowedMediaTypes
     };

97-111: Maintain consistency in media type handling.

The transmission content media types method follows the same pattern. Consider applying the same configuration-based approach for temporary media types.

 private static string[] GetAllowedTransmissionContentMediaTypes(DialogTransmissionContentType contentType)
     => contentType.Id switch
     {
         DialogTransmissionContentType.Values.ContentReference
             => contentType.AllowedMediaTypes
-                .Append(MediaTypes.EmbeddableMarkdown)
-                .Append(MediaTypes.EmbeddableMarkdownDeprecated)
+                .Concat(TemporaryMediaTypes)
                 .ToArray(),
         _ => contentType.AllowedMediaTypes
     };
src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/DialogContentInputConverter.cs (1)

Line range hint 13-15: Address the TODO comment regarding team discussion.

The TODO comment indicates that this implementation needs team discussion. Consider scheduling a team review to address this technical debt.

Would you like me to create an issue to track this technical debt and schedule the team discussion?

src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/TransmissionContentInputConverter.cs (1)

Line range hint 12-17: Consider combining with DialogContentInputConverter.

The TODO comment suggests combining this class with DialogContentInputConverter. This would reduce code duplication and improve maintainability.

Would you like me to:

  1. Create an issue to track this refactoring task?
  2. Generate a proof-of-concept implementation that combines both converters?
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 03929f5 and 1bd26a9.

📒 Files selected for processing (11)
  • src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/ContentValueDtoValidator.cs (3 hunks)
  • src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/DialogContentInputConverter.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/MappingProfile.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/MediaTypeExtensions.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/TransmissionContentInputConverter.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.Domain/Dialogs/Entities/Contents/DialogContentType.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.Domain/Dialogs/Entities/Transmissions/Contents/DialogTransmissionContentType.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.Domain/MediaTypes.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.WebApi/Common/Authorization/AuthorizationPolicy.cs (1 hunks)
  • tests/Digdir.Domain.Dialogporten.Application.Integration.Tests/Features/V1/ServiceOwner/Dialogs/Commands/CreateDialogTests.cs (6 hunks)
  • tests/Digdir.Domain.Dialogporten.Application.Integration.Tests/Features/V1/ServiceOwner/Transmissions/Commands/CreateTransmissionTests.cs (4 hunks)
🔇 Additional comments (15)
tests/Digdir.Domain.Dialogporten.Application.Integration.Tests/Features/V1/ServiceOwner/Dialogs/Commands/CreateDialogTests.cs (4)

8-8: LGTM!

The addition of the Contents namespace import is appropriate for accessing dialog content entities.


303-305: LGTM!

The assertion correctly verifies the media type validation error.


351-353: LGTM!

The assertion correctly verifies the media type validation error.


Line range hint 356-388: Well-structured test parameterization.

Good use of the [Theory] attribute with [InlineData] to test both current and deprecated media types. The pragma warnings are appropriately used to suppress obsolete warnings for deprecated types.

src/Digdir.Domain.Dialogporten.WebApi/Common/Authorization/AuthorizationPolicy.cs (1)

21-21: Verify the security implications of the new legacy HTML scope.

Since this scope grants access to legacy HTML content, we should ensure:

  1. The scope is properly validated in all relevant endpoints
  2. There are appropriate security measures for handling legacy HTML content
✅ Verification successful

Legacy HTML scope implementation is properly secured

The scope is correctly validated through proper authorization checks and is limited to specific content types (AdditionalInfo and MainContentReference). The implementation includes appropriate security measures and test coverage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of the new scope in authorization checks and content handling
echo "Searching for LegacyHtmlScope usage in authorization requirements..."
rg "LegacyHtmlScope" -A 5

echo "Searching for potential HTML content handling..."
ast-grep --pattern 'RequireAuthorization($$$)' 

Length of output: 7861

src/Digdir.Domain.Dialogporten.Domain/Dialogs/Entities/Contents/DialogContentType.cs (2)

68-70: LGTM! Clear migration plan with issue reference.

The TODO comment provides good context about the migration strategy and includes a link to the tracking issue #1749. This aligns well with the PR's objective of implementing the first step in accommodating new media types.


71-72: Verify the scope of warning suppression.

The warning suppression for the obsolete media type is properly scoped to just the specific usage. However, please ensure that:

  1. The new media types are ready to be used in the next phase
  2. The migration plan in issue Create migration for FCE MediaTypes #1749 includes steps to remove these warning suppressions

Let me verify the readiness of new media types and migration plans:

✅ Verification successful

Warning suppression is properly managed as part of the media type transition plan

The warning suppression is correctly scoped and is part of a well-documented transition plan:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for the definition and usage of new media types
echo "Searching for new media type definitions..."
rg "EmbeddableMarkdown[^D]" -A 5

echo "Checking migration issue details..."
gh issue view 1749 --json title,body,labels

Length of output: 8209


Script:

#!/bin/bash
# Check the blocking issue details
echo "Checking blocking issue #1728..."
gh issue view 1728 --json title,body,state,labels

# Check for any related PRs
echo -e "\nChecking related PRs..."
gh pr list --search "1728 in:title,body"

Length of output: 3865

src/Digdir.Domain.Dialogporten.Domain/MediaTypes.cs (2)

7-8: LGTM! Proper deprecation notices.

The [Obsolete] attributes with clear migration messages help guide developers to use the new constants.

Also applies to: 11-12


8-9: Verify the impact of changing media type format from '+json' to '-url'.

The change from +json suffix to -url with explicit type parameters represents a significant architectural change in how content is delivered.

Please ensure that:

  1. All consumers of these media types are updated to handle the new format
  2. Documentation is updated to reflect this change
  3. API contracts and OpenAPI specifications are updated
✅ Verification successful

Media type format change is properly handled with backward compatibility

The codebase has comprehensive support for the transition from '+json' to '-url' format:

  • Automatic conversion from deprecated to new format via MediaTypeExtensions.ConvertIfDeprecatedMediaType()
  • Validation rules accepting both formats
  • Proper deprecation notices with [Obsolete] attributes
  • Extensive test coverage for both formats
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usages of the old media type format
rg -l "\+json;type=(markdown|html)" --type cs

Length of output: 3556


Script:

#!/bin/bash
# Check the actual content of DTO files and look for media type usage
echo "=== Checking DTO implementations ==="
rg -A 5 -B 5 "\+json;type=(markdown|html)" \
    src/Digdir.Domain.Dialogporten.Application/Features/V1/ServiceOwner/DialogTransmissions/Queries/Get/TransmissionDto.cs \
    src/Digdir.Domain.Dialogporten.Application/Features/V1/ServiceOwner/Dialogs/Commands/Update/UpdateDialogDto.cs \
    src/Digdir.Domain.Dialogporten.Application/Features/V1/ServiceOwner/Dialogs/Commands/Create/CreateDialogDto.cs

echo -e "\n=== Checking for media type parsing or comparison logic ==="
rg -A 5 "MediaType" --type cs

Length of output: 66105

src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/MappingProfile.cs (1)

14-17: LGTM! Consistent mapping configuration.

The mapping profiles correctly handle media type conversion for both transmission and dialog content.

src/Digdir.Domain.Dialogporten.Domain/Dialogs/Entities/Transmissions/Contents/DialogTransmissionContentType.cs (1)

39-43: LGTM! Clear migration plan with issue reference.

The temporary use of deprecated media type is well-documented with a TODO comment and issue reference (#1749).

To track the migration completion:

✅ Verification successful

Migration for FCE MediaTypes is still pending (issue #1749 is open)

The current implementation using deprecated media type is a valid temporary solution with proper documentation and tracking. No immediate action required.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the issue is still open
gh issue view 1749 --json state,title

Length of output: 128


Script:

#!/bin/bash
# Check if the issue is still open with explicit repository
gh issue view 1749 --repo Altinn/dialogporten --json state,title

Length of output: 129

tests/Digdir.Domain.Dialogporten.Application.Integration.Tests/Features/V1/ServiceOwner/Transmissions/Commands/CreateTransmissionTests.cs (2)

40-44: LGTM! Good test coverage for both current and deprecated media types.

The conversion from [Fact] to [Theory] with multiple test cases ensures that both the current EmbeddableMarkdown and deprecated EmbeddableMarkdownDeprecated media types are properly tested.


85-89: LGTM! Consistent test coverage for error cases.

The error case test has been properly updated to verify that HTTPS validation works consistently for both current and deprecated media types.

src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/DialogContentInputConverter.cs (1)

53-53: LGTM! Proper handling of deprecated media types.

The use of ConvertIfDeprecatedMediaType() ensures consistent handling of deprecated media types during conversion.

src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/TransmissionContentInputConverter.cs (1)

56-56: LGTM! Consistent handling of deprecated media types.

The use of ConvertIfDeprecatedMediaType() aligns with the implementation in DialogContentInputConverter.

@oskogstad oskogstad changed the title feat(app): Clarifying changes to FCE MediaTypes feat(app): Change FCE MediaTypes Feb 3, 2025
@oskogstad oskogstad force-pushed the feat/change-fce-media-types branch from aeb435b to 27bc81b Compare February 3, 2025 09:36
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: 1

🧹 Nitpick comments (1)
src/Digdir.Domain.Dialogporten.Infrastructure/Persistence/Migrations/20250203085824_ChangeFCEMediaTypes.cs (1)

27-51: Consider adding safety measures to the content updates.

The SQL updates are well-structured but consider adding:

  1. Explicit transaction handling if not managed by EF Core.
  2. Error logging for failed updates.
  3. A count of affected rows for verification.

Here's a suggested enhancement:

 migrationBuilder.Sql("""
                      -- Update MediaType in DialogContent table
+                     DO $$ 
+                     DECLARE 
+                         affected_rows INTEGER;
+                     BEGIN
                      UPDATE public."DialogContent"
                      SET "MediaType" = CASE
                          WHEN "MediaType" = 'application/vnd.dialogporten.frontchannelembed+json;type=html'
                          THEN 'application/vnd.dialogporten.frontchannelembed-url;type=text/html'
                          WHEN "MediaType" = 'application/vnd.dialogporten.frontchannelembed+json;type=markdown'
                          THEN 'application/vnd.dialogporten.frontchannelembed-url;type=text/markdown'
                          ELSE "MediaType"
                      END
                      WHERE "MediaType" IN ('application/vnd.dialogporten.frontchannelembed+json;type=html',
                         'application/vnd.dialogporten.frontchannelembed+json;type=markdown');
+                     GET DIAGNOSTICS affected_rows = ROW_COUNT;
+                     RAISE NOTICE 'Updated % rows in DialogContent', affected_rows;
                      
                      -- Update MediaType in DialogTransmissionContent table
                      UPDATE public."DialogTransmissionContent"
                      SET "MediaType" = CASE
                          WHEN "MediaType" = 'application/vnd.dialogporten.frontchannelembed+json;type=html'
                          THEN 'application/vnd.dialogporten.frontchannelembed-url;type=text/html'
                          WHEN "MediaType" = 'application/vnd.dialogporten.frontchannelembed+json;type=markdown'
                          THEN 'application/vnd.dialogporten.frontchannelembed-url;type=text/markdown'
                          ELSE "MediaType"
                      END
                      WHERE "MediaType" IN ('application/vnd.dialogporten.frontchannelembed+json;type=html',
                      'application/vnd.dialogporten.frontchannelembed+json;type=markdown');
+                     GET DIAGNOSTICS affected_rows = ROW_COUNT;
+                     RAISE NOTICE 'Updated % rows in DialogTransmissionContent', affected_rows;
+                     END $$;
                      """);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 73fb725 and 27bc81b.

⛔ Files ignored due to path filters (2)
  • src/Digdir.Domain.Dialogporten.Infrastructure/Persistence/Migrations/20250203085824_ChangeFCEMediaTypes.Designer.cs is excluded by !**/Migrations/**/*Designer.cs
  • src/Digdir.Domain.Dialogporten.Infrastructure/Persistence/Migrations/DialogDbContextModelSnapshot.cs is excluded by !**/Migrations/DialogDbContextModelSnapshot.cs
📒 Files selected for processing (2)
  • src/Digdir.Domain.Dialogporten.Domain/MediaTypes.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.Infrastructure/Persistence/Migrations/20250203085824_ChangeFCEMediaTypes.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Digdir.Domain.Dialogporten.Domain/MediaTypes.cs
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Dry run deploy apps / Deploy service to test
  • GitHub Check: Dry run deploy apps / Deploy graphql to test
  • GitHub Check: Dry run deploy apps / Deploy web-api-so to test
  • GitHub Check: Dry run deploy apps / Deploy web-api-eu to test
  • GitHub Check: build / build-and-test
🔇 Additional comments (2)
src/Digdir.Domain.Dialogporten.Infrastructure/Persistence/Migrations/20250203085824_ChangeFCEMediaTypes.cs (2)

1-9: LGTM! Migration setup follows best practices.

The migration class is properly structured with appropriate naming and attributes.


13-26: Verify ID assumptions and document breaking changes.

The migration assumes specific IDs exist in the tables. While this is likely correct based on the PR context, consider:

  1. Adding a safety check for the existence of these IDs.
  2. Documenting this as a breaking change in the API documentation since media types are changing.

Let's verify the ID assumptions:

✅ Verification successful

ID Existence & Breaking Change Documentation

  • The investigation shows that IDs 6 (for DialogContentType) and 3 (for DialogTransmissionContentType) are used repeatedly in our migration seed data. This confirms that the migration’s assumptions are in line with the established data.
  • Although the IDs appear to be stable across migrations, consider adding a safeguard (or explicit check) in the migration or at the DB level to ensure these records exist at runtime.
  • Finally, document the breaking change (specifically the media type update) clearly in API release notes and any related documentation to alert consumers of the change.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the IDs exist in the tables and check for any references

# Search for ID definitions and references
rg -A 5 "Id = 6|Id = 3" --type cs

# Search for any existing documentation about these IDs
fd -e md -e txt . | xargs rg "DialogContentType.*6|DialogTransmissionContentType.*3"

Length of output: 79491

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: 0

🧹 Nitpick comments (2)
src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/ContentValueDtoValidator.cs (2)

24-26: Consider caching the allowed media types list.

While the backwards compatibility approach is correct, using Append() creates a new sequence on each validation. Consider caching the combined list as a field to improve performance.

+    private readonly string[] _allowedMediaTypes;
+
+    public ContentValueDtoValidator(DialogTransmissionContentType contentType)
+    {
+        _allowedMediaTypes = contentType.AllowedMediaTypes
+            .Append(MediaTypes.EmbeddableMarkdownDeprecated)
+            .ToArray();
+
         RuleFor(x => x.MediaType)
             .NotEmpty()
-            .Must(value => value is not null && contentType.AllowedMediaTypes
-                // Manually adding this for backwards compatibility, until correspondence is updated and deployed
-                .Append(MediaTypes.EmbeddableMarkdownDeprecated).Contains(value))
+            .Must(value => value is not null && _allowedMediaTypes.Contains(value))

78-84: Consider caching media type lists and documenting removal timeline.

The implementation correctly handles backwards compatibility but has some areas for improvement:

  1. Multiple Append() calls create new sequences on each validation
  2. The temporary nature of these changes should be documented with a timeline or tracking issue
+    // Cache commonly used media type combinations
+    private static readonly string[] _legacyMainContentReferenceTypes = DialogContentType
+        .Values.MainContentReference.AllowedMediaTypes
+        .Append(MediaTypes.LegacyEmbeddableHtml)
+        .Append(MediaTypes.EmbeddableMarkdownDeprecated)
+        .Append(MediaTypes.LegacyEmbeddableHtmlDeprecated)
+        .ToArray();
+
+    private static readonly string[] _mainContentReferenceTypes = DialogContentType
+        .Values.MainContentReference.AllowedMediaTypes
+        .Append(MediaTypes.EmbeddableMarkdownDeprecated)
+        .ToArray();

     [SuppressMessage("Style", "IDE0072:Add missing cases")]
     private static string[] GetAllowedMediaTypes(DialogContentType contentType, IUser? user)
         => contentType.Id switch
         {
             DialogContentType.Values.AdditionalInfo when UserHasLegacyHtmlScope(user)
                 => contentType.AllowedMediaTypes.Append(MediaTypes.LegacyHtml).ToArray(),
             DialogContentType.Values.MainContentReference when UserHasLegacyHtmlScope(user)
-                => contentType.AllowedMediaTypes.Append(MediaTypes.LegacyEmbeddableHtml)
-                    // Manually adding this for backwards compatibility, until correspondence is updated and deployed
-                    .Append(MediaTypes.EmbeddableMarkdownDeprecated)
-                    .Append(MediaTypes.LegacyEmbeddableHtmlDeprecated).ToArray(),
+                => _legacyMainContentReferenceTypes,
             DialogContentType.Values.MainContentReference
-                => contentType.AllowedMediaTypes.Append(MediaTypes.EmbeddableMarkdownDeprecated).ToArray(),
+                => _mainContentReferenceTypes,
             _ => contentType.AllowedMediaTypes
         };

Also, consider adding a TODO comment with more details:

// TODO: Remove deprecated media types after correspondence service is updated
// Tracking issue: #1728
// Expected removal: Q2 2025
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 27bc81b and f3c2878.

📒 Files selected for processing (2)
  • src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/ContentValueDtoValidator.cs (2 hunks)
  • src/Digdir.Domain.Dialogporten.Domain/MediaTypes.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Digdir.Domain.Dialogporten.Domain/MediaTypes.cs
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Dry run deploy apps / Deploy graphql to test
  • GitHub Check: build / build-and-test

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: 1

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f3c2878 and 4b9df43.

📒 Files selected for processing (4)
  • src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/ContentValueDtoValidator.cs (2 hunks)
  • src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/DialogContentInputConverter.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/TransmissionContentInputConverter.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.Domain/MediaTypes.cs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/ContentValueDtoValidator.cs
  • src/Digdir.Domain.Dialogporten.Domain/MediaTypes.cs
🔇 Additional comments (5)
src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/DialogContentInputConverter.cs (3)

13-13: Address the TODO comment during this media type refactoring.

Since this PR involves significant changes to media types and content handling, it would be a good time to discuss and resolve this TODO with the team. This could help ensure the new media type implementation aligns with the team's long-term vision.

Would you like me to create an issue to track this discussion item?


24-68: LGTM! The converter implementation is robust and performant.

The implementation demonstrates good practices:

  • Proper null handling
  • Efficient property caching
  • Clean separation of concerns

53-53: Verify the MapDeprecatedMediaType extension method.

The change correctly handles the migration of deprecated media types, which aligns with the PR's objective of implementing a two-step transition process.

Let's verify the extension method implementation:

✅ Verification successful

The MapDeprecatedMediaType extension method is verified.

  • The extension method is defined in src/Digdir.Domain.Dialogporten.Domain/MediaTypes.cs (line 24) with the expected signature.
  • Its usage in both DialogContentInputConverter.cs and TransmissionContentInputConverter.cs aligns with the intended functionality for handling deprecated media types.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the MapDeprecatedMediaType extension method exists and check its implementation

# Search for the extension method definition
ast-grep --pattern 'public static string MapDeprecatedMediaType(this string mediaType)'

# Search for any tests covering this method
rg -l "MapDeprecatedMediaType.*Test"

Length of output: 128


Script:

#!/bin/bash
# Description: Search the entire repository for any occurrence of "MapDeprecatedMediaType" 
# to verify if the extension method is defined somewhere or used elsewhere in the code.

rg -n "MapDeprecatedMediaType"

Length of output: 520

src/Digdir.Domain.Dialogporten.Application/Features/V1/Common/Content/TransmissionContentInputConverter.cs (2)

31-70: Implementation looks solid.

The media type mapping change is well-integrated into the existing conversion logic. The code maintains proper null handling, immutability, and uses efficient property caching.


13-17: Consider addressing the TODO comment as part of this PR.

Since both this converter and DialogContentInputConverter now handle media type mapping similarly, this might be an opportune time to combine them as suggested in the comment. This would help maintain consistency in media type handling across the codebase.

Let's check if DialogContentInputConverter has similar structure:

✅ Verification successful

Please consider addressing the existing TODO comment in both converters.

Both the TransmissionContentInputConverter and the DialogContentInputConverter contain nearly identical mapping logic—including handling the mapping for deprecated media types—and both feature a TODO suggesting a potential merge. This consistency indicates that there is an opportunity to consolidate the shared logic, which would help maintain consistency and reduce duplicate code in the project.

  • Verify if combining these converters is acceptable within the current architecture.
  • If so, refactor and merge the common logic for media type mapping to streamline future maintenance.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find and examine DialogContentInputConverter implementation
rg -l "DialogContentInputConverter" | xargs cat

Length of output: 15658

@oskogstad oskogstad merged commit ef4e0a4 into main Feb 3, 2025
23 checks passed
@oskogstad oskogstad deleted the feat/change-fce-media-types branch February 3, 2025 17:35
oskogstad pushed a commit that referenced this pull request Feb 3, 2025
🤖 I have created a release *beep* *boop*
---


##
[1.48.0](v1.47.8...v1.48.0)
(2025-02-03)


### Features

* **app:** Change FCE MediaTypes
([#1729](#1729))
([ef4e0a4](ef4e0a4))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
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