armature-core 0.8.5

High-performance async HTTP framework core - routing, handlers, middleware
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
//! Route Matching Cache and Static Route Optimization
//!
//! This module provides optimizations for route matching:
//!
//! - **Route Cache**: LRU cache for recently matched routes
//! - **Static Fast Path**: O(1) HashMap lookup for static routes
//! - **Compiled Routes**: Pre-analyzed route patterns
//!
//! # Performance
//!
//! - Cache hit: ~5ns (vs ~50-150ns for pattern matching)
//! - Static lookup: ~10ns (vs ~50ns+ for trie traversal)
//! - Cache miss: Falls back to normal matching + caches result
//!
//! # Usage
//!
//! ```rust,ignore
//! use armature_core::route_cache::{CachedRouter, StaticRoutes};
//!
//! // Create cached router
//! let mut router = CachedRouter::new();
//! router.add_static("/api/health", handler);
//! router.add_pattern("/users/:id", handler);
//!
//! // Routing uses optimized paths automatically
//! let response = router.route(request).await?;
//! ```

use crate::handler::BoxedHandler;
use crate::route_constraint::RouteConstraints;
use crate::routing::Router;
use crate::{Error, HttpMethod, HttpRequest, HttpResponse};
use bytes::Bytes;
use lru::LruCache;
use parking_lot::Mutex;
use smallvec::SmallVec;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::num::NonZeroUsize;
use std::sync::atomic::{AtomicU64, Ordering};

/// Max path segments kept inline (on the stack) before a segment split falls
/// back to heap allocation. Mirrors `routing::split_segments`'s inline
/// capacity so the common case (`<= 8` segments) never allocates a `Vec`
/// just to walk the path during matching/extraction.
const INLINE_PATH_SEGMENTS: usize = 8;

// ============================================================================
// Cache Key
// ============================================================================

/// A cache key combining method and path.
#[derive(Clone, Debug, Eq)]
pub struct RouteKey {
    /// HTTP method
    method: HttpMethod,
    /// Request path (without query string)
    path: String,
}

impl RouteKey {
    /// Create a new route key.
    #[inline]
    pub fn new(method: HttpMethod, path: impl Into<String>) -> Self {
        Self {
            method,
            path: path.into(),
        }
    }

    /// Create from request.
    ///
    /// Returns `None` if the request method is not a known HTTP method, so
    /// unknown methods are never silently treated as GET.
    #[inline]
    pub fn from_request(req: &HttpRequest) -> Option<Self> {
        let path = req
            .path
            .split_once('?')
            .map(|(p, _)| p)
            .unwrap_or(&req.path);

        Some(Self {
            method: HttpMethod::try_from(&req.method).ok()?,
            path: path.to_string(),
        })
    }
}

impl PartialEq for RouteKey {
    fn eq(&self, other: &Self) -> bool {
        self.method == other.method && self.path == other.path
    }
}

impl Hash for RouteKey {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.method.as_str().hash(state);
        self.path.hash(state);
    }
}

// ============================================================================
// Cache Entry
// ============================================================================

/// A cached route match result.
#[derive(Clone)]
pub struct CachedRoute {
    /// Index into the route table
    pub route_index: usize,
    /// Pre-extracted path parameters (interned name, segment_index)
    pub param_indices: Vec<(&'static str, usize)>,
    /// Is this a static route (no params)?
    pub is_static: bool,
    /// Segment index of a catch-all parameter, if any.
    ///
    /// The catch-all parameter captures all remaining segments joined with
    /// `/`, mirroring `CompiledRoute::extract_params`.
    pub catch_all_index: Option<usize>,
}

impl CachedRoute {
    /// Create a cached entry for a static route.
    pub fn static_route(route_index: usize) -> Self {
        Self {
            route_index,
            param_indices: Vec::new(),
            is_static: true,
            catch_all_index: None,
        }
    }

    /// Create a cached entry for a parameterized route.
    ///
    /// Names must already be interned via [`crate::param_intern::intern`];
    /// taking them pre-interned is what keeps that lock off the request path.
    pub fn with_params(route_index: usize, param_indices: Vec<(&'static str, usize)>) -> Self {
        Self {
            route_index,
            param_indices,
            is_static: false,
            catch_all_index: None,
        }
    }

    /// Create a cached entry from a compiled route pattern.
    pub fn from_compiled(route_index: usize, compiled: &CompiledRoute) -> Self {
        Self {
            route_index,
            param_indices: compiled.param_indices.clone(),
            is_static: compiled.is_static,
            catch_all_index: compiled
                .has_catch_all
                .then(|| compiled.segments.len().saturating_sub(1)),
        }
    }

    /// Extract parameters from a path using cached indices.
    #[inline]
    pub fn extract_params(&self, path: &str) -> crate::RouteParams {
        let mut params = crate::RouteParams::new();
        if self.is_static {
            return params;
        }

        let segments: SmallVec<[&str; INLINE_PATH_SEGMENTS]> =
            path.split('/').filter(|s| !s.is_empty()).collect();

        for &(name, idx) in &self.param_indices {
            if self.catch_all_index == Some(idx) {
                // Catch-all: join all remaining segments
                if let Some(rest) = segments.get(idx..) {
                    params.push((name, Bytes::from(rest.join("/"))));
                }
            } else if let Some(value) = segments.get(idx) {
                params.push((name, Bytes::copy_from_slice(value.as_bytes())));
            }
        }

        params
    }
}

// ============================================================================
// LRU Route Cache
// ============================================================================

/// LRU cache for route matching results.
///
/// Backed by [`lru::LruCache`], which tracks true access-recency order via an
/// intrusive doubly-linked list: `get` promotes the accessed entry to
/// most-recently-used, and eviction on `insert` always removes the actual
/// least-recently-used entry — never an arbitrary one.
///
/// Thread-safe with interior mutability via a `Mutex`. A lookup mutates
/// recency order, so — unlike a plain read-through cache — there is no
/// benefit to a `RwLock`'s shared-read mode here; every operation needs
/// exclusive access.
pub struct RouteCache {
    /// Cached routes by key, in LRU order.
    cache: Mutex<LruCache<RouteKey, CachedRoute>>,
    /// Statistics
    stats: RouteCacheStats,
}

impl RouteCache {
    /// Create new cache with default size (1024 entries).
    pub fn new() -> Self {
        Self::with_capacity(1024)
    }

    /// Create cache with specific capacity.
    ///
    /// `lru::LruCache` requires a non-zero capacity; a caller-requested `0`
    /// is clamped to the smallest usable capacity of 1 rather than panicking.
    pub fn with_capacity(max_size: usize) -> Self {
        let capacity = NonZeroUsize::new(max_size).unwrap_or(NonZeroUsize::MIN);
        Self {
            cache: Mutex::new(LruCache::new(capacity)),
            stats: RouteCacheStats::default(),
        }
    }

    /// Get a cached route.
    ///
    /// A true LRU lookup: on a hit, the entry is promoted to
    /// most-recently-used, so it survives future evictions longer than
    /// entries that haven't been accessed recently.
    #[inline]
    pub fn get(&self, key: &RouteKey) -> Option<CachedRoute> {
        let mut cache = self.cache.lock();
        let result = cache.get(key).cloned();

        if result.is_some() {
            self.stats.hits.fetch_add(1, Ordering::Relaxed);
        } else {
            self.stats.misses.fetch_add(1, Ordering::Relaxed);
        }

        result
    }

    /// Insert a route into the cache.
    ///
    /// When the cache is already full and `key` is a new entry, the true
    /// least-recently-used entry (by access order) is evicted to make room.
    pub fn insert(&self, key: RouteKey, route: CachedRoute) {
        let mut cache = self.cache.lock();

        let len_before = cache.len();
        let was_present = cache.peek(&key).is_some();

        cache.put(key, route);

        if !was_present && len_before >= cache.cap().get() {
            self.stats.evictions.fetch_add(1, Ordering::Relaxed);
        }

        self.stats.insertions.fetch_add(1, Ordering::Relaxed);
    }

    /// Clear the cache.
    pub fn clear(&self) {
        self.cache.lock().clear();
    }

    /// Get cache statistics.
    pub fn stats(&self) -> &RouteCacheStats {
        &self.stats
    }

    /// Get current cache size.
    pub fn len(&self) -> usize {
        self.cache.lock().len()
    }

    /// Check if cache is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl Default for RouteCache {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Static Route Fast Path
// ============================================================================

/// Fast path for static routes using HashMap.
///
/// Static routes (no parameters) can be matched in O(1) time using
/// a direct HashMap lookup, bypassing pattern matching entirely.
pub struct StaticRoutes {
    /// Static routes by (method, path)
    routes: HashMap<RouteKey, usize>,
    /// Statistics
    stats: StaticRouteStats,
}

impl StaticRoutes {
    /// Create new static route store.
    pub fn new() -> Self {
        Self {
            routes: HashMap::new(),
            stats: StaticRouteStats::default(),
        }
    }

    /// Add a static route.
    pub fn add(&mut self, method: HttpMethod, path: impl Into<String>, route_index: usize) {
        let key = RouteKey::new(method, path);
        self.routes.insert(key, route_index);
    }

    /// Look up a static route.
    #[inline]
    pub fn get(&self, key: &RouteKey) -> Option<usize> {
        let result = self.routes.get(key).copied();

        if result.is_some() {
            self.stats.hits.fetch_add(1, Ordering::Relaxed);
        } else {
            self.stats.misses.fetch_add(1, Ordering::Relaxed);
        }

        result
    }

    /// Check if path is static (no parameter segments).
    pub fn is_static_path(path: &str) -> bool {
        !path.contains(':') && !path.contains('*')
    }

    /// Get statistics.
    pub fn stats(&self) -> &StaticRouteStats {
        &self.stats
    }

    /// Get number of static routes.
    pub fn len(&self) -> usize {
        self.routes.len()
    }

    /// Check if empty.
    pub fn is_empty(&self) -> bool {
        self.routes.is_empty()
    }
}

impl Default for StaticRoutes {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Compiled Route Pattern
// ============================================================================

/// Pre-compiled route pattern for fast matching.
#[derive(Clone, Debug)]
pub struct CompiledRoute {
    /// Original pattern
    pub pattern: String,
    /// Parsed segments
    pub segments: Vec<RouteSegment>,
    /// Parameter indices (interned name, segment_index).
    ///
    /// Names are interned once here, at compile time, so the match path only
    /// copies a `&'static str` instead of taking the interner's global lock
    /// once per captured parameter per request.
    pub param_indices: Vec<(&'static str, usize)>,
    /// Is this a static route?
    pub is_static: bool,
    /// Has catch-all segment?
    pub has_catch_all: bool,
}

/// A segment in a route pattern.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RouteSegment {
    /// Static segment (exact match)
    Static(String),
    /// Named parameter (:name)
    Param(String),
    /// Catch-all (*path)
    CatchAll(String),
}

impl CompiledRoute {
    /// Compile a route pattern.
    pub fn compile(pattern: &str) -> Self {
        let mut segments = Vec::new();
        let mut param_indices = Vec::new();
        let mut is_static = true;
        let mut has_catch_all = false;

        for (idx, part) in pattern.split('/').filter(|s| !s.is_empty()).enumerate() {
            if let Some(name) = part.strip_prefix(':') {
                segments.push(RouteSegment::Param(name.to_string()));
                param_indices.push((crate::param_intern::intern(name), idx));
                is_static = false;
            } else if let Some(name) = part.strip_prefix('*') {
                let name = if name.is_empty() { "*" } else { name };
                segments.push(RouteSegment::CatchAll(name.to_string()));
                param_indices.push((crate::param_intern::intern(name), idx));
                is_static = false;
                has_catch_all = true;
            } else {
                segments.push(RouteSegment::Static(part.to_string()));
            }
        }

        Self {
            pattern: pattern.to_string(),
            segments,
            param_indices,
            is_static,
            has_catch_all,
        }
    }

    /// Check if a path matches this pattern.
    #[inline]
    pub fn matches(&self, path: &str) -> bool {
        let path_segments: SmallVec<[&str; INLINE_PATH_SEGMENTS]> =
            path.split('/').filter(|s| !s.is_empty()).collect();

        if !self.has_catch_all && path_segments.len() != self.segments.len() {
            return false;
        }

        if self.has_catch_all && path_segments.len() < self.segments.len() - 1 {
            return false;
        }

        for (idx, segment) in self.segments.iter().enumerate() {
            match segment {
                RouteSegment::Static(s) => {
                    if path_segments.get(idx) != Some(&s.as_str()) {
                        return false;
                    }
                }
                RouteSegment::Param(_) => {
                    if idx >= path_segments.len() {
                        return false;
                    }
                }
                RouteSegment::CatchAll(_) => {
                    // Matches remaining segments
                    break;
                }
            }
        }

        true
    }

    /// Extract parameters from a matching path.
    pub fn extract_params(&self, path: &str) -> crate::RouteParams {
        let mut params = crate::RouteParams::new();
        if self.is_static {
            return params;
        }

        let path_segments: SmallVec<[&str; INLINE_PATH_SEGMENTS]> =
            path.split('/').filter(|s| !s.is_empty()).collect();

        for &(name, idx) in &self.param_indices {
            if let Some(segment) = self.segments.get(idx) {
                match segment {
                    RouteSegment::Param(_) => {
                        if let Some(value) = path_segments.get(idx) {
                            params.push((name, Bytes::copy_from_slice(value.as_bytes())));
                        }
                    }
                    RouteSegment::CatchAll(_) => {
                        // Join remaining segments
                        let remaining: String = path_segments[idx..].join("/");
                        params.push((name, Bytes::from(remaining)));
                    }
                    _ => {}
                }
            }
        }

        params
    }
}

// ============================================================================
// Optimized Router
// ============================================================================

/// Router entry with compiled pattern.
pub struct OptimizedRoute {
    /// HTTP method
    pub method: HttpMethod,
    /// Compiled pattern
    pub compiled: CompiledRoute,
    /// Handler
    pub handler: BoxedHandler,
    /// Optional route constraints for parameter validation.
    ///
    /// Carried alongside the compiled pattern so the optimized dispatch can
    /// validate a matched route's parameters exactly as the linear
    /// [`Router`](crate::routing::Router) does, returning the same
    /// `Error::BadRequest` on failure.
    pub constraints: Option<RouteConstraints>,
}

/// Optimized router with caching and static fast path.
pub struct OptimizedRouter {
    /// All routes
    routes: Vec<OptimizedRoute>,
    /// Static route fast path
    static_routes: StaticRoutes,
    /// Route cache
    cache: RouteCache,
    /// Statistics
    stats: RouterStats,
}

impl OptimizedRouter {
    /// Create new optimized router.
    pub fn new() -> Self {
        Self {
            routes: Vec::new(),
            static_routes: StaticRoutes::new(),
            cache: RouteCache::new(),
            stats: RouterStats::default(),
        }
    }

    /// Create with specific cache size.
    pub fn with_cache_size(cache_size: usize) -> Self {
        Self {
            routes: Vec::new(),
            static_routes: StaticRoutes::new(),
            cache: RouteCache::with_capacity(cache_size),
            stats: RouterStats::default(),
        }
    }

    /// Add a route.
    pub fn add_route(
        &mut self,
        method: HttpMethod,
        path: impl Into<String>,
        handler: BoxedHandler,
    ) {
        let path = path.into();
        let compiled = CompiledRoute::compile(&path);
        let route_index = self.routes.len();

        // Add to static routes if applicable
        if compiled.is_static {
            self.static_routes.add(method.clone(), &path, route_index);
        }

        self.routes.push(OptimizedRoute {
            method,
            compiled,
            handler,
            constraints: None,
        });
    }

    /// Build an `OptimizedRouter` from a fully-populated linear [`Router`].
    ///
    /// Every [`Route`](crate::routing::Route) — method, path, handler, and
    /// optional constraints — is ingested into the optimized structures so the
    /// serve path can dispatch in O(1) for the common case while preserving the
    /// linear router's exact semantics:
    ///
    /// * Routes keep their registration order in `routes`, and the pattern-match
    ///   fallback returns the **first** matching route in that order, matching
    ///   [`Router::route`](crate::routing::Router::route).
    /// * A static route is only added to the O(1) static fast path if no
    ///   **earlier** route (of the same method) also matches that concrete path.
    ///   This preserves first-registered-wins precedence: an earlier `:param` or
    ///   `*catch_all` route that would shadow a later static path is still
    ///   selected by the fallback scan, never bypassed by the HashMap. Duplicate
    ///   static registrations are likewise resolved to the first one.
    /// * Constraints travel with each route and are validated after the match.
    pub fn from_router(router: &Router) -> Self {
        let mut opt = Self::new();

        for route in &router.routes {
            let compiled = CompiledRoute::compile(&route.path);
            let route_index = opt.routes.len();

            // Only take the O(1) static fast path when no earlier route shadows
            // this concrete path. `matches` handles static, `:param`, and
            // `*catch_all` earlier routes, so precedence is identical to the
            // linear first-match scan.
            if compiled.is_static {
                let shadowed_by_earlier = opt.routes.iter().any(|earlier| {
                    earlier.method == route.method && earlier.compiled.matches(&route.path)
                });
                if !shadowed_by_earlier {
                    opt.static_routes
                        .add(route.method.clone(), &route.path, route_index);
                }
            }

            opt.routes.push(OptimizedRoute {
                method: route.method.clone(),
                compiled,
                handler: route.handler.clone(),
                constraints: route.constraints.clone(),
            });
        }

        opt
    }

    /// Route a request with optimized matching.
    pub async fn route(&self, mut request: HttpRequest) -> Result<HttpResponse, Error> {
        self.stats.requests.fetch_add(1, Ordering::Relaxed);

        // Match on the path alone; the query is parsed on demand by
        // `HttpRequest::query`, and only if a handler asks for it.
        let path = request.path_only();

        // Unknown HTTP methods must not fall back to GET handlers.
        let Ok(method) = HttpMethod::try_from(&request.method) else {
            return Err(Error::RouteNotFound(format!("{} {}", request.method, path)));
        };

        let key = RouteKey::new(method.clone(), path);

        // 1. Try static route fast path (O(1)). Static routes carry no path
        //    params; any constraints validate against the empty map (matching
        //    the linear router, which only checks params that are present).
        if let Some(route_index) = self.static_routes.get(&key) {
            self.stats.static_hits.fetch_add(1, Ordering::Relaxed);
            let route = &self.routes[route_index];
            if let Some(constraints) = &route.constraints {
                constraints.validate(&request.path_params)?;
            }
            return route.handler.call(request).await;
        }

        // 2. Try cache (O(1)).
        if let Some(cached) = self.cache.get(&key) {
            self.stats.cache_hits.fetch_add(1, Ordering::Relaxed);
            let route = &self.routes[cached.route_index];
            let params = cached.extract_params(path);
            if let Some(constraints) = &route.constraints {
                constraints.validate(&params)?;
            }
            request.path_params = params;
            return route.handler.call(request).await;
        }

        // 3. Fall back to pattern matching. Returns the first matching route in
        //    registration order, mirroring the linear `Router::route`.
        self.stats.pattern_matches.fetch_add(1, Ordering::Relaxed);

        for (route_index, route) in self.routes.iter().enumerate() {
            if route.method != method {
                continue;
            }

            if route.compiled.matches(path) {
                // Cache the match for future requests
                let cached = CachedRoute::from_compiled(route_index, &route.compiled);
                self.cache.insert(key, cached);

                // Extract params, validate constraints, then call handler.
                let params = route.compiled.extract_params(path);
                if let Some(constraints) = &route.constraints {
                    constraints.validate(&params)?;
                }
                request.path_params = params;
                return route.handler.call(request).await;
            }
        }

        Err(Error::RouteNotFound(format!("{} {}", request.method, path)))
    }

    /// Get statistics.
    pub fn stats(&self) -> &RouterStats {
        &self.stats
    }

    /// Get cache statistics.
    pub fn cache_stats(&self) -> &RouteCacheStats {
        self.cache.stats()
    }

    /// Get static route statistics.
    pub fn static_stats(&self) -> &StaticRouteStats {
        self.static_routes.stats()
    }

    /// Clear the route cache.
    pub fn clear_cache(&self) {
        self.cache.clear();
    }

    /// Get number of routes.
    pub fn len(&self) -> usize {
        self.routes.len()
    }

    /// Check if router is empty.
    pub fn is_empty(&self) -> bool {
        self.routes.is_empty()
    }
}

impl Default for OptimizedRouter {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Statistics
// ============================================================================

/// Route cache statistics.
#[derive(Debug, Default)]
pub struct RouteCacheStats {
    hits: AtomicU64,
    misses: AtomicU64,
    insertions: AtomicU64,
    evictions: AtomicU64,
}

impl RouteCacheStats {
    /// Get cache hits.
    pub fn hits(&self) -> u64 {
        self.hits.load(Ordering::Relaxed)
    }

    /// Get cache misses.
    pub fn misses(&self) -> u64 {
        self.misses.load(Ordering::Relaxed)
    }

    /// Get insertions.
    pub fn insertions(&self) -> u64 {
        self.insertions.load(Ordering::Relaxed)
    }

    /// Get evictions.
    pub fn evictions(&self) -> u64 {
        self.evictions.load(Ordering::Relaxed)
    }

    /// Get hit ratio.
    pub fn hit_ratio(&self) -> f64 {
        let hits = self.hits() as f64;
        let total = hits + self.misses() as f64;
        if total > 0.0 { hits / total } else { 0.0 }
    }
}

/// Static route statistics.
#[derive(Debug, Default)]
pub struct StaticRouteStats {
    hits: AtomicU64,
    misses: AtomicU64,
}

impl StaticRouteStats {
    /// Get hits.
    pub fn hits(&self) -> u64 {
        self.hits.load(Ordering::Relaxed)
    }

    /// Get misses.
    pub fn misses(&self) -> u64 {
        self.misses.load(Ordering::Relaxed)
    }

    /// Get hit ratio.
    pub fn hit_ratio(&self) -> f64 {
        let hits = self.hits() as f64;
        let total = hits + self.misses() as f64;
        if total > 0.0 { hits / total } else { 0.0 }
    }
}

/// Router statistics.
#[derive(Debug, Default)]
pub struct RouterStats {
    requests: AtomicU64,
    static_hits: AtomicU64,
    cache_hits: AtomicU64,
    pattern_matches: AtomicU64,
}

impl RouterStats {
    /// Get total requests.
    pub fn requests(&self) -> u64 {
        self.requests.load(Ordering::Relaxed)
    }

    /// Get static route hits.
    pub fn static_hits(&self) -> u64 {
        self.static_hits.load(Ordering::Relaxed)
    }

    /// Get cache hits.
    pub fn cache_hits(&self) -> u64 {
        self.cache_hits.load(Ordering::Relaxed)
    }

    /// Get pattern match fallbacks.
    pub fn pattern_matches(&self) -> u64 {
        self.pattern_matches.load(Ordering::Relaxed)
    }

    /// Get optimization efficiency (static + cache hits / total).
    pub fn optimization_ratio(&self) -> f64 {
        let optimized = self.static_hits() + self.cache_hits();
        let total = self.requests();
        if total > 0 {
            optimized as f64 / total as f64
        } else {
            0.0
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::RouteParamsExt;

    #[test]
    fn test_route_key_equality() {
        let key1 = RouteKey::new(HttpMethod::GET, "/users");
        let key2 = RouteKey::new(HttpMethod::GET, "/users");
        let key3 = RouteKey::new(HttpMethod::POST, "/users");

        assert_eq!(key1, key2);
        assert_ne!(key1, key3);
    }

    #[test]
    fn test_cached_route_static() {
        let cached = CachedRoute::static_route(0);
        assert!(cached.is_static);

        let params = cached.extract_params("/users");
        assert!(params.is_empty());
    }

    #[test]
    fn test_cached_route_with_params() {
        let cached = CachedRoute::with_params(0, vec![(crate::param_intern::intern("id"), 1)]);
        assert!(!cached.is_static);

        let params = cached.extract_params("/users/123");
        assert_eq!(params.get_str("id"), Some("123"));
    }

    #[test]
    fn test_route_key_from_request_unknown_method() {
        let req = HttpRequest::new("PROPFIND", "/health".to_string());
        assert!(RouteKey::from_request(&req).is_none());

        let req = HttpRequest::new("GET", "/health?x=1".to_string());
        let key = RouteKey::from_request(&req).unwrap();
        assert_eq!(key, RouteKey::new(HttpMethod::GET, "/health"));
    }

    #[test]
    fn test_cached_route_catch_all_extracts_remaining_segments() {
        let compiled = CompiledRoute::compile("/files/*path");
        let cached = CachedRoute::from_compiled(0, &compiled);
        assert_eq!(cached.catch_all_index, Some(1));

        let params = cached.extract_params("/files/docs/readme.md");
        assert_eq!(params.get_str("path"), Some("docs/readme.md"));

        let params = cached.extract_params("/files/docs");
        assert_eq!(params.get_str("path"), Some("docs"));
    }

    #[tokio::test]
    async fn test_router_unknown_method_not_routed_to_get() {
        let mut router = OptimizedRouter::new();
        router.add_route(
            HttpMethod::GET,
            "/health",
            crate::handler::handler(|_req: HttpRequest| async {
                Ok::<_, Error>(HttpResponse::ok())
            }),
        );

        // Known method hits the static fast path.
        let ok = router
            .route(HttpRequest::new("GET", "/health".to_string()))
            .await;
        assert!(ok.is_ok());

        // Unknown method must not fall back to the GET handler.
        let err = router
            .route(HttpRequest::new("PROPFIND", "/health".to_string()))
            .await;
        assert!(matches!(err, Err(Error::RouteNotFound(_))));
    }

    #[tokio::test]
    async fn test_router_cached_catch_all_params() {
        let mut router = OptimizedRouter::new();
        router.add_route(
            HttpMethod::GET,
            "/files/*path",
            crate::handler::handler(|req: HttpRequest| async move {
                let path = req.param("path").map(str::to_owned).unwrap_or_default();
                let mut response = HttpResponse::ok();
                response.body = Bytes::from(path.into_bytes());
                Ok::<_, Error>(response)
            }),
        );

        // First request: pattern match populates the cache.
        let first = router
            .route(HttpRequest::new("GET", "/files/docs/readme.md".to_string()))
            .await
            .unwrap();
        assert_eq!(first.body, Bytes::from_static(b"docs/readme.md"));

        // Second request: served from the cache, must yield the same params.
        let second = router
            .route(HttpRequest::new("GET", "/files/docs/readme.md".to_string()))
            .await
            .unwrap();
        assert_eq!(second.body, Bytes::from_static(b"docs/readme.md"));
        assert!(router.stats().cache_hits() > 0);
    }

    #[tokio::test]
    async fn test_router_decodes_query_params() {
        let mut router = OptimizedRouter::new();
        router.add_route(
            HttpMethod::GET,
            "/search",
            crate::handler::handler(|req: HttpRequest| async move {
                let q = req.query_param("q").unwrap_or_default().to_owned();
                let mut response = HttpResponse::ok();
                response.body = Bytes::from(q.into_bytes());
                Ok::<_, Error>(response)
            }),
        );

        let response = router
            .route(HttpRequest::new(
                "GET",
                "/search?q=hello%20world".to_string(),
            ))
            .await
            .unwrap();
        assert_eq!(response.body, Bytes::from_static(b"hello world"));
    }

    #[test]
    fn test_route_cache() {
        let cache = RouteCache::new();

        let key = RouteKey::new(HttpMethod::GET, "/users");
        let route = CachedRoute::static_route(0);

        // Miss
        assert!(cache.get(&key).is_none());
        assert_eq!(cache.stats().misses(), 1);

        // Insert
        cache.insert(key.clone(), route);

        // Hit
        assert!(cache.get(&key).is_some());
        assert_eq!(cache.stats().hits(), 1);
    }

    #[test]
    fn test_static_routes() {
        let mut static_routes = StaticRoutes::new();

        static_routes.add(HttpMethod::GET, "/api/health", 0);
        static_routes.add(HttpMethod::GET, "/api/users", 1);

        let key = RouteKey::new(HttpMethod::GET, "/api/health");
        assert_eq!(static_routes.get(&key), Some(0));

        let key = RouteKey::new(HttpMethod::GET, "/api/users");
        assert_eq!(static_routes.get(&key), Some(1));

        let key = RouteKey::new(HttpMethod::GET, "/api/missing");
        assert_eq!(static_routes.get(&key), None);
    }

    #[test]
    fn test_is_static_path() {
        assert!(StaticRoutes::is_static_path("/api/health"));
        assert!(StaticRoutes::is_static_path("/users"));
        assert!(!StaticRoutes::is_static_path("/users/:id"));
        assert!(!StaticRoutes::is_static_path("/files/*path"));
    }

    #[test]
    fn test_compiled_route_static() {
        let compiled = CompiledRoute::compile("/api/health");
        assert!(compiled.is_static);
        assert!(compiled.param_indices.is_empty());
        assert!(compiled.matches("/api/health"));
        assert!(!compiled.matches("/api/users"));
    }

    #[test]
    fn test_compiled_route_with_param() {
        let compiled = CompiledRoute::compile("/users/:id");
        assert!(!compiled.is_static);
        assert_eq!(compiled.param_indices.len(), 1);

        assert!(compiled.matches("/users/123"));
        assert!(compiled.matches("/users/abc"));
        assert!(!compiled.matches("/users"));
        assert!(!compiled.matches("/users/123/extra"));

        let params = compiled.extract_params("/users/123");
        assert_eq!(params.get_str("id"), Some("123"));
    }

    #[test]
    fn test_compiled_route_multiple_params() {
        let compiled = CompiledRoute::compile("/users/:user_id/posts/:post_id");
        assert!(!compiled.is_static);
        assert_eq!(compiled.param_indices.len(), 2);

        assert!(compiled.matches("/users/123/posts/456"));

        let params = compiled.extract_params("/users/123/posts/456");
        assert_eq!(params.get_str("user_id"), Some("123"));
        assert_eq!(params.get_str("post_id"), Some("456"));
    }

    #[test]
    fn test_compiled_route_catch_all() {
        let compiled = CompiledRoute::compile("/files/*path");
        assert!(!compiled.is_static);
        assert!(compiled.has_catch_all);

        assert!(compiled.matches("/files/docs"));
        assert!(compiled.matches("/files/docs/readme.md"));

        let params = compiled.extract_params("/files/docs/readme.md");
        assert_eq!(params.get_str("path"), Some("docs/readme.md"));
    }

    #[test]
    fn test_router_stats() {
        let stats = RouterStats::default();

        stats.requests.fetch_add(100, Ordering::Relaxed);
        stats.static_hits.fetch_add(50, Ordering::Relaxed);
        stats.cache_hits.fetch_add(30, Ordering::Relaxed);
        stats.pattern_matches.fetch_add(20, Ordering::Relaxed);

        assert_eq!(stats.requests(), 100);
        assert_eq!(stats.static_hits(), 50);
        assert_eq!(stats.cache_hits(), 30);
        assert_eq!(stats.pattern_matches(), 20);
        assert!((stats.optimization_ratio() - 0.8).abs() < 0.001);
    }

    // ------------------------------------------------------------------
    // `from_router`: the compiled serve-path router must dispatch with the
    // exact semantics of the linear `Router::route`.
    // ------------------------------------------------------------------

    #[tokio::test]
    async fn test_from_router_dispatches_static_and_param() {
        let mut router = crate::routing::Router::new();
        router.add_route(crate::routing::Route::new(
            HttpMethod::GET,
            "/health",
            |_req: HttpRequest| async { Ok::<_, Error>(HttpResponse::ok()) },
        ));
        router.add_route(crate::routing::Route::new(
            HttpMethod::GET,
            "/users/:id",
            |req: HttpRequest| async move {
                let id = req.param("id").map(str::to_owned).unwrap_or_default();
                let mut r = HttpResponse::ok();
                r.body = Bytes::from(id.into_bytes());
                Ok::<_, Error>(r)
            },
        ));

        let opt = OptimizedRouter::from_router(&router);

        // Static route → O(1) static fast path.
        let resp = opt.route(HttpRequest::new("GET", "/health")).await.unwrap();
        assert_eq!(resp.status, 200);
        assert!(opt.stats().static_hits() >= 1);

        // Param route → pattern match, params extracted onto the request.
        let resp = opt
            .route(HttpRequest::new("GET", "/users/42"))
            .await
            .unwrap();
        assert_eq!(resp.body, Bytes::from_static(b"42"));
    }

    #[tokio::test]
    async fn test_from_router_catch_all() {
        let mut router = crate::routing::Router::new();
        router.add_route(crate::routing::Route::new(
            HttpMethod::GET,
            "/files/*path",
            |req: HttpRequest| async move {
                let p = req.param("path").map(str::to_owned).unwrap_or_default();
                let mut r = HttpResponse::ok();
                r.body = Bytes::from(p.into_bytes());
                Ok::<_, Error>(r)
            },
        ));

        let opt = OptimizedRouter::from_router(&router);

        // Catch-all returns the full joined remainder, not a single segment.
        let resp = opt
            .route(HttpRequest::new("GET", "/files/docs/readme.md"))
            .await
            .unwrap();
        assert_eq!(resp.body, Bytes::from_static(b"docs/readme.md"));
    }

    #[tokio::test]
    async fn test_from_router_validates_constraints() {
        let constraints =
            RouteConstraints::new().add("id", Box::new(crate::route_constraint::UIntConstraint));
        let mut router = crate::routing::Router::new();
        router.add_route(
            crate::routing::Route::new(HttpMethod::GET, "/users/:id", |_req: HttpRequest| async {
                Ok::<_, Error>(HttpResponse::ok())
            })
            .with_constraints(constraints),
        );

        let opt = OptimizedRouter::from_router(&router);

        // Valid param passes.
        let ok = opt.route(HttpRequest::new("GET", "/users/123")).await;
        assert!(ok.is_ok());

        // Invalid param → same BadRequest as the linear router.
        let err = opt.route(HttpRequest::new("GET", "/users/abc")).await;
        assert!(matches!(err, Err(Error::BadRequest(_))));

        // Cached path must re-validate constraints identically.
        let err_again = opt.route(HttpRequest::new("GET", "/users/abc")).await;
        assert!(matches!(err_again, Err(Error::BadRequest(_))));
    }

    #[tokio::test]
    async fn test_from_router_unknown_method_not_get() {
        let mut router = crate::routing::Router::new();
        router.add_route(crate::routing::Route::new(
            HttpMethod::GET,
            "/health",
            |_req: HttpRequest| async { Ok::<_, Error>(HttpResponse::ok()) },
        ));
        let opt = OptimizedRouter::from_router(&router);

        let err = opt.route(HttpRequest::new("PROPFIND", "/health")).await;
        assert!(matches!(err, Err(Error::RouteNotFound(_))));
    }

    #[tokio::test]
    async fn test_from_router_query_method_routing() {
        let mut router = crate::routing::Router::new();
        router.add_route(crate::routing::Route::new(
            HttpMethod::QUERY,
            "/search",
            |req: HttpRequest| async move {
                Ok::<_, Error>(HttpResponse::ok().with_bytes_body(req.body))
            },
        ));
        let opt = OptimizedRouter::from_router(&router);

        // QUERY carries its query in the body; routing matches on method+path.
        let mut req = HttpRequest::new("QUERY", "/search");
        req.body = Bytes::from_static(b"name=john");
        let resp = opt.route(req).await.unwrap();
        assert_eq!(resp.into_body_bytes().as_ref(), b"name=john");

        // GET to the same path must NOT reach the QUERY handler.
        let err = opt.route(HttpRequest::new("GET", "/search")).await;
        assert!(matches!(err, Err(Error::RouteNotFound(_))));
    }

    #[tokio::test]
    async fn test_from_router_preserves_registration_order_precedence() {
        // A `:param` route registered BEFORE a static route that it shadows.
        // The linear router returns the first registered match; the optimized
        // router must not let the static HashMap override that.
        let mut router = crate::routing::Router::new();
        router.add_route(crate::routing::Route::new(
            HttpMethod::GET,
            "/users/:id",
            |req: HttpRequest| async move {
                let id = req.param("id").map(str::to_owned).unwrap_or_default();
                Ok::<_, Error>(HttpResponse::ok().with_body(format!("param:{id}").into_bytes()))
            },
        ));
        router.add_route(crate::routing::Route::new(
            HttpMethod::GET,
            "/users/me",
            |_req: HttpRequest| async {
                Ok::<_, Error>(HttpResponse::ok().with_body(b"static".to_vec()))
            },
        ));

        // Reference: what the linear router does for /users/me.
        let linear = router
            .clone()
            .route(HttpRequest::new("GET", "/users/me"))
            .await
            .unwrap();

        let opt = OptimizedRouter::from_router(&router);
        let optimized = opt
            .route(HttpRequest::new("GET", "/users/me"))
            .await
            .unwrap();

        // Identical: both select the earlier-registered :id route.
        assert_eq!(optimized.body, linear.body);
        assert_eq!(optimized.body, Bytes::from_static(b"param:me"));
    }

    /// The linear `Router` and the compiled `OptimizedRouter` are independent
    /// matchers over the same route table, and they have silently drifted apart
    /// before (trailing slashes, zero-segment catch-alls). Drive a fixed matrix
    /// of targets through both and require identical outcomes.
    #[tokio::test]
    async fn test_from_router_agrees_with_linear_router_on_a_target_matrix() {
        let patterns = [
            (HttpMethod::GET, "/health"),
            (HttpMethod::GET, "/users/:id"),
            (HttpMethod::GET, "/users/:id/posts/:post"),
            (HttpMethod::GET, "/files/*path"),
            (HttpMethod::POST, "/users"),
        ];

        let mut router = crate::routing::Router::new();
        for (method, pattern) in patterns {
            // The body identifies which route answered and with which captures,
            // so a disagreement about *which* route matched is caught too, not
            // just a disagreement about whether anything matched.
            let label = pattern.to_string();
            router.add_route(crate::routing::Route::new(
                method,
                pattern,
                move |req: HttpRequest| {
                    let label = label.clone();
                    async move {
                        let mut captures: Vec<String> = req
                            .path_params
                            .iter()
                            .map(|(k, v)| format!("{k}={}", String::from_utf8_lossy(v)))
                            .collect();
                        captures.sort();
                        let body = format!("{label} {}", captures.join(","));
                        Ok::<_, Error>(HttpResponse::ok().with_body(body.into_bytes()))
                    }
                },
            ));
        }

        let opt = OptimizedRouter::from_router(&router);

        let targets = [
            ("GET", "/health"),
            ("GET", "/health/"),
            ("GET", "/health/extra"),
            ("GET", "/users"),
            ("GET", "/users/42"),
            ("GET", "/users/42/"),
            ("GET", "/users/42?x=1"),
            ("GET", "/users/42/posts/7"),
            ("GET", "/users/42/posts"),
            ("GET", "/files"),
            ("GET", "/files/"),
            ("GET", "/files/a"),
            ("GET", "/files/a/b/c.txt"),
            ("GET", "/"),
            ("GET", "/nope"),
            ("POST", "/users"),
            ("POST", "/users/42"),
            ("POST", "/health"),
            ("PROPFIND", "/health"),
        ];

        for (method, target) in targets {
            let linear = router.route(HttpRequest::new(method, target)).await;
            let compiled = opt.route(HttpRequest::new(method, target)).await;
            match (linear, compiled) {
                (Ok(a), Ok(b)) => assert_eq!(a.body, b.body, "{method} {target}"),
                (Err(_), Err(_)) => {}
                (a, b) => panic!(
                    "{method} {target}: linear matched={}, compiled matched={}",
                    a.is_ok(),
                    b.is_ok()
                ),
            }
        }
    }

    #[tokio::test]
    async fn test_from_router_decodes_query_params() {
        let mut router = crate::routing::Router::new();
        router.add_route(crate::routing::Route::new(
            HttpMethod::GET,
            "/search",
            |req: HttpRequest| async move {
                let q = req.query_param("q").unwrap_or_default().to_owned();
                Ok::<_, Error>(HttpResponse::ok().with_body(q.into_bytes()))
            },
        ));
        let opt = OptimizedRouter::from_router(&router);

        let resp = opt
            .route(HttpRequest::new("GET", "/search?q=hello%20world"))
            .await
            .unwrap();
        assert_eq!(resp.body, Bytes::from_static(b"hello world"));
    }

    #[test]
    fn test_from_router_skips_shadowed_static_fast_path() {
        // `/users/:id` (index 0) shadows the later static `/users/me` (index 1),
        // so `/users/me` must NOT be registered in the static fast path.
        let mut router = crate::routing::Router::new();
        router.add_route(crate::routing::Route::new(
            HttpMethod::GET,
            "/users/:id",
            |_req: HttpRequest| async { Ok::<_, Error>(HttpResponse::ok()) },
        ));
        router.add_route(crate::routing::Route::new(
            HttpMethod::GET,
            "/users/me",
            |_req: HttpRequest| async { Ok::<_, Error>(HttpResponse::ok()) },
        ));
        let opt = OptimizedRouter::from_router(&router);
        // The shadowed static route stays out of the O(1) map.
        assert!(
            opt.static_routes
                .get(&RouteKey::new(HttpMethod::GET, "/users/me"))
                .is_none()
        );

        // A non-shadowed static route DOES get the fast path.
        let mut router2 = crate::routing::Router::new();
        router2.add_route(crate::routing::Route::new(
            HttpMethod::GET,
            "/health",
            |_req: HttpRequest| async { Ok::<_, Error>(HttpResponse::ok()) },
        ));
        let opt2 = OptimizedRouter::from_router(&router2);
        assert!(
            opt2.static_routes
                .get(&RouteKey::new(HttpMethod::GET, "/health"))
                .is_some()
        );
    }

    #[test]
    fn test_route_cache_eviction() {
        let cache = RouteCache::with_capacity(10);

        // Fill cache
        for i in 0..15 {
            let key = RouteKey::new(HttpMethod::GET, format!("/route/{}", i));
            cache.insert(key, CachedRoute::static_route(i));
        }

        // Should have evicted some entries
        assert!(cache.len() <= 10);
        assert!(cache.stats().evictions() > 0);
    }

    /// Regression: eviction must follow true access recency, not
    /// `HashMap`'s unspecified iteration order. A cache with random
    /// eviction would only pass this by chance (roughly 1-in-N per key
    /// where N is the capacity); a real LRU passes it deterministically
    /// every time.
    #[test]
    fn test_route_cache_lru_eviction_respects_recency() {
        let cache = RouteCache::with_capacity(3);

        let key0 = RouteKey::new(HttpMethod::GET, "/route/0");
        let key1 = RouteKey::new(HttpMethod::GET, "/route/1");
        let key2 = RouteKey::new(HttpMethod::GET, "/route/2");
        let key3 = RouteKey::new(HttpMethod::GET, "/route/3");

        // Fill the cache to capacity, oldest to newest: key0, key1, key2.
        cache.insert(key0.clone(), CachedRoute::static_route(0));
        cache.insert(key1.clone(), CachedRoute::static_route(1));
        cache.insert(key2.clone(), CachedRoute::static_route(2));

        // Refresh key0 (the oldest entry): a real LRU promotes it to
        // most-recently-used, so it must survive the next eviction even
        // though key1 and key2 were inserted after it.
        assert!(cache.get(&key0).is_some());

        // Cache is full; inserting a new key must evict the true LRU entry
        // — key1, the oldest entry that was never re-accessed — not an
        // arbitrary one.
        cache.insert(key3.clone(), CachedRoute::static_route(3));

        assert!(
            cache.get(&key0).is_some(),
            "recently-accessed entry must survive eviction"
        );
        assert!(
            cache.get(&key1).is_none(),
            "genuinely-unaccessed entry must be evicted"
        );
        assert!(cache.get(&key2).is_some());
        assert!(cache.get(&key3).is_some());
        assert_eq!(cache.len(), 3);
    }
}