Skip to main content

luxid_core/
router.rs

1//! Explicit route registration.
2//!
3//! Routes are declared, never auto-discovered. A route that does not exist must
4//! be traceable to a visible line of code rather than to a linker section that
5//! silently dropped a symbol.
6//!
7//! Middleware attaches at three levels and runs outermost-first:
8//! global (`App::middleware`) → group (`Router::middleware`) → route
9//! (`.middleware()` on the returned handle).
10
11use std::sync::Arc;
12
13use crate::middleware::{Action, Middleware};
14
15/// A controller that defines resource actions.
16///
17/// Implemented by `#[luxid::controller]` for any block defining at least one of
18/// `index`, `show`, `store`, `update`, `destroy` — and it registers only the
19/// ones that exist, so a read-only controller does not acquire a `DELETE` route
20/// that 500s.
21pub trait ResourceRoutes {
22    fn register(router: &mut Router);
23}
24
25/// `#[non_exhaustive]` is load-bearing, for the same reason it is on
26/// `HttpContext`: it forces downstream crates to write a `_` arm, so adding a
27/// verb — HEAD, TRACE, whatever a future protocol needs — is permanently
28/// non-breaking. Adding `Options` for CORS preflight was the warning shot.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum Method {
32    Get,
33    Post,
34    Put,
35    Patch,
36    Delete,
37    /// Registrable so an application can answer a CORS preflight.
38    ///
39    /// Middleware is attached per route (see `App::into_parts`), so a request
40    /// that matches nothing never reaches any middleware — which means a
41    /// preflight cannot be answered by a CORS middleware alone. It needs a
42    /// real route, and therefore a real method.
43    Options,
44}
45
46pub struct Route {
47    method: Method,
48    path: String,
49    action: Arc<dyn Action>,
50    middleware: Vec<Arc<dyn Middleware>>,
51}
52
53impl Route {
54    /// Attach middleware to this route alone. Chainable.
55    pub fn middleware<M: Middleware>(&mut self, middleware: M) -> &mut Self {
56        self.middleware.push(Arc::new(middleware));
57        self
58    }
59}
60
61enum Entry {
62    Route(Route),
63    Group {
64        prefix: String,
65        router: Router,
66    },
67    /// A directory served verbatim. Carries no middleware: static assets are
68    /// public by definition, and running an auth guard over a stylesheet would
69    /// be surprising rather than safe.
70    Static {
71        path: String,
72        dir: String,
73    },
74}
75
76/// One row of the routing table, as `luxid routes` renders it.
77///
78/// Not comparable: it carries an `Operation`, which holds schema function
79/// pointers. Compare the fields you care about, or the rendered document.
80#[derive(Debug, Clone)]
81pub struct RouteInfo {
82    pub method: Method,
83    pub path: String,
84    pub action: &'static str,
85    /// How many middleware wrap this route, outermost first.
86    pub middleware: usize,
87    /// What `#[openapi(..)]` recorded for this action.
88    pub operation: Option<crate::openapi::Operation>,
89}
90
91impl Method {
92    pub fn as_str(&self) -> &'static str {
93        match self {
94            Self::Get => "GET",
95            Self::Post => "POST",
96            Self::Put => "PUT",
97            Self::Patch => "PATCH",
98            Self::Delete => "DELETE",
99            Self::Options => "OPTIONS",
100        }
101    }
102}
103
104/// A flattened route, used by `App` and by `luxid routes`.
105pub struct Registered {
106    pub method: Method,
107    pub path: String,
108    pub action: Arc<dyn Action>,
109    pub middleware: Vec<Arc<dyn Middleware>>,
110}
111
112#[derive(Default)]
113pub struct Router {
114    entries: Vec<Entry>,
115    middleware: Vec<Arc<dyn Middleware>>,
116}
117
118impl Router {
119    pub fn new() -> Self {
120        Self::default()
121    }
122
123    /// Attach middleware to every route in this router (and its groups).
124    pub fn middleware<M: Middleware>(&mut self, middleware: M) -> &mut Self {
125        self.middleware.push(Arc::new(middleware));
126        self
127    }
128
129    pub fn get<A: Action>(&mut self, path: &str, action: A) -> &mut Route {
130        self.route(Method::Get, path, action)
131    }
132
133    pub fn post<A: Action>(&mut self, path: &str, action: A) -> &mut Route {
134        self.route(Method::Post, path, action)
135    }
136
137    pub fn put<A: Action>(&mut self, path: &str, action: A) -> &mut Route {
138        self.route(Method::Put, path, action)
139    }
140
141    pub fn patch<A: Action>(&mut self, path: &str, action: A) -> &mut Route {
142        self.route(Method::Patch, path, action)
143    }
144
145    pub fn delete<A: Action>(&mut self, path: &str, action: A) -> &mut Route {
146        self.route(Method::Delete, path, action)
147    }
148
149    /// Register an `OPTIONS` route, typically a CORS preflight responder.
150    pub fn options<A: Action>(&mut self, path: &str, action: A) -> &mut Route {
151        self.route(Method::Options, path, action)
152    }
153
154    /// Register a controller's resource actions under `path`.
155    ///
156    /// ```ignore
157    /// r.resource("/posts", PostsController).middleware(Auth::jwt());
158    /// ```
159    ///
160    /// Returns the group the routes live in, so middleware attaches to all of
161    /// them at once.
162    pub fn resource<C: ResourceRoutes>(&mut self, path: &str, controller: C) -> &mut Router {
163        let _ = controller;
164
165        let mut inner = Router::new();
166        C::register(&mut inner);
167
168        self.entries.push(Entry::Group {
169            prefix: path.to_owned(),
170            router: inner,
171        });
172
173        match self.entries.last_mut() {
174            Some(Entry::Group { router, .. }) => router,
175            _ => unreachable!("a group was just pushed"),
176        }
177    }
178
179    /// Nest routes under a shared prefix. Call `r.middleware(..)` inside the
180    /// closure to apply middleware to the whole group.
181    pub fn group(&mut self, prefix: &str, build: impl FnOnce(&mut Router)) -> &mut Self {
182        let mut inner = Router::new();
183        build(&mut inner);
184
185        self.entries.push(Entry::Group {
186            prefix: prefix.to_owned(),
187            router: inner,
188        });
189        self
190    }
191
192    fn route<A: Action>(&mut self, method: Method, path: &str, action: A) -> &mut Route {
193        self.entries.push(Entry::Route(Route {
194            method,
195            path: path.to_owned(),
196            action: Arc::new(action),
197            middleware: Vec::new(),
198        }));
199
200        match self.entries.last_mut() {
201            Some(Entry::Route(route)) => route,
202            _ => unreachable!("a route was just pushed"),
203        }
204    }
205
206    /// Serve `dir` from the filesystem under `path`.
207    ///
208    /// ```ignore
209    /// r.static_files("/build", "public/build");
210    /// ```
211    ///
212    /// Used for a built frontend bundle. In development the Vite dev server
213    /// serves those files instead, so this route is simply unused.
214    pub fn static_files(&mut self, path: &str, dir: &str) -> &mut Self {
215        self.entries.push(Entry::Static {
216            path: path.to_owned(),
217            dir: dir.to_owned(),
218        });
219        self
220    }
221
222    /// Describe the routing table without consuming the router, so an app can
223    /// print its routes and then serve them.
224    pub fn describe(&self) -> Vec<RouteInfo> {
225        let mut rows = Vec::new();
226        self.describe_into("", self.middleware.len(), &mut rows);
227        rows
228    }
229
230    fn describe_into(&self, prefix: &str, inherited: usize, rows: &mut Vec<RouteInfo>) {
231        for entry in &self.entries {
232            match entry {
233                Entry::Route(route) => rows.push(RouteInfo {
234                    method: route.method,
235                    path: join(prefix, &route.path),
236                    action: route.action.name(),
237                    middleware: inherited + route.middleware.len(),
238                    operation: route.action.openapi(),
239                }),
240                Entry::Group {
241                    prefix: group_prefix,
242                    router,
243                } => router.describe_into(
244                    &join(prefix, group_prefix),
245                    inherited + router.middleware.len(),
246                    rows,
247                ),
248                Entry::Static { path, .. } => rows.push(RouteInfo {
249                    method: Method::Get,
250                    path: format!("{}/{{**path}}", join(prefix, path)),
251                    action: "static files",
252                    // Zero, not `inherited`: static mounts are registered
253                    // straight onto the salvo router and never enter the
254                    // middleware chain. Reporting the inherited count would
255                    // claim a guard that is not there.
256                    middleware: 0,
257                    operation: None,
258                }),
259            }
260        }
261    }
262
263    /// Flatten into absolute paths with fully resolved middleware stacks.
264    pub(crate) fn flatten(self) -> Flattened {
265        let mut out = Flattened::default();
266        self.flatten_into("", &[], &mut out);
267        out
268    }
269
270    fn flatten_into(self, prefix: &str, inherited: &[Arc<dyn Middleware>], out: &mut Flattened) {
271        let mut stack = inherited.to_vec();
272        stack.extend(self.middleware);
273
274        for entry in self.entries {
275            match entry {
276                Entry::Route(route) => {
277                    let mut middleware = stack.clone();
278                    middleware.extend(route.middleware);
279
280                    out.routes.push(Registered {
281                        method: route.method,
282                        path: join(prefix, &route.path),
283                        action: route.action,
284                        middleware,
285                    });
286                }
287                Entry::Group {
288                    prefix: group_prefix,
289                    router,
290                } => router.flatten_into(&join(prefix, &group_prefix), &stack, out),
291                Entry::Static { path, dir } => out.statics.push(StaticMount {
292                    path: join(prefix, &path),
293                    dir,
294                }),
295            }
296        }
297    }
298}
299
300/// The router resolved into what `App` needs to build a salvo router.
301#[derive(Default)]
302pub(crate) struct Flattened {
303    pub routes: Vec<Registered>,
304    pub statics: Vec<StaticMount>,
305}
306
307pub(crate) struct StaticMount {
308    pub path: String,
309    pub dir: String,
310}
311
312fn join(prefix: &str, path: &str) -> String {
313    let head = prefix.trim_end_matches('/');
314    let tail = path.trim_start_matches('/');
315
316    // `resource` registers its collection route as "", which must join to the
317    // group prefix itself rather than to `/posts/`.
318    let joined = if tail.is_empty() {
319        head.to_owned()
320    } else {
321        format!("{head}/{tail}")
322    };
323
324    if joined.is_empty() {
325        "/".to_owned()
326    } else {
327        joined
328    }
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334    use crate::context::HttpContext;
335    use crate::error::Result;
336    use crate::http::Response;
337    use crate::middleware::{BoxFuture, Next};
338
339    struct Noop;
340    impl Action for Noop {
341        fn call(&self, ctx: HttpContext) -> BoxFuture<'static, Result<Response>> {
342            Box::pin(async move { ctx.response.no_content() })
343        }
344    }
345
346    struct Tag;
347    impl Middleware for Tag {
348        fn handle<'a>(&'a self, ctx: HttpContext, next: Next) -> BoxFuture<'a, Result<Response>> {
349            Box::pin(async move { next.run(ctx).await })
350        }
351    }
352
353    #[test]
354    fn joins_group_prefixes_into_absolute_paths() {
355        let mut router = Router::new();
356        router.group("/api/v1", |r| {
357            r.get("/users", Noop);
358            r.group("/admin", |r| {
359                r.get("/stats", Noop);
360            });
361        });
362
363        let paths: Vec<_> = router
364            .flatten()
365            .routes
366            .into_iter()
367            .map(|r| r.path)
368            .collect();
369        assert_eq!(paths, vec!["/api/v1/users", "/api/v1/admin/stats"]);
370    }
371
372    #[test]
373    fn resolves_middleware_outermost_first() {
374        let mut router = Router::new();
375        router.middleware(Tag);
376        router.group("/api", |r| {
377            r.middleware(Tag);
378            r.get("/users", Noop).middleware(Tag);
379            r.get("/health", Noop);
380        });
381
382        let registered = router.flatten().routes;
383
384        assert_eq!(registered[0].middleware.len(), 3, "global + group + route");
385        assert_eq!(registered[1].middleware.len(), 2, "global + group only");
386    }
387
388    #[test]
389    fn a_route_at_the_root_keeps_a_single_slash() {
390        let mut router = Router::new();
391        router.get("/", Noop);
392
393        assert_eq!(router.flatten().routes[0].path, "/");
394    }
395
396    #[test]
397    fn static_mounts_are_flattened_separately_from_routes() {
398        let mut router = Router::new();
399        router.get("/", Noop);
400        router.static_files("/build", "public/build");
401
402        let flattened = router.flatten();
403
404        // Static directories are not actions, so they do not appear among the
405        // routes that carry middleware stacks.
406        assert_eq!(flattened.routes.len(), 1);
407        assert_eq!(flattened.statics.len(), 1);
408        assert_eq!(flattened.statics[0].path, "/build");
409        assert_eq!(flattened.statics[0].dir, "public/build");
410    }
411
412    #[test]
413    fn a_static_mount_reports_no_middleware() {
414        // It really has none — `App::into_parts` registers it directly on the
415        // salvo router. Claiming otherwise in `luxid routes` would suggest a
416        // guard that does not exist.
417        let mut router = Router::new();
418        router.middleware(Tag);
419        router.static_files("/build", "public/build");
420
421        let rows = router.describe();
422        assert_eq!(rows[0].middleware, 0);
423    }
424
425    #[test]
426    fn a_static_mount_inherits_its_group_prefix() {
427        let mut router = Router::new();
428        router.group("/assets", |r| {
429            r.static_files("/build", "public/build");
430        });
431
432        assert_eq!(router.flatten().statics[0].path, "/assets/build");
433    }
434
435    #[test]
436    fn sibling_groups_do_not_inherit_each_others_middleware() {
437        let mut router = Router::new();
438        router.group("/a", |r| {
439            r.middleware(Tag);
440            r.get("/x", Noop);
441        });
442        router.group("/b", |r| {
443            r.get("/y", Noop);
444        });
445
446        let registered = router.flatten().routes;
447        assert_eq!(registered[0].middleware.len(), 1);
448        assert_eq!(registered[1].middleware.len(), 0);
449    }
450}