Skip to content

refactor!: Avoid using exceptions for control-flow - #48

Merged
nielsenko merged 31 commits into
serverpod:mainfrom
nielsenko:no-hijack-exception
Apr 28, 2025
Merged

nielsenko merged 31 commits into
serverpod:mainfrom
nielsenko:no-hijack-exception

Conversation

@nielsenko

@nielsenko nielsenko commented Apr 24, 2025 •

Copy link
Copy Markdown
Collaborator

Description

This PR avoids the exception based control flow employed by shelf wrt. request hijacking.

Instead it refactors the newly introduced RequestContext class to be a sum-type of:

  • ResponseContext - a context that has been given a Response
  • HijackContext - a context that has been hijacked.
  • NewContext - a new yet unhandled context.

A Handler is now a function taking and producing RequestContexts, ie: typedef Handler = FutureOr<RequestContext> Function(RequestContext) (the previous handler type is now called a Responder).

This has lots of ripple effects.

This PR sits on top of (and supersedes) #47

Related Issues

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.

This changes the Handler type which is pretty core to relic.

Summary by CodeRabbit

  • New Features

    • Introduced an adaptor-based abstraction for server request handling, enabling flexible backends and improved middleware composition.
    • Added new context classes for request, response, and hijacking, supporting advanced request lifecycle management.
    • Added new IO adaptor and helper functions for binding and serving HTTP servers.
  • Refactor

    • Replaced direct use of dart:io and request hijacking with context-based APIs and adaptor interfaces.
    • Unified handler signatures to operate on context objects instead of raw requests/responses.
    • Simplified and consolidated export structure for public API.
  • Bug Fixes

    • Improved error handling and response normalization in middleware and server logic.
  • Chores

    • Updated .gitignore and version constraints in pubspec.yaml.
    • Enhanced and refactored tests to use the new context-based API and server abstraction.
    • Removed obsolete hijack tests and related internal code.

@coderabbitai

coderabbitai Bot commented Apr 24, 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

This update introduces a significant architectural refactor to the HTTP server handling in the codebase. The core server logic is abstracted away from direct dependency on Dart's HttpServer by introducing a new Adaptor interface, along with supporting context-based abstractions for request and response lifecycle management. The request/response handling now revolves around context objects, enabling more flexible middleware and handler composition. Hijacking and socket-level operations are moved out of the core Request class and are instead managed through adaptor and context interfaces. Supporting files and tests are updated to use the new context-based API, and direct references to dart:io are removed from most of the core library, centralizing platform-specific logic in adaptor modules. The test suite and example code are also refactored to align with these changes.

Changes

Files/Groups Change Summary
lib/relic.dart, lib/src/adaptor/adaptor.dart, lib/src/adaptor/context.dart, lib/src/adaptor/io/bind_http_server.dart, lib/src/adaptor/io/io_adaptor.dart, lib/src/adaptor/io/request.dart, lib/src/adaptor/io/response.dart, lib/src/adaptor/security_options.dart, lib/src/io_serve.dart Introduce adaptor interface and context abstractions, add IO adaptor and supporting infrastructure, reorganize exports, and add new server serving function.
lib/src/handler/handler.dart, lib/src/handler/cascade.dart, lib/src/middleware/middleware.dart, lib/src/middleware/middleware_logger.dart, lib/src/io/static/static_handler.dart Refactor handlers and middleware to operate on context objects, update function signatures and internal logic for new context-based API.
lib/src/message/request.dart, lib/src/message/response.dart, lib/src/headers/headers.dart, lib/src/body/body.dart, lib/src/body/types/mime_type.dart, lib/src/hijack/hijack.dart, lib/src/hijack/exception/hijack_exception.dart, lib/src/relic_server_serve.dart Remove direct dart:io dependencies and hijack logic from core classes, delete obsolete constructors, methods, and files, and update request/response abstractions.
lib/src/relic_server.dart Refactor RelicServer to use the new adaptor and context system, update request handling, lifecycle, and middleware logic.
example/example.dart Update example to use multi-isolate server model and new serving abstractions.
.github/workflows/dart-tests.yaml, .gitignore, pubspec.yaml Minor workflow, ignore, and dependency constraint updates.
test/ (all test files except removed/renamed files) Refactor tests to use context-based handlers, update server setup and teardown, align test utilities and assertions with new abstractions.
test/hijack/hijack_test.dart Remove hijack-specific test suite as hijack logic is now handled elsewhere.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant IOAdaptor
    participant RelicServer
    participant Handler
    participant Middleware

    Client->>IOAdaptor: Send HTTP request
    IOAdaptor->>RelicServer: Stream AdaptorRequest
    RelicServer->>Middleware: Wrap Handler
    RelicServer->>Handler: Pass RequestContext
    Handler-->>RelicServer: Return RequestContext (ResponseContext/ HijackContext)
    RelicServer->>IOAdaptor: Respond or hijack based on context
    IOAdaptor-->>Client: Send HTTP response or hijack socket
Loading

Possibly related PRs


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

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@nielsenko nielsenko mentioned this pull request Apr 24, 2025
7 of 9 tasks
@nielsenko
nielsenko force-pushed the no-hijack-exception branch 4 times, most recently from 8e6fd19 to fd31c4e Compare April 24, 2025 13:48
@codecov

codecov Bot commented Apr 24, 2025 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 91.71975% with 13 lines in your changes missing coverage. Please review.

Project coverage is 79.16%. Comparing base (9879ba3) to head (f1f4e40).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
lib/src/handler/handler.dart 50.00% 4 Missing ⚠️
lib/src/relic_server.dart 93.02% 3 Missing ⚠️
lib/src/adapter/io/response.dart 71.42% 2 Missing ⚠️
lib/src/middleware/middleware.dart 86.66% 2 Missing ⚠️
lib/src/middleware/middleware_logger.dart 85.71% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #48      +/-   ##
==========================================
+ Coverage   78.94%   79.16%   +0.22%     
==========================================
  Files          70       74       +4     
  Lines        2170     2165       -5     
  Branches     1220     1233      +13     
==========================================
+ Hits         1713     1714       +1     
+ Misses        457      451       -6     

☔ 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 force-pushed the no-hijack-exception branch from fd31c4e to 052b46a Compare April 24, 2025 13:54
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 24, 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.

@nielsenko nielsenko self-assigned this Apr 24, 2025

@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: 16

🔭 Outside diff range comments (1)
test/middleware/create_middleware_test.dart (1)

155-173: 🛠️ Refactor suggestion

Throw dedicated Exception objects instead of bare strings
Several tests deliberately throw string literals (throw 'middleware error',
throw 'bad handler'). Dart’s analysis rule
only_throw_errors is silenced at the top of the file, but relying on
non-Error/Exception types makes stack traces harder to interpret and can mask
bugs once these examples are copied into production code.

-  onRequest: (final request) => throw 'middleware error')
+  onRequest: (final request) =>
+      throw StateError('Middleware request failure'))

Consider replacing all ad-hoc string throws (159-161, 169-171, 178-182, 191-195,
205-215, 227-230, 248-250) with typed exceptions and remove the
// ignore_for_file: only_throw_errors directive.

🧹 Nitpick comments (25)
test/static/alternative_root_test.dart (1)

4-4: Update import path for static handler
The test now pulls in static_handler.dart from package:relic/src/io/static/static_handler.dart to reflect its new location. Ensure the file exists at that path and that createStaticHandler remains accessible. Consider re-exporting it via the public API to avoid deep src/ imports in tests.

Would you like to establish a public re-export in lib/relic.dart so tests can import createStaticHandler without referencing src/io/static directly?

test/static/directory_listing_test.dart (1)

5-5: Align static handler import path
This import was adjusted to package:relic/src/io/static/static_handler.dart. Please verify that all static-related tests consistently use the updated path and that createStaticHandler is correctly exposed.

Can we introduce a public-facing import to simplify these test imports and reduce coupling to internal folder structure?

test/static/symbolic_link_test.dart (1)

5-5: Correct static handler import in symbolic link tests
The new import path matches the refactored location under lib/src/io/static. Confirm that the relocation covers all necessary files (including platform-specific symlink logic) and that tests resolve the handler properly.

Consider adding a stable public export for createStaticHandler to avoid deep imports in test code.

test/adaptor/server_adaptor_test.dart (1)

1-35: Well-structured test file for the adaptor abstraction.

This test file effectively validates the core functionality of the server adaptor abstraction. It properly sets up and tears down server instances and verifies basic request handling through the adaptor interface.

A few suggestions to enhance test coverage:

  • Consider adding tests for different HTTP methods (POST, PUT, DELETE)
  • Add tests for request/response headers handling
  • Test error scenarios and edge cases
lib/src/adaptor/io/response.dart (1)

25-27: Consider error handling for stream operations.

The stream operations could potentially fail, especially in network scenarios. Consider adding error handling to ensure any failures are properly logged or propagated.

-    return httpResponse
-        .addStream(body.read())
-        .then((final _) => httpResponse.close());
+    return httpResponse
+        .addStream(body.read())
+        .then((final _) => httpResponse.close())
+        .catchError((error) {
+          // Log the error or handle it appropriately
+          // Consider if the response should be closed in case of error
+          httpResponse.close();
+          throw error; // Re-throw to propagate the error
+        });
lib/src/adaptor/io/http_response_extension.dart (1)

99-105: Consider removing or activating dead code.

The ContentTypeExtension is marked as dead code but kept in the codebase. If it's intended for future use, consider moving it to a draft file or adding more specific TODOs about when and how it will be used.

-// TODO(nielsenko): This is currently dead-code, but perhaps useful.
+// TODO(nielsenko): This extension will be used when implementing [feature X] in future work (issue #XXX).
lib/src/io_serve.dart (1)

31-45: Consider adding error handling for server initialization.

While the implementation correctly initializes and starts the server, there's no explicit error handling for failures during server binding or startup. Consider adding try/catch blocks to provide more helpful error messages.

 Future<RelicServer> serve(
   final Handler handler,
   final InternetAddress address,
   final int port, {
   final SecurityContext? context,
   final int? backlog,
   final bool shared = false,
   final bool strictHeaders = false,
   final String? poweredByHeader,
 }) async {
+  try {
     final adaptor = IOAdaptor(await bindHttpServer(
       address,
       port: port,
       context: context,
       backlog: backlog ?? 0,
       shared: shared,
     ));
     final server = RelicServer(
       adaptor,
       strictHeaders: strictHeaders,
       poweredByHeader: poweredByHeader,
     );
     await server.mountAndStart(handler);
     return server;
+  } catch (e) {
+    throw StateError('Failed to initialize or start server: $e');
+  }
 }
lib/src/adaptor/adaptor.dart (1)

10-18: Consider making Adaptor generic and document lifecycle contracts
Right now AdaptorRequest can wrap anything (HTTP, gRPC, …) but the interface
does not clarify:

  • whether respond/hijack may be called concurrently,
  • if respond can be invoked more than once,
  • who owns closing the request stream when close() is called.

Adding thorough doc comments or a small state diagram will save future
implementers from subtle race conditions.

example/example.dart (1)

8-15: Over-subscription risk with numberOfProcessors * 2 isolates
Spawning twice as many isolates as logical cores often hurts throughput because
each isolate still performs async I/O and competes for the same event loop
threads. Start with Platform.numberOfProcessors and expose the multiplier as
a CLI flag so users can tune it.

-  final isolateCount = Platform.numberOfProcessors * 2;
+  final isolateCount =
+      int.parse(Platform.environment['RELIC_ISOLATES'] ??
+          '${Platform.numberOfProcessors}');
test/headers/headers_test_utils.dart (1)

33-38: Provide clear error information when the adaptor is not IOAdaptor

Throwing a bare ArgumentError() gives almost no clue to the test author.
Attach a message so failures are actionable, or fall back to a generic URL if
the adaptor is not IO-based.

-    if (adaptor is! IOAdaptor) throw ArgumentError();
+    if (adaptor is! IOAdaptor) {
+      throw ArgumentError(
+        'Cannot infer server URL: expected an IOAdaptor but found '
+        '${adaptor.runtimeType}.',
+      );
+    }
lib/relic.dart (2)

8-8: Exporting the entire handler.dart widens the public API surface

Previously only Handler was public; exporting the whole file now exposes
internal helpers (e.g. createSyncHandler, private typedefs) that were never
meant to be stable. This is a breaking change for consumers and complicates
semver guarantees. Consider adding explicit show Handler, respondWith
selectors instead, or bump the major version and document the new contracts.


15-17: Potential leakage of IO-only utilities in a platform-agnostic package

src/io/static/static_handler.dart and src/io_serve.dart are exported at
the top level, yet the PR goal is to decouple from dart:io.
If the intention is to stay pure-Dart for non-IO platforms (e.g. dart:html,
Flutter Web), mark these exports with conditional imports or move them behind
an io feature flag to avoid accidental inclusion in web builds.

lib/src/handler/handler.dart (2)

19-24: Consider tightening the typedef set – ResponseHandler / HijackHandler are unused

ResponseHandler and HijackHandler look well–named, but there is no reference to either in the library tree that accompanies this PR. Dead typedefs add cognitive noise and will be flagged by dart analyze as unused_element.

If they are only “reserved for later”, please add a short // ignore: line or a TODO explaining the future plan; otherwise, drop them until they are actually consumed.


36-37: Name clash between Responder and ResponseHandler

Responder (request → response) and ResponseHandler (context → ResponseContext) are extremely close in meaning but differ in the parameter type. Mixing them in user code will be error-prone. Renaming one of them – e.g. LegacyResponder or merging both into one canonical alias – will reduce ambiguity.

lib/src/adaptor/io/request.dart (2)

25-29: Header copy risks mutating the source map

request.headers.forEach((k, v) => mh[k] = v) stores the original List<String> objects coming from dart:io into your mutable Headers. Subsequent modifications by either side are now visible to the other. To maintain immutability guarantees, clone the list:

-    request.headers.forEach((final k, final v) => mh[k] = v);
+    request.headers.forEach(
+      (k, v) => mh[k] = List<String>.unmodifiable(v),
+    );

31-40: Pass a detached stream instead of the full HttpRequest

Body.fromDataStream only needs a Stream<List<int>>; handing over the entire HttpRequest leaks mutable state (e.g. it exposes response, uri, etc.) to lower layers. Use request.cast<List<int>>() to forward only the byte stream:

-    request,
+    request.cast<List<int>>(),
test/relic_server_serve_test.dart (3)

120-124: Unnecessary extra parentheses around createSyncHandler

The outer (…) pair creates no new closure – it just wraps an expression. Dropping them makes the call site cleaner:

-await _scheduleServer((createSyncHandler(
+await _scheduleServer(createSyncHandler(

255-259: Handler parameter still named request, but type is RequestContext

For consistency with the new API introduced in this PR, rename the variable to ctx (or give it an explicit RequestContext type) to avoid reader confusion.

-  final server = await testServe(
-    (final request) {
+  final server = await testServe(
+    (final RequestContext ctx) {
       Future(() => throw StateError('oh no'));
-      return syncHandler(request);
+      return syncHandler(ctx);
     },
   );

207-215: Casting to HijackableContext is unnecessary

ctx is already a HijackableContext when the server is configured for hijacking. Prefer using the helper introduced in handler.dart for clarity:

-  final hijackableContext = ctx as HijackableContext;
-  return hijackableContext.hijack(expectAsync1(...));
+  return hijack(expectAsync1(...))(ctx);
lib/src/middleware/middleware.dart (4)

20-22: Docs reference HijackException which no longer exists

The API comment still instructs middleware authors to re-throw HijackExceptions, but the hijack-exception mechanism was removed in this refactor. Keeping this note will confuse users and is technically wrong.

-/// Middleware that captures exceptions should be sure to pass
-/// [HijackException]s on without modification.
+/// (Legacy note removed – hijack exceptions are no longer part of the public
+/// API.)

45-49: Parameter docs lag behind implementation

createMiddleware now operates on the context-based pipeline, yet the parameter
docs still speak in terms of a bare Request/Response flow. This will mislead
users who try to type onRequest as FutureOr<RequestContext> etc.

Update the comment blocks so that:

  • onRequest is documented as receiving a Request (that’s fine) and must
    return a Response?, not a RequestContext.
  • onResponse receives a Response.
  • onError signature matches the typedef that appears in the source.

50-53: Avoid re-assigning nullable function parameters

Re-assigning the optional parameters (onRequest ??= …) mutates the original
variable that callers pass in. It is safer to introduce local variables so the
public API remains side-effect free.

-  onRequest ??= (final request) => null;
-  onResponse ??= (final response) => response;
+  final _onRequest = onRequest ?? (final _) => null;
+  final _onResponse = onResponse ?? (final response) => response;

(remember to replace later usages)


55-57: Redundant cast & comment

requestCtx has already been proven to be a RespondableContext; the extra
as RespondableContext (and the inline “why is this needed” comment) are
unnecessary and degrade readability.

-      final ctx = requestCtx as RespondableContext; // why is this needed
+      final ctx = requestCtx;
test/util/test_util.dart (2)

14-15: Typedef name slightly misleading

SyncHandler implies “synchronous” but the typedef still allows returning a
Future through subtype variance. To avoid accidental misuse consider naming it
SyncRequestContextHandler or enforce a non-Future return type.


42-48: makeSimpleRequest returns obscure error on wrong context type

Throwing ArgumentError(newCtx) when the handler doesn’t return a
ResponseContext hides the real problem. Provide a clearer message so failing
tests are actionable.

-  if (newCtx is! ResponseContext) throw ArgumentError(newCtx);
+  if (newCtx is! ResponseContext) {
+    throw StateError(
+        'Expected ResponseContext but got ${newCtx.runtimeType}: $newCtx');
+  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9879ba3 and 052b46a.

📒 Files selected for processing (57)
  • .github/workflows/dart-tests.yaml (1 hunks)
  • .gitignore (1 hunks)
  • example/example.dart (1 hunks)
  • lib/relic.dart (1 hunks)
  • lib/src/adaptor/adaptor.dart (1 hunks)
  • lib/src/adaptor/context.dart (1 hunks)
  • lib/src/adaptor/io/bind_http_server.dart (1 hunks)
  • lib/src/adaptor/io/http_response_extension.dart (4 hunks)
  • lib/src/adaptor/io/io_adaptor.dart (1 hunks)
  • lib/src/adaptor/io/request.dart (1 hunks)
  • lib/src/adaptor/io/response.dart (1 hunks)
  • lib/src/adaptor/security_options.dart (1 hunks)
  • lib/src/body/body.dart (0 hunks)
  • lib/src/body/types/mime_type.dart (0 hunks)
  • lib/src/handler/cascade.dart (2 hunks)
  • lib/src/handler/handler.dart (3 hunks)
  • lib/src/headers/codecs/common_types_codecs.dart (0 hunks)
  • lib/src/headers/headers.dart (0 hunks)
  • lib/src/headers/typed/headers/access_control_allow_methods_header.dart (0 hunks)
  • lib/src/hijack/exception/hijack_exception.dart (0 hunks)
  • lib/src/hijack/hijack.dart (0 hunks)
  • lib/src/io/static/directory_listing.dart (1 hunks)
  • lib/src/io/static/static_handler.dart (5 hunks)
  • lib/src/io_serve.dart (1 hunks)
  • lib/src/logger/logger.dart (0 hunks)
  • lib/src/message/request.dart (1 hunks)
  • lib/src/message/response.dart (0 hunks)
  • lib/src/middleware/middleware.dart (2 hunks)
  • lib/src/middleware/middleware_logger.dart (2 hunks)
  • lib/src/relic_server.dart (2 hunks)
  • lib/src/relic_server_serve.dart (0 hunks)
  • pubspec.yaml (2 hunks)
  • test/adaptor/server_adaptor_test.dart (1 hunks)
  • test/exception/relic_exceptions_test.dart (6 hunks)
  • test/handler/cascade_test.dart (8 hunks)
  • test/handler/pipeline_test.dart (2 hunks)
  • test/headers/basic/x_powered_by_header_test.dart (0 hunks)
  • test/headers/header_test.dart (0 hunks)
  • test/headers/headers_accessor_test.dart (1 hunks)
  • test/headers/headers_test_utils.dart (5 hunks)
  • test/headers/typed_headers/access_control_request_method_header_test.dart (0 hunks)
  • test/hijack/hijack_test.dart (0 hunks)
  • test/hijack/relic_hijack_test.dart (3 hunks)
  • test/message/apply_headers_test.dart (1 hunks)
  • test/message/request_test.dart (0 hunks)
  • test/message/response_test.dart (2 hunks)
  • test/middleware/create_middleware_test.dart (15 hunks)
  • test/middleware/log_middleware_test.dart (0 hunks)
  • test/relic_server_serve_test.dart (25 hunks)
  • test/relic_server_test.dart (3 hunks)
  • test/static/alternative_root_test.dart (1 hunks)
  • test/static/basic_file_test.dart (0 hunks)
  • test/static/default_document_test.dart (1 hunks)
  • test/static/directory_listing_test.dart (1 hunks)
  • test/static/symbolic_link_test.dart (1 hunks)
  • test/static/test_util.dart (3 hunks)
  • test/util/test_util.dart (1 hunks)
💤 Files with no reviewable changes (17)
  • test/headers/basic/x_powered_by_header_test.dart
  • test/static/basic_file_test.dart
  • test/message/request_test.dart
  • test/headers/header_test.dart
  • lib/src/logger/logger.dart
  • lib/src/headers/typed/headers/access_control_allow_methods_header.dart
  • lib/src/headers/codecs/common_types_codecs.dart
  • test/headers/typed_headers/access_control_request_method_header_test.dart
  • lib/src/body/body.dart
  • lib/src/body/types/mime_type.dart
  • test/middleware/log_middleware_test.dart
  • lib/src/hijack/exception/hijack_exception.dart
  • lib/src/message/response.dart
  • lib/src/headers/headers.dart
  • test/hijack/hijack_test.dart
  • lib/src/hijack/hijack.dart
  • lib/src/relic_server_serve.dart
🧰 Additional context used
🪛 GitHub Check: codecov/patch
lib/src/adaptor/io/response.dart

[warning] 16-16: lib/src/adaptor/io/response.dart#L16
Added line #L16 was not covered by tests

lib/src/handler/handler.dart

[warning] 50-50: lib/src/handler/handler.dart#L50
Added line #L50 was not covered by tests

🔇 Additional comments (74)
.github/workflows/dart-tests.yaml (1)

83-83: Enable complete matrix test runs
Adding fail-fast: false ensures all matrix combinations for unit tests execute, which helps surface failures across different OS/SDK/dependency configurations. Confirm that downstream steps (e.g., coverage upload) correctly interpret non-zero exit codes when continue-on-error is not set.

You may want to verify that the combination of continue-on-error and fail-fast: false behaves as intended in all scenarios.

pubspec.yaml (2)

7-7: Use caret syntax for SDK constraint
Switching from ">=3.3.0 <4.0.0" to ^3.3.0 preserves the original range. Ensure this aligns with the LOWEST_DART_SDK used in CI to avoid inadvertently allowing unsupported SDK versions.


20-20: Use caret syntax for http dev dependency
Updating http to ^1.0.0 maintains the previous range semantics (>=1.0.0 <2.0.0). Please confirm there are no downstream version conflicts introduced by this change.

test/message/apply_headers_test.dart (1)

9-9: Import path updated for IO adaptor extension
The test now imports http_response_extension.dart from the src/adaptor/io directory, matching the new adaptor-based structure. Ensure that the extension still defines applyHeaders and all tests pass against this relocated file.

.gitignore (1)

5-5: Ignore generated coverage reports
Adding coverage/ to .gitignore is a good practice to keep coverage artifacts out of version control.

lib/src/io/static/directory_listing.dart (1)

8-9: Adjust relative imports for reorganized directories
Updated imports to ../../body/body.dart and ../../message/response.dart to reflect the io/static folder hierarchy. Verify that these paths resolve correctly and that Body and Response are still exported from those modules.

test/static/default_document_test.dart (1)

5-5: Update import for relocated static handler
The static handler import has been changed to package:relic/src/io/static/static_handler.dart. Confirm that createStaticHandler is exported here and that all other static-serving tests use the same path.

test/headers/headers_accessor_test.dart (1)

173-173: Clarify test group for decode-counting behavior
The group name now clearly states it’s testing the “counts decodes” scenario using a non-const accessor to tally decode calls. This improves readability and intent.

lib/src/adaptor/security_options.dart (1)

1-11: Well-designed abstraction for platform-agnostic security options

The SecurityOptions class provides a clean abstraction for handling security contexts across different platforms. The use of Object as the type for the context field effectively decouples the security configuration from platform-specific implementations, which aligns with the broader architectural refactoring goals.

The documentation clearly explains the purpose of each element and the reasoning behind design decisions.

test/handler/cascade_test.dart (6)

10-28: Handler functions successfully adapted to the new context-based model

The changes wrap all responder functions with respondWith() to adapt them to the new handler interface that operates on RequestContext objects rather than raw Request objects. This is consistent with the PR's goal of refactoring the request handling mechanism to avoid using exceptions for control flow.


42-49: Request handling updated to use context-based API

The request handling code has been updated to use makeSimpleRequest(), which properly processes the context-based handler interface. This maintains the same test logic while adapting to the new architecture.


57-67: Cascade handlers correctly converted to use the context-based approach

All handlers in cascade tests have been consistently updated to use the new respondWith() wrapper, ensuring they work within the new request context model.


76-87: Cascade customization logic properly maintains context compatibility

The tests for customizing cascade behavior with statusCodes and shouldCascade parameters have been correctly updated to work with the new context-based architecture.


96-133: Error scenarios properly maintained in the refactored code

The error scenario tests have been preserved without changes since they don't directly interact with request handling logic, maintaining test coverage for important edge cases.


143-153: Custom cascade behavior testing correctly adapted

The tests for custom cascade behavior using the shouldCascade callback have been properly updated to use the context-based handler model.

lib/src/io/static/static_handler.dart (3)

10-19: Import paths updated to reflect the new directory structure

The import paths have been updated to use the new deeper directory structure, which is consistent with the architectural changes in the PR.


68-134: Static handler properly adapted to the new context-based model

The createStaticHandler function now wraps its handler logic with the respondWith() function, converting it to work with the new context-based handler interface. This ensures compatibility with the broader architectural changes.


185-206: File handler correctly adapted to the context-based approach

The createFileHandler function now wraps its handler logic with the respondWith() function, ensuring it works with the new context-based handler model.

test/handler/pipeline_test.dart (2)

2-2: Added import for context-based request handling

The new import for the context module supports the updated handler interface that works with request contexts instead of raw requests.


32-36: Inner handler signature updated to use context-based approach

The innerHandler function signature has been updated to accept and return a RequestContext instead of a Request/Response. This aligns with the new handler interface and ensures compatibility with the middleware pipeline being tested.

test/adaptor/server_adaptor_test.dart (1)

19-19: Good use of server.url abstraction.

Using server.url rather than hardcoded host/port demonstrates proper use of the adaptor abstraction, making the tests more robust when run in different environments.

test/message/response_test.dart (2)

56-58: Good refactoring of content type access pattern.

The change from using getContentType() to accessing bodyType?.mimeType and bodyType?.encoding properties aligns with the broader refactoring to remove direct dependencies on dart:io. This property-based approach is cleaner and more object-oriented than the previous method call.


67-68: Correctly updated assertion.

Properly updated to check encoding?.name instead of direct comparison, maintaining the test's intent while aligning with the new API.

lib/src/adaptor/io/bind_http_server.dart (2)

1-30: Clean HTTP server binding abstraction.

This function provides a well-designed abstraction over HTTP server binding with appropriate handling of both secure and non-secure server creation. The parameter structure with sensible defaults is excellent.


13-21: Good conditional logic for server type.

The conditional approach based on security context presence is clear and concise. This implementation makes it easy for callers to enable HTTPS by simply providing a security context.

lib/src/adaptor/io/response.dart (1)

7-29: Well-structured extension for IO-specific response handling.

This extension cleanly separates IO-specific response writing logic from the core Response class, aligning with the architectural goal of abstracting platform dependencies through adaptors.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 16-16: lib/src/adaptor/io/response.dart#L16
Added line #L16 was not covered by tests

test/relic_server_test.dart (6)

1-2: Good addition of timeout annotation.

Adding @Timeout.none will prevent test failures due to default timeout constraints, which is appropriate for tests that involve server operations.


14-15: Helpful code documentation.

The comment clearly explains why a concrete type is used rather than an interface or var, which helps future maintainers understand the design decision.


27-29: Proper asynchronous handling and URI validation.

The conversion to await pattern reflects the refactored asynchronous mountAndStart method, and the comment about using toUri explains the reasoning behind ensuring a valid URI object.


36-37: Consistent async pattern application.

Consistently awaiting the asynchronous mountAndStart method across all test cases ensures proper sequencing of operations.


48-49: Consistent async handling in delayed request test.

The change to await mountAndStart is consistent with the refactoring to make this method asynchronous, maintaining proper test sequencing.


55-56: Proper async handling in error case testing.

Consistently applying the async pattern to the error testing case maintains the integrity of the test suite with the refactored API.

lib/src/adaptor/io/http_response_extension.dart (4)

3-4: Updated import paths reflect refactored project structure.

These imports have been updated to reflect the new project structure, where dependencies are accessed from higher-level paths. This is consistent with the overall architectural refactoring.


77-84: Replaced named extension with anonymous extension.

Converting this to an anonymous extension reduces namespace pollution but might slightly impact code discoverability. However, this is appropriate since the extension is tightly coupled to this file's functionality.


86-97: Simplified extension implementation for TransferEncodingHeader.

Converting to an anonymous extension is appropriate here as these helper methods are implementation details not meant to be directly referenced elsewhere.


107-120: Good implementation of ContentType conversion.

This extension provides a clean way to convert between the library's Body type and dart:io ContentType, properly handling null cases. The implementation aligns with the architectural goal of isolating platform-specific code to adaptor classes.

lib/src/handler/cascade.dart (2)

1-1: Updated import to use context-based abstractions.

Replacing the dart:async import with the context module import reflects the architectural shift to context-based request handling, centralizing these abstractions.


72-79: Refactored handler implementation to use async/await and context types.

The implementation has been improved to:

  1. Use modern async/await pattern instead of Future chains
  2. Leverage the new RequestContext/ResponseContext types
  3. Properly handle the cascade logic based on response context

This refactoring aligns with the PR objective of removing exceptions for control flow.

lib/src/io_serve.dart (3)

1-8: Well-structured imports for IO server implementation.

The imports clearly separate standard library dependencies from package-specific modules, and bring in only the necessary components for server initialization.


9-20: Clear and comprehensive documentation with template tags.

The documentation effectively explains the function's purpose and uses template tags to make portions reusable across the codebase. The explanation of header behavior is particularly thorough.


21-30: Well-designed function signature with appropriate defaults.

The function signature exposes all necessary configuration options with sensible defaults, while maintaining a clean API. The optional parameters provide flexibility for different server configurations.

test/middleware/create_middleware_test.dart (2)

108-117: Avoid asserting inside production-style callbacks
expect() is executed from inside the onResponse middleware.
If the assertion fails it will surface as an uncaught exception rather than a
TestFailure, so the test runner may report the failure in an unexpected way
(or even mark the test as “error” instead of “fail”). Wrap the handler with
expectAsync* or return the future from the test so the failure is properly
tracked.

-  .addMiddleware(createMiddleware(onResponse: (final response) {
-    expect(...);             // may throw outside test zone
-    return _middlewareResponse;
-  }))
+  .addMiddleware(createMiddleware(onResponse: expectAsync1((final response) {
+    expect(...);
+    return _middlewareResponse;
+  }))

Confirm all other middleware callbacks that contain expect are wrapped the
same way to avoid hidden flakes.


227-230: Use the same error type when re-throwing
onError catches Object error and re-throws error.
If error is ResponseContext (because your new architecture allows returning
either a Response or throwing), you will be throwing a completely different
type than callers expect.

Add a type check or convert the error into an Exception before re-throwing to
avoid surprising downstream handlers.

- throw error;
+ if (error is Exception || error is Error) {
+   throw error;
+ } else {
+   throw StateError('Unhandled error: $error');
+ }
lib/src/adaptor/io/io_adaptor.dart (7)

1-10: Appropriate imports and organization

The imports are well-organized, with standard library imports first, followed by external packages, and then internal imports. The IO-specific code is properly namespaced with dart:io as io to avoid naming conflicts.


11-15: Clean implementation of IOAdaptor

Good implementation of the IOAdaptor class that properly extends the Adaptor interface. The constructor takes the underlying io.HttpServer and stores it as a private field, following good encapsulation practices.


16-21: Well-exposed server properties and request stream

The implementation correctly exposes the server's address and port properties and transforms the native HTTP request stream into the application's AdaptorRequest abstraction using a clean mapping function.


22-29: Proper response handling

The respond method correctly:

  1. Casts the request to the expected implementation type
  2. Extracts the native HTTP response object
  3. Uses the extension method to write the application's Response to the native response

This maintains clean separation between IO-specific and application code.


31-41: Clean socket hijacking implementation

The hijack method correctly:

  1. Casts the request to access the underlying HTTP request
  2. Detaches the socket without writing headers (appropriate for hijacking)
  3. Wraps the socket in a StreamChannel for bidirectional communication
  4. Passes the channel to the callback

This implements the socket hijacking pattern cleanly without relying on exceptions.


43-45: Server shutdown implementation

The close method correctly delegates to the underlying server's close method with force: true to ensure prompt cleanup of resources.


47-53: Well-designed adaptor request implementation

The _IOAdaptorRequest class cleanly wraps a native HTTP request and provides conversion to the application's Request abstraction. The private class implementation follows the pattern of hiding implementation details.

lib/src/middleware/middleware_logger.dart (3)

1-1: Added context import for new architecture

Appropriately added the import for context types to support the new context-based architecture.


22-28: Improved async handling with modern syntax

Good refactoring from chained .then() calls to modern async/await syntax, making the code more readable and maintainable.


41-57: Simplified error handling approach

The error handling has been properly simplified by removing special case handling for HijackException and using a standard try/catch block with rethrow. This aligns with the PR's goal of eliminating exception-based control flow.

test/exception/relic_exceptions_test.dart (6)

7-9: Updated imports for new test utilities

Correctly updated imports to use the new test utilities that support the context-based architecture.


10-23: Simplified server teardown

The server teardown logic has been simplified to use the new close() method on RelicServer which properly handles resource cleanup. This is cleaner than the previous implementation.


24-68: Updated exception tests to use new handler signature

All the exception tests have been properly updated to use the new handler signature, accepting an unused parameter (final _) instead of a Request object. This correctly aligns with the new context-based approach.


71-71: Updated server type

Correctly updated the server type from HttpServer? to RelicServer? to reflect the new server abstraction.


73-76: Simplified server setup

The server setup function has been simplified to use the new testServe utility function, which eliminates the need for manual server configuration. This is a good abstraction that hides implementation details.


77-92: Improved URL construction

The URL construction now uses the server's url property with replace(path: path) which is more maintainable than manual URI construction. This aligns with the overall simplification and abstraction goals.

test/hijack/relic_hijack_test.dart (6)

5-10: Updated imports for context-based approach

Correctly updated imports to include the context types and test utilities needed for the new context-based approach.


11-23: Simplified server teardown

The server teardown logic has been simplified similar to other test files, using the new close() method on RelicServer.


25-45: Rewritten test for context-based hijacking

The test has been properly rewritten to verify that when a NewContext is hijacked via its hijack method, a HijackContext is returned. This test correctly validates the new approach to hijacking without relying on exceptions.


48-48: Updated server type

Correctly updated the server type from HttpServer? to RelicServer? to reflect the new server abstraction.


50-56: TODO comment for security context

There's an unresolved TODO comment regarding security context that should be addressed.

Please clarify whether the security context functionality has been implemented elsewhere or if this is a feature that still needs to be implemented. If it's the latter, consider creating a follow-up task to track this work.


57-72: Improved URL construction

Similar to other test files, the URL construction now uses the server's url property with replace(path: path) instead of manual construction.

test/static/test_util.dart (1)

56-56: Preserve context data instead of rebuilding from scratch

Creating a brand-new context with relativeRequest.toContext() discards any
state that might have been attached to requestCtx (e.g. per-request
extensions, tracing information). Prefer cloning the existing context
while replacing only the request object if such an API exists
(ctx.copyWithRequest(relativeRequest)), or at minimum pass ctx
forward after mutation.

test/headers/headers_test_utils.dart (1)

85-91: respondWith callback ignores request body reading errors

Inside mountAndStart the callback touches the headers but does not guard
against malformed bodies or header parsing exceptions, meaning the server
could emit a 500 that the client interprets as 200. Consider validating
headers inside a try/catch and returning Response.badRequest() on error
so tests receive deterministic failures.

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

48-52: Missing test coverage for hijack helper

Code-coverage tooling points out that line 50 is not executed in tests. A trivial unit test that wraps a dummy HijackCallback would lock in the behaviour and protect against accidental API breaks.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 50-50: lib/src/handler/handler.dart#L50
Added line #L50 was not covered by tests

test/relic_server_serve_test.dart (1)

471-479:

Details

❌ Incorrect review comment

testServe argument label likely wrong – verify build passes

testServe(…, context: securityContext) looks suspicious: the parameter elsewhere is called securityContext. If the signature is in fact testServe({SecurityContext? securityContext}), the current named argument will not compile.


🏁 Script executed:

#
#!/bin/bash
# Locate testServe declaration and show its parameter list
rg -A3 -B3 $'Future<.*> testServe' | head -n 20

Length of output: 448


Ignore incorrect named argument concern for testServe

The testServe function in test/util/test_util.dart is declared as:

Future<RelicServer> testServe(
  Handler handler, {
  SecurityContext? context,
  String? poweredByHeader,
})

so calling it with context: securityContext is correct. No change required.

Likely an incorrect or invalid review comment.

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

68-69: Return value loses original context information

newCtx.withResponse(response) replaces the original response but drops any
fields that innerHandler might have added to ResponseContext (e.g. timing
metadata). Consider cloning the existing context rather than creating a fresh
one, or – if withResponse already copies auxiliary fields – document this
behaviour clearly.

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

189-190: Possible divergence between public contract and helper updateMap

updateMap returns Map<String, Object> but copyWith’s context parameter
accepts nullable values to remove keys. If updateMap still returns Map
with nullable values, declare the variable accordingly:

-    final newContext = updateMap(this.context, context);
+    final Map<String, Object?> newContext = updateMap(this.context, context);

Otherwise Object? values can leak into a field typed Map<String,Object> and
cause sound-null-safety violations elsewhere.

lib/src/relic_server.dart (2)

112-145: request shadowing makes stack-traces harder to read

Inside the middleware wrapper the parameter is called request; however there is already a Request variable named request in the outer _handleRequest scope. Shadowing different types with the same identifier complicates debugging and may cause accidental captures in future refactors.

Recommend renaming the middleware parameter to ctx (or similar) to reflect its RequestContext nature.

-    return (final request) async {
+    return (final ctx) async {
       try {
-        final newCtx = await handler(request);
+        final newCtx = await handler(ctx);

[ suggest_nitpick ]


120-127: Date header should be RFC-1123 formatted & immutable

DateTime.now() produces a local-timezone DateTime. HTTP/1.1 requires the Date header to be a IMF-fixdate (RFC-1123) in GMT. Consider formatting here or defer to HttpDate.format.

In addition, mutating mh.date inside transform relies on header objects being mutable. If Headers become immutable in future this silent mutation will break. Prefer constructing a new Headers instance.

[ suggest_optional_refactor ]

lib/src/adaptor/context.dart (1)

56-58: Minor naming – make the extension public or mark explicitly private

RequestInternal is currently public because the file is in lib/.
If this helper is intended for internal use only, prepend an underscore (_RequestContextX) or move to src/ to avoid leaking it in the public API.

[ suggest_nitpick ]

Comment thread lib/src/adaptor/io/response.dart Resolved
Comment thread lib/src/adaptor/adaptor.dart Resolved
Comment thread example/example.dart Resolved
Comment thread test/static/test_util.dart Resolved
Comment thread lib/src/relic_server.dart Resolved
Comment thread lib/src/relic_server.dart Resolved
Comment thread lib/src/adaptor/context.dart Resolved
Comment thread lib/src/adaptor/context.dart Resolved
Comment thread lib/src/adaptor/context.dart Resolved
@nielsenko
nielsenko force-pushed the no-hijack-exception branch from 052b46a to 408f138 Compare April 25, 2025 05:22
@nielsenko
nielsenko marked this pull request as ready for review April 25, 2025 07:49
@nielsenko
nielsenko requested a review from SandPod April 25, 2025 07:49

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Changes look good overall.

Had a couple of comments and questions.

Comment thread example/example.dart Resolved
Comment thread example/example.dart Resolved
Comment thread example/multi_isolate.dart Resolved
Comment thread lib/src/adaptor/io/io_adaptor.dart Resolved
Comment thread lib/src/hijack/hijack.dart Resolved
Comment thread test/handler/cascade_test.dart Resolved
Comment thread test/hijack/relic_hijack_test.dart Resolved
Comment thread lib/src/middleware/middleware.dart Resolved
Comment thread test/relic_server_test.dart Resolved
@nielsenko
nielsenko force-pushed the no-hijack-exception branch from 2a0a5e0 to f1f4e40 Compare April 25, 2025 13:07

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

Giving a thumb's up not to block merging this. But I would like to see the cast and dangerous dereff removed with the motivation provided.

@nielsenko
nielsenko merged commit 1b61832 into serverpod:main Apr 28, 2025
This was referenced May 22, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Aug 25, 2025
7 tasks done
@coderabbitai coderabbitai Bot mentioned this pull request Sep 19, 2025
7 of 9 tasks
@coderabbitai coderabbitai Bot mentioned this pull request Oct 22, 2025
8 of 9 tasks
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.

Handle request hijacking without using exceptions for control flow Isolate dart:io Usage to Enable Pluggable HTTP Backends

2 participants