Repository navigation
refactor: Introduce WildcardListHeader<T> base-class - #159
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the 📝 WalkthroughWalkthroughRefactors multiple typed headers to extend a new generic WildcardListHeader, centralizing wildcard/list parsing and encoding. Each header’s codec now uses private _parse/_encode helpers. Several classes replace stored fields with getters backed by the base class. Tests are updated for constructor const-ness and error message text. Changes
Sequence Diagram(s)sequenceDiagram
participant Client as Caller
participant Codec as HeaderCodec
participant H as TypedHeader (extends WildcardListHeader)
participant Base as WildcardListHeader<T>
Note over Client,Codec: Parsing flow
Client->>Codec: decode(values)
Codec->>H: _parse(values)
H->>Base: parse(values, elementParser)
alt Single "*"
Base-->>H: wildcard()
else List of tokens
Base-->>H: H(values)
end
H-->>Codec: instance
Codec-->>Client: header instance
Note over Client,Codec: Encoding flow
Client->>Codec: encode(header)
Codec->>H: _encode(header)
H->>H: encodeHeader(header)
H->>Base: header.encode(elementEncoder)
Base-->>H: Iterable<String>
H-->>Codec: List<String>
Codec-->>Client: encoded values
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Pre-merge checks (1 passed, 2 warnings)❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
Pre-merge checks (2 passed, 1 warning)❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing Touches🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #159 +/- ##
==========================================
- Coverage 92.45% 91.84% -0.61%
==========================================
Files 84 85 +1
Lines 3153 3128 -25
Branches 1610 1620 +10
==========================================
- Hits 2915 2873 -42
- Misses 238 255 +17 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
715304e to
b3469cb
Compare
|
@CodeRabbit review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (13)
test/headers/typed/access_control_allow_headers_header_test.dart (1)
41-45: Align test description with new terminology (“values” not “headers”)Minor copy tweak to mirror the unified error text.
- 'a message that states the wildcard cannot be used with other headers', + 'a message that states the wildcard cannot be used with other values',lib/src/headers/typed/headers/wildcard_list_header.dart (2)
19-23: Enforce non-empty values at runtime, not just in assertsAsserts are skipped in production; allow-list constructors could slip through with an empty list. Add a runtime guard.
- WildcardListHeader(final List<T> values) - : assert(values.isNotEmpty, 'Values list cannot be empty'), - values = List.unmodifiable(values), - isWildcard = false; + WildcardListHeader(final List<T> values) + : assert(values.isNotEmpty, 'Values list cannot be empty'), + values = List.unmodifiable(values), + isWildcard = false { + if (this.values.isEmpty) { + throw ArgumentError('Values list cannot be empty'); + } + }
76-82: Minor generic shadowing in helperAvoid reusing the class’s type parameter name in the static helper for readability.
- static bool _listEquals<T>(final List<T> a, final List<T> b) { + static bool _listEquals<E>(final List<E> a, final List<E> b) {lib/src/headers/typed/headers/access_control_expose_headers_header.dart (1)
13-16: Guard against empty header lists at constructionMirror the base-class runtime check so direct .headers(...) calls can’t create invalid instances in production.
- AccessControlExposeHeadersHeader.headers( - {required final Iterable<String> headers}) - : super(List.from(headers)); + AccessControlExposeHeadersHeader.headers( + {required final Iterable<String> headers}) + : super(List.from(headers)) { + if (this.headers.isEmpty) { + throw ArgumentError('Headers list cannot be empty'); + } + }lib/src/headers/typed/headers/access_control_allow_methods_header.dart (2)
32-36: Confirm whether '*' is valid for Access-Control-Allow-MethodsSpecs commonly require an explicit list of methods; wildcard may be non-compliant. If '*' is not allowed, reject it in parse.
Apply this diff if wildcard must be disallowed:
- if (parsed.isWildcard) { - return const AccessControlAllowMethodsHeader.wildcard(); - } else { + if (parsed.isWildcard) { + throw const FormatException("Wildcard '*' is not permitted for Access-Control-Allow-Methods"); + } else { return AccessControlAllowMethodsHeader.methods(methods: parsed.values); }
39-46: Encode as a single comma-separated header value for consistencyMost list-type headers are serialized as one field with comma-separated items. Consider emitting one joined value.
- static List<String> encodeHeader( - final AccessControlAllowMethodsHeader header) { - return header.encode((final RequestMethod rm) => rm.value).toList(); - } + static List<String> encodeHeader( + final AccessControlAllowMethodsHeader header) { + return [header.encode((final RequestMethod rm) => rm.value).join(', ')]; + }lib/src/headers/typed/headers/accept_language_header.dart (3)
36-42: Prefer a single comma-separated header stringAlign encoding with common HTTP list serialization; emit one value instead of many.
- static List<String> encodeHeader(final AcceptLanguageHeader header) { - return header.encode((final LanguageQuality lq) => lq.encode()).toList(); - } + static List<String> encodeHeader(final AcceptLanguageHeader header) { + return [header.encode((final LanguageQuality lq) => lq.encode()).join(', ')]; + }
57-75: Make q-parameter parsing tolerant (case/spacing) and stricter by ABNFCurrent split on ';q=' misses variants like '; q=0.8' or uppercase 'Q'. Use a regex to parse robustly and validate precision.
- factory LanguageQuality.parse(final String value) { - final languageParts = value.split(';q='); - final language = languageParts[0].trim().toLowerCase(); - if (language.isEmpty) { - throw const FormatException('Invalid language'); - } - - double? quality; - if (languageParts.length > 1) { - final qualityValue = double.tryParse(languageParts[1].trim()); - if (qualityValue == null || qualityValue < 0 || qualityValue > 1) { - throw const FormatException('Invalid quality value'); - } - quality = qualityValue; - } - return LanguageQuality(language, quality); - } + factory LanguageQuality.parse(final String value) { + final re = RegExp( + r'^\s*([A-Za-z0-9*-]+)\s*(?:;\s*[qQ]\s*=\s*([0-9](?:\.[0-9]{0,3})?))?\s*$'); + final m = re.firstMatch(value); + if (m == null) { + throw const FormatException('Invalid language'); + } + final language = m.group(1)!.toLowerCase(); + final qStr = m.group(2); + double? quality; + if (qStr != null) { + final q = double.tryParse(qStr); + if (q == null || q < 0 || q > 1) { + throw const FormatException('Invalid quality value'); + } + quality = q; + } + return LanguageQuality(language, quality); + }
77-81: Normalize q formatting to max 3 decimals and trim trailing zerosProduces cleaner wire format and aligns with common weighting precision.
- String encode() { - return quality == 1.0 ? language : '$language;q=$quality'; - } + String encode() { + final q = quality ?? 1.0; + if (q == 1.0) return language; + final qStr = q.toStringAsFixed(3).replaceFirst(RegExp(r'\.?0+$'), ''); + return '$language;q=$qStr'; + }lib/src/headers/typed/headers/clear_site_data_header.dart (1)
88-90: Docstring contradicts implementationComment claims “returns a custom instance” but code throws. Fix the comment or implement custom values.
- /// If the value does not match any predefined types, it returns a custom instance. + /// If the value does not match any predefined types, a [FormatException] is thrown.lib/src/headers/typed/headers/access_control_allow_headers_header.dart (1)
39-46: Consider simplifying the encoding delegation.The double delegation pattern (
encodeHeader→_encode) seems unnecessary here. Since_encodesimply callsencodeHeader, you could directly useencodeHeaderin the codec.- static const codec = HeaderCodec(_parse, _encode); + static const codec = HeaderCodec(_parse, encodeHeader); static List<String> encodeHeader( final AccessControlAllowHeadersHeader header) { return header.encode((final String str) => str).toList(); } - - static List<String> _encode(final AccessControlAllowHeadersHeader header) { - return encodeHeader(header); - }lib/src/headers/typed/headers/accept_encoding_header.dart (1)
36-42: Consider simplifying the encoding delegation here as well.Similar to the previous file, the double delegation through
_encodeappears unnecessary.- static const codec = HeaderCodec(_parse, _encode); + static const codec = HeaderCodec(_parse, encodeHeader); static List<String> encodeHeader(final AcceptEncodingHeader header) { return header.encode((final EncodingQuality eq) => eq.encode()).toList(); } - - static List<String> _encode(final AcceptEncodingHeader header) { - return encodeHeader(header); - }lib/src/headers/typed/headers/etag_condition_header.dart (1)
47-53: Apply consistent encoding simplification.Both
IfMatchHeaderandIfNoneMatchHeaderhave the same double delegation pattern that could be simplified.For
IfMatchHeader:- static const codec = HeaderCodec(_parse, _encode); + static const codec = HeaderCodec(_parse, encodeHeader); static List<String> encodeHeader(final IfMatchHeader header) { return header.encode((final ETagHeader etag) => etag.encode()).toList(); } - - static List<String> _encode(final IfMatchHeader header) { - return encodeHeader(header); - }For
IfNoneMatchHeader:- static const codec = HeaderCodec(_parse, _encode); + static const codec = HeaderCodec(_parse, encodeHeader); static List<String> encodeHeader(final IfNoneMatchHeader header) { return header.encode((final ETagHeader etag) => etag.encode()).toList(); } - - static List<String> _encode(final IfNoneMatchHeader header) { - return encodeHeader(header); - }Also applies to: 86-92
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (11)
lib/src/headers/typed/headers/accept_encoding_header.dart(2 hunks)lib/src/headers/typed/headers/accept_language_header.dart(2 hunks)lib/src/headers/typed/headers/access_control_allow_headers_header.dart(1 hunks)lib/src/headers/typed/headers/access_control_allow_methods_header.dart(1 hunks)lib/src/headers/typed/headers/access_control_expose_headers_header.dart(1 hunks)lib/src/headers/typed/headers/clear_site_data_header.dart(2 hunks)lib/src/headers/typed/headers/etag_condition_header.dart(1 hunks)lib/src/headers/typed/headers/wildcard_list_header.dart(1 hunks)test/headers/header_test.dart(1 hunks)test/headers/typed/access_control_allow_headers_header_test.dart(1 hunks)test/static/if_none_match_test.dart(1 hunks)
🔇 Additional comments (20)
test/headers/typed/access_control_allow_headers_header_test.dart (1)
55-56: Updated error message assertion — LGTMMatches the new shared validation text from WildcardListHeader.
test/headers/header_test.dart (1)
696-699: Remove const on IfMatchHeader.etags — LGTMCorrectly reflects that etag condition headers’ list constructors are no longer const, while keeping inner ETagHeader const.
Run to catch any lingering const usages that would now be invalid:
#!/bin/bash # Find remaining const uses of list-based ETag condition headers. rg -nP -S 'const\s+IfNoneMatchHeader\.etags\(' rg -nP -S 'const\s+IfMatchHeader\.etags\('test/static/if_none_match_test.dart (1)
42-45: Drop const on IfNoneMatchHeader.etags — LGTMConsistent with the refactor; inner ETagHeader remains const.
lib/src/headers/typed/headers/access_control_expose_headers_header.dart (1)
30-39: Parsing delegation — LGTMClean delegation to the generic parser with an identity mapper; wildcard and non-wildcard cases mapped correctly.
lib/src/headers/typed/headers/access_control_allow_methods_header.dart (1)
26-27: Getter replacement looks goodReplacing a public field with a getter backed by the base
valuesis clean and keeps immutability semantics.lib/src/headers/typed/headers/clear_site_data_header.dart (1)
26-33: Quote stripping and de-duplication look goodHandles multiple header lines, trims quotes, and removes duplicates; default
toSet()keeps insertion order in Dart.lib/src/headers/typed/headers/access_control_allow_headers_header.dart (5)
1-2: LGTM! Clean import consolidation.The import changes align well with the new base class architecture, replacing multiple utility imports with the single
wildcard_list_header.dartimport.
8-8: Good architectural improvement with the generic base class.The refactoring to extend
WildcardListHeader<String>provides better code reuse and consistency across header implementations.
25-26: Good API preservation with the headers getter.The getter maintains backward compatibility while delegating to the base class's
valuesproperty. This is a clean approach to preserving the public API.
28-37: Well-structured parsing delegation.The parsing logic properly delegates to
WildcardListHeader.parsewith appropriate identity function for string values. The conditional construction based onisWildcardis clean and maintainable.
9-9: Verify the codec pattern consistency across all refactored headers.The codec now uses private static methods
_parseand_encode, which is a good encapsulation pattern. Let's verify this pattern is consistently applied across all refactored headers.#!/bin/bash # Verify that all header classes following the WildcardListHeader pattern use the same codec structure rg -A 2 "extends WildcardListHeader" --type dart | head -20 rg "static const codec = HeaderCodec\(_parse, _encode\)" --type dartlib/src/headers/typed/headers/accept_encoding_header.dart (4)
7-8: Excellent type-safe refactoring with EncodingQuality.Using
WildcardListHeader<EncodingQuality>provides strong typing while maintaining the wildcard functionality. The codec pattern is consistent with other refactored headers.
24-24: Good API preservation for backward compatibility.The
encodingsgetter maintains the existing public API while internally using the base class'svaluesproperty.
58-75: Well-implemented parsing with proper validation.The
EncodingQuality.parsefactory constructor includes good error handling for empty encodings and invalid quality values (range checking 0-1). The quality value parsing with optional;q=suffix is correct.
78-80: Clean encoding implementation.The
encode()method correctly handles the default quality value of 1.0 by omitting it from the output, which follows HTTP header best practices.lib/src/headers/typed/headers/etag_condition_header.dart (5)
6-6: Good use of sealed class for the hierarchy.Using
sealed classforETagConditionHeaderensures exhaustive matching and prevents external implementations while allowingIfMatchHeaderandIfNoneMatchHeaderto extend it.
8-11: Note the breaking change: constructors are no longer const.As mentioned in the PR objectives, the
ETagConditionHeader.etagsconstructor can no longer be const due to base class constraints. This is a necessary trade-off for the unified architecture.
14-14: Consistent API preservation pattern.The
etagsgetter follows the same pattern as other refactored headers, maintaining backward compatibility.
32-44: Good validation in parsing logic.Both
IfMatchHeaderandIfNoneMatchHeaderproperly validate ETag format before parsing. The use ofETagHeader.isValidETagensures consistent validation.Also applies to: 71-83
1-93: Verify the WildcardListHeader base class implementation.The refactoring looks solid, but we should verify that the
WildcardListHeaderbase class properly handles the common functionality, especially the wildcard validation logic mentioned in test updates.#!/bin/bash # Check the WildcardListHeader implementation fd -e dart "wildcard_list_header.dart" --exec cat {} # Verify that error messages are consistent rg "Wildcard.*cannot be used with other values" --type dart
b3469cb to
1a98212
Compare
SandPod
left a comment
There was a problem hiding this comment.
Clean refactor. Just one question.
|
@SandPod Can we disregard the codecov failure? This PR removes a lot of redundant but tested code, meaning the number of lines and lines covered has been reduced 1:1 causing the overall project coverage to be reduced. The actual patch has higher than project coverage. |
185f36e to
550d7af
Compare
|
Rebased on main |
bffaa10 to
ddf10c9
Compare
Add WildcardListHeader<T> to handle common wildcard/list pattern: - Generic wildcard parsing with '*' validation - List management with typed values - Flexible encoding via function parameter - No constraints on type parameter T - Foundation for refactoring Accept headers
…ListHeader Refactored AcceptEncodingHeader and AcceptLanguageHeader as subclasses of WildcardListHeader
- Fix AccessControlAllowMethodsHeader to use proper uppercase HTTP method names - RequestMethod.value returns uppercase (e.g. 'GET') while .name returns lowercase
- Convert AccessControlAllowMethodsHeader to extend WildcardListHeader<RequestMethod> - Use WildcardListHeader.parse for consistent parsing logic - Remove duplicated wildcard handling code - Follow same pattern as AcceptEncodingHeader and AcceptLanguageHeader
…ader - Convert AccessControlExposeHeadersHeader to extend WildcardListHeader<String> - Use WildcardListHeader.parse for consistent parsing logic - Remove duplicated wildcard handling code - Follow same pattern as other wildcard headers
- Convert AccessControlAllowHeadersHeader to extend WildcardListHeader<String> - Use WildcardListHeader.parse for consistent parsing logic - Remove duplicated wildcard handling code - Update test to use standardized error message 'other values' instead of 'other headers'
- Convert ClearSiteDataHeader to extend WildcardListHeader<ClearSiteDataType> - Preserve custom quote removal logic for Clear-Site-Data header format - Use custom parsing instead of WildcardListHeader.parse to handle quotes - Remove duplicated wildcard handling code - Follow same pattern as other wildcard headers
- Convert ETagConditionHeader base class to extend WildcardListHeader<ETagHeader> - Update IfMatchHeader and IfNoneMatchHeader to use base class functionality - Use WildcardListHeader.parse for consistent parsing logic - Remove duplicated wildcard handling code from both concrete classes - Fix const constructor calls in tests (etags constructor is no longer const) - Follow same pattern as other wildcard headers
ddf10c9 to
725d962
Compare
|
Rebased on main |
Description
Refactors HTTP header classes to use a generic
WildcardListHeader<T>base class. Moves parsing logic to factory constructors and encoding logic to instance methods on quality classes. Unifies the implementation pattern across all wildcard headers including Accept-Encoding, Accept-Language, Access-Control headers, Clear-Site-Data, and ETag condition headers.Related Issues
N/A
Pre-Launch Checklist
Breaking Changes
ETagConditionHeader constructors are no longer const due to base class constraints.
Additional Notes
All wildcard headers now follow consistent inheritance pattern. Test coverage maintained.
Summary by CodeRabbit
New Features
Bug Fixes
Refactor
Tests