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
//! high level async function service with "variadic generic" ish.

use core::{convert::Infallible, future::Future, marker::PhantomData};

use std::net::SocketAddr;

use xitca_service::{pipeline::PipelineE, AsyncClosure, Service};

use crate::http::{BorrowReq, Extensions, HeaderMap, Method, Request, RequestExt, Uri};

/// A service factory shortcut offering given async function ability to use [FromRequest] to destruct and transform `Service<Req>`'s
/// `Req` type and receive them as function argument.
///
/// Given async function's return type must impl [Responder] trait for transforming arbitrary return type to `Service::Future`'s
/// output type.
pub fn handler_service<F, T>(func: F) -> HandlerService<F, T, marker::BuilderMark>
where
    F: AsyncClosure<T> + Clone,
{
    HandlerService::new(func)
}

pub struct HandlerService<F, T, M> {
    func: F,
    _p: PhantomData<fn(T, M)>,
}

// marker for specialized trait implement on HandlerService
mod marker {
    pub struct BuilderMark;
    pub struct ServiceMark;
}

impl<F, T, M> HandlerService<F, T, M> {
    pub const fn new(func: F) -> Self {
        Self { func, _p: PhantomData }
    }
}

impl<F, T, M> Clone for HandlerService<F, T, M>
where
    F: Clone,
{
    fn clone(&self) -> Self {
        Self::new(self.func.clone())
    }
}

impl<F, T> Service for HandlerService<F, T, marker::BuilderMark>
where
    F: Clone,
{
    type Response = HandlerService<F, T, marker::ServiceMark>;
    type Error = Infallible;

    async fn call(&self, _: ()) -> Result<Self::Response, Self::Error> {
        Ok(HandlerService::new(self.func.clone()))
    }
}

impl<F, Req, T, O> Service<Req> for HandlerService<F, T, marker::ServiceMark>
where
    // for borrowed extractors, `T` is the `'static` version of the extractors
    T: FromRequest<'static, Req>,
    // just to assist type inference to pinpoint `T`
    F: AsyncClosure<T>,
    F: for<'a> AsyncClosure<T::Type<'a>, Output = O>,
    O: Responder<Req>,
    T::Error: From<O::Error>,
{
    type Response = O::Response;
    type Error = T::Error;

    #[inline]
    async fn call(&self, req: Req) -> Result<Self::Response, Self::Error> {
        let extract = T::Type::<'_>::from_request(&req).await?;
        let res = self.func.call(extract).await;
        res.respond(req).await.map_err(Into::into)
    }
}

/// Extract type from Req asynchronously and receive them with function passed to [handler_service].
///
/// `'a` is the lifetime of the extracted type.
///
/// When `Req` is also a borrowed type, the lifetimes of `Req` type and of the extracted type should
/// be kept separate. See example below of extracting &str from &String:
///
/// # Examples
/// ```
/// # use std::future::Future;
/// # use xitca_http::util::service::handler::FromRequest;
///
/// // new type for implementing FromRequest trait to &str.
/// struct Str<'a>(&'a str);
///
/// // borrowed Req type has a named lifetime of it self while trait implementor has the same lifetime
/// // from FromRequest's lifetime param.
/// impl<'a, 'r> FromRequest<'a, &'r String> for Str<'a> {
///     type Type<'b> = Str<'b>; // use GAT lifetime to output a named lifetime instance of implementor.
///     type Error = ();
///
///     async fn from_request(req: &'a &'r String) -> Result<Self, Self::Error> {
///         Ok(Str(req))
///     }
/// }
///
/// # async fn extract() {
/// let input = &String::from("996");
/// let extract = Str::from_request(&input).await.unwrap();
/// assert_eq!(extract.0, input.as_str());
/// # }
/// ```
pub trait FromRequest<'a, Req>: Sized {
    // Used to construct the type for any lifetime 'b.
    type Type<'b>: FromRequest<'b, Req, Error = Self::Error>;
    type Error;

    fn from_request(req: &'a Req) -> impl Future<Output = Result<Self, Self::Error>>;
}

macro_rules! from_req_impl {
    ($req0: ident, $($req: ident,)*) => {
        impl<'a, Req, $req0, $($req,)*> FromRequest<'a, Req> for ($req0, $($req,)*)
        where
            $req0: FromRequest<'a, Req>,
            $(
                $req: FromRequest<'a, Req>,
                $req0::Error: From<$req::Error>,
            )*
        {
            type Type<'r> = ($req0::Type<'r>, $($req::Type<'r>,)*);
            type Error = $req0::Error;

            #[inline]
            async fn from_request(req: &'a Req) -> Result<Self, Self::Error> {
                Ok((
                    $req0::from_request(req).await?,
                    $($req::from_request(req).await?,)*
                ))
            }
        }
    }
}

from_req_impl! { A, }
from_req_impl! { A, B, }
from_req_impl! { A, B, C, }
from_req_impl! { A, B, C, D, }
from_req_impl! { A, B, C, D, E, }
from_req_impl! { A, B, C, D, E, F, }
from_req_impl! { A, B, C, D, E, F, G, }
from_req_impl! { A, B, C, D, E, F, G, H, }
from_req_impl! { A, B, C, D, E, F, G, H, I, }

/// Make Response with ownership of Req.
/// The Output type is what returns from [handler_service] function.
pub trait Responder<Req> {
    type Response;
    type Error;

    /// generate response from given request.
    fn respond(self, req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>>;

    /// map response type and mutate it's state.
    /// default to pass through without any modification.
    fn map(self, res: Self::Response) -> Result<Self::Response, Self::Error>
    where
        Self: Sized,
    {
        Ok(res)
    }
}

macro_rules! responder_impl {
    ($res0: ident, $($res: ident,)*) => {
        #[allow(non_snake_case)]
        impl<Req, $res0, $($res,)*> Responder<Req> for ($res0, $($res,)*)
        where
            $res0: Responder<Req>,
            $(
                $res: Responder<Req, Response = $res0::Response>,
                $res0::Error: From<$res::Error>,
            )*
        {
            type Response = $res0::Response;
            type Error = $res0::Error;

            async fn respond(self, req: Req) -> Result<Self::Response, Self::Error> {
                let ($res0, $($res,)*) = self;

                let res = $res0.respond(req).await?;
                $(
                    let res = $res.map(res)?;
                )*

                Ok(res)
            }

            fn map(self, mut res: Self::Response) -> Result<Self::Response, Self::Error> {
                let ($res0, $($res,)*) = self;

                res = $res0.map(res)?;
                $(
                    res = $res.map(res)?;
                )*

                Ok(res)
            }
        }
    }
}

responder_impl! { A, }
responder_impl! { A, B, }
responder_impl! { A, B, C, }
responder_impl! { A, B, C, D, }
responder_impl! { A, B, C, D, E, }
responder_impl! { A, B, C, D, E, F, }

impl<R, F, S> Responder<R> for PipelineE<F, S>
where
    F: Responder<R>,
    S: Responder<R, Response = F::Response>,
    F::Error: From<S::Error>,
{
    type Response = F::Response;
    type Error = F::Error;

    #[inline]
    async fn respond(self, req: R) -> Result<Self::Response, Self::Error> {
        match self {
            Self::First(f) => f.respond(req).await,
            Self::Second(s) => s.respond(req).await.map_err(From::from),
        }
    }
}

macro_rules! borrow_req_impl {
    ($tt: tt) => {
        impl<'a, Ext> FromRequest<'a, Request<Ext>> for &'a $tt {
            type Type<'b> = &'b $tt;
            type Error = Infallible;

            #[inline]
            async fn from_request(req: &'a Request<Ext>) -> Result<Self, Self::Error> {
                Ok(req.borrow())
            }
        }
    };
}

borrow_req_impl!(Method);
borrow_req_impl!(Uri);
borrow_req_impl!(HeaderMap);
borrow_req_impl!(Extensions);

impl<'a, Ext> FromRequest<'a, Request<Ext>> for &'a Request<Ext>
where
    Ext: 'static,
{
    type Type<'b> = &'b Request<Ext>;
    type Error = Infallible;

    #[inline]
    async fn from_request(req: &'a Request<Ext>) -> Result<Self, Self::Error> {
        Ok(req)
    }
}

impl<'a, B> FromRequest<'a, Request<RequestExt<B>>> for &'a SocketAddr {
    type Type<'b> = &'b SocketAddr;
    type Error = Infallible;

    #[inline]
    async fn from_request(req: &'a Request<RequestExt<B>>) -> Result<Self, Self::Error> {
        Ok(req.borrow())
    }
}

#[cfg(test)]
mod test {
    use xitca_service::ServiceExt;
    use xitca_unsafe_collection::futures::NowOrPanic;

    use crate::{
        http::{Response, StatusCode},
        unspecified_socket_addr,
    };

    use super::*;

    async fn handler(
        method: &Method,
        addr: &SocketAddr,
        uri: &Uri,
        headers: &HeaderMap,
        (_, ext): (&Request<RequestExt<()>>, &Extensions),
    ) -> StatusCode {
        assert_eq!(method, Method::GET);
        assert_eq!(*addr, unspecified_socket_addr());
        assert_eq!(uri.path(), "/");
        assert!(headers.is_empty());
        assert!(ext.is_empty());

        StatusCode::MULTI_STATUS
    }

    impl Responder<Request<RequestExt<()>>> for StatusCode {
        type Response = Response<()>;
        type Error = Infallible;

        async fn respond(self, _: Request<RequestExt<()>>) -> Result<Self::Response, Self::Error> {
            let mut res = Response::new(());
            *res.status_mut() = self;
            Ok(res)
        }
    }

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

        let res = handler_service(handler)
            .enclosed_fn(enclosed)
            .call(())
            .now_or_panic()
            .unwrap()
            .call(Request::default())
            .now_or_panic()
            .unwrap();

        assert_eq!(res.status(), StatusCode::MULTI_STATUS);
    }

    #[cfg(feature = "router")]
    #[test]
    fn handler_in_router() {
        use crate::util::service::{route::get, Router};

        let res = Router::new()
            .insert("/", get(handler_service(handler)))
            .call(())
            .now_or_panic()
            .unwrap()
            .call(Request::default())
            .now_or_panic()
            .unwrap();

        assert_eq!(res.status(), StatusCode::MULTI_STATUS);
    }
}