Skip to content

feat: Support Router.attach - #62

Merged
nielsenko merged 6 commits into
serverpod:mainfrom
nielsenko:router-attach
May 9, 2025
Merged

nielsenko merged 6 commits into
serverpod:mainfrom
nielsenko:router-attach

Conversation

@nielsenko

@nielsenko nielsenko commented May 9, 2025 •

Copy link
Copy Markdown
Collaborator

Description

This Pull Request introduces the Router.attach feature, with corresponding unit tests.

This PR changes how we optimize for static routes. Now all routes are added to the trie,
wheather they are static or not and the HashMap of static routes is purely a performance
optimization that is updated lazily on lookup.

The advantage of maintaining all routes in the trie is that it makes implementing attach
trivial.

I considered dropping the optimization for static routes completely, but maintaining it
lazily proved simple.

The PR also extends the benchmark for comparision with another router wrt. add and lookup
of dynamic and static routes.

Related Issues

Pre-Launch Checklist

Please ensure that your PR meets the following requirements before submitting:

  • This update focuses on a single feature or bug fix. (For multiple fixes, please submit separate PRs.)
  • I have read and followed the Dart Style Guide and formatted the code using dart format.
  • I have referenced at least one issue this PR fixes or is related to.
  • I have updated/added relevant documentation (doc comments with ///), ensuring consistency with existing project documentation.
  • I have added new tests to verify the changes.
  • All existing and new tests pass successfully.
  • I have documented any breaking changes below.

Breaking Changes

  • Includes breaking changes.
  • No breaking changes.

Benchmark results:

2,4 GHz 8-Core Intel Core i9

./benchmark/benchmark.exe
Setting up benchmark data with 10000 routes...
Setup complete.
Starting benchmarks
Router Add Static x10000(RunTime): 5417.4670329670325 us.
Routingkit Add Static x10000(RunTime): 10859.33908045977 us.
Router Lookup Static x10000(RunTime): 1408.81 us.
Routingkit Lookup Static x10000(RunTime): 2318.04 us.
Router Add Dynamic x10000(RunTime): 26446.70707070707 us.
Routingkit Add Dynamic x10000(RunTime): 15398.784 us.
Router Lookup Dynamic x10000(RunTime): 3205.05875 us.
Routingkit Lookup Dynamic x10000(RunTime): 18607.539130434783 us.
Done

Summary by CodeRabbit

  • New Features

    • Added support for distinguishing between static and dynamic route matches in route lookups.
    • Introduced new benchmarks for measuring performance with the routingkit package.
  • Bug Fixes

    • Improved handling when attaching sub-routers, including error handling for conflicting routes.
  • Refactor

    • Unified static and dynamic route storage into a single structure with lazy caching for static routes.
    • Localized router setup within benchmark classes for clearer benchmarking.
  • Tests

    • Enhanced test coverage for sub-router attachment and route conflict scenarios.
    • Improved test descriptions for readability.
  • Chores

    • Added .exe files to .gitignore.
    • Added routingkit to development dependencies.

@coderabbitai

coderabbitai Bot commented May 9, 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 changes unify static and dynamic route storage in the Router class by using a single PathTrie, with a lazy static route cache for fast lookups. The attach method merges sub-router tries. Benchmarks are refactored and extended to include routingkit comparisons. Tests are updated for router attachment scenarios.

Changes

File(s) Change Summary
.gitignore Added rule to ignore .exe files.
pubspec.yaml Added routingkit to dev_dependencies.
benchmark/benchmark.dart Refactored benchmark setup; moved router initialization into benchmark classes; added new benchmarks for routingkit; updated driver to include new benchmarks.
lib/src/router/path_trie.dart Added isDynamic field to LookupResult; updated trie lookup to set this flag based on matched route type.
lib/src/router/router.dart Unified static and dynamic routes into a single PathTrie; replaced static route map with lazy cache; refactored add, attach, and lookup methods to use new structure.
test/router/router_test.dart Improved test descriptions; added new tests for sub-router attachment and conflict scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant MainRouter as Router
    participant SubRouter as Router
    participant PathTrie

    MainRouter->SubRouter: attach('/foo', SubRouter)
    SubRouter->PathTrie: get _allRoutes
    MainRouter->PathTrie: merge SubRouter._allRoutes
    PathTrie-->>MainRouter: merged trie

    MainRouter->MainRouter: clear SubRouter's _staticCache
Loading
sequenceDiagram
    participant Router
    participant PathTrie
    participant StaticCache

    Router->StaticCache: lookup(path)
    alt found in cache
        StaticCache-->>Router: return value
    else not found
        Router->PathTrie: lookup(path)
        PathTrie-->>Router: LookupResult(value, params, isDynamic)
        alt isDynamic == false
            Router->StaticCache: cache value
        end
        Router-->>Caller: return LookupResult
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Handle dynamic routes on attach (#59) ✅
Handle static routes on attach (#60) ✅

Possibly related PRs


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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@nielsenko nielsenko self-assigned this May 9, 2025
@codecov

codecov Bot commented May 9, 2025 •

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 80.09%. Comparing base (ed56e37) to head (3959ecb).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #62      +/-   ##
==========================================
+ Coverage   80.07%   80.09%   +0.01%     
==========================================
  Files          78       78              
  Lines        2279     2281       +2     
  Branches     1289     1290       +1     
==========================================
+ Hits         1825     1827       +2     
  Misses        454      454              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@nielsenko

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 9, 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 marked this pull request as ready for review May 9, 2025 07:44
@coderabbitai

coderabbitai Bot commented May 9, 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: 2

🧹 Nitpick comments (3)
benchmark/benchmark.dart (2)

60-68: Use late final to prevent unintended reassignment of benchmark routers

staticRouterForLookup is only set once in setup() and never reassigned.
Declaring it as late final documents this intent and protects against
accidental mutation inside future refactors.

-  late Router<int> staticRouterForLookup;
+  late final Router<int> staticRouterForLookup;

(The same applies to dynamicRouterForLookup, staticRouterForLookup
and dynamicRouterForLookup in the routing-kit benchmarks further
below.)


116-187: Consider factoring out duplicated benchmark boiler-plate

All four routing-kit benchmark classes replicate the same
loop-initialisation logic already present in the in-house router
benchmarks. Extracting a small helper (or even a generic mix-in)
would:

  • eliminate ~70 duplicate LOC,
  • ensure the two router families stay behaviour-identical, and
  • make it easier to tweak parameters such as routeCount
    without touching six separate places.

This is an optional readability / maintainability refactor, no
functional issue.

lib/src/router/router.dart (1)

50-63: Minor: avoid constructing a fresh LookupResult when cache hits

On a cache hit we already know the route is static and parameters are
empty. Returning a pre-allocated constant can save a small amount of
GC pressure inside tight loops (e.g. benchmarks):

-if (value != null) return LookupResult(value, {}, false);
+if (value != null) {
+  // Re-use a shared empty map to avoid allocation on every hit.
+  return LookupResult(value, const {}, false);
+}

Not critical, but it moves the hot-path to zero allocations.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ed56e37 and edf0e30.

📒 Files selected for processing (6)
  • .gitignore (1 hunks)
  • benchmark/benchmark.dart (5 hunks)
  • lib/src/router/path_trie.dart (4 hunks)
  • lib/src/router/router.dart (2 hunks)
  • pubspec.yaml (1 hunks)
  • test/router/router_test.dart (13 hunks)
🔇 Additional comments (9)
pubspec.yaml (1)

24-24: Dependency addition looks good for benchmarking.

Adding the routingkit package as a dev dependency will enable performance comparison benchmarks as mentioned in the PR objectives.

.gitignore (1)

17-17: Good addition to ignore executable files.

Adding *.exe to .gitignore is appropriate when introducing benchmarking code that might generate Windows executables during testing.

lib/src/router/path_trie.dart (5)

11-12: Clean implementation of the isDynamic flag.

Good documentation explaining the purpose of this new field, which will help track whether a matched route contains parameters.


15-15: Constructor updated correctly for the new field.

The constructor has been properly modified to include the new isDynamic parameter.


156-156: Flag initialization for route dynamism tracking.

Good initialization of the isDynamic flag to false by default, which will be toggled when parameter segments are matched.


169-169: Dynamic route detection logic.

The flag is correctly set to true when a parameterized segment is matched during path traversal.


178-178: Complete implementation of the lookup result.

The isDynamic flag is properly passed to the LookupResult constructor, completing the implementation of the dynamic route tracking feature.

test/router/router_test.dart (2)

24-25: Improved test descriptions for better readability.

The commas added to the test descriptions improve readability and adhere to proper grammar in multi-line descriptions.

Also applies to: 31-32, 38-39, 45-46, 53-54, 61-62, 80-81, 87-88, 94-95, 112-113, 119-120, 138-139, 145-146, 166-167, 228-229, 235-236, 242-243, 259-260, 266-267, 283-284, 290-291, 317-318, 324-325, 352-353, 560-561


607-666: Comprehensive tests for Router.attach feature.

Excellent test coverage for the new attach functionality, including:

  • Verifying routes from sub-routers are accessible with the correct path prefix
  • Testing with and without trailing slashes
  • Validating root path handling
  • Checking non-existent route behavior
  • Confirming error handling for conflicting routes

These tests thoroughly validate the feature described in the PR objectives.

Comment thread lib/src/router/router.dart Resolved
Comment thread lib/src/router/router.dart Resolved
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 9, 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 requested a review from SandPod May 9, 2025 08:22

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

Nothing to comment about.

Comment thread benchmark/benchmark.dart Resolved
Comment thread lib/src/router/router.dart Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Handle static routes on attach Handle dynamic routes on attach

2 participants