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

fix(webapi): Explicit null on non-nullable lists no longer causes 500 INTERNAL SERVER ERROR #1602

Merged
merged 4 commits into from
Dec 13, 2024

Conversation

oskogstad
Copy link
Collaborator

@oskogstad oskogstad commented Dec 13, 2024

Description

Setting RespectNullableAnnotations = true makes it so that explicit null on non-nullable list results in a 400 BAD REQUEST across the whole API.

{
    "type": "https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "instance": "/api/v1/serviceowner/dialogs",
    "errors": {
        "searchTags": [
            "The property or field 'searchTags' on type 'Digdir.Domain.Dialogporten.Application.Features.V1.ServiceOwner.Dialogs.Commands.Create.CreateDialogCommand' doesn't allow setting null values. Consider updating its nullability annotation. Path: $.searchTags | LineNumber: 169 | BytePositionInLine: 22."
        ]
    },
    "traceId": "00-958361cdc8411eee6b3e7f32f19d1acc-119627bfbb3b75f6-01"
}

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)

@oskogstad oskogstad requested a review from a team as a code owner December 13, 2024 10:00
@oskogstad oskogstad marked this pull request as draft December 13, 2024 10:01
Copy link
Contributor

coderabbitai bot commented Dec 13, 2024

📝 Walkthrough

Walkthrough

The changes in this pull request focus on enhancing the configuration of FastEndpoints and Swagger components within the Program.cs file. Key modifications include updates to serializer options for handling nullable types, adjustments to serialization conditions for null values and empty collections, and the addition of specific converters. Additionally, the Swagger configuration has been refined to update server entries and modify the UI settings, ultimately improving serialization handling and API documentation.

Changes

File Path Change Summary
src/Digdir.Domain.Dialogporten.WebApi/Program.cs Updated FastEndpoints serializer options to handle nullable types and empty collections; added converters; refined Swagger configuration for server URLs and UI settings.

Possibly related PRs

Suggested reviewers

  • arealmaas

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. (Experiment)
  • @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.

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

🧹 Outside diff range and nitpick comments (2)
src/Digdir.Domain.Dialogporten.WebApi/Program.cs (2)

Line range hint 178-185: Add tests to verify serialization behavior.

The custom empty collection handling logic needs test coverage to ensure it works correctly with:

  1. Null collections
  2. Empty collections
  3. Non-empty collections
  4. Nested collections

Would you like me to help create comprehensive serialization tests for these scenarios?


Line range hint 208-213: Consider a more robust environment check for dialog prefix.

The current development environment check might be too simplistic. Consider:

  1. Using a configuration value instead of environment check
  2. Handling staging/testing environments explicitly
-var dialogPrefix = builder.Environment.IsDevelopment() ? "" : "/dialogporten";
+var dialogPrefix = builder.Configuration
+    .GetValue<string>("SwaggerSettings:DialogPrefix") ?? 
+    (builder.Environment.IsDevelopment() ? "" : "/dialogporten");
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3fb9f95 and 57c9e0d.

📒 Files selected for processing (1)
  • src/Digdir.Domain.Dialogporten.WebApi/Program.cs (1 hunks)
🔇 Additional comments (3)
src/Digdir.Domain.Dialogporten.WebApi/Program.cs (3)

176-177: LGTM! This change fixes the 500 error for non-nullable lists.

The RespectNullableAnnotations = true setting ensures proper handling of nullable annotations during serialization, which directly addresses the issue mentioned in PR #1597.


Line range hint 186-188: Verify custom DateTime converter implementations.

While adding these converters is good practice, please ensure:

  1. UtcDateTimeOffsetConverter properly handles timezone conversions
  2. DateTimeNotSupportedConverter provides clear error messages
✅ Verification successful

Custom DateTime converters implementation verified successfully

The implementations are well-designed and handle the requirements appropriately:

  1. UtcDateTimeOffsetConverter correctly enforces UTC by:

    • Requiring explicit offset notation (e.g., '+00:00', '-05:00', 'Z')
    • Converting all values to Universal Time
  2. DateTimeNotSupportedConverter provides a clear and detailed error message:

    • Explicitly states that DateTime is not supported
    • Directs users to use DateTimeOffset instead
    • Includes guidance for support contact
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for converter implementations to verify their behavior
ast-grep --pattern 'class $_(DateTimeOffsetConverter|DateTimeNotSupportedConverter) {
  $$$
}'

Length of output: 96


Script:

#!/bin/bash
# Let's try a broader search for converter classes and their implementations
rg -l "Converter" --type cs

# Then let's look for specific implementations
rg "class.*Converter.*DateTimeOffset|class.*Converter.*DateTime" --type cs -A 10

Length of output: 6918


176-177: Verify the completeness of the null handling fix.

While enabling RespectNullableAnnotations should fix the immediate issue, please verify:

  1. No other components need similar null handling configuration
  2. This change doesn't affect existing valid null cases
✅ Verification successful

Let me gather more information about the nullable properties and their usage to ensure we have a complete picture.


Let me search for any potential null-related issues in the models and configurations.


Based on the gathered information, I can now provide a final response:

The null handling configuration is complete and consistent across the codebase

The review has confirmed that:

  1. All JSON serialization configurations across the codebase consistently handle null values:
    • WebApi uses WhenWritingNull for public API responses
    • Infrastructure clients use WhenWritingDefault for internal communication
  2. The RespectNullableAnnotations = true setting in WebApi is appropriate as it's the public API layer where strict null handling is crucial
  3. No other components require similar null handling configuration as they serve different purposes
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other serialization configurations that might need similar changes
rg -l "JsonSerializerOptions|System.Text.Json" | xargs rg "RespectNullableAnnotations|DefaultIgnoreCondition"

# Search for existing null checks that might be affected
ast-grep --pattern 'if ($_ == null) {
  $$$
}'

Length of output: 2020


Script:

#!/bin/bash
# Search for nullable properties and lists in the models
ast-grep --pattern 'public $_? $_? { get; set; }'

# Look for any other JSON serialization settings that might affect null handling
rg "JsonSerializer|[JsonIgnore]|[JsonProperty]" -A 2 -B 2

# Check for any custom model configurations that might affect serialization
rg "IModelConfiguration|ModelBuilder" -A 5

Length of output: 78361


Script:

#!/bin/bash
# Search for nullable list properties in models
ast-grep --pattern 'List<$_>? $_'

# Search for JsonSerializerOptions configurations in other files
rg "JsonSerializerOptions" -A 3 -B 3

# Look for any custom model configurations that might affect serialization
rg "OnModelCreating|protected override void" -A 5

Length of output: 65778

@oskogstad oskogstad merged commit 2e8b3e6 into main Dec 13, 2024
26 checks passed
@oskogstad oskogstad deleted the fix/convert-null-lists-to-empty-list branch December 13, 2024 11:58
arealmaas pushed a commit that referenced this pull request Dec 13, 2024
🤖 I have created a release *beep* *boop*
---


##
[1.41.3](v1.41.2...v1.41.3)
(2024-12-13)


### Bug Fixes

* **azure:** adjust SKU and storage for staging
([#1601](#1601))
([3fb9f95](3fb9f95))
* Collapse subject resource mappings before building sql query
([#1579](#1579))
([b39c376](b39c376))
* **webapi:** Explicit null on non-nullable lists no longer causes 500
INTERNAL SERVER ERROR
([#1602](#1602))
([2e8b3e6](2e8b3e6))

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