Skip to main content

renox_core/
routing.rs

1use std::collections::HashMap;
2use std::fmt::{Display, Write};
3
4use std::convert::Infallible;
5
6use anyhow::{anyhow, bail};
7use axum::Router;
8use axum::extract::Request;
9use axum::handler::Handler;
10use axum::middleware::from_fn;
11use axum::response::IntoResponse;
12use axum::routing::{self, MethodRouter, Route};
13use tower::{Layer, Service};
14
15use crate::AppState;
16
17/// A module's routes, with optional names for URL generation.
18///
19/// ```
20/// # use renox::prelude::*;
21/// # async fn index() {}
22/// # async fn show() {}
23/// # async fn store() {}
24/// # let _ =
25/// Routes::new()
26///     .get("/products", index).name("products.index")
27///     .get("/products/{id}", show).name("products.show")
28///     .post("/products", store).name("products.store")
29/// # ;
30/// ```
31#[derive(Default)]
32pub struct Routes {
33    router: Router<AppState>,
34    names: Vec<(String, String)>,
35    last_path: Option<String>,
36    listing: Vec<RouteInfo>,
37    fallback: Option<MethodRouter<AppState>>,
38    domains: Vec<(String, Routes)>,
39}
40
41/// What a module's `Routes` hold, for `App::boot`.
42pub(crate) struct RouteParts {
43    pub router: Router<AppState>,
44    pub names: Vec<(String, String)>,
45    pub listing: Vec<RouteInfo>,
46    pub fallback: Option<MethodRouter<AppState>>,
47    pub domains: Vec<(String, Routes)>,
48}
49
50/// One route as `route:list` shows it.
51#[derive(Debug, Clone, PartialEq, Eq)]
52#[non_exhaustive]
53pub struct RouteInfo {
54    /// `GET`, `POST`, … or `*` for a `route()` whose methods Renox can't see.
55    pub method: String,
56    /// The path pattern, e.g. `/posts/{id}`.
57    pub path: String,
58    /// The route's name, if it has one.
59    pub name: Option<String>,
60    /// The module that defined it, or `renox` for the framework's own.
61    pub module: String,
62    /// Guards and limits, e.g. `auth`, `throttle:60/60s`.
63    pub middleware: Vec<String>,
64    /// The host pattern of a `Routes::domain` route, e.g. `admin.example.com`.
65    pub domain: Option<String>,
66}
67
68macro_rules! method {
69    ($($method:ident),*) => {$(
70        /// Adds a route for this HTTP method (the function's name) at `path`.
71        pub fn $method<H, T>(self, path: &str, handler: H) -> Self
72        where
73            H: Handler<T, AppState>,
74            T: 'static,
75        {
76            self.add(path, routing::$method(handler), &stringify!($method).to_uppercase())
77        }
78    )*};
79}
80
81impl Routes {
82    /// An empty set of routes.
83    pub fn new() -> Self {
84        Self::default()
85    }
86
87    method!(get, post, put, patch, delete);
88
89    /// The routes of a resource, like Laravel's `Route::resource`: only the
90    /// actions given, under `path`, named `{name}.{action}`.
91    ///
92    /// | Action | Method and path | Name |
93    /// |---|---|---|
94    /// | `index` | `GET /products` | `products.index` |
95    /// | `create` | `GET /products/new` | `products.create` |
96    /// | `store` | `POST /products` | `products.store` |
97    /// | `show` | `GET /products/{id}` | `products.show` |
98    /// | `edit` | `GET /products/{id}/edit` | `products.edit` |
99    /// | `update` | `PUT` and `PATCH /products/{id}` | `products.update` |
100    /// | `destroy` | `DELETE /products/{id}` | `products.destroy` |
101    ///
102    /// ```
103    /// # use renox::prelude::*;
104    /// # use renox::Resource;
105    /// # async fn index() -> &'static str { "" }
106    /// # async fn show(Path(id): Path<i64>) -> String { id.to_string() }
107    /// # async fn destroy(Path(id): Path<i64>) -> String { id.to_string() }
108    /// # let _: Routes =
109    /// Routes::new()
110    ///     .resource("/products", "products", Resource::new().index(index).show(show).destroy(destroy))
111    ///     .require_auth()
112    /// # ;
113    /// ```
114    pub fn resource(mut self, path: &str, name: &str, resource: Resource) -> Self {
115        assert!(
116            path.starts_with('/') && !path.ends_with('/'),
117            "Routes::resource(\"{path}\", …): the path must start with `/` and not end with one"
118        );
119        let member = format!("{path}/{{id}}");
120        let actions = [
121            ("index", "GET", path.to_owned(), resource.index),
122            ("create", "GET", format!("{path}/new"), resource.create),
123            ("store", "POST", path.to_owned(), resource.store),
124            ("show", "GET", member.clone(), resource.show),
125            ("edit", "GET", format!("{member}/edit"), resource.edit),
126            ("update", "PUT", member.clone(), resource.update),
127            ("destroy", "DELETE", member, resource.destroy),
128        ];
129        for (action, method, at, router) in actions {
130            if let Some(router) = router {
131                let method = if action == "update" {
132                    "PUT|PATCH"
133                } else {
134                    method
135                };
136                self = self
137                    .add(&at, router, method)
138                    .name(&format!("{name}.{action}"));
139            }
140        }
141        self
142    }
143
144    /// Adds a route with any axum method router, e.g. `get(show).post(update)`.
145    pub fn route(self, path: &str, method_router: MethodRouter<AppState>) -> Self {
146        self.add(path, method_router, "*")
147    }
148
149    /// A page that needs no handler: `GET path` renders `template` with the
150    /// usual globals (Laravel's `Route::view`), e.g. an "About" page.
151    ///
152    /// ```
153    /// # use renox::prelude::*;
154    /// # let _: Routes =
155    /// Routes::new().view("/about", "pages/about.html").name("about")
156    /// # ;
157    /// ```
158    pub fn view(self, path: &str, template: &str) -> Self {
159        let template = template.to_owned();
160        self.add(
161            path,
162            axum::routing::get(move || {
163                let template = template.clone();
164                async move { crate::view(&template, minijinja::context! {}) }
165            }),
166            "GET",
167        )
168    }
169
170    /// Sends `path` to `to` with a 302 (Laravel's `Route::redirect`), e.g.
171    /// an old address.
172    pub fn redirect(self, path: &str, to: &str) -> Self {
173        let to = to.to_owned();
174        self.add(
175            path,
176            axum::routing::any(move || {
177                let to = to.clone();
178                async move { redirect_with(axum::http::StatusCode::FOUND, &to) }
179            }),
180            "*",
181        )
182    }
183
184    /// Like [`redirect`](Self::redirect), with a 301: the move is permanent.
185    pub fn permanent_redirect(self, path: &str, to: &str) -> Self {
186        let to = to.to_owned();
187        self.add(
188            path,
189            axum::routing::any(move || {
190                let to = to.clone();
191                async move { redirect_with(axum::http::StatusCode::MOVED_PERMANENTLY, &to) }
192            }),
193            "*",
194        )
195    }
196
197    fn add(mut self, path: &str, method_router: MethodRouter<AppState>, method: &str) -> Self {
198        self.router = self.router.route(path, method_router);
199        self.last_path = Some(path.to_owned());
200        self.listing.push(RouteInfo {
201            method: method.to_owned(),
202            path: path.to_owned(),
203            name: None,
204            module: String::new(),
205            middleware: Vec::new(),
206            domain: None,
207        });
208        self
209    }
210
211    /// Notes a layer on every route added so far, for `route:list`.
212    fn mark(mut self, middleware: &str) -> Self {
213        for route in &mut self.listing {
214            route.middleware.push(middleware.to_owned());
215        }
216        self
217    }
218
219    /// Names the route added just before, for use with `url()` and `route()` in templates.
220    ///
221    /// # Panics
222    ///
223    /// If no route has been added yet.
224    pub fn name(mut self, name: &str) -> Self {
225        let path = self
226            .last_path
227            .clone()
228            .expect("Routes::name() must follow a route");
229        self.names.push((name.to_owned(), path));
230        // A name belongs to a path, so it also covers the methods added just
231        // before for the same path (`.get(p, a).post(p, b).name(n)`) that
232        // don't have a name of their own.
233        let path = self.last_path.clone();
234        for route in self.listing.iter_mut().rev() {
235            if Some(&route.path) != path.as_ref() {
236                break;
237            }
238            if route.name.is_none() {
239                route.name = Some(name.to_owned());
240            }
241        }
242        self
243    }
244
245    /// Only logged-in users may use the routes added so far; guests are sent
246    /// to the `login` route. Call it after adding the routes it should cover.
247    pub fn require_auth(self) -> Self {
248        self.route_layer(from_fn(crate::auth::require_auth))
249            .mark("auth")
250    }
251
252    /// Like `require_auth`, and the user must have verified their email;
253    /// others are sent to the `verification.notice` route.
254    pub fn require_verified(self) -> Self {
255        self.route_layer(from_fn(crate::auth::require_verified))
256            .mark("verified")
257    }
258
259    /// Only users the gate `name` lets through (`App::gate`, `gate_async` or
260    /// a permission of that name, after `gate_before`) may use the routes
261    /// added so far; guests are sent to log in, others get 403.
262    pub fn require_gate(self, name: &str) -> Self {
263        self.requirement(
264            crate::auth::Requirement::Gate(name.to_owned()),
265            "gate",
266            name,
267        )
268    }
269
270    /// Only users with `role` (the `Permissions` module) may use the routes
271    /// added so far; guests are sent to log in, others get 403.
272    pub fn require_role(self, role: &str) -> Self {
273        self.requirement(
274            crate::auth::Requirement::Role(role.to_owned()),
275            "role",
276            role,
277        )
278    }
279
280    /// Only users granted `permission` (the `Permissions` module, after
281    /// `gate_before`) may use the routes added so far.
282    pub fn require_permission(self, permission: &str) -> Self {
283        self.requirement(
284            crate::auth::Requirement::Permission(permission.to_owned()),
285            "permission",
286            permission,
287        )
288    }
289
290    /// Requests with an API token must have `ability`
291    /// (`User::create_token_with`); sessions and unrestricted tokens pass.
292    pub fn require_ability(self, ability: &str) -> Self {
293        self.requirement(
294            crate::auth::Requirement::Ability(ability.to_owned()),
295            "ability",
296            ability,
297        )
298    }
299
300    /// Only requests that authenticated as a device (`Authorization: Bearer`
301    /// with a `DeviceToken`) may use the routes added so far; others get 401
302    /// as JSON. Users and guests are not devices.
303    pub fn require_device(self) -> Self {
304        self.device_guard(None, "device")
305    }
306
307    /// Like `require_device`, and the device's token must have `ability`
308    /// (403 otherwise).
309    pub fn require_device_ability(self, ability: &str) -> Self {
310        self.device_guard(Some(ability), &format!("device:{ability}"))
311    }
312
313    fn device_guard(self, ability: Option<&str>, mark: &str) -> Self {
314        let ability = ability.map(|a| std::sync::Arc::new(a.to_owned()));
315        self.route_layer(from_fn(
316            move |req: Request, next: axum::middleware::Next| {
317                crate::auth::device_guard(ability.clone(), req, next)
318            },
319        ))
320        .mark(mark)
321    }
322
323    fn requirement(self, requirement: crate::auth::Requirement, kind: &str, name: &str) -> Self {
324        let requirement = std::sync::Arc::new(requirement);
325        self.route_layer(from_fn(
326            move |req: Request, next: axum::middleware::Next| {
327                crate::auth::require(requirement.clone(), req, next)
328            },
329        ))
330        .mark(&format!("{kind}:{name}"))
331    }
332
333    /// Users who haven't typed their password in the last three hours are
334    /// asked for it (`/confirm-password`, from the `Auth` module) before the
335    /// routes added so far, e.g. billing settings. Also marks `auth`.
336    pub fn require_password_confirmed(self) -> Self {
337        self.route_layer(from_fn(crate::auth::require_password_confirmed))
338            .route_layer(from_fn(crate::auth::require_auth))
339            .mark("password.confirm")
340    }
341
342    /// Only guests may use the routes added so far; logged-in users are sent
343    /// to the `home` route (e.g. for login and registration pages).
344    pub fn guest_only(self) -> Self {
345        self.route_layer(from_fn(crate::auth::guest_only))
346            .mark("guest")
347    }
348
349    /// Limits the routes added so far to `max` requests per `per`, counted per
350    /// logged-in user or per IP address. Over the limit: 429 with `Retry-After`.
351    pub fn throttle(self, max: u32, per: std::time::Duration) -> Self {
352        let covered: Vec<String> = self
353            .listing
354            .iter()
355            .map(|route| format!("{} {}", route.method, route.path))
356            .collect();
357        let id =
358            crate::webhook::sha256_hex(format!("{}|{max}|{}", covered.join(","), per.as_secs()));
359        let limiter = std::sync::Arc::new(crate::rate_limit::Limiter::new(
360            id[..16].to_owned(),
361            max,
362            per,
363        ));
364        self.route_layer(from_fn(
365            move |req: Request, next: axum::middleware::Next| {
366                let limiter = limiter.clone();
367                async move { crate::rate_limit::check(&limiter, req, next).await }
368            },
369        ))
370        .mark(&format!("throttle:{max}/{}s", per.as_secs()))
371    }
372
373    /// Limits the routes added so far with the named limiter `name`
374    /// (`App::rate_limiter`), whose rule picks the limit per request.
375    pub fn throttle_by(self, name: &str) -> Self {
376        let owned = name.to_owned();
377        self.route_layer(from_fn(
378            move |req: Request, next: axum::middleware::Next| {
379                let name = owned.clone();
380                async move { crate::rate_limit::check_named(&name, req, next).await }
381            },
382        ))
383        .mark(&format!("throttle:{name}"))
384    }
385
386    /// Receives `W`'s webhooks at `path` (POST): verifies, stores once per
387    /// event and processes them in the queue. See `renox::webhook`. The
388    /// route is named `webhooks.<provider>`, skips CSRF and keeps working in
389    /// maintenance mode.
390    pub fn webhook<W: crate::webhook::Webhook>(self, path: &str) -> Self {
391        let mut routes = self
392            .post(path, crate::webhook::receive::<W>)
393            .name(&format!("webhooks.{}", W::PROVIDER));
394        if let Some(route) = routes.listing.last_mut() {
395            route.middleware.push("no-csrf".into());
396            route.middleware.push(format!("webhook:{}", W::PROVIDER));
397        }
398        routes
399    }
400
401    /// Gives the routes added so far an `ETag` (a hash of the page as sent),
402    /// and answers `304 Not Modified` without the body when the browser
403    /// already has that version (`If-None-Match`). For pages fetched again
404    /// and again that rarely change, e.g. a catalogue or an API list.
405    /// Only `GET`/`HEAD` answers with status 200 and a body of at most
406    /// 2 MB get one; streamed bodies don't.
407    pub fn etag(self) -> Self {
408        self.route_layer(from_fn(
409            |req: Request, next: axum::middleware::Next| async move {
410                let mut res = next.run(req).await;
411                res.extensions_mut().insert(crate::security::WantsEtag);
412                res
413            },
414        ))
415        .mark("etag")
416    }
417
418    /// Lets the routes added so far be posted to without a CSRF token, for
419    /// callers that have no session, such as a payment gateway's webhook.
420    /// Such a handler must check the request itself (e.g. its signature).
421    pub fn without_csrf(self) -> Self {
422        self.mark("no-csrf")
423    }
424
425    /// Makes the routes added so far safe to replay: a non-`GET` request must
426    /// carry an `Idempotency-Key` header (else 400); the first answer for a
427    /// key is stored and sent again, with `Idempotent-Replayed: true`, for
428    /// the same key and body without running the handler again; the same key
429    /// with a different body is 422; two requests with one key at once run
430    /// the handler once. Answers with a 5xx status are not stored, so the
431    /// client can try again. Keys belong to the user (or the session) and the
432    /// route, and are kept for
433    /// [`DEFAULT_RETENTION`](crate::idempotency::DEFAULT_RETENTION).
434    ///
435    /// Add `.offline()` before `.require_auth()` and similar guards, so
436    /// those run first and nothing is stored for a refused request. See
437    /// [`Routes::offline_with`] for the clock limits.
438    ///
439    /// ```
440    /// # use renox::prelude::*;
441    /// # async fn complete_stop() -> &'static str { "done" }
442    /// # let _: Routes =
443    /// Routes::new()
444    ///     .post("/stops/{id}/complete", complete_stop)
445    ///     .offline()
446    ///     .require_auth()
447    /// # ;
448    /// ```
449    pub fn offline(self) -> Self {
450        self.offline_with(crate::idempotency::Skew::default())
451    }
452
453    /// Like [`Routes::offline`], with the limits for how far a device's clock
454    /// may differ from the server's.
455    ///
456    /// ```
457    /// # use renox::prelude::*;
458    /// use std::time::Duration;
459    /// use renox::idempotency::Skew;
460    /// # async fn complete_stop() -> &'static str { "done" }
461    /// # let _: Routes =
462    /// Routes::new()
463    ///     .post("/stops/{id}/complete", complete_stop)
464    ///     .offline_with(Skew::new().past(Duration::from_secs(72 * 3600)))
465    /// # ;
466    /// ```
467    pub fn offline_with(self, skew: crate::idempotency::Skew) -> Self {
468        self.route_layer(from_fn(
469            move |req: Request, next: axum::middleware::Next| async move {
470                crate::idempotency::middleware(skew, req, next).await
471            },
472        ))
473        .mark("offline")
474    }
475
476    /// Lets browsers on `origins` (e.g. `https://app.example.com`, or `*`
477    /// for any) call the routes added so far with `fetch`: answers CORS
478    /// preflights and adds the `Access-Control-Allow-*` headers. Allows the
479    /// usual methods and the `Content-Type`, `Authorization`, `Accept` and
480    /// `X-CSRF-Token` headers. Use `cors_layer` for anything else.
481    pub fn cors(self, origins: &[&str]) -> Self {
482        use axum::http::{HeaderName, HeaderValue, Method, header};
483        use tower_http::cors::{AllowOrigin, CorsLayer};
484
485        let origin = if origins.contains(&"*") {
486            AllowOrigin::any()
487        } else {
488            AllowOrigin::list(
489                origins
490                    .iter()
491                    .filter_map(|o| HeaderValue::from_str(o.trim_end_matches('/')).ok()),
492            )
493        };
494        let layer = CorsLayer::new()
495            .allow_origin(origin)
496            .allow_methods([
497                Method::GET,
498                Method::POST,
499                Method::PUT,
500                Method::PATCH,
501                Method::DELETE,
502                Method::OPTIONS,
503            ])
504            .allow_headers([
505                header::CONTENT_TYPE,
506                header::AUTHORIZATION,
507                header::ACCEPT,
508                HeaderName::from_static(crate::CSRF_HEADER),
509            ])
510            .max_age(std::time::Duration::from_secs(3600));
511        self.cors_layer(layer)
512    }
513
514    /// Like `cors`, with a `tower_http::cors::CorsLayer` built by hand
515    /// (`renox::cors::CorsLayer`), e.g. to allow credentials.
516    pub fn cors_layer(mut self, layer: tower_http::cors::CorsLayer) -> Self {
517        // `layer`, not `route_layer`: preflights use OPTIONS, which the
518        // routes themselves don't handle.
519        self.router = self.router.layer(layer);
520        self.mark("cors")
521    }
522
523    /// Wraps the routes added so far in a tower layer (axum's `route_layer`).
524    pub fn route_layer<L>(mut self, layer: L) -> Self
525    where
526        L: Layer<Route> + Clone + Send + Sync + 'static,
527        L::Service: Service<Request> + Clone + Send + Sync + 'static,
528        <L::Service as Service<Request>>::Response: IntoResponse + 'static,
529        <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
530        <L::Service as Service<Request>>::Future: Send + 'static,
531    {
532        self.router = self.router.route_layer(layer);
533        self
534    }
535
536    /// Adds the routes of `other`, with their names and layers.
537    pub fn merge(mut self, other: impl Into<Routes>) -> Self {
538        let other = other.into();
539        self.router = self.router.merge(other.router);
540        self.names.extend(other.names);
541        self.listing.extend(other.listing);
542        self.domains.extend(other.domains);
543        assert!(
544            self.fallback.is_none() || other.fallback.is_none(),
545            "Routes::merge: both sides have a fallback"
546        );
547        self.fallback = self.fallback.or(other.fallback);
548        self.last_path = None;
549        self
550    }
551
552    /// What answers a request no route and no public file matches: a page
553    /// of your own instead of the 404 page (Laravel's `Route::fallback`).
554    /// One per app, or per domain inside [`Routes::domain`].
555    ///
556    /// ```
557    /// # use renox::prelude::*;
558    /// async fn missing(uri: axum::http::Uri) -> (StatusCode, String) {
559    ///     (StatusCode::NOT_FOUND, format!("Nothing at {}. Try the search.", uri.path()))
560    /// }
561    /// # let _: Routes =
562    /// Routes::new().fallback(missing)
563    /// # ;
564    /// ```
565    pub fn fallback<H, T>(mut self, handler: H) -> Self
566    where
567        H: Handler<T, AppState>,
568        T: 'static,
569    {
570        assert!(
571            self.fallback.is_none(),
572            "Routes::fallback: these routes have a fallback already"
573        );
574        self.fallback = Some(routing::any(handler));
575        self
576    }
577
578    /// Routes served only on hosts matching `pattern`, e.g.
579    /// `admin.example.com`, or `{account}.example.com` with the account in
580    /// [`DomainParams`](crate::DomainParams) (Laravel's `Route::domain`).
581    ///
582    /// ```
583    /// # use renox::prelude::*;
584    /// # async fn dashboard() {}
585    /// # async fn home() {}
586    /// # let _: Routes =
587    /// Routes::new()
588    ///     .get("/", home) // other hosts
589    ///     .domain(
590    ///         "admin.example.com",
591    ///         Routes::new().get("/", dashboard).name("admin.dashboard").require_auth(),
592    ///     )
593    /// # ;
594    /// ```
595    ///
596    /// A host that matches a domain gets that domain's routes only (all
597    /// modules' routes for that pattern), plus Renox's own (`/health`, the
598    /// scripts, public files); every other host gets the routes without a
599    /// domain. So the same path can mean different pages on different hosts.
600    /// `route()` gives the path, as for other routes. Matching uses the
601    /// `Host` header: behind a proxy, keep it (Caddy and nginx's
602    /// `proxy_set_header Host $host` do).
603    pub fn domain(mut self, pattern: &str, routes: impl Into<Routes>) -> Self {
604        self.domains.push((pattern.to_owned(), routes.into()));
605        self.last_path = None;
606        self
607    }
608
609    /// Adds `routes` under a path prefix and a name prefix, like Laravel's
610    /// `Route::prefix('admin')->name('admin.')->group(…)`. Guards added to
611    /// `routes` cover only them; guards added after the group cover
612    /// everything added so far, as usual.
613    ///
614    /// ```
615    /// # use renox::prelude::*;
616    /// # async fn dashboard() {}
617    /// # async fn users() {}
618    /// # let _ =
619    /// Routes::new().group(
620    ///     "/admin",
621    ///     "admin.",
622    ///     Routes::new()
623    ///         .get("/", dashboard).name("dashboard") // GET /admin, `admin.dashboard`
624    ///         .get("/users", users).name("users")    // GET /admin/users, `admin.users`
625    ///         .require_auth(),
626    /// )
627    /// # ;
628    /// ```
629    ///
630    /// # Panics
631    ///
632    /// If `path` doesn't start with `/` or ends with `/`.
633    pub fn group(mut self, path: &str, name: &str, routes: impl Into<Routes>) -> Self {
634        assert!(
635            path.starts_with('/') && !path.ends_with('/'),
636            "Routes::group(\"{path}\", …): the prefix must start with `/` and not end with one"
637        );
638        let routes = routes.into();
639        assert!(
640            routes.domains.is_empty() && routes.fallback.is_none(),
641            "Routes::group(\"{path}\", …): put `domain` and `fallback` outside path groups"
642        );
643        let join = |inner: &str| {
644            if inner == "/" {
645                path.to_owned()
646            } else {
647                format!("{path}{inner}")
648            }
649        };
650        self.router = self.router.nest(path, routes.router);
651        self.names.extend(
652            routes
653                .names
654                .into_iter()
655                .map(|(route_name, route_path)| (format!("{name}{route_name}"), join(&route_path))),
656        );
657        self.listing
658            .extend(routes.listing.into_iter().map(|info| RouteInfo {
659                path: join(&info.path),
660                name: info.name.map(|route_name| format!("{name}{route_name}")),
661                ..info
662            }));
663        self.last_path = None;
664        self
665    }
666
667    pub(crate) fn into_parts(self) -> RouteParts {
668        RouteParts {
669            router: self.router,
670            names: self.names,
671            listing: self.listing,
672            fallback: self.fallback,
673            domains: self.domains,
674        }
675    }
676}
677
678impl From<Router<AppState>> for Routes {
679    fn from(router: Router<AppState>) -> Self {
680        Self {
681            router,
682            ..Self::default()
683        }
684    }
685}
686
687/// Every named route in the application.
688#[derive(Debug, Default)]
689pub struct RouteTable {
690    paths: HashMap<String, String>,
691    /// The `Routes::domain` pattern of names defined inside one.
692    domains: HashMap<String, String>,
693    /// The methods of each named route, as listed: `GET`, `PUT|PATCH`, `*`.
694    methods: HashMap<String, String>,
695}
696
697impl RouteTable {
698    pub(crate) fn insert(&mut self, name: String, path: String) -> anyhow::Result<()> {
699        if let Some(existing) = self.paths.get(&name) {
700            bail!("route name `{name}` is used for both `{existing}` and `{path}`");
701        }
702        self.paths.insert(name, path);
703        Ok(())
704    }
705
706    /// The path pattern of a named route, e.g. `/products/{id}`.
707    pub fn path(&self, name: &str) -> Option<&str> {
708        self.paths.get(name).map(String::as_str)
709    }
710
711    /// Every route name, in no particular order.
712    #[cfg_attr(not(test), allow(dead_code))]
713    pub(crate) fn names(&self) -> impl Iterator<Item = &str> {
714        self.paths.keys().map(String::as_str)
715    }
716
717    /// Records the methods `name` answers (`GET`, `PUT|PATCH`, `*` for any).
718    pub(crate) fn set_method(&mut self, name: &str, method: &str) {
719        self.methods.insert(name.to_owned(), method.to_owned());
720    }
721
722    /// Records that `name` belongs to the routes of `domain`.
723    pub(crate) fn set_domain(&mut self, name: &str, domain: &str) {
724        self.domains.insert(name.to_owned(), domain.to_owned());
725    }
726
727    /// The name of the route `method` reached at the path pattern `path`
728    /// (axum's `MatchedPath`, e.g. `/products/{id}`) on `domain` (`None` for
729    /// routes without one): several routes can share a path, one per method, such as
730    /// `GET /account` (`account.show`) and `DELETE /account`
731    /// (`account.destroy`). `HEAD` counts as `GET`. Without `method`, or when
732    /// no route names that method, the first name in order.
733    pub(crate) fn name_of(
734        &self,
735        path: &str,
736        domain: Option<&str>,
737        method: Option<&str>,
738    ) -> Option<&str> {
739        let on_path = || {
740            self.paths
741                .iter()
742                .filter(move |(name, p)| {
743                    p.as_str() == path && self.domains.get(*name).map(String::as_str) == domain
744                })
745                .map(|(name, _)| name.as_str())
746        };
747        let wanted = method.map(|m| if m == "HEAD" { "GET" } else { m });
748        let by_method = wanted.and_then(|wanted| {
749            on_path()
750                .filter(|name| {
751                    self.methods.get(*name).is_some_and(|listed| {
752                        listed == "*" || listed.split('|').any(|m| m == wanted)
753                    })
754                })
755                .min()
756        });
757        by_method.or_else(|| on_path().min())
758    }
759
760    /// Builds the URL path of a named route, filling its parameters in order.
761    pub fn url(&self, name: &str, params: &[&dyn Display]) -> anyhow::Result<String> {
762        let pattern = self
763            .path(name)
764            .ok_or_else(|| anyhow!("route `{name}` is not defined"))?;
765        fill(pattern, params).map_err(|err| anyhow!("route `{name}`: {err}"))
766    }
767}
768
769fn fill(pattern: &str, params: &[&dyn Display]) -> anyhow::Result<String> {
770    let mut out = String::with_capacity(pattern.len());
771    let mut params = params.iter();
772    let mut rest = pattern;
773
774    while let Some(start) = rest.find('{') {
775        out.push_str(&rest[..start]);
776        let end = rest[start..]
777            .find('}')
778            .ok_or_else(|| anyhow!("unclosed `{{` in `{pattern}`"))?
779            + start;
780        let placeholder = &rest[start + 1..end];
781        let value = params
782            .next()
783            .ok_or_else(|| anyhow!("missing value for `{{{placeholder}}}`"))?
784            .to_string();
785        encode(&mut out, &value, placeholder.starts_with('*'));
786        rest = &rest[end + 1..];
787    }
788    out.push_str(rest);
789
790    if params.next().is_some() {
791        bail!("too many parameters for `{pattern}`");
792    }
793    Ok(out)
794}
795
796pub(crate) fn encode(out: &mut String, value: &str, keep_slashes: bool) {
797    for byte in value.bytes() {
798        match byte {
799            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
800                out.push(byte as char)
801            }
802            b'/' if keep_slashes => out.push('/'),
803            _ => {
804                let _ = write!(out, "%{byte:02X}");
805            }
806        }
807    }
808}
809
810#[cfg(test)]
811mod tests {
812    use super::*;
813
814    fn table() -> RouteTable {
815        let mut t = RouteTable::default();
816        t.insert("home".into(), "/".into()).unwrap();
817        t.insert("products.show".into(), "/products/{id}".into())
818            .unwrap();
819        t.insert("docs".into(), "/docs/{*path}".into()).unwrap();
820        t
821    }
822
823    #[test]
824    fn builds_urls() {
825        let t = table();
826        assert_eq!(t.url("home", &[]).unwrap(), "/");
827        assert_eq!(t.url("products.show", &[&42]).unwrap(), "/products/42");
828        assert_eq!(
829            t.url("products.show", &[&"a b/c"]).unwrap(),
830            "/products/a%20b%2Fc"
831        );
832        assert_eq!(
833            t.url("docs", &[&"guide/intro"]).unwrap(),
834            "/docs/guide/intro"
835        );
836    }
837
838    #[test]
839    fn rejects_bad_calls() {
840        let t = table();
841        assert!(t.url("missing", &[]).is_err());
842        assert!(t.url("products.show", &[]).is_err());
843        assert!(t.url("home", &[&1]).is_err());
844    }
845
846    #[test]
847    fn rejects_duplicate_names() {
848        let mut t = table();
849        assert!(t.insert("home".into(), "/home".into()).is_err());
850    }
851}
852
853/// The handlers of a resource, for [`Routes::resource`]; leave out the
854/// actions it doesn't have.
855#[derive(Default)]
856#[must_use = "a resource does nothing until given to Routes::resource"]
857pub struct Resource {
858    index: Option<MethodRouter<AppState>>,
859    create: Option<MethodRouter<AppState>>,
860    store: Option<MethodRouter<AppState>>,
861    show: Option<MethodRouter<AppState>>,
862    edit: Option<MethodRouter<AppState>>,
863    update: Option<MethodRouter<AppState>>,
864    destroy: Option<MethodRouter<AppState>>,
865}
866
867macro_rules! resource_action {
868    ($($action:ident => $router:expr),* $(,)?) => {$(
869        /// Sets the handler of this action (the function's name).
870        pub fn $action<H, T>(mut self, handler: H) -> Self
871        where
872            H: Handler<T, AppState>,
873            T: 'static,
874        {
875            let make: fn(H) -> MethodRouter<AppState> = $router;
876            self.$action = Some(make(handler));
877            self
878        }
879    )*};
880}
881
882impl Resource {
883    /// A resource with no actions; add them with `index`, `store`, …
884    pub fn new() -> Self {
885        Self::default()
886    }
887
888    resource_action!(
889        index => routing::get,
890        create => routing::get,
891        store => routing::post,
892        show => routing::get,
893        edit => routing::get,
894        update => |h| routing::put(h.clone()).patch(h),
895        destroy => routing::delete,
896    );
897}
898
899/// Whether a route name matches a pattern where `*` stands for anything,
900/// e.g. `admin.*` or `products.*`, like Laravel's `routeIs`.
901pub(crate) fn route_name_matches(name: &str, pattern: &str) -> bool {
902    let mut parts = pattern.split('*');
903    let first = parts.next().unwrap_or_default();
904    let Some(mut rest) = name.strip_prefix(first) else {
905        return false;
906    };
907    let parts: Vec<&str> = parts.collect();
908    let Some((last, middle)) = parts.split_last() else {
909        return rest.is_empty(); // no `*`: the whole name
910    };
911    for part in middle {
912        match rest.find(part) {
913            Some(at) => rest = &rest[at + part.len()..],
914            None => return false,
915        }
916    }
917    rest.ends_with(last)
918}
919
920/// The route that answers this request, from a handler or middleware:
921/// its name (`products.show`) and path pattern (`/products/{id}`).
922///
923/// ```
924/// # use renox::prelude::*;
925/// use renox::CurrentRoute;
926///
927/// async fn menu(route: CurrentRoute) -> String {
928///     if route.is("admin.*") { "admin".into() } else { route.name().unwrap_or("?").into() }
929/// }
930/// ```
931///
932/// In templates: `{% if route_is('products.*') %}` and `request.route`.
933#[derive(Debug, Clone)]
934pub struct CurrentRoute {
935    name: Option<String>,
936    path: Option<String>,
937}
938
939impl CurrentRoute {
940    /// The route's name, if it has one.
941    pub fn name(&self) -> Option<&str> {
942        self.name.as_deref()
943    }
944
945    /// The path pattern the request matched, e.g. `/products/{id}`.
946    pub fn path(&self) -> Option<&str> {
947        self.path.as_deref()
948    }
949
950    /// Whether the route's name matches any of `patterns` (`*` stands for
951    /// anything): `route.is("admin.*")`.
952    pub fn is(&self, pattern: &str) -> bool {
953        self.name
954            .as_deref()
955            .is_some_and(|name| route_name_matches(name, pattern))
956    }
957
958    pub(crate) fn of(
959        method: &axum::http::Method,
960        extensions: &axum::http::Extensions,
961        state: &AppState,
962    ) -> Self {
963        let path = extensions
964            .get::<axum::extract::MatchedPath>()
965            .map(|p| p.as_str().to_owned());
966        let domain = extensions
967            .get::<crate::domain::MatchedDomain>()
968            .map(|d| &*d.0);
969        let name = path
970            .as_deref()
971            .and_then(|p| state.routes.name_of(p, domain, Some(method.as_str())))
972            .map(str::to_owned);
973        Self { name, path }
974    }
975}
976
977impl<S: Send + Sync> axum::extract::FromRequestParts<S> for CurrentRoute {
978    type Rejection = Infallible;
979
980    async fn from_request_parts(
981        parts: &mut axum::http::request::Parts,
982        _: &S,
983    ) -> Result<Self, Infallible> {
984        Ok(match parts.extensions.get::<AppState>() {
985            Some(state) => Self::of(&parts.method, &parts.extensions, state),
986            None => Self {
987                name: None,
988                path: None,
989            },
990        })
991    }
992}
993
994#[cfg(test)]
995mod route_name_tests {
996    use super::route_name_matches;
997
998    #[test]
999    fn patterns_match_like_laravel() {
1000        assert!(route_name_matches("admin.users.index", "admin.*"));
1001        assert!(route_name_matches("admin.users.index", "*.index"));
1002        assert!(route_name_matches("admin.users.index", "admin.*.index"));
1003        assert!(route_name_matches("products.show", "products.show"));
1004        assert!(!route_name_matches("products.show", "products"));
1005        assert!(!route_name_matches("shop.products.show", "products.*"));
1006        assert!(route_name_matches("anything", "*"));
1007        assert!(!route_name_matches("admin", "admin.*"));
1008        // A middle part that isn't there (#252).
1009        assert!(!route_name_matches("admin.users.index", "admin.*.posts.*"));
1010        assert!(route_name_matches(
1011            "admin.users.posts.edit",
1012            "admin.*.posts.*"
1013        ));
1014    }
1015
1016    /// Outside the app's middleware (no `AppState` on the request), no
1017    /// route is current.
1018    #[tokio::test]
1019    async fn current_route_without_the_app_is_none() {
1020        use axum::extract::FromRequestParts;
1021        let (mut parts, ()) = axum::http::Request::builder()
1022            .uri("/x")
1023            .body(())
1024            .unwrap()
1025            .into_parts();
1026        let current = super::CurrentRoute::from_request_parts(&mut parts, &())
1027            .await
1028            .unwrap();
1029        assert_eq!(current.name(), None);
1030    }
1031}
1032
1033/// A redirect with this status and `Location`.
1034fn redirect_with(status: axum::http::StatusCode, to: &str) -> axum::response::Response {
1035    match axum::http::HeaderValue::from_str(to) {
1036        Ok(location) => (status, [(axum::http::header::LOCATION, location)]).into_response(),
1037        Err(_) => axum::http::StatusCode::INTERNAL_SERVER_ERROR.into_response(),
1038    }
1039}