use std::any::type_name;
use std::fmt::Write;
use std::sync::Arc;
use http::Method;
use percent_encoding::{AsciiSet, CONTROLS, percent_decode_str, utf8_percent_encode};
use crate::context::PathParams;
use crate::controller::{Action, Resource};
use crate::handler::Handler;
use crate::middleware::{Middleware, Pipeline};
#[derive(Debug, Clone, PartialEq, Eq)]
enum Segment {
Static(String),
Param(String, String),
Glob(String),
}
pub struct Route {
method: Method,
pattern: String,
segments: Vec<Segment>,
label: String,
pub(crate) handler: Arc<dyn Handler>,
pub(crate) stack: Arc<[Arc<dyn Middleware>]>,
constraints: Vec<(String, regex::Regex)>,
version: Option<Version>,
}
type Docs = fn() -> Vec<crate::openapi::ActionDoc>;
#[derive(Debug, Clone)]
pub(crate) struct Version {
pub(crate) name: String,
pub(crate) default: bool,
}
impl Route {
pub fn method(&self) -> &Method {
&self.method
}
pub fn pattern(&self) -> &str {
&self.pattern
}
pub fn label(&self) -> &str {
&self.label
}
pub(crate) fn answers(&self, requested: Option<&str>) -> bool {
match (&self.version, requested) {
(None, _) => true,
(Some(version), Some(requested)) => version.name == requested,
(Some(version), None) => version.default,
}
}
pub(crate) fn is_versioned(&self) -> bool {
self.version.is_some()
}
}
pub(crate) enum Match<'r> {
Found(&'r Route, PathParams),
MethodNotAllowed(Vec<Method>),
NotFound,
}
#[derive(Default)]
pub struct Router {
prefix: String,
middleware: Vec<Arc<dyn Middleware>>,
routes: Vec<Route>,
docs: Vec<(&'static str, Docs)>,
version: Option<Version>,
}
impl Router {
pub fn new() -> Self {
Self::default()
}
pub fn route<H: Handler>(&mut self, method: Method, path: &str, handler: H) -> &mut Self {
self.add(method, path, Arc::new(handler), handler_label::<H>())
}
fn add(
&mut self,
method: Method,
path: &str,
handler: Arc<dyn Handler>,
label: String,
) -> &mut Self {
let pattern = join(&self.prefix, path);
let segments = parse_pattern(&pattern);
self.routes.push(Route {
method,
pattern,
segments,
label,
handler,
stack: self.middleware.clone().into(),
constraints: Vec::new(),
version: self.version.clone(),
});
self
}
pub fn constrain(&mut self, param: &str, pattern: &str) -> &mut Self {
let regex = regex::Regex::new(&format!("^(?:{pattern})$"))
.unwrap_or_else(|e| panic!("invalid constraint for `{param}`: {e}"));
self.routes
.last_mut()
.expect("constrain follows a route")
.constraints
.push((param.to_owned(), regex));
self
}
pub fn get(&mut self, path: &str, handler: impl Handler) -> &mut Self {
self.route(Method::GET, path, handler)
}
pub fn post(&mut self, path: &str, handler: impl Handler) -> &mut Self {
self.route(Method::POST, path, handler)
}
pub fn put(&mut self, path: &str, handler: impl Handler) -> &mut Self {
self.route(Method::PUT, path, handler)
}
pub fn patch(&mut self, path: &str, handler: impl Handler) -> &mut Self {
self.route(Method::PATCH, path, handler)
}
pub fn delete(&mut self, path: &str, handler: impl Handler) -> &mut Self {
self.route(Method::DELETE, path, handler)
}
pub fn scope(&mut self, prefix: &str, draw: impl FnOnce(&mut Router)) -> &mut Self {
self.nested(join(&self.prefix, prefix), Vec::new(), draw)
}
pub fn pipe_through(
&mut self,
pipeline: &Pipeline,
draw: impl FnOnce(&mut Router),
) -> &mut Self {
self.nested(self.prefix.clone(), pipeline.stack.clone(), draw)
}
pub fn version(
&mut self,
name: &str,
default: bool,
draw: impl FnOnce(&mut Router),
) -> &mut Self {
let outer = self.version.replace(Version {
name: name.to_owned(),
default,
});
self.nested(self.prefix.clone(), Vec::new(), draw);
self.version = outer;
self
}
fn nested(
&mut self,
prefix: String,
extra: Vec<Arc<dyn Middleware>>,
draw: impl FnOnce(&mut Router),
) -> &mut Self {
let mut middleware = self.middleware.clone();
middleware.extend(extra);
let mut nested = Router {
prefix,
middleware,
routes: Vec::new(),
docs: Vec::new(),
version: self.version.clone(),
};
draw(&mut nested);
self.routes.extend(nested.routes);
for (name, docs) in nested.docs {
self.add_docs(name, docs);
}
self
}
pub fn document<C: crate::openapi::Documented>(&mut self) -> &mut Self {
self.add_docs(short_type_name::<C>(), C::actions);
self
}
fn add_docs(&mut self, name: &'static str, docs: Docs) {
if !self.docs.iter().any(|(n, _)| *n == name) {
self.docs.push((name, docs));
}
}
pub(crate) fn docs_for(&self, name: &str) -> Vec<crate::openapi::ActionDoc> {
self.docs
.iter()
.find(|(n, _)| *n == name)
.map(|(_, docs)| docs())
.unwrap_or_default()
}
pub(crate) fn route_constraints(route: &Route) -> Vec<(&str, &str)> {
route
.constraints
.iter()
.map(|(param, pattern)| (param.as_str(), pattern.as_str()))
.collect()
}
pub fn resources<R: Resource>(&mut self, name: &str) -> &mut Self {
self.resources_only::<R>(name, R::ACTIONS)
}
pub fn resources_only<R: Resource>(&mut self, name: &str, actions: &[Action]) -> &mut Self {
let base = format!("/{}", name.trim_matches('/'));
let full = join(&self.prefix, &base);
if full.contains("/:") {
let table = base.rsplit('/').next().unwrap_or_default().to_owned();
NESTED
.write()
.unwrap_or_else(|e| e.into_inner())
.insert(table, full);
}
let member = format!("{base}/:id");
let controller = short_type_name::<R>();
let label = |action: &str| format!("{controller}#{action}");
for action in actions {
match action {
Action::Index => self.add(Method::GET, &base, Arc::new(R::index), label("index")),
Action::New => self.add(
Method::GET,
&format!("{base}/new"),
Arc::new(R::new),
label("new"),
),
Action::Create => {
self.add(Method::POST, &base, Arc::new(R::create), label("create"))
}
Action::Show => self.add(Method::GET, &member, Arc::new(R::show), label("show")),
Action::Edit => self.add(
Method::GET,
&format!("{member}/edit"),
Arc::new(R::edit),
label("edit"),
),
Action::Update => self
.add(Method::PATCH, &member, Arc::new(R::update), label("update"))
.add(Method::PUT, &member, Arc::new(R::update), label("update")),
Action::Destroy => self.add(
Method::DELETE,
&member,
Arc::new(R::destroy),
label("destroy"),
),
};
}
self
}
pub fn routes(&self) -> &[Route] {
&self.routes
}
pub fn describe(&self) -> String {
let method_width = self
.routes
.iter()
.map(|r| r.method.as_str().len())
.max()
.unwrap_or(0);
let pattern_width = self
.routes
.iter()
.map(|r| r.pattern.len())
.max()
.unwrap_or(0);
let mut out = String::new();
for route in &self.routes {
let _ = writeln!(
out,
"{:<method_width$} {:<pattern_width$} {}",
route.method.as_str(),
route.pattern,
route.label
);
}
out
}
#[cfg(test)]
pub(crate) fn recognize(&self, method: &Method, path: &str) -> Match<'_> {
self.recognize_version(method, path, None)
}
pub(crate) fn recognize_version(
&self,
method: &Method,
path: &str,
requested: Option<&str>,
) -> Match<'_> {
let found = self.recognize_exact(method, path, requested);
if !matches!(found, Match::NotFound) {
return found;
}
let last = path.rsplit('/').next().unwrap_or("");
let Some((stem, format)) = last.rsplit_once('.') else {
return found;
};
let is_format = format.starts_with(|c: char| c.is_ascii_alphabetic())
&& format.chars().all(|c| c.is_ascii_alphanumeric());
if stem.is_empty() || !is_format {
return found;
}
let bare = &path[..path.len() - format.len() - 1];
match self.recognize_exact(method, bare, requested) {
Match::Found(route, mut params) => {
params.push("format", format.to_owned());
Match::Found(route, params)
}
Match::MethodNotAllowed(allowed) => Match::MethodNotAllowed(allowed),
Match::NotFound => found,
}
}
fn recognize_exact(&self, method: &Method, path: &str, requested: Option<&str>) -> Match<'_> {
let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
let mut best: Option<(&Route, PathParams, Vec<u8>)> = None;
let mut allowed: Vec<Method> = Vec::new();
for route in &self.routes {
let Some((params, rank)) = match_segments(&route.segments, &parts) else {
continue;
};
let constrained = route.constraints.iter().any(|(name, pattern)| {
!params
.get(name)
.is_some_and(|value| pattern.is_match(value))
});
if constrained {
continue;
}
if !route.answers(requested) {
continue;
}
let method_matches =
route.method == *method || (*method == Method::HEAD && route.method == Method::GET);
if method_matches {
let better = best.as_ref().is_none_or(|(best_route, _, best_rank)| {
rank < *best_rank
|| (rank == *best_rank
&& requested.is_some()
&& route.is_versioned()
&& !best_route.is_versioned())
});
if better {
best = Some((route, params, rank));
}
} else if !allowed.contains(&route.method) {
allowed.push(route.method.clone());
}
}
match best {
Some((route, params, _)) => Match::Found(route, params),
None if !allowed.is_empty() => Match::MethodNotAllowed(allowed),
None => Match::NotFound,
}
}
}
pub trait ToPath {
fn to_path(&self) -> String;
}
impl ToPath for str {
fn to_path(&self) -> String {
self.to_owned()
}
}
impl ToPath for String {
fn to_path(&self) -> String {
self.clone()
}
}
impl<T: ToPath + ?Sized> ToPath for &T {
fn to_path(&self) -> String {
(**self).to_path()
}
}
const SEGMENT: &AsciiSet = &CONTROLS
.add(b' ')
.add(b'"')
.add(b'#')
.add(b'%')
.add(b'/')
.add(b'<')
.add(b'>')
.add(b'?')
.add(b'[')
.add(b'\\')
.add(b']')
.add(b'^')
.add(b'`')
.add(b'{')
.add(b'|')
.add(b'}');
tokio::task_local! {
static PATH_PREFIX: String;
}
static NESTED: std::sync::RwLock<std::collections::BTreeMap<String, String>> =
std::sync::RwLock::new(std::collections::BTreeMap::new());
#[derive(Clone)]
pub(crate) struct RouteParams(pub(crate) crate::context::PathParams);
#[doc(hidden)]
pub fn collection_path_of(table: &str, value: impl Fn(&str) -> Option<String>) -> String {
let nested = NESTED
.read()
.unwrap_or_else(|e| e.into_inner())
.get(table)
.cloned();
let Some(pattern) = nested else {
return prefixed(format!("/{table}"));
};
let current = crate::current::get::<RouteParams>();
let mut path = String::new();
for segment in pattern.split('/').filter(|s| !s.is_empty()) {
path.push('/');
match segment.strip_prefix(':') {
Some(param) => {
let filled = value(param).or_else(|| {
current
.as_ref()
.and_then(|c| c.0.get(param).map(str::to_owned))
});
match filled {
Some(filled) => path.push_str(&encode_segment(&filled)),
None => path.push_str(segment),
}
}
None => path.push_str(segment),
}
}
prefixed(path)
}
pub async fn with_path_prefix<F: std::future::Future>(prefix: String, fut: F) -> F::Output {
PATH_PREFIX.scope(prefix, fut).await
}
#[doc(hidden)]
pub fn prefixed(path: String) -> String {
PATH_PREFIX
.try_with(|prefix| {
if path == "/" {
prefix.clone()
} else {
format!("{prefix}{path}")
}
})
.unwrap_or(path)
}
pub fn url_for(path: impl crate::router::ToPath) -> crate::Result<String> {
let base = crate::Config::current()?.url()?;
Ok(format!("{base}{}", path.to_path()))
}
#[doc(hidden)]
pub fn encode_segment(s: &str) -> String {
utf8_percent_encode(s, SEGMENT).to_string()
}
#[doc(hidden)]
pub fn encode_path(s: &str) -> String {
s.split('/')
.map(encode_segment)
.collect::<Vec<_>>()
.join("/")
}
pub(crate) fn requested_version(headers: &http::HeaderMap) -> Option<String> {
if let Some(version) = headers
.get("api-version")
.and_then(|v| v.to_str().ok())
.map(str::trim)
.filter(|v| !v.is_empty())
{
return Some(version.trim_start_matches(['v', 'V']).to_owned());
}
let accept = headers.get(http::header::ACCEPT)?.to_str().ok()?;
accept.split(',').find_map(|media| {
let mut parts = media.split(';').map(str::trim);
let ty = parts.next()?;
if let Some(version) = parts.find_map(|p| p.strip_prefix("version=")) {
return Some(
version
.trim_matches('"')
.trim_start_matches(['v', 'V'])
.to_owned(),
);
}
let vendor = ty.strip_prefix("application/vnd.")?;
let name = vendor.split('+').next()?;
let version = name.rsplit('.').next()?.strip_prefix(['v', 'V'])?;
(!version.is_empty()
&& version
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-'))
.then(|| version.to_owned())
})
}
fn handler_label<H>() -> String {
let name = type_name::<H>();
if name.contains("{{closure}}") {
return "<closure>".to_owned();
}
let mut segments = name.rsplit("::");
if let (Some(method), Some(owner)) = (segments.next(), segments.next())
&& owner.starts_with(|c: char| c.is_ascii_uppercase())
{
let owner = owner
.strip_suffix("Controller")
.filter(|short| !short.is_empty())
.unwrap_or(owner);
return format!("{owner}#{method}");
}
name.to_owned()
}
fn short_type_name<T>() -> &'static str {
let name = type_name::<T>();
let base = name.split('<').next().unwrap_or(name);
let short = base.rsplit("::").next().unwrap_or(base);
short
.strip_suffix("Controller")
.filter(|s| !s.is_empty())
.unwrap_or(short)
}
fn join(prefix: &str, path: &str) -> String {
let joined = format!(
"{}/{}",
prefix.trim_end_matches('/'),
path.trim_matches('/')
);
if joined.len() > 1 {
joined.trim_end_matches('/').to_owned()
} else {
joined
}
}
fn parse_pattern(pattern: &str) -> Vec<Segment> {
let segments: Vec<Segment> = pattern
.split('/')
.filter(|s| !s.is_empty())
.map(|s| {
if let Some(param) = s.strip_prefix(':') {
let (name, suffix) = param.split_at(param.find('.').unwrap_or(param.len()));
Segment::Param(name.to_owned(), suffix.to_owned())
} else if let Some(name) = s.strip_prefix('*') {
Segment::Glob(name.to_owned())
} else {
Segment::Static(s.to_owned())
}
})
.collect();
if let Some(pos) = segments.iter().position(|s| matches!(s, Segment::Glob(_))) {
assert!(
pos == segments.len() - 1,
"glob segment must be last in route pattern `{pattern}`"
);
}
segments
}
fn match_segments(segments: &[Segment], parts: &[&str]) -> Option<(PathParams, Vec<u8>)> {
let mut params = PathParams::default();
let mut rank = Vec::with_capacity(segments.len());
for (i, segment) in segments.iter().enumerate() {
match segment {
Segment::Static(s) => {
if *parts.get(i)? != s.as_str() {
return None;
}
rank.push(0);
}
Segment::Param(name, suffix) => {
let value = parts.get(i)?.strip_suffix(suffix.as_str())?;
if value.is_empty() || value.contains('.') {
return None;
}
params.push(name, decode(value));
rank.push(if suffix.is_empty() { 2 } else { 1 });
}
Segment::Glob(name) => {
let rest = parts.get(i..).filter(|rest| !rest.is_empty())?;
params.push(name, decode(&rest.join("/")));
rank.push(3);
return Some((params, rank));
}
}
}
(parts.len() == segments.len()).then_some((params, rank))
}
fn decode(s: &str) -> String {
percent_decode_str(s).decode_utf8_lossy().into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
async fn noop(_ctx: crate::Context) -> &'static str {
""
}
fn found<'r>(router: &'r Router, method: Method, path: &str) -> Option<(&'r str, PathParams)> {
match router.recognize(&method, path) {
Match::Found(route, params) => Some((route.pattern(), params)),
_ => None,
}
}
#[test]
fn joins_prefixes() {
assert_eq!(join("", "/"), "/");
assert_eq!(join("", ""), "/");
assert_eq!(join("", "/posts"), "/posts");
assert_eq!(join("/admin", "/"), "/admin");
assert_eq!(join("/admin/", "users/"), "/admin/users");
}
#[test]
fn any_route_takes_a_format_extension() {
let mut router = Router::new();
router
.get("/posts", noop)
.get("/posts/:id", noop)
.get("/feed.xml", noop);
let (pattern, params) = found(&router, Method::GET, "/posts/7.json").unwrap();
assert_eq!(pattern, "/posts/:id");
assert_eq!(
(params.get("id"), params.get("format")),
(Some("7"), Some("json"))
);
assert_eq!(
found(&router, Method::GET, "/posts.json").unwrap().0,
"/posts"
);
assert_eq!(
found(&router, Method::GET, "/feed.xml").unwrap().0,
"/feed.xml"
);
assert!(found(&router, Method::GET, "/other.json").is_none());
router.get("/versions/:platform/*version", noop);
let (_, params) = found(&router, Method::GET, "/versions/ios/3.2.0").unwrap();
assert_eq!(params.get("version"), Some("3.2.0"));
assert!(found(&router, Method::GET, "/posts/3.2.0").is_none());
}
#[test]
fn params_can_end_in_a_suffix() {
let mut router = Router::new();
router
.get("/reports/:id", noop)
.get("/reports/:id.json", noop);
let (pattern, params) = found(&router, Method::GET, "/reports/7.json").unwrap();
assert_eq!(pattern, "/reports/:id.json");
assert_eq!(params.get("id"), Some("7"));
assert_eq!(
found(&router, Method::GET, "/reports/7").unwrap().0,
"/reports/:id"
);
let (pattern, params) = found(&router, Method::GET, "/reports/7.xml").unwrap();
assert_eq!(pattern, "/reports/:id");
assert_eq!(
(params.get("id"), params.get("format")),
(Some("7"), Some("xml"))
);
assert!(
found(&router, Method::GET, "/reports/.json").is_none_or(|(p, _)| p == "/reports/:id")
);
}
#[test]
fn matches_root_and_trailing_slashes() {
let mut r = Router::new();
r.get("/", noop).get("/posts", noop);
assert_eq!(found(&r, Method::GET, "/").unwrap().0, "/");
assert_eq!(found(&r, Method::GET, "/posts/").unwrap().0, "/posts");
}
#[test]
fn captures_and_decodes_params() {
let mut r = Router::new();
r.get("/users/:id/posts/:slug", noop);
let (_, params) = found(&r, Method::GET, "/users/42/posts/hello%20world").unwrap();
assert_eq!(params.get("id"), Some("42"));
assert_eq!(params.get("slug"), Some("hello world"));
}
#[test]
fn static_beats_param_beats_glob_regardless_of_order() {
let mut r = Router::new();
r.get("/files/*path", noop)
.get("/files/:name", noop)
.get("/files/new", noop);
assert_eq!(
found(&r, Method::GET, "/files/new").unwrap().0,
"/files/new"
);
assert_eq!(
found(&r, Method::GET, "/files/a").unwrap().0,
"/files/:name"
);
assert_eq!(
found(&r, Method::GET, "/files/a.txt")
.unwrap()
.1
.get("path"),
Some("a.txt")
);
let (pattern, params) = found(&r, Method::GET, "/files/a/b.txt").unwrap();
assert_eq!(pattern, "/files/*path");
assert_eq!(params.get("path"), Some("a/b.txt"));
}
#[test]
fn glob_requires_at_least_one_segment() {
let mut r = Router::new();
r.get("/files/*path", noop);
assert!(found(&r, Method::GET, "/files").is_none());
}
#[test]
fn reports_allowed_methods() {
let mut r = Router::new();
r.get("/posts", noop).post("/posts", noop);
match r.recognize(&Method::DELETE, "/posts") {
Match::MethodNotAllowed(allowed) => assert_eq!(allowed, [Method::GET, Method::POST]),
_ => panic!("expected 405"),
}
assert!(matches!(
r.recognize(&Method::GET, "/nope"),
Match::NotFound
));
}
#[test]
fn head_falls_back_to_get() {
let mut r = Router::new();
r.get("/posts", noop);
assert!(found(&r, Method::HEAD, "/posts").is_some());
}
#[test]
fn labels_handlers_and_resources() {
struct Posts;
impl Resource for Posts {}
let mut r = Router::new();
r.get("/", noop)
.get("/c", |_ctx| async { "" })
.resources_only::<Posts>("posts", &[Action::Show]);
let labels: Vec<&str> = r.routes().iter().map(Route::label).collect();
assert_eq!(
labels,
["glacier::router::tests::noop", "<closure>", "Posts#show"]
);
assert!(r.describe().contains("GET /posts/:id Posts#show"));
}
#[test]
#[should_panic(expected = "glob segment must be last")]
fn rejects_glob_in_the_middle() {
Router::new().get("/a/*rest/b", noop);
}
}