phoenix-routing 0.1.1

Laravel-inspired routing and named URL generation for Phoenix
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
use std::{
    collections::{HashMap, HashSet},
    fmt,
    panic::AssertUnwindSafe,
    sync::Arc,
};

use bytes::Bytes;
use futures_util::FutureExt;
pub use http::Method;
use http::{HeaderValue, StatusCode, header, uri::Authority};
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
use phoenix_http::{
    Handler, IntoResponse, Middleware, Request, RequestBodyMode, Response, RouteManifest,
    apply_middleware,
};
use thiserror::Error;

const PATH_SEGMENT_ENCODE_SET: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'.')
    .remove(b'_')
    .remove(b'~');

type MatchedRoute = (usize, Vec<(String, String)>);

#[derive(Clone, Copy, Debug)]
struct InvalidPathParameter;

struct RouteDefinition {
    method: Method,
    path: String,
    name: Option<String>,
    handler: Arc<dyn Handler>,
    body_mode: RequestBodyMode,
    middleware: Vec<Arc<dyn Middleware>>,
}

#[derive(Default)]
pub struct Routes {
    definitions: Vec<RouteDefinition>,
    global_middleware: Vec<Arc<dyn Middleware>>,
    error: Option<RouteBuildError>,
}

impl Routes {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn get<H>(self, path: impl Into<String>, handler: H) -> Self
    where
        H: Handler,
    {
        self.route(Method::GET, path, handler)
    }

    #[must_use]
    pub fn post<H>(self, path: impl Into<String>, handler: H) -> Self
    where
        H: Handler,
    {
        self.route(Method::POST, path, handler)
    }

    #[must_use]
    pub fn put<H>(self, path: impl Into<String>, handler: H) -> Self
    where
        H: Handler,
    {
        self.route(Method::PUT, path, handler)
    }

    #[must_use]
    pub fn patch<H>(self, path: impl Into<String>, handler: H) -> Self
    where
        H: Handler,
    {
        self.route(Method::PATCH, path, handler)
    }

    #[must_use]
    pub fn delete<H>(self, path: impl Into<String>, handler: H) -> Self
    where
        H: Handler,
    {
        self.route(Method::DELETE, path, handler)
    }

    #[must_use]
    pub fn route<H>(mut self, method: Method, path: impl Into<String>, handler: H) -> Self
    where
        H: Handler,
    {
        let body_mode = handler.request_body_mode();
        self.definitions.push(RouteDefinition {
            method,
            path: normalize_path(&path.into()),
            name: None,
            handler: Arc::new(handler),
            body_mode,
            middleware: Vec::new(),
        });
        self
    }

    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        if let Some(route) = self.definitions.last_mut() {
            route.name = Some(name.into());
        } else {
            self.error = Some(RouteBuildError::NoRouteToConfigure("name"));
        }
        self
    }

    /// Bind browser action input and output contracts to the most recently
    /// declared route. The Rust types are consumed by Phoenix's build tooling;
    /// request extraction and response serialization remain compiler checked
    /// by the registered handler.
    #[must_use]
    pub fn action<Input, Output>(mut self) -> Self {
        if self.definitions.last().is_none() {
            self.error = Some(RouteBuildError::NoRouteToConfigure("action"));
        }
        self
    }

    #[must_use]
    pub fn middleware<M>(mut self, middleware: M) -> Self
    where
        M: Middleware,
    {
        if let Some(route) = self.definitions.last_mut() {
            route.middleware.push(Arc::new(middleware));
        } else {
            self.error = Some(RouteBuildError::NoRouteToConfigure("middleware"));
        }
        self
    }

    #[must_use]
    pub fn with_middleware<M>(mut self, middleware: M) -> Self
    where
        M: Middleware,
    {
        self.global_middleware.push(Arc::new(middleware));
        self
    }

    /// Number of route declarations currently registered (before [`Self::build`]).
    #[must_use]
    pub fn len(&self) -> usize {
        self.definitions.len()
    }

    /// Return true when no route declarations are registered.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.definitions.is_empty()
    }

    /// Merge declarations from another route file while preserving their
    /// registration order. Global middleware from `other` remains scoped to
    /// the imported declarations.
    #[must_use]
    pub fn merge(mut self, mut other: Self) -> Self {
        if self.error.is_none() {
            self.error = other.error.take();
        }
        let imported_globals = other.global_middleware;
        for mut definition in other.definitions {
            let mut middleware = imported_globals.clone();
            middleware.append(&mut definition.middleware);
            definition.middleware = middleware;
            self.definitions.push(definition);
        }
        self
    }

    #[must_use]
    pub fn group<F>(mut self, group: RouteGroup, configure: F) -> Self
    where
        F: FnOnce(Routes) -> Routes,
    {
        let RouteGroup {
            prefix,
            name_prefix,
            middleware: group_middleware,
        } = group;
        let child = configure(Self::new());
        if self.error.is_none() {
            self.error = child.error;
        }

        for mut route in child.definitions {
            route.path = join_paths(&prefix, &route.path);
            route.name = route.name.map(|name| format!("{name_prefix}{name}"));

            let mut middleware = group_middleware.clone();
            middleware.extend(child.global_middleware.iter().cloned());
            middleware.extend(route.middleware);
            route.middleware = middleware;
            self.definitions.push(route);
        }
        self
    }

    /// Apply a path/name/middleware scope to an existing route collection.
    #[must_use]
    pub fn scoped(self, group: RouteGroup) -> Self {
        Self::new().group(group, |_| self)
    }

    /// Compile route definitions into an immutable request router.
    ///
    /// # Errors
    ///
    /// Returns an error for invalid patterns, duplicate names, or configuration
    /// calls that did not target a registered route.
    pub fn build(self) -> Result<Router, RouteBuildError> {
        if let Some(error) = self.error {
            return Err(error);
        }

        let mut method_routers: HashMap<Method, matchit::Router<usize>> = HashMap::new();
        let mut named_routes = HashMap::new();
        let mut compiled_routes = Vec::with_capacity(self.definitions.len());

        for definition in self.definitions {
            let index = compiled_routes.len();
            let method = definition.method.clone();
            let path = definition.path.clone();

            method_routers
                .entry(method.clone())
                .or_default()
                .insert(path.clone(), index)
                .map_err(|error| RouteBuildError::InvalidPattern {
                    method: method.clone(),
                    path: path.clone(),
                    reason: error.to_string(),
                })?;

            if let Some(name) = &definition.name
                && named_routes.insert(name.clone(), path.clone()).is_some()
            {
                return Err(RouteBuildError::DuplicateName(name.clone()));
            }

            compiled_routes.push(CompiledRoute {
                name: definition.name,
                body_mode: definition.body_mode,
                handler: apply_middleware(definition.handler, &definition.middleware),
            });
        }

        let inner = Arc::new(RouterInner {
            method_routers,
            routes: compiled_routes,
        });
        let dispatch: Arc<dyn Handler> = Arc::new(DispatchHandler {
            inner: Arc::clone(&inner),
        });
        let dispatch: Arc<dyn Handler> = Arc::new(PanicBoundary { next: dispatch });
        let handler = apply_middleware(dispatch, &self.global_middleware);

        Ok(Router {
            handler: Arc::new(PanicBoundary { next: handler }),
            named_routes: Arc::new(named_routes),
            body_modes: BodyModeRouter::Single(inner),
        })
    }
}

#[derive(Clone, Default)]
pub struct RouteGroup {
    prefix: String,
    name_prefix: String,
    middleware: Vec<Arc<dyn Middleware>>,
}

impl RouteGroup {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
        self.prefix = normalize_prefix(&prefix.into());
        self
    }

    #[must_use]
    pub fn name(mut self, prefix: impl Into<String>) -> Self {
        self.name_prefix = prefix.into();
        self
    }

    #[must_use]
    pub fn middleware<M>(mut self, middleware: M) -> Self
    where
        M: Middleware,
    {
        self.middleware.push(Arc::new(middleware));
        self
    }
}

#[derive(Clone)]
pub struct Router {
    handler: Arc<dyn Handler>,
    named_routes: Arc<HashMap<String, String>>,
    body_modes: BodyModeRouter,
}

#[derive(Clone)]
enum BodyModeRouter {
    Single(Arc<RouterInner>),
    Multi(Arc<Vec<RouterMount>>),
}

/// Metadata for the application module selected for the current request.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ApplicationContext {
    name: Arc<str>,
    path_prefix: Arc<str>,
    host: Option<Arc<str>>,
}

impl ApplicationContext {
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    #[must_use]
    pub fn path_prefix(&self) -> &str {
        &self.path_prefix
    }

    #[must_use]
    pub fn host(&self) -> Option<&str> {
        self.host.as_deref()
    }
}

/// One independently compiled router mounted into a multi-application router.
pub struct RouterMount {
    context: ApplicationContext,
    match_prefix: String,
    authority: Option<Authority>,
    router: Router,
}

impl RouterMount {
    /// Construct and validate a router mount.
    ///
    /// # Errors
    ///
    /// Returns an error for invalid application names or Host authorities.
    pub fn new(
        name: impl Into<String>,
        path_prefix: impl Into<String>,
        host: Option<impl Into<String>>,
        router: Router,
    ) -> Result<Self, MultiRouterError> {
        let name = name.into();
        if !valid_application_name(&name) {
            return Err(MultiRouterError::InvalidApplicationName(name));
        }
        let match_prefix = normalize_prefix(&path_prefix.into());
        let display_prefix = if match_prefix.is_empty() {
            "/".to_owned()
        } else {
            match_prefix.clone()
        };
        let (authority, display_host) = match host.map(Into::into) {
            Some(host) => {
                let normalized = host.trim().to_ascii_lowercase();
                let authority = normalized
                    .parse::<Authority>()
                    .map_err(|_| MultiRouterError::InvalidHost(host))?;
                (Some(authority), Some(Arc::from(normalized)))
            }
            None => (None, None),
        };
        Ok(Self {
            context: ApplicationContext {
                name: Arc::from(name),
                path_prefix: Arc::from(display_prefix),
                host: display_host,
            },
            match_prefix,
            authority,
            router,
        })
    }
}

impl fmt::Debug for Router {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Router")
            .field("named_routes", &self.named_routes)
            .finish_non_exhaustive()
    }
}

impl Router {
    /// Compose independently built routers using Host and path-prefix selection.
    ///
    /// Host-bound mounts win over hostless fallbacks, explicit ports win over
    /// host-only bindings, and longer path prefixes win over shorter prefixes.
    ///
    /// # Errors
    ///
    /// Returns an error for empty sets, duplicate application names/selectors,
    /// or duplicate global route names.
    pub fn multi(mounts: Vec<RouterMount>) -> Result<Self, MultiRouterError> {
        if mounts.is_empty() {
            return Err(MultiRouterError::Empty);
        }
        let mut application_names = HashSet::new();
        let mut selectors = HashSet::new();
        let mut named_routes = HashMap::new();
        for mount in &mounts {
            if !application_names.insert(mount.context.name.to_string()) {
                return Err(MultiRouterError::DuplicateApplication(
                    mount.context.name.to_string(),
                ));
            }
            let selector = (
                mount.authority.as_ref().map(ToString::to_string),
                mount.match_prefix.clone(),
            );
            if !selectors.insert(selector.clone()) {
                return Err(MultiRouterError::DuplicateSelector {
                    host: selector.0,
                    path_prefix: display_prefix(&selector.1),
                });
            }
            for (name, path) in mount.router.named_routes.iter() {
                if named_routes.insert(name.clone(), path.clone()).is_some() {
                    return Err(MultiRouterError::DuplicateRouteName(name.clone()));
                }
            }
        }
        let mounts = Arc::new(mounts);
        let dispatch: Arc<dyn Handler> = Arc::new(MultiDispatch {
            mounts: Arc::clone(&mounts),
        });
        Ok(Self {
            handler: Arc::new(PanicBoundary { next: dispatch }),
            named_routes: Arc::new(named_routes),
            body_modes: BodyModeRouter::Multi(mounts),
        })
    }

    pub async fn handle(&self, mut request: Request) -> Response {
        request
            .extensions_mut()
            .insert(RouteManifest::new(Arc::clone(&self.named_routes)));
        self.handler.call(request).await
    }

    #[doc(hidden)]
    #[must_use]
    pub fn request_body_mode(&self, request: &Request) -> RequestBodyMode {
        match &self.body_modes {
            BodyModeRouter::Single(inner) => {
                inner.request_body_mode(request.method(), request.uri().path())
            }
            BodyModeRouter::Multi(mounts) => select_mount(mounts, request)
                .map_or(RequestBodyMode::Buffered, |mount| {
                    mount.router.request_body_mode(request)
                }),
        }
    }

    /// Generate a URL from a Laravel-style named route.
    ///
    /// # Errors
    ///
    /// Returns an error when the route name is unknown or a required path
    /// parameter is missing.
    pub fn url(&self, name: &str, params: &[(&str, &str)]) -> Result<String, UrlGenerationError> {
        let pattern = self
            .named_routes
            .get(name)
            .ok_or_else(|| UrlGenerationError::UnknownRoute(name.to_owned()))?;
        let params: HashMap<&str, &str> = params.iter().copied().collect();
        let mut output = String::with_capacity(pattern.len());

        for segment in pattern.split('/') {
            if segment.is_empty() {
                continue;
            }
            output.push('/');
            if let Some(parameter) = segment
                .strip_prefix('{')
                .and_then(|value| value.strip_suffix('}'))
            {
                let value =
                    params
                        .get(parameter)
                        .ok_or_else(|| UrlGenerationError::MissingParameter {
                            route: name.to_owned(),
                            parameter: parameter.to_owned(),
                        })?;
                output.push_str(&utf8_percent_encode(value, PATH_SEGMENT_ENCODE_SET).to_string());
            } else {
                output.push_str(segment);
            }
        }

        if output.is_empty() {
            output.push('/');
        }
        Ok(output)
    }
}

struct MultiDispatch {
    mounts: Arc<Vec<RouterMount>>,
}

impl Handler for MultiDispatch {
    fn call(&self, mut request: Request) -> phoenix_http::BoxFuture<Response> {
        let selected = select_mount(&self.mounts, &request)
            .map(|mount| (mount.context.clone(), Arc::clone(&mount.router.handler)));
        Box::pin(async move {
            let Some((context, handler)) = selected else {
                return (StatusCode::NOT_FOUND, "Application Not Found").into_response();
            };
            request.extensions_mut().insert(context);
            handler.call(request).await
        })
    }
}

fn select_mount<'a>(mounts: &'a [RouterMount], request: &Request) -> Option<&'a RouterMount> {
    let request_authority = request_authority(request);
    mounts
        .iter()
        .filter(|mount| {
            prefix_matches(&mount.match_prefix, request.uri().path())
                && mount.authority.as_ref().is_none_or(|configured| {
                    request_authority
                        .as_ref()
                        .is_some_and(|actual| authority_matches(configured, actual))
                })
        })
        .max_by_key(|mount| {
            (
                u8::from(mount.authority.is_some()),
                u8::from(
                    mount
                        .authority
                        .as_ref()
                        .is_some_and(|authority| authority.port_u16().is_some()),
                ),
                mount.match_prefix.len(),
            )
        })
}

fn request_authority(request: &Request) -> Option<Authority> {
    request.uri().authority().cloned().or_else(|| {
        request
            .headers()
            .get(header::HOST)
            .and_then(|value| value.to_str().ok())
            .and_then(|value| value.to_ascii_lowercase().parse().ok())
    })
}

fn authority_matches(configured: &Authority, actual: &Authority) -> bool {
    configured.host().eq_ignore_ascii_case(actual.host())
        && configured
            .port_u16()
            .is_none_or(|port| actual.port_u16() == Some(port))
}

fn prefix_matches(prefix: &str, path: &str) -> bool {
    prefix.is_empty()
        || path == prefix
        || path
            .strip_prefix(prefix)
            .is_some_and(|suffix| suffix.starts_with('/'))
}

fn valid_application_name(name: &str) -> bool {
    let mut characters = name.chars();
    characters
        .next()
        .is_some_and(|character| character.is_ascii_alphabetic())
        && characters
            .all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'))
}

fn display_prefix(prefix: &str) -> String {
    if prefix.is_empty() {
        "/".to_owned()
    } else {
        prefix.to_owned()
    }
}

struct CompiledRoute {
    name: Option<String>,
    body_mode: RequestBodyMode,
    handler: Arc<dyn Handler>,
}

struct RouterInner {
    method_routers: HashMap<Method, matchit::Router<usize>>,
    routes: Vec<CompiledRoute>,
}

struct DispatchHandler {
    inner: Arc<RouterInner>,
}

struct PanicBoundary {
    next: Arc<dyn Handler>,
}

impl Handler for PanicBoundary {
    fn call(&self, request: Request) -> phoenix_http::BoxFuture<Response> {
        let next = Arc::clone(&self.next);
        Box::pin(async move {
            let result = AssertUnwindSafe(async move { next.call(request).await })
                .catch_unwind()
                .await;
            result.unwrap_or_else(|_| {
                Response::text("Internal Server Error")
                    .with_status(StatusCode::INTERNAL_SERVER_ERROR)
            })
        })
    }
}

impl Handler for DispatchHandler {
    fn call(&self, request: Request) -> phoenix_http::BoxFuture<Response> {
        let inner = Arc::clone(&self.inner);
        Box::pin(async move { inner.dispatch(request).await })
    }
}

impl RouterInner {
    fn request_body_mode(&self, method: &Method, path: &str) -> RequestBodyMode {
        let lookup_method = if method == Method::HEAD && !self.has_match(&Method::HEAD, path) {
            &Method::GET
        } else {
            method
        };
        self.method_routers
            .get(lookup_method)
            .and_then(|router| router.at(path).ok())
            .map_or(RequestBodyMode::Buffered, |matched| {
                self.routes[*matched.value].body_mode
            })
    }

    async fn dispatch(&self, mut request: Request) -> Response {
        let is_head = request.method() == Method::HEAD;
        let lookup_method = if is_head && !self.has_match(&Method::HEAD, request.uri().path()) {
            &Method::GET
        } else {
            request.method()
        };

        match self.find_match(lookup_method, request.uri().path()) {
            Ok(Some((index, params))) => {
                let route = &self.routes[index];
                request.set_route(route.name.clone(), params);
                let response = route.handler.call(request).await;
                return if is_head {
                    response.into_head()
                } else {
                    response
                };
            }
            Err(InvalidPathParameter) => {
                return (StatusCode::BAD_REQUEST, "Invalid path parameter encoding")
                    .into_response();
            }
            Ok(None) => {}
        }

        let allowed = self.allowed_methods(request.uri().path());
        if request.method() == Method::OPTIONS && !allowed.is_empty() {
            return response_with_allow(StatusCode::NO_CONTENT, &allowed);
        }
        if !allowed.is_empty() {
            return response_with_allow(StatusCode::METHOD_NOT_ALLOWED, &allowed);
        }

        (StatusCode::NOT_FOUND, "Not Found").into_response()
    }

    fn has_match(&self, method: &Method, path: &str) -> bool {
        self.method_routers
            .get(method)
            .is_some_and(|router| router.at(path).is_ok())
    }

    fn find_match(
        &self,
        method: &Method,
        path: &str,
    ) -> Result<Option<MatchedRoute>, InvalidPathParameter> {
        let Some(router) = self.method_routers.get(method) else {
            return Ok(None);
        };
        let Ok(matched) = router.at(path) else {
            return Ok(None);
        };
        let params = matched
            .params
            .iter()
            .map(|(key, value)| decode_path_parameter(value).map(|value| (key.to_owned(), value)))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Some((*matched.value, params)))
    }

    fn allowed_methods(&self, path: &str) -> Vec<Method> {
        let mut methods: Vec<Method> = self
            .method_routers
            .iter()
            .filter(|(_, router)| router.at(path).is_ok())
            .map(|(method, _)| method.clone())
            .collect();
        if methods.contains(&Method::GET) && !methods.contains(&Method::HEAD) {
            methods.push(Method::HEAD);
        }
        methods.sort_by(|left, right| left.as_str().cmp(right.as_str()));
        methods
    }
}

fn decode_path_parameter(value: &str) -> Result<String, InvalidPathParameter> {
    let bytes = value.as_bytes();
    let mut index = 0;
    while index < bytes.len() {
        if bytes[index] == b'%' {
            let Some(encoded) = bytes.get(index + 1..index + 3) else {
                return Err(InvalidPathParameter);
            };
            if !encoded.iter().all(u8::is_ascii_hexdigit) {
                return Err(InvalidPathParameter);
            }
            index += 3;
        } else {
            index += 1;
        }
    }

    percent_decode_str(value)
        .decode_utf8()
        .map(std::borrow::Cow::into_owned)
        .map_err(|_| InvalidPathParameter)
}

fn response_with_allow(status: StatusCode, methods: &[Method]) -> Response {
    let allow = methods
        .iter()
        .map(Method::as_str)
        .collect::<Vec<_>>()
        .join(", ");
    let mut response = Response::new(status, Bytes::new());
    if let Ok(value) = HeaderValue::from_str(&allow) {
        response.headers_mut().insert(http::header::ALLOW, value);
    }
    response
}

fn normalize_path(path: &str) -> String {
    let trimmed = path.trim();
    if trimmed.is_empty() || trimmed == "/" {
        "/".to_owned()
    } else {
        format!("/{}", trimmed.trim_matches('/'))
    }
}

fn normalize_prefix(prefix: &str) -> String {
    let prefix = normalize_path(prefix);
    if prefix == "/" { String::new() } else { prefix }
}

fn join_paths(prefix: &str, path: &str) -> String {
    if prefix.is_empty() {
        return normalize_path(path);
    }
    if path == "/" {
        return prefix.to_owned();
    }
    format!("{prefix}{}", normalize_path(path))
}

#[derive(Debug, Error)]
pub enum RouteBuildError {
    #[error("cannot configure route {0}: no route has been registered")]
    NoRouteToConfigure(&'static str),
    #[error("duplicate route name `{0}`")]
    DuplicateName(String),
    #[error("invalid route pattern for {method} {path}: {reason}")]
    InvalidPattern {
        method: Method,
        path: String,
        reason: String,
    },
}

#[derive(Debug, Error, PartialEq, Eq)]
pub enum MultiRouterError {
    #[error("a multi-application router requires at least one application")]
    Empty,
    #[error("invalid application name `{0}`")]
    InvalidApplicationName(String),
    #[error("invalid application Host authority `{0}`")]
    InvalidHost(String),
    #[error("duplicate application name `{0}`")]
    DuplicateApplication(String),
    #[error("duplicate application selector for host {host:?} and path `{path_prefix}`")]
    DuplicateSelector {
        host: Option<String>,
        path_prefix: String,
    },
    #[error("duplicate route name `{0}` across applications")]
    DuplicateRouteName(String),
}

#[derive(Debug, Error, PartialEq, Eq)]
pub enum UrlGenerationError {
    #[error("unknown named route `{0}`")]
    UnknownRoute(String),
    #[error("named route `{route}` requires parameter `{parameter}`")]
    MissingParameter { route: String, parameter: String },
}

/// Declare a route collection without repeating the builder variable.
///
/// ```
/// use phoenix_routing::routes;
///
/// let routes = routes! {
///     GET "/" => |_request: phoenix_http::Request| async { "home" }, name = "home";
///     POST "/users" => |_request: phoenix_http::Request| async { "created" },
///         name = "users.store";
/// };
/// assert!(routes.build().is_ok());
/// ```
#[macro_export]
macro_rules! routes {
    (
        $(
            $method:ident $path:literal => $handler:expr
            $(, name = $name:literal)?
            $(, middleware = [$($middleware:expr),* $(,)?])?
            ;
        )*
    ) => {{
        let routes = $crate::Routes::new();
        $(
            let routes = $crate::__phoenix_route!(routes, $method, $path, $handler);
            $(let routes = routes.name($name);)?
            $($(let routes = routes.middleware($middleware);)*)?
        )*
        routes
    }};
}

#[doc(hidden)]
#[macro_export]
macro_rules! __phoenix_route {
    ($routes:expr, GET, $path:expr, $handler:expr) => {
        $routes.get($path, $handler)
    };
    ($routes:expr, POST, $path:expr, $handler:expr) => {
        $routes.post($path, $handler)
    };
    ($routes:expr, PUT, $path:expr, $handler:expr) => {
        $routes.put($path, $handler)
    };
    ($routes:expr, PATCH, $path:expr, $handler:expr) => {
        $routes.patch($path, $handler)
    };
    ($routes:expr, DELETE, $path:expr, $handler:expr) => {
        $routes.delete($path, $handler)
    };
    ($routes:expr, HEAD, $path:expr, $handler:expr) => {
        $routes.route($crate::Method::HEAD, $path, $handler)
    };
    ($routes:expr, OPTIONS, $path:expr, $handler:expr) => {
        $routes.route($crate::Method::OPTIONS, $path, $handler)
    };
}

#[cfg(test)]
mod tests {
    use super::*;
    use phoenix_http::{RequestBodyMode, SecurityHeaders, streaming};

    fn application_name(request: Request) -> phoenix_http::BoxFuture<Response> {
        Box::pin(async move {
            request
                .extensions()
                .get::<ApplicationContext>()
                .map_or_else(|| "missing".to_owned(), |context| context.name().to_owned())
                .into_response()
        })
    }

    #[tokio::test]
    async fn multi_router_selects_path_and_host_apps_and_generates_global_urls() {
        let site = Routes::new()
            .get("/", application_name)
            .name("home")
            .scoped(RouteGroup::new().name("site."))
            .build()
            .unwrap();
        let admin = Routes::new()
            .get("/", application_name)
            .name("dashboard")
            .scoped(RouteGroup::new().prefix("/admin").name("admin."))
            .build()
            .unwrap();
        let partner = Routes::new()
            .get("/", application_name)
            .name("home")
            .scoped(RouteGroup::new().name("partner."))
            .build()
            .unwrap();
        let router = Router::multi(vec![
            RouterMount::new("site", "/", None::<String>, site).unwrap(),
            RouterMount::new("admin", "/admin", None::<String>, admin).unwrap(),
            RouterMount::new("partner", "/", Some("partner.test"), partner).unwrap(),
        ])
        .unwrap();

        let site_response = router
            .handle(Request::new(Method::GET, "/".parse().unwrap()))
            .await;
        assert_eq!(site_response.body(), "site");

        let admin_response = router
            .handle(Request::new(Method::GET, "/admin".parse().unwrap()))
            .await;
        assert_eq!(admin_response.body(), "admin");

        let mut partner_request = Request::new(Method::GET, "/".parse().unwrap());
        partner_request
            .headers_mut()
            .insert(header::HOST, HeaderValue::from_static("partner.test:8080"));
        let partner_response = router.handle(partner_request).await;
        assert_eq!(partner_response.body(), "partner");

        assert_eq!(router.url("site.home", &[]).unwrap(), "/");
        assert_eq!(router.url("admin.dashboard", &[]).unwrap(), "/admin");
        assert_eq!(router.url("partner.home", &[]).unwrap(), "/");
    }

    #[test]
    fn multi_router_rejects_ambiguous_apps() {
        let first = Routes::new().get("/", application_name).build().unwrap();
        let second = Routes::new().get("/", application_name).build().unwrap();
        let error = Router::multi(vec![
            RouterMount::new("first", "/same", None::<String>, first).unwrap(),
            RouterMount::new("second", "/same", None::<String>, second).unwrap(),
        ])
        .unwrap_err();
        assert_eq!(
            error,
            MultiRouterError::DuplicateSelector {
                host: None,
                path_prefix: "/same".to_owned(),
            }
        );
    }

    #[test]
    fn path_prefix_matching_stops_at_segment_boundaries() {
        assert!(prefix_matches("/admin", "/admin"));
        assert!(prefix_matches("/admin", "/admin/users"));
        assert!(!prefix_matches("/admin", "/administrator"));
    }

    #[test]
    fn body_mode_preflight_matches_single_and_multi_application_dispatch() {
        let streaming_router = Routes::new()
            .post(
                "/upload",
                streaming(|_request: Request| async { "streamed" }),
            )
            .build()
            .unwrap();
        let upload = Request::new(Method::POST, "/upload".parse().unwrap());
        let wrong_method = Request::new(Method::GET, "/upload".parse().unwrap());
        assert_eq!(
            streaming_router.request_body_mode(&upload),
            RequestBodyMode::Streaming
        );
        assert_eq!(
            streaming_router.request_body_mode(&wrong_method),
            RequestBodyMode::Buffered
        );

        let site = Routes::new()
            .post("/upload", |_request: Request| async { "buffered" })
            .build()
            .unwrap();
        let admin = Routes::new()
            .post(
                "/upload",
                streaming(|_request: Request| async { "streamed" }),
            )
            .scoped(RouteGroup::new().prefix("/admin"))
            .build()
            .unwrap();
        let router = Router::multi(vec![
            RouterMount::new("site", "/", None::<String>, site).unwrap(),
            RouterMount::new("admin", "/admin", None::<String>, admin).unwrap(),
        ])
        .unwrap();
        let site_upload = Request::new(Method::POST, "/upload".parse().unwrap());
        let admin_upload = Request::new(Method::POST, "/admin/upload".parse().unwrap());
        assert_eq!(
            router.request_body_mode(&site_upload),
            RequestBodyMode::Buffered
        );
        assert_eq!(
            router.request_body_mode(&admin_upload),
            RequestBodyMode::Streaming
        );
    }

    #[tokio::test]
    async fn routes_macro_applies_names_methods_and_route_middleware() {
        let router = routes! {
            GET "/items" => |_request: Request| async { "items" }, name = "items.index";
            POST "/items" => |_request: Request| async { "created" },
                name = "items.store", middleware = [SecurityHeaders];
        }
        .build()
        .unwrap();

        let response = router
            .handle(Request::new(Method::POST, "/items".parse().unwrap()))
            .await;
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(response.body(), "created");
        assert_eq!(response.headers()["x-content-type-options"], "nosniff");
        assert_eq!(router.url("items.index", &[]).unwrap(), "/items");
        assert_eq!(router.url("items.store", &[]).unwrap(), "/items");
    }
}