Skip to content

refactor: Use RelicApp in Server - #4134

Merged
nielsenko merged 8 commits into
serverpod:mainfrom
nielsenko:server-use-relic-app
Nov 6, 2025
Merged

nielsenko merged 8 commits into
serverpod:mainfrom
nielsenko:server-use-relic-app

Conversation

@nielsenko

@nielsenko nielsenko commented Oct 30, 2025 •

Copy link
Copy Markdown
Collaborator

Summary

Use Relic's router for endpoint dispatch in api server.

Closes: #4101

Changes

  • Migrated server to implement RouterInjectable and use RelicApp for request routing
  • Removed EndpointResult classes.
  • Changed _handleUriCall to return Response directly instead of EndpointResult
  • Moved all exception-to-response mapping to the _reportException middleware
  • Made EndpointDispatchException sealed to enable exhaustive pattern matching
  • Simplified NotAuthorizedException to store AuthenticationFailureReason directly
  • Updated canUserAccessEndpoint to return AuthenticationFailureReason? instead of result wrapper
  • Removed sessionLogId from error responses to avoid exposing internal database IDs
  • Removed helper methods _toResponse and _logMalformedCalls (no longer needed)
  • Updated all existing tests to reflect new return types

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

Breaking changes

None. This is an internal refactoring that doesn't affect the public API.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added router injection capability for streamlined middleware and route registration.
  • Refactor

    • Simplified authentication error handling, moving from verbose result objects to concise reason-based responses.
    • Restructured request dispatch and exception handling for improved maintainability.
    • Enhanced server startup architecture with injected application management.

@coderabbitai

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

The PR introduces two major refactorings: (1) simplifies error handling by replacing Result-object classes with a direct AuthenticationFailureReason enum in endpoint dispatch, and (2) refactors server request routing to use Router from the relic package via middleware injection, replacing manual path/HTTP verb dispatch.

Changes

Cohort / File(s) Summary
Error model refactor
packages/serverpod/lib/src/server/endpoint_dispatch.dart
Removes Result\* public classes (ResultSuccess, ResultInvalidParams, ResultNoSuchEndpoint, ResultInternalServerError, ResultStatusCode, ExceptionResult, EndpointResult). Changes canUserAccessEndpoint return type from Future<ResultAuthenticationFailed?> to Future<AuthenticationFailureReason?>. Updates NotAuthorizedException constructor to accept reason field directly instead of authenticationFailedResult. Converts EndpointDispatchException from abstract to sealed class.
Exception property access updates
packages/serverpod/lib/src/server/websocket_request_handlers/method_websocket_request_handler.dart, packages/serverpod_test/lib/src/function_call_wrappers.dart
Updates NotAuthorizedException exception handler to read e.reason instead of e.authenticationFailedResult.reason in error response mapping.
Test alignment
packages/serverpod/test/endpoint/authentication_test.dart
Updates tests for canUserAccessEndpoint to expect direct AuthenticationFailureReason return value instead of ResultAuthenticationFailed wrapper.
Server routing refactor
packages/serverpod/lib/src/server/server.dart
Implements RouterInjectable interface on Server class. Adds injectIn(RelicRouter router) method to register middleware (_verboseLogging, _headers, _reportException) and routes (health, websocket, cloud storage, endpoints). Replaces RelicServer/IOAdapter startup with RelicApp-based serving. Refactors request dispatch from manual path handling to modular _endpoints and _cloudStorage entry points using _handleUriCall. Introduces _dispatchWebSocket abstraction for websocket handling. Updates exception handling to target specific exception types (EndpointDispatchException, SerializableException, HeaderException, AuthHeaderEncodingException).

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant RelicRouter
    participant Server
    participant Middleware
    participant Endpoints

    rect rgb(200, 230, 201)
    Note over Client,RelicRouter: Request enters via Router
    end
    
    Client->>RelicRouter: HTTP Request
    RelicRouter->>Middleware: _verboseLogging
    Middleware->>Middleware: _headers
    Middleware->>Middleware: _reportException
    
    alt Health Check
        Middleware->>Server: GET /
        Server-->>Client: Health metrics (OK/SADNESS)
    else Endpoint Request
        Middleware->>Endpoints: Route to handler
        rect rgb(255, 242, 204)
        Note over Endpoints: canUserAccessEndpoint check
        end
        Endpoints->>Endpoints: Authenticate & Authorize
        alt Success
            Endpoints->>Endpoints: Invoke endpoint method
            Endpoints-->>Client: HTTP Response
        else AuthenticationFailureReason
            Endpoints->>Endpoints: Construct NotAuthorizedException
            Endpoints-->>Client: 401/403 Response
        end
    else WebSocket Upgrade
        Middleware->>Server: _dispatchWebSocket
        Server-->>Client: WebSocket Connection
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Special attention areas:
    • packages/serverpod/lib/src/server/endpoint_dispatch.dart: API-breaking changes removing multiple public result classes; verify all downstream clients handle the new AuthenticationFailureReason enum correctly
    • packages/serverpod/lib/src/server/server.dart: Substantial architectural refactor introducing middleware pipeline and Router injection; ensure all request paths (health, endpoints, websocket, cloud storage) remain functionally equivalent and error handling is correctly applied across all routes
    • Verify exception mapping consistency across the three affected files when handling NotAuthorizedException with the new reason field
    • Test coverage changes in authentication_test.dart should be validated against both old and new code paths

Possibly related PRs

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'refactor: Use RelicApp in Server' is concise and specific, clearly describing the main architectural change replacing manual dispatch with RelicApp for request routing.
Description check ✅ Passed The PR description provides a comprehensive summary of changes, links to issue #4101, includes a complete pre-launch checklist with all items checked, and explicitly documents breaking changes (noting none for this internal refactor).
Linked Issues check ✅ Passed The PR successfully implements all objectives from #4101: migrates to Router-based dispatch via RouterInjectable implementation, refactors request handling, improves error handling architecture, updates tests, and maintains backward compatibility.
Out of Scope Changes check ✅ Passed All changes are directly related to the primary objective of refactoring request handling to use Router. Changes to authentication handling (AuthenticationFailureReason), exception architecture (sealed EndpointDispatchException), and result classes removal are necessary supporting changes for the Router integration.

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 force-pushed the server-use-relic-app branch 3 times, most recently from 3528654 to d736baf Compare October 30, 2025 16:40
@nielsenko nielsenko self-assigned this Oct 30, 2025
@nielsenko
nielsenko force-pushed the server-use-relic-app branch 19 times, most recently from d6fb252 to 32d5fb6 Compare November 6, 2025 10:23
- Extract _health handler
- Extract web service dispatch handler
- Let middleware handle errors
- Use middleware for default headers
- Split endpoint and cloud storage handling at the router level.
- Use middleware for logging
…irectly

- Changed _handleUriCall to return Response instead of EndpointResult
- Exceptions now propagate to _reportException middleware which constructs Response objects directly
- Removed _toResponse method (no longer needed)
- Removed EndpointResult and all its subclasses (not part of public API)
- Updated NotAuthorizedException to store AuthenticationFailureReason directly instead of ResultAuthenticationFailed
- Updated EndpointDispatch.canUserAccessEndpoint to return AuthenticationFailureReason? instead of ResultAuthenticationFailed?
- Updated authentication tests to check AuthenticationFailureReason directly
- Make EndpointDispatchException sealed.
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Nov 6, 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.

@nielsenko
nielsenko force-pushed the server-use-relic-app branch from 32d5fb6 to 3a199f8 Compare November 6, 2025 10:47
@nielsenko nielsenko linked an issue Nov 6, 2025 that may be closed by this pull request
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Nov 6, 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: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7e989a2 and 3a199f8.

📒 Files selected for processing (5)
  • packages/serverpod/lib/src/server/endpoint_dispatch.dart (5 hunks)
  • packages/serverpod/lib/src/server/server.dart (11 hunks)
  • packages/serverpod/lib/src/server/websocket_request_handlers/method_websocket_request_handler.dart (1 hunks)
  • packages/serverpod/test/endpoint/authentication_test.dart (7 hunks)
  • packages/serverpod_test/lib/src/function_call_wrappers.dart (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.dart

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.dart: Format all Dart code using dart format . before committing
Code must pass Dart analyzer in strict mode (util/run_tests_analyze or melos lint_strict)
Use descriptive variable and function names

Files:

  • packages/serverpod/lib/src/server/websocket_request_handlers/method_websocket_request_handler.dart
  • packages/serverpod/lib/src/server/server.dart
  • packages/serverpod/test/endpoint/authentication_test.dart
  • packages/serverpod_test/lib/src/function_call_wrappers.dart
  • packages/serverpod/lib/src/server/endpoint_dispatch.dart
**/lib/**/*.dart

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Remove unnecessary comments from production code

Files:

  • packages/serverpod/lib/src/server/websocket_request_handlers/method_websocket_request_handler.dart
  • packages/serverpod/lib/src/server/server.dart
  • packages/serverpod_test/lib/src/function_call_wrappers.dart
  • packages/serverpod/lib/src/server/endpoint_dispatch.dart
**/*_test.dart

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*_test.dart: Write test descriptions using the Given/When/Then pattern
Organize tests with passing/success cases first, group related cases using group(), then follow with error cases

Files:

  • packages/serverpod/test/endpoint/authentication_test.dart
🧠 Learnings (9)
📚 Learning: 2025-09-17T16:09:20.868Z
Learnt from: nielsenko
Repo: serverpod/serverpod PR: 3980
File: packages/serverpod/lib/src/web_server/web_server.dart:102-115
Timestamp: 2025-09-17T16:09:20.868Z
Learning: In Serverpod's web server authentication handling (packages/serverpod/lib/src/web_server/web_server.dart), query parameter authentication fallback (`authenticationKey ??= queryParameters['auth']`) is intentionally maintained for legacy compatibility reasons, even though it has security implications regarding credential leakage.

Applied to files:

  • packages/serverpod/lib/src/server/websocket_request_handlers/method_websocket_request_handler.dart
  • packages/serverpod/lib/src/server/server.dart
  • packages/serverpod/test/endpoint/authentication_test.dart
  • packages/serverpod_test/lib/src/function_call_wrappers.dart
  • packages/serverpod/lib/src/server/endpoint_dispatch.dart
📚 Learning: 2025-11-04T12:09:52.649Z
Learnt from: marcelomendoncasoares
Repo: serverpod/serverpod PR: 4150
File: examples/auth/auth_flutter/lib/widgets/profile_info.dart:23-30
Timestamp: 2025-11-04T12:09:52.649Z
Learning: In Serverpod example and testing projects (e.g., examples/auth/auth_flutter), prefer letting errors bubble up naturally rather than handling them gracefully with catchError or try-catch blocks. This helps developers see what went wrong during development and testing.

Applied to files:

  • packages/serverpod/lib/src/server/websocket_request_handlers/method_websocket_request_handler.dart
  • packages/serverpod/test/endpoint/authentication_test.dart
  • packages/serverpod_test/lib/src/function_call_wrappers.dart
📚 Learning: 2025-08-26T13:22:33.125Z
Learnt from: tp
Repo: serverpod/serverpod PR: 3829
File: modules/new_serverpod_auth/serverpod_auth_idp/serverpod_auth_idp_server/lib/src/providers/passkey/business/passkey_accounts.dart:0-0
Timestamp: 2025-08-26T13:22:33.125Z
Learning: The passkeys_server Dart library evolved from version 0.3.0 to 0.4.0, adding required parameters to verifyRegistration and verifyLogin methods for complete WebAuthn security validation including challenge, clientDataJSON, and attestationObject verification.

Applied to files:

  • packages/serverpod/lib/src/server/websocket_request_handlers/method_websocket_request_handler.dart
  • packages/serverpod/test/endpoint/authentication_test.dart
📚 Learning: 2025-07-02T16:07:50.947Z
Learnt from: tp
Repo: serverpod/serverpod PR: 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:

  • packages/serverpod/lib/src/server/server.dart
  • packages/serverpod_test/lib/src/function_call_wrappers.dart
📚 Learning: 2025-11-03T15:40:41.827Z
Learnt from: SandPod
Repo: serverpod/serverpod PR: 4144
File: modules/new_serverpod_auth/serverpod_auth_idp/serverpod_auth_idp_server/lib/src/providers/passkey/endpoints/passkey_idp_base_endpoint.dart:0-0
Timestamp: 2025-11-03T15:40:41.827Z
Learning: In Serverpod authentication IDP endpoint files (modules/new_serverpod_auth/serverpod_auth_idp/serverpod_auth_idp_server), endpoint base classes should import `serverpod_auth_idp_server/core.dart` to access the Session type, rather than importing `package:serverpod_auth_core_server/session.dart` directly. This pattern is consistently used in Apple, Email, and Google endpoint files.

Applied to files:

  • packages/serverpod/lib/src/server/server.dart
  • packages/serverpod/test/endpoint/authentication_test.dart
  • packages/serverpod_test/lib/src/function_call_wrappers.dart
  • packages/serverpod/lib/src/server/endpoint_dispatch.dart
📚 Learning: 2025-08-25T19:46:58.073Z
Learnt from: tp
Repo: serverpod/serverpod PR: 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:

  • packages/serverpod/lib/src/server/server.dart
📚 Learning: 2025-07-03T09:16:08.642Z
Learnt from: nielsenko
Repo: serverpod/serverpod PR: 3625
File: packages/serverpod/lib/src/cloud_storage/public_endpoint.dart:82-93
Timestamp: 2025-07-03T09:16:08.642Z
Learning: In Serverpod's CloudStoragePublicEndpoint, the _readBinaryBody method must buffer the entire request body in memory because the storage.storeFile interface requires a ByteData object. Implementing true streaming uploads would require reworking Serverpod's serialization handling of binary arguments. The current implementation uses BytesBuilder for efficient byte accumulation instead of list concatenation.

Applied to files:

  • packages/serverpod/lib/src/server/server.dart
📚 Learning: 2025-06-18T14:49:11.263Z
Learnt from: tp
Repo: serverpod/serverpod PR: 3672
File: tests/serverpod_test_server/test_integration/test_tools/test_session_builder_test.dart:10-30
Timestamp: 2025-06-18T14:49:11.263Z
Learning: In Serverpod test files, tp prefers using nullable late variables for AuthenticationInfo in tests (e.g., `late AuthenticationInfo? authenticationInfo;`) rather than non-nullable ones to avoid using `!` operators and to get clearer error messages when authentication setup fails. This provides better diagnostics when `session.authenticated` returns null.

Applied to files:

  • packages/serverpod/test/endpoint/authentication_test.dart
  • packages/serverpod_test/lib/src/function_call_wrappers.dart
  • packages/serverpod/lib/src/server/endpoint_dispatch.dart
📚 Learning: 2025-07-02T16:09:27.702Z
Learnt from: tp
Repo: serverpod/serverpod PR: 3747
File: tests/serverpod_new_auth_test/serverpod_new_auth_test_server/pubspec.yaml:37-38
Timestamp: 2025-07-02T16:09:27.702Z
Learning: In Serverpod migration testing, it's appropriate for test servers like serverpod_new_auth_test_server to include dependencies on both legacy packages (e.g., serverpod_auth_server) and new modular packages to enable comprehensive testing of migration paths from old to new authentication systems.

Applied to files:

  • packages/serverpod/test/endpoint/authentication_test.dart

@nielsenko
nielsenko force-pushed the server-use-relic-app branch from ba1561a to eba4895 Compare November 6, 2025 12:01
@nielsenko
nielsenko marked this pull request as ready for review November 6, 2025 12:03
@nielsenko
nielsenko requested a review from a team November 6, 2025 12:03

@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 looks good, have a couple of comments and minor suggestions.

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

@nielsenko
nielsenko merged commit cd0d0f5 into serverpod:main Nov 6, 2025
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 6, 2025
@nielsenko
nielsenko deleted the server-use-relic-app branch August 20, 2026 15:10
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Refactor request handling to use Router class from relic package

2 participants