Repository navigation
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 📝 WalkthroughWalkthroughThis change introduces a complete routing subsystem to the codebase. It adds a generic Changes
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
Assessment against linked issues
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Codecov ReportAll modified and coverable lines are covered by tests ✅
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. 🚀 New features to boost your workflow:
|
1b21a05 to
3798afe
Compare
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
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 descriptionThere'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 wordingFor 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 configurableThe 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 simplifiedThe 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 logicThe
_isDynamicmethod 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-syncThe 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: ConsiderStringoverSymbolfor parameter keys
Symbolvalues 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). UsingString(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 runnersWaiting 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
📒 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_harnesspackage 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
LinkedHashMapas 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
NormalizedPathclass 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 testingThis test group effectively verifies the LRU cache behavior by testing both scenarios where an item becomes MRU:
- Through access via get operation
- Through update via put operation
The assertions comprehensively verify the cache state after operations.
109-159: LGTM - Thorough small-capacity LRU cache testsThe 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 implementationThe 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.
SandPod
left a comment
There was a problem hiding this comment.
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?
Description
This PR introduces support for:
/about) and paths with named parameters (e.g.,/users/:userId).//), current directory segments (.), and parent directory segments (..) consistently.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.
NormalizedPath
NormalizedPathclass (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/.NormalizedPathinstances are interned using anLruCache. This means that identical normalized paths (e.g., from/a/band/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.PathTrie
:id) are stored in aPathTrie(router/lib/path_trie.dart), a specialized prefix tree data structure.users) and parameterized segments (like:id) are handled distinctly.PathTriealso includes checks to prevent ambiguous routes, such as defining/users/:idand/users/:userIdat the same level.LruCache
router/lib/lru_cache.dart) is implemented using aLinkedHashMap.NormalizedPathfor interning path instances, ensuring that frequently accessed normalized paths remain in the cache while less frequent ones are evicted, keeping memory usage bounded.Router
Routerclass (router/lib/router.dart) orchestrates the routing logic.HashMap(staticRoutes), keyed by theirNormalizedPath. This provides O(1) average lookup time for the most common type of route.PathTrie(dynamicRoutes) for efficient prefix matching and parameter extraction.Routerfirst checks thestaticRoutesHashMapfor a quick match. If not found, it then consults thedynamicRoutesPathTrie.Benchmark results
2,4 GHz 8-Core Intel Core i9
Related Issues
Pre-Launch Checklist
Please ensure that your PR meets the following requirements before submitting:
///), ensuring consistency with existing project documentation.Breaking Changes
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Chores
Documentation