Repository navigation
feat!: Distinguish between path and method miss in router lookups - #179
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 📝 WalkthroughWalkthroughReplaces RequestMethod with a new Method enum across the codebase. Introduces a sealed LookupResult hierarchy (RouterMatch, PathMiss, MethodMiss) and makes Router.lookup return non-null results. Updates routing middleware and static handler to handle method mismatches (405) vs path misses (404). Adjusts headers/codec handling and tests accordingly. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Client
participant Server
participant RoutingMiddleware as RoutingMiddleware
participant Router
participant Handler as Matched Handler
Client->>Server: HTTP request (method, path)
Server->>RoutingMiddleware: handle(Request)
RoutingMiddleware->>Router: lookup(Method, path)
alt RouterMatch
Router-->>RoutingMiddleware: RouterMatch(value, params, matched, remaining)
RoutingMiddleware->>Handler: invoke with context (params, paths)
Handler-->>RoutingMiddleware: Response (200+)
RoutingMiddleware-->>Server: Response
else PathMiss
Router-->>RoutingMiddleware: PathMiss(path)
RoutingMiddleware-->>Server: call next middleware/handler (404 flow)
else MethodMiss
Router-->>RoutingMiddleware: MethodMiss(allowed: Set<Method>)
RoutingMiddleware-->>Server: Response 405 + Allow header
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related PRs
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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 #179 +/- ##
==========================================
+ Coverage 91.78% 91.79% +0.01%
==========================================
Files 85 85
Lines 3127 3133 +6
Branches 1620 1620
==========================================
+ Hits 2870 2876 +6
Misses 257 257 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
82692a7 to
c88244e
Compare
0f4de5b to
5295a53
Compare
7f59300 to
aea352d
Compare
|
@CodeRabbit review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
lib/src/middleware/routing_middleware.dart (1)
25-35: Avoid LateInitializationError in_RoutingMiddlewareBuilder
_toHandlermay remain uninitialized whentoHandleris null andTisn’t aHandler. Accessing it inArgumentError.checkNotNullwill throw before your intended error. Initialize via a local and throw explicitly._RoutingMiddlewareBuilder( this._router, { final Handler Function(T)? toHandler, }) { - if (toHandler != null) { - _toHandler = toHandler; - } else if (_isSubtype<T, Handler>()) { - _toHandler = (final x) => x as Handler; - } - ArgumentError.checkNotNull(_toHandler, 'toHandler'); + Handler Function(T)? fn = toHandler; + if (fn == null && _isSubtype<T, Handler>()) { + fn = (final x) => x as Handler; + } + if (fn == null) { + throw ArgumentError.notNull('toHandler'); + } + _toHandler = fn; }lib/src/io/static/static_handler.dart (2)
258-275: HEAD + Range currently streams a body (violates HTTP).Range handlers don’t special‑case HEAD, so 206 responses for HEAD include a payload. HEAD must send headers only. Pass the method through and return an empty stream while preserving Content‑Length.
Apply this diff:
@@ - if (rangeHeader != null) { - return await _handleRangeRequest(ctx, fileInfo, headers, rangeHeader); - } + if (rangeHeader != null) { + return await _handleRangeRequest(ctx, fileInfo, headers, rangeHeader, method); + } @@ -Future<ResponseContext> _handleRangeRequest( +Future<ResponseContext> _handleRangeRequest( final NewContext ctx, final FileInfo fileInfo, final Headers headers, - final RangeHeader rangeHeader, + final RangeHeader rangeHeader, + final Method method, ) async { @@ - if (!_isRangeRequestValid(ctx, fileInfo)) { - return _serveFullFile(ctx, fileInfo, headers, ctx.request.method); + if (!_isRangeRequestValid(ctx, fileInfo)) { + return _serveFullFile(ctx, fileInfo, headers, method); } @@ - 0 => _serveFullFile(ctx, fileInfo, headers, ctx.request.method), - 1 => _serveSingleRange(ctx, fileInfo, headers, ranges.first), - _ => await _serveMultipleRanges(ctx, fileInfo, headers, ranges), + 0 => _serveFullFile(ctx, fileInfo, headers, method), + 1 => _serveSingleRange(ctx, fileInfo, headers, ranges.first, method), + _ => await _serveMultipleRanges(ctx, fileInfo, headers, ranges, method), }; @@ -ResponseContext _serveSingleRange( +ResponseContext _serveSingleRange( final NewContext ctx, final FileInfo fileInfo, final Headers headers, final Range range, + final Method method, ) { @@ - return ctx.respond(Response( + final body = (method == Method.head) + ? Body.fromDataStream( + const Stream.empty(), + contentLength: end - start, + mimeType: fileInfo.mimeType, + encoding: fileInfo.mimeType?.isText == true ? utf8 : null, + ) + : _createRangeBody(fileInfo, start, end); + + return ctx.respond(Response( HttpStatus.partialContent, headers: headers.transform((final mh) => mh ..contentRange = ContentRangeHeader( start: start, end: end - 1, size: fileInfo.stat.size, )), - body: _createRangeBody(fileInfo, start, end), + body: body, )); @@ -Future<ResponseContext> _serveMultipleRanges( +Future<ResponseContext> _serveMultipleRanges( final NewContext ctx, final FileInfo fileInfo, final Headers headers, final List<Range> ranges, + final Method method, ) async { final boundary = 'RelicMultipartBoundary-${Random().nextInt(1000000)}'; - final controller = StreamController<Uint8List>(); - int totalLength = 0; + final controller = StreamController<Uint8List>(); + int totalLength = 0; @@ - for (final range in ranges) { - final (start, end) = _calculateRangeBounds(range, fileInfo.stat.size); - totalLength += await _writeMultipartSection( - controller, - fileInfo, - boundary, - start, - end, - ); - } + if (method == Method.head) { + for (final range in ranges) { + final (start, end) = _calculateRangeBounds(range, fileInfo.stat.size); + final mimeType = fileInfo.mimeType ?? MimeType.octetStream; + final partHeader = '\r\n--$boundary\r\n' + 'Content-Type: ${mimeType.toHeaderValue()}\r\n' + 'Content-Range: bytes $start-${end - 1}/${fileInfo.stat.size}\r\n\r\n'; + totalLength += utf8.encode(partHeader).length + (end - start); + } + } else { + for (final range in ranges) { + final (start, end) = _calculateRangeBounds(range, fileInfo.stat.size); + totalLength += await _writeMultipartSection( + controller, + fileInfo, + boundary, + start, + end, + ); + } + } @@ - controller.add(footerBytes); + if (method != Method.head) controller.add(footerBytes); totalLength += footerBytes.length; @@ - return ctx.respond(Response( + return ctx.respond(Response( HttpStatus.partialContent, headers: headers.transform((final mh) => mh ..[Headers.contentTypeHeader] = [ '${MimeType.multipartByteranges.toHeaderValue()}; boundary=$boundary' ]), - body: Body.fromDataStream( - controller.stream, + body: Body.fromDataStream( + method == Method.head ? const Stream.empty() : controller.stream, contentLength: totalLength, mimeType: MimeType.multipartByteranges, encoding: fileInfo.mimeType?.isText == true ? utf8 : null, ), ));Also applies to: 311-335
319-323: *416 responses should include Content-Range: bytes /size.Add Content-Range for unsatisfied ranges to comply with RFC 7233.
Apply this diff:
- if (start == end) { - return ctx.respond(Response(416, headers: headers)); - } + if (start == end) { + return ctx.respond(Response( + 416, + headers: headers.transform( + (final mh) => mh..contentRange = ContentRangeHeader(size: fileInfo.stat.size), + ), + )); + }
🧹 Nitpick comments (13)
analysis_options.yaml (1)
3-5: Avoid globally disabling strict-raw-types (prefer fixing generics or add a temporary, time-boxed waiver).Turning this off can hide unsafe raw generic usage across the codebase. If this is temporary for migration, add an owner/date TODO; otherwise keep it enabled.
analyzer: language: - strict-raw-types: false + strict-raw-types: true # Prefer fixing raw generic usage; if temporarily disabling, add a TODO with owner/date.test/static/test_util.dart (1)
17-18: Method parameterization is good; update doc to reflect non-GET usage.Doc still says “Makes a simple GET request…”. Suggest clarifying default vs. override.
-/// Makes a simple GET request to [handler] and returns the result. +/// Makes a request to [handler] (default: Method.get) and returns the result.benchmark/benchmark.dart (1)
105-106: Benchmark now assumes every lookup is a definite matchUsing
.asMatchis fine given the dataset always inserts the exact routes it looks up. To avoid accidental benchmark crashes if routes/data change later, consider a cheap assert around the result.Apply this optional guard:
- router.lookup(Method.get, route).asMatch.value; + final r = router.lookup(Method.get, route); + assert(r is RouterMatch<int>, 'Unexpected miss for $route'); + (r as RouterMatch<int>).value;Also applies to: 144-145
lib/src/router/method.dart (1)
13-25: Enum parsing looks solid; tiny doc polish and a nullable variant would help DX
- Change “Throws an [FormatException]” to “Throws a [FormatException]”.
- Consider adding
Method.tryParse(String)that returnsMethod?instead of throwing to simplify callers that need non-exception control flow./// Parses a [method] string and returns the corresponding [Method] instance. /// - /// Throws an [FormatException] if the [method] string is invalid. + /// Throws a [FormatException] if the [method] string is invalid. factory Method.parse(final String method) { final trimmed = method.trim(); if (trimmed.isEmpty) throw const FormatException('Value cannot be empty'); return _reverseMap[trimmed.toLowerCase()] ?? (throw FormatException('Invalid value', method)); } + + /// Returns `null` if the [method] string is invalid. + static Method? tryParse(final String method) { + final trimmed = method.trim(); + if (trimmed.isEmpty) return null; + return _reverseMap[trimmed.toLowerCase()]; + }test/router/router_methods_test.dart (2)
51-57: Fix test description typo: “PassMiss” → “PathMiss”Keeps terminology consistent with the new result type.
- (final vv) => 'when looking up with $vv for that path, ' - 'then returns PassMiss', + (final vv) => 'when looking up with $vv for that path, ' + 'then returns PathMiss',
64-71: Also assert the Allow set on MethodMiss resultsWe’re testing 405 semantics; verifying
allowedstrengthens guarantees and guards regressions.final result = router.lookup(Method.post, '/specific-method-mismatch'); - expect(result, isA<MethodMiss>()); + expect(result, isA<MethodMiss>()); + expect((result as MethodMiss).allowed, equals({Method.get})); @@ - expect(router.lookup(Method.post, '/path-alpha'), isA<MethodMiss>()); + final missAlpha = router.lookup(Method.post, '/path-alpha'); + expect(missAlpha, isA<MethodMiss>()); + expect((missAlpha as MethodMiss).allowed, equals({Method.get})); @@ - expect(router.lookup(Method.get, '/path-beta'), isA<MethodMiss>()); + final missBeta = router.lookup(Method.get, '/path-beta'); + expect(missBeta, isA<MethodMiss>()); + expect((missBeta as MethodMiss).allowed, equals({Method.post})); @@ - expect(result, isA<MethodMiss>()); + expect(result, isA<MethodMiss>()); + expect((result as MethodMiss).allowed, equals({Method.get}));Also applies to: 152-167, 203-210, 240-247
lib/src/io/static/static_handler.dart (2)
25-31: Cache staleness should compare modified, not changed (ctime).Using FileStat.changed may invalidate cache on metadata changes. Prefer modified to align with Last-Modified.
Apply this diff:
- bool get isStale { + bool get isStale { final freshStat = file.statSync(); - return stat.size != freshStat.size || - stat.changed.isBefore(freshStat.changed); + return stat.size != freshStat.size || + stat.modified.isBefore(freshStat.modified); }
77-79: Guard substring(1) on requestPath.remainingPath.path should start with '/', but a defensive guard avoids RangeError on empty/malformed values.
Apply this diff:
- final filePath = p.join(resolvedRootPath, requestPath.substring(1)); + final relative = requestPath.startsWith('/') + ? requestPath.substring(1) + : requestPath; + final filePath = p.join(resolvedRootPath, relative);If router guarantees leading '/', ignore.
test/router/router_groups_test.dart (2)
55-58: Duplicate test case – remove one copy.The “/v1/posts then it fails” test appears twice.
Apply this diff:
- test('when looking up partial path /v1/posts, then it fails', () { - final failedResult = router.lookup(Method.get, '/v1/posts'); - expect(failedResult, isA<PathMiss>()); - });
149-153: Stray read of router.isEmpty.This has no assertion/effect; drop it.
Apply this diff:
- router.isEmpty;lib/src/router/router.dart (1)
72-75: Outdated docstring.Mentions “[Match] … Returns
null” but lookup returns LookupResult with PathMiss/MethodMiss/RouterMatch.Apply this diff:
- /// Returns a [Match] containing the associated value and any extracted - /// parameters if a match is found. Returns `null` if no matching route exists. + /// Returns a [LookupResult]: + /// - [RouterMatch] with value and parameters on success + /// - [PathMiss] if no route matches the path + /// - [MethodMiss] if a route matches the path but not the methodlib/src/router/lookup_result.dart (1)
29-31: Consider adding safety to the type cast.The
asMatchgetter performs an unchecked cast toRouterMatch<T>. Consider adding runtime type checking to prevent potentialCastErrorexceptions.Apply this diff to add type safety:
extension LookupResultExtension<T> on LookupResult<T> { - Match<T> get asMatch => this as RouterMatch<T>; + Match<T> get asMatch { + if (this is RouterMatch<T>) { + return this as RouterMatch<T>; + } + throw StateError('Cannot convert ${runtimeType} to Match<T>. Only RouterMatch<T> instances can be converted.'); + }test/src/middleware/context_property_test.dart (1)
5-8: Make helper accept a Method for future-proofingAllow passing a
Method(defaulting to GET) so this utility can create contexts for other methods without duplicating code.-RequestContext _createContextInstance([final String uriSuffix = 'test']) { - final request = Request(Method.get, Uri.parse('http://test.com/$uriSuffix')); +RequestContext _createContextInstance([ + final String uriSuffix = 'test', + final Method method = Method.get, +]) { + final request = Request(method, Uri.parse('http://test.com/$uriSuffix')); return request.toContext(Object()); }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (33)
analysis_options.yaml(1 hunks)benchmark/benchmark.dart(2 hunks)lib/relic.dart(1 hunks)lib/src/adapter/io/request.dart(1 hunks)lib/src/headers/codecs/common_types_codecs.dart(1 hunks)lib/src/headers/headers.dart(5 hunks)lib/src/headers/standard_headers_extensions.dart(7 hunks)lib/src/headers/typed/headers/access_control_allow_methods_header.dart(3 hunks)lib/src/io/static/static_handler.dart(2 hunks)lib/src/message/request.dart(3 hunks)lib/src/method/request_method.dart(0 hunks)lib/src/middleware/routing_middleware.dart(3 hunks)lib/src/router/lookup_result.dart(1 hunks)lib/src/router/method.dart(1 hunks)lib/src/router/path_trie.dart(7 hunks)lib/src/router/router.dart(4 hunks)test/exception/relic_exceptions_test.dart(1 hunks)test/handler/cascade_test.dart(3 hunks)test/headers/header_test.dart(4 hunks)test/headers/typed/access_control_request_method_header_test.dart(2 hunks)test/hijack/relic_hijack_test.dart(1 hunks)test/message/request_test.dart(19 hunks)test/middleware/log_middleware_test.dart(1 hunks)test/middleware/routing_middleware_test.dart(2 hunks)test/relic_server_serve_test.dart(7 hunks)test/router/router_groups_test.dart(1 hunks)test/router/router_methods_test.dart(11 hunks)test/router/router_test.dart(11 hunks)test/src/middleware/context_property_test.dart(1 hunks)test/static/basic_file_test.dart(1 hunks)test/static/test_util.dart(2 hunks)test/static/unsupported_methods_test.dart(8 hunks)test/util/test_util.dart(1 hunks)
💤 Files with no reviewable changes (1)
- lib/src/method/request_method.dart
🧰 Additional context used
🧠 Learnings (4)
📚 Learning: 2025-09-22T07:34:15.385Z
Learnt from: CR
PR: serverpod/relic#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-22T07:34:15.385Z
Learning: Applies to {lib,example}/**/*.dart : Implement handlers as functions processing RequestContext and returning ResponseContext; use middleware to wrap handlers and compose via a pipeline
Applied to files:
lib/relic.dartlib/src/message/request.dartlib/src/headers/standard_headers_extensions.dartlib/src/middleware/routing_middleware.dart
📚 Learning: 2025-09-22T07:34:15.385Z
Learnt from: CR
PR: serverpod/relic#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-22T07:34:15.385Z
Learning: Applies to {lib,example}/**/*.dart : Access and validate HTTP headers via strongly-typed APIs (type-safe headers)
Applied to files:
lib/src/headers/typed/headers/access_control_allow_methods_header.dartlib/src/headers/headers.dartlib/src/headers/standard_headers_extensions.darttest/headers/header_test.dart
📚 Learning: 2025-05-05T14:40:00.323Z
Learnt from: nielsenko
PR: serverpod/relic#52
File: lib/src/router/router.dart:37-53
Timestamp: 2025-05-05T14:40:00.323Z
Learning: In the Router and PathTrie implementation in Dart, both static and dynamic routes consistently throw ArgumentError when attempting to add duplicate routes, despite comments suggesting dynamic routes would be overwritten with a warning.
Applied to files:
test/message/request_test.dartlib/src/router/path_trie.dart
📚 Learning: 2025-09-22T07:34:15.385Z
Learnt from: CR
PR: serverpod/relic#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-22T07:34:15.385Z
Learning: Applies to analysis_options.yaml : Adopt `serverpod_lints` via `analysis_options.yaml` for lint rules
Applied to files:
analysis_options.yaml
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
- GitHub Check: Run Unit Tests (macos-latest, beta, upgrade)
- GitHub Check: Run Unit Tests (macos-latest, 3.5.0, downgrade)
- GitHub Check: Run Unit Tests (macos-latest, 3.5.0, upgrade)
🔇 Additional comments (48)
test/static/test_util.dart (1)
29-33: LGTM: migrate Request construction to Method.Type alignment looks correct and consistent with the new API.
test/util/test_util.dart (1)
52-52: LGTM: default Request now uses Method.get.Matches the new public API; no issues.
test/middleware/log_middleware_test.dart (1)
22-22: LGTM: log expectation updated to Method.get.value.Keeps the test aligned with the new enum.
test/exception/relic_exceptions_test.dart (1)
83-85: LGTM: http.Request now uses Method.get.value.Consistent with the rename and http API expectations.
test/hijack/relic_hijack_test.dart (1)
58-60: LGTM: http.Request method updated to Method.get.value.Matches the new enum usage.
test/handler/cascade_test.dart (1)
45-48: LGTM: switched Request constructors to Method.get in all cases.Consistent with the enum rename; tests remain semantically identical.
Also applies to: 60-66, 79-86
lib/relic.dart (1)
28-28: Approve: RequestMethod removal verified — Method exported.No occurrences of RequestMethod found repo-wide; lib/relic.dart exports src/router/method.dart (line 28). Update CHANGELOG/UPGRADING to document this breaking API change.
test/static/basic_file_test.dart (1)
55-55: API rename to Method.head looks correctHEAD test semantics remain intact; no further changes needed here.
test/headers/typed/access_control_request_method_header_test.dart (1)
90-91: Expectations updated to Method.post — goodParsing with whitespace and standard value both validated against the new enum.
Also applies to: 105-105
test/static/unsupported_methods_test.dart (1)
29-29: 405 + Allow header tests migrated to Method — good coverageAssertions check both presence and cardinality; no order dependency, which is correct for Set.
Also applies to: 37-39, 51-51, 59-61, 73-73, 81-83, 95-95, 103-105
lib/src/adapter/io/request.dart (1)
9-9: Implement/verify a case-insensitive, trimming Method.parseNo Method.parse was found; enum Method exists (values like get, head; value => name.toUpperCase()). The call at lib/src/adapter/io/request.dart:9 uses Method.parse(request.method). Add/verify a parse(String) that trims and matches case-insensitively to the enum (or replace the call with a safe lookup).
test/message/request_test.dart (1)
15-16: Tests migrated to Method.get — approve; verify no remaining RequestMethod usagesConstructor and error-path tests still exercise the same behaviors; no further action if sweep passes. Re-run and paste results:
rg -n '\bRequestMethod\b' test || true
sed -n '1,500p' test/message/request_test.dartlib/src/message/request.dart (1)
4-4: Approve — Method enum re-exported; no RequestMethod symbol remainslib/relic.dart exports src/router/method.dart (line 28). No exact 'RequestMethod' occurrences found in the repo; accessControlRequestMethod usages are expected.
test/router/router_methods_test.dart (1)
14-24: Nice reusable assertion helperThis cuts repetition and makes failures clearer. Good use of generics and type guards.
test/relic_server_serve_test.dart (1)
71-74: Method enum migration looks correct
- Asserting
request.methodagainstMethod.get/postis aligned with the new API.- Using
Method.*.valuewhen constructinghttp.Requestpreserves uppercase tokens required by the client library.Also applies to: 171-172, 191-193, 209-210, 427-429, 499-500, 515-517
lib/src/io/static/static_handler.dart (2)
166-168: Switch to Method enum looks correct.Allowing only GET/HEAD is preserved with the new Method type.
171-179: 405 response builds Allow from Set (good).This aligns with the new Headers.allow Set codec.
lib/src/headers/typed/headers/access_control_allow_methods_header.dart (1)
8-13: Migration to Method is consistent and type-safe.Parsing via Method.parse and encoding via m.value aligns with the new codec surface.
Also applies to: 25-29, 37-40
lib/src/headers/headers.dart (2)
89-91: accessControlRequestMethod now uses methodCodec (good).Matches the Method migration and keeps header API consistent.
263-279: Explicit sets are fine.No behavior change; only stronger typing.
Also applies to: 280-308, 310-338
test/headers/header_test.dart (2)
469-472: HashCode checks gated for List/Set are sensible.Avoids false negatives where core List/Set hash semantics aren’t controlled.
Also applies to: 486-499, 505-508
559-585: Method-based header tests look correct.
- AccessControlAllowMethodsHeader.methods(Method.values)
- accessControlRequestMethod = Method.get
- allow = {Method.get}
test/router/router_groups_test.dart (2)
5-14: Helper asserts on RouterMatch are correct.Casts guarded; clearer failure mode.
16-34: Route group lookups and PathMiss expectations read well.Covers nested groups, params, and equivalence.
Also applies to: 36-64, 66-114, 124-132, 133-144
test/router/router_test.dart (3)
8-17: Updated expectLookupResult matches new LookupResult types.Asserting RouterMatch then checking value/parameters is correct.
31-48: PathMiss assertions reflect the new API.Transition away from null checks is consistent.
Also applies to: 106-111, 132-136, 248-259, 279-283, 303-315, 378-383, 557-561, 573-577, 662-669
1-691: Add test asserting MethodMiss.allowed contains allowed methods (405)test/router/router_methods_test.dart already asserts MethodMiss is returned but doesn't check the allowed set — add the concise test below:
test('method mismatch yields MethodMiss with allowed methods', () { final r = Router<String>()..get('/only-get', 'ok'); final res = r.lookup(Method.post, '/only-get'); expect(res, isA<MethodMiss>()); if (res is MethodMiss) { expect(res.allowed, equals({Method.get})); } });lib/src/router/router.dart (2)
29-31: allowed set computation LGTM.Used by MethodMiss to build Allow; deterministic by enum order.
159-165: Incorrect — group() already returns an attached/shared Router. attach(NormalizedPath(path), subRouter._allRoutes) merges the subtrie into the parent and sets trie._root = currentNode, so multiple group('/x') calls return Router instances that share the same underlying PathTrie node and will see each other’s additions/lookups (lib/src/router/router.dart:59–65; lib/src/router/path_trie.dart:286–322).Likely an incorrect or invalid review comment.
lib/src/router/lookup_result.dart (5)
5-7: Well-structured sealed class hierarchy for typed routing results.The sealed class hierarchy effectively distinguishes between successful matches and different types of failures. The const constructor and sealed nature provide type safety and exhaustive pattern matching capabilities.
9-11: Clean inheritance structure for miss scenarios.The
Miss<T>abstract class provides a good base for failure cases, maintaining consistency in the type hierarchy while allowing specific miss types to extend it.
13-17: Proper path miss representation.The
PathMiss<T>class correctly carries theNormalizedPathinformation for 404 scenarios, enabling callers to understand which path was not found.
19-23: Correct method miss implementation for 405 responses.The
MethodMiss<T>class properly carries theSet<Method>of allowed methods, which is essential for generating compliant HTTP 405 responses that must include an Allow header with the list of supported methods.
25-27: Appropriate router match implementation.The
RouterMatch<T>class correctly extendsMatch<T>and implementsLookupResult<T>, bridging the gap between the path trie's match representation and the router's lookup result system.test/middleware/routing_middleware_test.dart (7)
13-17: Clean test utility updates for Method enum.The
_FakeRequestupdates correctly align with the Method enum changes, replacingRequestMethodwithMethodand providing sensible defaults and URL construction.
356-377: Effective parameterized testing for all HTTP methods.The parameterized test correctly exercises all
Method.valuesand validates the method mapping works correctly in the routing middleware.
379-402: Comprehensive 405 Method Not Allowed testing.The new test group properly validates that 405 responses are returned for method mismatches rather than falling back to 404, which aligns with the PR objectives and HTTP standards.
404-419: Proper Allow header validation in 405 responses.This test correctly verifies that 405 responses include the Allow header with the supported methods, which is required by RFC 7231 section 6.5.5.
421-439: Comprehensive Allow header testing with multiple methods.The test properly validates that when multiple methods are supported for the same path, the Allow header contains all supported methods, using
unorderedEqualsto handle set ordering.
441-460: Parameterized route method mismatch testing.This test correctly validates that method mismatches on parameterized routes return 405 with proper Allow headers, ensuring the routing system works correctly with path parameters.
462-481: Crucial path miss vs method miss distinction.This test is essential for validating the core PR objective - ensuring that path misses (no matching route) invoke the next handler rather than returning 405, properly distinguishing between resource-not-found (404) and method-not-allowed (405) scenarios.
lib/src/headers/codecs/common_types_codecs.dart (3)
152-153: Clean Method codec implementation.The
encodeMethodfunction andmethodCodecprovide a clean interface for single Method encoding/decoding, using the Method'svalueproperty andparsemethod consistently.
158-164: Proper Set-based method parsing.The function correctly returns a
Set<Method>instead ofList<Method>, which aligns with HTTP semantics where allowed methods are typically treated as a set without ordering or duplicates.
167-170: Consistent method list encoding.The
encodeMethodListfunction correctly handlesIterable<Method>and uses the Method'svalueproperty directly, maintaining consistency with the single method codec.lib/src/headers/standard_headers_extensions.dart (3)
1-1: Correct import path update.The import change from
../method/request_method.dartto../router/method.dartproperly reflects the consolidation of HTTP method handling under the router module.
20-21: Consistent Method type usage in header extensions.The updates to
accessControlRequestMethodcorrectly use the unifiedMethodtype across both getter and setter operations in the header extensions.Also applies to: 113-114, 222-223
45-45: Proper Set-based Allow header handling.The change from
List<Method>?toSet<Method>?for theallowheader correctly represents HTTP Allow header semantics, where the order of methods is not significant and duplicates should not occur.Also applies to: 143-143, 247-247
test/src/middleware/context_property_test.dart (1)
6-6: Method enum migration is correctUsing
Method.getwithRequestaligns with the new API surface. No issues here.
Introduces a more precise router lookup system that differentiates between path misses (no matching route exists) and method misses (route exists but HTTP method not allowed). This enables proper HTTP semantics for 405 responses. Key changes: - Adds PathMiss and MethodMiss result types to LookupResult hierarchy - PathMiss indicates no route matches the requested path (should result in 404) - MethodMiss includes allowed methods for the path (should result in 405) - Router.lookup() now returns specific miss types instead of generic null - Enables routing middleware to implement correct HTTP status codes This breaking change allows middleware to distinguish between 'resource not found' (404) and 'method not allowed' (405) scenarios, improving REST API compliance and providing better error responses to clients.
Consolidates HTTP method handling by eliminating the separate RequestMethod type and using the unified Method enum throughout the codebase. This change affects header parsing, routing, and request handling. Key changes: - Updates header codecs to use Method.parse instead of RequestMethod parsing - Modifies Access-Control-Request-Method header to work with Method type - Unifies method representation across the entire HTTP stack - Simplifies method handling in routing middleware and request processing This breaking change provides better type consistency and reduces complexity in method handling across different parts of the framework.
…ponses Add tests to validate that routing middleware correctly returns 405 status code for matching paths with non-matching HTTP methods, and ensures the Allow header is properly populated with allowed methods. Tests cover: - Basic 405 response for method mismatches - Allow header containing single allowed method - Allow header containing multiple allowed methods - 405 behavior with parameterized routes - Distinction between path miss (404) and method miss (405)
aea352d to
c25254b
Compare
Description
This PR introduces improvements to HTTP method handling and router lookup precision in the Relic framework. The changes consolidate method representation, distinguish between different types of routing failures, and add comprehensive test coverage for HTTP 405 responses.
Key Changes:
RequestMethodtype and uses the unifiedMethodenum throughout the codebase, affecting header parsing, routing, and request handlingPathMissandMethodMissresult types to distinguish between "resource not found" (404) and "method not allowed" (405) scenariosThese changes improve REST API compliance by enabling proper HTTP semantics and providing better error responses to clients.
Related Issues
Closes: #177
Pre-Launch Checklist
Please ensure that your PR meets the following requirements before submitting:
///), ensuring consistency with existing project documentation.Breaking Changes
Breaking Changes:
RequestMethodtype removed; all method handling now usesMethodenumRouter.lookup()now returnsLookupResult<T>instead of nullableMatch<T>, requiring updates to code that directly uses router lookup resultsMethodtype instead ofRequestMethodAdditional Notes
The changes maintain backward compatibility for high-level routing middleware usage while improving the underlying type system. The new router lookup precision enables middleware to implement correct HTTP status codes according to RFC specifications, particularly for 405 Method Not Allowed responses.
Summary by CodeRabbit
New Features
Refactor
Tests