Skip to content

feat!: Distinguish between path and method miss in router lookups - #179

Merged
nielsenko merged 4 commits into
serverpod:mainfrom
nielsenko:router-405
Sep 22, 2025
Merged

nielsenko merged 4 commits into
serverpod:mainfrom
nielsenko:router-405

Conversation

@nielsenko

@nielsenko nielsenko commented Sep 19, 2025 •

Copy link
Copy Markdown
Collaborator

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:

  • Method Consolidation: Eliminates the separate RequestMethod type and uses the unified Method enum throughout the codebase, affecting header parsing, routing, and request handling
  • Precise Router Lookups: Introduces PathMiss and MethodMiss result types to distinguish between "resource not found" (404) and "method not allowed" (405) scenarios
  • 405 Response Testing: Adds comprehensive test coverage validating that routing middleware correctly returns 405 status codes with proper Allow headers for method mismatches

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

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

Breaking Changes:

  • Method Type Unification: RequestMethod type removed; all method handling now uses Method enum
  • Router Lookup Return Type: Router.lookup() now returns LookupResult<T> instead of nullable Match<T>, requiring updates to code that directly uses router lookup results
  • Header API Changes: Access-Control-Request-Method header now works with Method type instead of RequestMethod

Additional 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

    • Introduced a new HTTP Method enum with parsing and uppercase value access.
    • Router lookup now returns explicit results (match, path miss, method miss) with 405 responses and Allow header.
    • Improved header handling for Access-Control-Request-Method and Allow using dedicated codecs and method sets.
  • Refactor

    • Replaced RequestMethod with Method across the public API (Request, headers, router, static handler).
    • Allow header now exposes Set instead of a list.
  • Tests

    • Updated test suite to align with the new Method API and explicit lookup results.

@coderabbitai

coderabbitai Bot commented Sep 19, 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

Replaces 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

Cohort / File(s) Summary of changes
Analyzer config
analysis_options.yaml
Disabled strict raw types (analyzer.language.strict-raw-types: false).
HTTP method type migration
lib/src/router/method.dart, lib/src/method/request_method.dart (removed), lib/relic.dart, lib/src/message/request.dart, lib/src/adapter/io/request.dart
Added Method enum with parse/value; removed RequestMethod enum and its codec; updated exports to src/router/method.dart; replaced Request.method type and parsing to Method.
Router result model and lookup flow
lib/src/router/lookup_result.dart, lib/src/router/path_trie.dart, lib/src/router/router.dart, benchmark/benchmark.dart
Introduced sealed LookupResult with Miss, PathMiss, MethodMiss, and RouterMatch; PathTrie now returns Match<T>?; Router.lookup now non-null and returns PathMiss/MethodMiss/RouterMatch; added allowed methods on entries; benchmarks updated to use asMatch.
Routing middleware and static handler
lib/src/middleware/routing_middleware.dart, lib/src/io/static/static_handler.dart
Middleware now branches on PathMiss (next), MethodMiss (405 + Allow), RouterMatch (dispatch); static handler uses Method, sets Allow as Set.
Headers and codecs
lib/src/headers/codecs/common_types_codecs.dart, lib/src/headers/headers.dart, lib/src/headers/standard_headers_extensions.dart, lib/src/headers/typed/headers/access_control_allow_methods_header.dart
Introduced methodCodec; switched parsing/encoding from RequestMethod to Method; changed allow from List to Set; updated extensions and typed header to Method.
Tests: router and middleware
test/router/*, test/middleware/routing_middleware_test.dart
Updated to Method enum; replaced null expectations with PathMiss/MethodMiss; added helpers asserting RouterMatch; added 405 tests and Allow header assertions.
Tests: headers and static
test/headers/*, test/static/*
Switched RequestMethod→Method; allow expectations now Set; minor guard changes for list/set.
Tests: misc
test/exception/relic_exceptions_test.dart, test/hijack/relic_hijack_test.dart, test/message/request_test.dart, test/util/test_util.dart, test/src/middleware/context_property_test.dart, test/handler/cascade_test.dart, test/relic_server_serve_test.dart
Replaced RequestMethod usage with Method; updated helpers to default to Method.get; adjusted http.Request method strings via Method.*.value.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Out of Scope Changes Check ⚠️ Warning The PR goes beyond the linked issue by performing a broad API consolidation and other wide-ranging changes: removal of the old RequestMethod enum in favor of a new Method enum across headers, codecs, and public APIs; changing header collection types (List → Set); updates to exported symbols (lib/relic.dart); an analyzer option change; and benchmark adjustments, all of which are breaking and not strictly required to satisfy issue #177. These larger refactors should be justified separately or split from the core router-miss work to reduce review and migration burden. Either split the method-consolidation and header-type refactors into a separate PR or explicitly document and justify them in the current PR with a detailed migration guide and changelog entries; additionally add compatibility notes and update public API docs so consumers can adopt the breaking changes deliberately.
✅ Passed checks (4 passed)
Check name Status Explanation
Title Check ✅ Passed The title "feat!: Distinguish between path and method miss in router lookups" is concise, focused on the primary change (distinguishing path vs method misses) and correctly signals a breaking change via the "!" marker; it clearly describes the main intent and is appropriate for a teammate scanning history.
Linked Issues Check ✅ Passed The changes implement the objectives from [#177]: router lookups now produce distinct LookupResult variants (PathMiss and MethodMiss), MethodMiss carries the allowed Set, Router.lookup and routing middleware use these results to return 405 with an Allow header, and tests were added to cover 405 behavior, so downstream code can distinguish 404 vs 405 and obtain allowed methods.
Description Check ✅ Passed The PR description follows the repository template and includes a clear Description, Related Issues (Closes: #177), a Pre-Launch Checklist, explicit Breaking Changes, and Additional Notes; it documents why the change is needed and what was changed. There is a minor inconsistency in the checklist (the "referenced issue" item is unchecked despite the "Closes: #177" line), but overall the description is complete and documents the breaking changes.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented Sep 19, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.50746% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 91.79%. Comparing base (fa33942) to head (c25254b).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
lib/src/router/lookup_result.dart 83.33% 1 Missing ⚠️
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.
📢 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 changed the title router 405 feat!: Distinguish between path and method miss in router lookups Sep 19, 2025
@nielsenko
nielsenko force-pushed the router-405 branch 6 times, most recently from 82692a7 to c88244e Compare September 19, 2025 08:54
@nielsenko nielsenko self-assigned this Sep 19, 2025
@nielsenko
nielsenko force-pushed the router-405 branch 15 times, most recently from 0f4de5b to 5295a53 Compare September 22, 2025 07:32
@nielsenko
nielsenko force-pushed the router-405 branch 4 times, most recently from 7f59300 to aea352d Compare September 22, 2025 07:56
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Sep 22, 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: 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

_toHandler may remain uninitialized when toHandler is null and T isn’t a Handler. Accessing it in ArgumentError.checkNotNull will 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 match

Using .asMatch is 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 returns Method? 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 results

We’re testing 405 semantics; verifying allowed strengthens 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 method
lib/src/router/lookup_result.dart (1)

29-31: Consider adding safety to the type cast.

The asMatch getter performs an unchecked cast to RouterMatch<T>. Consider adding runtime type checking to prevent potential CastError exceptions.

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

Allow 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

📥 Commits

Reviewing files that changed from the base of the PR and between fa33942 and aea352d.

📒 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.dart
  • lib/src/message/request.dart
  • lib/src/headers/standard_headers_extensions.dart
  • lib/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.dart
  • lib/src/headers/headers.dart
  • lib/src/headers/standard_headers_extensions.dart
  • test/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.dart
  • lib/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 correct

HEAD 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 — good

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

Assertions 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.parse

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

Constructor 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.dart

lib/src/message/request.dart (1)

4-4: Approve — Method enum re-exported; no RequestMethod symbol remains

lib/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 helper

This 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.method against Method.get/post is aligned with the new API.
  • Using Method.*.value when constructing http.Request preserves 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 the NormalizedPath information 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 the Set<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 extends Match<T> and implements LookupResult<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 _FakeRequest updates correctly align with the Method enum changes, replacing RequestMethod with Method and providing sensible defaults and URL construction.


356-377: Effective parameterized testing for all HTTP methods.

The parameterized test correctly exercises all Method.values and 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 unorderedEquals to 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 encodeMethod function and methodCodec provide a clean interface for single Method encoding/decoding, using the Method's value property and parse method consistently.


158-164: Proper Set-based method parsing.

The function correctly returns a Set<Method> instead of List<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 encodeMethodList function correctly handles Iterable<Method> and uses the Method's value property 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.dart to ../router/method.dart properly reflects the consolidation of HTTP method handling under the router module.


20-21: Consistent Method type usage in header extensions.

The updates to accessControlRequestMethod correctly use the unified Method type 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>? to Set<Method>? for the allow header 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 correct

Using Method.get with Request aligns with the new API surface. No issues here.

Comment thread lib/src/headers/headers.dart Resolved
Comment thread lib/src/router/path_trie.dart Resolved
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)
@nielsenko
nielsenko marked this pull request as ready for review September 22, 2025 09:02
@nielsenko
nielsenko requested a review from a team September 22, 2025 09:02
Comment thread test/router/router_groups_test.dart Resolved

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

2 Questions.

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.

Support distinguishing method mismatches from path misses for proper 405 responses

2 participants