Skip to content

feat!: Introduce RelicApp - #212

Merged
nielsenko merged 8 commits into
serverpod:mainfrom
nielsenko:app
Oct 16, 2025
Merged

nielsenko merged 8 commits into
serverpod:mainfrom
nielsenko:app

Conversation

@nielsenko

@nielsenko nielsenko commented Oct 10, 2025 •

Copy link
Copy Markdown
Collaborator

Description

This PR introduces RelicApp, a new class that extends Router<Handler> to simplify common usage patterns and reduce boilerplate for getting started with Relic.

  • Added RelicApp class in lib/src/router/router.dart with a run() method that handles adapter setup and server lifecycle
  • Added RelicAppIOServeEx extension in lib/src/adapter/io/io_serve.dart providing a convenient serve() method with sensible defaults
  • Added IOAdapter.bind() static factory method for cleaner adapter creation
  • Updated all examples to use RelicApp instead of Router<Handler> + serve()
  • Updated test utilities to use the new pattern

Why this is beneficial:

  • Matches conventions from popular frameworks (Express, Flask, ASP.NET Core)
  • Reduces boilerplate - no need for .asHandler extension or dart:io imports in simple cases
  • Better discoverability through IDE autocomplete
  • More intuitive for beginners while maintaining full flexibility for advanced users
  • Only ~10 lines of core implementation

Before:

final router = Router<Handler>()..get('/hello', handler);
await serve(router.asHandler, InternetAddress.anyIPv4, 8080);

After:

final app = RelicApp()..get('/hello', handler);
await app.serve(); // Defaults: localhost:8080

Related Issues

Pre-Launch Checklist

  • This update focuses on a single feature or bug fix.
  • 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.

serve() is now an extension method on RelicApp.

Additional Notes

  • Advanced users can use app.run() with custom adapters
  • Router composition (attach(), group()) works seamlessly with RelicApp

Summary by CodeRabbit

  • New Features
    • Streamlined HTTP server initialization and app-based configuration with a simpler serve() flow.
  • Examples
    • Updated example apps to use the new app-centric startup and routing pattern.
  • Tests
    • Added unit tests validating the new app lifecycle and server startup/teardown.
  • Chores
    • Minor cleanup of middleware wiring and not-found handling consolidation.

@coderabbitai

coderabbitai Bot commented Oct 10, 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.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

Adds a RelicApp class with run() and a RelicApp.serve() extension, an IOAdapter.bind() factory, replaces the top-level serve(handler, ...) flow, updates examples/tests to use RelicApp and app.serve(), and adapts test utilities to bind and mount IOAdapter directly.

Changes

Cohort / File(s) Summary
Examples → RelicApp
example/context.dart, example/context_property.dart, example/example.dart, example/hello_world.dart, example/middleware_example.dart, example/multi_isolate.dart, example/static_files_example.dart
Replaced Router/handler + top-level serve() usage with RelicApp instantiation, route wiring on app, and app.serve() startup. Removed dart:io imports and simplified not-found/fallback wiring and middleware composition.
Core router / RelicApp
lib/src/router/router.dart
Added RelicApp (extends RelicRouter) with Future<RelicServer> run(FutureOr<Adapter> Function() adapterFactory) to create, mount, and start a RelicServer.
IO adapter factory
lib/src/adapter/io/io_adapter.dart
Added static IOAdapter.bind(...) factory that awaits bindHttpServer(...) and returns an IOAdapter instance. Imported bind_http_server.dart.
IO serve extension
lib/src/adapter/io/io_serve.dart
Removed top-level serve(...) function; added extension RelicAppIOServeEx on RelicApp exposing serve({InternetAddress? address, int port = 8080, SecurityContext? securityContext, int? backlog, bool shared = false}) that delegates to run() and IOAdapter.bind().
Tests: RelicApp & utilities
test/router/relic_app_test.dart, test/util/test_util.dart
Added relic_app_test.dart covering RelicApp instantiation, callability, run/serve lifecycle with a fake adapter; updated testServe() to asynchronously bind IOAdapter, construct RelicServer, mount handler, and return the server.
PR notes / revert doc
relicapp_pr.md
Documents the additive RelicApp pattern and lists removals/reverts (RelicApp, extension, IOAdapter.bind) if reverted; included as narrative/context.

Sequence Diagram(s)

sequenceDiagram
    participant Dev
    participant RelicApp
    participant ServeExt as RelicAppIOServeEx
    participant IOAdapter
    participant BindHttp as bindHttpServer
    participant RelicServer
    participant Handler

    rect rgba(220,240,255,0.35)
    note right of Dev: App composition & serve()
    Dev->>RelicApp: app = RelicApp()
    Dev->>RelicApp: app.get('/path', handler)
    Dev->>RelicApp: await app.serve()
    end

    ServeExt->>IOAdapter: IOAdapter.bind(address, port, ...)
    IOAdapter->>BindHttp: bindHttpServer(address, port, ...)
    BindHttp-->>IOAdapter: HttpServer
    IOAdapter-->>ServeExt: IOAdapter

    ServeExt->>RelicApp: run(() => IOAdapter)
    RelicApp->>RelicServer: RelicServer(adapter)
    RelicServer->>RelicServer: mountAndStart(app.call)
    RelicServer-->>Dev: Future<RelicServer>

    Dev->>RelicServer: incoming HTTP request
    RelicServer->>RelicApp: call(request)
    RelicApp->>Handler: route -> handler
    Handler-->>Dev: response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Title Check ✅ Passed The pull request title "feat!: Introduce RelicApp" clearly summarizes the primary change by indicating the introduction of the RelicApp class and expresses the breaking change intent, making it concise and directly related to the main change in the changeset.
Linked Issues Check ✅ Passed The changes implement the key coding requirements from issue #222 by adding RelicApp with a run() method, introducing the RelicAppIOServeEx extension for serve(), providing the IOAdapter.bind() static factory, and updating examples and tests to use the new pattern in line with the linked issue’s objectives.
Out of Scope Changes Check ✅ Passed All modifications strictly relate to introducing and integrating RelicApp and its supporting functions without any unrelated or extraneous changes outside the scope defined by the linked issue.
Description Check ✅ Passed The pull request description follows the repository template by providing a detailed description, listing related issues, completing the pre-launch checklist, outlining breaking changes, and including additional notes, ensuring all required sections are present and clearly filled out.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@codecov

codecov Bot commented Oct 10, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.78%. Comparing base (33e64fb) to head (4fa84cb).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #212      +/-   ##
==========================================
+ Coverage   91.77%   91.78%   +0.01%     
==========================================
  Files          87       87              
  Lines        3258     3262       +4     
  Branches     1674     1677       +3     
==========================================
+ Hits         2990     2994       +4     
  Misses        268      268              

☔ 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 app branch 10 times, most recently from 07a9857 to c73879e Compare October 14, 2025 13:09
@nielsenko nielsenko self-assigned this Oct 14, 2025
@nielsenko
nielsenko force-pushed the app branch 7 times, most recently from b1246ac to 015bce2 Compare October 15, 2025 11:56
@nielsenko nielsenko changed the title feat: Introduce RelicApp feat!: Introduce RelicApp Oct 15, 2025
@nielsenko
nielsenko force-pushed the app branch 4 times, most recently from 865c85e to 7696b41 Compare October 16, 2025 07:20
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Oct 16, 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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
example/middleware_example.dart (1)

50-56: Avoid unsafe cast of Authorization header

Casting with as BearerAuthorizationHeader? will throw if a non-Bearer auth header is present. Use an is check.

-      final bearer =
-          ctx.request.headers.authorization as BearerAuthorizationHeader?;
+      final auth = ctx.request.headers.authorization;
+      final bearer =
+          auth is BearerAuthorizationHeader ? auth : null;
🧹 Nitpick comments (3)
example/hello_world.dart (1)

17-19: Align comment with serve() defaults; verify extension import

If app.serve() defaults to loopback (localhost:8080), the comment “on all network interfaces” is misleading. Update the comment to reflect the actual default, or pass address explicitly.

Apply this small tweak if the default is loopback:

-  // Start the server on all network interfaces, port 8080
+  // Start the server on localhost:8080 (default)

Also confirm that RelicAppIOServeEx is exported by package:relic/io_adapter.dart so app.serve() resolves.

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

235-243: run() implementation looks correct; consider doc and typedef

Mounts handler and starts server as expected.

  • Add a brief doc comment explaining lifecycle and returned server.
  • Consider a typedef for the factory, e.g., typedef AdapterFactory = FutureOr<Adapter> Function(); for reuse and clarity.
lib/src/adapter/io/io_adapter.dart (1)

26-41: Nice convenience: IOAdapter.bind

Factory simplifies adapter creation and aligns with app.run()/serve path.

Add a short doc comment describing params and defaults (e.g., ephemeral port 0, backlog/shared semantics) for discoverability.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 33e64fb and 7696b41.

📒 Files selected for processing (13)
  • example/context.dart (1 hunks)
  • example/context_property.dart (1 hunks)
  • example/example.dart (1 hunks)
  • example/hello_world.dart (1 hunks)
  • example/middleware_example.dart (1 hunks)
  • example/multi_isolate.dart (1 hunks)
  • example/static_files_example.dart (2 hunks)
  • lib/src/adapter/io/io_adapter.dart (2 hunks)
  • lib/src/adapter/io/io_serve.dart (2 hunks)
  • lib/src/router/router.dart (2 hunks)
  • relicapp_pr.md (0 hunks)
  • test/router/relic_app_test.dart (1 hunks)
  • test/util/test_util.dart (1 hunks)
💤 Files with no reviewable changes (1)
  • relicapp_pr.md
🔇 Additional comments (6)
example/hello_world.dart (1)

7-15: Good migration to RelicApp and wildcard route

Concise and clear; responds to all paths as intended.

example/static_files_example.dart (2)

25-38: LGTM: app-based bootstrap

Switch to RelicApp is clean; route wiring remains unchanged.


55-56: LGTM: simplified startup

app.serve() usage matches the new pattern.

test/router/relic_app_test.dart (1)

8-49: Solid coverage of RelicApp surface

Tests validate typing, callable behavior, and run() lifecycle with a fake adapter. Nice.

example/context_property.dart (1)

36-41: LGTM: clear example of middleware + route on RelicApp

Simple and correct; demonstrates ContextProperty usage well.

test/util/test_util.dart (1)

62-70: LGTM: in-process server binding via IOAdapter.bind

Clean async setup; ephemeral port on loopback and explicit mount/start look good.

Comment thread example/middleware_example.dart Resolved
Comment thread example/multi_isolate.dart Resolved
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Oct 16, 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: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
lib/src/adapter/io/io_serve.dart (1)

7-16: Remove duplicate file-level documentation.

This file-level documentation is duplicated at the extension method level (lines 18-27) and no longer describes a top-level function. Please remove this redundant documentation block.

Apply this diff:

-/// Starts a server that listens on the specified [address] and
-/// [port] and sends requests to [handler].
-///
-/// If [securityContext] is provided, a secure server will be started.
-///
-/// {@template relic_server_header_defaults}
-/// Every response will get a "date" header.
-/// If this header is present in the `Response`, it will not be
-/// overwritten.
-/// {@endtemplate}
 extension RelicAppIOServeEx on RelicApp {
🧹 Nitpick comments (2)
test/router/relic_app_test.dart (1)

67-74: Consider adding error handling tests.

While the current tests cover the happy path, consider adding tests for error scenarios such as:

  • Adapter factory throwing an exception
  • Server mounting failures
  • Multiple concurrent calls to run() or serve()

These edge cases would improve confidence in the implementation's robustness.

lib/src/adapter/io/io_serve.dart (1)

28-34: Simplify backlog parameter handling.

The backlog parameter is nullable (int?) but always defaults to 0 in the implementation (line 40). This is inconsistent. Either:

  1. Make it non-nullable with a default value: int backlog = 0
  2. Respect null if it has semantic meaning

If 0 is always the intended default, apply this diff:

   Future<RelicServer> serve({
     final InternetAddress? address,
     final int port = 8080,
     final SecurityContext? securityContext,
-    final int? backlog,
+    final int backlog = 0,
     final bool shared = false,
   }) {
     return run(() => IOAdapter.bind(
           // expose on loopback interface by default
           address ?? InternetAddress.loopbackIPv4,
           port: port,
           context: securityContext,
-          backlog: backlog ?? 0,
+          backlog: backlog,
           shared: shared,
         ));
   }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7696b41 and 1bbbf1c.

📒 Files selected for processing (12)
  • example/context.dart (1 hunks)
  • example/context_property.dart (1 hunks)
  • example/example.dart (1 hunks)
  • example/hello_world.dart (1 hunks)
  • example/middleware_example.dart (1 hunks)
  • example/multi_isolate.dart (1 hunks)
  • example/static_files_example.dart (2 hunks)
  • lib/src/adapter/io/io_adapter.dart (2 hunks)
  • lib/src/adapter/io/io_serve.dart (2 hunks)
  • lib/src/router/router.dart (2 hunks)
  • test/router/relic_app_test.dart (1 hunks)
  • test/util/test_util.dart (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • example/multi_isolate.dart
  • example/middleware_example.dart
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-16T07:49:04.643Z
Learnt from: nielsenko
PR: serverpod/relic#212
File: example/multi_isolate.dart:32-38
Timestamp: 2025-10-16T07:49:04.643Z
Learning: In the Relic framework, the default binding for RelicApp.serve() is intentionally set to InternetAddress.loopbackIPv4 (localhost only) rather than anyIPv4. This is a deliberate security-first design decision to require explicit consent (via the address parameter) before exposing endpoints outside the host.

Applied to files:

  • lib/src/adapter/io/io_serve.dart
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Run Unit Tests (macos-latest, beta, upgrade)
  • GitHub Check: Run Unit Tests (macos-latest, beta, downgrade)
  • GitHub Check: Run Unit Tests (macos-latest, stable, downgrade)
  • GitHub Check: Run Unit Tests (macos-latest, 3.5.0, downgrade)
  • GitHub Check: Run Unit Tests (windows-latest, beta, upgrade)
  • GitHub Check: Run Unit Tests (macos-latest, stable, upgrade)
  • GitHub Check: Run Unit Tests (macos-latest, 3.5.0, upgrade)
🔇 Additional comments (18)
lib/src/router/router.dart (3)

1-2: LGTM!

The dart:async import is necessary for FutureOr and Future types used in the run() method.


235-239: LGTM!

The class documentation clearly explains the purpose and usage of RelicApp. The design extending RelicRouter maintains backward compatibility while providing a cleaner API.


259-265: The call method is properly defined via extension—no issues found.

Verification confirms the call method is implemented in lib/src/router/router_handler_extension.dart (line 27) as a callable extension on Router. This allows RelicRouter to function as a Handler, making the mountAndStart(call) invocation on line 263 valid and correct.

example/hello_world.dart (1)

8-19: LGTM!

The migration to RelicApp is clean and demonstrates the simplified API effectively. The catch-all route pattern using '/**' and the app.serve() call showcase the reduced boilerplate mentioned in the PR objectives.

example/static_files_example.dart (1)

25-55: LGTM!

The migration from RelicRouter to RelicApp and the simplified server startup with app.serve() align perfectly with the PR's goal of reducing boilerplate. The routing and middleware configuration remain clear and maintainable.

example/context_property.dart (1)

36-40: LGTM!

The example demonstrates middleware integration with the new RelicApp API effectively. The fluent interface (chaining .use() and .get()) maintains good readability while reducing boilerplate.

test/router/relic_app_test.dart (4)

9-17: LGTM!

This test verifies the core inheritance relationship, ensuring RelicApp properly extends Router<Handler>.


19-35: LGTM!

This test confirms that RelicApp is callable as a Handler, which is essential for the run() method's mountAndStart(call) invocation. The test properly verifies both the callable behavior and the response handling.


37-49: LGTM!

The test verifies the core run() functionality, ensuring the server is created and the handler is mounted. Proper cleanup with await server.close() is included.


51-63: LGTM!

This test validates the serve() extension method, confirming it creates and mounts a RelicServer correctly.

test/util/test_util.dart (1)

63-70: LGTM!

The updated testServe function correctly uses the new IOAdapter.bind() pattern and explicit server mounting. Using port: 0 for dynamic port assignment is a good practice for tests, avoiding port conflicts.

lib/src/adapter/io/io_adapter.dart (2)

7-7: LGTM!

The import of bind_http_server.dart is necessary for the new bind() factory method.


26-58: Approve bind and bindHttpServer implementation
The bind() factory and underlying bindHttpServer() correctly branch to HttpServer.bind versus HttpServer.bindSecure based on the presence of a SecurityContext.

example/context.dart (1)

169-182: LGTM!

The migration to RelicApp is clean and maintains all the functionality of the original implementation. The direct assignment of the fallback property (lines 176-178) is idiomatic and clear. The example effectively demonstrates various context types while showcasing the new API.

example/example.dart (3)

6-12: LGTM! Clean migration to RelicApp.

The setup correctly uses RelicApp with method chaining for routes, middleware, and custom fallback. This matches the intended API simplification described in the PR objectives.


14-15: LGTM! Simplified server startup.

The app.serve() call correctly uses the new extension method with sensible defaults (localhost:8080). Based on learnings, the loopback-only default is an intentional security-first design.


1-1: No change needed: retain the io_adapter import. The serve() extension is only exported by io_adapter.dart and isn’t exposed through relic.dart, so this import is required.

lib/src/adapter/io/io_serve.dart (1)

35-42: LGTM! Security-first default confirmed.

The implementation correctly delegates to run() with an IOAdapter.bind factory. The default to InternetAddress.loopbackIPv4 (line 37) is intentional and aligns with the security-first design documented in the learnings.

Based on learnings

Copilot AI 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.

Pull Request Overview

This PR introduces RelicApp, a convenience class that extends Router<Handler> to simplify server initialization and reduce boilerplate. The main goal is to provide a more intuitive API that matches conventions from popular web frameworks while maintaining full flexibility for advanced use cases.

Key Changes:

  • Introduced RelicApp class with run() method for custom adapters
  • Added serve() extension method with sensible defaults (localhost:8080)
  • Updated all examples and test utilities to use the new pattern

Reviewed Changes

Copilot reviewed 13 out of 13 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
lib/src/router/router.dart Adds RelicApp class with run() method for server lifecycle management
lib/src/adapter/io/io_serve.dart Converts serve() from standalone function to RelicApp extension method with default parameters
lib/src/adapter/io/io_adapter.dart Adds IOAdapter.bind() static factory method for cleaner adapter creation
test/router/relic_app_test.dart Adds comprehensive tests for RelicApp instantiation, invocation, and server lifecycle
test/util/test_util.dart Updates test utility to use IOAdapter.bind() and RelicServer directly
example/*.dart Updates all examples to use RelicApp instead of Router<Handler> + standalone serve()
relicapp_pr.md Removes draft PR description file

Comment thread lib/src/adapter/io/io_serve.dart Resolved
Comment thread example/multi_isolate.dart Resolved
Co-authored-by: Copilot <[email protected]>
@nielsenko
nielsenko marked this pull request as ready for review October 16, 2025 09:29
@nielsenko
nielsenko requested review from a team and SandPod October 16, 2025 09:29

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Changes look good!

Couple of minor questions around examples and documentation.

Comment thread relicapp_pr.md Resolved
Comment thread example/example.dart Resolved
Comment thread example/example.dart Resolved
Comment thread lib/src/adapter/io/io_serve.dart Resolved
Comment thread example/example.dart Resolved
@nielsenko
nielsenko requested a review from SandPod October 16, 2025 14:04

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM! 👍

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.

Introduce RelicApp class to simplify common usage patterns

3 participants