Repository navigation
refactor!: Avoid using exceptions for control-flow - #48
Conversation
Rename IOServerAdaptor to IOAdaptor
Creating an IOAdaptor can be done with the function createIOAdaptor. Other adaptors should facilitate similar creation.
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the 📝 WalkthroughWalkthroughThis 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 Changes
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
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Connection info is adaptor specific information and do not belong on the Request class.
8e6fd19 to
fd31c4e
Compare
Codecov ReportAttention: Patch coverage is
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. 🚀 New features to boost your workflow:
|
fd31c4e to
052b46a
Compare
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 16
🔭 Outside diff range comments (1)
test/middleware/create_middleware_test.dart (1)
155-173: 🛠️ Refactor suggestionThrow dedicated
Exceptionobjects instead of bare strings
Several tests deliberately throw string literals (throw 'middleware error',
throw 'bad handler'). Dart’s analysis rule
only_throw_errorsis silenced at the top of the file, but relying on
non-Error/Exceptiontypes 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_errorsdirective.
🧹 Nitpick comments (25)
test/static/alternative_root_test.dart (1)
4-4: Update import path for static handler
The test now pulls instatic_handler.dartfrompackage:relic/src/io/static/static_handler.dartto reflect its new location. Ensure the file exists at that path and thatcreateStaticHandlerremains accessible. Consider re-exporting it via the public API to avoid deepsrc/imports in tests.Would you like to establish a public re-export in
lib/relic.dartso tests can importcreateStaticHandlerwithout referencingsrc/io/staticdirectly?test/static/directory_listing_test.dart (1)
5-5: Align static handler import path
This import was adjusted topackage:relic/src/io/static/static_handler.dart. Please verify that all static-related tests consistently use the updated path and thatcreateStaticHandleris 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 underlib/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
createStaticHandlerto 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 makingAdaptorgeneric and document lifecycle contracts
Right nowAdaptorRequestcan wrap anything (HTTP, gRPC, …) but the interface
does not clarify:
- whether
respond/hijackmay be called concurrently,- if
respondcan 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 withnumberOfProcessors * 2isolates
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 withPlatform.numberOfProcessorsand 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 notIOAdaptorThrowing 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 entirehandler.dartwidens the public API surfacePreviously only
Handlerwas 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 explicitshow 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.dartandsrc/io_serve.dartare exported at
the top level, yet the PR goal is to decouple fromdart: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
aniofeature flag to avoid accidental inclusion in web builds.lib/src/handler/handler.dart (2)
19-24: Consider tightening the typedef set –ResponseHandler/HijackHandlerare unused
ResponseHandlerandHijackHandlerlook 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 bydart analyzeasunused_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) andResponseHandler(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.LegacyResponderor 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 originalList<String>objects coming fromdart:iointo your mutableHeaders. 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 fullHttpRequest
Body.fromDataStreamonly needs aStream<List<int>>; handing over the entireHttpRequestleaks mutable state (e.g. it exposesresponse,uri, etc.) to lower layers. Userequest.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 aroundcreateSyncHandlerThe 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 namedrequest, but type isRequestContextFor consistency with the new API introduced in this PR, rename the variable to
ctx(or give it an explicitRequestContexttype) 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 toHijackableContextis unnecessary
ctxis already aHijackableContextwhen the server is configured for hijacking. Prefer using the helper introduced inhandler.dartfor clarity:- final hijackableContext = ctx as HijackableContext; - return hijackableContext.hijack(expectAsync1(...)); + return hijack(expectAsync1(...))(ctx);lib/src/middleware/middleware.dart (4)
20-22: Docs referenceHijackExceptionwhich no longer existsThe 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
createMiddlewarenow operates on the context-based pipeline, yet the parameter
docs still speak in terms of a bareRequest/Responseflow. This will mislead
users who try to typeonRequestasFutureOr<RequestContext>etc.Update the comment blocks so that:
onRequestis documented as receiving aRequest(that’s fine) and must
return aResponse?, not aRequestContext.onResponsereceives aResponse.onErrorsignature matches the typedef that appears in the source.
50-53: Avoid re-assigning nullable function parametersRe-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
requestCtxhas already been proven to be aRespondableContext; 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
SyncHandlerimplies “synchronous” but the typedef still allows returning a
Futurethrough subtype variance. To avoid accidental misuse consider naming it
SyncRequestContextHandleror enforce a non-Futurereturn type.
42-48:makeSimpleRequestreturns obscure error on wrong context typeThrowing
ArgumentError(newCtx)when the handler doesn’t return a
ResponseContexthides 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
📒 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
Addingfail-fast: falseensures 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 whencontinue-on-erroris not set.You may want to verify that the combination of
continue-on-errorandfail-fast: falsebehaves 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.0preserves the original range. Ensure this aligns with theLOWEST_DART_SDKused in CI to avoid inadvertently allowing unsupported SDK versions.
20-20: Use caret syntax forhttpdev dependency
Updatinghttpto^1.0.0maintains 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 importshttp_response_extension.dartfrom thesrc/adaptor/iodirectory, matching the new adaptor-based structure. Ensure that the extension still definesapplyHeadersand all tests pass against this relocated file..gitignore (1)
5-5: Ignore generated coverage reports
Addingcoverage/to.gitignoreis 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.dartand../../message/response.dartto reflect theio/staticfolder hierarchy. Verify that these paths resolve correctly and thatBodyandResponseare 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 topackage:relic/src/io/static/static_handler.dart. Confirm thatcreateStaticHandleris 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 optionsThe
SecurityOptionsclass provides a clean abstraction for handling security contexts across different platforms. The use ofObjectas the type for thecontextfield 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 modelThe changes wrap all responder functions with
respondWith()to adapt them to the new handler interface that operates onRequestContextobjects rather than rawRequestobjects. 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 APIThe 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 approachAll 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 compatibilityThe tests for customizing cascade behavior with
statusCodesandshouldCascadeparameters have been correctly updated to work with the new context-based architecture.
96-133: Error scenarios properly maintained in the refactored codeThe 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 adaptedThe tests for custom cascade behavior using the
shouldCascadecallback 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 structureThe 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 modelThe
createStaticHandlerfunction now wraps its handler logic with therespondWith()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 approachThe
createFileHandlerfunction now wraps its handler logic with therespondWith()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 handlingThe 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 approachThe
innerHandlerfunction signature has been updated to accept and return aRequestContextinstead of aRequest/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.urlrather 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 accessingbodyType?.mimeTypeandbodyType?.encodingproperties aligns with the broader refactoring to remove direct dependencies ondart: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?.nameinstead 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
Responseclass, 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 teststest/relic_server_test.dart (6)
1-2: Good addition of timeout annotation.Adding
@Timeout.nonewill 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
mountAndStartmethod, and the comment about usingtoUriexplains the reasoning behind ensuring a valid URI object.
36-37: Consistent async pattern application.Consistently awaiting the asynchronous
mountAndStartmethod across all test cases ensures proper sequencing of operations.
48-49: Consistent async handling in delayed request test.The change to await
mountAndStartis 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:
- Use modern async/await pattern instead of Future chains
- Leverage the new RequestContext/ResponseContext types
- 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 theonResponsemiddleware.
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
expectare wrapped the
same way to avoid hidden flakes.
227-230: Use the same error type when re-throwing
onErrorcatchesObject errorand re-throwserror.
IferrorisResponseContext(because your new architecture allows returning
either aResponseor throwing), you will be throwing a completely different
type than callers expect.Add a type check or convert the error into an
Exceptionbefore 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 organizationThe 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 ioto avoid naming conflicts.
11-15: Clean implementation of IOAdaptorGood implementation of the
IOAdaptorclass that properly extends theAdaptorinterface. The constructor takes the underlyingio.HttpServerand stores it as a private field, following good encapsulation practices.
16-21: Well-exposed server properties and request streamThe implementation correctly exposes the server's address and port properties and transforms the native HTTP request stream into the application's
AdaptorRequestabstraction using a clean mapping function.
22-29: Proper response handlingThe
respondmethod correctly:
- Casts the request to the expected implementation type
- Extracts the native HTTP response object
- Uses the extension method to write the application's
Responseto the native responseThis maintains clean separation between IO-specific and application code.
31-41: Clean socket hijacking implementationThe
hijackmethod correctly:
- Casts the request to access the underlying HTTP request
- Detaches the socket without writing headers (appropriate for hijacking)
- Wraps the socket in a
StreamChannelfor bidirectional communication- Passes the channel to the callback
This implements the socket hijacking pattern cleanly without relying on exceptions.
43-45: Server shutdown implementationThe
closemethod correctly delegates to the underlying server's close method withforce: trueto ensure prompt cleanup of resources.
47-53: Well-designed adaptor request implementationThe
_IOAdaptorRequestclass cleanly wraps a native HTTP request and provides conversion to the application'sRequestabstraction. 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 architectureAppropriately added the import for context types to support the new context-based architecture.
22-28: Improved async handling with modern syntaxGood refactoring from chained
.then()calls to modernasync/awaitsyntax, making the code more readable and maintainable.
41-57: Simplified error handling approachThe error handling has been properly simplified by removing special case handling for
HijackExceptionand 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 utilitiesCorrectly updated imports to use the new test utilities that support the context-based architecture.
10-23: Simplified server teardownThe server teardown logic has been simplified to use the new
close()method onRelicServerwhich properly handles resource cleanup. This is cleaner than the previous implementation.
24-68: Updated exception tests to use new handler signatureAll the exception tests have been properly updated to use the new handler signature, accepting an unused parameter
(final _)instead of aRequestobject. This correctly aligns with the new context-based approach.
71-71: Updated server typeCorrectly updated the server type from
HttpServer?toRelicServer?to reflect the new server abstraction.
73-76: Simplified server setupThe server setup function has been simplified to use the new
testServeutility function, which eliminates the need for manual server configuration. This is a good abstraction that hides implementation details.
77-92: Improved URL constructionThe URL construction now uses the server's
urlproperty withreplace(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 approachCorrectly updated imports to include the context types and test utilities needed for the new context-based approach.
11-23: Simplified server teardownThe server teardown logic has been simplified similar to other test files, using the new
close()method onRelicServer.
25-45: Rewritten test for context-based hijackingThe test has been properly rewritten to verify that when a
NewContextis hijacked via itshijackmethod, aHijackContextis returned. This test correctly validates the new approach to hijacking without relying on exceptions.
48-48: Updated server typeCorrectly updated the server type from
HttpServer?toRelicServer?to reflect the new server abstraction.
50-56: TODO comment for security contextThere'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 constructionSimilar to other test files, the URL construction now uses the server's
urlproperty withreplace(path: path)instead of manual construction.test/static/test_util.dart (1)
56-56: Preserve context data instead of rebuilding from scratchCreating a brand-new context with
relativeRequest.toContext()discards any
state that might have been attached torequestCtx(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 passctx
forward after mutation.test/headers/headers_test_utils.dart (1)
85-91:respondWithcallback ignores request body reading errorsInside
mountAndStartthe 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 atry/catchand returningResponse.badRequest()on error
so tests receive deterministic failures.lib/src/handler/handler.dart (1)
48-52: Missing test coverage forhijackhelperCode-coverage tooling points out that line 50 is not executed in tests. A trivial unit test that wraps a dummy
HijackCallbackwould 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 teststest/relic_server_serve_test.dart (1)
471-479:Details
❌ Incorrect review comment
testServeargument label likely wrong – verify build passes
testServe(…, context: securityContext)looks suspicious: the parameter elsewhere is calledsecurityContext. If the signature is in facttestServe({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 20Length of output: 448
Ignore incorrect named argument concern for testServe
The
testServefunction intest/util/test_util.dartis declared as:Future<RelicServer> testServe( Handler handler, { SecurityContext? context, String? poweredByHeader, })so calling it with
context: securityContextis 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 thatinnerHandlermight have added toResponseContext(e.g. timing
metadata). Consider cloning the existing context rather than creating a fresh
one, or – ifwithResponsealready copies auxiliary fields – document this
behaviour clearly.lib/src/message/request.dart (1)
189-190: Possible divergence between public contract and helperupdateMap
updateMapreturnsMap<String, Object>butcopyWith’scontextparameter
accepts nullable values to remove keys. IfupdateMapstill returnsMap
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 typedMap<String,Object>and
cause sound-null-safety violations elsewhere.lib/src/relic_server.dart (2)
112-145:requestshadowing makes stack-traces harder to readInside the middleware wrapper the parameter is called
request; however there is already aRequestvariable namedrequestin the outer_handleRequestscope. 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 itsRequestContextnature.- 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-timezoneDateTime. HTTP/1.1 requires theDateheader to be a IMF-fixdate (RFC-1123) in GMT. Consider formatting here or defer toHttpDate.format.In addition, mutating
mh.dateinsidetransformrelies on header objects being mutable. IfHeadersbecome immutable in future this silent mutation will break. Prefer constructing a newHeadersinstance.[ suggest_optional_refactor ]
lib/src/adaptor/context.dart (1)
56-58: Minor naming – make the extension public or mark explicitly private
RequestInternalis currently public because the file is inlib/.
If this helper is intended for internal use only, prepend an underscore (_RequestContextX) or move tosrc/to avoid leaking it in the public API.[ suggest_nitpick ]
052b46a to
408f138
Compare
… 'Hello World' server
.. and avoid calling `.toRequest()` twice.
SandPod
left a comment
There was a problem hiding this comment.
Changes look good overall.
Had a couple of comments and questions.
2a0a5e0 to
f1f4e40
Compare
SandPod
left a comment
There was a problem hiding this comment.
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.
Description
This PR avoids the exception based control flow employed by
shelfwrt. request hijacking.Instead it refactors the newly introduced
RequestContextclass to be a sum-type of:ResponseContext- a context that has been given aResponseHijackContext- a context that has been hijacked.NewContext- a new yet unhandled context.A
Handleris now a function taking and producingRequestContexts, ie:typedef Handler = FutureOr<RequestContext> Function(RequestContext)(the previous handler type is now called aResponder).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:
///), ensuring consistency with existing project documentation.Breaking Changes
This changes the
Handlertype which is pretty core to relic.Summary by CodeRabbit
New Features
Refactor
dart:ioand request hijacking with context-based APIs and adaptor interfaces.Bug Fixes
Chores
.gitignoreand version constraints inpubspec.yaml.