xitca-http 0.9.1

http library for xitca
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
pub use xitca_router::{MatchError, params::Params};

use core::{error, fmt, marker::PhantomData};

use xitca_service::{BoxFuture, FnService, Service, object::BoxedServiceObject, pipeline::PipelineT};

use crate::http::Request;

use super::{
    handler::HandlerService,
    route::{MethodNotAllowed, Route},
};

pub use self::object::RouteObject;

/// Simple router for matching path and call according service.
///
/// An [ServiceObject](xitca_service::object::ServiceObject) must be specified as a type parameter
/// in order to determine how the router type-erases node services.
pub struct Router<Obj> {
    // record for last time PathGen is called with certain route string prefix.
    prefix: usize,
    routes: xitca_router::Router<Obj>,
}

impl<Obj> Default for Router<Obj> {
    fn default() -> Self {
        Router::new()
    }
}

impl<Obj> Router<Obj> {
    pub fn new() -> Self {
        Router {
            prefix: 0,
            routes: xitca_router::Router::new(),
        }
    }
}

impl<Obj> Router<Obj> {
    /// Insert a new service builder to given path. The service builder must produce another
    /// service type that impl [Service] trait while it's generic `Req` type must impl
    /// [IntoObject] trait.
    ///
    /// # Panic:
    ///
    /// When multiple services inserted to the same path.
    pub fn insert<F, Arg, Req>(mut self, path: &str, mut builder: F) -> Self
    where
        F: Service<Arg> + RouteGen + Send + Sync,
        F::Response: Service<Req>,
        Req: IntoObject<F::Route<F>, Arg, Object = Obj>,
    {
        let path = builder.path_gen(path);
        self.routes
            .insert(path, Req::into_object(F::route_gen(builder)))
            .unwrap();
        self
    }

    /// Merge another router into this one. All routes from `other` are moved into `self`.
    ///
    /// # Panic:
    ///
    /// When routes from `other` conflict with existing routes in `self`.
    pub fn merge(mut self, other: Router<Obj>) -> Self {
        self.routes.merge(other.routes).unwrap();
        self
    }

    #[doc(hidden)]
    /// See [TypedRoute] for detail.
    pub fn insert_typed<T, M>(mut self, _: T) -> Router<Obj>
    where
        T: TypedRoute<M, Route = Obj>,
    {
        let path = T::path();
        let route = T::route();
        self.routes.insert(path, route).unwrap();
        self
    }
}

impl<Obj, Arg> Service<Arg> for Router<Obj>
where
    Obj: Service<Arg>,
    Arg: Clone,
{
    type Response = service::RouterService<Obj::Response>;
    type Error = Obj::Error;

    async fn call(&self, arg: Arg) -> Result<Self::Response, Self::Error> {
        let mut router = xitca_router::Router::new();

        for (path, service) in self.routes.entries() {
            let service = service.call(arg.clone()).await?;
            router.insert(path, service).unwrap();
        }

        Ok(service::RouterService {
            prefix: self.prefix,
            router,
        })
    }
}

/// Error type of Router service.
pub enum RouterError<E> {
    /// failed to match on a routed service.
    Match(MatchError),
    /// a match of service is found but it's not allowed for access.
    NotAllowed(MethodNotAllowed),
    /// error produced by routed service.
    Service(E),
}

impl<E> fmt::Debug for RouterError<E>
where
    E: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::Match(ref e) => fmt::Debug::fmt(e, f),
            Self::NotAllowed(ref e) => fmt::Debug::fmt(e, f),
            Self::Service(ref e) => fmt::Debug::fmt(e, f),
        }
    }
}

impl<E> fmt::Display for RouterError<E>
where
    E: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::Match(ref e) => fmt::Display::fmt(e, f),
            Self::NotAllowed(ref e) => fmt::Display::fmt(e, f),
            Self::Service(ref e) => fmt::Display::fmt(e, f),
        }
    }
}

impl<E> error::Error for RouterError<E> where E: error::Error {}

/// trait for specialized route generation when utilizing [Router::insert].
#[diagnostic::on_unimplemented(
    message = "`{Self}` does not impl PathGen trait",
    label = "route must impl PathGen trait for specialized route path configuration",
    note = "consider add `impl PathGen for {Self}`"
)]
pub trait PathGen {
    /// path generator.
    ///
    /// default to passthrough of original prefix path.
    fn path_gen(&mut self, prefix: &str) -> String {
        String::from(prefix)
    }
}

/// trait for specialized route generation when utilizing [Router::insert].
#[diagnostic::on_unimplemented(
    message = "`{Self}` does not impl RouteGen trait",
    label = "route must impl RouteGen trait for specialized route path and service configuration",
    note = "consider add `impl PathGen for {Self}` and `impl RouteGen for {Self}`"
)]
pub trait RouteGen: PathGen {
    /// service builder type for generating the final route service.
    type Route<R>;

    /// route service generator.
    ///
    /// implicit default to map error type to [RouterError] with [RouterMapErr].
    fn route_gen<R>(route: R) -> Self::Route<R>;
}

// nest router needs special handling for path generation.
impl<Obj> PathGen for Router<Obj>
where
    Obj: PathGen,
{
    fn path_gen(&mut self, path: &str) -> String {
        let mut path = String::from(path);

        if path.ends_with("/{*}") {
            drop(path.split_off("{*}".len()));
        }

        if path.ends_with('/') {
            path.pop();
        }

        self.prefix += path.len();

        self.routes.for_each_mut(|_, v| {
            v.path_gen(path.as_str());
        });

        path.push_str("/{*}");

        path
    }
}

impl<Obj> RouteGen for Router<Obj>
where
    Obj: RouteGen,
{
    type Route<R> = R;

    fn route_gen<R>(route: R) -> Self::Route<R> {
        route
    }
}

impl<R, N, const M: usize> PathGen for Route<R, N, M> {}

impl<R, N, const M: usize> RouteGen for Route<R, N, M> {
    type Route<R1> = R1;

    fn route_gen<R1>(route: R1) -> Self::Route<R1> {
        route
    }
}

impl<F, T, M> PathGen for HandlerService<F, T, M> {}

impl<F, T, M> RouteGen for HandlerService<F, T, M> {
    type Route<R> = RouterMapErr<R>;

    fn route_gen<R>(route: R) -> Self::Route<R> {
        RouterMapErr(route)
    }
}

impl<F> PathGen for FnService<F> {}

impl<F> RouteGen for FnService<F> {
    type Route<R1> = RouterMapErr<R1>;

    fn route_gen<R1>(route: R1) -> Self::Route<R1> {
        RouterMapErr(route)
    }
}

impl<F, S, M> PathGen for PipelineT<F, S, M>
where
    F: PathGen,
{
    fn path_gen(&mut self, prefix: &str) -> String {
        self.first.path_gen(prefix)
    }
}

impl<F, S, M> RouteGen for PipelineT<F, S, M>
where
    F: RouteGen,
{
    type Route<R> = F::Route<R>;

    fn route_gen<R>(route: R) -> Self::Route<R> {
        F::route_gen(route)
    }
}

/// default error mapper service that map all service error type to `RouterError::Second`
pub struct RouterMapErr<S>(pub S);

impl<S> PathGen for RouterMapErr<S>
where
    S: PathGen,
{
    fn path_gen(&mut self, prefix: &str) -> String {
        self.0.path_gen(prefix)
    }
}

impl<S> RouteGen for RouterMapErr<S>
where
    S: RouteGen,
{
    type Route<R> = S::Route<R>;

    fn route_gen<R>(route: R) -> Self::Route<R> {
        S::route_gen(route)
    }
}

impl<S, Arg> Service<Arg> for RouterMapErr<S>
where
    S: Service<Arg>,
{
    type Response = service::MapErrService<S::Response>;
    type Error = S::Error;

    async fn call(&self, arg: Arg) -> Result<Self::Response, Self::Error> {
        self.0.call(arg).await.map(service::MapErrService)
    }
}

/// An object constructor represents a one of possibly many ways to create a trait object from `I`.
///
/// A [Service] type, for example, may be type-erased into `Box<dyn Service<&'static str>>`,
/// `Box<dyn for<'a> Service<&'a str>>`, `Box<dyn Service<&'static str> + Service<u8>>`, etc.
/// Each would be a separate impl for [IntoObject].
#[diagnostic::on_unimplemented(
    message = "`{Self}` does not impl IntoObject trait",
    label = "route must impl IntoObject trait for specialized type erased service type",
    note = "consider add `impl IntoObject<_> for {Self}`"
)]
pub trait IntoObject<I, Arg> {
    /// The type-erased form of `I`.
    type Object;

    /// Constructs `Self::Object` from `I`.
    fn into_object(inner: I) -> Self::Object;
}

mod object {
    use super::*;

    pub trait RouteService<Arg>: PathGen {
        type Response;
        type Error;

        fn call<'s>(&'s self, arg: Arg) -> BoxFuture<'s, Self::Response, Self::Error>
        where
            Arg: 's;
    }

    impl<Arg, S> RouteService<Arg> for S
    where
        S: Service<Arg> + PathGen,
    {
        type Response = S::Response;
        type Error = S::Error;

        fn call<'s>(&'s self, arg: Arg) -> BoxFuture<'s, Self::Response, Self::Error>
        where
            Arg: 's,
        {
            Box::pin(Service::call(self, arg))
        }
    }

    pub struct RouteObject<Arg, S, E>(pub Box<dyn RouteService<Arg, Response = S, Error = E> + Send + Sync>);

    impl<Arg, S, E> PathGen for RouteObject<Arg, S, E> {
        fn path_gen(&mut self, prefix: &str) -> String {
            self.0.path_gen(prefix)
        }
    }

    impl<Arg, S, E> RouteGen for RouteObject<Arg, S, E> {
        type Route<R> = R;

        fn route_gen<R>(route: R) -> Self::Route<R> {
            route
        }
    }

    impl<Arg, S, E> Service<Arg> for RouteObject<Arg, S, E> {
        type Response = S;
        type Error = E;

        async fn call(&self, arg: Arg) -> Result<Self::Response, Self::Error> {
            self.0.call(arg).await
        }
    }
}

impl<T, Arg, Ext, Res, Err> IntoObject<T, Arg> for Request<Ext>
where
    Ext: 'static,
    T: Service<Arg> + RouteGen + Send + Sync + 'static,
    T::Response: Service<Request<Ext>, Response = Res, Error = Err> + 'static,
{
    type Object = object::RouteObject<Arg, BoxedServiceObject<Request<Ext>, Res, Err>, T::Error>;

    fn into_object(inner: T) -> Self::Object {
        struct Builder<T, Req>(T, PhantomData<fn(Req)>);

        impl<T, Req> PathGen for Builder<T, Req>
        where
            T: PathGen,
        {
            fn path_gen(&mut self, prefix: &str) -> String {
                self.0.path_gen(prefix)
            }
        }

        impl<T, Req> RouteGen for Builder<T, Req>
        where
            T: RouteGen,
        {
            type Route<R> = T::Route<R>;

            fn route_gen<R>(route: R) -> Self::Route<R> {
                T::route_gen(route)
            }
        }

        impl<T, Req, Arg, Res, Err> Service<Arg> for Builder<T, Req>
        where
            T: Service<Arg> + RouteGen + 'static,
            T::Response: Service<Req, Response = Res, Error = Err> + 'static,
        {
            type Response = BoxedServiceObject<Req, Res, Err>;
            type Error = T::Error;

            async fn call(&self, arg: Arg) -> Result<Self::Response, Self::Error> {
                self.0.call(arg).await.map(|s| Box::new(s) as _)
            }
        }

        object::RouteObject(Box::new(Builder(inner, PhantomData)))
    }
}

#[doc(hidden)]
/// trait for concrete typed Router and Routes.
/// all generic types must be known when implementing the trait and Router<Obj>
/// would infer it's generic types from it.
pub trait TypedRoute<M = ()> {
    /// typed route. in form of Box<dyn ServiceObject<_>>
    type Route;

    /// method for providing matching path of Self::Route.
    fn path() -> &'static str;

    /// method for generating typed route.
    fn route() -> Self::Route;
}

mod service {
    use xitca_service::ready::ReadyService;

    use crate::http::{BorrowReq, BorrowReqMut, Uri};

    use super::{Params, RouterError, Service};

    pub struct RouterService<S> {
        // a length record of prefix of current router.
        // when it's Some the request path has to be sliced to exclude the string path prefix.
        pub(super) prefix: usize,
        pub(super) router: xitca_router::Router<S>,
    }

    impl<S, Req, E> Service<Req> for RouterService<S>
    where
        S: Service<Req, Error = RouterError<E>>,
        Req: BorrowReq<Uri> + BorrowReqMut<Params>,
    {
        type Response = S::Response;
        type Error = S::Error;

        // as of the time of committing rust compiler have problem optimizing this piece of code.
        // using async fn call directly would cause significant code bloating.
        #[allow(clippy::manual_async_fn)]
        #[inline]
        fn call(&self, mut req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>> {
            async {
                let path = req.borrow().path();
                let xitca_router::Match { value, params } =
                    self.router.at(&path[self.prefix..]).map_err(RouterError::Match)?;
                *req.borrow_mut() = params;
                Service::call(value, req).await
            }
        }
    }

    impl<S> ReadyService for RouterService<S> {
        type Ready = ();

        #[inline]
        async fn ready(&self) -> Self::Ready {}
    }

    pub struct MapErrService<S>(pub(super) S);

    impl<S, Req> Service<Req> for MapErrService<S>
    where
        S: Service<Req>,
    {
        type Response = S::Response;
        type Error = RouterError<S::Error>;

        #[inline]
        async fn call(&self, req: Req) -> Result<Self::Response, Self::Error> {
            self.0.call(req).await.map_err(RouterError::Service)
        }
    }
}

#[cfg(test)]
mod test {
    use core::convert::Infallible;

    use xitca_service::{ServiceExt, fn_service, ready::ReadyService};
    use xitca_unsafe_collection::futures::NowOrPanic;

    use crate::{
        http::{RequestExt, Response},
        util::service::route::get,
    };

    use super::*;

    async fn enclosed<S, Req>(service: &S, req: Req) -> Result<S::Response, S::Error>
    where
        S: Service<Req>,
    {
        service.call(req).await
    }

    async fn func(_: Request<RequestExt<()>>) -> Result<Response<()>, Infallible> {
        Ok(Response::new(()))
    }

    #[test]
    fn router_sync() {
        fn bound_check<T: Send + Sync>(_: T) {}

        bound_check(Router::new().insert("/", fn_service(func)))
    }

    #[test]
    fn router_accept_request() {
        Router::new()
            .insert("/", fn_service(func))
            .call(())
            .now_or_panic()
            .unwrap()
            .call(Request::default())
            .now_or_panic()
            .unwrap();
    }

    #[test]
    fn router_enclosed_fn() {
        Router::new()
            .insert("/", fn_service(func))
            .enclosed_fn(enclosed)
            .call(())
            .now_or_panic()
            .unwrap()
            .call(Request::default())
            .now_or_panic()
            .unwrap();
    }

    #[test]
    fn router_add_params_http() {
        let req = Request::builder().uri("/users/1").body(Default::default()).unwrap();

        Router::new()
            .insert(
                "/users/{id}",
                fn_service(|req: Request<RequestExt<()>>| async move {
                    let params = req.body().params();
                    assert_eq!(params.get("id").unwrap(), "1");
                    Ok::<_, Infallible>(Response::new(()))
                }),
            )
            .enclosed_fn(enclosed)
            .call(())
            .now_or_panic()
            .unwrap()
            .call(req)
            .now_or_panic()
            .unwrap();
    }

    #[test]
    fn router_nest() {
        let handler = || get(fn_service(func)).enclosed_fn(enclosed);

        let router = || Router::new().insert("/nest", handler()).enclosed_fn(enclosed);

        let req = || {
            Request::builder()
                .uri("http://foo.bar/scope/nest")
                .body(Default::default())
                .unwrap()
        };

        Router::new()
            .insert("/raw", fn_service(func))
            .insert("/root", handler())
            .insert("/scope", router())
            .call(())
            .now_or_panic()
            .unwrap()
            .call(req())
            .now_or_panic()
            .unwrap();

        Router::new()
            .insert("/root", handler())
            .insert("/scope/", router())
            .call(())
            .now_or_panic()
            .unwrap()
            .call(req())
            .now_or_panic()
            .unwrap();

        Router::new()
            .insert(
                "/1111/",
                Router::new().insert(
                    "/222222/3",
                    Router::new().insert("/3333333", Router::new().insert("/4444", router())),
                ),
            )
            .call(())
            .now_or_panic()
            .unwrap()
            .call(
                Request::builder()
                    .uri("http://foo.bar/1111/222222/3/3333333/4444/nest")
                    .body(Default::default())
                    .unwrap(),
            )
            .now_or_panic()
            .unwrap();

        Router::new()
            .insert("/api", Router::new().insert("/v2", router()))
            .call(())
            .now_or_panic()
            .unwrap()
            .call(
                Request::builder()
                    .uri("http://foo.bar/api/v2/nest")
                    .body(Default::default())
                    .unwrap(),
            )
            .now_or_panic()
            .unwrap();
    }

    #[test]
    fn router_service_call_size() {
        let service = Router::new()
            .insert("/", fn_service(func))
            .call(())
            .now_or_panic()
            .unwrap();

        println!(
            "router service ready call size: {:?}",
            core::mem::size_of_val(&service.ready())
        );

        println!(
            "router service call size: {:?}",
            core::mem::size_of_val(&service.call(Request::default()))
        );
    }

    #[test]
    fn router_typed() {
        type Req = Request<RequestExt<()>>;
        type Route = BoxedServiceObject<Req, Response<()>, RouterError<Infallible>>;
        type Object = object::RouteObject<(), Route, Infallible>;

        struct Index;

        impl TypedRoute for Index {
            type Route = Object;

            fn path() -> &'static str {
                "/"
            }

            fn route() -> Self::Route {
                Req::into_object(RouterMapErr(xitca_service::fn_service(func)))
            }
        }

        struct V2;

        impl TypedRoute for V2 {
            type Route = Object;

            fn path() -> &'static str {
                "/v2"
            }

            fn route() -> Self::Route {
                Req::into_object(RouterMapErr(xitca_service::fn_service(func)))
            }
        }

        Router::new()
            .insert_typed(Index)
            .insert_typed(V2)
            .call(())
            .now_or_panic()
            .unwrap()
            .call(Request::default())
            .now_or_panic()
            .unwrap();
    }
}