1use std::sync::Arc;
12
13use crate::middleware::{Action, Middleware};
14
15pub trait ResourceRoutes {
22 fn register(router: &mut Router);
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum Method {
32 Get,
33 Post,
34 Put,
35 Patch,
36 Delete,
37 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 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 Static {
71 path: String,
72 dir: String,
73 },
74}
75
76#[derive(Debug, Clone)]
81pub struct RouteInfo {
82 pub method: Method,
83 pub path: String,
84 pub action: &'static str,
85 pub middleware: usize,
87 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
104pub 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 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 pub fn options<A: Action>(&mut self, path: &str, action: A) -> &mut Route {
151 self.route(Method::Options, path, action)
152 }
153
154 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 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 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 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 middleware: 0,
257 operation: None,
258 }),
259 }
260 }
261 }
262
263 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#[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 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 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 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}