Repository navigation
feat!: Introduce RelicApp - #212
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 Note Other AI code review bot(s) detectedCodeRabbit 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. 📝 WalkthroughWalkthroughAdds 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Pre-merge checks and finishing touches✅ Passed checks (5 passed)
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. Comment |
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
07a9857 to
c73879e
Compare
b1246ac to
015bce2
Compare
865c85e to
7696b41
Compare
|
@CodeRabbit review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
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 headerCasting with
as BearerAuthorizationHeader?will throw if a non-Bearer auth header is present. Use anischeck.- 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 importIf 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 typedefMounts 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.bindFactory 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
📒 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 routeConcise and clear; responds to all paths as intended.
example/static_files_example.dart (2)
25-38: LGTM: app-based bootstrapSwitch to RelicApp is clean; route wiring remains unchanged.
55-56: LGTM: simplified startupapp.serve() usage matches the new pattern.
test/router/relic_app_test.dart (1)
8-49: Solid coverage of RelicApp surfaceTests 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 RelicAppSimple and correct; demonstrates ContextProperty usage well.
test/util/test_util.dart (1)
62-70: LGTM: in-process server binding via IOAdapter.bindClean async setup; ephemeral port on loopback and explicit mount/start look good.
|
@CodeRabbit review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
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()orserve()These edge cases would improve confidence in the implementation's robustness.
lib/src/adapter/io/io_serve.dart (1)
28-34: Simplifybacklogparameter handling.The
backlogparameter is nullable (int?) but always defaults to0in the implementation (line 40). This is inconsistent. Either:
- Make it non-nullable with a default value:
int backlog = 0- Respect
nullif it has semantic meaningIf
0is 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
📒 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:asyncimport is necessary forFutureOrandFuturetypes used in therun()method.
235-239: LGTM!The class documentation clearly explains the purpose and usage of
RelicApp. The design extendingRelicRoutermaintains backward compatibility while providing a cleaner API.
259-265: Thecallmethod is properly defined via extension—no issues found.Verification confirms the
callmethod is implemented inlib/src/router/router_handler_extension.dart(line 27) as a callable extension onRouter. This allowsRelicRouterto function as aHandler, making themountAndStart(call)invocation on line 263 valid and correct.example/hello_world.dart (1)
8-19: LGTM!The migration to
RelicAppis clean and demonstrates the simplified API effectively. The catch-all route pattern using'/**'and theapp.serve()call showcase the reduced boilerplate mentioned in the PR objectives.example/static_files_example.dart (1)
25-55: LGTM!The migration from
RelicRoutertoRelicAppand the simplified server startup withapp.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
RelicAppAPI 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
RelicAppproperly extendsRouter<Handler>.
19-35: LGTM!This test confirms that
RelicAppis callable as aHandler, which is essential for therun()method'smountAndStart(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 withawait server.close()is included.
51-63: LGTM!This test validates the
serve()extension method, confirming it creates and mounts aRelicServercorrectly.test/util/test_util.dart (1)
63-70: LGTM!The updated
testServefunction correctly uses the newIOAdapter.bind()pattern and explicit server mounting. Usingport: 0for 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.dartis necessary for the newbind()factory method.
26-58: Approve bind and bindHttpServer implementation
Thebind()factory and underlyingbindHttpServer()correctly branch toHttpServer.bindversusHttpServer.bindSecurebased on the presence of aSecurityContext.example/context.dart (1)
169-182: LGTM!The migration to
RelicAppis clean and maintains all the functionality of the original implementation. The direct assignment of thefallbackproperty (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
RelicAppwith 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 anIOAdapter.bindfactory. The default toInternetAddress.loopbackIPv4(line 37) is intentional and aligns with the security-first design documented in the learnings.Based on learnings
… for all arguments. Update examples and tests.
There was a problem hiding this comment.
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
RelicAppclass withrun()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 |
Co-authored-by: Copilot <[email protected]>
SandPod
left a comment
There was a problem hiding this comment.
Changes look good!
Couple of minor questions around examples and documentation.
Description
This PR introduces
RelicApp, a new class that extendsRouter<Handler>to simplify common usage patterns and reduce boilerplate for getting started with Relic.RelicAppclass inlib/src/router/router.dartwith arun()method that handles adapter setup and server lifecycleRelicAppIOServeExextension inlib/src/adapter/io/io_serve.dartproviding a convenientserve()method with sensible defaultsIOAdapter.bind()static factory method for cleaner adapter creationRelicAppinstead ofRouter<Handler>+serve()Why this is beneficial:
.asHandlerextension ordart:ioimports in simple casesBefore:
After:
Related Issues
Pre-Launch Checklist
///), ensuring consistency with existing project documentation.Breaking Changes
serve()is now an extension method onRelicApp.Additional Notes
app.run()with custom adaptersattach(),group()) works seamlessly withRelicAppSummary by CodeRabbit