Repository navigation
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the 📝 WalkthroughWalkthroughThis pull request refactors the framework to abstract all direct usage of Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Adaptor (IOAdaptor)
participant RelicServer
participant Handler
Client->>Adaptor: HTTP request arrives
Adaptor->>RelicServer: Stream<RequestContext>
RelicServer->>Handler: Calls with Request
Handler-->>RelicServer: Returns Response
RelicServer->>Adaptor: Calls respond() on RequestContext with Response
Adaptor->>Client: Sends HTTP response
Assessment against linked issues
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 (
|
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #47 +/- ##
==========================================
+ Coverage 78.94% 79.43% +0.49%
==========================================
Files 70 73 +3
Lines 2170 2164 -6
Branches 1220 1231 +11
==========================================
+ Hits 1713 1719 +6
+ Misses 457 445 -12 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
bd094f6 to
7049b5d
Compare
77bbd25 to
be49cbc
Compare
Rename IOServerAdaptor to IOAdaptor
be49cbc to
7c539f3
Compare
Creating an IOAdaptor can be done with the function createIOAdaptor. Other adaptors should facilitate similar creation.
b88541e to
c1c31e5
Compare
2aabd36 to
e296bf9
Compare
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 10
🔭 Outside diff range comments (5)
lib/src/adaptor/io/http_response_extension.dart (2)
21-29:⚠️ Potential issueDon’t overwrite an explicit “Content-Type” header supplied by the caller
applyHeadersalways setsresponseHeaders.contentType = body.getContentType();even when the user already provided aContent-Typeheader. This unexpectedly discards the caller’s explicit header (e.g. a custom charset).-// Set Content-Type based on the MIME type of the body. -responseHeaders.contentType = body.getContentType(); +// Respect an explicitly supplied Content-Type header. +if (!headers.containsKey(Headers.contentTypeHeader)) { + responseHeaders.contentType = body.getContentType(); +}Failing to preserve the original header violates the principle of least surprise and may break clients that rely on a specific charset value.
31-46: 🛠️ Refactor suggestionMutating the original
Transfer-Encodinglist creates hidden side-effects
encodingsis a reference to the internal list returned byheaders.transferEncoding?.encodings.
When you lateradd(TransferEncoding.chunked)you mutate the sourceHeadersinstance, not just the outgoing response:final encodings = [...?headers.transferEncoding?.encodings];Copying the list (
[...encodings]) avoids this subtle shared-mutable-state bug.lib/src/message/request.dart (1)
1-1:⚠️ Potential issueRemove unused
dart:ioimportThe file now defines its own
ConnectionInfoand no longer referencesio.*, so theimport 'dart:io' as io;is unused and will trigger an analyzer hint.-import 'dart:io' as io; +// import 'dart:io' as io; // No longer neededIf other
partfiles still rely on the alias, move the import to those files instead to keep the public “core” message layer platform-agnostic.test/headers/headers_test_utils.dart (1)
19-54: 🛠️ Refactor suggestionGood extension implementation for testing URL handling.
The RelicServerTestEx extension provides a clean way to infer URLs for test servers using the new adaptor architecture. The approach with Expando is elegant for attaching additional test metadata to server instances.
However, the error handling could be improved:
Uri _inferUrl() { final adaptor = this.adaptor; - if (adaptor is! IOAdaptor) throw ArgumentError(); + if (adaptor is! IOAdaptor) throw ArgumentError('This extension only works with IOAdaptor instances'); if (adaptor.address.isLoopback) { return Uri(scheme: 'http', host: 'localhost', port: adaptor.port); }test/relic_server_serve_test.dart (1)
403-431:⚠️ Potential issueSkipped test with context parameter change.
The test for the "buffer_output" context parameter has been updated but is now skipped with a TODO comment. This should be addressed to ensure this functionality is properly tested.
The context key was renamed from 'relic_server.buffer_output' to 'buffer_output', but there's a comment indicating that this approach may need to be revisited. Please implement a solution for propagating the buffer_output parameter or document why this test is skipped.
🧹 Nitpick comments (12)
test/message/response_test.dart (1)
6-8: Avoid duplicate imports – switch to a single aliased import instead
Importing the same library twice (hide Requestfirst, then the full library) is redundant and will trigger a “Duplicate import” analyzer lint. If you need both the full API and to avoid theRequestsymbol clash you can solve it with an alias:-import 'package:relic/relic.dart' hide Request; -import 'package:relic/relic.dart'; +import 'package:relic/relic.dart' as relic;Then reference
relic.Request(or whatever symbols you need) in the test body.
This removes the duplication and keeps the intent explicit.lib/src/adaptor/io/http_response_extension.dart (1)
99-105: Dead-code alert – remove or justify theContentTypeExtension
The TODO already notes this extension is unused. Dead code complicates maintenance and confuses readers; delete it or add a concrete use-case (with tests) to justify its presence.example/example.dart (1)
18-21: UseIsolate.kill(priority: Isolate.immediate)for a faster shutdown
Callingkill()without a priority waits for each isolate’s next event loop turn. Using the immediate priority guarantees prompt termination, which is desirable during Ctrl-C shutdown.- i.kill(); + i.kill(priority: Isolate.immediate);lib/src/adaptor/adaptor.dart (1)
12-22: Clear adaptor abstraction with good documentation.The Adaptor interface provides a good abstraction that completely decouples the server from specific HTTP server implementations.
However, the documentation mentions "adaptor specific context" which "must be passed back along with the response" but this isn't explicitly represented in the API. Consider clarifying that the RequestContext itself serves as this container.
- /// The request may be is accompanied by an adaptor specific [context]. If so, it - /// must be passed back along with the response. + /// The RequestContext itself serves as the adaptor-specific context, + /// encapsulating both the request and the means to respond to it.test/exception/relic_exceptions_test.dart (1)
71-79: Server initialization updated to use test helpers.Good use of the new testServe helper function to simplify test server setup.
Remove the commented-out reference to securityContext since the parameter was removed from the method signature:
_server = await testServe( handler, - // context: securityContext, );test/hijack/relic_hijack_test.dart (1)
55-56: Minor: ignore parameter with_and discard bracesYou can shorten the closure to
request.hijack((_) {});—the explicitfinaland braces are optional here.- request.hijack((final _) {}); + request.hijack((_) {});Totally optional, but keeps style consistent with other tests.
lib/src/adaptor/io/io_adaptor.dart (1)
32-33: Use a getter forrequestsinstead of a mutablelatefieldAssigning
late Stream<RequestContext> requests = …makesrequestsmutable and initialised once in the constructor. A simple@override Stream<RequestContext> get requests => _server.map(_IORequestContext.new);:- @override - late Stream<RequestContext> requests = _server.map(_IORequestContext.new); + @override + Stream<RequestContext> get requests => + _server.map<RequestContext>(_IORequestContext.new);Advantages:
• guarantees immutability
• no risk of accidentally reassigning the field
• avoids the subtle order-of-initialisation issues thatlatecan introduce.lib/src/message/request.dart (1)
263-264: Keep generic types onupdateMapfor stricter type safetyDropping the explicit type args (
<String, Object?>) relies on inference, but herecontextis nullable whereasupdateMaplikely expectsMap<String, Object?>?. Being explicit avoids surprises ifupdateMap’s signature changes.- final newContext = updateMap(this.context, context); + final newContext = + updateMap<String, Object?>(this.context, context);[nitpick]
test/relic_server_serve_test.dart (2)
24-25: Simplified error handling during server shutdown.The error handling during server shutdown has been simplified by removing the forced close fallback logic, which is cleaner but assumes that a second close attempt will succeed without additional error handling.
Consider adding a timeout to the fallback close attempt:
try { await server.close().timeout(const Duration(seconds: 5)); } catch (e) { - await server.close(); + await server.close().timeout(const Duration(seconds: 10)); } finally { _server = null; }
495-498: Less specific parameter naming in _scheduleServer function.The parameter name changed from
securityContexttocontext, which is less specific and could be confusing.Future<void> _scheduleServer( final Handler handler, { final SecurityContext? securityContext, }) async { assert(_server == null); _server = await testServe( handler, - context: securityContext, + securityContext: securityContext, ); }This requires updating the testServe function to accept a parameter named
securityContextinstead of or in addition tocontext.lib/src/relic_server.dart (2)
52-54: Shut-down sequence should also dispose the adaptor
close()only cancels the subscription. If the adaptor owns network resources (e.g., sockets inIOAdaptor) they will remain open. Consider adding adispose()/close()method toAdaptorand invoking it here, falling back gracefully when the adaptor does not implement it.
110-116: HTTPDateheader should follow RFC 7231 format
DateTime.now()produces aDateTimeobject but the HTTP spec requires a specific string format (e.g., “Tue, 15 Nov 1994 08:12:31 GMT”). Withoutdart:io’sHttpDate.format, consider a small utility that formats aDateTimeto the correct wire format and reuse it here.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (51)
.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/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/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/io/static/directory_listing.dart(1 hunks)lib/src/io/static/static_handler.dart(1 hunks)lib/src/io_serve.dart(1 hunks)lib/src/logger/logger.dart(0 hunks)lib/src/message/request.dart(4 hunks)lib/src/message/response.dart(0 hunks)lib/src/middleware/middleware.dart(0 hunks)lib/src/middleware/middleware_logger.dart(1 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(3 hunks)test/handler/cascade_test.dart(0 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(4 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/log_middleware_test.dart(0 hunks)test/relic_server_serve_test.dart(13 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(1 hunks)test/util/test_util.dart(2 hunks)
💤 Files with no reviewable changes (18)
- lib/src/headers/codecs/common_types_codecs.dart
- test/headers/typed_headers/access_control_request_method_header_test.dart
- lib/src/headers/typed/headers/access_control_allow_methods_header.dart
- test/middleware/log_middleware_test.dart
- test/hijack/hijack_test.dart
- lib/src/logger/logger.dart
- test/headers/basic/x_powered_by_header_test.dart
- test/handler/cascade_test.dart
- test/static/basic_file_test.dart
- test/message/request_test.dart
- test/headers/header_test.dart
- lib/src/hijack/exception/hijack_exception.dart
- lib/src/body/types/mime_type.dart
- lib/src/middleware/middleware.dart
- lib/src/headers/headers.dart
- lib/src/message/response.dart
- lib/src/body/body.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
🔇 Additional comments (50)
.gitignore (1)
5-5: Ignore coverage directoryAdding
coverage/to.gitignorecorrectly excludes coverage artifacts generated by tests..github/workflows/dart-tests.yaml (1)
83-83: Disable fail-fast for unit test matrixSetting
fail-fast: falseensures that all matrix combinations run to completion even if some fail, providing full coverage of platform and SDK variations.test/static/alternative_root_test.dart (1)
4-4: Update static handler import pathThe import for
static_handler.dartnow points to the relocatedsrc/io/staticdirectory. Confirm that no old references tosrc/static/static_handler.dartremain and that all tests import the correct module.test/static/directory_listing_test.dart (1)
5-5: Update static handler import pathAligns with moving the static handler implementation under
src/io/static. Ensure consistency across all static-related tests and that the module is exported correctly inlib/relic.dart.test/static/default_document_test.dart (1)
5-5: Update static handler import pathImport updated to
package:relic/src/io/static/static_handler.dartto reflect the new directory structure. Verify other tests and examples have been updated similarly.test/message/apply_headers_test.dart (1)
9-9: Imports updated to new IO adaptor path – looks good.The test now correctly imports
http_response_extension.dartfrom the newsrc/adaptor/iodirectory, aligning with the refactored extension location. No functional changes are needed here.lib/src/io/static/directory_listing.dart (1)
8-9: Relative imports adjusted for new directory layout – LGTM.The imports for
BodyandResponsehave been updated to use two-level relative paths, matching the file’s move undersrc/io/static. Paths resolve correctly (../../body/body.dartand../../message/response.dart) and no logic was affected.lib/src/io/static/static_handler.dart (1)
10-18: Static handler imports realigned – no issues.All imports from
body,handler,headers,message, andmethodmodules now use two-level relative paths undersrc/io/static. This aligns with the file’s relocation and keeps the module references correct. The rest of the handler logic remains unchanged.test/static/symbolic_link_test.dart (1)
5-5: Static handler import path updated – approved.The test now correctly references the relocated
static_handler.dartundersrc/io/static. Everything else in the test remains the same and will continue to validate symlink behavior as before.test/static/test_util.dart (1)
5-5: Datetime extension import path updated – correct.The utility now imports
datetime_extension.dartfromsrc/io/static/extension, keeping it in sync with the code reorganization. No further changes are required here.pubspec.yaml (2)
7-7: Version constraint format improved for consistencyThe SDK constraint has been updated to use caret notation (
^3.3.0) instead of range notation (>=3.3.0 <4.0.0). This maintains the same semantic versioning requirements while using a more concise format.
20-20: Consistent version constraint format for dev dependenciesThe http package constraint has been similarly updated to use caret notation for consistency with other dependencies.
test/headers/headers_accessor_test.dart (1)
173-173: Improved test group description for clarityThe test group description now clearly explains that this group tests a header accessor that counts decodes, making the test purpose more explicit and easier to understand.
lib/src/adaptor/security_options.dart (1)
1-11: Well-designed platform-agnostic security abstractionThis new class provides an excellent abstraction for security options without introducing platform-specific dependencies. The approach of using
Objectas the type for the context field enables flexibility while maintaining the platform-agnostic nature of the core interfaces.Key benefits:
- Supports the decoupling from dart:io as specified in the PR objectives
- Enables secure server binding across different platforms
- Maintains a clean separation of concerns
test/util/test_util.dart (2)
3-3: Added dart:io import to support test server creationThis import is required for the new
testServefunction to useInternetAddress.loopbackIPv4. Note that while the PR aims to decouple from dart:io, this is specifically in a test utility which is an appropriate place for platform-specific code.
43-55: Added helpful test utility for consistent server creationThe new
testServefunction is a well-designed test helper that:
- Simplifies server setup in tests by providing sensible defaults
- Uses ephemeral port assignment (port 0) for parallel test execution
- Properly forwards security context and other optional parameters
This supports the PR's adaptor abstraction while making tests more concise and consistent.
lib/src/middleware/middleware_logger.dart (1)
4-4: Import change aligns with the HijackException relocation.This import change reflects the architectural refactoring where
HijackExceptionwas moved from its own file to therequest.dartfile as part of the decoupling from dart:io. This maintains the functionality of the error handling in Line 45 while supporting the larger abstraction effort.test/adaptor/server_adaptor_test.dart (1)
8-38: Well-structured test for the new adaptor abstraction.This test file properly validates the functionality of the new server adaptor abstraction with clean setup/teardown and clear assertions. The tests confirm that the adaptor correctly handles both root path and custom path requests, which is essential for verifying the refactoring work.
test/relic_server_test.dart (6)
1-2: Test configuration ensures reliable server testing.The
@Timeout.noneannotation prevents tests from failing due to variable server response times, which is appropriate for server-based tests.
14-15: Clear comment about type requirement.Good clarification about using a concrete type to ensure extensions are applied. This helps future maintainers understand why the specific type declaration is important.
27-31: Properly awaiting asynchronous server operations.The addition of
awaitforserver.mountAndStartis critical since this method has been refactored to be asynchronous in the new adaptor-based architecture. This ensures tests properly wait for server setup before proceeding with requests.
36-37: Consistent asynchronous handling.This change maintains consistency with the newly asynchronous nature of the
mountAndStartmethod, ensuring the test properly waits for the server to be ready.
48-50: Fixed asynchronous operation timing.Properly awaiting the mount operation ensures the test correctly verifies that requests are delayed until a handler is mounted, which is a key behavior of the server.
55-64: Correct error testing with asynchronous operations.Awaiting the first mount operation ensures the test correctly verifies that attempting to mount multiple handlers throws a StateError, validating an important constraint of the server.
lib/src/adaptor/io/bind_http_server.dart (1)
4-30: Well-designed server binding abstraction.This function cleanly encapsulates the creation of both HTTP and HTTPS servers behind a single interface, supporting the architectural goal of decoupling from dart:io. The function:
- Handles both standard and secure server creation
- Properly passes through all relevant configuration parameters
- Uses sensible defaults (port 0 for ephemeral ports)
- Consistently prefixes dart:io classes with
io.to avoid name conflictsThis is a key building block for the adaptor-based architecture that enables platform-agnostic server implementations.
test/message/response_test.dart (1)
55-70: Strengthen the null-safety checks aroundencoding
Response.internalServerError()guarantees a body, butbodyType?.encodingis still nullable. If the implementation ever returnsnull, theencoding?.nameaccess yieldsnulland theexpect(equals('utf-8'))will fail with a cryptic diff. Consider asserting non-null first for clearer intent:- final encoding = response.body.bodyType?.encoding; + final encoding = response.body.bodyType?.encoding; + expect(encoding, isNotNull, reason: 'internalServerError must set UTF-8');or switch to the non-null assertion operator (
response.body.bodyType!.encoding!.name).lib/src/adaptor/io/http_response_extension.dart (1)
63-73: HTTP/1.0 bodies are not chunked – guard by protocol version
_shouldEnableChunkedEncodingenables chunked encoding regardless of the client’s HTTP version. For HTTP/1.0 clients this will yield a malformed response. Consider checkingthis.headers.protocolVersion(orthis.persistentConnection) before enabling chunking.example/example.dart (1)
23-28: 🛠️ Refactor suggestionReplace blocking
sleepwith an async delay to keep the isolate responsiveThe synchronous
sleepblocks the entire isolate, preventing it from accepting new requests and defeating the concurrency benefit of multiple isolates.-Response _echoRequest(final Request request) { - sleep(const Duration(seconds: 1)); // pretend to be really slow - return Response.ok( +Future<Response> _echoRequest(final Request request) async { + await Future<void>.delayed(const Duration(seconds: 1)); // simulate latency + return Response.ok(
servewill happily await theFuture<Response>.Likely an incorrect or invalid review comment.
lib/src/io_serve.dart (1)
1-45: Well-structured implementation of the IO-specific serve function.This function sets up the server with an IOAdaptor wrapper around HttpServer, effectively decoupling the core RelicServer from dart:io implementation details. The function signature provides appropriate required and optional parameters with good documentation.
I particularly like the use of the template
{@template relic_server_header_defaults}for reusable header documentation, which ensures consistency across the API documentation.lib/src/adaptor/io/response.dart (1)
7-29: Good use of extension pattern for IO-specific functionality.The extension approach cleanly separates IO-specific code from the core Response class, aligning with the decoupling strategy. The implementation correctly handles status code, headers, and streaming the response body.
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 16-16: lib/src/adaptor/io/response.dart#L16
Added line #L16 was not covered by testslib/src/adaptor/adaptor.dart (1)
6-10: Clean abstraction for request context.This simple interface provides a good abstraction for handling requests and responses, enabling platform-agnostic request processing.
test/exception/relic_exceptions_test.dart (3)
7-8: Good update to imports reflecting the architectural changes.Replacing direct dart:io imports with test utilities aligns with the decoupling strategy.
11-22: Simplified server shutdown logic.The updated tearDown logic correctly uses the RelicServer close method, eliminating special handling that was needed for HttpServer.
85-88: Improved URL construction using RelicServer URL property.Using the server's URL property is cleaner than manually constructing the URL with hostname and port.
test/hijack/relic_hijack_test.dart (1)
7-9: LGTM – imports updated to new helpersThe switch to common test helpers (
headers_test_utils.dart,test_util.dart) reduces duplication and keeps the tests in sync with the new adaptor API.
No issues spotted.lib/src/adaptor/io/io_adaptor.dart (1)
18-21: Close theHttpResponseafter writing
response.writeHttpResponse()writes headers/body but does not automatically close the response (it usually returnsFuture<void>afterresponse.close()). Double-check the implementation; if it only writes bytes you still need:await response.writeHttpResponse(_ioRequest.response); await _ioRequest.response.close();Otherwise the connection may remain open until the client times out, especially for keep-alive requests.
lib/relic.dart (5)
3-3: Export of adaptor abstraction is a good separation of concerns.This new export is a key part of the architectural change, providing access to the
AdaptorandRequestContextabstractions that decouple the framework from directdart:iodependencies.
15-16: Organizational improvement for IO-specific code.Moving the static handler to an IO-specific path and adding the io_serve export properly separates platform-specific code from the core framework. This aligns well with the PR objective of decoupling from dart:io HttpServer.
17-17: Consolidated exception handling.The HijackException is now exported alongside Request, improving organization by keeping related functionality together. This is a good design decision that simplifies the import structure for consumers.
19-19: RequestMethod is now properly exported.Explicitly exporting the RequestMethod ensures that consumers have access to this important enum without needing to import it separately.
23-23: Simplified server export structure.Exporting the entire relic_server.dart file simplifies the API by providing a single source for server-related functionality rather than separate exports for different components.
test/headers/headers_test_utils.dart (2)
62-72: IPv6 support is commented out.The server creation logic only attempts IPv4 connections with IPv6 support commented out. This might limit testing on IPv6 networks.
Consider re-enabling IPv6 support or documenting why it's currently disabled. Also, you might want to add a more descriptive error message:
for (final address in [ -// InternetAddress.loopbackIPv6, + InternetAddress.loopbackIPv6, InternetAddress.loopbackIPv4 ]) { try { final adaptor = IOAdaptor(await bindHttpServer(address)); return RelicServer(adaptor, strictHeaders: strictHeaders); } on SocketException catch (_) { continue; } } - throw ArgumentError('Failed to load'); + throw ArgumentError('Failed to bind to any loopback address. Both IPv4 and IPv6 binding attempts failed.');
85-85: Correctly awaits the asynchronous server mount.The code properly awaits
server.mountAndStart(), which is important since the method signature has changed to be asynchronous in the refactored architecture.lib/src/adaptor/io/request.dart (2)
11-30: Well-structured request conversion function.The
fromHttpRequestfunction cleanly bridges between the native HttpRequest and the framework's Request abstraction, supporting the decoupling from dart:io.
59-63: Clean ContentType extension implementation.The extension to convert ContentType to MimeType is well-designed and clearly documented, with a good explanation of the naming choice to avoid conflicts.
test/relic_server_serve_test.dart (5)
232-237: Clean usage of the new testServe utility.The test now properly uses the new
testServefunction and server.url property instead of manually constructing server instances and URLs. This makes the code more maintainable and aligned with the new architecture.Also applies to: 239-239
268-282: Corrected error code expectation for bad HTTP host.The test now correctly expects a 400 Bad Request response instead of 500 Internal Server Error for a bad HTTP host request, which is the proper HTTP status code for this scenario.
437-442: Commented-out connection info assertions.The connection info assertions are commented out with a TODO. This should be addressed to ensure connection info is properly tested with the new adaptor architecture.
Replace the commented code with appropriate assertions for the new adaptor model:
final connectionInfo = request.connectionInfo!; /* TODO: expect(connectionInfo.remoteAddress, equals(_server!.address)); expect(connectionInfo.localPort, equals(_server!.port)); */ + expect(connectionInfo.remoteAddress, isNotEmpty); + expect(connectionInfo.localPort, equals(_server!.url.port));
459-459: Improved URL construction for SSL tests.The URL construction for SSL tests now uses
_server!.url.replace(scheme: 'https')instead of manual URI string building, which is cleaner and more maintainable.
486-488: Updated server port and type to match new architecture.The _serverPort getter and _server variable have been updated to work with the new RelicServer abstraction instead of directly with HttpServer.
Connection info is adaptor specific information and do not belong on the Request class.
2434c88 to
84d14c4
Compare
SandPod
left a comment
There was a problem hiding this comment.
Nice isolation of the IO package.
Cool that you have an example with multiple isolates, but I think we should promote the package with an easy to get started with example. Then we could have more advanced cases showcased later.
One comment that I had that I couldn't add to the file since it was simply moved:
io/static/extension/DatetimeExtension -> Feels like we have similar functionality somewhere else in the project as well. Should they be combined?
| print('Starting $isolateCount isolates'); | ||
| final isolates = await Future.wait(List.generate( | ||
| isolateCount, | ||
| (final index) => | ||
| Isolate.spawn((final _) => _serve(), null, debugName: '$index'))); |
There was a problem hiding this comment.
Suggestion: Simplify the initial example.
This is cool, but should probably be separated to a different example. I think the main example should show how easy it is to get started with the framework.
Running on multiple isolates is a really cool addition, but we should track it as a more advanced example and not the first one seen when getting started with the framework.
Ideally this should look really really simple, probably even without the sigint since that introduced redundant complexity to understand "Relic".
There was a problem hiding this comment.
Okay. My intention was to ensure that people understands how to utilize all CPU-cores on their servers. I'll move it to a different file and make example.dart really simple.
There was a problem hiding this comment.
We should showcase this as well! Wonder if we should have these in the README as a get started part? Since that is what you observe on the first page of pub.dev.
| Response _echoRequest(final Request request) { | ||
| sleep(const Duration(seconds: 1)); // pretend to be really slow | ||
| return Response.ok( | ||
| body: Body.fromString( | ||
| 'Request for "${request.url}"', | ||
| 'Request for "${request.url}" handled by isolate ${Isolate.current.debugName}', | ||
| ), | ||
| ); | ||
| } |
There was a problem hiding this comment.
Suggestion: Could we even remove this and only focus on starting the server?
There was a problem hiding this comment.
I'll make example.dart be a Hello World server, and move the current example to echo.dart.
| import 'util/util.dart'; | ||
|
|
||
| /// A [Server] backed by a `dart:io` [HttpServer]. | ||
| /// A server that uses a [Adaptor] to handle HTTP requests. |
There was a problem hiding this comment.
Question: Let's walk through the changes of this file tomorrow morning.
|
Superseded by #48 which sits on top of this PR |
Description
This diff introduces a layer of abstraction (
Adaptor) to decouple the core web framework logic from the specificdart:ioHttpServerimplementation. This potentially allowsrelicto run on different platforms or with different server backends in the future. The example and tests have been updated to reflect this new architecture.AdaptorAbstraction:Adaptorabstract class and aRequestContextinterface. This defines a contract for platform-specific server implementations to produce requests and handle responses.IOAdaptor) is added, wrappingdart:io.HttpServer.Core Library Refactoring:
RelicServer(lib/src/relic_server.dart) is refactored to take anAdaptorin its constructor instead of creating anHttpServerdirectly. It now listens to theadaptor.requestsstream.servefunction (lib/src/relic_server_serve.dart) is deleted.servefunction is created inlib/src/io_serve.dart. This function now creates anIOAdaptorand passes it to theRelicServer.dart:ioimports and dependencies have been removed from several core files:Example Update:
servefunction.shared: true, leveraging the new server architecture. It also includes basic graceful shutdown logic usingProcessSignal.sigint.Testing:
RelicServerand the newservefunction.testServeis introduced to simplify server setup in tests.CI/CD & Configuration:
fail-fast: falseto the strategy matrix, allowing all jobs in the matrix to run even if one fails.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 PR changes the public interface of various classes, most importantly
RelicServer.Additional notes
This PR is probably best reviewed "squashed" instead of commit-by-commit. There has been some back and fourth.
Also, there is another significant refactoring PR inbound in so I suggest spending less time on this and more time on that, if time is at a premium.
Summary by CodeRabbit
New Features
Refactor
Bug Fixes
Chores
Documentation
Style