rustlavel-http 0.1.1

Rustlavel HTTP server, router, middleware pipeline, request/response
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
//! The router: what an application's `routes/web.rs` fills in.
//!
//! ```ignore
//! pub fn routes(r: &mut Router) {
//!     r.get("/", home);
//!     r.get("/users/{id}", show).name("users.show");
//!
//!     r.group("/admin", |r| {
//!         r.middleware(auth);
//!         r.get("/dashboard", dashboard);
//!     });
//! }
//! ```

use crate::handler::Handler;
use crate::method::Method;
use crate::middleware::{Middleware, Next};
use crate::request::Request;
use crate::response::Response;
use crate::status::Status;
use crate::url;
use std::collections::BTreeMap;
use std::sync::Arc;

/// One piece of a route pattern.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Segment {
    /// A literal path segment.
    Static(String),
    /// `{id}` — matches exactly one segment and captures it.
    Param(String),
    /// `{path:*}` — matches the rest of the path, slashes included.
    Wildcard(String),
}

pub struct Route {
    pub method: Method,
    /// The pattern as written, used for `route:list` and metrics labels.
    pub pattern: String,
    pub name: Option<String>,
    /// What this route does, in one line. Feeds generated API documentation.
    pub summary: Option<String>,
    /// A grouping label, so generated docs are not one flat list.
    pub tag: Option<String>,
    /// Documented responses: status, and what it means.
    pub responses: Vec<(u16, String)>,
    /// Documented parameters: name, and what it is.
    pub parameters: Vec<(String, String)>,
    pub deprecated: bool,
    /// The API version this route belongs to, from [`Router::version`].
    pub version: Option<String>,
    /// When the route was deprecated (unix time), sent as `Deprecation`.
    pub deprecated_at: Option<i64>,
    /// When the route will be removed (unix time), sent as `Sunset`.
    pub sunset: Option<i64>,
    segments: Vec<Segment>,
    handler: Arc<dyn Handler>,
    middleware: Arc<Vec<Arc<dyn Middleware>>>,
}

impl Route {
    /// The parameter names this route captures, in order.
    ///
    /// Generated documentation needs these even when the author documented
    /// none, because a path parameter is required whether or not it is
    /// described.
    pub fn parameter_names(&self) -> Vec<String> {
        self.segments
            .iter()
            .filter_map(|segment| match segment {
                Segment::Param(name) | Segment::Wildcard(name) => Some(name.clone()),
                Segment::Static(_) => None,
            })
            .collect()
    }
}

impl Route {
    /// How specific this route is, so `/users/new` is tried before `/users/{id}`.
    fn specificity(&self) -> (usize, usize) {
        let statics = self.segments.iter().filter(|s| matches!(s, Segment::Static(_))).count();
        let wildcards = self.segments.iter().filter(|s| matches!(s, Segment::Wildcard(_))).count();
        // More static segments first; any wildcard sinks to the bottom.
        (wildcards, usize::MAX - statics)
    }

    fn match_path(&self, path: &str) -> Option<BTreeMap<String, String>> {
        let mut params = BTreeMap::new();
        let mut parts = split_path(path);
        let mut index = 0;

        while index < self.segments.len() {
            match &self.segments[index] {
                Segment::Wildcard(name) => {
                    // Consumes everything that is left, including nothing.
                    let rest = parts.collect::<Vec<_>>().join("/");
                    params.insert(name.clone(), url::decode(&rest));
                    return Some(params);
                }
                Segment::Static(expected) => {
                    if parts.next()? != expected {
                        return None;
                    }
                }
                Segment::Param(name) => {
                    let value = parts.next()?;
                    if value.is_empty() {
                        return None;
                    }
                    params.insert(name.clone(), url::decode(value));
                }
            }
            index += 1;
        }

        // Every pattern segment matched; the path must be exhausted too.
        parts.next().is_none().then_some(params)
    }
}

fn split_path(path: &str) -> impl Iterator<Item = &str> {
    path.split('/').filter(|part| !part.is_empty())
}

fn parse_pattern(pattern: &str) -> Vec<Segment> {
    split_path(pattern)
        .map(|part| match part.strip_prefix('{').and_then(|p| p.strip_suffix('}')) {
            Some(name) => match name.strip_suffix(":*") {
                Some(name) => Segment::Wildcard(name.to_string()),
                None => Segment::Param(name.to_string()),
            },
            None => Segment::Static(part.to_string()),
        })
        .collect()
}

/// Collects routes, then answers requests.
#[derive(Default)]
pub struct Router {
    routes: Vec<Route>,
    /// Prefix and middleware of the group currently being defined.
    scope_prefix: String,
    scope_version: Option<String>,
    scope_middleware: Vec<Arc<dyn Middleware>>,
    /// Runs for every request, whatever the route.
    global_middleware: Vec<Arc<dyn Middleware>>,
    fallback: Option<Arc<dyn Handler>>,
}

impl Router {
    pub fn new() -> Self {
        Self::default()
    }

    /// Add middleware. Inside a `group` it applies to that group's routes;
    /// at the top level it applies to every request, including 404s.
    pub fn middleware(&mut self, middleware: impl Middleware) -> &mut Self {
        if self.scope_prefix.is_empty() && self.scope_middleware.is_empty() {
            self.global_middleware.push(Arc::new(middleware));
        } else {
            self.scope_middleware.push(Arc::new(middleware));
        }
        self
    }

    /// Register routes under a shared prefix and middleware stack.
    pub fn group(&mut self, prefix: &str, define: impl FnOnce(&mut Router)) -> &mut Self {
        let mut child = Router {
            scope_prefix: join_paths(&self.scope_prefix, prefix),
            scope_middleware: self.scope_middleware.clone(),
            scope_version: self.scope_version.clone(),
            ..Router::default()
        };
        define(&mut child);

        // A group's global-looking middleware belongs to that group only.
        debug_assert!(child.global_middleware.is_empty() || !child.routes.is_empty());
        self.routes.extend(child.routes);
        self
    }

    /// Register one version of an API: a group under `/{version}` whose routes
    /// know which version they are.
    ///
    /// ```ignore
    /// r.version("v1", |v1| { v1.get("/users", v1::users::index); });
    /// r.version("v2", |v2| { v2.get("/users", v2::users::index); });
    /// ```
    ///
    /// A handler can read the version with `req.api_version()`, which lets one
    /// handler serve two versions where the difference is small, and generated
    /// documentation groups routes by it. Versioning by header instead of path
    /// is [`crate::versioning::VersionHeader`].
    pub fn version(&mut self, version: &str, define: impl FnOnce(&mut Router)) -> &mut Self {
        let mut child = Router {
            scope_prefix: join_paths(&self.scope_prefix, &format!("/{}", version.trim_start_matches('/'))),
            scope_middleware: self.scope_middleware.clone(),
            scope_version: Some(version.trim_start_matches('/').to_string()),
            ..Router::default()
        };
        define(&mut child);
        self.routes.extend(child.routes);
        self
    }

    /// The response when nothing matched. Defaults to a plain 404.
    pub fn fallback(&mut self, handler: impl Handler) -> &mut Self {
        self.fallback = Some(Arc::new(handler));
        self
    }

    pub fn route(&mut self, method: Method, pattern: &str, handler: impl Handler) -> RouteHandle<'_> {
        let full = join_paths(&self.scope_prefix, pattern);
        self.routes.push(Route {
            method,
            segments: parse_pattern(&full),
            pattern: full,
            name: None,
            summary: None,
            tag: None,
            responses: Vec::new(),
            parameters: Vec::new(),
            deprecated: false,
            version: self.scope_version.clone(),
            deprecated_at: None,
            sunset: None,
            handler: Arc::new(handler),
            middleware: Arc::new(self.scope_middleware.clone()),
        });
        RouteHandle { index: self.routes.len() - 1, router: self }
    }

    pub fn get(&mut self, pattern: &str, handler: impl Handler) -> RouteHandle<'_> {
        self.route(Method::Get, pattern, handler)
    }

    pub fn post(&mut self, pattern: &str, handler: impl Handler) -> RouteHandle<'_> {
        self.route(Method::Post, pattern, handler)
    }

    pub fn put(&mut self, pattern: &str, handler: impl Handler) -> RouteHandle<'_> {
        self.route(Method::Put, pattern, handler)
    }

    pub fn patch(&mut self, pattern: &str, handler: impl Handler) -> RouteHandle<'_> {
        self.route(Method::Patch, pattern, handler)
    }

    pub fn delete(&mut self, pattern: &str, handler: impl Handler) -> RouteHandle<'_> {
        self.route(Method::Delete, pattern, handler)
    }

    /// Start a RESTful resource: `r.resource("/posts").index(..).show(..)`.
    pub fn resource<'r>(&'r mut self, base: &str) -> Resource<'r> {
        Resource { base: base.trim_end_matches('/').to_string(), router: self }
    }

    /// Sort routes so lookups are deterministic. Called once before serving.
    pub fn finalize(&mut self) {
        self.routes.sort_by_key(Route::specificity);
    }

    pub fn routes(&self) -> &[Route] {
        &self.routes
    }

    /// Build a URL from a named route: `url_for("users.show", &[("id", "7")])`.
    pub fn url_for(&self, name: &str, params: &[(&str, &str)]) -> Option<String> {
        let route = self.routes.iter().find(|route| route.name.as_deref() == Some(name))?;
        let lookup = |key: &str| params.iter().find(|(k, _)| *k == key).map(|(_, v)| *v);

        let mut out = String::new();
        for segment in &route.segments {
            out.push('/');
            match segment {
                Segment::Static(value) => out.push_str(value),
                Segment::Param(name) => out.push_str(&url::encode(lookup(name)?)),
                Segment::Wildcard(name) => out.push_str(lookup(name)?),
            }
        }
        Some(if out.is_empty() { "/".to_string() } else { out })
    }

    /// Match a request and run it through the pipeline.
    pub async fn dispatch(&self, mut request: Request) -> Response {
        let path = request.path().to_string();
        let mut path_matched = false;
        let mut allowed = Vec::new();

        for route in &self.routes {
            let Some(params) = route.match_path(&path) else { continue };
            path_matched = true;

            // HEAD is served by the GET route, minus the body.
            let usable = route.method == request.method()
                || (request.method() == Method::Head && route.method == Method::Get);

            if !usable {
                allowed.push(route.method);
                continue;
            }

            request.set_params(params);
            request.route = Some(route.pattern.clone());
            if let Some(version) = &route.version {
                request.extend(crate::versioning::ApiVersion(version.clone()));
            }

            let mut stack = self.global_middleware.clone();
            stack.extend(route.middleware.iter().cloned());
            let response =
                run_guarded(Next::new(Arc::new(stack), Arc::clone(&route.handler)), request).await;
            return crate::versioning::stamp_lifecycle(route, response);
        }

        let response = if path_matched {
            // The path exists but not for this verb: 405, and say what is allowed.
            allowed.sort();
            allowed.dedup();
            let allow = allowed.iter().map(|m| m.as_str()).collect::<Vec<_>>().join(", ");
            Response::new(Status::METHOD_NOT_ALLOWED).with_header("allow", allow).with_text(format!(
                "{} is not allowed on {path}",
                request.method()
            ))
        } else {
            match &self.fallback {
                Some(handler) => {
                    let stack = Arc::new(self.global_middleware.clone());
                    return Next::new(stack, Arc::clone(handler)).run(request).await;
                }
                None => Response::not_found(),
            }
        };

        // Global middleware still observes unmatched requests, so logging and
        // Telescope see the 404s too.
        let stack = Arc::new(self.global_middleware.clone());
        let endpoint: Arc<dyn Handler> = Arc::new(crate::handler::Fixed(response));
        Next::new(stack, endpoint).run(request).await
    }
}

/// Run the pipeline, turning a panic into the error page.
///
/// This lives at the router rather than in the server so a panicking handler
/// fails the same way in a test as it does in production — a test that would
/// otherwise abort the whole run instead reports a 500.
async fn run_guarded(next: Next, request: Request) -> Response {
    crate::panic::install_hook();
    let started = std::time::Instant::now();

    // A panicking handler still needs to render a page describing the request,
    // but the request itself has been moved into the pipeline by then.
    let probe = Request::new(request.method(), request.target().to_string())
        .with_header("accept", request.header("accept").unwrap_or("text/html"));
    let route = request.route().map(str::to_string);

    let response = match crate::panic::catch(next.run(request)).await {
        Ok(response) => response,
        Err(message) => {
            let location = crate::panic::take_location().map(|l| (l.file, l.line));
            rustlavel_core::error!(
                "panic in {} {}: {message}",
                probe.method(),
                probe.path()
            );
            crate::error_page::render(
                &crate::error_page::Diagnostic::from_panic(message, location),
                Some(&probe),
            )
        }
    };

    // Dispatched here rather than in the server, so instrumentation sees the
    // same events under the test client as it does over a socket.
    if rustlavel_core::events::has_subscribers() {
        let mut event = rustlavel_core::Event::new("http.request")
            .with("method", probe.method().as_str())
            .with("path", probe.path())
            .with("status", response.status.code())
            .took(started.elapsed());
        if let Some(route) = route {
            // The pattern, not the path: one metric series per route, not per id.
            event = event.with("route", route);
        }
        // Read from the response rather than the request, which the pipeline
        // has consumed by now; the middleware puts it there for exactly this.
        if let Some(id) = response.headers.get(crate::request_id::HEADER) {
            event = event.with("request_id", id);
        }
        event.dispatch();
    }

    response
}

/// Returned by `get`/`post`/… so a route can be named after registration.
pub struct RouteHandle<'r> {
    index: usize,
    router: &'r mut Router,
}

impl RouteHandle<'_> {
    /// Name the route for `url_for` and `route:list`.
    pub fn name(self, name: &str) -> Self {
        self.router.routes[self.index].name = Some(name.to_string());
        self
    }

    /// Say what this route does, in one line.
    ///
    /// Documentation is attached here rather than kept in a separate file, so
    /// it cannot drift away from the route it describes.
    pub fn describe(self, summary: &str) -> Self {
        self.router.routes[self.index].summary = Some(summary.to_string());
        self
    }

    /// Group this route under a heading in generated documentation.
    pub fn tag(self, tag: &str) -> Self {
        self.router.routes[self.index].tag = Some(tag.to_string());
        self
    }

    /// Document a response this route can return.
    pub fn responds(self, status: u16, description: &str) -> Self {
        self.router.routes[self.index].responses.push((status, description.to_string()));
        self
    }

    /// Describe a parameter. Undescribed path parameters are still documented,
    /// just without prose.
    pub fn param(self, name: &str, description: &str) -> Self {
        self.router.routes[self.index]
            .parameters
            .push((name.to_string(), description.to_string()));
        self
    }

    /// Mark the route as deprecated in generated documentation.
    pub fn deprecated(self) -> Self {
        self.router.routes[self.index].deprecated = true;
        self
    }

    /// Say when the route was deprecated, as `YYYY-MM-DD`.
    ///
    /// Responses then carry `Deprecation: @<unix time>` (RFC 9745), which is
    /// how a client library learns to warn its own developers. Implies
    /// [`RouteHandle::deprecated`].
    ///
    /// # Panics
    ///
    /// On a date that is not `YYYY-MM-DD` — this is called at startup, with a
    /// literal, and a typo should fail there rather than send garbage.
    pub fn deprecated_at(self, date: &str) -> Self {
        let when = crate::date::parse_ymd(date)
            .unwrap_or_else(|| panic!("`{date}` is not a date; deprecated_at wants YYYY-MM-DD"));
        let route = &mut self.router.routes[self.index];
        route.deprecated = true;
        route.deprecated_at = Some(when);
        self
    }

    /// Say when the route will stop working, as `YYYY-MM-DD`.
    ///
    /// Responses then carry `Sunset` (RFC 8594) with that date, and the route
    /// is marked deprecated. Nothing removes the route on the day — that is a
    /// deploy, and a person's decision — but every client has been told.
    ///
    /// # Panics
    ///
    /// On a date that is not `YYYY-MM-DD`, for the reason given on
    /// [`RouteHandle::deprecated_at`].
    pub fn sunset(self, date: &str) -> Self {
        let when = crate::date::parse_ymd(date)
            .unwrap_or_else(|| panic!("`{date}` is not a date; sunset wants YYYY-MM-DD"));
        let route = &mut self.router.routes[self.index];
        route.deprecated = true;
        route.sunset = Some(when);
        self
    }
}

/// The seven RESTful routes, registered one at a time.
pub struct Resource<'r> {
    base: String,
    router: &'r mut Router,
}

impl Resource<'_> {
    /// `GET /posts`
    pub fn index(self, handler: impl Handler) -> Self {
        let (base, router) = (self.base.clone(), self.router);
        router.get(&base, handler).name(&format!("{}.index", resource_name(&base)));
        Resource { base, router }
    }

    /// `POST /posts`
    pub fn store(self, handler: impl Handler) -> Self {
        let (base, router) = (self.base.clone(), self.router);
        router.post(&base, handler).name(&format!("{}.store", resource_name(&base)));
        Resource { base, router }
    }

    /// `GET /posts/{id}`
    pub fn show(self, handler: impl Handler) -> Self {
        let (base, router) = (self.base.clone(), self.router);
        let pattern = format!("{base}/{{id}}");
        router.get(&pattern, handler).name(&format!("{}.show", resource_name(&base)));
        Resource { base, router }
    }

    /// `PUT /posts/{id}`
    pub fn update(self, handler: impl Handler) -> Self {
        let (base, router) = (self.base.clone(), self.router);
        let pattern = format!("{base}/{{id}}");
        router.put(&pattern, handler).name(&format!("{}.update", resource_name(&base)));
        Resource { base, router }
    }

    /// `DELETE /posts/{id}`
    pub fn destroy(self, handler: impl Handler) -> Self {
        let (base, router) = (self.base.clone(), self.router);
        let pattern = format!("{base}/{{id}}");
        router.delete(&pattern, handler).name(&format!("{}.destroy", resource_name(&base)));
        Resource { base, router }
    }
}

fn resource_name(base: &str) -> String {
    base.trim_matches('/').replace('/', ".")
}

fn join_paths(prefix: &str, path: &str) -> String {
    let joined = format!("/{}/{}", prefix.trim_matches('/'), path.trim_matches('/'));
    let cleaned = joined.replace("//", "/");
    if cleaned.len() > 1 { cleaned.trim_end_matches('/').to_string() } else { "/".to_string() }
}

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

    async fn ok(_req: Request) -> &'static str {
        "ok"
    }

    fn router_with(define: impl FnOnce(&mut Router)) -> Router {
        let mut router = Router::new();
        define(&mut router);
        router.finalize();
        router
    }

    #[tokio::test]
    async fn matches_static_and_parameter_routes() {
        let router = router_with(|r| {
            r.get("/", ok);
            r.get("/users/{id}", |req: Request| async move {
                format!("user {}", req.param("id").unwrap())
            });
        });

        assert_eq!(router.dispatch(Request::new(Method::Get, "/")).await.body_string(), "ok");
        assert_eq!(
            router.dispatch(Request::new(Method::Get, "/users/7")).await.body_string(),
            "user 7"
        );
        assert_eq!(
            router.dispatch(Request::new(Method::Get, "/nope")).await.status,
            Status::NOT_FOUND
        );
    }

    #[tokio::test]
    async fn static_segments_win_over_parameters() {
        let router = router_with(|r| {
            r.get("/users/{id}", |_req: Request| async { "param" });
            r.get("/users/new", |_req: Request| async { "static" });
        });

        assert_eq!(
            router.dispatch(Request::new(Method::Get, "/users/new")).await.body_string(),
            "static"
        );
        assert_eq!(
            router.dispatch(Request::new(Method::Get, "/users/12")).await.body_string(),
            "param"
        );
    }

    #[tokio::test]
    async fn wildcards_capture_the_remaining_path() {
        let router = router_with(|r| {
            r.get("/files/{path:*}", |req: Request| async move {
                req.param("path").unwrap_or_default().to_string()
            });
        });

        let response = router.dispatch(Request::new(Method::Get, "/files/css/app.css")).await;
        assert_eq!(response.body_string(), "css/app.css");
    }

    #[tokio::test]
    async fn parameters_are_percent_decoded() {
        let router = router_with(|r| {
            r.get("/tags/{tag}", |req: Request| async move { req.param("tag").unwrap().to_string() });
        });

        let response = router.dispatch(Request::new(Method::Get, "/tags/rust%20lang")).await;
        assert_eq!(response.body_string(), "rust lang");
    }

    #[tokio::test]
    async fn wrong_method_reports_405_with_allow() {
        let router = router_with(|r| {
            r.post("/users", ok);
        });

        let response = router.dispatch(Request::new(Method::Get, "/users")).await;
        assert_eq!(response.status, Status::METHOD_NOT_ALLOWED);
        assert_eq!(response.headers.get("allow"), Some("POST"));
    }

    #[tokio::test]
    async fn head_is_served_by_the_get_route() {
        let router = router_with(|r| {
            r.get("/", ok);
        });

        assert_eq!(router.dispatch(Request::new(Method::Head, "/")).await.status, Status::OK);
    }

    #[tokio::test]
    async fn groups_apply_prefix_and_middleware() {
        let router = router_with(|r| {
            r.group("/admin", |r| {
                r.middleware(|req: Request, next: Next| async move {
                    next.run(req).await.with_header("x-guard", "on")
                });
                r.get("/dashboard", ok);
            });
            r.get("/public", ok);
        });

        let guarded = router.dispatch(Request::new(Method::Get, "/admin/dashboard")).await;
        assert_eq!(guarded.headers.get("x-guard"), Some("on"));

        let open = router.dispatch(Request::new(Method::Get, "/public")).await;
        assert_eq!(open.headers.get("x-guard"), None);
    }

    #[tokio::test]
    async fn global_middleware_also_sees_unmatched_requests() {
        let router = router_with(|r| {
            r.middleware(|req: Request, next: Next| async move {
                next.run(req).await.with_header("x-seen", "1")
            });
            r.get("/", ok);
        });

        let missing = router.dispatch(Request::new(Method::Get, "/nope")).await;
        assert_eq!(missing.status, Status::NOT_FOUND);
        assert_eq!(missing.headers.get("x-seen"), Some("1"));
    }

    #[test]
    fn builds_urls_from_named_routes() {
        let router = router_with(|r| {
            r.get("/users/{id}/posts/{slug}", ok).name("users.posts");
        });

        assert_eq!(
            router.url_for("users.posts", &[("id", "7"), ("slug", "hello world")]).as_deref(),
            Some("/users/7/posts/hello%20world")
        );
        assert_eq!(router.url_for("users.posts", &[("id", "7")]), None);
        assert_eq!(router.url_for("missing", &[]), None);
    }

    #[tokio::test]
    async fn resource_registers_the_rest_routes() {
        let router = router_with(|r| {
            r.resource("/posts").index(ok).store(ok).show(ok).update(ok).destroy(ok);
        });

        assert_eq!(router.routes().len(), 5);
        assert_eq!(router.url_for("posts.show", &[("id", "3")]).as_deref(), Some("/posts/3"));
        assert_eq!(router.dispatch(Request::new(Method::Delete, "/posts/3")).await.status, Status::OK);
    }

    #[tokio::test]
    async fn fallback_replaces_the_default_404() {
        let router = router_with(|r| {
            r.fallback(|_req: Request| async { (404, "custom miss") });
        });

        let response = router.dispatch(Request::new(Method::Get, "/anything")).await;
        assert_eq!(response.body_string(), "custom miss");
    }

    #[test]
    fn documentation_rides_along_with_the_route() {
        let router = router_with(|r| {
            r.get("/users/{id}", ok)
                .name("users.show")
                .describe("Fetch one user")
                .tag("Users")
                .param("id", "The user's id")
                .responds(200, "The user")
                .responds(404, "No such user");
        });

        let route = &router.routes()[0];
        assert_eq!(route.summary.as_deref(), Some("Fetch one user"));
        assert_eq!(route.tag.as_deref(), Some("Users"));
        assert_eq!(route.responses.len(), 2);
        assert_eq!(route.parameter_names(), vec!["id"]);
        assert!(!route.deprecated);
    }

    #[test]
    fn path_parameters_are_known_even_when_undocumented() {
        let router = router_with(|r| {
            r.get("/teams/{team}/members/{member}", ok);
            r.get("/files/{path:*}", ok);
        });

        let names: Vec<Vec<String>> =
            router.routes().iter().map(Route::parameter_names).collect();
        assert!(names.contains(&vec!["team".to_string(), "member".to_string()]));
        assert!(names.contains(&vec!["path".to_string()]));
    }

    #[test]
    fn joins_prefixes_without_doubling_slashes() {
        assert_eq!(join_paths("/admin/", "/users"), "/admin/users");
        assert_eq!(join_paths("", "/"), "/");
        assert_eq!(join_paths("/admin", ""), "/admin");
    }
}