Repository navigation
feat!: Defer static handling to Relic - #3980
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 📝 WalkthroughWalkthroughRefactors request handling to use Context.respond, updates web server routing to a pipeline-based per-route handler with multi-method support, overhauls static file serving to a built-in static handler with pattern-based caching, adjusts static route usages and tests, and switches the relic dependency to a Git source across packages and templates. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant C as Client
participant P as Shelf Pipeline
participant R as Router
participant H as Route Handler
participant S as _handleRouteCall
participant Ctx as Context
participant Res as Response
C->>P: HTTP Request
P->>R: Route match
R->>H: Invoke handler for Route (methods set)
H->>S: _handleRouteCall(route, session, ctx)
S->>Ctx: context.respond(Response...)
Ctx-->>C: HTTP Response
note over H,S: Errors also use context.respond(...)
sequenceDiagram
autonumber
participant C as Client
participant RSD as RouteStaticDirectory
participant SH as StaticHandler (built-in)
participant FS as File System
C->>RSD: GET /url_prefix/** (nested paths)
RSD->>SH: Delegate request
SH->>FS: Read file /web/<serverDirectory>/...
FS-->>SH: File bytes + metadata
SH-->>RSD: Response with ETag/Last-Modified/Range support
RSD-->>C: Response (Cache-Control via pattern match)
note over RSD: Cache-Control set from pathCachePatterns or default one year
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Pre-merge checks and finishing touches✅ Passed checks (3 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 |
2258c59 to
f865d45
Compare
d79824f to
c766fd7
Compare
|
@CodeRabbit review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 6
♻️ Duplicate comments (1)
packages/serverpod/pubspec.yaml (1)
32-35: Temporary git pin: lock to commit SHA and track follow-up to switch to release.Branch refs are mutable; use a commit SHA for CI determinism. Also ensure a task exists to swap back to a published version once available. (Noting prior comment that this is temporary.)
relic: git: url: https://github.com/nielsenko/relic.git - ref: merged + ref: <commit-sha>Check all pubspecs for relic refs:
#!/bin/bash rg -n '\brelic:\s*\n\s*git:' -C2 --glob '**/pubspec.yaml'
🧹 Nitpick comments (18)
modules/new_serverpod_auth/serverpod_auth_idp/serverpod_auth_idp_server/lib/src/providers/apple/business/apple_accounts.dart (1)
160-160: Avoid unchecked cast to RespondableContext; guard or assert.If this handler is ever mounted where
ctxisn’t aRespondableContext, this will throw at runtime. Prefer a type-safe guard.- return (ctx as RespondableContext).respond(Response.ok()); + if (ctx case final RespondableContext rctx) { + return rctx.respond(Response.ok()); + } + throw StateError( + 'AppleAccounts.serverNotificationHandler requires RespondableContext', + );templates/pubspecs/tests/serverpod_test_server/pubspec.yaml (1)
14-17: Template should pin git dep to a commit SHA for stability.Templates propagate to new projects; use an immutable commit rather than a branch name.
relic: git: url: https://github.com/nielsenko/relic.git - ref: merged + ref: <commit-sha>templates/pubspecs/packages/serverpod_client/pubspec.yaml (1)
21-24: Dev dependency on git: prefer commit SHA for reproducibility.Same rationale as other pubspecs; update template to a fixed commit.
relic: git: url: https://github.com/nielsenko/relic.git - ref: merged + ref: <commit-sha>packages/serverpod_client/pubspec.yaml (1)
22-25: Pin git ref to commit SHA.Stabilizes CI and avoids supply‑chain drift; swap to release tag before publishing.
relic: git: url: https://github.com/nielsenko/relic.git - ref: merged + ref: <commit-sha>packages/serverpod/lib/src/server/server.dart (1)
257-261: Return 500 instead of 400 on body read failures.You log as internal error; mapping to 400 can mislead clients and monitoring.
- return context.respond(Response.badRequest( - body: Body.fromString('Failed to read request body.'), - headers: headers, - )); + return context.respond(Response.internalServerError( + body: Body.fromString('Failed to read request body.'), + headers: headers, + ));tests/serverpod_test_server/pubspec.yaml (1)
15-18: Pin git dependency to a commit SHA (not a branch) across pubspecsMultiple pubspec.yaml files reference relic with
ref: merged— pin to a specific commit SHA for reproducible CI builds.relic: git: url: https://github.com/nielsenko/relic.git - ref: merged + ref: <commit-sha>Find all occurrences and update consistently:
rg -n --hidden -S --glob '**/pubspec.yaml' -P 'ref:\s*merged' -C2
examples/auth_example/auth_example_server/lib/server.dart (1)
39-41: Scope static route to a prefix to avoid catch‑all shadowing, or document ordering guarantees.
'/**'can mask future dynamic routes if ordering changes. Prefer a prefix (e.g.,/static/**) or add a code comment that this must remain last.Proposed change:
- RouteStaticDirectory(serverDirectory: 'static'), - '/**', + RouteStaticDirectory(serverDirectory: 'static'), + '/static/**',tests/serverpod_test_nonvector/serverpod_test_nonvector_server/lib/server.dart (1)
26-26: Use recursive match to serve nested assets.
'/*'won’t match paths like/nested/file.txt. The new handler expects'/**'.- '/*', + '/**',templates/serverpod_templates/projectname_server_upgrade/lib/server.dart (1)
22-24: Consider scoping static files to a prefix to reduce accidental route capture in user projects.Templates benefit from safer defaults. Prefer
/static/**; if you keep'/**', add an inline comment that it must remain last.- RouteStaticDirectory(serverDirectory: 'static'), - '/**', + RouteStaticDirectory(serverDirectory: 'static'), + '/static/**',tests/serverpod_test_server/test_integration/static_files_test.dart (2)
21-22: Excessive 5‑hour HTTP timeouts in tests.Use shorter timeouts to avoid hangs.
- ..connectionTimeout = Duration(hours: 5) - ..idleTimeout = Duration(hours: 5)); + ..connectionTimeout = Duration(seconds: 30) + ..idleTimeout = Duration(minutes: 2));
34-36: Close the test HTTP client to avoid resource leaks.tearDownAll(() async { + client.close(); await directory.delete(recursive: true); });packages/serverpod/lib/src/web_server/routes/static_directory.dart (2)
48-51: Docs mismatch: patterns set specific max‑ages, not just “not cached”.Clarify that patterns map to a Duration (including
noCache), not only an exclusion.- /// A regular expression that will be used to determine if a path should not - /// be cached. + /// Optional patterns mapping path matches to a specific cache max‑age. + /// Use [PathCacheMaxAge.noCache] to disable caching for matched paths.
56-61: Initialize_pathCachePatternsin the initializer list; no need forlate.- RouteStaticDirectory({ - required this.serverDirectory, - List<PathCacheMaxAge>? pathCachePatterns, - }) : super(methods: {Method.get, Method.head}) { - _pathCachePatterns = pathCachePatterns; + RouteStaticDirectory({ + required this.serverDirectory, + List<PathCacheMaxAge>? pathCachePatterns, + }) : _pathCachePatterns = pathCachePatterns, + super(methods: {Method.get, Method.head}) {packages/serverpod/lib/src/web_server/web_server.dart (5)
75-81: Avoid downcasting ServerpodRouter; expose the underlying Router via an accessorRelying on
router as Router<Route>is brittle and obscures intent. Provide a typed accessor onServerpodRouterand use it here.Apply this diff here:
- routeWith(router as Router<Route>, toHandler: _routeToHandler), + routeWith(router.asRouter, toHandler: _routeToHandler),And add this accessor in the
ServerpodRouterextension type:extension type ServerpodRouter._(Router<Route> _router) { /// Creates a new [ServerpodRouter]. ServerpodRouter() : _router = Router<Route>(); + /// Exposes the underlying relic router (read‑only). + Router<Route> get asRouter => _router;
107-111: Break after locating the auth cookieTiny optimization and avoids later (unexpected) overwrites if multiple cookies exist.
- for (var cookie in request.headers.cookie?.cookies ?? const <Cookie>[]) { - if (cookie.name == 'auth') { - authenticationKey = cookie.value; - } - } + for (var cookie in request.headers.cookie?.cookies ?? const <Cookie>[]) { + if (cookie.name == 'auth') { + authenticationKey = cookie.value; + break; + } + }
113-115: If query fallback is retained, prefer requestedUri for proxy correctness
requestedUri.queryParametersreflects the externally visible URL behind proxies. Use it instead ofrequest.url.queryParameters.- var queryParameters = request.url.queryParameters; + var queryParameters = request.requestedUri.queryParameters;
213-218: Defensively copy and validate Route.methodsPrevent external mutation and catch empty sets early.
- final Set<Method> methods; + final Set<Method> methods; @@ - Route({this.methods = const {Method.get}}); + Route({Set<Method> methods = const {Method.get}}) + : assert(methods.isNotEmpty, 'Route.methods cannot be empty'), + methods = Set.unmodifiable(methods);
291-293: Auto-include HEAD when GET is allowedMany servers implicitly allow HEAD for GET routes. Add it here to improve HTTP compliance.
- void add(Route route) => - _router.anyOf(route.methods, route._matchPath!, route); + void add(Route route) { + final methods = route.methods.contains(Method.get) + ? {...route.methods, Method.head} + : route.methods; + _router.anyOf(methods, route._matchPath!, route); + }If Relic already synthesizes HEAD, ignore this.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (16)
examples/auth_example/auth_example_server/lib/server.dart(1 hunks)modules/new_serverpod_auth/serverpod_auth_idp/serverpod_auth_idp_server/lib/src/providers/apple/business/apple_accounts.dart(1 hunks)packages/serverpod/lib/src/server/server.dart(6 hunks)packages/serverpod/lib/src/web_server/routes/static_directory.dart(1 hunks)packages/serverpod/lib/src/web_server/web_server.dart(7 hunks)packages/serverpod/pubspec.yaml(1 hunks)packages/serverpod_client/pubspec.yaml(1 hunks)packages/serverpod_client/test/test_utils/test_http_server.dart(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)templates/serverpod_templates/projectname_server_upgrade/lib/server.dart(1 hunks)tests/serverpod_new_auth_test/serverpod_new_auth_test_server/lib/server.dart(1 hunks)tests/serverpod_test_nonvector/serverpod_test_nonvector_server/lib/server.dart(1 hunks)tests/serverpod_test_server/pubspec.yaml(1 hunks)tests/serverpod_test_server/test_integration/static_files_test.dart(8 hunks)
🧰 Additional context used
🧠 Learnings (4)
📚 Learning: 2025-08-25T19:46:58.073Z
Learnt from: tp
PR: serverpod/serverpod#3917
File: modules/new_serverpod_auth/serverpod_auth_idp/serverpod_auth_idp_server/analysis_options.yaml:3-6
Timestamp: 2025-08-25T19:46:58.073Z
Learning: In Serverpod, test tool paths like `test/integration/test_tools/serverpod_test_tools.dart` are configured per project in the "generator.yaml" file and managed by a generator system, so they don't need to be updated manually across all files at once.
Applied to files:
templates/pubspecs/tests/serverpod_test_server/pubspec.yamltests/serverpod_test_server/pubspec.yamltests/serverpod_test_nonvector/serverpod_test_nonvector_server/lib/server.darttests/serverpod_test_server/test_integration/static_files_test.dart
📚 Learning: 2025-06-27T08:39:36.440Z
Learnt from: tp
PR: serverpod/serverpod#3721
File: util/pub_get_all:0-0
Timestamp: 2025-06-27T08:39:36.440Z
Learning: In the Serverpod project, `dart pub get` commands work fine on Flutter packages both locally and in CI environments, even when the package has `flutter: sdk: flutter` dependencies in pubspec.yaml. The technical constraint of Flutter SDK dependencies causing `dart pub` failures may not apply in all environments or recent Dart versions.
Applied to files:
templates/pubspecs/tests/serverpod_test_server/pubspec.yaml
📚 Learning: 2025-07-02T16:07:50.947Z
Learnt from: tp
PR: serverpod/serverpod#3747
File: modules/new_serverpod_auth/serverpod_auth_migration/serverpod_auth_migration_server/lib/src/business/migrating_email_endpoint_base.dart:4-4
Timestamp: 2025-07-02T16:07:50.947Z
Learning: In Serverpod, tp prefers importing the full package (e.g., 'package:serverpod_auth_migration_server/serverpod_auth_migration_server.dart') as a baseline rather than using smaller local imports, even within the same package where it might be considered a "self-import".
Applied to files:
templates/serverpod_templates/projectname_server_upgrade/lib/server.darttests/serverpod_test_nonvector/serverpod_test_nonvector_server/lib/server.darttests/serverpod_test_server/test_integration/static_files_test.dart
📚 Learning: 2025-08-28T20:43:36.257Z
Learnt from: CR
PR: serverpod/serverpod#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-28T20:43:36.257Z
Learning: Applies to **/test/**/*_test.dart : Group related test cases using group() where appropriate
Applied to files:
tests/serverpod_test_server/test_integration/static_files_test.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). (2)
- GitHub Check: Migration e2e tests (3.35.2)
- GitHub Check: Migration e2e tests (3.29.0)
🔇 Additional comments (11)
packages/serverpod_client/test/test_utils/test_http_server.dart (1)
41-41: LGTM: respond() migration is correct.The handler now returns a HandledContext via
respond, aligning with the new API.packages/serverpod/lib/src/server/server.dart (6)
210-210: LGTM: health check response via respond().
236-236: Preflight: verify all required CORS headers are present.You merge
httpOptionsResponseHeaders; ensure it includesAccess-Control-Allow-Methods,Access-Control-Allow-Headers, andVary: Originas needed.
248-253: 413 handling looks good.Body is drained (when reading started) and response includes details; OK.
270-271: LGTM: unified response path through _toResponse().
161-163: Incorrect — sessionLogId already surfaced in 500 response.
packages/serverpod/lib/src/server/server.dart:312 returns "Internal server error. Call log id: ${result.sessionLogId}" for ResultInternalServerError.Likely an incorrect or invalid review comment.
1-659: Sweep: ensure no lingering withResponse() calls remain.Sandbox ripgrep returned "No files were searched" so automated verification couldn't complete. Run in the repository root and attach the output:
rg -nP --hidden --no-ignore -S '\bwithResponse\s*(' || true
(If rg is unavailable) grep -RIn --exclude-dir={build,.dart_tool} 'withResponse\s*(' || true
To prevent mixed APIs across the repo.
tests/serverpod_new_auth_test/serverpod_new_auth_test_server/lib/server.dart (1)
26-28: LGTM on adopting recursive static routing.packages/serverpod/lib/src/web_server/web_server.dart (3)
145-146: LGTM: clean internal error mapping
context.respond(Response.internalServerError())aligns with the new respond API and centralizes error handling.
265-266: LGTM: redirect via respond(seeOther)Correctly uses
respondwithResponse.seeOther.
277-281: LGTM: OK response with explicit MIME and conservative cachingGood defaults for HTML/JSON widgets.
SandPod
left a comment
There was a problem hiding this comment.
Couple of questions, but these might be out of scope for this issue. I'm wondering what issue should be used to capture these concerns.
e652fd7 to
7ddda4d
Compare
7ddda4d to
80bf314
Compare
…ctor - Add ETag and If-None-Match conditional request tests - Add If-Modified-Since conditional request tests - Add Range header tests for partial content (206 responses) - Add Content-Type header validation tests - Add HEAD method support tests - Verify proper 304 Not Modified and 416 Range Not Satisfiable responses
…o cookies or query parameters
77a59cd to
79fdf66
Compare
79fdf66 to
ebd03fb
Compare
…ng it abstract and clearing out implementation
SandPod
left a comment
There was a problem hiding this comment.
Last considerations otherwise it looks good! 👍
Description
RouteStaticDirectoryto use Relic's static handler with improved caching and HTTP feature supportRouteclass from single method to support multiple HTTP methodswithResponsecalls to use Relic'srespondmethodFixes: #2498
Fixes: #3758
Fixes: #3986
Fixes: #3983
Pre-launch Checklist
///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.If you need help, consider asking for advice on the discussion board.
Breaking changes
This changes the interface of
RouteStaticDirectory,Route, and how to setup routing of static assets (using tail-matching/prefix/**)Summary by CodeRabbit