Skip to main content

glacier/
router.rs

1//! The router: maps a method and path to a handler.
2//!
3//! Patterns are made of `/`-separated segments:
4//!
5//! * `posts` matches exactly,
6//! * `:id` captures one segment as the `id` parameter,
7//! * `*path` captures the rest of the path (must be last).
8//!
9//! When several routes match, the most specific one wins: static segments
10//! beat parameters, which beat globs, compared left to right. Ties go to the
11//! route registered first.
12
13use std::any::type_name;
14use std::fmt::Write;
15use std::sync::Arc;
16
17use http::Method;
18use percent_encoding::{AsciiSet, CONTROLS, percent_decode_str, utf8_percent_encode};
19
20use crate::context::PathParams;
21use crate::controller::{Action, Resource};
22use crate::handler::Handler;
23use crate::middleware::{Middleware, Pipeline};
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26enum Segment {
27    Static(String),
28    /// `:id`, or `:id.json`: a name, and text the segment must end with.
29    Param(String, String),
30    Glob(String),
31}
32
33pub struct Route {
34    method: Method,
35    pattern: String,
36    segments: Vec<Segment>,
37    label: String,
38    pub(crate) handler: Arc<dyn Handler>,
39    /// Middleware from enclosing `pipe_through` blocks, outermost first.
40    pub(crate) stack: Arc<[Arc<dyn Middleware>]>,
41    /// Params that must match a pattern for the route to match.
42    constraints: Vec<(String, regex::Regex)>,
43    /// The API version the route answers, from a `version` scope.
44    version: Option<Version>,
45}
46
47/// A controller's documented actions, for OpenAPI.
48type Docs = fn() -> Vec<crate::openapi::ActionDoc>;
49
50/// An API version a route answers: requests asking for it (by an
51/// `Api-Version` header, or `Accept: application/vnd.….v2+json`), and
52/// for the default version, requests that ask for none.
53#[derive(Debug, Clone)]
54pub(crate) struct Version {
55    pub(crate) name: String,
56    pub(crate) default: bool,
57}
58
59impl Route {
60    pub fn method(&self) -> &Method {
61        &self.method
62    }
63
64    pub fn pattern(&self) -> &str {
65        &self.pattern
66    }
67
68    /// The handler's name, e.g. `blog::controllers::pages::home` or
69    /// `Posts#show`.
70    pub fn label(&self) -> &str {
71        &self.label
72    }
73
74    /// Whether the route answers a request for API version `requested`
75    /// (`None`: a request that names none).
76    pub(crate) fn answers(&self, requested: Option<&str>) -> bool {
77        match (&self.version, requested) {
78            (None, _) => true,
79            (Some(version), Some(requested)) => version.name == requested,
80            (Some(version), None) => version.default,
81        }
82    }
83
84    pub(crate) fn is_versioned(&self) -> bool {
85        self.version.is_some()
86    }
87}
88
89pub(crate) enum Match<'r> {
90    Found(&'r Route, PathParams),
91    MethodNotAllowed(Vec<Method>),
92    NotFound,
93}
94
95#[derive(Default)]
96pub struct Router {
97    prefix: String,
98    middleware: Vec<Arc<dyn Middleware>>,
99    routes: Vec<Route>,
100    /// What each controller's actions respond with, for OpenAPI.
101    docs: Vec<(&'static str, Docs)>,
102    /// The version of the enclosing `version` scope.
103    version: Option<Version>,
104}
105
106impl Router {
107    pub fn new() -> Self {
108        Self::default()
109    }
110
111    /// # Panics
112    ///
113    /// If the pattern has a glob segment anywhere but last. Routes are drawn
114    /// once at boot, so this surfaces immediately.
115    pub fn route<H: Handler>(&mut self, method: Method, path: &str, handler: H) -> &mut Self {
116        self.add(method, path, Arc::new(handler), handler_label::<H>())
117    }
118
119    fn add(
120        &mut self,
121        method: Method,
122        path: &str,
123        handler: Arc<dyn Handler>,
124        label: String,
125    ) -> &mut Self {
126        let pattern = join(&self.prefix, path);
127        let segments = parse_pattern(&pattern);
128        self.routes.push(Route {
129            method,
130            pattern,
131            segments,
132            label,
133            handler,
134            stack: self.middleware.clone().into(),
135            constraints: Vec::new(),
136            version: self.version.clone(),
137        });
138        self
139    }
140
141    /// Requires the last route's `param` to match `pattern` in full, as
142    /// Rails' `constraints: {platform: /ios|android/}`; otherwise the route
143    /// doesn't match (`routes!`: `where platform = "ios|android"`).
144    ///
145    /// # Panics
146    ///
147    /// If no route was added yet, or the pattern isn't a valid regex.
148    pub fn constrain(&mut self, param: &str, pattern: &str) -> &mut Self {
149        let regex = regex::Regex::new(&format!("^(?:{pattern})$"))
150            .unwrap_or_else(|e| panic!("invalid constraint for `{param}`: {e}"));
151        self.routes
152            .last_mut()
153            .expect("constrain follows a route")
154            .constraints
155            .push((param.to_owned(), regex));
156        self
157    }
158
159    pub fn get(&mut self, path: &str, handler: impl Handler) -> &mut Self {
160        self.route(Method::GET, path, handler)
161    }
162
163    pub fn post(&mut self, path: &str, handler: impl Handler) -> &mut Self {
164        self.route(Method::POST, path, handler)
165    }
166
167    pub fn put(&mut self, path: &str, handler: impl Handler) -> &mut Self {
168        self.route(Method::PUT, path, handler)
169    }
170
171    pub fn patch(&mut self, path: &str, handler: impl Handler) -> &mut Self {
172        self.route(Method::PATCH, path, handler)
173    }
174
175    pub fn delete(&mut self, path: &str, handler: impl Handler) -> &mut Self {
176        self.route(Method::DELETE, path, handler)
177    }
178
179    /// Groups routes under a common path prefix.
180    pub fn scope(&mut self, prefix: &str, draw: impl FnOnce(&mut Router)) -> &mut Self {
181        self.nested(join(&self.prefix, prefix), Vec::new(), draw)
182    }
183
184    /// Runs every route drawn inside `draw` through `pipeline`'s middleware.
185    /// Pipelines nest: inner routes run outer pipelines first.
186    ///
187    /// Unlike app-level middleware, pipelines run after routing, so they
188    /// don't see 404s.
189    pub fn pipe_through(
190        &mut self,
191        pipeline: &Pipeline,
192        draw: impl FnOnce(&mut Router),
193    ) -> &mut Self {
194        self.nested(self.prefix.clone(), pipeline.stack.clone(), draw)
195    }
196
197    /// Routes that answer only requests for API version `name` (an
198    /// `Api-Version: 2` header, or `Accept: application/vnd.app.v2+json`),
199    /// as GitHub's API versions. The `default` version also answers
200    /// requests that name none. `routes!`: `scope "/" version "2" { … }`.
201    pub fn version(
202        &mut self,
203        name: &str,
204        default: bool,
205        draw: impl FnOnce(&mut Router),
206    ) -> &mut Self {
207        let outer = self.version.replace(Version {
208            name: name.to_owned(),
209            default,
210        });
211        self.nested(self.prefix.clone(), Vec::new(), draw);
212        self.version = outer;
213        self
214    }
215
216    fn nested(
217        &mut self,
218        prefix: String,
219        extra: Vec<Arc<dyn Middleware>>,
220        draw: impl FnOnce(&mut Router),
221    ) -> &mut Self {
222        let mut middleware = self.middleware.clone();
223        middleware.extend(extra);
224        let mut nested = Router {
225            prefix,
226            middleware,
227            routes: Vec::new(),
228            docs: Vec::new(),
229            version: self.version.clone(),
230        };
231        draw(&mut nested);
232        self.routes.extend(nested.routes);
233        for (name, docs) in nested.docs {
234            self.add_docs(name, docs);
235        }
236        self
237    }
238
239    /// Records what `C`'s actions respond with, for OpenAPI. `routes!`
240    /// does this for every controller it routes to.
241    pub fn document<C: crate::openapi::Documented>(&mut self) -> &mut Self {
242        self.add_docs(short_type_name::<C>(), C::actions);
243        self
244    }
245
246    fn add_docs(&mut self, name: &'static str, docs: Docs) {
247        if !self.docs.iter().any(|(n, _)| *n == name) {
248            self.docs.push((name, docs));
249        }
250    }
251
252    /// The documented actions of the controller named `name` (`Books`).
253    pub(crate) fn docs_for(&self, name: &str) -> Vec<crate::openapi::ActionDoc> {
254        self.docs
255            .iter()
256            .find(|(n, _)| *n == name)
257            .map(|(_, docs)| docs())
258            .unwrap_or_default()
259    }
260
261    /// Each route's constraints, by param, for OpenAPI.
262    pub(crate) fn route_constraints(route: &Route) -> Vec<(&str, &str)> {
263        route
264            .constraints
265            .iter()
266            .map(|(param, pattern)| (param.as_str(), pattern.as_str()))
267            .collect()
268    }
269
270    /// Mounts `R`'s RESTful actions under `/name`: all seven by default, or
271    /// exactly those defined in a `#[glacier::controller]`.
272    pub fn resources<R: Resource>(&mut self, name: &str) -> &mut Self {
273        self.resources_only::<R>(name, R::ACTIONS)
274    }
275
276    /// Mounts only the given actions of `R` under `/name`.
277    pub fn resources_only<R: Resource>(&mut self, name: &str, actions: &[Action]) -> &mut Self {
278        let base = format!("/{}", name.trim_matches('/'));
279        // Nested (`/orgs/:org_id/projects`): records' paths fill the params.
280        let full = join(&self.prefix, &base);
281        if full.contains("/:") {
282            let table = base.rsplit('/').next().unwrap_or_default().to_owned();
283            NESTED
284                .write()
285                .unwrap_or_else(|e| e.into_inner())
286                .insert(table, full);
287        }
288        let member = format!("{base}/:id");
289        let controller = short_type_name::<R>();
290        let label = |action: &str| format!("{controller}#{action}");
291        for action in actions {
292            match action {
293                Action::Index => self.add(Method::GET, &base, Arc::new(R::index), label("index")),
294                Action::New => self.add(
295                    Method::GET,
296                    &format!("{base}/new"),
297                    Arc::new(R::new),
298                    label("new"),
299                ),
300                Action::Create => {
301                    self.add(Method::POST, &base, Arc::new(R::create), label("create"))
302                }
303                Action::Show => self.add(Method::GET, &member, Arc::new(R::show), label("show")),
304                Action::Edit => self.add(
305                    Method::GET,
306                    &format!("{member}/edit"),
307                    Arc::new(R::edit),
308                    label("edit"),
309                ),
310                Action::Update => self
311                    .add(Method::PATCH, &member, Arc::new(R::update), label("update"))
312                    .add(Method::PUT, &member, Arc::new(R::update), label("update")),
313                Action::Destroy => self.add(
314                    Method::DELETE,
315                    &member,
316                    Arc::new(R::destroy),
317                    label("destroy"),
318                ),
319            };
320        }
321        self
322    }
323
324    /// All registered routes, in registration order.
325    pub fn routes(&self) -> &[Route] {
326        &self.routes
327    }
328
329    /// A human-readable route table, as printed by `glacier routes`.
330    pub fn describe(&self) -> String {
331        let method_width = self
332            .routes
333            .iter()
334            .map(|r| r.method.as_str().len())
335            .max()
336            .unwrap_or(0);
337        let pattern_width = self
338            .routes
339            .iter()
340            .map(|r| r.pattern.len())
341            .max()
342            .unwrap_or(0);
343        let mut out = String::new();
344        for route in &self.routes {
345            let _ = writeln!(
346                out,
347                "{:<method_width$}  {:<pattern_width$}  {}",
348                route.method.as_str(),
349                route.pattern,
350                route.label
351            );
352        }
353        out
354    }
355
356    #[cfg(test)]
357    pub(crate) fn recognize(&self, method: &Method, path: &str) -> Match<'_> {
358        self.recognize_version(method, path, None)
359    }
360
361    /// The route for `path`, for a request asking for API version
362    /// `requested` (or none). As Rails' `(.:format)`, a path no route
363    /// matches is tried again without its extension, which becomes the
364    /// `format` param: `/posts/1.json` reaches `/posts/:id` with format
365    /// `json`.
366    pub(crate) fn recognize_version(
367        &self,
368        method: &Method,
369        path: &str,
370        requested: Option<&str>,
371    ) -> Match<'_> {
372        let found = self.recognize_exact(method, path, requested);
373        if !matches!(found, Match::NotFound) {
374            return found;
375        }
376        let last = path.rsplit('/').next().unwrap_or("");
377        let Some((stem, format)) = last.rsplit_once('.') else {
378            return found;
379        };
380        let is_format = format.starts_with(|c: char| c.is_ascii_alphabetic())
381            && format.chars().all(|c| c.is_ascii_alphanumeric());
382        if stem.is_empty() || !is_format {
383            return found;
384        }
385        let bare = &path[..path.len() - format.len() - 1];
386        match self.recognize_exact(method, bare, requested) {
387            Match::Found(route, mut params) => {
388                params.push("format", format.to_owned());
389                Match::Found(route, params)
390            }
391            Match::MethodNotAllowed(allowed) => Match::MethodNotAllowed(allowed),
392            Match::NotFound => found,
393        }
394    }
395
396    fn recognize_exact(&self, method: &Method, path: &str, requested: Option<&str>) -> Match<'_> {
397        let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
398        let mut best: Option<(&Route, PathParams, Vec<u8>)> = None;
399        let mut allowed: Vec<Method> = Vec::new();
400
401        for route in &self.routes {
402            let Some((params, rank)) = match_segments(&route.segments, &parts) else {
403                continue;
404            };
405            let constrained = route.constraints.iter().any(|(name, pattern)| {
406                !params
407                    .get(name)
408                    .is_some_and(|value| pattern.is_match(value))
409            });
410            if constrained {
411                continue;
412            }
413            if !route.answers(requested) {
414                continue;
415            }
416            // HEAD falls back to GET; hyper drops the body for HEAD responses.
417            let method_matches =
418                route.method == *method || (*method == Method::HEAD && route.method == Method::GET);
419            if method_matches {
420                // A route of the requested version beats an unversioned one
421                // at the same path.
422                let better = best.as_ref().is_none_or(|(best_route, _, best_rank)| {
423                    rank < *best_rank
424                        || (rank == *best_rank
425                            && requested.is_some()
426                            && route.is_versioned()
427                            && !best_route.is_versioned())
428                });
429                if better {
430                    best = Some((route, params, rank));
431                }
432            } else if !allowed.contains(&route.method) {
433                allowed.push(route.method.clone());
434            }
435        }
436
437        match best {
438            Some((route, params, _)) => Match::Found(route, params),
439            None if !allowed.is_empty() => Match::MethodNotAllowed(allowed),
440            None => Match::NotFound,
441        }
442    }
443}
444
445/// Something with a URL: a path string, or a record (`redirect!(post)`,
446/// `link_to("Edit", post)`), whose path comes from `Model::path`.
447pub trait ToPath {
448    fn to_path(&self) -> String;
449}
450
451impl ToPath for str {
452    fn to_path(&self) -> String {
453        self.to_owned()
454    }
455}
456
457impl ToPath for String {
458    fn to_path(&self) -> String {
459        self.clone()
460    }
461}
462
463/// Records (`derive(Model)` implements `ToPath` via `Model::path`) and
464/// paths work by reference too.
465impl<T: ToPath + ?Sized> ToPath for &T {
466    fn to_path(&self) -> String {
467        (**self).to_path()
468    }
469}
470
471/// Characters escaped in a path segment: everything but RFC 3986 unreserved
472/// characters and sub-delims that are safe in paths.
473const SEGMENT: &AsciiSet = &CONTROLS
474    .add(b' ')
475    .add(b'"')
476    .add(b'#')
477    .add(b'%')
478    .add(b'/')
479    .add(b'<')
480    .add(b'>')
481    .add(b'?')
482    .add(b'[')
483    .add(b'\\')
484    .add(b']')
485    .add(b'^')
486    .add(b'`')
487    .add(b'{')
488    .add(b'|')
489    .add(b'}');
490
491tokio::task_local! {
492    static PATH_PREFIX: String;
493}
494
495/// Each nested resource's base path by its name, the model's table:
496/// `projects` → `/orgs/:org_id/projects`.
497static NESTED: std::sync::RwLock<std::collections::BTreeMap<String, String>> =
498    std::sync::RwLock::new(std::collections::BTreeMap::new());
499
500/// The route params of the request being handled, for paths built during
501/// it (`posts_path()` inside `/orgs/42/…` keeps the `42`).
502#[derive(Clone)]
503pub(crate) struct RouteParams(pub(crate) crate::context::PathParams);
504
505/// The collection path of `table` (`/projects`, or its nested base with
506/// each `:param` filled by `value(param)`, else the current request's
507/// param of that name), with the request's prefix in front.
508#[doc(hidden)]
509pub fn collection_path_of(table: &str, value: impl Fn(&str) -> Option<String>) -> String {
510    let nested = NESTED
511        .read()
512        .unwrap_or_else(|e| e.into_inner())
513        .get(table)
514        .cloned();
515    let Some(pattern) = nested else {
516        return prefixed(format!("/{table}"));
517    };
518    let current = crate::current::get::<RouteParams>();
519    let mut path = String::new();
520    for segment in pattern.split('/').filter(|s| !s.is_empty()) {
521        path.push('/');
522        match segment.strip_prefix(':') {
523            Some(param) => {
524                let filled = value(param).or_else(|| {
525                    current
526                        .as_ref()
527                        .and_then(|c| c.0.get(param).map(str::to_owned))
528                });
529                match filled {
530                    Some(filled) => path.push_str(&encode_segment(&filled)),
531                    None => path.push_str(segment),
532                }
533            }
534            None => path.push_str(segment),
535        }
536    }
537    prefixed(path)
538}
539
540/// Runs `fut` with every path the app builds (path helpers, record paths)
541/// starting with `prefix`, such as `/42` for org 42: what
542/// [`IdPrefix`](crate::middleware::IdPrefix) does for the rest of a request.
543pub async fn with_path_prefix<F: std::future::Future>(prefix: String, fut: F) -> F::Output {
544    PATH_PREFIX.scope(prefix, fut).await
545}
546
547/// `path` with the current request's prefix in front (`/42/projects`), or
548/// as it is. Path helpers and record paths call it.
549#[doc(hidden)]
550pub fn prefixed(path: String) -> String {
551    PATH_PREFIX
552        .try_with(|prefix| {
553            if path == "/" {
554                prefix.clone()
555            } else {
556                format!("{prefix}{path}")
557            }
558        })
559        .unwrap_or(path)
560}
561
562/// An absolute URL for a path or a record, from the app's configured
563/// `url`: `url_for(edit_password_path(&token))?` for a link in a mail.
564///
565/// # Errors
566///
567/// Before the app is configured, or in production without a `url`.
568pub fn url_for(path: impl crate::router::ToPath) -> crate::Result<String> {
569    let base = crate::Config::current()?.url()?;
570    Ok(format!("{base}{}", path.to_path()))
571}
572
573/// A path with query params, as `.glacier`'s
574/// `new_session_path(email_address: e)` writes it: each value
575/// percent-encoded, after a `?` (or a `&` when the path has a query).
576///
577/// ```
578/// let path = glacier::router::with_query("/session/new".into(), &[("email", "a b@x.com".into())]);
579/// assert_eq!(path, "/session/new?email=a%20b%40x.com");
580/// ```
581pub fn with_query(mut path: String, params: &[(&str, String)]) -> String {
582    for (i, (key, value)) in params.iter().enumerate() {
583        path.push(if i == 0 && !path.contains('?') {
584            '?'
585        } else {
586            '&'
587        });
588        path.push_str(&utf8_percent_encode(key, QUERY).to_string());
589        path.push('=');
590        path.push_str(&utf8_percent_encode(value, QUERY).to_string());
591    }
592    path
593}
594
595/// Everything but unreserved characters, for query keys and values.
596const QUERY: &AsciiSet = &percent_encoding::NON_ALPHANUMERIC
597    .remove(b'-')
598    .remove(b'.')
599    .remove(b'_')
600    .remove(b'~');
601
602/// Percent-encodes one path segment (used by `paths!` helpers).
603#[doc(hidden)]
604pub fn encode_segment(s: &str) -> String {
605    utf8_percent_encode(s, SEGMENT).to_string()
606}
607
608/// Percent-encodes a multi-segment path, keeping the `/` separators.
609#[doc(hidden)]
610pub fn encode_path(s: &str) -> String {
611    s.split('/')
612        .map(encode_segment)
613        .collect::<Vec<_>>()
614        .join("/")
615}
616
617/// The API version a request asks for: an `Api-Version` header, or a
618/// vendor media type in `Accept` (`application/vnd.shop.v2+json`, or
619/// `application/json; version=2`).
620pub(crate) fn requested_version(headers: &http::HeaderMap) -> Option<String> {
621    if let Some(version) = headers
622        .get("api-version")
623        .and_then(|v| v.to_str().ok())
624        .map(str::trim)
625        .filter(|v| !v.is_empty())
626    {
627        return Some(version.trim_start_matches(['v', 'V']).to_owned());
628    }
629    let accept = headers.get(http::header::ACCEPT)?.to_str().ok()?;
630    accept.split(',').find_map(|media| {
631        let mut parts = media.split(';').map(str::trim);
632        let ty = parts.next()?;
633        if let Some(version) = parts.find_map(|p| p.strip_prefix("version=")) {
634            return Some(
635                version
636                    .trim_matches('"')
637                    .trim_start_matches(['v', 'V'])
638                    .to_owned(),
639            );
640        }
641        // `application/vnd.shop.v2+json`
642        let vendor = ty.strip_prefix("application/vnd.")?;
643        let name = vendor.split('+').next()?;
644        let version = name.rsplit('.').next()?.strip_prefix(['v', 'V'])?;
645        (!version.is_empty()
646            && version
647                .chars()
648                .all(|c| c.is_ascii_alphanumeric() || c == '-'))
649        .then(|| version.to_owned())
650    })
651}
652
653/// `blog::controllers::pages::home` for functions, `Pages#home` for
654/// controller methods, `<closure>` for closures.
655fn handler_label<H>() -> String {
656    let name = type_name::<H>();
657    if name.contains("{{closure}}") {
658        return "<closure>".to_owned();
659    }
660    let mut segments = name.rsplit("::");
661    if let (Some(method), Some(owner)) = (segments.next(), segments.next())
662        && owner.starts_with(|c: char| c.is_ascii_uppercase())
663    {
664        // `PostsController#create` is `Posts#create`, as Rails labels it.
665        let owner = owner
666            .strip_suffix("Controller")
667            .filter(|short| !short.is_empty())
668            .unwrap_or(owner);
669        return format!("{owner}#{method}");
670    }
671    name.to_owned()
672}
673
674/// `Posts` for `app::controllers::PostsController`.
675fn short_type_name<T>() -> &'static str {
676    let name = type_name::<T>();
677    let base = name.split('<').next().unwrap_or(name);
678    let short = base.rsplit("::").next().unwrap_or(base);
679    short
680        .strip_suffix("Controller")
681        .filter(|s| !s.is_empty())
682        .unwrap_or(short)
683}
684
685fn join(prefix: &str, path: &str) -> String {
686    let joined = format!(
687        "{}/{}",
688        prefix.trim_end_matches('/'),
689        path.trim_matches('/')
690    );
691    if joined.len() > 1 {
692        joined.trim_end_matches('/').to_owned()
693    } else {
694        joined
695    }
696}
697
698fn parse_pattern(pattern: &str) -> Vec<Segment> {
699    let segments: Vec<Segment> = pattern
700        .split('/')
701        .filter(|s| !s.is_empty())
702        .map(|s| {
703            if let Some(param) = s.strip_prefix(':') {
704                let (name, suffix) = param.split_at(param.find('.').unwrap_or(param.len()));
705                Segment::Param(name.to_owned(), suffix.to_owned())
706            } else if let Some(name) = s.strip_prefix('*') {
707                Segment::Glob(name.to_owned())
708            } else {
709                Segment::Static(s.to_owned())
710            }
711        })
712        .collect();
713
714    if let Some(pos) = segments.iter().position(|s| matches!(s, Segment::Glob(_))) {
715        assert!(
716            pos == segments.len() - 1,
717            "glob segment must be last in route pattern `{pattern}`"
718        );
719    }
720    segments
721}
722
723/// Returns the captured params and a specificity rank (lower is more specific).
724fn match_segments(segments: &[Segment], parts: &[&str]) -> Option<(PathParams, Vec<u8>)> {
725    let mut params = PathParams::default();
726    let mut rank = Vec::with_capacity(segments.len());
727
728    for (i, segment) in segments.iter().enumerate() {
729        match segment {
730            Segment::Static(s) => {
731                if *parts.get(i)? != s.as_str() {
732                    return None;
733                }
734                rank.push(0);
735            }
736            // A suffixed param (`:id.json`) beats a bare one for `1.json`.
737            // As Rails' default `[^/.?]+`, a param stops at a dot, so
738            // `/posts/7.json` is post 7 as JSON; a `*glob` takes dots.
739            Segment::Param(name, suffix) => {
740                let value = parts.get(i)?.strip_suffix(suffix.as_str())?;
741                if value.is_empty() || value.contains('.') {
742                    return None;
743                }
744                params.push(name, decode(value));
745                rank.push(if suffix.is_empty() { 2 } else { 1 });
746            }
747            Segment::Glob(name) => {
748                let rest = parts.get(i..).filter(|rest| !rest.is_empty())?;
749                params.push(name, decode(&rest.join("/")));
750                rank.push(3);
751                return Some((params, rank));
752            }
753        }
754    }
755
756    (parts.len() == segments.len()).then_some((params, rank))
757}
758
759fn decode(s: &str) -> String {
760    percent_decode_str(s).decode_utf8_lossy().into_owned()
761}
762
763#[cfg(test)]
764mod tests {
765    use super::*;
766
767    async fn noop(_ctx: crate::Context) -> &'static str {
768        ""
769    }
770
771    fn found<'r>(router: &'r Router, method: Method, path: &str) -> Option<(&'r str, PathParams)> {
772        match router.recognize(&method, path) {
773            Match::Found(route, params) => Some((route.pattern(), params)),
774            _ => None,
775        }
776    }
777
778    #[test]
779    fn joins_prefixes() {
780        assert_eq!(join("", "/"), "/");
781        assert_eq!(join("", ""), "/");
782        assert_eq!(join("", "/posts"), "/posts");
783        assert_eq!(join("/admin", "/"), "/admin");
784        assert_eq!(join("/admin/", "users/"), "/admin/users");
785    }
786
787    #[test]
788    fn any_route_takes_a_format_extension() {
789        let mut router = Router::new();
790        router
791            .get("/posts", noop)
792            .get("/posts/:id", noop)
793            .get("/feed.xml", noop);
794        let (pattern, params) = found(&router, Method::GET, "/posts/7.json").unwrap();
795        assert_eq!(pattern, "/posts/:id");
796        assert_eq!(
797            (params.get("id"), params.get("format")),
798            (Some("7"), Some("json"))
799        );
800        assert_eq!(
801            found(&router, Method::GET, "/posts.json").unwrap().0,
802            "/posts"
803        );
804        assert_eq!(
805            found(&router, Method::GET, "/feed.xml").unwrap().0,
806            "/feed.xml"
807        );
808        assert!(found(&router, Method::GET, "/other.json").is_none());
809        // A version number isn't a format; a glob keeps its dots.
810        router.get("/versions/:platform/*version", noop);
811        let (_, params) = found(&router, Method::GET, "/versions/ios/3.2.0").unwrap();
812        assert_eq!(params.get("version"), Some("3.2.0"));
813        assert!(found(&router, Method::GET, "/posts/3.2.0").is_none());
814    }
815
816    #[test]
817    fn params_can_end_in_a_suffix() {
818        let mut router = Router::new();
819        router
820            .get("/reports/:id", noop)
821            .get("/reports/:id.json", noop);
822        let (pattern, params) = found(&router, Method::GET, "/reports/7.json").unwrap();
823        assert_eq!(pattern, "/reports/:id.json");
824        assert_eq!(params.get("id"), Some("7"));
825        assert_eq!(
826            found(&router, Method::GET, "/reports/7").unwrap().0,
827            "/reports/:id"
828        );
829        let (pattern, params) = found(&router, Method::GET, "/reports/7.xml").unwrap();
830        assert_eq!(pattern, "/reports/:id");
831        assert_eq!(
832            (params.get("id"), params.get("format")),
833            (Some("7"), Some("xml"))
834        );
835        assert!(
836            found(&router, Method::GET, "/reports/.json").is_none_or(|(p, _)| p == "/reports/:id")
837        );
838    }
839
840    #[test]
841    fn matches_root_and_trailing_slashes() {
842        let mut r = Router::new();
843        r.get("/", noop).get("/posts", noop);
844        assert_eq!(found(&r, Method::GET, "/").unwrap().0, "/");
845        assert_eq!(found(&r, Method::GET, "/posts/").unwrap().0, "/posts");
846    }
847
848    #[test]
849    fn captures_and_decodes_params() {
850        let mut r = Router::new();
851        r.get("/users/:id/posts/:slug", noop);
852        let (_, params) = found(&r, Method::GET, "/users/42/posts/hello%20world").unwrap();
853        assert_eq!(params.get("id"), Some("42"));
854        assert_eq!(params.get("slug"), Some("hello world"));
855    }
856
857    #[test]
858    fn static_beats_param_beats_glob_regardless_of_order() {
859        let mut r = Router::new();
860        r.get("/files/*path", noop)
861            .get("/files/:name", noop)
862            .get("/files/new", noop);
863        assert_eq!(
864            found(&r, Method::GET, "/files/new").unwrap().0,
865            "/files/new"
866        );
867        assert_eq!(
868            found(&r, Method::GET, "/files/a").unwrap().0,
869            "/files/:name"
870        );
871        // A param stops at a dot; a glob keeps the whole file name.
872        assert_eq!(
873            found(&r, Method::GET, "/files/a.txt")
874                .unwrap()
875                .1
876                .get("path"),
877            Some("a.txt")
878        );
879        let (pattern, params) = found(&r, Method::GET, "/files/a/b.txt").unwrap();
880        assert_eq!(pattern, "/files/*path");
881        assert_eq!(params.get("path"), Some("a/b.txt"));
882    }
883
884    #[test]
885    fn glob_requires_at_least_one_segment() {
886        let mut r = Router::new();
887        r.get("/files/*path", noop);
888        assert!(found(&r, Method::GET, "/files").is_none());
889    }
890
891    #[test]
892    fn reports_allowed_methods() {
893        let mut r = Router::new();
894        r.get("/posts", noop).post("/posts", noop);
895        match r.recognize(&Method::DELETE, "/posts") {
896            Match::MethodNotAllowed(allowed) => assert_eq!(allowed, [Method::GET, Method::POST]),
897            _ => panic!("expected 405"),
898        }
899        assert!(matches!(
900            r.recognize(&Method::GET, "/nope"),
901            Match::NotFound
902        ));
903    }
904
905    #[test]
906    fn head_falls_back_to_get() {
907        let mut r = Router::new();
908        r.get("/posts", noop);
909        assert!(found(&r, Method::HEAD, "/posts").is_some());
910    }
911
912    #[test]
913    fn labels_handlers_and_resources() {
914        struct Posts;
915        impl Resource for Posts {}
916
917        let mut r = Router::new();
918        r.get("/", noop)
919            .get("/c", |_ctx| async { "" })
920            .resources_only::<Posts>("posts", &[Action::Show]);
921        let labels: Vec<&str> = r.routes().iter().map(Route::label).collect();
922        assert_eq!(
923            labels,
924            ["glacier::router::tests::noop", "<closure>", "Posts#show"]
925        );
926        assert!(r.describe().contains("GET  /posts/:id  Posts#show"));
927    }
928
929    #[test]
930    #[should_panic(expected = "glob segment must be last")]
931    fn rejects_glob_in_the_middle() {
932        Router::new().get("/a/*rest/b", noop);
933    }
934}