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

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

use std::{borrow::Cow, collections::HashMap, error};

use xitca_service::{
    object::{BoxedServiceObject, BoxedSyncServiceObject},
    pipeline::PipelineT,
    ready::ReadyService,
    FnService, Service,
};

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

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

/// 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> {
    routes: HashMap<Cow<'static, str>, Obj>,
}

/// 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 {}

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

impl<Obj> Router<Obj> {
    pub fn new() -> Self {
        Router { routes: HashMap::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: &'static str, mut builder: F) -> Self
    where
        F: Service<Arg> + RouterGen + Send + Sync,
        F::Response: Service<Req>,
        Req: IntoObject<F::Route<F>, Arg, Object = Obj>,
    {
        let path = builder.path_gen(path);
        assert!(self
            .routes
            .insert(path, Req::into_object(F::route_gen(builder)))
            .is_none());
        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();
        assert!(self.routes.insert(Cow::Borrowed(path), route).is_none());
        self
    }
}

/// trait for specialized route generation when utilizing [Router::insert].
pub trait RouterGen {
    /// service builder type for generating the final route service.
    type Route<R>;

    /// path generator.
    ///
    /// default to passthrough of original prefix path.
    fn path_gen(&mut self, prefix: &'static str) -> Cow<'static, str> {
        Cow::Borrowed(prefix)
    }

    /// 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> RouterGen for Router<Obj> {
    type Route<R> = R;

    fn path_gen(&mut self, prefix: &'static str) -> Cow<'static, str> {
        let mut path = String::from(prefix);
        if path.ends_with('/') {
            path.pop();
        }

        self.routes = self
            .routes
            .drain()
            .map(|(k, v)| {
                let mut path = path.clone();
                path.push_str(k.as_ref());
                (Cow::Owned(path), v)
            })
            .collect();

        path.push_str("/*");

        Cow::Owned(path)
    }

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

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

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

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

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

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

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

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

    fn path_gen(&mut self, prefix: &'static str) -> Cow<'static, str> {
        self.first.path_gen(prefix)
    }

    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, Arg> Service<Arg> for RouterMapErr<S>
where
    S: Service<Arg>,
{
    type Response = MapErrService<S::Response>;
    type Error = S::Error;

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

pub struct MapErrService<S>(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)
    }
}

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

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

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

        Ok(RouterService { routes })
    }
}

pub struct RouterService<S> {
    routes: 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 core::future::Future<Output = Result<Self::Response, Self::Error>> {
        async {
            let xitca_router::Match { value, params } =
                self.routes.at(req.borrow().path()).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 {}
}

/// 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].
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;
}

impl<T, Arg, Ext, Res, Err> IntoObject<T, Arg> for Request<Ext>
where
    Ext: 'static,
    T: Service<Arg> + Send + Sync + 'static,
    T::Response: Service<Request<Ext>, Response = Res, Error = Err> + 'static,
{
    type Object = BoxedSyncServiceObject<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, Arg, Res, Err> Service<Arg> for Builder<T, Req>
        where
            T: Service<Arg> + '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 _)
            }
        }

        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;
}

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

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

    use crate::{
        http::{Request, 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();
    }

    #[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 RouteObject = BoxedSyncServiceObject<(), Route, Infallible>;

        struct Index;

        impl TypedRoute for Index {
            type Route = RouteObject;

            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 = RouteObject;

            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();
    }
}