Repository navigation
feat: Support WebServer.addMiddleware (based on Router.use) - #4035
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 📝 WalkthroughWalkthroughReplaces previous routing glue with a Router-based pipeline, adds middleware support (session hydration and exception reporting), exposes session via a RequestContext extension, introduces Route.call(NewContext) as the public per-route entrypoint, updates route registration to use route.call, and bumps relic to ^0.7.0 across packages, templates, and tests. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Client
participant WS as WebServer
participant R as Router<Handler>
participant SM as _SessionMiddleware
participant EM as _ReportExceptionMiddleware
participant Rt as Route.call
participant RC as Route.handleCall
Client->>WS: HTTP Request
WS->>R: routeWith(_router)
R->>SM: handle(request, context)
SM->>SM: Hydrate Session into Context
SM->>EM: next(request, context)
EM->>Rt: try { next(request, context) }
Rt->>RC: handleCall(session, context)
RC-->>Rt: HandledContext/Response
Rt-->>EM: Response
EM-->>R: Response
R-->>WS: Response
WS-->>Client: HTTP Response
rect rgba(255,220,220,0.18)
note over EM: On exception -> report and return 500
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 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 |
50d0d7d to
76ee54f
Compare
|
@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)
packages/serverpod/lib/src/web_server/web_server.dart (1)
96-101: Fix error message: use configured port, notportgetter.On bind failure,
portis null; log should reference_config.port.Apply:
- await _reportException(e, stackTrace, - message: 'Failed to bind socket, ' - 'port $port may already be in use.'); + await _reportException( + e, + stackTrace, + message: 'Failed to bind socket, port ${_config.port} may already be in use.', + );
🧹 Nitpick comments (2)
packages/serverpod/lib/src/web_server/web_server.dart (2)
182-204: Harden exception middleware: guard access toctx.session.If session init ever fails,
ctx.sessioncan throw during error reporting.Use a safe fallback:
Handler call(Handler next) { return (ctx) async { final request = ctx.request; try { return await next(ctx); } catch (e, stackTrace) { - await _webServer._reportException( + Session? session; + try { + session = ctx.session; + } catch (_) { + session = null; + } + await _webServer._reportException( e, stackTrace, space: OriginSpace.application, - session: ctx.session, + session: session, request: request, ); return ctx.respond(Response.internalServerError()); } }; }
62-65: NewaddMiddlewareAPI mirrors Router.use; consider a global default.Optional: make
pathdefault to '/' for convenience.- void addMiddleware(Middleware middleware, String path) => + void addMiddleware(Middleware middleware, [String path = '/']) => _router.use(path, middleware);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
packages/serverpod/lib/src/web_server/web_server.dart(5 hunks)packages/serverpod/pubspec.yaml(1 hunks)packages/serverpod_client/pubspec.yaml(1 hunks)templates/pubspecs/packages/serverpod/pubspec.yaml(1 hunks)templates/pubspecs/packages/serverpod_client/pubspec.yaml(1 hunks)templates/pubspecs/tests/serverpod_test_server/pubspec.yaml(1 hunks)tests/serverpod_test_server/pubspec.yaml(1 hunks)
🔇 Additional comments (12)
packages/serverpod_client/pubspec.yaml (1)
23-23: Consistent relic upgrade.Looks good and in sync with templates.
Use the repo-wide check shared in another comment to confirm no ^0.6.x remain.
tests/serverpod_test_server/pubspec.yaml (1)
15-15: LGTM — relic updated to ^0.7.0 here as well.templates/pubspecs/packages/serverpod/pubspec.yaml (1)
31-31: Template aligned with core package; looks good.packages/serverpod/lib/src/web_server/web_server.dart (6)
59-61: Route registration viaanyOf(..., route.call)looks correct.
81-83: Server pipeline wiring LGTM.
routeWith(_router)+ 404 fallback is clear and predictable.
162-180: Session middleware looks good.Lightweight session hydration before routing; no blocking calls.
206-211: Context property/extension is concise; note it throws if unset.Given the guard added in the exception middleware, this is fine.
Please ensure all requests pass through
_SessionMiddleware(e.g., no alternate entrypoints) sosessionis always set before route handling.
223-228: Route.call bridge is a clean integration point.Keeps
handleCall(Session, NewContext)intact while aligning with Router.
26-29: Middleware registration order is correctIn relic ^0.7.0 the last-registered middleware runs outermost, so ReportExceptionMiddleware already wraps SessionMiddleware and routes.
templates/pubspecs/packages/serverpod_client/pubspec.yaml (1)
22-22: Relic bump confirmed; all dependencies updated to ^0.7.0 and no ^0.6.x constraints remain.templates/pubspecs/tests/serverpod_test_server/pubspec.yaml (1)
14-14: Dependency bump verified. All template and generated pubspec.yaml files reference relic ^0.7.0.packages/serverpod/pubspec.yaml (1)
32-32: Approve relic ^0.7.0 bump; verify all Router, Pipeline, routeWith, ContextProperty, RequestContext, and respondWith usages conform to relic 0.7 APIs.
c011112 to
e18177b
Compare
|
@CodeRabbit review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (3)
packages/serverpod/lib/src/web_server/web_server.dart (2)
209-209: Consider using a named ContextProperty for consistency.The
_sessionPropertyis created without a name, while the test file (middleware_test.dart line 85) uses a named property:ContextProperty<AuthenticationInfo>('autoInfo'). This inconsistency may cause confusion about when to use named vs unnamed properties.Consider providing an explicit name for clarity and to prevent potential key collisions:
-final _sessionProperty = ContextProperty<Session>(); +final _sessionProperty = ContextProperty<Session>('session');
233-233: Address or track the TODO comment.The TODO questions whether to simplify the API by removing
handleCallin favor of just usingcall. This could be a valuable simplification, but would be a breaking change.Would you like me to:
- Open a new issue to track this API simplification decision?
- Evaluate the impact of such a change across the codebase?
tests/serverpod_test_server/test_integration/web_server/middleware_test.dart (1)
65-73: Test description could be clearer about the expected failure.The test expects a 500 error, but the description doesn't explain why. The 500 occurs because
TestRoutealways accessescontext.authInfo(line 81), which throws on unauthenticated paths where_AuthMiddlewarehasn't run. The exception is then caught by_ReportExceptionMiddleware, resulting in a 500 response.Consider clarifying the test name to indicate the expected exception:
test( - 'Given a route that requires authentication is added to an unauthenticated path, ' - 'when a client request the path without authorization, ' - 'then a 500 Internal Error is returned', () async { + 'Given a route that accesses authInfo is added to a path without auth middleware, ' + 'when a client requests the path, ' + 'then a 500 Internal Server Error is returned due to missing authInfo', () async {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
packages/serverpod/lib/src/web_server/web_server.dart(6 hunks)tests/serverpod_test_server/test_integration/web_server/middleware_test.dart(1 hunks)
⏰ 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). (26)
- GitHub Check: Serverpod concurrent integration tests (server) (3.35.2)
- GitHub Check: Serverpod integration tests (server) (3.29.0)
- GitHub Check: Serverpod integration tests (server) (3.35.2)
- GitHub Check: Serverpod concurrent integration tests (server) (3.29.0)
- GitHub Check: Bootstrap tests (3.35.2, ubuntu-latest, tests/bootstrap_project)
- GitHub Check: Bootstrap tests (3.29.0, ubuntu-latest, tests/bootstrap_project)
- GitHub Check: CLI e2e tests (3.35.2, ubuntu-latest, tests/serverpod_cli_e2e_test)
- GitHub Check: CLI e2e tests (3.29.0, ubuntu-latest, tests/serverpod_cli_e2e_test)
- GitHub Check: Bootstrap tests (3.35.2, windows-latest, tests/bootstrap_project)
- GitHub Check: Bootstrap tests (3.29.0, windows-latest, tests/bootstrap_project)
- GitHub Check: Migration e2e tests (3.35.2)
- GitHub Check: Migration e2e tests (3.29.0)
- GitHub Check: Serverpod E2E web tests (3.35.2)
- GitHub Check: Serverpod E2E web tests (3.29.0)
- GitHub Check: dart analyze downgrade (3.35.2, windows-latest)
- GitHub Check: Unit tests IO (3.35.2, windows-latest)
- GitHub Check: dart analyze downgrade (3.35.2, ubuntu-latest)
- GitHub Check: serverpod generate (3.29.0)
- GitHub Check: serverpod generate (3.35.2)
- GitHub Check: Unit tests IO (3.29.0, ubuntu-latest)
- GitHub Check: Unit tests IO (3.29.0, windows-latest)
- GitHub Check: Unit tests IO (3.35.2, ubuntu-latest)
- GitHub Check: dart analyze downgrade (3.29.0, ubuntu-latest)
- GitHub Check: dart analyze (3.29.0, ubuntu-latest)
- GitHub Check: dart analyze downgrade (3.29.0, windows-latest)
- GitHub Check: dart analyze (3.29.0, windows-latest)
🔇 Additional comments (7)
packages/serverpod/lib/src/web_server/web_server.dart (4)
59-60: LGTM! Route registration now uses middleware pipeline.The change to call
route.callinstead of direct handling correctly integrates routes into the new middleware-based pipeline.
161-183: LGTM! Session lifecycle is properly managed.The middleware correctly creates a session per request, stores it in context, and ensures cleanup via the
finallyblock. Resource management is sound.
185-207: LGTM! Exception handling middleware is correctly implemented.The middleware properly catches exceptions, reports them with session context, and returns an appropriate 500 response.
62-64: Verify externalMiddlewaresignature: Definition isn’t found in this repo; confirm in the relic package thatMiddlewareis typedef’d asHandler Function(Handler).tests/serverpod_test_server/test_integration/web_server/middleware_test.dart (3)
8-24: LGTM! Test setup correctly demonstrates path-specific middleware.The setup appropriately configures middleware for
/apionly, creating different behavior for/api/foo(authenticated) vs/bar(unauthenticated). This effectively tests the path-specific middleware functionality.
76-83: LGTM! Test route correctly demonstrates context property access.The route implementation appropriately accesses
context.authInfoto demonstrate how middleware-injected context properties work in practice.
91-100: LGTM! Auth middleware correctly implements the middleware pattern.The middleware properly:
- Checks authentication via
ctx.session.authenticated- Returns 401 for unauthenticated requests
- Stores
AuthenticationInfoin context for downstream handlers- Delegates to the next handler when authenticated
This serves as a good reference implementation for custom middleware.
e18177b to
63f87e3
Compare
63f87e3 to
b868507
Compare
exaby73
left a comment
There was a problem hiding this comment.
Small suggestion on the test structure
SandPod
left a comment
There was a problem hiding this comment.
LGTM!
Just had a couple of NITs.
Description
WebServer.addMiddlewaremethod for custom middleware registration.ServerpodRouterextension type with directRouter<Handler>usage.ContextProperty.WebServer.addMiddleware.Fixes: #2499
Fixes: #3553
Pre-launch Checklist
///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.Summary by CodeRabbit
New Features
Refactor
Tests
Chores