tako-rs-core 2.0.0

Internal core implementation crate for tako-rs. Use the `tako-rs` umbrella crate instead.
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
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
//! HTTP request routing and dispatch functionality.
//!
//! This module provides the core `Router` struct that manages HTTP routes, middleware chains,
//! and request dispatching. The router supports dynamic path parameters, middleware composition,
//! plugin integration, and global state management. It handles matching incoming requests to
//! registered routes and executing the appropriate handlers through middleware pipelines.
//!
//! # Examples
//!
//! ```rust
//! use tako::{router::Router, Method, responder::Responder, types::Request};
//!
//! async fn hello(_req: Request) -> impl Responder {
//!     "Hello, World!"
//! }
//!
//! async fn user_handler(_req: Request) -> impl Responder {
//!     "User profile"
//! }
//!
//! let mut router = Router::new();
//! router.route(Method::GET, "/", hello);
//! router.route(Method::GET, "/users/{id}", user_handler);
//!
//! // Add global middleware
//! router.middleware(|req, next| async move {
//!     println!("Processing request to: {}", req.uri());
//!     next.run(req).await
//! });
//! ```

use std::sync::Arc;
use std::sync::Weak;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;

use arc_swap::ArcSwap;
use http::Method;
use http::StatusCode;
use smallvec::SmallVec;

use crate::body::TakoBody;
use crate::extractors::params::PathParams;
use crate::handler::BoxHandler;
use crate::handler::Handler;
use crate::middleware::Next;
#[cfg(feature = "plugins")]
use crate::plugins::TakoPlugin;
use crate::responder::Responder;
use crate::route::Route;
use crate::router_state::RouterState;
#[cfg(feature = "signals")]
use crate::signals::Signal;
#[cfg(feature = "signals")]
use crate::signals::SignalArbiter;
#[cfg(feature = "signals")]
use crate::signals::ids;
use crate::state::set_state;
use crate::types::BoxMiddleware;
use crate::types::Request;
use crate::types::Response;

/// Builds an empty-body response with the given status code without going
/// through `http::response::Builder`. The builder API returns `Result` to
/// surface invalid header values, but for the router's hot-path 404 / 405 /
/// 408 / 505 responses we have no headers to fail on, so the result is
/// statically infallible. This helper avoids `.expect("valid …")` calls in
/// the dispatch path.
#[inline]
fn empty_status_response(status: StatusCode) -> Response {
  let mut resp = http::Response::new(TakoBody::empty());
  *resp.status_mut() = status;
  resp
}

/// Type alias for a global error handler function.
///
/// Called when a response has a server error status (5xx). Receives the original
/// response and can transform it (e.g., to return JSON errors instead of plain text).
pub type ErrorHandler = Arc<dyn Fn(Response) -> Response + Send + Sync + 'static>;

/// HTTP router for managing routes, middleware, and request dispatching.
///
/// The `Router` is the central component for routing HTTP requests to appropriate
/// handlers. It supports dynamic path parameters, middleware chains, plugin integration,
/// and global state management. Routes are matched based on HTTP method and path pattern,
/// with support for trailing slash redirection and parameter extraction.
///
/// # Examples
///
/// ```rust
/// use tako::{router::Router, Method, responder::Responder, types::Request};
///
/// async fn index(_req: Request) -> impl Responder {
///     "Welcome to the home page!"
/// }
///
/// async fn user_profile(_req: Request) -> impl Responder {
///     "User profile page"
/// }
///
/// let mut router = Router::new();
/// router.route(Method::GET, "/", index);
/// router.route(Method::GET, "/users/{id}", user_profile);
/// router.state("app_name", "MyApp".to_string());
/// ```
#[doc(alias = "router")]
pub struct Router {
  /// Map of registered routes keyed by method (O(1) array lookup).
  inner: MethodMap<matchit::Router<Arc<Route>>>,
  /// An easy-to-iterate index of the same routes so we can access the `Arc<Route>` values.
  ///
  /// Holds `Weak<Route>` (not `Arc`) so an external holder of an `Arc<Route>`
  /// returned from [`Router::route`] can release it without keeping the router
  /// graph alive past its useful lifetime. All current code paths that store a
  /// `Weak` here also store the matching `Arc` in `inner`, so upgrades always
  /// succeed today; [`Router::compact_routes`] sweeps dangling weaks lazily so
  /// any future API that removes from `inner` does not cause this index to
  /// grow without bound.
  routes: MethodMap<Vec<Weak<Route>>>,
  /// Optional path prefix prepended to every `route()` call while it is set.
  /// Used by [`Router::mount_all_into`] and [`Router::scope`] (see v2 roadmap).
  /// Only consulted at registration time — zero cost on the dispatch hot path.
  pending_prefix: Option<String>,
  /// Global middleware chain applied to all routes.
  pub(crate) middlewares: ArcSwap<Vec<BoxMiddleware>>,
  /// Fast check: true when global middleware is registered (avoids `ArcSwap` load on hot path).
  has_global_middleware: AtomicBool,
  /// Optional fallback handler executed when no route matches.
  fallback: Option<BoxHandler>,
  /// Registered plugins for extending functionality.
  #[cfg(feature = "plugins")]
  plugins: Vec<Box<dyn TakoPlugin>>,
  /// Flag to ensure plugins are initialized only once.
  #[cfg(feature = "plugins")]
  plugins_initialized: AtomicBool,
  /// Signal arbiter for in-process event emission and handling.
  #[cfg(feature = "signals")]
  signals: SignalArbiter,
  /// Default timeout for all routes.
  pub(crate) timeout: Option<Duration>,
  /// Fallback handler executed when a request times out.
  timeout_fallback: Option<BoxHandler>,
  /// Global error handler for 5xx responses.
  error_handler: Option<ErrorHandler>,
  /// Global error handler for 4xx responses (opt-in; runs after dispatch).
  client_error_handler: Option<ErrorHandler>,
  /// Per-router typed state populated via [`Router::with_state`].
  /// `Arc` is shared with every dispatched request via the request extension
  /// so the `State<T>` extractor can read instance-local values.
  router_state: Arc<RouterState>,
  /// Fast-path flag: when `false`, dispatch skips the per-request Arc clone +
  /// extension insert that wires `router_state` into requests.
  has_router_state: AtomicBool,
}

impl Default for Router {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

impl Router {
  /// Creates a new, empty router.
  #[must_use]
  pub fn new() -> Self {
    let router = Self {
      inner: MethodMap::new(),
      routes: MethodMap::new(),
      pending_prefix: None,
      middlewares: ArcSwap::new(Arc::default()),
      has_global_middleware: AtomicBool::new(false),
      fallback: None,
      #[cfg(feature = "plugins")]
      plugins: Vec::new(),
      #[cfg(feature = "plugins")]
      plugins_initialized: AtomicBool::new(false),
      #[cfg(feature = "signals")]
      signals: SignalArbiter::new(),
      timeout: None,
      timeout_fallback: None,
      error_handler: None,
      client_error_handler: None,
      router_state: Arc::new(RouterState::new()),
      has_router_state: AtomicBool::new(false),
    };

    #[cfg(feature = "signals")]
    {
      // Atomic first-write: under concurrent `Router::new` calls the
      // previous `get_state.is_none() → set_state` pair was TOCTOU and let
      // two threads each install their own arbiter. `get_or_init_state`
      // resolves both to the same `Arc<SignalArbiter>`.
      let arbiter_clone = router.signals.clone();
      let _ = crate::state::get_or_init_state::<SignalArbiter, _>(move || arbiter_clone);
    }

    router
  }

  /// Registers a new route with the router.
  ///
  /// Associates an HTTP method and path pattern with a handler function. The path
  /// can contain dynamic segments using curly braces (e.g., `/users/{id}`), which
  /// are extracted as parameters during request processing.
  ///
  /// # Panics
  ///
  /// Panics if a route with the same method and path pattern is already registered.
  ///
  /// # Examples
  ///
  /// ```rust
  /// use tako::{router::Router, Method, responder::Responder, types::Request};
  ///
  /// async fn get_user(_req: Request) -> impl Responder {
  ///     "User details"
  /// }
  ///
  /// async fn create_user(_req: Request) -> impl Responder {
  ///     "User created"
  /// }
  ///
  /// let mut router = Router::new();
  /// router.route(Method::GET, "/users/{id}", get_user);
  /// router.route(Method::POST, "/users", create_user);
  /// router.route(Method::GET, "/health", |_req| async { "OK" });
  /// ```
  pub fn route<H, T>(&mut self, method: Method, path: &str, handler: H) -> Arc<Route>
  where
    H: Handler<T> + Clone + 'static,
  {
    let final_path = self.apply_pending_prefix(path);
    let route = Arc::new(Route::new(
      final_path.clone(),
      method.clone(),
      BoxHandler::new::<H, T>(handler),
      None,
    ));

    if let Err(err) = self
      .inner
      .get_or_default_mut(&method)
      .insert(final_path, route.clone())
    {
      panic!("Failed to register route: {err}");
    }

    self
      .routes
      .get_or_default_mut(&method)
      .push(Arc::downgrade(&route));

    route
  }

  /// Returns `path` with the active `pending_prefix` (if any) prepended.
  /// Cold path; only runs at registration time.
  fn apply_pending_prefix(&self, path: &str) -> String {
    match &self.pending_prefix {
      None => path.to_string(),
      Some(prefix) => {
        let prefix = prefix.trim_end_matches('/');
        if path.is_empty() || path == "/" {
          if prefix.is_empty() {
            "/".to_string()
          } else {
            prefix.to_string()
          }
        } else if path.starts_with('/') {
          let mut s = String::with_capacity(prefix.len() + path.len());
          s.push_str(prefix);
          s.push_str(path);
          s
        } else {
          let mut s = String::with_capacity(prefix.len() + 1 + path.len());
          s.push_str(prefix);
          s.push('/');
          s.push_str(path);
          s
        }
      }
    }
  }

  /// Registers a `GET` route. Shorthand for [`Router::route`] with [`Method::GET`].
  #[inline]
  pub fn get<H, T>(&mut self, path: &str, handler: H) -> Arc<Route>
  where
    H: Handler<T> + Clone + 'static,
  {
    self.route(Method::GET, path, handler)
  }

  /// Registers a `POST` route. Shorthand for [`Router::route`] with [`Method::POST`].
  #[inline]
  pub fn post<H, T>(&mut self, path: &str, handler: H) -> Arc<Route>
  where
    H: Handler<T> + Clone + 'static,
  {
    self.route(Method::POST, path, handler)
  }

  /// Registers a `PUT` route. Shorthand for [`Router::route`] with [`Method::PUT`].
  #[inline]
  pub fn put<H, T>(&mut self, path: &str, handler: H) -> Arc<Route>
  where
    H: Handler<T> + Clone + 'static,
  {
    self.route(Method::PUT, path, handler)
  }

  /// Registers a `DELETE` route. Shorthand for [`Router::route`] with [`Method::DELETE`].
  #[inline]
  pub fn delete<H, T>(&mut self, path: &str, handler: H) -> Arc<Route>
  where
    H: Handler<T> + Clone + 'static,
  {
    self.route(Method::DELETE, path, handler)
  }

  /// Registers a `PATCH` route. Shorthand for [`Router::route`] with [`Method::PATCH`].
  #[inline]
  pub fn patch<H, T>(&mut self, path: &str, handler: H) -> Arc<Route>
  where
    H: Handler<T> + Clone + 'static,
  {
    self.route(Method::PATCH, path, handler)
  }

  /// Registers a `HEAD` route. Shorthand for [`Router::route`] with [`Method::HEAD`].
  #[inline]
  pub fn head<H, T>(&mut self, path: &str, handler: H) -> Arc<Route>
  where
    H: Handler<T> + Clone + 'static,
  {
    self.route(Method::HEAD, path, handler)
  }

  /// Registers an `OPTIONS` route. Shorthand for [`Router::route`] with [`Method::OPTIONS`].
  #[inline]
  pub fn options<H, T>(&mut self, path: &str, handler: H) -> Arc<Route>
  where
    H: Handler<T> + Clone + 'static,
  {
    self.route(Method::OPTIONS, path, handler)
  }

  /// Registers every route declared via the `#[tako::route]` / `#[tako::get]`
  /// (and friends) attribute macros into this router.
  ///
  /// Each macro contributes a thunk into the global [`TAKO_ROUTES`] slice at
  /// link time; this method walks the slice and invokes each thunk against
  /// `self`, which calls [`Router::route`] under the hood. Routes are
  /// registered in the order the linker emits them — typically the order they
  /// appear within a translation unit, but unspecified across crates. If two
  /// thunks register the same `(method, path)` pair, the second call will
  /// panic, matching the behavior of [`Router::route`].
  ///
  /// # Why `linkme` and not explicit registration
  ///
  /// We keep the `linkme` distributed-slice strategy on purpose. The
  /// alternative — an explicit `register_routes!(my_crate::routes)` invocation
  /// per crate — was considered and rejected because:
  ///
  /// * Adding a handler would require touching three places (the handler
  ///   itself, the per-crate registration list, and the call site that
  ///   imports it) instead of one. The macro authoring story is the main
  ///   reason teams pick attribute routing in the first place.
  /// * Cross-crate path collisions panic at startup either way; explicit
  ///   registration does not buy any extra safety.
  /// * Link-order non-determinism only matters when two routes share a
  ///   `(method, path)` pair — that is already a hard failure and a CI test
  ///   catches it deterministically.
  /// * Prefix grouping is already covered by [`Router::mount_all_into`], so
  ///   "I want all my routes under `/api`" does not require explicit
  ///   registration.
  ///
  /// Callers that need stable, deterministic ordering should call
  /// [`Router::route`] directly.
  ///
  /// # Examples
  ///
  /// ```ignore
  /// use tako::{get, router::Router};
  ///
  /// #[get("/health")]
  /// async fn health() -> impl tako::responder::Responder { "ok" }
  ///
  /// let mut router = Router::new();
  /// router.mount_all();
  /// ```
  pub fn mount_all(&mut self) -> &mut Self {
    for register in TAKO_ROUTES {
      register(self);
    }
    self
  }

  /// Like [`Router::mount_all`] but registers every macro-declared route under
  /// the given path prefix. The prefix is normalized (trailing `/` stripped),
  /// then prepended to each registered path. Useful when you want, e.g., all
  /// `#[get("/users")]` declarations to live under `/api`.
  ///
  /// Ordering across crates remains the linker's choice (see
  /// [`Router::mount_all`] for details).
  ///
  /// # Examples
  ///
  /// ```ignore
  /// let mut router = Router::new();
  /// router.mount_all_into("/api"); // /users → /api/users, /health → /api/health
  /// ```
  pub fn mount_all_into(&mut self, prefix: &str) -> &mut Self {
    let saved = self.pending_prefix.take();
    self.pending_prefix = Some(prefix.to_string());
    // Same panic-restore guard as `scope`: a route conflict from any
    // registered `#[tako_route]` macro now resets `pending_prefix`.
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
      for register in TAKO_ROUTES {
        register(self);
      }
    }));
    self.pending_prefix = saved;
    if let Err(payload) = result {
      std::panic::resume_unwind(payload);
    }
    self
  }

  /// Registers a group of routes under a shared path prefix.
  ///
  /// The closure receives `self` with the prefix active, so any `route()` /
  /// `get()` / `post()` etc. calls inside register the routes with the prefix
  /// prepended. Prefixes nest: a `scope("/v1", |r| r.scope("/users", …))`
  /// produces routes under `/v1/users`. Cold path; no dispatch impact.
  ///
  /// # Examples
  ///
  /// ```rust
  /// use tako::router::Router;
  /// use tako::responder::Responder;
  ///
  /// async fn list_users() -> impl Responder { "users" }
  /// async fn create_user() -> impl Responder { "created" }
  ///
  /// let mut router = Router::new();
  /// router.scope("/api/v1", |r| {
  ///     r.get("/users", list_users);
  ///     r.post("/users", create_user);
  /// });
  /// ```
  pub fn scope<F>(&mut self, prefix: &str, build: F) -> &mut Self
  where
    F: FnOnce(&mut Router),
  {
    let saved = self.pending_prefix.take();
    let new_prefix = match &saved {
      Some(parent) => {
        let parent = parent.trim_end_matches('/');
        if prefix.starts_with('/') {
          format!("{parent}{prefix}")
        } else {
          format!("{parent}/{prefix}")
        }
      }
      None => prefix.to_string(),
    };
    self.pending_prefix = Some(new_prefix);
    // Panic-safe restore of `pending_prefix`. A route-conflict panic in the
    // user-supplied `build` closure used to leave the temporary nested
    // prefix in place, permanently poisoning subsequent route registrations
    // on the same builder.
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| build(self)));
    self.pending_prefix = saved;
    if let Err(payload) = result {
      std::panic::resume_unwind(payload);
    }
    self
  }

  /// Mounts every route from a child router under the given path prefix.
  ///
  /// Unlike [`Router::merge`], `nest` builds **new** `Arc<Route>` instances for
  /// each child route via `Route::cloned_with_path` — so re-nesting the same
  /// child cannot double-stack its global middleware onto the same shared
  /// `Arc<Route>`. The child router's global middleware chain is prepended to
  /// each newly-registered route's middleware chain (so child globals run
  /// before child-route middleware at dispatch time).
  ///
  /// Caveats:
  /// - Route-level plugins on the child are **not** carried over.
  /// - The child's fallback / error handlers are **not** inherited.
  ///
  /// # Panics
  ///
  /// Panics at registration time if mounting the child would conflict with a
  /// route already present on `self` (same method + same prefixed path).
  /// Mirrors the behavior of [`Router::route`] — route registration is a
  /// startup-time operation and conflicts are configuration bugs, not
  /// runtime conditions.
  ///
  /// # Examples
  ///
  /// ```rust
  /// use tako::router::Router;
  /// use tako::responder::Responder;
  ///
  /// async fn list_users() -> impl Responder { "users" }
  ///
  /// let mut api = Router::new();
  /// api.get("/users", list_users);
  ///
  /// let mut root = Router::new();
  /// root.nest("/api/v1", api); // /users → /api/v1/users
  /// ```
  pub fn nest(&mut self, prefix: &str, child: Router) -> &mut Self {
    let upstream_globals = child.middlewares.load_full();

    for (method, weak_vec) in child.routes.iter() {
      for weak in weak_vec {
        let Some(child_route) = weak.upgrade() else {
          continue;
        };

        let combined = combine_prefix_path(prefix, &child_route.path);
        let new_path = self.apply_pending_prefix(&combined);

        let new_route = child_route.cloned_with_path(new_path.clone());

        if !upstream_globals.is_empty() {
          let existing = new_route.middlewares.load_full();
          let mut merged = Vec::with_capacity(upstream_globals.len() + existing.len());
          merged.extend(upstream_globals.iter().cloned());
          merged.extend(existing.iter().cloned());
          new_route.has_middleware.store(true, Ordering::Release);
          new_route.middlewares.store(Arc::new(merged));
        }

        if let Err(err) = self
          .inner
          .get_or_default_mut(&method)
          .insert(new_path, new_route.clone())
        {
          panic!("Failed to nest route: {err}");
        }
        self
          .routes
          .get_or_default_mut(&method)
          .push(Arc::downgrade(&new_route));
      }
    }

    #[cfg(feature = "signals")]
    self.signals.merge_from(&child.signals);

    self
  }

  /// Registers a route with trailing slash redirection enabled.
  ///
  /// When TSR is enabled, requests to paths with or without trailing slashes
  /// are automatically redirected to the canonical version. This helps maintain
  /// consistent URLs and prevents duplicate content issues.
  ///
  /// # Panics
  ///
  /// - Panics if called with the root path (`"/"`) since TSR is not applicable.
  /// - Panics if a route with the same method and path pattern is already registered.
  ///
  /// # Examples
  ///
  /// ```rust
  /// use tako::{router::Router, Method, responder::Responder, types::Request};
  ///
  /// async fn api_handler(_req: Request) -> impl Responder {
  ///     "API endpoint"
  /// }
  ///
  /// let mut router = Router::new();
  /// // Both "/api" and "/api/" will redirect to the canonical form
  /// router.route_with_tsr(Method::GET, "/api", api_handler);
  /// ```
  pub fn route_with_tsr<H, T>(&mut self, method: Method, path: &str, handler: H) -> Arc<Route>
  where
    H: Handler<T> + Clone + 'static,
  {
    assert!(path != "/", "Cannot route with TSR for root path");

    let final_path = self.apply_pending_prefix(path);
    let route = Arc::new(Route::new(
      final_path.clone(),
      method.clone(),
      BoxHandler::new::<H, T>(handler),
      Some(true),
    ));

    if let Err(err) = self
      .inner
      .get_or_default_mut(&method)
      .insert(final_path, route.clone())
    {
      panic!("Failed to register route: {err}");
    }

    self
      .routes
      .get_or_default_mut(&method)
      .push(Arc::downgrade(&route));

    route
  }

  /// Executes the given endpoint through the global middleware chain.
  ///
  /// This helper is used for cases like TSR redirects and default 404 responses,
  /// ensuring that router-level middleware (e.g., CORS) always runs.
  async fn run_with_global_middlewares_for_endpoint(
    &self,
    req: Request,
    endpoint: BoxHandler,
  ) -> Response {
    if self.has_global_middleware.load(Ordering::Acquire) {
      Next {
        global_middlewares: self.middlewares.load_full(),
        route_middlewares: Arc::default(),
        index: 0,
        endpoint,
      }
      .run(req)
      .await
    } else {
      endpoint.call(req).await
    }
  }

  /// Executes the middleware chain with an optional timeout.
  ///
  /// If a timeout is specified and exceeded, the timeout fallback handler
  /// is invoked or a default 408 Request Timeout response is returned.
  async fn run_with_timeout(
    &self,
    req: Request,
    next: Next,
    timeout_duration: Option<Duration>,
  ) -> Response {
    match timeout_duration {
      Some(duration) => {
        #[cfg(not(feature = "compio"))]
        {
          match tokio::time::timeout(duration, next.run(req)).await {
            Ok(response) => response,
            Err(_elapsed) => self.handle_timeout().await,
          }
        }
        #[cfg(feature = "compio")]
        {
          let sleep = std::pin::pin!(compio::time::sleep(duration));
          let work = std::pin::pin!(next.run(req));
          match futures_util::future::select(work, sleep).await {
            futures_util::future::Either::Left((response, _)) => response,
            futures_util::future::Either::Right(((), _)) => self.handle_timeout().await,
          }
        }
      }
      None => next.run(req).await,
    }
  }

  /// Returns the timeout response using the fallback handler or a default 408.
  async fn handle_timeout(&self) -> Response {
    if let Some(handler) = &self.timeout_fallback {
      handler.call(Request::default()).await
    } else {
      empty_status_response(StatusCode::REQUEST_TIMEOUT)
    }
  }

  /// Dispatches an incoming request to the appropriate route handler.
  #[inline]
  pub async fn dispatch(&self, mut req: Request) -> Response {
    // Per-router state: only inject when at least one `with_state` was called.
    // The atomic load is monomorphic and cheap; the Arc clone (atomic incref)
    // only happens for routers that actually use instance-local state.
    if self.has_router_state.load(Ordering::Acquire) {
      req.extensions_mut().insert(Arc::clone(&self.router_state));
    }

    // App-level request signal — emitted here so every transport gets it for
    // free without duplicating the boilerplate. The cost is a single string
    // formatting pair per request and is gated to the `signals` feature.
    #[cfg(feature = "signals")]
    let (req_method_str, req_path_str) = (req.method().to_string(), req.uri().path().to_string());
    #[cfg(feature = "signals")]
    {
      SignalArbiter::emit_app(
        Signal::with_capacity(ids::REQUEST_STARTED, 2)
          .meta("method", req_method_str.clone())
          .meta("path", req_path_str.clone()),
      )
      .await;
    }

    // Phase 1: Route lookup using a borrowed path — no String allocation on the
    // hot path. The block scope ensures all borrows on `req` are released before
    // we need to mutate it.
    let route_match = {
      if let Some(method_router) = self.inner.get(req.method())
        && let Ok(matched) = method_router.at(req.uri().path())
      {
        let route = Arc::clone(matched.value);
        let mut it = matched.params.iter();
        let first = it.next();
        let params = first.map(|(fk, fv)| {
          let mut p = SmallVec::<[(String, String); 4]>::new();
          p.push((fk.to_string(), fv.to_string()));
          for (k, v) in it {
            p.push((k.to_string(), v.to_string()));
          }
          PathParams(p)
        });
        Some((route, params))
      } else {
        None
      }
    };

    // Phase 2: Dispatch — `req` is no longer borrowed, safe to mutate.
    let response = if let Some((route, params)) = route_match {
      // Protocol guard: short-circuit dispatch *but fall through* to the shared
      // completion tail (error-handler + REQUEST_COMPLETED signal). Returning
      // here would leak the in-flight signal pair (REQUEST_STARTED already
      // emitted above without a matching REQUEST_COMPLETED).
      if let Some(res) = Self::enforce_protocol_guard(&route, &req) {
        res
      } else {
        #[cfg(feature = "signals")]
        let route_signals = route.signal_arbiter();

        // Initialize route-level plugins on first request
        #[cfg(feature = "plugins")]
        route.setup_plugins_once();

        // Inject route-level SIMD JSON config into request extensions
        if let Some(mode) = route.get_simd_json_mode() {
          req.extensions_mut().insert(mode);
        }

        if let Some(params) = params {
          req.extensions_mut().insert(params);
        }

        // Inject the matched route template (e.g. `/users/{id}`) so handlers
        // and middleware can label metrics/logs by the routing key, not the
        // concrete URI.
        req
          .extensions_mut()
          .insert(crate::router_state::MatchedPath(route.path.clone()));

        // Determine effective timeout: route-level overrides router-level
        let effective_timeout = route.get_timeout().or(self.timeout);

        // Fast atomic check: skip ArcSwap loads entirely when no middleware is registered.
        let needs_chain = self.has_global_middleware.load(Ordering::Acquire)
          || route.has_middleware.load(Ordering::Acquire);

        #[cfg(feature = "signals")]
        {
          // Reuse the strings already formatted for REQUEST_STARTED instead of
          // re-allocating per request on the hot path. Cheap `String::clone` is
          // a single Vec dup; route-level signals consume the clones for the
          // STARTED emission and the final move into ROUTE_REQUEST_COMPLETED.
          let method_str = req_method_str.clone();
          let path_str = req_path_str.clone();
          let route_template = route.path.clone();

          route_signals
            .emit(
              Signal::with_capacity(ids::ROUTE_REQUEST_STARTED, 3)
                .meta("method", method_str.clone())
                .meta("path", path_str.clone())
                .meta("route", route_template.clone()),
            )
            .await;

          let response = if !needs_chain && effective_timeout.is_none() {
            route.handler.call(req).await
          } else {
            let next = Next {
              global_middlewares: self.middlewares.load_full(),
              route_middlewares: route.middlewares.load_full(),
              index: 0,
              endpoint: route.handler.clone(),
            };
            self.run_with_timeout(req, next, effective_timeout).await
          };

          route_signals
            .emit(
              Signal::with_capacity(ids::ROUTE_REQUEST_COMPLETED, 4)
                .meta("method", method_str)
                .meta("path", path_str)
                .meta("route", route_template)
                .meta("status", response.status().as_u16().to_string()),
            )
            .await;

          response
        }

        #[cfg(not(feature = "signals"))]
        {
          if !needs_chain && effective_timeout.is_none() {
            route.handler.call(req).await
          } else {
            let next = Next {
              global_middlewares: self.middlewares.load_full(),
              route_middlewares: route.middlewares.load_full(),
              index: 0,
              endpoint: route.handler.clone(),
            };
            self.run_with_timeout(req, next, effective_timeout).await
          }
        }
      }
    } else {
      // Cold path: no direct match — try TSR redirect / 405 / fallback.
      // String allocation is acceptable here.
      let tsr_path = {
        let p = req.uri().path();
        if p.ends_with('/') {
          p.trim_end_matches('/').to_string()
        } else {
          format!("{p}/")
        }
      };

      if let Some(method_router) = self.inner.get(req.method())
        && let Ok(matched) = method_router.at(&tsr_path)
        && matched.value.tsr
      {
        let handler = move |_req: Request| {
          let tsr_path = tsr_path.clone();
          async move {
            // `tsr_path` is reconstructed from registered route segments and
            // the incoming URI path. It can technically contain bytes that
            // are invalid in an HTTP header value (CR/LF/NUL) if the request
            // path is crafted maliciously — in that case fall back to a
            // bare 308 without a `Location` header rather than panicking.
            match http::HeaderValue::from_str(&tsr_path) {
              Ok(loc) => {
                let mut resp = empty_status_response(StatusCode::TEMPORARY_REDIRECT);
                resp.headers_mut().insert(http::header::LOCATION, loc);
                resp
              }
              Err(_) => empty_status_response(StatusCode::TEMPORARY_REDIRECT),
            }
          }
        };

        self
          .run_with_global_middlewares_for_endpoint(req, BoxHandler::new::<_, (Request,)>(handler))
          .await
      } else {
        // Method-mismatch detection: if the same path is registered for any
        // *other* method, RFC 9110 mandates 405 with an `Allow` header rather
        // than 404. This is the cold path; iterating the 9 standard methods
        // is cheap.
        let allowed = self.collect_allowed_methods(req.uri().path());
        if !allowed.is_empty() {
          let allow_value = join_methods(&allowed);
          let handler = move |_req: Request| {
            let allow_value = allow_value.clone();
            async move {
              // `allow_value` is built from `Method::as_str()` for the
              // registered methods, so it only contains ASCII method tokens
              // — `HeaderValue::from_str` is statically infallible. Use the
              // fallible API and ignore the impossible error rather than
              // panicking.
              let mut resp = empty_status_response(StatusCode::METHOD_NOT_ALLOWED);
              if let Ok(v) = http::HeaderValue::from_str(&allow_value) {
                resp.headers_mut().insert(http::header::ALLOW, v);
              }
              resp
            }
          };
          self
            .run_with_global_middlewares_for_endpoint(
              req,
              BoxHandler::new::<_, (Request,)>(handler),
            )
            .await
        } else if let Some(handler) = &self.fallback {
          self
            .run_with_global_middlewares_for_endpoint(req, handler.clone())
            .await
        } else {
          let handler = |_req: Request| async { empty_status_response(StatusCode::NOT_FOUND) };

          self
            .run_with_global_middlewares_for_endpoint(
              req,
              BoxHandler::new::<_, (Request,)>(handler),
            )
            .await
        }
      }
    };

    let response = self.maybe_apply_error_handler(response);

    #[cfg(feature = "signals")]
    {
      SignalArbiter::emit_app(
        Signal::with_capacity(ids::REQUEST_COMPLETED, 3)
          .meta("method", req_method_str)
          .meta("path", req_path_str)
          .meta("status", response.status().as_u16().to_string()),
      )
      .await;
    }

    response
  }

  /// Applies the appropriate error handler if one is set:
  /// - 5xx → [`Router::error_handler`]
  /// - 4xx → [`Router::client_error_handler`]
  fn maybe_apply_error_handler(&self, response: Response) -> Response {
    let status = response.status();
    if status.is_server_error() {
      if let Some(handler) = &self.error_handler {
        return handler(response);
      }
    } else if status.is_client_error()
      && let Some(handler) = &self.client_error_handler
    {
      return handler(response);
    }
    response
  }

  /// Adds a value to the global type-based state accessible by all handlers.
  ///
  /// Global state allows sharing data across different routes and middleware.
  /// Values are stored by their concrete type and retrieved via the
  /// `State` extractor (from `tako-extractors`) or with
  /// [`crate::state::get_state`].
  ///
  /// # Examples
  ///
  /// ```rust
  /// use tako::router::Router;
  ///
  /// #[derive(Clone)]
  /// struct AppConfig { database_url: String, api_key: String }
  ///
  /// let mut router = Router::new();
  /// router.state(AppConfig {
  ///     database_url: "postgresql://localhost/mydb".to_string(),
  ///     api_key: "secret-key".to_string(),
  /// });
  /// // You can also store simple types by type:
  /// router.state::<String>("1.0.0".to_string());
  /// ```
  pub fn state<T: Clone + Send + Sync + 'static>(&mut self, value: T) {
    set_state(value);
  }

  /// Inserts a value into this router's instance-local typed state.
  ///
  /// Unlike [`Router::state`] (which writes the process-global registry and
  /// therefore allows only one value per `T` per process), `with_state` is
  /// per-router — multiple routers can hold distinct `T`s without collisions.
  ///
  /// The `State` extractor (from `tako-extractors`) reads the per-router
  /// store first and falls back to the global store if no per-router value
  /// exists, so existing code that uses `set_state` / `Router::state`
  /// continues to work unchanged.
  ///
  /// Hot-path cost is one `Arc` clone per request *only when* at least one
  /// `with_state` call has happened on this router; an `AtomicBool::Acquire`
  /// fast-path skips it for routers that don't use instance-local state.
  ///
  /// # Examples
  ///
  /// ```rust
  /// use tako::router::Router;
  ///
  /// #[derive(Clone)]
  /// struct Db;
  ///
  /// let mut router = Router::new();
  /// router.with_state(Db);
  /// ```
  pub fn with_state<T: Clone + Send + Sync + 'static>(&mut self, value: T) -> &mut Self {
    self.router_state.insert(value);
    self.has_router_state.store(true, Ordering::Release);
    self
  }

  /// Returns the per-router typed state (shared `Arc`).
  #[inline]
  pub fn router_state(&self) -> &Arc<RouterState> {
    &self.router_state
  }

  #[cfg(feature = "signals")]
  /// Returns a reference to the signal arbiter.
  pub fn signals(&self) -> &SignalArbiter {
    &self.signals
  }

  #[cfg(feature = "signals")]
  /// Returns a clone of the signal arbiter, useful for sharing through state.
  pub fn signal_arbiter(&self) -> SignalArbiter {
    self.signals.clone()
  }

  #[cfg(feature = "signals")]
  /// Registers a handler for a named signal on this router's arbiter.
  pub fn on_signal<F, Fut>(&self, id: impl Into<String>, handler: F)
  where
    F: Fn(Signal) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = ()> + Send + 'static,
  {
    self.signals.on(id, handler);
  }

  #[cfg(feature = "signals")]
  /// Emits a signal through this router's arbiter.
  pub async fn emit_signal(&self, signal: Signal) {
    self.signals.emit(signal).await;
  }

  /// Adds global middleware to the router.
  ///
  /// Global middleware is executed for all routes in the order it was added,
  /// before any route-specific middleware. Middleware can modify requests,
  /// generate responses, or perform side effects like logging or authentication.
  ///
  /// # Examples
  ///
  /// ```rust
  /// use tako::{router::Router, middleware::Next, types::Request};
  ///
  /// let mut router = Router::new();
  ///
  /// // Logging middleware
  /// router.middleware(|req, next| async move {
  ///     println!("Request: {} {}", req.method(), req.uri());
  ///     let response = next.run(req).await;
  ///     println!("Response: {}", response.status());
  ///     response
  /// });
  ///
  /// // Authentication middleware
  /// router.middleware(|req, next| async move {
  ///     if req.headers().contains_key("authorization") {
  ///         next.run(req).await
  ///     } else {
  ///         "Unauthorized".into_response()
  ///     }
  /// });
  /// ```
  pub fn middleware<F, Fut, R>(&self, f: F) -> &Self
  where
    F: Fn(Request, Next) -> Fut + Clone + Send + Sync + 'static,
    Fut: std::future::Future<Output = R> + Send + 'static,
    R: Responder + Send + 'static,
  {
    let mw: BoxMiddleware = Arc::new(move |req, next| {
      let fut = f(req, next);
      Box::pin(async move { fut.await.into_response() })
    });

    // RCU-style append: rebuild the Vec atomically against concurrent pushers.
    // ArcSwap retries the closure on CAS conflict, so concurrent middleware
    // registrations cannot lose entries.
    self.middlewares.rcu(move |current| {
      let mut next = Vec::with_capacity(current.len() + 1);
      next.extend(current.iter().cloned());
      next.push(mw.clone());
      Arc::new(next)
    });
    self.has_global_middleware.store(true, Ordering::Release);
    self
  }

  /// Sets a fallback handler that will be executed when no route matches.
  ///
  /// The fallback runs after global middlewares and can be used to implement
  /// custom 404 pages, catch-all logic, or method-independent handlers.
  ///
  /// # Examples
  ///
  /// ```rust
  /// use tako::{router::Router, Method, responder::Responder, types::Request};
  ///
  /// async fn not_found(_req: Request) -> impl Responder { "Not Found" }
  ///
  /// let mut router = Router::new();
  /// router.route(Method::GET, "/", |_req| async { "Hello" });
  /// router.fallback(not_found);
  /// ```
  pub fn fallback<F, Fut, R>(&mut self, handler: F) -> &mut Self
  where
    F: Fn(Request) -> Fut + Clone + Send + Sync + 'static,
    Fut: std::future::Future<Output = R> + Send + 'static,
    R: Responder + Send + 'static,
  {
    // Use the Request-arg handler impl to box the fallback
    self.fallback = Some(BoxHandler::new::<F, (Request,)>(handler));
    self
  }

  /// Sets a fallback handler that supports extractors (like `Path`, `Query`, etc.).
  ///
  /// Use this when your fallback needs to parse request data via extractors. If you
  /// only need access to the raw `Request`, prefer `fallback` for simpler type inference.
  ///
  /// # Examples
  ///
  /// ```rust
  /// use tako::{router::Router, responder::Responder, extractors::{path::Path, query::Query}};
  ///
  /// #[derive(serde::Deserialize)]
  /// struct Q { q: Option<String> }
  ///
  /// async fn fallback_with_q(Path(_p): Path<String>, Query(_q): Query<Q>) -> impl Responder {
  ///     "Not Found"
  /// }
  ///
  /// let mut router = Router::new();
  /// router.fallback_with_extractors(fallback_with_q);
  /// ```
  pub fn fallback_with_extractors<H, T>(&mut self, handler: H) -> &mut Self
  where
    H: Handler<T> + Clone + 'static,
  {
    self.fallback = Some(BoxHandler::new::<H, T>(handler));
    self
  }

  /// Sets a default timeout for all routes.
  ///
  /// This timeout can be overridden on individual routes using `Route::timeout`.
  /// When a request exceeds the timeout duration, the timeout fallback handler
  /// is invoked (if configured) or a 408 Request Timeout response is returned.
  ///
  /// # Examples
  ///
  /// ```rust
  /// use tako::router::Router;
  /// use std::time::Duration;
  ///
  /// let mut router = Router::new();
  /// router.timeout(Duration::from_secs(30));
  /// ```
  pub fn timeout(&mut self, duration: Duration) -> &mut Self {
    self.timeout = Some(duration);
    self
  }

  /// Sets a fallback handler that will be executed when a request times out.
  ///
  /// If no timeout fallback is set, a default 408 Request Timeout response is returned.
  ///
  /// # Examples
  ///
  /// ```rust
  /// use tako::{router::Router, responder::Responder, types::Request};
  /// use std::time::Duration;
  ///
  /// async fn timeout_handler(_req: Request) -> impl Responder {
  ///     "Request took too long"
  /// }
  ///
  /// let mut router = Router::new();
  /// router.timeout(Duration::from_secs(30));
  /// router.timeout_fallback(timeout_handler);
  /// ```
  pub fn timeout_fallback<F, Fut, R>(&mut self, handler: F) -> &mut Self
  where
    F: Fn(Request) -> Fut + Clone + Send + Sync + 'static,
    Fut: std::future::Future<Output = R> + Send + 'static,
    R: Responder + Send + 'static,
  {
    self.timeout_fallback = Some(BoxHandler::new::<F, (Request,)>(handler));
    self
  }

  /// Sets a global error handler for 5xx responses.
  ///
  /// The error handler receives any response with a server error status and can
  /// transform it (e.g., to return JSON-formatted errors instead of plain text).
  ///
  /// # Examples
  ///
  /// ```rust
  /// use tako::router::Router;
  /// use tako::body::TakoBody;
  ///
  /// let mut router = Router::new();
  /// router.error_handler(|resp| {
  ///     let status = resp.status();
  ///     let body = format!(r#"{{"error": "{}"}}"#, status.canonical_reason().unwrap_or("Unknown"));
  ///     let mut res = http::Response::new(TakoBody::from(body));
  ///     *res.status_mut() = status;
  ///     res.headers_mut().insert(
  ///         http::header::CONTENT_TYPE,
  ///         http::HeaderValue::from_static("application/json"),
  ///     );
  ///     res
  /// });
  /// ```
  pub fn error_handler(
    &mut self,
    handler: impl Fn(Response) -> Response + Send + Sync + 'static,
  ) -> &mut Self {
    self.error_handler = Some(Arc::new(handler));
    self
  }

  /// Sets a global error handler for 4xx responses.
  ///
  /// Mirrors [`Router::error_handler`] but fires for client errors. Useful for
  /// converting bare 404 / 405 / 422 responses into structured error documents
  /// (e.g. via [`crate::problem::default_problem_responder`]).
  pub fn client_error_handler(
    &mut self,
    handler: impl Fn(Response) -> Response + Send + Sync + 'static,
  ) -> &mut Self {
    self.client_error_handler = Some(Arc::new(handler));
    self
  }

  /// Convenience: install [`crate::problem::default_problem_responder`] for
  /// both 4xx and 5xx so unhandled errors always render as
  /// `application/problem+json`.
  pub fn use_problem_json(&mut self) -> &mut Self {
    let h: ErrorHandler = Arc::new(crate::problem::default_problem_responder);
    self.error_handler = Some(h.clone());
    self.client_error_handler = Some(h);
    self
  }

  /// Registers a plugin with the router.
  ///
  /// Plugins extend the router's functionality by providing additional features
  /// like compression, CORS handling, rate limiting, or custom behavior. Plugins
  /// are initialized once when the server starts.
  ///
  /// # Examples
  ///
  /// ```rust
  /// # #[cfg(feature = "plugins")]
  /// use tako::{router::Router, plugins::TakoPlugin};
  /// # #[cfg(feature = "plugins")]
  /// use anyhow::Result;
  ///
  /// # #[cfg(feature = "plugins")]
  /// struct LoggingPlugin;
  ///
  /// # #[cfg(feature = "plugins")]
  /// impl TakoPlugin for LoggingPlugin {
  ///     fn name(&self) -> &'static str {
  ///         "logging"
  ///     }
  ///
  ///     fn setup(&self, _router: &Router) -> Result<()> {
  ///         println!("Logging plugin initialized");
  ///         Ok(())
  ///     }
  /// }
  ///
  /// # #[cfg(feature = "plugins")]
  /// # fn example() {
  /// let mut router = Router::new();
  /// router.plugin(LoggingPlugin);
  /// # }
  /// ```
  #[cfg(feature = "plugins")]
  #[cfg_attr(docsrs, doc(cfg(feature = "plugins")))]
  pub fn plugin<P>(&mut self, plugin: P) -> &mut Self
  where
    P: TakoPlugin + Clone + Send + Sync + 'static,
  {
    self.plugins.push(Box::new(plugin));
    self
  }

  /// Returns references to all registered plugins.
  #[cfg(feature = "plugins")]
  #[cfg_attr(docsrs, doc(cfg(feature = "plugins")))]
  pub(crate) fn plugins(&self) -> Vec<&dyn TakoPlugin> {
    self.plugins.iter().map(AsRef::as_ref).collect()
  }

  /// Initializes all registered plugins exactly once.
  #[cfg(feature = "plugins")]
  #[cfg_attr(docsrs, doc(cfg(feature = "plugins")))]
  #[doc(hidden)]
  pub fn setup_plugins_once(&self) {
    use std::sync::atomic::Ordering;

    // Hot-path fast exit: see `Route::setup_plugins_once`. Acquire-load
    // pairs with the Release half of the swap so plugin-published state
    // is visible by the time we skip the RMW.
    if self.plugins_initialized.load(Ordering::Acquire) {
      return;
    }

    if !self.plugins_initialized.swap(true, Ordering::SeqCst) {
      for plugin in self.plugins() {
        // Surface plugin setup errors loudly — a silently-skipped CORS,
        // auth, rate-limit, or CSRF plugin would leave the server
        // running without the protection the operator expected
        // (security-relevant fail-open). Cold path — first dispatch only.
        if let Err(e) = plugin.setup(self) {
          tracing::error!(
            plugin = plugin.name(),
            error = %e,
            "router-level TakoPlugin::setup failed; plugin not active"
          );
        }
      }
    }
  }

  /// Merges another router into this router.
  ///
  /// This method combines routes and middleware from another router into the
  /// current one. Routes are copied over, and the other router's global middleware
  /// is prepended to each merged route's middleware chain.
  ///
  /// # Panics
  ///
  /// Panics at registration time if a merged route conflicts with one already
  /// present on `self` (same method + same path). Mirrors the behavior of
  /// [`Router::route`] and [`Router::nest`] — merge is a startup-time
  /// operation and route conflicts are configuration bugs.
  ///
  /// # Examples
  ///
  /// ```rust
  /// use tako::{router::Router, Method, responder::Responder, types::Request};
  ///
  /// async fn api_handler(_req: Request) -> impl Responder {
  ///     "API response"
  /// }
  ///
  /// async fn web_handler(_req: Request) -> impl Responder {
  ///     "Web response"
  /// }
  ///
  /// // Create API router
  /// let mut api_router = Router::new();
  /// api_router.route(Method::GET, "/users", api_handler);
  /// api_router.middleware(|req, next| async move {
  ///     println!("API middleware");
  ///     next.run(req).await
  /// });
  ///
  /// // Create main router and merge API router
  /// let mut main_router = Router::new();
  /// main_router.route(Method::GET, "/", web_handler);
  /// main_router.merge(api_router);
  /// ```
  pub fn merge(&mut self, other: Router) {
    let upstream_globals = other.middlewares.load_full();

    for (method, weak_vec) in other.routes.iter() {
      for weak in weak_vec {
        if let Some(child_route) = weak.upgrade() {
          // Re-issue the route as a fresh `Arc<Route>` (same path) so we do
          // not mutate the child's middleware chain in-place — other router
          // instances may still hold the original `Arc` and would observe
          // unrelated middleware insertions otherwise.
          let new_route = child_route.cloned_with_path(child_route.path.clone());

          if !upstream_globals.is_empty() {
            let existing = new_route.middlewares.load_full();
            let mut merged = Vec::with_capacity(upstream_globals.len() + existing.len());
            merged.extend(upstream_globals.iter().cloned());
            merged.extend(existing.iter().cloned());
            new_route.has_middleware.store(true, Ordering::Release);
            new_route.middlewares.store(Arc::new(merged));
          }

          // Match `nest` semantics: a path conflict is a builder bug, not a
          // silent overwrite. Returning early via `let _ = … insert` would
          // throw away the existing route under a stable URL.
          if let Err(err) = self
            .inner
            .get_or_default_mut(&method)
            .insert(new_route.path.clone(), new_route.clone())
          {
            panic!(
              "Failed to merge route '{}' (method {:?}): {err}",
              new_route.path, method
            );
          }

          self
            .routes
            .get_or_default_mut(&method)
            .push(Arc::downgrade(&new_route));
        }
      }
    }

    #[cfg(feature = "signals")]
    self.signals.merge_from(&other.signals);
  }

  /// Returns every method that has a route matching the given path.
  ///
  /// Used by the 405 / `Allow` cold-path branch in [`Router::dispatch`]; not on
  /// the fast path. Iterates all standard methods (O(9)) plus any custom ones.
  fn collect_allowed_methods(&self, path: &str) -> SmallVec<[Method; 4]> {
    let mut allowed = SmallVec::<[Method; 4]>::new();
    for (method, m) in self.inner.iter() {
      if m.at(path).is_ok() {
        allowed.push(method);
      }
    }
    allowed
  }

  /// Ensures the request HTTP version satisfies the route's configured protocol guard.
  /// Returns `Some(Response)` with 505 HTTP Version Not Supported when the request
  /// doesn't match the guard, otherwise returns `None` to continue dispatch.
  fn enforce_protocol_guard(route: &Route, req: &Request) -> Option<Response> {
    if let Some(guard) = route.protocol_guard()
      && guard != req.version()
    {
      return Some(empty_status_response(
        StatusCode::HTTP_VERSION_NOT_SUPPORTED,
      ));
    }
    None
  }

  // OpenAPI route collection

  /// Collects `OpenAPI` metadata from all registered routes.
  ///
  /// Returns a vector of tuples containing the HTTP method, path, and `OpenAPI`
  /// metadata for each route that has `OpenAPI` information attached.
  ///
  /// # Examples
  ///
  /// ```rust,ignore
  /// use tako::{router::Router, Method};
  ///
  /// let mut router = Router::new();
  /// router.route(Method::GET, "/users", list_users)
  ///     .summary("List users")
  ///     .tag("users");
  ///
  /// for (method, path, openapi) in router.collect_openapi_routes() {
  ///     println!("{} {} - {:?}", method, path, openapi.summary);
  /// }
  /// ```
  #[cfg(any(feature = "utoipa", feature = "vespera"))]
  #[cfg_attr(docsrs, doc(cfg(any(feature = "utoipa", feature = "vespera"))))]
  pub fn collect_openapi_routes(&self) -> Vec<(Method, String, crate::openapi::RouteOpenApi)> {
    let mut result = Vec::new();

    for (method, weak_vec) in self.routes.iter() {
      for weak in weak_vec {
        if let Some(route) = weak.upgrade()
          && let Some(openapi) = route.openapi_metadata()
        {
          result.push((method.clone(), route.path.clone(), openapi));
        }
      }
    }

    result
  }

  /// Drops dangling `Weak<Route>` entries from the per-method `routes` index.
  ///
  /// All current routes stay live for the router's lifetime, so this is a
  /// no-op in well-behaved code. It exists as a safety valve: if any future
  /// API ever removes from `inner` (hot reload, route deregistration), or if
  /// downstream code holds the `Arc<Route>` returned from [`Router::route`]
  /// past the router's lifetime, this method bounds the size of the index.
  ///
  /// Cold path; safe to call repeatedly. Linear in the total number of
  /// registered routes.
  pub fn compact_routes(&mut self) {
    for weak_vec in self.routes.iter_mut() {
      weak_vec.retain(|w| w.strong_count() > 0);
    }
  }
}

/// Joins a path prefix and a child path, normalising the boundary slash.
fn combine_prefix_path(prefix: &str, path: &str) -> String {
  if prefix.is_empty() || prefix == "/" {
    return path.to_string();
  }
  let prefix = prefix.trim_end_matches('/');
  if path.is_empty() || path == "/" {
    return prefix.to_string();
  }
  if path.starts_with('/') {
    let mut out = String::with_capacity(prefix.len() + path.len());
    out.push_str(prefix);
    out.push_str(path);
    out
  } else {
    let mut out = String::with_capacity(prefix.len() + 1 + path.len());
    out.push_str(prefix);
    out.push('/');
    out.push_str(path);
    out
  }
}

/// Joins a slice of HTTP methods into a comma-separated `Allow`-header value.
fn join_methods(methods: &[Method]) -> String {
  let mut out = String::with_capacity(methods.len() * 8);
  for (i, m) in methods.iter().enumerate() {
    if i > 0 {
      out.push_str(", ");
    }
    out.push_str(m.as_str());
  }
  out
}

/// Distributed slice of route registration thunks.
///
/// Each `#[tako::route]` / `#[tako::get]` / etc. attribute contributes a
/// `fn(&mut Router)` closure that calls [`Router::route`] with the
/// generated `Params::METHOD` / `Params::PATH` and the handler. Iterating
/// the slice — what [`Router::mount_all`] does — replays every contribution
/// against the supplied router.
#[linkme::distributed_slice]
pub static TAKO_ROUTES: [fn(&mut Router)] = [..];

/// Maps the 9 standard HTTP methods to array indices.
/// Returns `None` for non-standard / extension methods.
#[inline]
fn method_slot(method: &Method) -> Option<usize> {
  Some(match *method {
    Method::GET => 0,
    Method::POST => 1,
    Method::PUT => 2,
    Method::DELETE => 3,
    Method::PATCH => 4,
    Method::HEAD => 5,
    Method::OPTIONS => 6,
    Method::CONNECT => 7,
    Method::TRACE => 8,
    _ => return None,
  })
}

/// Reconstructs a `Method` from its slot index.
///
/// The only caller iterates `0..9` over the `standard` array, so out-of-range
/// indices indicate an internal invariant violation. In debug builds this
/// trips an assertion; in release we degrade to `Method::GET` rather than
/// panic from a hot router path.
#[inline]
fn method_from_slot(idx: usize) -> Method {
  match idx {
    0 => Method::GET,
    1 => Method::POST,
    2 => Method::PUT,
    3 => Method::DELETE,
    4 => Method::PATCH,
    5 => Method::HEAD,
    6 => Method::OPTIONS,
    7 => Method::CONNECT,
    8 => Method::TRACE,
    _ => {
      debug_assert!(false, "method_from_slot called with idx={idx}");
      Method::GET
    }
  }
}

/// A compact, cache-friendly map keyed by HTTP method.
///
/// Standard methods (GET, POST, PUT, …) use O(1) array indexing.
/// Non-standard methods fall back to linear scan (extremely rare in practice).
struct MethodMap<V> {
  standard: [Option<V>; 9],
  custom: Vec<(Method, V)>,
}

impl<V> MethodMap<V> {
  fn new() -> Self {
    Self {
      standard: std::array::from_fn(|_| None),
      custom: Vec::new(),
    }
  }

  /// O(1) lookup for standard methods, linear scan for custom.
  #[inline]
  fn get(&self, method: &Method) -> Option<&V> {
    if let Some(idx) = method_slot(method) {
      self.standard[idx].as_ref()
    } else {
      self
        .custom
        .iter()
        .find(|(m, _)| m == method)
        .map(|(_, v)| v)
    }
  }

  /// Returns a mutable reference, inserting `V::default()` if absent.
  fn get_or_default_mut(&mut self, method: &Method) -> &mut V
  where
    V: Default,
  {
    if let Some(idx) = method_slot(method) {
      self.standard[idx].get_or_insert_with(V::default)
    } else {
      let pos = self.custom.iter().position(|(m, _)| m == method);
      if let Some(pos) = pos {
        &mut self.custom[pos].1
      } else {
        self.custom.push((method.clone(), V::default()));
        // SAFETY-style invariant: we just pushed, so the vec is non-empty.
        // Using `expect` over `unwrap` to surface the invariant if it ever
        // breaks in a future refactor.
        &mut self
          .custom
          .last_mut()
          .expect("custom vec must contain the entry we just pushed")
          .1
      }
    }
  }

  /// Iterates over all `(Method, &V)` pairs (standard then custom).
  fn iter(&self) -> impl Iterator<Item = (Method, &V)> {
    self
      .standard
      .iter()
      .enumerate()
      .filter_map(|(idx, slot)| slot.as_ref().map(|v| (method_from_slot(idx), v)))
      .chain(self.custom.iter().map(|(m, v)| (m.clone(), v)))
  }

  /// Mutable counterpart of [`MethodMap::iter`]. Used by router GC paths.
  fn iter_mut(&mut self) -> impl Iterator<Item = &mut V> {
    self
      .standard
      .iter_mut()
      .filter_map(|slot| slot.as_mut())
      .chain(self.custom.iter_mut().map(|(_, v)| v))
  }
}