volo-http 0.5.7

HTTP framework implementation of volo.
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
//! [`Router`] implemententation for [`Server`].
//!
//! [`Router`] is a [`Service`] that can route a path to a [`MethodRouter`] or fallback to another
//! [`Route`].
//!
//! See [`Router`] and [`Router::route`] for more details.
//!
//! [`Server`]: crate::server::Server

use std::{collections::HashMap, convert::Infallible};

use faststr::FastStr;
use http::status::StatusCode;
use metainfo::METAINFO;
use motore::{ServiceExt, layer::Layer, service::Service};
use volo::context::Context;

use super::{
    Fallback, Route,
    method_router::MethodRouter,
    utils::{Matcher, NEST_CATCH_PARAM, RouteId, StripPrefixLayer},
};
use crate::{
    body::Body,
    context::ServerContext,
    request::Request,
    response::Response,
    server::{IntoResponse, handler::Handler},
};

/// The router for routing path to [`Service`]s or handlers.
#[must_use]
pub struct Router<B = Body, E = Infallible> {
    matcher: Matcher,
    /// Each route with the pattern reported as [`MatchedPath`]: the registered uri, or the prefix
    /// for nested routes.
    routes: HashMap<RouteId, (Endpoint<B, E>, FastStr)>,
    fallback: Fallback<B, E>,
    is_default_fallback: bool,
}

impl<B, E> Default for Router<B, E>
where
    B: Send + 'static,
    E: 'static,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<B, E> Router<B, E>
where
    B: Send + 'static,
    E: 'static,
{
    /// Create a new router.
    pub fn new() -> Self
    where
        E: 'static,
    {
        Self {
            matcher: Default::default(),
            routes: Default::default(),
            fallback: Fallback::from_status_code(StatusCode::NOT_FOUND),
            is_default_fallback: true,
        }
    }

    /// Create a route for the given path with the given [`MethodRouter`].
    ///
    /// The uri matcher is based on [`matchit`](https://docs.rs/matchit/0.8.0/matchit/).  It
    /// supports normal path and parameterized path.
    ///
    /// # Examples
    ///
    /// ## Normal path
    ///
    /// ```
    /// use volo_http::server::route::{Router, get};
    ///
    /// async fn index() -> &'static str {
    ///     "Hello, World"
    /// }
    ///
    /// let router: Router = Router::new().route("/", get(index));
    /// ```
    ///
    /// ## Path with Named Parameters
    ///
    /// Named parameters like `/{id}` match anything until the next `/` or the end of the path.
    ///
    /// The params can be extract by extractor `PathParamsMap`:
    ///
    /// ```
    /// use volo::FastStr;
    /// use volo_http::server::{
    ///     param::PathParamsMap,
    ///     route::{Router, get},
    /// };
    ///
    /// async fn param(map: PathParamsMap) -> FastStr {
    ///     map.get("id").unwrap().clone()
    /// }
    ///
    /// let router: Router = Router::new().route("/user/{id}", get(param));
    /// ```
    ///
    /// Or you can use `PathParams` directly:
    ///
    /// ```
    /// use volo::FastStr;
    /// use volo_http::server::{
    ///     param::PathParams,
    ///     route::{Router, get},
    /// };
    ///
    /// async fn param(PathParams(id): PathParams<String>) -> String {
    ///     id
    /// }
    ///
    /// let router: Router = Router::new().route("/user/{id}", get(param));
    /// ```
    ///
    /// More than one params are also supported:
    ///
    /// ```
    /// use volo::FastStr;
    /// use volo_http::server::{
    ///     param::PathParams,
    ///     route::{Router, get},
    /// };
    ///
    /// async fn param(PathParams((user, post)): PathParams<(usize, usize)>) -> String {
    ///     format!("user id: {user}, post id: {post}")
    /// }
    ///
    /// let router: Router = Router::new().route("/user/{user}/post/{post}", get(param));
    /// ```
    ///
    /// ## Path with Catch-all Parameters
    ///
    /// Catch-all parameters start with `*` and match anything until the end of the path. They must
    /// always be at the **end** of the route.
    ///
    /// ```
    /// use volo_http::server::{
    ///     param::PathParams,
    ///     route::{Router, get},
    /// };
    ///
    /// async fn index() -> &'static str {
    ///     "Hello, World"
    /// }
    ///
    /// async fn fallback(PathParams(uri): PathParams<String>) -> String {
    ///     format!("Path `{uri}` is not available")
    /// }
    ///
    /// let router: Router = Router::new()
    ///     .route("/", get(index))
    ///     .route("/index", get(index))
    ///     .route("/{*fallback}", get(fallback));
    /// ```
    ///
    /// For more usage methods, please refer to:
    /// [`matchit`](https://docs.rs/matchit/0.8.0/matchit/).
    pub fn route<S>(mut self, uri: S, method_router: MethodRouter<B, E>) -> Self
    where
        S: AsRef<str>,
    {
        let route_id = self
            .matcher
            .insert(uri.as_ref())
            .expect("Insert routing rule failed");

        self.routes.insert(
            route_id,
            (
                Endpoint::MethodRouter(method_router),
                FastStr::new(uri.as_ref()),
            ),
        );

        self
    }

    /// Create a route for the given path with a given [`Router`] and nest it into the current
    /// router.
    ///
    /// The `uri` param is a prefix of the whole uri and will be stripped before calling the inner
    /// router, and the inner [`Router`] will handle uri without the given prefix, but all params
    /// will be kept.
    ///
    /// # Examples
    ///
    /// ```
    /// use volo_http::server::{
    ///     param::PathParams,
    ///     route::{Router, get},
    /// };
    ///
    /// async fn hello_world() -> &'static str {
    ///     "Hello, World"
    /// }
    /// async fn handle_tid(PathParams(tid): PathParams<String>) -> String {
    ///     tid
    /// }
    /// async fn uid_and_tid(PathParams((uid, tid)): PathParams<(String, String)>) -> String {
    ///     format!("uid: {uid}, tid: {tid}")
    /// }
    ///
    /// let post_router = Router::new()
    ///     // http://<SERVER>/post/
    ///     .route("/", get(hello_world))
    ///     // http://<SERVER>/post/114
    ///     .route("/{tid}", get(handle_tid));
    /// let user_router = Router::new()
    ///     // http://<SERVER>/user/114/name
    ///     .route("/name", get(hello_world))
    ///     // http://<SERVER>/user/114/tid/514
    ///     .route("/post/{tid}", get(uid_and_tid));
    ///
    /// let router: Router = Router::new()
    ///     .nest("/post", post_router)
    ///     .nest("/user/{uid}/", user_router);
    /// ```
    pub fn nest<U>(self, uri: U, router: Router<B, E>) -> Self
    where
        U: AsRef<str>,
    {
        self.nest_route(uri.as_ref().to_owned(), Route::new(router))
    }

    /// Create a route for the given path with a given [`Service`] and nest it into the current
    /// router.
    ///
    /// The service will handle any uri with the param `uri` as its prefix.
    pub fn nest_service<U, S>(self, uri: U, service: S) -> Self
    where
        U: AsRef<str>,
        S: Service<ServerContext, Request<B>, Error = E> + Send + Sync + 'static,
        S::Response: IntoResponse,
    {
        self.nest_route(
            uri.as_ref().to_owned(),
            Route::new(service.map_response(IntoResponse::into_response)),
        )
    }

    fn nest_route(mut self, prefix: String, route: Route<B, E>) -> Self {
        let uri = if prefix.ends_with('/') {
            format!("{prefix}{NEST_CATCH_PARAM}")
        } else {
            format!("{prefix}/{NEST_CATCH_PARAM}")
        };

        // Because we use `matchit::Router` for matching uri, for `/{*catch}`, `/xxx` matches it
        // but `/` does not match. To solve the problem, we should also insert `/` for handling it.
        let route_id = self
            .matcher
            .insert(prefix.clone())
            .expect("Insert routing rule failed");
        let pattern = FastStr::new(prefix.trim_end_matches('/'));

        // If user uses `router.nest("/user", another)`, `/user`, `/user/`, `/user/{*catch}` should
        // be inserted. But if user uses `/user/`, we will insert `/user/` and `/user/{*catch}`
        // only.
        if !prefix.ends_with('/') {
            let prefix_with_slash = prefix + "/";
            self.matcher
                .insert_with_id(prefix_with_slash, route_id)
                .expect("Insert routing rule failed");
        }

        self.matcher
            .insert_with_id(uri, route_id)
            .expect("Insert routing rule failed");

        self.routes.insert(
            route_id,
            (
                Endpoint::Service(Route::new(StripPrefixLayer.layer(route))),
                pattern,
            ),
        );

        self
    }

    /// Set a global fallback for router.
    ///
    /// If there is no route matches the current uri, router will call the fallback handler.
    ///
    /// Default is returning "404 Not Found".
    pub fn fallback<H, T>(mut self, handler: H) -> Self
    where
        for<'a> H: Handler<T, B, E> + Clone + Send + Sync + 'a,
        T: 'static,
        E: 'static,
    {
        self.fallback = Fallback::from_handler(handler);
        self
    }

    /// Set a global fallback for router.
    ///
    /// If there is no route matches the current uri, router will call the fallback service.
    ///
    /// Default is returning "404 Not Found".
    pub fn fallback_service<S>(mut self, service: S) -> Self
    where
        for<'a> S: Service<ServerContext, Request<B>, Error = E> + Send + Sync + 'a,
        S::Response: IntoResponse,
    {
        self.fallback = Fallback::from_service(service);
        self
    }

    /// Merge another router to self.
    ///
    /// # Panics
    ///
    /// - Panics if the two router have routes with the same path.
    ///
    /// # Examples
    ///
    /// ```
    /// use volo_http::server::route::{Router, get};
    ///
    /// async fn index() -> &'static str {
    ///     "Hello, World"
    /// }
    ///
    /// fn foo_router() -> Router {
    ///     Router::new()
    ///         .route("/foo/", get(index))
    ///         .route("/foo/index", get(index))
    /// }
    ///
    /// fn bar_router() -> Router {
    ///     Router::new()
    ///         .route("/bar/", get(index))
    ///         .route("/bar/index", get(index))
    /// }
    ///
    /// fn baz_router() -> Router {
    ///     Router::new()
    ///         .route("/baz/", get(index))
    ///         .route("/baz/index", get(index))
    /// }
    ///
    /// let app = Router::new()
    ///     .merge(foo_router())
    ///     .merge(bar_router())
    ///     .merge(baz_router());
    /// ```
    pub fn merge(mut self, other: Self) -> Self {
        let Router {
            mut matcher,
            mut routes,
            fallback,
            is_default_fallback,
        } = other;

        for (path, route_id) in matcher.drain() {
            self.matcher
                .insert_with_id(path, route_id)
                .expect("Insert routing rule failed during merging router");
        }
        for (route_id, route) in routes.drain() {
            if self.routes.insert(route_id, route).is_some() {
                unreachable!()
            }
        }

        match (self.is_default_fallback, is_default_fallback) {
            (_, true) => {}
            (true, false) => {
                self.fallback = fallback;
                self.is_default_fallback = false;
            }
            (false, false) => {
                panic!("Merge `Router` failed because both `Router` have customized `fallback`")
            }
        }

        self
    }

    /// Add a new inner layer to all routes in router.
    ///
    /// The layer's `Service` should be `Send + Sync + 'static`.
    pub fn layer<L, B2, E2>(self, l: L) -> Router<B2, E2>
    where
        L: Layer<Route<B, E>> + Clone + Send + Sync + 'static,
        L::Service: Service<ServerContext, Request<B2>, Error = E2> + Send + Sync + 'static,
        <L::Service as Service<ServerContext, Request<B2>>>::Response: IntoResponse,
        B2: 'static,
    {
        let routes = self
            .routes
            .into_iter()
            .map(|(id, (route, pattern))| {
                let route = route.layer(l.clone());
                (id, (route, pattern))
            })
            .collect();

        let fallback = self.fallback.layer(l.clone());

        Router {
            matcher: self.matcher,
            routes,
            fallback,
            is_default_fallback: self.is_default_fallback,
        }
    }
}

impl<B, E> Service<ServerContext, Request<B>> for Router<B, E>
where
    B: Send + 'static,
    E: 'static,
{
    type Response = Response;
    type Error = E;

    async fn call(
        &self,
        cx: &mut ServerContext,
        req: Request<B>,
    ) -> Result<Self::Response, Self::Error> {
        if let Ok(matched) = self.matcher.at(req.uri().clone().path()) {
            if let Some((route, pattern)) = self.routes.get(matched.value) {
                if !matched.params.is_empty() {
                    cx.params_mut().extend(matched.params);
                }
                MatchedPath::record(cx, pattern);
                return route.call(cx, req).await;
            }
        }

        // No route handles this request. An outer router may already have recorded its prefix
        // before delegating here, so clear it: a fallback is not a route.
        cx.extensions_mut().remove::<MatchedPath>();
        let _ = METAINFO.try_with(|mi| mi.borrow_mut().remove_faststr::<MatchedPath>());

        self.fallback.call(cx, req).await
    }
}

/// The route pattern that matched the current request, e.g. `/users/{id}`.
///
/// Stored in [`ServerContext`] extensions for logging and metrics, this provides
/// a stable route label instead of the concrete request path, keeping metric
/// tag cardinality bounded.
///
/// For nested routers, the pattern combines each matched prefix with the inner
/// route pattern. For [`Router::nest_service`], only the prefix is recorded.
/// No pattern is recorded for requests handled by a fallback.
///
/// The same pattern is also stored in the request's [`METAINFO`] when one is in scope (the server
/// always provides one), as a plain [`FastStr`] keyed by this type, so observers without access to
/// the context, such as a future wrapper measuring the request from outside the router, can read it
/// with `METAINFO.with(|mi| mi.borrow().get_faststr::<MatchedPath>().cloned())`.
///
/// ```
/// use volo::context::Context;
/// use volo_http::{context::ServerContext, server::route::MatchedPath};
///
/// fn route_of(cx: &ServerContext) -> Option<&str> {
///     cx.extensions()
///         .get::<MatchedPath>()
///         .map(MatchedPath::as_str)
/// }
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MatchedPath(FastStr);

impl MatchedPath {
    /// The pattern as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume the value and return the pattern.
    pub fn into_inner(self) -> FastStr {
        self.0
    }

    fn record(cx: &mut ServerContext, pattern: &FastStr) {
        let extensions = cx.extensions_mut();
        let matched = match extensions.get_mut::<MatchedPath>() {
            // Called from a nested router: the outer router recorded its prefix already.
            Some(outer) => {
                outer.0 = FastStr::from_string(outer.0.to_string() + pattern);
                outer.0.clone()
            }
            None => {
                extensions.insert(MatchedPath(pattern.clone()));
                pattern.clone()
            }
        };
        let _ = METAINFO.try_with(|mi| mi.borrow_mut().insert_faststr::<MatchedPath>(matched));
    }
}

impl std::ops::Deref for MatchedPath {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl AsRef<str> for MatchedPath {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

#[allow(clippy::large_enum_variant)]
enum Endpoint<B = Body, E = Infallible> {
    MethodRouter(MethodRouter<B, E>),
    Service(Route<B, E>),
}

impl<B, E> Service<ServerContext, Request<B>> for Endpoint<B, E>
where
    B: Send + 'static,
    E: 'static,
{
    type Response = Response;
    type Error = E;

    async fn call(
        &self,
        cx: &mut ServerContext,
        req: Request<B>,
    ) -> Result<Self::Response, Self::Error> {
        match self {
            Self::MethodRouter(mr) => mr.call(cx, req).await,
            Self::Service(service) => service.call(cx, req).await,
        }
    }
}

impl<B, E> Default for Endpoint<B, E>
where
    B: Send + 'static,
    E: 'static,
{
    fn default() -> Self {
        Self::MethodRouter(Default::default())
    }
}

impl<B, E> Endpoint<B, E>
where
    B: Send + 'static,
    E: 'static,
{
    fn layer<L, B2, E2>(self, l: L) -> Endpoint<B2, E2>
    where
        L: Layer<Route<B, E>> + Clone + Send + Sync + 'static,
        L::Service: Service<ServerContext, Request<B2>, Error = E2> + Send + Sync,
        <L::Service as Service<ServerContext, Request<B2>>>::Response: IntoResponse,
        B2: 'static,
    {
        match self {
            Self::MethodRouter(mr) => Endpoint::MethodRouter(mr.layer(l)),
            Self::Service(s) => Endpoint::Service(Route::new(
                l.layer(s).map_response(IntoResponse::into_response),
            )),
        }
    }
}

#[cfg(test)]
mod router_tests {
    use faststr::FastStr;
    use http::{method::Method, status::StatusCode, uri::Uri};
    use motore::service::Service;
    use volo::context::Context;

    use super::{MatchedPath, Router};
    use crate::{
        body::{Body, BodyConversion},
        request::Request,
        server::{
            Server,
            param::PathParamsVec,
            route::method_router::any,
            test_helpers::{TestServer, empty_cx},
        },
    };

    async fn always_ok() {}
    async fn teapot() -> StatusCode {
        StatusCode::IM_A_TEAPOT
    }

    #[tokio::test]
    async fn url_match() {
        async fn is_ok(server: &TestServer<Router<Option<Body>>, Option<Body>>, uri: &str) -> bool {
            server.call_route(Method::GET, uri, None).await.status() == StatusCode::OK
        }
        let router: Router<Option<Body>> = Router::new()
            .route("/", any(always_ok))
            .route("/catch/{id}", any(always_ok))
            .route("/catch/{id}/another", any(always_ok))
            .route("/catch/{id}/another/{uid}", any(always_ok))
            .route("/catch/{id}/another/{uid}/again", any(always_ok))
            .route("/catch/{id}/another/{uid}/again/{tid}", any(always_ok))
            .route("/catch_all/{*all}", any(always_ok));
        let server = Server::new(router).into_test_server();

        assert!(is_ok(&server, "/").await);
        assert!(is_ok(&server, "/catch/114").await);
        assert!(is_ok(&server, "/catch/514").await);
        assert!(is_ok(&server, "/catch/ll45l4").await);
        assert!(is_ok(&server, "/catch/ll45l4/another").await);
        assert!(is_ok(&server, "/catch/ll45l4/another/1919").await);
        assert!(is_ok(&server, "/catch/ll45l4/another/1919/again").await);
        assert!(is_ok(&server, "/catch/ll45l4/another/1919/again/810").await);
        assert!(is_ok(&server, "/catch_all/114").await);
        assert!(is_ok(&server, "/catch_all/114/514/1919/810").await);

        assert!(!is_ok(&server, "/catch").await);
        assert!(!is_ok(&server, "/catch/114/").await);
        assert!(!is_ok(&server, "/catch/114/another/514/").await);
        assert!(!is_ok(&server, "/catch/11/another/45/again/14/").await);
        assert!(!is_ok(&server, "/catch_all").await);
        assert!(!is_ok(&server, "/catch_all/").await);
    }

    #[tokio::test]
    async fn matched_path() {
        async fn matched_path_of(router: &Router<Option<Body>>, uri: &str) -> Option<String> {
            let mut cx = empty_cx();
            let req = Request::builder()
                .method(Method::GET)
                .uri(uri)
                .body(None)
                .unwrap();
            let _ = router.call(&mut cx, req).await;
            cx.extensions()
                .get::<MatchedPath>()
                .map(|path| path.as_str().to_owned())
        }

        let router: Router<Option<Body>> = Router::new()
            .route("/", any(always_ok))
            .route("/users/{id}", any(always_ok))
            .route("/files/{*path}", any(always_ok))
            .nest(
                "/api/{version}",
                Router::new().route("/items/{id}", any(always_ok)),
            )
            .nest("/legacy/", Router::new().route("/", any(always_ok)))
            .nest(
                "/v/{ver}",
                Router::new().nest("/deep", Router::new().route("/leaf/{id}", any(always_ok))),
            )
            .merge(Router::new().route("/merged/{id}", any(always_ok)));

        assert_eq!(matched_path_of(&router, "/").await.as_deref(), Some("/"));
        // Different values, same route, same pattern.
        assert_eq!(
            matched_path_of(&router, "/users/42").await.as_deref(),
            Some("/users/{id}")
        );
        assert_eq!(
            matched_path_of(&router, "/users/43").await.as_deref(),
            Some("/users/{id}")
        );
        assert_eq!(
            matched_path_of(&router, "/files/a/b/c").await.as_deref(),
            Some("/files/{*path}")
        );
        // Nested routers prepend their prefix.
        assert_eq!(
            matched_path_of(&router, "/api/v2/items/7").await.as_deref(),
            Some("/api/{version}/items/{id}")
        );
        assert_eq!(
            matched_path_of(&router, "/legacy/").await.as_deref(),
            Some("/legacy/")
        );
        // Two levels of nesting: every prefix is composed, not only the innermost one.
        assert_eq!(
            matched_path_of(&router, "/v/3/deep/leaf/9")
                .await
                .as_deref(),
            Some("/v/{ver}/deep/leaf/{id}")
        );
        // Merged routers keep their patterns.
        assert_eq!(
            matched_path_of(&router, "/merged/1").await.as_deref(),
            Some("/merged/{id}")
        );
        // Fallbacks, top-level or inside a nested router, record nothing.
        assert_eq!(matched_path_of(&router, "/nope").await, None);
        assert_eq!(matched_path_of(&router, "/api/v2/nope").await, None);
    }

    #[tokio::test]
    async fn matched_path_is_mirrored_into_metainfo() {
        use std::cell::RefCell;

        use metainfo::{METAINFO, MetaInfo};

        // (from the context, from METAINFO) after one request
        async fn both(
            router: &Router<Option<Body>>,
            uri: &str,
        ) -> (Option<String>, Option<String>) {
            METAINFO
                .scope(RefCell::new(MetaInfo::default()), async {
                    let mut cx = empty_cx();
                    let req = Request::builder()
                        .method(Method::GET)
                        .uri(uri)
                        .body(None)
                        .unwrap();
                    let _ = router.call(&mut cx, req).await;
                    let from_cx = cx
                        .extensions()
                        .get::<MatchedPath>()
                        .map(|p| p.as_str().to_owned());
                    let from_mi = METAINFO.with(|mi| {
                        mi.borrow()
                            .get_faststr::<MatchedPath>()
                            .map(|p| p.as_str().to_owned())
                    });
                    (from_cx, from_mi)
                })
                .await
        }

        let router: Router<Option<Body>> = Router::new().route("/users/{id}", any(always_ok)).nest(
            "/api/{version}",
            Router::new().route("/items/{id}", any(always_ok)),
        );

        let (cx, mi) = both(&router, "/users/42").await;
        assert_eq!(cx.as_deref(), Some("/users/{id}"));
        assert_eq!(mi, cx);

        // Nested: METAINFO holds the composed pattern, not just the outer prefix.
        let (cx, mi) = both(&router, "/api/v2/items/7").await;
        assert_eq!(cx.as_deref(), Some("/api/{version}/items/{id}"));
        assert_eq!(mi, cx);

        // Cleared in both places on fallback, including after a nested prefix matched.
        assert_eq!(both(&router, "/nope").await, (None, None));
        assert_eq!(both(&router, "/api/v2/nope").await, (None, None));
    }

    #[tokio::test]
    async fn matched_path_is_visible_mid_request() {
        use std::cell::RefCell;

        use metainfo::{METAINFO, MetaInfo};

        use crate::{
            context::ServerContext,
            response::Response,
            server::{
                IntoResponse,
                middleware::{Next, from_fn},
            },
        };

        fn current() -> Option<String> {
            METAINFO.with(|mi| {
                mi.borrow()
                    .get_faststr::<MatchedPath>()
                    .map(|p| p.as_str().to_owned())
            })
        }

        // A handler runs after the innermost match, so it must see the complete pattern.
        async fn echo_matched_path() -> String {
            current().unwrap_or_default()
        }

        // What a layer applied to the outer router sees at the start and at the end of its call.
        struct Seen {
            start: Option<String>,
            end: Option<String>,
        }

        async fn probe(
            cx: &mut ServerContext,
            req: Request<Option<Body>>,
            next: Next<Option<Body>>,
        ) -> Response {
            let start = current();
            let resp = next.run(cx, req).await.into_response();
            cx.extensions_mut().insert(Seen {
                start,
                end: current(),
            });
            resp
        }

        async fn run(router: &Router<Option<Body>>, uri: &str) -> (String, Seen) {
            METAINFO
                .scope(RefCell::new(MetaInfo::default()), async {
                    let mut cx = empty_cx();
                    let req = Request::builder()
                        .method(Method::GET)
                        .uri(uri)
                        .body(None)
                        .unwrap();
                    let resp = router.call(&mut cx, req).await.unwrap();
                    let body = resp.into_body().into_string().await.unwrap();
                    let seen = cx.extensions_mut().remove::<Seen>().unwrap();
                    (body, seen)
                })
                .await
        }

        let router: Router<Option<Body>> = Router::new()
            .route("/users/{id}", any(echo_matched_path))
            .nest(
                "/api/{version}",
                Router::new().route("/items/{id}", any(echo_matched_path)),
            )
            .layer(from_fn(probe));

        // Plain route: the layer wraps the leaf, so the pattern is complete from the start.
        let (body, seen) = run(&router, "/users/42").await;
        assert_eq!(body, "/users/{id}");
        assert_eq!(seen.start.as_deref(), Some("/users/{id}"));
        assert_eq!(seen.end.as_deref(), Some("/users/{id}"));

        // Nested route: the layer wraps the nested endpoint, so when its call starts only the
        // prefix has matched; the handler and the end of the call see the complete pattern.
        let (body, seen) = run(&router, "/api/v2/items/7").await;
        assert_eq!(body, "/api/{version}/items/{id}");
        assert_eq!(seen.start.as_deref(), Some("/api/{version}"));
        assert_eq!(seen.end.as_deref(), Some("/api/{version}/items/{id}"));
    }

    #[tokio::test]
    async fn router_fallback() {
        async fn is_teapot(
            server: &TestServer<Router<Option<Body>>, Option<Body>>,
            uri: &str,
        ) -> bool {
            server.call_route(Method::GET, uri, None).await.status() == StatusCode::IM_A_TEAPOT
        }
        let router: Router<Option<Body>> = Router::new()
            .route("/", any(always_ok))
            .route("/catch/{id}", any(always_ok))
            .route("/catch_all/{*all}", any(always_ok))
            .fallback(teapot);
        let server = Server::new(router).into_test_server();

        assert!(is_teapot(&server, "//").await);
        assert!(is_teapot(&server, "/catch/").await);
        assert!(is_teapot(&server, "/catch_all/").await);

        assert!(!is_teapot(&server, "/catch/114").await);
        assert!(!is_teapot(&server, "/catch_all/514").await);
        assert!(!is_teapot(&server, "/catch_all/114/514/1919/810").await);
    }

    #[tokio::test]
    async fn nest_router() {
        async fn uri_and_params(uri: Uri, params: PathParamsVec) -> String {
            let mut v = vec![FastStr::from_string(uri.to_string())];
            v.extend(params.into_iter().map(|(_, v)| v));
            v.join("\n")
        }
        async fn get_res(
            server: &TestServer<Router<Option<Body>>, Option<Body>>,
            uri: &str,
        ) -> String {
            server
                .call_route(Method::GET, uri, None)
                .await
                .into_string()
                .await
                .unwrap()
        }

        let router: Router<Option<Body>> = Router::new()
            .nest(
                // uri prefix without final slash ('/')
                "/test-1",
                Router::new()
                    .route("/", any(uri_and_params))
                    .route("/id/{id}", any(uri_and_params))
                    .route("/catch/{*content}", any(uri_and_params)),
            )
            .nest(
                // uri prefix with final slash ('/')
                "/test-2/",
                Router::new()
                    .route("/", any(uri_and_params))
                    .route("/id/{id}", any(uri_and_params))
                    .route("/catch/{*content}", any(uri_and_params)),
            )
            .nest(
                // uri prefix with a param without final slash ('/')
                "/test-3/{catch}",
                Router::new()
                    .route("/", any(uri_and_params))
                    .route("/id/{id}", any(uri_and_params))
                    .route("/catch/{*content}", any(uri_and_params)),
            )
            .nest(
                // uri prefix with a param and final slash ('/')
                "/test-4/{catch}/",
                Router::new()
                    .route("/", any(uri_and_params))
                    .route("/id/{id}", any(uri_and_params))
                    .route("/catch/{*content}", any(uri_and_params)),
            );
        let server = Server::new(router).into_test_server();

        // We register it as `/test-1`, so it does match.
        assert_eq!(get_res(&server, "/test-1").await, "/");
        assert_eq!(get_res(&server, "/test-1/").await, "/");
        assert_eq!(get_res(&server, "/test-1/id/114").await, "/id/114\n114");
        assert_eq!(
            get_res(&server, "/test-1/catch/114/514/1919/810").await,
            "/catch/114/514/1919/810\n114/514/1919/810",
        );

        // We register it as `/test-2/`, so `/test-2` does not match, but `/test-2/` does match.
        assert!(get_res(&server, "/test-2").await.is_empty());
        assert_eq!(get_res(&server, "/test-2/").await, "/");
        assert_eq!(get_res(&server, "/test-2/id/114").await, "/id/114\n114");
        assert_eq!(
            get_res(&server, "/test-2/catch/114/514/1919/810").await,
            "/catch/114/514/1919/810\n114/514/1919/810",
        );

        // The first param can be kept.
        assert_eq!(get_res(&server, "/test-3/114").await, "/\n114");
        assert_eq!(get_res(&server, "/test-3/114/").await, "/\n114");
        assert_eq!(
            get_res(&server, "/test-3/114/id/514").await,
            "/id/514\n114\n514",
        );
        assert_eq!(
            get_res(&server, "/test-3/114/catch/514/1919/810").await,
            "/catch/514/1919/810\n114\n514/1919/810",
        );

        // It is also empty.
        assert!(get_res(&server, "/test-4/114").await.is_empty());
        assert_eq!(get_res(&server, "/test-4/114/").await, "/\n114");
        assert_eq!(
            get_res(&server, "/test-4/114/id/514").await,
            "/id/514\n114\n514",
        );
        assert_eq!(
            get_res(&server, "/test-4/114/catch/514/1919/810").await,
            "/catch/514/1919/810\n114\n514/1919/810",
        );
    }

    #[tokio::test]
    async fn deep_nest_router() {
        async fn uri_and_params(uri: Uri, params: PathParamsVec) -> String {
            let mut v = vec![FastStr::from_string(uri.to_string())];
            v.extend(params.into_iter().map(|(_, v)| v));
            v.join("\n")
        }
        async fn get_res(
            server: &TestServer<Router<Option<Body>>, Option<Body>>,
            uri: &str,
        ) -> String {
            server
                .call_route(Method::GET, uri, None)
                .await
                .into_string()
                .await
                .unwrap()
        }

        // rule: `/test-1/{catch1}/test-2/{catch2}/test-3/{nest-route}`
        let router: Router<Option<Body>> = Router::new().nest(
            "/test-1/{catch1}",
            Router::new().nest(
                "/test-2/{catch2}/",
                Router::new().nest(
                    "/test-3",
                    Router::new()
                        .route("/", any(uri_and_params))
                        .route("/id/{id}", any(uri_and_params))
                        .route("/catch/{*content}", any(uri_and_params)),
                ),
            ),
        );
        let server = Server::new(router).into_test_server();

        // catch1: 114
        // catch2: 514
        // inner-uri: /
        assert_eq!(
            get_res(&server, "/test-1/114/test-2/514/test-3/").await,
            "/\n114\n514",
        );
        // catch1: 114
        // catch2: 514
        // inner-uri: /id/1919
        // id: 1919
        assert_eq!(
            get_res(&server, "/test-1/114/test-2/514/test-3/id/1919").await,
            "/id/1919\n114\n514\n1919",
        );
        // catch1: 114
        // catch2: 514
        // inner-uri: /id/1919
        // id: 1919
        assert_eq!(
            get_res(&server, "/test-1/114/test-2/514/test-3/catch/1919/810").await,
            "/catch/1919/810\n114\n514\n1919/810",
        );
    }

    #[tokio::test]
    async fn nest_router_with_query() {
        async fn get_query(uri: Uri) -> Result<String, StatusCode> {
            if let Some(query) = uri.query() {
                Ok(query.to_owned())
            } else {
                Err(StatusCode::BAD_REQUEST)
            }
        }
        async fn get_res(
            server: &TestServer<Router<Option<Body>>, Option<Body>>,
            uri: &str,
        ) -> Result<String, StatusCode> {
            let resp = server.call_route(Method::GET, uri, None).await;
            if resp.status().is_success() {
                Ok(resp
                    .into_string()
                    .await
                    .expect("response is not a valid string"))
            } else {
                Err(resp.status())
            }
        }

        let router: Router<Option<Body>> =
            Router::new().nest("/nest", Router::new().route("/query", any(get_query)));
        let server = Server::new(router).into_test_server();

        assert_eq!(
            get_res(&server, "/nest/query?foo=bar").await.unwrap(),
            "foo=bar",
        );
        assert_eq!(get_res(&server, "/nest/query?foo").await.unwrap(), "foo");
        assert_eq!(get_res(&server, "/nest/query?").await.unwrap(), "");
        assert!(get_res(&server, "/nest/query").await.is_err());
    }

    #[tokio::test]
    async fn deep_nest_router_with_query() {
        async fn get_query(uri: Uri) -> Result<String, StatusCode> {
            if let Some(query) = uri.query() {
                Ok(query.to_owned())
            } else {
                Err(StatusCode::BAD_REQUEST)
            }
        }
        async fn get_res(
            server: &TestServer<Router<Option<Body>>, Option<Body>>,
            uri: &str,
        ) -> Result<String, StatusCode> {
            let resp = server.call_route(Method::GET, uri, None).await;
            if resp.status().is_success() {
                Ok(resp
                    .into_string()
                    .await
                    .expect("response is not a valid string"))
            } else {
                Err(resp.status())
            }
        }

        let router: Router<Option<Body>> = Router::new().nest(
            "/nest-1",
            Router::new().nest(
                "/nest-2",
                Router::new().nest("/nest-3", Router::new().route("/query", any(get_query))),
            ),
        );
        let server = Server::new(router).into_test_server();

        assert_eq!(
            get_res(&server, "/nest-1/nest-2/nest-3/query?foo=bar")
                .await
                .unwrap(),
            "foo=bar",
        );
        assert_eq!(
            get_res(&server, "/nest-1/nest-2/nest-3/query?foo")
                .await
                .unwrap(),
            "foo",
        );
        assert_eq!(
            get_res(&server, "/nest-1/nest-2/nest-3/query?")
                .await
                .unwrap(),
            "",
        );
        assert!(
            get_res(&server, "/nest-1/nest-2/nest-3/query")
                .await
                .is_err()
        );
    }
}