Skip to main content

phoenix_routing/
lib.rs

1use std::{
2    collections::{HashMap, HashSet},
3    fmt,
4    panic::AssertUnwindSafe,
5    sync::Arc,
6};
7
8use bytes::Bytes;
9use futures_util::FutureExt;
10pub use http::Method;
11use http::{HeaderValue, StatusCode, header, uri::Authority};
12use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
13use phoenix_http::{
14    Handler, IntoResponse, Middleware, Request, RequestBodyMode, Response, RouteManifest,
15    apply_middleware,
16};
17use thiserror::Error;
18
19const PATH_SEGMENT_ENCODE_SET: &AsciiSet = &NON_ALPHANUMERIC
20    .remove(b'-')
21    .remove(b'.')
22    .remove(b'_')
23    .remove(b'~');
24
25type MatchedRoute = (usize, Vec<(String, String)>);
26
27#[derive(Clone, Copy, Debug)]
28struct InvalidPathParameter;
29
30struct RouteDefinition {
31    method: Method,
32    path: String,
33    name: Option<String>,
34    handler: Arc<dyn Handler>,
35    body_mode: RequestBodyMode,
36    middleware: Vec<Arc<dyn Middleware>>,
37}
38
39#[derive(Default)]
40pub struct Routes {
41    definitions: Vec<RouteDefinition>,
42    global_middleware: Vec<Arc<dyn Middleware>>,
43    error: Option<RouteBuildError>,
44}
45
46impl Routes {
47    #[must_use]
48    pub fn new() -> Self {
49        Self::default()
50    }
51
52    #[must_use]
53    pub fn get<H>(self, path: impl Into<String>, handler: H) -> Self
54    where
55        H: Handler,
56    {
57        self.route(Method::GET, path, handler)
58    }
59
60    #[must_use]
61    pub fn post<H>(self, path: impl Into<String>, handler: H) -> Self
62    where
63        H: Handler,
64    {
65        self.route(Method::POST, path, handler)
66    }
67
68    #[must_use]
69    pub fn put<H>(self, path: impl Into<String>, handler: H) -> Self
70    where
71        H: Handler,
72    {
73        self.route(Method::PUT, path, handler)
74    }
75
76    #[must_use]
77    pub fn patch<H>(self, path: impl Into<String>, handler: H) -> Self
78    where
79        H: Handler,
80    {
81        self.route(Method::PATCH, path, handler)
82    }
83
84    #[must_use]
85    pub fn delete<H>(self, path: impl Into<String>, handler: H) -> Self
86    where
87        H: Handler,
88    {
89        self.route(Method::DELETE, path, handler)
90    }
91
92    #[must_use]
93    pub fn route<H>(mut self, method: Method, path: impl Into<String>, handler: H) -> Self
94    where
95        H: Handler,
96    {
97        let body_mode = handler.request_body_mode();
98        self.definitions.push(RouteDefinition {
99            method,
100            path: normalize_path(&path.into()),
101            name: None,
102            handler: Arc::new(handler),
103            body_mode,
104            middleware: Vec::new(),
105        });
106        self
107    }
108
109    #[must_use]
110    pub fn name(mut self, name: impl Into<String>) -> Self {
111        if let Some(route) = self.definitions.last_mut() {
112            route.name = Some(name.into());
113        } else {
114            self.error = Some(RouteBuildError::NoRouteToConfigure("name"));
115        }
116        self
117    }
118
119    /// Bind browser action input and output contracts to the most recently
120    /// declared route. The Rust types are consumed by Phoenix's build tooling;
121    /// request extraction and response serialization remain compiler checked
122    /// by the registered handler.
123    #[must_use]
124    pub fn action<Input, Output>(mut self) -> Self {
125        if self.definitions.last().is_none() {
126            self.error = Some(RouteBuildError::NoRouteToConfigure("action"));
127        }
128        self
129    }
130
131    #[must_use]
132    pub fn middleware<M>(mut self, middleware: M) -> Self
133    where
134        M: Middleware,
135    {
136        if let Some(route) = self.definitions.last_mut() {
137            route.middleware.push(Arc::new(middleware));
138        } else {
139            self.error = Some(RouteBuildError::NoRouteToConfigure("middleware"));
140        }
141        self
142    }
143
144    #[must_use]
145    pub fn with_middleware<M>(mut self, middleware: M) -> Self
146    where
147        M: Middleware,
148    {
149        self.global_middleware.push(Arc::new(middleware));
150        self
151    }
152
153    /// Number of route declarations currently registered (before [`Self::build`]).
154    #[must_use]
155    pub fn len(&self) -> usize {
156        self.definitions.len()
157    }
158
159    /// Return true when no route declarations are registered.
160    #[must_use]
161    pub fn is_empty(&self) -> bool {
162        self.definitions.is_empty()
163    }
164
165    /// Merge declarations from another route file while preserving their
166    /// registration order. Global middleware from `other` remains scoped to
167    /// the imported declarations.
168    #[must_use]
169    pub fn merge(mut self, mut other: Self) -> Self {
170        if self.error.is_none() {
171            self.error = other.error.take();
172        }
173        let imported_globals = other.global_middleware;
174        for mut definition in other.definitions {
175            let mut middleware = imported_globals.clone();
176            middleware.append(&mut definition.middleware);
177            definition.middleware = middleware;
178            self.definitions.push(definition);
179        }
180        self
181    }
182
183    #[must_use]
184    pub fn group<F>(mut self, group: RouteGroup, configure: F) -> Self
185    where
186        F: FnOnce(Routes) -> Routes,
187    {
188        let RouteGroup {
189            prefix,
190            name_prefix,
191            middleware: group_middleware,
192        } = group;
193        let child = configure(Self::new());
194        if self.error.is_none() {
195            self.error = child.error;
196        }
197
198        for mut route in child.definitions {
199            route.path = join_paths(&prefix, &route.path);
200            route.name = route.name.map(|name| format!("{name_prefix}{name}"));
201
202            let mut middleware = group_middleware.clone();
203            middleware.extend(child.global_middleware.iter().cloned());
204            middleware.extend(route.middleware);
205            route.middleware = middleware;
206            self.definitions.push(route);
207        }
208        self
209    }
210
211    /// Apply a path/name/middleware scope to an existing route collection.
212    #[must_use]
213    pub fn scoped(self, group: RouteGroup) -> Self {
214        Self::new().group(group, |_| self)
215    }
216
217    /// Compile route definitions into an immutable request router.
218    ///
219    /// # Errors
220    ///
221    /// Returns an error for invalid patterns, duplicate names, or configuration
222    /// calls that did not target a registered route.
223    pub fn build(self) -> Result<Router, RouteBuildError> {
224        if let Some(error) = self.error {
225            return Err(error);
226        }
227
228        let mut method_routers: HashMap<Method, matchit::Router<usize>> = HashMap::new();
229        let mut named_routes = HashMap::new();
230        let mut compiled_routes = Vec::with_capacity(self.definitions.len());
231
232        for definition in self.definitions {
233            let index = compiled_routes.len();
234            let method = definition.method.clone();
235            let path = definition.path.clone();
236
237            method_routers
238                .entry(method.clone())
239                .or_default()
240                .insert(path.clone(), index)
241                .map_err(|error| RouteBuildError::InvalidPattern {
242                    method: method.clone(),
243                    path: path.clone(),
244                    reason: error.to_string(),
245                })?;
246
247            if let Some(name) = &definition.name
248                && named_routes.insert(name.clone(), path.clone()).is_some()
249            {
250                return Err(RouteBuildError::DuplicateName(name.clone()));
251            }
252
253            compiled_routes.push(CompiledRoute {
254                name: definition.name,
255                body_mode: definition.body_mode,
256                handler: apply_middleware(definition.handler, &definition.middleware),
257            });
258        }
259
260        let inner = Arc::new(RouterInner {
261            method_routers,
262            routes: compiled_routes,
263        });
264        let dispatch: Arc<dyn Handler> = Arc::new(DispatchHandler {
265            inner: Arc::clone(&inner),
266        });
267        let dispatch: Arc<dyn Handler> = Arc::new(PanicBoundary { next: dispatch });
268        let handler = apply_middleware(dispatch, &self.global_middleware);
269
270        Ok(Router {
271            handler: Arc::new(PanicBoundary { next: handler }),
272            named_routes: Arc::new(named_routes),
273            body_modes: BodyModeRouter::Single(inner),
274        })
275    }
276}
277
278#[derive(Clone, Default)]
279pub struct RouteGroup {
280    prefix: String,
281    name_prefix: String,
282    middleware: Vec<Arc<dyn Middleware>>,
283}
284
285impl RouteGroup {
286    #[must_use]
287    pub fn new() -> Self {
288        Self::default()
289    }
290
291    #[must_use]
292    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
293        self.prefix = normalize_prefix(&prefix.into());
294        self
295    }
296
297    #[must_use]
298    pub fn name(mut self, prefix: impl Into<String>) -> Self {
299        self.name_prefix = prefix.into();
300        self
301    }
302
303    #[must_use]
304    pub fn middleware<M>(mut self, middleware: M) -> Self
305    where
306        M: Middleware,
307    {
308        self.middleware.push(Arc::new(middleware));
309        self
310    }
311}
312
313#[derive(Clone)]
314pub struct Router {
315    handler: Arc<dyn Handler>,
316    named_routes: Arc<HashMap<String, String>>,
317    body_modes: BodyModeRouter,
318}
319
320#[derive(Clone)]
321enum BodyModeRouter {
322    Single(Arc<RouterInner>),
323    Multi(Arc<Vec<RouterMount>>),
324}
325
326/// Metadata for the application module selected for the current request.
327#[derive(Clone, Debug, Eq, PartialEq)]
328pub struct ApplicationContext {
329    name: Arc<str>,
330    path_prefix: Arc<str>,
331    host: Option<Arc<str>>,
332}
333
334impl ApplicationContext {
335    #[must_use]
336    pub fn name(&self) -> &str {
337        &self.name
338    }
339
340    #[must_use]
341    pub fn path_prefix(&self) -> &str {
342        &self.path_prefix
343    }
344
345    #[must_use]
346    pub fn host(&self) -> Option<&str> {
347        self.host.as_deref()
348    }
349}
350
351/// One independently compiled router mounted into a multi-application router.
352pub struct RouterMount {
353    context: ApplicationContext,
354    match_prefix: String,
355    authority: Option<Authority>,
356    router: Router,
357}
358
359impl RouterMount {
360    /// Construct and validate a router mount.
361    ///
362    /// # Errors
363    ///
364    /// Returns an error for invalid application names or Host authorities.
365    pub fn new(
366        name: impl Into<String>,
367        path_prefix: impl Into<String>,
368        host: Option<impl Into<String>>,
369        router: Router,
370    ) -> Result<Self, MultiRouterError> {
371        let name = name.into();
372        if !valid_application_name(&name) {
373            return Err(MultiRouterError::InvalidApplicationName(name));
374        }
375        let match_prefix = normalize_prefix(&path_prefix.into());
376        let display_prefix = if match_prefix.is_empty() {
377            "/".to_owned()
378        } else {
379            match_prefix.clone()
380        };
381        let (authority, display_host) = match host.map(Into::into) {
382            Some(host) => {
383                let normalized = host.trim().to_ascii_lowercase();
384                let authority = normalized
385                    .parse::<Authority>()
386                    .map_err(|_| MultiRouterError::InvalidHost(host))?;
387                (Some(authority), Some(Arc::from(normalized)))
388            }
389            None => (None, None),
390        };
391        Ok(Self {
392            context: ApplicationContext {
393                name: Arc::from(name),
394                path_prefix: Arc::from(display_prefix),
395                host: display_host,
396            },
397            match_prefix,
398            authority,
399            router,
400        })
401    }
402}
403
404impl fmt::Debug for Router {
405    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
406        formatter
407            .debug_struct("Router")
408            .field("named_routes", &self.named_routes)
409            .finish_non_exhaustive()
410    }
411}
412
413impl Router {
414    /// Compose independently built routers using Host and path-prefix selection.
415    ///
416    /// Host-bound mounts win over hostless fallbacks, explicit ports win over
417    /// host-only bindings, and longer path prefixes win over shorter prefixes.
418    ///
419    /// # Errors
420    ///
421    /// Returns an error for empty sets, duplicate application names/selectors,
422    /// or duplicate global route names.
423    pub fn multi(mounts: Vec<RouterMount>) -> Result<Self, MultiRouterError> {
424        if mounts.is_empty() {
425            return Err(MultiRouterError::Empty);
426        }
427        let mut application_names = HashSet::new();
428        let mut selectors = HashSet::new();
429        let mut named_routes = HashMap::new();
430        for mount in &mounts {
431            if !application_names.insert(mount.context.name.to_string()) {
432                return Err(MultiRouterError::DuplicateApplication(
433                    mount.context.name.to_string(),
434                ));
435            }
436            let selector = (
437                mount.authority.as_ref().map(ToString::to_string),
438                mount.match_prefix.clone(),
439            );
440            if !selectors.insert(selector.clone()) {
441                return Err(MultiRouterError::DuplicateSelector {
442                    host: selector.0,
443                    path_prefix: display_prefix(&selector.1),
444                });
445            }
446            for (name, path) in mount.router.named_routes.iter() {
447                if named_routes.insert(name.clone(), path.clone()).is_some() {
448                    return Err(MultiRouterError::DuplicateRouteName(name.clone()));
449                }
450            }
451        }
452        let mounts = Arc::new(mounts);
453        let dispatch: Arc<dyn Handler> = Arc::new(MultiDispatch {
454            mounts: Arc::clone(&mounts),
455        });
456        Ok(Self {
457            handler: Arc::new(PanicBoundary { next: dispatch }),
458            named_routes: Arc::new(named_routes),
459            body_modes: BodyModeRouter::Multi(mounts),
460        })
461    }
462
463    pub async fn handle(&self, mut request: Request) -> Response {
464        request
465            .extensions_mut()
466            .insert(RouteManifest::new(Arc::clone(&self.named_routes)));
467        self.handler.call(request).await
468    }
469
470    #[doc(hidden)]
471    #[must_use]
472    pub fn request_body_mode(&self, request: &Request) -> RequestBodyMode {
473        match &self.body_modes {
474            BodyModeRouter::Single(inner) => {
475                inner.request_body_mode(request.method(), request.uri().path())
476            }
477            BodyModeRouter::Multi(mounts) => select_mount(mounts, request)
478                .map_or(RequestBodyMode::Buffered, |mount| {
479                    mount.router.request_body_mode(request)
480                }),
481        }
482    }
483
484    /// Generate a URL from a Laravel-style named route.
485    ///
486    /// # Errors
487    ///
488    /// Returns an error when the route name is unknown or a required path
489    /// parameter is missing.
490    pub fn url(&self, name: &str, params: &[(&str, &str)]) -> Result<String, UrlGenerationError> {
491        let pattern = self
492            .named_routes
493            .get(name)
494            .ok_or_else(|| UrlGenerationError::UnknownRoute(name.to_owned()))?;
495        let params: HashMap<&str, &str> = params.iter().copied().collect();
496        let mut output = String::with_capacity(pattern.len());
497
498        for segment in pattern.split('/') {
499            if segment.is_empty() {
500                continue;
501            }
502            output.push('/');
503            if let Some(parameter) = segment
504                .strip_prefix('{')
505                .and_then(|value| value.strip_suffix('}'))
506            {
507                let value =
508                    params
509                        .get(parameter)
510                        .ok_or_else(|| UrlGenerationError::MissingParameter {
511                            route: name.to_owned(),
512                            parameter: parameter.to_owned(),
513                        })?;
514                output.push_str(&utf8_percent_encode(value, PATH_SEGMENT_ENCODE_SET).to_string());
515            } else {
516                output.push_str(segment);
517            }
518        }
519
520        if output.is_empty() {
521            output.push('/');
522        }
523        Ok(output)
524    }
525}
526
527struct MultiDispatch {
528    mounts: Arc<Vec<RouterMount>>,
529}
530
531impl Handler for MultiDispatch {
532    fn call(&self, mut request: Request) -> phoenix_http::BoxFuture<Response> {
533        let selected = select_mount(&self.mounts, &request)
534            .map(|mount| (mount.context.clone(), Arc::clone(&mount.router.handler)));
535        Box::pin(async move {
536            let Some((context, handler)) = selected else {
537                return (StatusCode::NOT_FOUND, "Application Not Found").into_response();
538            };
539            request.extensions_mut().insert(context);
540            handler.call(request).await
541        })
542    }
543}
544
545fn select_mount<'a>(mounts: &'a [RouterMount], request: &Request) -> Option<&'a RouterMount> {
546    let request_authority = request_authority(request);
547    mounts
548        .iter()
549        .filter(|mount| {
550            prefix_matches(&mount.match_prefix, request.uri().path())
551                && mount.authority.as_ref().is_none_or(|configured| {
552                    request_authority
553                        .as_ref()
554                        .is_some_and(|actual| authority_matches(configured, actual))
555                })
556        })
557        .max_by_key(|mount| {
558            (
559                u8::from(mount.authority.is_some()),
560                u8::from(
561                    mount
562                        .authority
563                        .as_ref()
564                        .is_some_and(|authority| authority.port_u16().is_some()),
565                ),
566                mount.match_prefix.len(),
567            )
568        })
569}
570
571fn request_authority(request: &Request) -> Option<Authority> {
572    request.uri().authority().cloned().or_else(|| {
573        request
574            .headers()
575            .get(header::HOST)
576            .and_then(|value| value.to_str().ok())
577            .and_then(|value| value.to_ascii_lowercase().parse().ok())
578    })
579}
580
581fn authority_matches(configured: &Authority, actual: &Authority) -> bool {
582    configured.host().eq_ignore_ascii_case(actual.host())
583        && configured
584            .port_u16()
585            .is_none_or(|port| actual.port_u16() == Some(port))
586}
587
588fn prefix_matches(prefix: &str, path: &str) -> bool {
589    prefix.is_empty()
590        || path == prefix
591        || path
592            .strip_prefix(prefix)
593            .is_some_and(|suffix| suffix.starts_with('/'))
594}
595
596fn valid_application_name(name: &str) -> bool {
597    let mut characters = name.chars();
598    characters
599        .next()
600        .is_some_and(|character| character.is_ascii_alphabetic())
601        && characters
602            .all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'))
603}
604
605fn display_prefix(prefix: &str) -> String {
606    if prefix.is_empty() {
607        "/".to_owned()
608    } else {
609        prefix.to_owned()
610    }
611}
612
613struct CompiledRoute {
614    name: Option<String>,
615    body_mode: RequestBodyMode,
616    handler: Arc<dyn Handler>,
617}
618
619struct RouterInner {
620    method_routers: HashMap<Method, matchit::Router<usize>>,
621    routes: Vec<CompiledRoute>,
622}
623
624struct DispatchHandler {
625    inner: Arc<RouterInner>,
626}
627
628struct PanicBoundary {
629    next: Arc<dyn Handler>,
630}
631
632impl Handler for PanicBoundary {
633    fn call(&self, request: Request) -> phoenix_http::BoxFuture<Response> {
634        let next = Arc::clone(&self.next);
635        Box::pin(async move {
636            let result = AssertUnwindSafe(async move { next.call(request).await })
637                .catch_unwind()
638                .await;
639            result.unwrap_or_else(|_| {
640                Response::text("Internal Server Error")
641                    .with_status(StatusCode::INTERNAL_SERVER_ERROR)
642            })
643        })
644    }
645}
646
647impl Handler for DispatchHandler {
648    fn call(&self, request: Request) -> phoenix_http::BoxFuture<Response> {
649        let inner = Arc::clone(&self.inner);
650        Box::pin(async move { inner.dispatch(request).await })
651    }
652}
653
654impl RouterInner {
655    fn request_body_mode(&self, method: &Method, path: &str) -> RequestBodyMode {
656        let lookup_method = if method == Method::HEAD && !self.has_match(&Method::HEAD, path) {
657            &Method::GET
658        } else {
659            method
660        };
661        self.method_routers
662            .get(lookup_method)
663            .and_then(|router| router.at(path).ok())
664            .map_or(RequestBodyMode::Buffered, |matched| {
665                self.routes[*matched.value].body_mode
666            })
667    }
668
669    async fn dispatch(&self, mut request: Request) -> Response {
670        let is_head = request.method() == Method::HEAD;
671        let lookup_method = if is_head && !self.has_match(&Method::HEAD, request.uri().path()) {
672            &Method::GET
673        } else {
674            request.method()
675        };
676
677        match self.find_match(lookup_method, request.uri().path()) {
678            Ok(Some((index, params))) => {
679                let route = &self.routes[index];
680                request.set_route(route.name.clone(), params);
681                let response = route.handler.call(request).await;
682                return if is_head {
683                    response.into_head()
684                } else {
685                    response
686                };
687            }
688            Err(InvalidPathParameter) => {
689                return (StatusCode::BAD_REQUEST, "Invalid path parameter encoding")
690                    .into_response();
691            }
692            Ok(None) => {}
693        }
694
695        let allowed = self.allowed_methods(request.uri().path());
696        if request.method() == Method::OPTIONS && !allowed.is_empty() {
697            return response_with_allow(StatusCode::NO_CONTENT, &allowed);
698        }
699        if !allowed.is_empty() {
700            return response_with_allow(StatusCode::METHOD_NOT_ALLOWED, &allowed);
701        }
702
703        (StatusCode::NOT_FOUND, "Not Found").into_response()
704    }
705
706    fn has_match(&self, method: &Method, path: &str) -> bool {
707        self.method_routers
708            .get(method)
709            .is_some_and(|router| router.at(path).is_ok())
710    }
711
712    fn find_match(
713        &self,
714        method: &Method,
715        path: &str,
716    ) -> Result<Option<MatchedRoute>, InvalidPathParameter> {
717        let Some(router) = self.method_routers.get(method) else {
718            return Ok(None);
719        };
720        let Ok(matched) = router.at(path) else {
721            return Ok(None);
722        };
723        let params = matched
724            .params
725            .iter()
726            .map(|(key, value)| decode_path_parameter(value).map(|value| (key.to_owned(), value)))
727            .collect::<Result<Vec<_>, _>>()?;
728        Ok(Some((*matched.value, params)))
729    }
730
731    fn allowed_methods(&self, path: &str) -> Vec<Method> {
732        let mut methods: Vec<Method> = self
733            .method_routers
734            .iter()
735            .filter(|(_, router)| router.at(path).is_ok())
736            .map(|(method, _)| method.clone())
737            .collect();
738        if methods.contains(&Method::GET) && !methods.contains(&Method::HEAD) {
739            methods.push(Method::HEAD);
740        }
741        methods.sort_by(|left, right| left.as_str().cmp(right.as_str()));
742        methods
743    }
744}
745
746fn decode_path_parameter(value: &str) -> Result<String, InvalidPathParameter> {
747    let bytes = value.as_bytes();
748    let mut index = 0;
749    while index < bytes.len() {
750        if bytes[index] == b'%' {
751            let Some(encoded) = bytes.get(index + 1..index + 3) else {
752                return Err(InvalidPathParameter);
753            };
754            if !encoded.iter().all(u8::is_ascii_hexdigit) {
755                return Err(InvalidPathParameter);
756            }
757            index += 3;
758        } else {
759            index += 1;
760        }
761    }
762
763    percent_decode_str(value)
764        .decode_utf8()
765        .map(std::borrow::Cow::into_owned)
766        .map_err(|_| InvalidPathParameter)
767}
768
769fn response_with_allow(status: StatusCode, methods: &[Method]) -> Response {
770    let allow = methods
771        .iter()
772        .map(Method::as_str)
773        .collect::<Vec<_>>()
774        .join(", ");
775    let mut response = Response::new(status, Bytes::new());
776    if let Ok(value) = HeaderValue::from_str(&allow) {
777        response.headers_mut().insert(http::header::ALLOW, value);
778    }
779    response
780}
781
782fn normalize_path(path: &str) -> String {
783    let trimmed = path.trim();
784    if trimmed.is_empty() || trimmed == "/" {
785        "/".to_owned()
786    } else {
787        format!("/{}", trimmed.trim_matches('/'))
788    }
789}
790
791fn normalize_prefix(prefix: &str) -> String {
792    let prefix = normalize_path(prefix);
793    if prefix == "/" { String::new() } else { prefix }
794}
795
796fn join_paths(prefix: &str, path: &str) -> String {
797    if prefix.is_empty() {
798        return normalize_path(path);
799    }
800    if path == "/" {
801        return prefix.to_owned();
802    }
803    format!("{prefix}{}", normalize_path(path))
804}
805
806#[derive(Debug, Error)]
807pub enum RouteBuildError {
808    #[error("cannot configure route {0}: no route has been registered")]
809    NoRouteToConfigure(&'static str),
810    #[error("duplicate route name `{0}`")]
811    DuplicateName(String),
812    #[error("invalid route pattern for {method} {path}: {reason}")]
813    InvalidPattern {
814        method: Method,
815        path: String,
816        reason: String,
817    },
818}
819
820#[derive(Debug, Error, PartialEq, Eq)]
821pub enum MultiRouterError {
822    #[error("a multi-application router requires at least one application")]
823    Empty,
824    #[error("invalid application name `{0}`")]
825    InvalidApplicationName(String),
826    #[error("invalid application Host authority `{0}`")]
827    InvalidHost(String),
828    #[error("duplicate application name `{0}`")]
829    DuplicateApplication(String),
830    #[error("duplicate application selector for host {host:?} and path `{path_prefix}`")]
831    DuplicateSelector {
832        host: Option<String>,
833        path_prefix: String,
834    },
835    #[error("duplicate route name `{0}` across applications")]
836    DuplicateRouteName(String),
837}
838
839#[derive(Debug, Error, PartialEq, Eq)]
840pub enum UrlGenerationError {
841    #[error("unknown named route `{0}`")]
842    UnknownRoute(String),
843    #[error("named route `{route}` requires parameter `{parameter}`")]
844    MissingParameter { route: String, parameter: String },
845}
846
847/// Declare a route collection without repeating the builder variable.
848///
849/// ```
850/// use phoenix_routing::routes;
851///
852/// let routes = routes! {
853///     GET "/" => |_request: phoenix_http::Request| async { "home" }, name = "home";
854///     POST "/users" => |_request: phoenix_http::Request| async { "created" },
855///         name = "users.store";
856/// };
857/// assert!(routes.build().is_ok());
858/// ```
859#[macro_export]
860macro_rules! routes {
861    (
862        $(
863            $method:ident $path:literal => $handler:expr
864            $(, name = $name:literal)?
865            $(, middleware = [$($middleware:expr),* $(,)?])?
866            ;
867        )*
868    ) => {{
869        let routes = $crate::Routes::new();
870        $(
871            let routes = $crate::__phoenix_route!(routes, $method, $path, $handler);
872            $(let routes = routes.name($name);)?
873            $($(let routes = routes.middleware($middleware);)*)?
874        )*
875        routes
876    }};
877}
878
879#[doc(hidden)]
880#[macro_export]
881macro_rules! __phoenix_route {
882    ($routes:expr, GET, $path:expr, $handler:expr) => {
883        $routes.get($path, $handler)
884    };
885    ($routes:expr, POST, $path:expr, $handler:expr) => {
886        $routes.post($path, $handler)
887    };
888    ($routes:expr, PUT, $path:expr, $handler:expr) => {
889        $routes.put($path, $handler)
890    };
891    ($routes:expr, PATCH, $path:expr, $handler:expr) => {
892        $routes.patch($path, $handler)
893    };
894    ($routes:expr, DELETE, $path:expr, $handler:expr) => {
895        $routes.delete($path, $handler)
896    };
897    ($routes:expr, HEAD, $path:expr, $handler:expr) => {
898        $routes.route($crate::Method::HEAD, $path, $handler)
899    };
900    ($routes:expr, OPTIONS, $path:expr, $handler:expr) => {
901        $routes.route($crate::Method::OPTIONS, $path, $handler)
902    };
903}
904
905#[cfg(test)]
906mod tests {
907    use super::*;
908    use phoenix_http::{RequestBodyMode, SecurityHeaders, streaming};
909
910    fn application_name(request: Request) -> phoenix_http::BoxFuture<Response> {
911        Box::pin(async move {
912            request
913                .extensions()
914                .get::<ApplicationContext>()
915                .map_or_else(|| "missing".to_owned(), |context| context.name().to_owned())
916                .into_response()
917        })
918    }
919
920    #[tokio::test]
921    async fn multi_router_selects_path_and_host_apps_and_generates_global_urls() {
922        let site = Routes::new()
923            .get("/", application_name)
924            .name("home")
925            .scoped(RouteGroup::new().name("site."))
926            .build()
927            .unwrap();
928        let admin = Routes::new()
929            .get("/", application_name)
930            .name("dashboard")
931            .scoped(RouteGroup::new().prefix("/admin").name("admin."))
932            .build()
933            .unwrap();
934        let partner = Routes::new()
935            .get("/", application_name)
936            .name("home")
937            .scoped(RouteGroup::new().name("partner."))
938            .build()
939            .unwrap();
940        let router = Router::multi(vec![
941            RouterMount::new("site", "/", None::<String>, site).unwrap(),
942            RouterMount::new("admin", "/admin", None::<String>, admin).unwrap(),
943            RouterMount::new("partner", "/", Some("partner.test"), partner).unwrap(),
944        ])
945        .unwrap();
946
947        let site_response = router
948            .handle(Request::new(Method::GET, "/".parse().unwrap()))
949            .await;
950        assert_eq!(site_response.body(), "site");
951
952        let admin_response = router
953            .handle(Request::new(Method::GET, "/admin".parse().unwrap()))
954            .await;
955        assert_eq!(admin_response.body(), "admin");
956
957        let mut partner_request = Request::new(Method::GET, "/".parse().unwrap());
958        partner_request
959            .headers_mut()
960            .insert(header::HOST, HeaderValue::from_static("partner.test:8080"));
961        let partner_response = router.handle(partner_request).await;
962        assert_eq!(partner_response.body(), "partner");
963
964        assert_eq!(router.url("site.home", &[]).unwrap(), "/");
965        assert_eq!(router.url("admin.dashboard", &[]).unwrap(), "/admin");
966        assert_eq!(router.url("partner.home", &[]).unwrap(), "/");
967    }
968
969    #[test]
970    fn multi_router_rejects_ambiguous_apps() {
971        let first = Routes::new().get("/", application_name).build().unwrap();
972        let second = Routes::new().get("/", application_name).build().unwrap();
973        let error = Router::multi(vec![
974            RouterMount::new("first", "/same", None::<String>, first).unwrap(),
975            RouterMount::new("second", "/same", None::<String>, second).unwrap(),
976        ])
977        .unwrap_err();
978        assert_eq!(
979            error,
980            MultiRouterError::DuplicateSelector {
981                host: None,
982                path_prefix: "/same".to_owned(),
983            }
984        );
985    }
986
987    #[test]
988    fn path_prefix_matching_stops_at_segment_boundaries() {
989        assert!(prefix_matches("/admin", "/admin"));
990        assert!(prefix_matches("/admin", "/admin/users"));
991        assert!(!prefix_matches("/admin", "/administrator"));
992    }
993
994    #[test]
995    fn body_mode_preflight_matches_single_and_multi_application_dispatch() {
996        let streaming_router = Routes::new()
997            .post(
998                "/upload",
999                streaming(|_request: Request| async { "streamed" }),
1000            )
1001            .build()
1002            .unwrap();
1003        let upload = Request::new(Method::POST, "/upload".parse().unwrap());
1004        let wrong_method = Request::new(Method::GET, "/upload".parse().unwrap());
1005        assert_eq!(
1006            streaming_router.request_body_mode(&upload),
1007            RequestBodyMode::Streaming
1008        );
1009        assert_eq!(
1010            streaming_router.request_body_mode(&wrong_method),
1011            RequestBodyMode::Buffered
1012        );
1013
1014        let site = Routes::new()
1015            .post("/upload", |_request: Request| async { "buffered" })
1016            .build()
1017            .unwrap();
1018        let admin = Routes::new()
1019            .post(
1020                "/upload",
1021                streaming(|_request: Request| async { "streamed" }),
1022            )
1023            .scoped(RouteGroup::new().prefix("/admin"))
1024            .build()
1025            .unwrap();
1026        let router = Router::multi(vec![
1027            RouterMount::new("site", "/", None::<String>, site).unwrap(),
1028            RouterMount::new("admin", "/admin", None::<String>, admin).unwrap(),
1029        ])
1030        .unwrap();
1031        let site_upload = Request::new(Method::POST, "/upload".parse().unwrap());
1032        let admin_upload = Request::new(Method::POST, "/admin/upload".parse().unwrap());
1033        assert_eq!(
1034            router.request_body_mode(&site_upload),
1035            RequestBodyMode::Buffered
1036        );
1037        assert_eq!(
1038            router.request_body_mode(&admin_upload),
1039            RequestBodyMode::Streaming
1040        );
1041    }
1042
1043    #[tokio::test]
1044    async fn routes_macro_applies_names_methods_and_route_middleware() {
1045        let router = routes! {
1046            GET "/items" => |_request: Request| async { "items" }, name = "items.index";
1047            POST "/items" => |_request: Request| async { "created" },
1048                name = "items.store", middleware = [SecurityHeaders];
1049        }
1050        .build()
1051        .unwrap();
1052
1053        let response = router
1054            .handle(Request::new(Method::POST, "/items".parse().unwrap()))
1055            .await;
1056        assert_eq!(response.status(), StatusCode::OK);
1057        assert_eq!(response.body(), "created");
1058        assert_eq!(response.headers()["x-content-type-options"], "nosniff");
1059        assert_eq!(router.url("items.index", &[]).unwrap(), "/items");
1060        assert_eq!(router.url("items.store", &[]).unwrap(), "/items");
1061    }
1062}