Skip to content

feat!: Defer static handling to Relic - #3980

Merged
nielsenko merged 18 commits into
serverpod:mainfrom
nielsenko:defer-static-to-relic
Oct 1, 2025
Merged

nielsenko merged 18 commits into
serverpod:mainfrom
nielsenko:defer-static-to-relic

Conversation

@nielsenko

@nielsenko nielsenko commented Sep 16, 2025 •

Copy link
Copy Markdown
Collaborator

Description

  • Updates RouteStaticDirectory to use Relic's static handler with improved caching and HTTP feature support
  • Migrates Route class from single method to support multiple HTTP methods
  • Refactors web server request handling to use Relic's pipeline and routing system
  • Updates all withResponse calls to use Relic's respond method

Fixes: #2498
Fixes: #3758
Fixes: #3986
Fixes: #3983

Pre-launch Checklist

  • I read the Contribute page and followed the process outlined there for submitting PRs.
  • This update contains only one single feature or bug fix and nothing else. (If you are submitting multiple fixes, please make multiple PRs.)
  • I read and followed the Dart Style Guide and formatted the code with dart format.
  • I listed at least one issue that this PR fixes in the description above.
  • I updated/added relevant documentation (doc comments with ///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.
  • I added new tests to check the change I am making.
  • All existing and new tests are passing.
  • Any breaking changes are documented below.

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

  • New Features
    • Improved static file serving: recursive matching (/**), nested paths, automatic content types, configurable Cache-Control, ETag/If-None-Match, Last-Modified/If-Modified-Since, Range (partial content), and HEAD support.
  • Refactor
    • Routing supports multiple HTTP methods per route; simplified response handling.
    • Static directory route configuration simplified; basePath parameter removed.
  • Tests
    • Expanded integration tests for static files, caching, conditional requests, ranges, and HEAD behavior.
  • Chores
    • Updated dependency resolution for “relic” to a pinned Git reference across packages and templates.

@coderabbitai

coderabbitai Bot commented Sep 16, 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

Refactors 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

Cohort / File(s) Summary of changes
Request context response API migration
packages/serverpod/lib/src/server/server.dart, modules/new_serverpod_auth/serverpod_auth_idp/serverpod_auth_idp_server/lib/src/providers/apple/business/apple_accounts.dart, packages/serverpod_client/test/test_utils/test_http_server.dart, packages/serverpod/lib/src/web_server/web_server.dart
Replaced withResponse(...) with respond(...) for sending responses across handlers, errors, and utilities.
Web server routing refactor
packages/serverpod/lib/src/web_server/web_server.dart
Switched to a Shelf Pipeline with per-route handlers; routing now supports Set<Method>; removed RouteMethod enum and related extensions; adjusted handler entry points and error paths; removed HSTS injection.
Static directory route refactor
packages/serverpod/lib/src/web_server/routes/static_directory.dart
Replaced manual I/O and MIME mapping with a built-in static handler; simplified RouteStaticDirectory constructor (removed basePath, serveAsRootPath); added pattern-based cache-control; delegated request handling to internal handler.
Static route usage updates
examples/auth_example/auth_example_server/lib/server.dart, templates/serverpod_templates/projectname_server_upgrade/lib/server.dart, tests/serverpod_new_auth_test/serverpod_new_auth_test_server/lib/server.dart, tests/serverpod_test_nonvector/serverpod_test_nonvector_server/lib/server.dart
Updated static route patterns from /* to /** and removed basePath argument in RouteStaticDirectory calls.
Static files integration tests
tests/serverpod_test_server/test_integration/static_files_test.dart
Reworked test setup; changed server directory and URL prefix; added nested file tests; expanded coverage for ETag, Last-Modified, range requests, HEAD, and content type; updated timeouts and client usage.
Dependency update: relic via Git
packages/serverpod/pubspec.yaml, packages/serverpod_client/pubspec.yaml, templates/pubspecs/packages/serverpod/pubspec.yaml, templates/pubspecs/packages/serverpod_client/pubspec.yaml, templates/pubspecs/tests/serverpod_test_server/pubspec.yaml, tests/serverpod_test_server/pubspec.yaml
Switched relic dependency from ^0.4.1 to Git source https://github.com/nielsenko/relic.git at ref: merged.

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(...)
Loading
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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
Title Check ✅ Passed The title succinctly highlights the major breaking change of deferring static file handling to Relic and clearly conveys the primary shift introduced by the pull request.
Description Check ✅ Passed The pull request description follows the required template by providing a “Description” section that clearly outlines the changes and rationale, lists multiple issues fixed under the “Fixes” heading, includes a complete “Pre-launch Checklist” section, and documents breaking changes in the designated section. The only minor discrepancy is that the checklist item confirming that at least one issue was listed remains unchecked despite the issues being explicitly enumerated above.

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.

@nielsenko nielsenko changed the title feat! Defer static handling to Relic feat!: Defer static handling to Relic Sep 16, 2025
@nielsenko
nielsenko force-pushed the defer-static-to-relic branch 3 times, most recently from 2258c59 to f865d45 Compare September 17, 2025 11:14
Comment thread packages/serverpod/pubspec.yaml Resolved
@nielsenko
nielsenko force-pushed the defer-static-to-relic branch 3 times, most recently from d79824f to c766fd7 Compare September 17, 2025 15:30
@nielsenko nielsenko self-assigned this Sep 17, 2025
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Sep 17, 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: 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 ctx isn’t a RespondableContext, 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 pubspecs

Multiple 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 _pathCachePatterns in the initializer list; no need for late.

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

Relying on router as Router<Route> is brittle and obscures intent. Provide a typed accessor on ServerpodRouter and 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 ServerpodRouter extension 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 cookie

Tiny 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.queryParameters reflects the externally visible URL behind proxies. Use it instead of request.url.queryParameters.

-      var queryParameters = request.url.queryParameters;
+      var queryParameters = request.requestedUri.queryParameters;

213-218: Defensively copy and validate Route.methods

Prevent 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 allowed

Many 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9f1b900 and c766fd7.

📒 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.yaml
  • tests/serverpod_test_server/pubspec.yaml
  • tests/serverpod_test_nonvector/serverpod_test_nonvector_server/lib/server.dart
  • tests/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.dart
  • tests/serverpod_test_nonvector/serverpod_test_nonvector_server/lib/server.dart
  • tests/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 includes Access-Control-Allow-Methods, Access-Control-Allow-Headers, and Vary: Origin as 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 respond with Response.seeOther.


277-281: LGTM: OK response with explicit MIME and conservative caching

Good defaults for HTML/JSON widgets.

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

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.

@nielsenko
nielsenko force-pushed the defer-static-to-relic branch from 7ddda4d to 80bf314 Compare September 30, 2025 11:34
@nielsenko
nielsenko force-pushed the defer-static-to-relic branch 6 times, most recently from 77a59cd to 79fdf66 Compare September 30, 2025 19:02
@nielsenko
nielsenko force-pushed the defer-static-to-relic branch from 79fdf66 to ebd03fb Compare September 30, 2025 19:22
@nielsenko
nielsenko requested a review from SandPod October 1, 2025 06:24

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

Last considerations otherwise it looks good! 👍

@nielsenko
nielsenko merged commit aac1a3a into serverpod:main Oct 1, 2025
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 1, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

3 participants