skyzen 0.1.1

A fast, ergonomic HTTP framework that works everywhere
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
//! Tree-based routing primitives.
//!
//! Routes are defined by combining nodes produced by the [`CreateRouteNode`] extension. Path
//! literals gain builder methods such as `.at(handler)` (GET), `.post(handler)`, `.put(handler)`,
//! `.patch(handler)`, `.delete(handler)`, `.head(handler)`, `.options(handler)`,
//! `.trace(handler)`, `.ws(handler)`, and `.route(children)`
//! so you can describe the full tree declaratively. Once a tree is assembled, call [`Route::build`]
//! to obtain a [`Router`] that can be mounted on a server or invoked directly from tests.
//!
//! ## Building routes
//! ```no_run
//! use skyzen::{
//!     routing::{CreateRouteNode, Params, Route},
//!     Result,
//! };
//!
//! async fn ping() -> Result<&'static str> {
//!     Ok("pong")
//! }
//!
//! async fn hello(params: Params) -> Result<String> {
//!     let name = params.get("name")?;
//!     Ok(format!("Hello, {name}!"))
//! }
//!
//! let router = Route::new((
//!     "/ping".at(ping),
//!     "/user".route((
//!         "/{name}".at(hello),
//!     )),
//! ))
//! .build();
//! ```
//!
//! ## Named parameters and wildcards
//! Use `{name}` to capture a single path segment and `{*path}` to capture the rest of the path.
//! Extract the captured values with [`Params`]:
//! ```no_run
//! use skyzen::{
//!     routing::{CreateRouteNode, Params, Route},
//!     Result,
//! };
//!
//! async fn echo(params: Params) -> Result<String> {
//!     let path = params.get("path")?;
//!     Ok(format!("Path: {path}"))
//! }
//!
//! let route = Route::new(("/files/{*path}".at(echo),));
//! ```
//!
//! ## Applying middleware to a route tree
//! Middleware can be attached to a [`Route`] via [`Route::middleware`]. The middleware is cloned
//! for every endpoint reachable from the route:
//! ```no_run
//! use skyzen::{
//!     routing::{CreateRouteNode, Route},
//!     utils::State,
//!     Result,
//! };
//!
//! let route = Route::new(("/counter".at(|| async { Result::Ok("0") }),))
//! .with(State(0usize));
//! ```
//!
//! Error handling can also be expressed as middleware. For example, you can catch endpoint errors
//! with [`ErrorHandlingMiddleware`](crate::middleware::ErrorHandlingMiddleware):
//! ```no_run
//! use skyzen::{
//!     middleware::ErrorHandlingMiddleware,
//!     routing::{CreateRouteNode, Route},
//!     Result,
//! };
//!
//! async fn boom() -> Result<&'static str> {
//!     Err(skyzen::Error::msg("boom"))
//! }
//!
//! let router = Route::new(("/panic".at(boom),))
//! .with(ErrorHandlingMiddleware::new(|error| async move {
//!     format!("Recovered from {error}")
//! }))
//! .build();
//! ```
//!
//! ## WebSocket routes
//! When the `ws` feature is enabled you can use `.ws` to accept upgrades without manually
//! extracting [`WebSocketUpgrade`](crate::websocket::WebSocketUpgrade):
//! ```no_run
//! use futures_util::StreamExt;
//! use skyzen::routing::{CreateRouteNode, Route};
//!
//! let routes = Route::new((
//!     "/chat".ws(|mut socket| async move {
//!         while let Some(Ok(message)) = socket.next().await {
//!             if let Some(text) = message.into_text() {
//!                 let _ = socket.send_text(text).await;
//!             }
//!         }
//!     }),
//! ));
//! ```
//! The `.ws` builder enforces the HTTP upgrade requirements automatically.
//!
//! Middleware is applied from the outermost route to the innermost endpoint, so errors bubble up
//! until they are handled.

#[cfg(feature = "ws")]
use std::future::Future;
use std::{fmt, sync::Arc};

#[cfg(all(feature = "openapi", not(target_arch = "wasm32")))]
use crate::openapi::RouteOpenApiEntry;
#[cfg(feature = "ws")]
use crate::websocket::{WebSocket, WebSocketUpgrade};
use crate::{handler, handler::Handler, openapi, openapi::OpenApi, Middleware};
use http_kit::endpoint::{AnyEndpoint, WithMiddleware};
use http_kit::{Endpoint, Method};
use skyzen_core::{Extractor, Responder};

/// Type alias for dynamically dispatched endpoints stored in the routing tree.
pub type BoxEndpoint = AnyEndpoint;
pub(crate) type EndpointFactory = Arc<dyn Fn() -> BoxEndpoint + Send + Sync>;

// Export param types
mod param;
pub use param::Params;

// Export router types
mod router;
pub use router::{build, RouteBuildError, Router};

/// Collection of route nodes anchored at a path prefix.
#[derive(Debug)]
pub struct Route {
    /// All nodes that hang off the route's mount point.
    nodes: Vec<RouteNode>,
}

/// A single node in the routing tree.
#[derive(Debug)]
pub struct RouteNode {
    /// The literal path segment represented by this node.
    path: String,
    /// The kind of node.
    node_type: RouteNodeType,
}

/// Distinguishes between nested routes and terminal endpoints.
pub enum RouteNodeType {
    /// Sub-route with additional child nodes.
    Route(Route),
    /// Terminal endpoint located at the provided path and method.
    Endpoint {
        /// Factory producing a fresh endpoint that can be safely shared.
        endpoint_factory: EndpointFactory,
        /// HTTP method matched by the node.
        method: Method,
        /// Handler metadata for `OpenAPI` export.
        openapi: Option<openapi::RouteHandlerDoc>,
    },
}

impl fmt::Debug for RouteNodeType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Route(route) => f.debug_tuple("Route").field(route).finish(),
            Self::Endpoint { method, .. } => {
                f.debug_struct("Endpoint").field("method", method).finish()
            }
        }
    }
}

impl Route {
    /// Build a [`Route`] from the provided nodes.
    #[must_use]
    pub fn new(nodes: impl Routes) -> Self {
        Self {
            nodes: nodes.into_route_nodes(),
        }
    }

    /// Register an alarm handler for Durable Object alarm events.
    ///
    /// The handler is an async function with extractors as arguments,
    /// just like a regular route handler.
    #[must_use]
    pub fn on_alarm<H, T, R>(self, handler: H) -> RouteWithAlarm
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        let endpoint = handler::into_endpoint(handler);
        RouteWithAlarm {
            route: self,
            alarm_endpoint: Arc::new(move || AnyEndpoint::new(endpoint.clone())),
        }
    }

    /// Attach middleware to this route and all nested endpoints.
    #[must_use]
    pub fn middleware<M>(mut self, middleware: M) -> Self
    where
        M: Middleware + Sync + Clone + 'static,
    {
        self.apply_middleware(middleware);
        self
    }

    /// Attach middleware to this route and all nested endpoints.
    ///
    /// This is an ergonomic alias for [`Route::middleware`].
    #[must_use]
    pub fn with<M>(self, middleware: M) -> Self
    where
        M: Middleware + Sync + Clone + 'static,
    {
        self.middleware(middleware)
    }

    #[allow(clippy::needless_pass_by_value)]
    fn apply_middleware<M>(&mut self, middleware: M)
    where
        M: Middleware + Sync + Clone + 'static,
    {
        for node in &mut self.nodes {
            node.apply_middleware(middleware.clone());
        }
    }

    /// Build the route, panicking on error.
    ///
    /// # Panics
    /// Panics if the route is invalid.
    #[must_use]
    pub fn build(self) -> Router {
        build(self).expect("Failed to build router")
    }

    /// Generate an [`OpenApi`] document describing this route tree.
    #[must_use]
    pub fn openapi(&self) -> OpenApi {
        #[cfg(all(feature = "openapi", not(target_arch = "wasm32")))]
        {
            let mut entries = Vec::new();
            collect_openapi_entries("", &self.nodes, &mut entries);
            OpenApi::from_entries(&entries)
        }

        #[cfg(not(all(feature = "openapi", not(target_arch = "wasm32"))))]
        {
            OpenApi::default()
        }
    }

    /// Enable the Redoc API documentation endpoint at `/api-docs`.
    #[must_use]
    pub fn enable_api_doc(mut self) -> Self {
        let openapi = self.openapi();
        self.nodes
            .push(openapi.redoc_route(openapi::DEFAULT_API_DOCS_MOUNT));
        self
    }
}

/// A [`Route`] with an attached alarm handler.
///
/// Created by [`Route::on_alarm`]. Call [`build`](Self::build) to produce a [`Router`].
pub struct RouteWithAlarm {
    route: Route,
    alarm_endpoint: EndpointFactory,
}

#[allow(clippy::missing_fields_in_debug)]
impl fmt::Debug for RouteWithAlarm {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RouteWithAlarm")
            .field("route", &self.route)
            .field("has_alarm", &true)
            .finish()
    }
}

impl RouteWithAlarm {
    /// Attach middleware to this route and all nested endpoints.
    #[must_use]
    pub fn middleware<M>(mut self, middleware: M) -> Self
    where
        M: Middleware + Sync + Clone + 'static,
    {
        self.route.apply_middleware(middleware);
        self
    }

    /// Attach middleware to this route and all nested endpoints.
    ///
    /// This is an ergonomic alias for [`RouteWithAlarm::middleware`].
    #[must_use]
    pub fn with<M>(self, middleware: M) -> Self
    where
        M: Middleware + Sync + Clone + 'static,
    {
        self.middleware(middleware)
    }

    /// Build the route, panicking on error.
    ///
    /// # Panics
    /// Panics if the route is invalid.
    #[must_use]
    pub fn build(self) -> Router {
        let alarm_factory = self.alarm_endpoint;
        let mut router = self.route.build();
        router.alarm_handler = Some(alarm_factory);
        router
    }

    /// Enable the Redoc API documentation endpoint at `/api-docs`.
    #[must_use]
    pub fn enable_api_doc(mut self) -> Self {
        let openapi = self.route.openapi();
        self.route
            .nodes
            .push(openapi.redoc_route(openapi::DEFAULT_API_DOCS_MOUNT));
        self
    }
}

impl RouteNode {
    /// Construct an endpoint node with the provided handler.
    #[must_use]
    pub(crate) fn new_endpoint<E>(
        path: impl Into<String>,
        method: Method,
        endpoint: E,
        openapi: Option<openapi::RouteHandlerDoc>,
    ) -> Self
    where
        E: Endpoint + Clone + Send + Sync + 'static,
    {
        let endpoint_factory: EndpointFactory =
            Arc::new(move || AnyEndpoint::new(endpoint.clone()));
        Self {
            path: path.into(),
            node_type: RouteNodeType::Endpoint {
                endpoint_factory,
                method,
                openapi,
            },
        }
    }

    /// Construct a nested route node mounted under `path`.
    #[must_use]
    pub(crate) fn new_route(path: impl Into<String>, route: Route) -> Self {
        Self {
            path: path.into(),
            node_type: RouteNodeType::Route(route),
        }
    }

    fn apply_middleware<M>(&mut self, middleware: M)
    where
        M: Middleware + Sync + Clone + 'static,
    {
        match &mut self.node_type {
            RouteNodeType::Route(route) => route.apply_middleware(middleware),
            RouteNodeType::Endpoint {
                endpoint_factory, ..
            } => {
                let factory = Arc::clone(endpoint_factory);
                *endpoint_factory = wrap_endpoint_factory(factory, middleware);
            }
        }
    }
}

fn wrap_endpoint_factory<M>(factory: EndpointFactory, middleware: M) -> EndpointFactory
where
    M: Middleware + Sync + Clone + 'static,
{
    Arc::new(move || {
        let endpoint = factory();
        let middleware = middleware.clone();
        AnyEndpoint::new(WithMiddleware::new(endpoint, middleware))
    })
}

impl RouteNode {
    /// Attach a GET handler to the current route node.
    #[must_use]
    pub fn at<H, T, R>(self, handler: H) -> Self
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        self.with_handler(Method::GET, handler)
    }

    /// Alias for [`RouteNode::at`].
    #[must_use]
    pub fn get<H, T, R>(self, handler: H) -> Self
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        self.at(handler)
    }

    /// Attach a POST handler to the current route node.
    #[must_use]
    pub fn post<H, T, R>(self, handler: H) -> Self
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        self.with_handler(Method::POST, handler)
    }

    /// Attach a PATCH handler to the current route node.
    #[must_use]
    pub fn patch<H, T, R>(self, handler: H) -> Self
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        self.with_handler(Method::PATCH, handler)
    }

    /// Attach a PUT handler to the current route node.
    #[must_use]
    pub fn put<H, T, R>(self, handler: H) -> Self
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        self.with_handler(Method::PUT, handler)
    }

    /// Attach a DELETE handler to the current route node.
    #[must_use]
    pub fn delete<H, T, R>(self, handler: H) -> Self
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        self.with_handler(Method::DELETE, handler)
    }

    /// Attach a HEAD handler to the current route node.
    #[must_use]
    pub fn head<H, T, R>(self, handler: H) -> Self
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        self.with_handler(Method::HEAD, handler)
    }

    /// Attach an OPTIONS handler to the current route node.
    #[must_use]
    pub fn options<H, T, R>(self, handler: H) -> Self
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        self.with_handler(Method::OPTIONS, handler)
    }

    /// Attach a TRACE handler to the current route node.
    #[must_use]
    pub fn trace<H, T, R>(self, handler: H) -> Self
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        self.with_handler(Method::TRACE, handler)
    }

    /// Attach an endpoint under the current path with an arbitrary HTTP method.
    #[must_use]
    pub fn endpoint<E>(self, method: Method, endpoint: E) -> Self
    where
        E: Endpoint + Clone + Send + Sync + 'static,
    {
        self.extend_with_nodes(vec![Self::new_endpoint("", method, endpoint, None)])
    }

    /// Attach additional child routes under the current path.
    #[must_use]
    pub fn route(self, routes: impl Routes) -> Self {
        self.extend_with_nodes(routes.into_route_nodes())
    }

    /// Attach a WebSocket handler that performs the upgrade under the current path.
    #[cfg(feature = "ws")]
    #[must_use]
    pub fn ws<F, Fut>(self, handler: F) -> Self
    where
        F: Fn(WebSocket) -> Fut + Clone + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let builder = move |upgrade: WebSocketUpgrade| {
            let callback = handler.clone();
            async move { upgrade.on_upgrade(callback) }
        };
        self.at(builder)
    }

    fn with_handler<H, T, R>(self, method: Method, handler: H) -> Self
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        let endpoint = endpoint_node_from_handler("", method, handler);
        self.extend_with_nodes(vec![endpoint])
    }

    fn extend_with_nodes(self, mut additional: Vec<Self>) -> Self {
        let path = self.path;
        let mut nodes = match self.node_type {
            RouteNodeType::Route(route) => route.nodes,
            RouteNodeType::Endpoint {
                endpoint_factory,
                method,
                openapi,
            } => vec![Self {
                path: String::new(),
                node_type: RouteNodeType::Endpoint {
                    endpoint_factory,
                    method,
                    openapi,
                },
            }],
        };

        nodes.append(&mut additional);

        Self {
            path,
            node_type: RouteNodeType::Route(Route { nodes }),
        }
    }
}

// Trait for building routes
/// Trait implemented by types that can be converted into route nodes.
pub trait Routes {
    /// Consume the type and produce the corresponding route nodes.
    fn into_route_nodes(self) -> Vec<RouteNode>;
}

/// Trait implemented by types that can be converted into a [`RouteNode`].
pub trait IntoRouteNode {
    /// Consume the type and produce the [`RouteNode`].
    fn into_route_node(self) -> RouteNode;
}

impl IntoRouteNode for RouteNode {
    fn into_route_node(self) -> RouteNode {
        self
    }
}

impl<T> Routes for Vec<T>
where
    T: IntoRouteNode,
{
    fn into_route_nodes(self) -> Vec<RouteNode> {
        self.into_iter()
            .map(IntoRouteNode::into_route_node)
            .collect()
    }
}

impl Routes for RouteNode {
    fn into_route_nodes(self) -> Vec<RouteNode> {
        vec![self]
    }
}

impl Routes for Route {
    fn into_route_nodes(self) -> Vec<RouteNode> {
        self.nodes
    }
}

impl Routes for () {
    fn into_route_nodes(self) -> Vec<RouteNode> {
        Vec::new()
    }
}

macro_rules! impl_routes_tuple {
    () => {};
    ($($ty:ident),+) => {
        #[allow(non_snake_case)]
        impl<$($ty,)+> Routes for ($($ty,)+)
        where
            $($ty: IntoRouteNode,)+
        {
            fn into_route_nodes(self) -> Vec<RouteNode> {
                let ($($ty,)+) = self;
                vec![$($ty.into_route_node(),)+]
            }
        }
    };
}

tuples!(impl_routes_tuple);

fn endpoint_node_from_handler<P, H, T, R>(path: P, method: Method, handler: H) -> RouteNode
where
    P: Into<String>,
    H: Handler<T, R>,
    T: Extractor,
    R: Responder,
{
    let handler_doc = openapi::describe_handler::<H>();
    let endpoint = handler::into_endpoint(handler);
    RouteNode::new_endpoint(path.into(), method, endpoint, Some(handler_doc))
}

#[cfg(all(feature = "openapi", not(target_arch = "wasm32")))]
fn collect_openapi_entries(
    path_prefix: &str,
    nodes: &[RouteNode],
    buf: &mut Vec<RouteOpenApiEntry>,
) {
    for node in nodes {
        let path = format!("{}{}", path_prefix, node.path);
        match &node.node_type {
            RouteNodeType::Route(route) => {
                collect_openapi_entries(&path, &route.nodes, buf);
            }
            RouteNodeType::Endpoint {
                method, openapi, ..
            } => {
                if let Some(openapi) = openapi {
                    buf.push(RouteOpenApiEntry::new(path, method.clone(), *openapi));
                }
            }
        }
    }
}

/// Builder extension that turns a path literal into convenient routing nodes.
pub trait CreateRouteNode: Sized {
    /// Attach a GET handler to the path.
    fn at<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder;

    /// Alias for [`CreateRouteNode::at`].
    fn get<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        self.at(handler)
    }

    /// Attach a POST handler to the path.
    fn post<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder;

    /// Attach a PATCH handler to the path.
    fn patch<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder;

    /// Attach a PUT handler to the path.
    fn put<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder;

    /// Attach a DELETE handler to the path.
    fn delete<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder;

    /// Attach a HEAD handler to the path.
    fn head<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder;

    /// Attach an OPTIONS handler to the path.
    fn options<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder;

    /// Attach a TRACE handler to the path.
    fn trace<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder;

    /// Mount nested routes under the current path segment.
    fn route(self, routes: impl Routes) -> RouteNode;

    /// Attach an endpoint at the specified method and path.
    ///
    /// Note: This is a low-level method; prefer using `.at`, `.post`, etc. for common HTTP methods.
    /// Especially when using `OpenAPI`, those methods will automatically generate documentation.
    fn endpoint<E>(self, method: Method, endpoint: E) -> RouteNode
    where
        E: Endpoint + Clone + Send + Sync + 'static;

    /// Attach a WebSocket handler that automatically performs the upgrade handshake.
    #[cfg(feature = "ws")]
    fn ws<F, Fut>(self, handler: F) -> RouteNode
    where
        F: Fn(WebSocket) -> Fut + Clone + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let builder = move |upgrade: WebSocketUpgrade| {
            let callback = handler.clone();
            async move { upgrade.on_upgrade(callback) }
        };
        self.at(builder)
    }
}

impl<P> CreateRouteNode for P
where
    P: Into<String>,
{
    fn at<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        endpoint_node_from_handler(self, Method::GET, handler)
    }

    fn post<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        endpoint_node_from_handler(self, Method::POST, handler)
    }

    fn patch<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        endpoint_node_from_handler(self, Method::PATCH, handler)
    }

    fn put<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        endpoint_node_from_handler(self, Method::PUT, handler)
    }

    fn delete<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        endpoint_node_from_handler(self, Method::DELETE, handler)
    }

    fn head<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        endpoint_node_from_handler(self, Method::HEAD, handler)
    }

    fn options<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        endpoint_node_from_handler(self, Method::OPTIONS, handler)
    }

    fn trace<H, T, R>(self, handler: H) -> RouteNode
    where
        H: Handler<T, R>,
        T: Extractor,
        R: Responder,
    {
        endpoint_node_from_handler(self, Method::TRACE, handler)
    }

    fn endpoint<E>(self, method: Method, endpoint: E) -> RouteNode
    where
        E: Endpoint + Clone + Send + Sync + 'static,
    {
        RouteNode::new_endpoint(self, method, endpoint, None)
    }

    fn route(self, routes: impl Routes) -> RouteNode {
        RouteNode::new_route(self.into(), Route::new(routes))
    }
}