Skip to content

refactor!: Decouple from dart:io HttpServer - #47

Closed
nielsenko wants to merge 15 commits into
serverpod:mainfrom
nielsenko:dart-io-decoupling
Closed

nielsenko wants to merge 15 commits into
serverpod:mainfrom
nielsenko:dart-io-decoupling

Conversation

@nielsenko

@nielsenko nielsenko commented Apr 22, 2025 •

Copy link
Copy Markdown
Collaborator

Description

This diff introduces a layer of abstraction (Adaptor) to decouple the core web framework logic from the specific dart:io HttpServer implementation. This potentially allows relic to run on different platforms or with different server backends in the future. The example and tests have been updated to reflect this new architecture.

  1. Adaptor Abstraction:

    • Introduces the Adaptor abstract class and a RequestContext interface. This defines a contract for platform-specific server implementations to produce requests and handle responses.
    • An IO-specific implementation (IOAdaptor) is added, wrapping dart:io.HttpServer.
  2. Core Library Refactoring:

    • RelicServer (lib/src/relic_server.dart) is refactored to take an Adaptor in its constructor instead of creating an HttpServer directly. It now listens to the adaptor.requests stream.
    • The old top-level serve function (lib/src/relic_server_serve.dart) is deleted.
    • A new IO-specific serve function is created in lib/src/io_serve.dart. This function now creates an IOAdaptor and passes it to the RelicServer.
    • dart:io imports and dependencies have been removed from several core files:
  3. Example Update:

    • The example is updated to use the new serve function.
    • It now demonstrates creating multiple isolates sharing the same port using shared: true, leveraging the new server architecture. It also includes basic graceful shutdown logic using ProcessSignal.sigint.
  4. Testing:

    • Tests are significantly updated to work with the refactored RelicServer and the new serve function.
    • A new test helper testServe is introduced to simplify server setup in tests.
  5. CI/CD & Configuration:

    • Added fail-fast: false to 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:

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

    • Introduced an adaptor-based server architecture, allowing for more flexible server implementations.
    • Added new abstractions for request context and adaptors, enabling support for different server backends.
    • Provided new utility functions for binding and serving HTTP servers.
    • Enhanced test utilities and introduced new tests for server adaptors.
  • Refactor

    • Refactored server logic to use adaptor interfaces instead of direct HTTP server usage.
    • Simplified and reorganized export statements for better maintainability.
    • Updated test infrastructure to use higher-level server abstractions.
  • Bug Fixes

    • Improved error handling and middleware wrapping for request processing.
    • Corrected expected error codes in certain test cases.
  • Chores

    • Updated SDK and dependency version constraints.
    • Improved .gitignore to exclude coverage reports.
  • Documentation

    • Clarified comments and improved test descriptions for better readability.
  • Style

    • Minor import and formatting cleanups across several files.

@coderabbitai

coderabbitai Bot commented Apr 22, 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 pull request refactors the framework to abstract all direct usage of dart:io for HTTP server functionality behind platform-agnostic interfaces. It introduces new adaptor classes and interfaces to encapsulate HTTP requests, responses, and server operations, moving dart:io-specific logic into internal modules. The core server logic, request/response handling, and middleware are updated to interact with these abstractions. The public API and exports are reorganized to reflect this separation. Associated tests and utilities are updated to use the new abstractions, and all references to direct dart:io usage in core logic are removed or isolated.

Changes

File(s) / Path(s) Change Summary
lib/relic.dart Refactored and reorganized exports; removed direct dart:io exports; grouped and broadened exports for new abstractions.
lib/src/relic_server.dart Refactored RelicServer to use Adaptor abstraction instead of dart:io's HttpServer; updated methods for new request/response flow; centralized middleware.
lib/src/message/request.dart Removed direct dart:io types; added ConnectionInfo and HijackException classes; updated request construction.
lib/src/message/response.dart Removed writeHttpResponse method and direct dart:io dependency.
lib/src/body/body.dart, lib/src/body/types/mime_type.dart, lib/src/headers/headers.dart Removed direct dart:io integrations and related constructors/extensions.
lib/src/hijack/exception/hijack_exception.dart Deleted file; HijackException now defined elsewhere.
lib/src/adaptor/adaptor.dart, lib/src/adaptor/io/io_adaptor.dart, lib/src/adaptor/io/request.dart, lib/src/adaptor/io/response.dart, lib/src/adaptor/io/bind_http_server.dart, lib/src/adaptor/security_options.dart Introduced new adaptor interfaces and IO-specific implementations to encapsulate HTTP server, request, and response logic.
lib/src/io_serve.dart Added new serve function using the adaptor abstraction for server startup.
lib/src/io/static/static_handler.dart, lib/src/io/static/directory_listing.dart Updated import paths to match new structure.
example/example.dart Refactored to demonstrate multi-isolate server using new abstractions.
test/*, test/util/test_util.dart, test/headers/headers_test_utils.dart Updated tests and utilities to use new server, adaptor, and request abstractions; removed direct dart:io usage; added utility wrappers.
.github/workflows/dart-tests.yaml, .gitignore, pubspec.yaml Minor config and ignore file updates.

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
Loading

Assessment against linked issues

Objective (Issue #) Addressed Explanation
Abstract all direct usage of dart:io behind platform-agnostic interfaces; refactor core to use these abstractions; move dart:io logic into internal implementation (#40) ✅

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.

@codecov

codecov Bot commented Apr 22, 2025 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 94.84536% with 5 lines in your changes missing coverage. Please review.

Project coverage is 79.43%. Comparing base (9879ba3) to head (1544146).

Files with missing lines Patch % Lines
lib/src/adaptor/io/response.dart 71.42% 2 Missing ⚠️
lib/src/adaptor/io/http_response_extension.dart 87.50% 1 Missing ⚠️
lib/src/message/request.dart 66.66% 1 Missing ⚠️
lib/src/relic_server.dart 97.61% 1 Missing ⚠️
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.
📢 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 dart-io-decoupling branch from bd094f6 to 7049b5d Compare April 22, 2025 07:32
@nielsenko nielsenko changed the title Decouple from dart:io HttpServer refactor!: Decouple from dart:io HttpServer Apr 22, 2025
@nielsenko
nielsenko force-pushed the dart-io-decoupling branch 2 times, most recently from 77bbd25 to be49cbc Compare April 22, 2025 11:21
Rename IOServerAdaptor to IOAdaptor
@nielsenko
nielsenko force-pushed the dart-io-decoupling branch from be49cbc to 7c539f3 Compare April 22, 2025 11:37
Creating an IOAdaptor can be done with the function createIOAdaptor.
Other adaptors should facilitate similar creation.
@nielsenko
nielsenko force-pushed the dart-io-decoupling branch from b88541e to c1c31e5 Compare April 23, 2025 08:07
@nielsenko
nielsenko force-pushed the dart-io-decoupling branch from 2aabd36 to e296bf9 Compare April 23, 2025 12:41
@nielsenko
nielsenko marked this pull request as ready for review April 24, 2025 03:15
@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.

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

🔭 Outside diff range comments (5)
lib/src/adaptor/io/http_response_extension.dart (2)

21-29: ⚠️ Potential issue

Don’t overwrite an explicit “Content-Type” header supplied by the caller
applyHeaders always sets responseHeaders.contentType = body.getContentType(); even when the user already provided a Content-Type header. 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 suggestion

Mutating the original Transfer-Encoding list creates hidden side-effects
encodings is a reference to the internal list returned by headers.transferEncoding?.encodings.
When you later add(TransferEncoding.chunked) you mutate the source Headers instance, 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 issue

Remove unused dart:io import

The file now defines its own ConnectionInfo and no longer references io.*, so the import 'dart:io' as io; is unused and will trigger an analyzer hint.

-import 'dart:io' as io;
+// import 'dart:io' as io; // No longer needed

If other part files 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 suggestion

Good 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 issue

Skipped 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 Request first, then the full library) is redundant and will trigger a “Duplicate import” analyzer lint. If you need both the full API and to avoid the Request symbol 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 the ContentTypeExtension
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: Use Isolate.kill(priority: Isolate.immediate) for a faster shutdown
Calling kill() 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 braces

You can shorten the closure to request.hijack((_) {});—the explicit final and 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 for requests instead of a mutable late field

Assigning late Stream<RequestContext> requests = … makes requests mutable 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 that late can introduce.

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

263-264: Keep generic types on updateMap for stricter type safety

Dropping the explicit type args (<String, Object?>) relies on inference, but here context is nullable whereas updateMap likely expects Map<String, Object?>?. Being explicit avoids surprises if updateMap’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 securityContext to context, 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 securityContext instead of or in addition to context.

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 in IOAdaptor) they will remain open. Consider adding a dispose()/close() method to Adaptor and invoking it here, falling back gracefully when the adaptor does not implement it.


110-116: HTTP Date header should follow RFC 7231 format
DateTime.now() produces a DateTime object but the HTTP spec requires a specific string format (e.g., “Tue, 15 Nov 1994 08:12:31 GMT”). Without dart:io’s HttpDate.format, consider a small utility that formats a DateTime to the correct wire format and reuse it here.

📜 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 01240fc.

📒 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 directory

Adding coverage/ to .gitignore correctly excludes coverage artifacts generated by tests.

.github/workflows/dart-tests.yaml (1)

83-83: Disable fail-fast for unit test matrix

Setting fail-fast: false ensures 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 path

The import for static_handler.dart now points to the relocated src/io/static directory. Confirm that no old references to src/static/static_handler.dart remain and that all tests import the correct module.

test/static/directory_listing_test.dart (1)

5-5: Update static handler import path

Aligns with moving the static handler implementation under src/io/static. Ensure consistency across all static-related tests and that the module is exported correctly in lib/relic.dart.

test/static/default_document_test.dart (1)

5-5: Update static handler import path

Import updated to package:relic/src/io/static/static_handler.dart to 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.dart from the new src/adaptor/io directory, 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 Body and Response have been updated to use two-level relative paths, matching the file’s move under src/io/static. Paths resolve correctly (../../body/body.dart and ../../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, and method modules now use two-level relative paths under src/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.dart under src/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.dart from src/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 consistency

The 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 dependencies

The 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 clarity

The 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 abstraction

This new class provides an excellent abstraction for security options without introducing platform-specific dependencies. The approach of using Object as 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 creation

This import is required for the new testServe function to use InternetAddress.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 creation

The new testServe function is a well-designed test helper that:

  1. Simplifies server setup in tests by providing sensible defaults
  2. Uses ephemeral port assignment (port 0) for parallel test execution
  3. 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 HijackException was moved from its own file to the request.dart file 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.none annotation 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 await for server.mountAndStart is 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 mountAndStart method, 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:

  1. Handles both standard and secure server creation
  2. Properly passes through all relevant configuration parameters
  3. Uses sensible defaults (port 0 for ephemeral ports)
  4. Consistently prefixes dart:io classes with io. to avoid name conflicts

This 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 around encoding
Response.internalServerError() guarantees a body, but bodyType?.encoding is still nullable. If the implementation ever returns null, the encoding?.name access yields null and the expect(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
_shouldEnableChunkedEncoding enables chunked encoding regardless of the client’s HTTP version. For HTTP/1.0 clients this will yield a malformed response. Consider checking this.headers.protocolVersion (or this.persistentConnection) before enabling chunking.

example/example.dart (1)

23-28: 🛠️ Refactor suggestion

Replace blocking sleep with an async delay to keep the isolate responsive

The synchronous sleep blocks 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(

serve will happily await the Future<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 tests

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

The 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 the HttpResponse after writing

response.writeHttpResponse() writes headers/body but does not automatically close the response (it usually returns Future<void> after response.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 Adaptor and RequestContext abstractions that decouple the framework from direct dart:io dependencies.


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 fromHttpRequest function 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 testServe function 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.

Comment thread example/example.dart Resolved
Comment thread lib/src/adaptor/io/response.dart Resolved
Comment thread test/hijack/relic_hijack_test.dart Resolved
Comment thread lib/src/adaptor/io/io_adaptor.dart Resolved
Comment thread lib/src/message/request.dart Resolved
Comment thread lib/src/adaptor/io/request.dart Resolved
Comment thread lib/src/adaptor/io/request.dart Resolved
Comment thread lib/src/adaptor/io/request.dart Resolved
Comment thread lib/src/relic_server.dart Resolved
Comment thread lib/src/relic_server.dart Resolved
@nielsenko
nielsenko requested a review from SandPod April 24, 2025 06:50
@nielsenko nielsenko self-assigned this Apr 24, 2025
@nielsenko
nielsenko force-pushed the dart-io-decoupling branch from 2434c88 to 84d14c4 Compare April 24, 2025 13:52

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

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?

Comment thread example/example.dart
Comment on lines +10 to +14
print('Starting $isolateCount isolates');
final isolates = await Future.wait(List.generate(
isolateCount,
(final index) =>
Isolate.spawn((final _) => _serve(), null, debugName: '$index')));

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.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

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.

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.

Comment thread example/example.dart
Comment on lines 30 to 37
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}',
),
);
}

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.

Suggestion: Could we even remove this and only focus on starting the server?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I'll make example.dart be a Hello World server, and move the current example to echo.dart.

Comment thread lib/src/adaptor/security_options.dart Resolved
Comment thread lib/src/adaptor/adaptor.dart Resolved
Comment thread test/adaptor/server_adaptor_test.dart Resolved
Comment thread test/headers/headers_test_utils.dart Resolved
Comment thread test/hijack/relic_hijack_test.dart Resolved
Comment thread test/message/response_test.dart Resolved
Comment thread lib/src/relic_server.dart
import 'util/util.dart';

/// A [Server] backed by a `dart:io` [HttpServer].
/// A server that uses a [Adaptor] to handle HTTP requests.

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.

Question: Let's walk through the changes of this file tomorrow morning.

@nielsenko

Copy link
Copy Markdown
Collaborator Author

Superseded by #48 which sits on top of this PR

@nielsenko nielsenko closed this Apr 25, 2025
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.

Isolate dart:io Usage to Enable Pluggable HTTP Backends

2 participants