Skip to content

feat: Router class - #52

Merged
nielsenko merged 11 commits into
mainfrom
router
May 7, 2025
Merged

nielsenko merged 11 commits into
mainfrom
router

Conversation

@nielsenko

@nielsenko nielsenko commented May 5, 2025 •

Copy link
Copy Markdown
Collaborator

Description

This PR introduces support for:

  • Static and Dynamic Routing: Supports exact path matching (e.g., /about) and paths with named parameters (e.g., /users/:userId).
  • Path Normalization: Input paths are automatically normalized to handle redundant slashes (//), current directory segments (.), and parent directory segments (..) consistently.
  • Parameter Extraction: For dynamic routes, named parameters are extracted from the request path and made available.

It aspire to be efficient by using different data structure for each route type. A hash map for fast O(1) static lookups and a path segment trie for efficient dynamic route matching and parameter extraction. An expensive part of routing is path normalization. To mitigate the cost, we use interning of normalized path, but bound the memory use with an LRU cahce.

  1. NormalizedPath

    • The NormalizedPath class (router/lib/normalized_path.dart) represents a canonical, standardized form of a URL path. It processes the input string, resolving segments like . and .., removing empty segments, and ensuring it starts with /.
    • To minimize memory usage and improve comparison speed (especially important for map keys), NormalizedPath instances are interned using an LruCache. This means that identical normalized paths (e.g., from /a/b and /a//b/.) will share the same object instance after normalization. The original path string is also cached against the normalized instance for faster subsequent lookups.
  2. PathTrie

    • Dynamic routes (those containing parameters like :id) are stored in a PathTrie (router/lib/path_trie.dart), a specialized prefix tree data structure.
    • Each node in the trie represents a path segment. Literal segments (like users) and parameterized segments (like :id) are handled distinctly.
    • This structure allows for efficient matching of incoming paths against registered dynamic routes. When traversing the trie with an incoming path, the router prioritizes literal matches over parameter matches at each level. Parameter values are captured during traversal.
    • The PathTrie also includes checks to prevent ambiguous routes, such as defining /users/:id and /users/:userId at the same level.
  3. LruCache

    • A simple Least Recently Used (LRU) cache (router/lib/lru_cache.dart) is implemented using a LinkedHashMap.
    • It's primarily used by NormalizedPath for interning path instances, ensuring that frequently accessed normalized paths remain in the cache while less frequent ones are evicted, keeping memory usage bounded.
  4. Router

    • The main Router class (router/lib/router.dart) orchestrates the routing logic.
    • It separates routes by type:
      • Static routes (no parameters) are stored in a standard HashMap (staticRoutes), keyed by their NormalizedPath. This provides O(1) average lookup time for the most common type of route.
      • Dynamic routes are delegated to the PathTrie (dynamicRoutes) for efficient prefix matching and parameter extraction.
    • During lookup, the Router first checks the staticRoutes HashMap for a quick match. If not found, it then consults the dynamicRoutes PathTrie.

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): 2948.4918414918416 us.
Router Lookup Static x10000(RunTime): 2163.6859070464766 us.
Router Add Dynamic x10000(RunTime): 25896.272727272728 us.
Router Lookup Dynamic x10000(RunTime): 2929.972027972028 us.
Done

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.

Summary by CodeRabbit

  • New Features

    • Introduced a generic URL router supporting static and dynamic routes with parameter extraction.
    • Added efficient path normalization and matching, including support for parameterized segments.
    • Implemented a Least Recently Used (LRU) cache for internal optimizations.
  • Bug Fixes

    • Not applicable.
  • Tests

    • Added comprehensive test suites for the router, path trie, normalized path, and LRU cache to ensure correctness and robustness.
  • Chores

    • Added benchmarking tools to measure routing performance.
    • Updated development dependencies to include benchmarking support.
  • Documentation

    • Not applicable.

@coderabbitai

coderabbitai Bot commented May 5, 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

This change introduces a complete routing subsystem to the codebase. It adds a generic Router class capable of mapping normalized URL paths (both static and dynamic with parameters) to values, backed by a static route map and a dynamic path trie. Supporting classes include an LRU cache for efficient path normalization and a NormalizedPath class for canonical path representation. The PathTrie class enables efficient dynamic route matching and parameter extraction. The public API is exposed via the main library file. The update also includes comprehensive unit tests for all major components and a benchmarking suite for performance measurement. The benchmark_harness package is added as a development dependency.

Changes

File(s) Change Summary
lib/relic.dart Added export for src/router/router.dart to expose routing API.
lib/src/router/router.dart Introduced generic Router<T> class with support for static and dynamic (parameterized) route registration and lookup.
lib/src/router/path_trie.dart Implemented PathTrie<T> and LookupResult<T> for efficient dynamic route matching and parameter extraction.
lib/src/router/normalized_path.dart Added NormalizedPath class for canonical path representation and normalization, with LRU interning.
lib/src/router/lru_cache.dart Added generic LruCache<K, V> for use in path normalization and caching.
benchmark/benchmark.dart Introduced performance benchmarking suite for static and dynamic route addition and lookup.
pubspec.yaml Added benchmark_harness as a development dependency.
test/router/lru_cache_test.dart Added unit tests for LruCache covering insertion, retrieval, update, and eviction behavior.
test/router/normalized_path_test.dart Added unit tests for NormalizedPath covering normalization, interning, equality, and string representation.
test/router/path_trie_test.dart Added comprehensive unit tests for PathTrie covering route addition, lookup, parameter extraction, and errors.
test/router/router_test.dart Added unit tests for Router covering static/dynamic routing, normalization, prioritization, and errors.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Router
    participant PathTrie
    participant NormalizedPath

    Client->>Router: add(path, handler)
    Router->>NormalizedPath: normalize(path)
    alt path has parameters
        Router->>PathTrie: add(NormalizedPath, handler)
    else
        Router->>Router: add to staticRoutes
    end

    Client->>Router: lookup(path)
    Router->>NormalizedPath: normalize(path)
    alt staticRoutes contains NormalizedPath
        Router-->>Client: handler
    else
        Router->>PathTrie: lookup(NormalizedPath)
        alt match found
            PathTrie-->>Router: LookupResult (handler, params)
            Router-->>Client: handler, params
        else
            Router-->>Client: null
        end
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Support for defining routes with HTTP methods (GET, POST, etc.) (#7) ❌ No HTTP method handling is present; only path-based routing is implemented.
Route parameter handling (e.g., /users/:id) (#7) ✅
Middleware support for pre- and post-route execution (#7) ❌ Middleware functionality is not implemented in this change.
Nested or grouped routes for better organization (#7) ❌ No explicit support for route grouping or nesting is present.
Error handling for undefined or invalid routes (#7) ✅

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.

@codecov

codecov Bot commented May 5, 2025 •

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 80.04%. Comparing base (1b61832) to head (7a854b2).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #52      +/-   ##
==========================================
+ Coverage   79.16%   80.04%   +0.87%     
==========================================
  Files          74       78       +4     
  Lines        2165     2260      +95     
  Branches     1233     1283      +50     
==========================================
+ Hits         1714     1809      +95     
  Misses        451      451              

☔ 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
nielsenko force-pushed the router branch 2 times, most recently from 1b21a05 to 3798afe Compare May 5, 2025 14:04
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 5, 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: 3

🧹 Nitpick comments (11)
lib/src/router/lru_cache.dart (2)

50-56: Consider optimizing the trim operation.

The current implementation iterates and removes entries one by one when trimming, which is fine for small excess removals.

When only removing a single entry (the most common case), you could optimize with a direct removal:

void _trim() {
  // Evict oldest entries if we've exceeded max size
  var keysToRemove = _cache.length - _maxSize;
-  while (keysToRemove-- > 0) {
-    _cache.remove(_cache.keys.first);
-  }
+  if (keysToRemove <= 0) return;
+  
+  // Fast path for single removal (common case)
+  if (keysToRemove == 1) {
+    _cache.remove(_cache.keys.first);
+    return;
+  }
+  
+  // Slower path for multiple removals
+  while (keysToRemove-- > 0) {
+    _cache.remove(_cache.keys.first);
+  }
}

58-60: Consider adding additional utility methods.

The cache implementation is solid, but could benefit from a few additional methods to enhance its functionality.

Consider adding these methods for improved usability:

/// Returns true if the cache contains [key].
/// Note: This does not affect the item's position in the LRU order.
bool containsKey(final K key) => _cache.containsKey(key);

/// Removes all entries from the cache.
void clear() => _cache.clear();

/// Removes the entry with [key] if present.
/// Returns the value associated with [key] before removal, or null if not found.
V? remove(final K key) => _cache.remove(key);
test/router/lru_cache_test.dart (2)

6-8: Missing comma in test description

There's a missing comma after "negative capacity" which makes the test description less readable.

-      'Given a negative capacity'
+      'Given a negative capacity, '
       'when cache is created '
       'then it fails', () {

13-15: Inconsistent test description wording

For consistency with other test descriptions, consider adding the article "a" before "cache is created".

       'Given a positive capacity, '
-      'when cache is created '
+      'when a cache is created '
       'then length is 0', () {
lib/src/router/normalized_path.dart (2)

13-13: Consider making the LRU cache size configurable

The cache capacity of 10000 is hardcoded, which might be excessive for some applications or insufficient for others. Consider making this configurable or at least document why this specific size was chosen.


27-36: Complex interning logic could be simplified

The interning logic is somewhat complex and might be difficult to follow. Consider simplifying it by restructuring or adding more detailed comments.

A clearer alternative could be:

  factory NormalizedPath(final String path) {
    var result = _interned[path];
    if (result == null) {
      result = NormalizedPath._(_normalize(path));
-      // intern for both normalized path and path
-      result = _interned[result.path] ??= result;
-      _interned[path] = result; // cache for original path as well
+      // Check if an equivalent normalized path already exists
+      final normalizedPath = result.path;
+      var internedResult = _interned[normalizedPath];
+      if (internedResult == null) {
+        // No existing instance, store this one
+        _interned[normalizedPath] = result;
+      } else {
+        // Use the existing instance
+        result = internedResult;
+      }
+      // Cache using the original path string as well
+      _interned[path] = result;
    }
    return result;
  }
lib/src/router/router.dart (1)

19-21: Consider encapsulating parameter identification logic

The _isDynamic method identifies parameter segments by checking if they start with :. If parameter syntax might change in the future (e.g., to support wildcards like *), this logic would need to be updated in multiple places. Consider extracting this to a more flexible mechanism.

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

42-45: Comment/documentation and implementation are out-of-sync

The comment claims that an existing value “is overwritten, and a warning is printed” but the actual code throws ArgumentError. Either restore the overwrite-and-warn behaviour or update the docs to reflect the current (safer) behaviour so downstream users know what to expect.

-  /// If a route with the exact same path already exists, its value is
-  /// overwritten, and a warning is printed.
+  /// If a route with the exact same path already exists, an
+  /// [ArgumentError] is thrown to prevent accidental overwrites.

Also applies to: 79-88


101-114: Consider String over Symbol for parameter keys

Symbol values created at runtime are never garbage-collected in Dart ≤3.3, which can lead to a slow memory leak if many unique parameter names are registered dynamically (e.g., via user-defined plugins). Using String (or an interned enum) avoids that risk and keeps JSON-serialisation simple.

test/router/path_trie_test.dart (1)

178-182: Typo: “NormalizedBox” should be “NormalizedPath”

Minor documentation slip — the test comment refers to NormalizedBox, which does not exist.

-      'should handle paths with trailing slashes consistently due to NormalizedBox',
+      'should handle paths with trailing slashes consistently due to NormalizedPath',
benchmark/benchmark.dart (1)

108-115: Interactive pause blocks automated runners

Waiting for <enter> when a VM service is detected hinders CI / automated benchmark runs and forces manual interaction:

if (info.serverUri != null) {
  print('Press <enter> when ready..');
  ...
}

Either guard this behind a CLI flag/environment variable or remove it for non-debug runs.

-  if (info.serverUri != null) {
-    print('Press <enter> when ready..');
-    if (stdin.hasTerminal) {
-      await stdin.first;
-    }
-  }
+  if (info.serverUri != null && stdin.hasTerminal &&
+      (const String.fromEnvironment('WAIT_FOR_DEBUGGER') == 'true')) {
+    print('Debugger attached.  Press <enter> when ready…');
+    await stdin.first;
+  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1b61832 and 0f7c6d4.

📒 Files selected for processing (11)
  • benchmark/benchmark.dart (1 hunks)
  • lib/relic.dart (1 hunks)
  • lib/src/router/lru_cache.dart (1 hunks)
  • lib/src/router/normalized_path.dart (1 hunks)
  • lib/src/router/path_trie.dart (1 hunks)
  • lib/src/router/router.dart (1 hunks)
  • pubspec.yaml (1 hunks)
  • test/router/lru_cache_test.dart (1 hunks)
  • test/router/normalized_path_test.dart (1 hunks)
  • test/router/path_trie_test.dart (1 hunks)
  • test/router/router_test.dart (1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
lib/src/router/normalized_path.dart

[warning] 78-78: lib/src/router/normalized_path.dart#L78
Added line #L78 was not covered by tests

🔇 Additional comments (18)
pubspec.yaml (1)

20-20: LGTM! Appropriate addition of the benchmark dependency.

The benchmark_harness package is correctly added as a development dependency, which aligns with the introduction of new benchmarking capabilities for the router functionality described in the PR objectives.

lib/relic.dart (1)

24-24: LGTM! Properly exposing the new Router API.

The Router class is now appropriately exported through the main library file, making it available for public consumption. This aligns with the PR objective of introducing a new Router class for URL path matching.

test/router/router_test.dart (8)

5-67: Comprehensive tests for basic router functionality.

The tests cover empty router scenarios, root path handling, and normalization of empty paths properly. The helper function for testing lookup results is well implemented.


69-177: Well-structured tests for static route handling.

Tests thoroughly verify static routes with different patterns of trailing slashes and multi-segment paths. The test groups follow a clear Given-When-Then pattern that improves readability.


181-216: Good error case testing for duplicate routes.

Tests properly verify that adding duplicate static routes throws ArgumentError and that the original routes remain intact. This helps ensure route integrity.


218-456: Comprehensive tests for dynamic route parameter extraction.

Tests thoroughly cover single and multi-parameter routes, parameter extraction, and proper prioritization of static routes over dynamic ones when they conflict.


459-488: LGTM! Good testing of conflicting dynamic routes.

The tests verify that attempting to add conflicting dynamic routes with different parameter names at the same position throws an error and preserves the original route.


490-534: LGTM! Proper testing of route prioritization.

Tests confirm that static routes are correctly prioritized over dynamic routes when they could both match a specific path.


536-566: LGTM! Good testing of route type isolation.

Tests ensure that static paths won't match dynamic routes and vice versa, verifying proper separation of route handling logic.


568-606: LGTM! Thorough testing of path normalization.

Tests verify that routes added with inconsistent slash patterns (leading, trailing, or both) are properly normalized and still match the intended paths.

lib/src/router/lru_cache.dart (4)

1-13: LGTM! Well-documented LRU cache implementation.

The implementation uses LinkedHashMap as the backing data structure, which is ideal for maintaining insertion order needed for LRU functionality. The class documentation clearly explains the purpose and behavior.


14-21: LGTM! Proper validation in constructor.

The constructor correctly validates that the cache size is positive, throwing an ArgumentError otherwise.


23-34: Efficient implementation of item retrieval with LRU update.

The lookup operator correctly removes and reinserts the item to mark it as recently used.


36-48: LGTM! Proper implementation of item insertion/update.

The assignment operator correctly handles both new insertions and updates to existing keys, maintaining the LRU ordering.

test/router/normalized_path_test.dart (1)

1-202: Well-structured and comprehensive test suite!

The test suite provides excellent coverage of the NormalizedPath class functionality including normalization logic, interning behavior, equality/hash code consistency, and string representation. The test descriptions follow a clear given/when/then pattern that makes the test intent explicit.

I particularly like how you've covered edge cases like:

  • Handling of . and .. segments
  • Path normalization with redundant slashes
  • Behavior when .. appears at the start or would go beyond root
  • Empty path normalization

The comment on lines 138-141 about the complexity of testing cache eviction is also appropriate.

test/router/lru_cache_test.dart (2)

68-106: LGTM - Effective LRU eviction testing

This test group effectively verifies the LRU cache behavior by testing both scenarios where an item becomes MRU:

  1. Through access via get operation
  2. Through update via put operation

The assertions comprehensively verify the cache state after operations.


109-159: LGTM - Thorough small-capacity LRU cache tests

The tests for caches with capacity 1 and 2 provide valuable verification of edge case behaviors. These smaller capacity tests are important for ensuring the basic LRU eviction works as expected in minimal scenarios.

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

62-69: LGTM - Efficient lookup implementation

The lookup implementation correctly prioritizes the fast static route lookup path before falling back to the more complex dynamic route matching. This is a good optimization.

Comment thread lib/src/router/normalized_path.dart Resolved
Comment thread lib/src/router/router.dart Resolved
Comment thread lib/src/router/path_trie.dart Resolved
@nielsenko
nielsenko requested a review from SandPod May 6, 2025 06:04
@nielsenko
nielsenko marked this pull request as ready for review May 6, 2025 06:04
Comment thread lib/src/router/normalized_path.dart Resolved

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

Nice work!

Have a couple of questions. But most of my time was spent on a single commit and I think you addressed a couple of the concerns in later commits. So feel free to close anything that is not relevant anymore.

Did you have any number for the benchmarks?
Maybe you could post them in the description of this PR so that we have something concerete to point agains?

Comment thread test/router/lru_cache_test.dart Resolved
Comment thread lib/src/router/normalized_path.dart Resolved
Comment thread lib/src/router/normalized_path.dart Resolved
Comment thread lib/src/router/normalized_path.dart Resolved
Comment thread lib/src/router/normalized_path.dart Resolved
Comment thread lib/src/router/path_trie.dart Resolved
Comment thread lib/src/router/path_trie.dart Resolved
Comment thread test/router/path_trie_test.dart Resolved
Comment thread test/router/path_trie_test.dart Resolved
Comment thread test/router/path_trie_test.dart Resolved
@nielsenko
nielsenko requested a review from SandPod May 7, 2025 07:30

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

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.

Route parameter handling (e.g., /users/:id).

2 participants