Skip to content

feat!: Replace HeaderDecode with HeaderCodec to allow customization on encoding as well - #43

Merged
nielsenko merged 7 commits into
serverpod:mainfrom
nielsenko:header-codec
Apr 9, 2025
Merged

nielsenko merged 7 commits into
serverpod:mainfrom
nielsenko:header-codec

Conversation

@nielsenko

@nielsenko nielsenko commented Apr 4, 2025 •

Copy link
Copy Markdown
Collaborator

Description

Currently you cannot customize encoding of header values with when constructing a HeaderAccessor, instead you have to either implement the TypedHeader interface or ensure .toString does the right thing.

With this PR this is no longer the case. Encoding will still default to the existing approach with this PR, but that may change later.

  • feat!: Replace HeaderDecode with HeaderCodec to allow customization on encoding as well

Related Issues

Fix: #44

Pre-Launch Checklist

Please ensure that your PR meets the following requirements before submitting:

  • This update focuses on a single feature or bug fix. (For multiple fixes, please submit separate PRs.)
  • I have read and followed the Dart Style Guide and formatted the code using dart format.
  • I have referenced at least one issue this PR fixes or is related to.
  • I have updated/added relevant documentation (doc comments with ///), ensuring consistency with existing project documentation.
  • I have added new tests to verify the changes.
  • All existing and new tests pass successfully.
  • I have documented any breaking changes below.

Breaking Changes

  • Includes breaking changes.
  • No breaking changes.

The interface of HeaderAccessor<T> changes

Summary by CodeRabbit

  • New Features

    • Introduced custom header support with dedicated procedures for encoding and decoding.
  • Refactor

    • Migrated header processing to a unified codec-based approach that enhances type safety, consistency, and caching.
  • Tests

    • Expanded test coverage to verify immediate header value retrieval and proper handling of both single and multi-value headers, including the integration of a new Custom class.

@coderabbitai

coderabbitai Bot commented Apr 4, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

The changes primarily refactor how headers are processed by replacing the old decoder implementations with a unified codec-based approach. The HeaderAccessor class now leverages a strongly typed HeaderCodec for both encoding and decoding header values with an updated caching mechanism. Alongside these modifications, new codec abstractions and implementations (_SingleDecodeHeaderCodec and _MultiDecodeHeaderCodec) are introduced, while the legacy HeaderDecoder classes have been removed. The test suite has been augmented to verify these changes, including new tests for a custom header type and immediate header value updates.

Changes

File(s) Change Summary
lib/src/headers/header_accessor.dart Updated HeaderAccessor to use HeaderCodec<T> instead of HeaderDecoder<T>, revised caching, and introduced new codec types: Codec, HeaderCodec, _SingleDecodeHeaderCodec, and _MultiDecodeHeaderCodec.
lib/src/headers/headers.dart Replaced all instances of HeaderDecoderSingle and HeaderDecoderMulti with HeaderCodec.single and HeaderCodec respectively, updating various header definitions.
test/headers/headers_accessor_test.dart, test/relic_server_serve_test.dart Modified tests to use HeaderCodec instead of the old decoder types; added a new Custom class with associated factory and encoding methods, and enhanced tests for immediate header updates and caching behavior.

Possibly related PRs


🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@codecov

codecov Bot commented Apr 4, 2025 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 88.11189% with 17 lines in your changes missing coverage. Please review.

Project coverage is 79.08%. Comparing base (6df02d4) to head (60c5601).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
lib/src/headers/header_accessor.dart 88.23% 2 Missing ⚠️
.../headers/typed/headers/accept_encoding_header.dart 50.00% 2 Missing ⚠️
.../headers/typed/headers/accept_language_header.dart 50.00% 2 Missing ⚠️
.../typed/headers/content_security_policy_header.dart 60.00% 2 Missing ⚠️
lib/src/headers/typed/headers/cookie_header.dart 50.00% 2 Missing ⚠️
...eaders/typed/headers/permission_policy_header.dart 60.00% 2 Missing ⚠️
lib/src/headers/typed/headers/upgrade_header.dart 50.00% 2 Missing ⚠️
...c/headers/typed/headers/etag_condition_header.dart 75.00% 1 Missing ⚠️
lib/src/headers/typed/headers/etag_header.dart 66.66% 1 Missing ⚠️
lib/src/headers/typed/headers/te_header.dart 66.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #43      +/-   ##
==========================================
+ Coverage   78.53%   79.08%   +0.55%     
==========================================
  Files          70       70              
  Lines        2273     2309      +36     
  Branches     1181     1219      +38     
==========================================
+ Hits         1785     1826      +41     
+ Misses        488      483       -5     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@nielsenko
nielsenko requested a review from SandPod April 4, 2025 15:09
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 4, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (4)
test/headers/headers_accessor_test.dart (2)

18-22: Consider acknowledging unused parse argument.

factory Custom.parse(String s) ignores s, always returning a new Custom. Confirm that this is intentional.


232-242: Double-check decode logic for the custom class.

Since Custom.parse returns a new instance in general, you rely on caching to preserve identical references here. If you want parse to reflect the raw input, consider using the input string. Otherwise, this test is fine as-is for demonstration.

lib/src/headers/header_accessor.dart (2)

37-39: Refactoring from a decode field to a codec field is a solid design choice.

Bringing encoding and decoding together into HeaderCodec improves future extensibility and clarity.

Could consider adding doc comments explaining how the codec can be customized (e.g., usage of HeaderCodec.single vs. HeaderCodec).

Also applies to: 47-47


115-118: Introduction of PointTuple and Point extension type is interesting.

This appears to be a harmless placeholder. Confirm if it’s only for demonstration or if tests will cover it later.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b0c6140 and 246178f.

📒 Files selected for processing (4)
  • lib/src/headers/header_accessor.dart (7 hunks)
  • lib/src/headers/headers.dart (1 hunks)
  • test/headers/headers_accessor_test.dart (2 hunks)
  • test/relic_server_serve_test.dart (1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
lib/src/headers/header_accessor.dart

[warning] 152-152: lib/src/headers/header_accessor.dart#L152
Added line #L152 was not covered by tests

🔇 Additional comments (20)
test/relic_server_serve_test.dart (1)

131-131: Upgrade to HeaderCodec looks good.

Switching from HeaderDecoderMulti to HeaderCodec is aligned with the new codec-based approach for header processing. No issues spotted here.

test/headers/headers_accessor_test.dart (6)

10-10: Use of HeaderCodec.single(parseInt) is valid.

Adopting HeaderCodec.single(parseInt) cleanly replaces the previous single-value decoder.


15-15: Use of HeaderCodec(parseStringList) is valid.

Replacing the multi-value decoder with the new codec-based approach follows the intended model.


24-25: New _customClass accessor aligns with the codec approach.

This is a proper demonstration of using a custom parser and encoder.


33-33: Accessor getter usage seems consistent.

Invoking _anInt[this]() aligns with your accessor pattern for immediate retrieval.


158-171: Validation of immediate readability after setting headers is appreciated.

The test ensures that the updated value can be accessed without re-fetching or re-building headers. This is good coverage.


173-230: Cache behavior testing is well structured.

Verifying decoder call counts helps ensure we avoid redundant parsing. This is thorough coverage.

lib/src/headers/header_accessor.dart (12)

31-32: Casting Expando to Expando<T> is acceptable.

This approach is safe as long as each HeaderAccessor is used with a consistent type parameter. No immediate problems spotted.


73-77: Caching logic ensures efficient repeated header reads.

Using _cache[raw] to avoid repeated parsing is a good performance optimization.


97-107: setValueOn correctly primes the cache.

By encoding and storing the result in _cache, subsequent reads avoid unnecessary decoding.


121-121: New Codec interface is well-defined.

The separation of decode and encode fosters clarity and maintainability.


125-144: HeaderCodec as a sealed class is neatly structured.

The distinction between _MultiDecodeHeaderCodec and _SingleDecodeHeaderCodec accommodates different usage patterns.


146-157: _MultiDecodeHeaderCodec constructor ensures fallback to _commonEncode.

Implementation details look coherent for multi-value decoding scenarios.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 152-152: lib/src/headers/header_accessor.dart#L152
Added line #L152 was not covered by tests


149-152: Line #152 lacks test coverage.

Static analysis reports line 152 (super._(encode ?? _commonEncode)) is uncovered. Consider adding a test that supplies a custom encode function to _MultiDecodeHeaderCodec.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 152-152: lib/src/headers/header_accessor.dart#L152
Added line #L152 was not covered by tests


158-169: _SingleDecodeHeaderCodec effectively handles single-value headers.

Replacing the old single decoder approach with a dedicated codec improves architecture consistency.


177-177: Header extension type is clearly defined.

This extension approach keeps runtime overhead low while adding typed header capabilities.


198-198: Delegation to _accessor.setValueOn is straightforward.

Keeps the method consistent with the rest of the typed header logic.


223-223: Robust error handling for invalid headers.

Appropriately throws InvalidHeaderException for underlying parse issues.


233-241: _commonEncode covers typical data shapes gracefully.

Providing fallback to toString() ensures consistent encoding for objects.

lib/src/headers/headers.dart (1)

67-411: Consistent and complete migration from HeaderDecoder to HeaderCodec

The changes systematically replace all instances of HeaderDecoderSingle with HeaderCodec.single and all instances of HeaderDecoderMulti with HeaderCodec throughout the file. This change aligns with the PR objective to enhance customization capabilities for header value encoding.

The migration is thorough and consistent across all header definitions including date-related headers, general headers, request headers, response headers, and security headers.

@nielsenko

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 4, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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)
lib/src/headers/header_accessor.dart (1)

31-32: Potential type-safety concern in _cache.
Casting from Expando to Expando<T> presumes each accessor is used with a unique type. It should be safe if you never reuse the same accessor for conflicting types, but be aware of the runtime cast.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 246178f and 321a190.

📒 Files selected for processing (4)
  • lib/src/headers/header_accessor.dart (7 hunks)
  • lib/src/headers/headers.dart (1 hunks)
  • test/headers/headers_accessor_test.dart (2 hunks)
  • test/relic_server_serve_test.dart (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/relic_server_serve_test.dart
🧰 Additional context used
🪛 GitHub Check: codecov/patch
lib/src/headers/header_accessor.dart

[warning] 179-179: lib/src/headers/header_accessor.dart#L179
Added line #L179 was not covered by tests

🔇 Additional comments (18)
test/headers/headers_accessor_test.dart (8)

10-10: Excellent use of HeaderCodec.single(parseInt).
This aligns perfectly with the new codec-based approach for parsing single-value headers. No concerns here.


15-15: Smooth transition to HeaderCodec(parseStringList).
Using the multi-value codec is appropriate for string lists. Looks good.


18-22: Test utility class for custom headers is fine.
Returning a hard-coded 'foo' indicates this is purely for demonstration or testing. If a meaningful parse/encode is desired in production, consider leveraging the provided input. Otherwise, no issues.


24-25: New _customClass accessor looks correct.
This properly demonstrates how to integrate a custom type using HeaderCodec.single.


33-33: Getter anInt extension for mutable headers
Consistent usage of the accessor. No issues found.


159-172: Immediate retrieval test offers good coverage.
It confirms that multiple updates (including raw header writes) reflect immediately when reading the typed value. Great job.


173-230: Thorough caching tests.
This group of tests ensures decode is called once per distinct update, validating the caching mechanism. No problems noted.


232-241: Verifying custom class integration.
This test checks encoding and decoding with a custom type, ensuring the same instance is reused. Looks good.

lib/src/headers/header_accessor.dart (9)

39-39: Migration to a codec field is a breaking change.
Externally, anything using the old decode field must be updated. Verify all references in your codebase and docs are adjusted accordingly.


47-47: Constructor refactor looks straightforward.
This addition neatly supports the new codec approach.


73-77: Logic for retrieving and caching decoded values is solid.
Preventing repeated parsing is a great optimization.


97-107: Efficient cache priming in setValueOn.
Retaining the old cache entries is correct, as the Expando’s lifetime is tied to the headers object.


115-126: Introduction of Codec<T, StorageT> is clear and coherent.
Defining a simple, bidirectional interface for decoding/encoding fosters clean abstractions.


128-145: HeaderCodec elegantly extends Codec.
Specializing for Iterable<String> aligns perfectly with multi-value header semantics.


173-183: Untested fallback on _commonEncode.
Line 179’s coverage may be lacking if no test calls the constructor with a null encode. Consider adding a test to ensure _MultiDecodeHeaderCodec is initialized without a custom encoder.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 179-179: lib/src/headers/header_accessor.dart#L179
Added line #L179 was not covered by tests


185-195: _SingleDecodeHeaderCodec is straightforward.
Good approach for single header values.


260-268: Pattern matching in _commonEncode is well-structured.
This gracefully handles a variety of object types, defaulting to toString() for unknowns.

lib/src/headers/headers.dart (1)

69-69: Consistent refactor to HeaderCodec and HeaderCodec.single.
All these lines adopt the new codec-based parsing approach, replacing the legacy decoders. The changes look correct and consistent, preserving single vs. multi-value logic as needed.

Also applies to: 74-74, 79-79, 84-84, 89-89, 95-95, 100-100, 105-105, 111-111, 116-116, 121-121, 126-126, 131-131, 136-136, 141-141, 146-146, 151-151, 156-156, 161-161, 166-166, 171-171, 176-176, 181-181, 186-186, 191-191, 196-196, 201-201, 206-206, 211-211, 218-218, 223-223, 229-229, 235-235, 240-240, 245-245, 250-250, 255-255, 260-260, 265-265, 270-270, 275-275, 280-280, 285-285, 290-290, 295-295, 300-300, 306-306, 312-312, 317-317, 322-322, 327-327, 332-332, 337-337, 341-341, 346-346, 351-351, 356-356, 361-361, 367-367, 373-373, 378-378, 383-383, 388-388, 393-393, 399-399, 405-405, 411-411

@nielsenko nielsenko self-assigned this Apr 4, 2025
@nielsenko nielsenko mentioned this pull request Apr 7, 2025
7 of 9 tasks
@nielsenko
nielsenko marked this pull request as ready for review April 7, 2025 06:32

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Changes look good, just a minor fix with the comments.

But can't we remove the TypedHeader class now? Doesn't seem like that interface is needed?

Comment thread lib/src/headers/header_accessor.dart Resolved
@nielsenko
nielsenko force-pushed the header-codec branch 2 times, most recently from 87bfcf3 to 019fbc5 Compare April 8, 2025 07:34
@nielsenko

Copy link
Copy Markdown
Collaborator Author

Changes look good, just a minor fix with the comments.

But can't we remove the TypedHeader class now? Doesn't seem like that interface is needed?

I did. It was still a somewhat larger undertaking, but now it has been removed

@nielsenko
nielsenko requested a review from SandPod April 8, 2025 07:52

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM!

Could be good to remove toHeaderString from the public interface as well.

…th InternalEx extension class for internal use
@nielsenko

Copy link
Copy Markdown
Collaborator Author

LGTM!

Could be good to remove toHeaderString from the public interface as well.

Done

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.

Customize encoder path

2 participants