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
use std::{any::TypeId, future::Future, marker::PhantomData};

use viz_utils::futures::future::BoxFuture;

use crate::{Context, Error, Extract, Middleware, Response, Result};

pub trait HandlerBase<Args>: Clone + 'static {
    type Output: Into<Response>;
    type Future: Future<Output = Self::Output> + Send + 'static;

    fn call(&self, args: Args) -> Self::Future;
}

pub trait Handler: Send + Sync + 'static {
    fn call<'a>(&'a self, _: &'a mut Context) -> BoxFuture<'a, Result<Response>>;

    fn clone_handler(&self) -> Box<dyn Handler>;
}

impl Handler for Box<dyn Handler> {
    fn call<'a>(&'a self, cx: &'a mut Context) -> BoxFuture<'a, Result<Response>> {
        (**self).call(cx)
    }

    fn clone_handler(&self) -> Box<dyn Handler> {
        (**self).clone_handler()
    }
}

pub struct HandlerWrapper<F, T> {
    pub(crate) f: F,
    _t: PhantomData<T>,
}

impl<F, T> HandlerWrapper<F, T> {
    pub fn new(f: F) -> Self {
        Self { f, _t: PhantomData }
    }
}

impl<F, T> Handler for HandlerWrapper<F, T>
where
    F: HandlerBase<T> + Send + Sync,
    T: Extract + Send + Sync + 'static,
    // T::Error: Into<Response> + Send,
    T::Error: Into<Response> + Into<Error> + Send,
{
    #[inline]
    fn call<'a>(&'a self, cx: &'a mut Context) -> BoxFuture<'a, Result<Response>> {
        Box::pin(async move {
            Ok(match T::extract(cx).await {
                Ok(args) => self.f.call(args).await.into(),
                Err(e) => {
                    // e.into()

                    if TypeId::of::<Error>() == TypeId::of::<T::Error>() {
                        Into::<Error>::into(e)
                            .downcast::<Response>()
                            .map_or_else(Into::into, Into::into)
                    } else {
                        e.into()
                    }
                }
            })
        })
    }

    #[inline]
    fn clone_handler(&self) -> Box<dyn Handler> {
        Box::new(Self {
            f: self.f.clone(),
            _t: PhantomData,
        })
    }
}

impl<'a, F, T> Middleware<'a, Context> for HandlerWrapper<F, T>
where
    F: HandlerBase<T> + Send + Sync + 'static,
    T: Extract + Send + Sync + 'static,
    T::Error: Into<Response> + Send,
{
    type Output = Result<Response>;

    #[inline]
    fn call(&'a self, cx: &'a mut Context) -> BoxFuture<'a, Self::Output> {
        Handler::call(self, cx)
    }
}

pub trait HandlerCamp<'h, Args>: Clone + 'static {
    type Output: Into<Response>;
    type Future: Future<Output = Self::Output> + Send + 'h;

    fn call(&'h self, cx: &'h mut Context, args: Args) -> Self::Future;
}

pub struct HandlerSuper<F, T> {
    pub(crate) f: F,
    _t: PhantomData<T>,
}

impl<F, T> HandlerSuper<F, T> {
    pub fn new(f: F) -> Self {
        Self { f, _t: PhantomData }
    }
}

impl<F, T> Handler for HandlerSuper<F, T>
where
    F: for<'h> HandlerCamp<'h, T> + Send + Sync,
    T: Extract + Send + Sync + 'static,
    // T::Error: Into<Response> + Send,
    T::Error: Into<Response> + Into<Error> + Send,
{
    #[inline]
    fn call<'a>(&'a self, cx: &'a mut Context) -> BoxFuture<'a, Result<Response>> {
        Box::pin(async move {
            Ok(match T::extract(cx).await {
                Ok(args) => self.f.call(cx, args).await.into(),
                Err(e) => {
                    // e.into()

                    if TypeId::of::<Error>() == TypeId::of::<T::Error>() {
                        Into::<Error>::into(e)
                            .downcast::<Response>()
                            .map_or_else(Into::into, Into::into)
                    } else {
                        e.into()
                    }
                }
            })
        })
    }

    #[inline]
    fn clone_handler(&self) -> Box<dyn Handler> {
        Box::new(Self {
            f: self.f.clone(),
            _t: PhantomData,
        })
    }
}

impl<'a, F, T> Middleware<'a, Context> for HandlerSuper<F, T>
where
    F: for<'h> HandlerCamp<'h, T> + Send + Sync + 'static,
    T: Extract + Send + Sync + 'static,
    T::Error: Into<Response> + Send,
{
    type Output = Result<Response>;

    #[inline]
    fn call(&'a self, cx: &'a mut Context) -> BoxFuture<'a, Self::Output> {
        Handler::call(self, cx)
    }
}

#[cfg(test)]
mod test {
    use futures_executor::block_on;

    use viz_utils::{anyhow::anyhow, futures::future::BoxFuture};

    use crate::*;

    #[allow(unstable_name_collisions)]
    #[test]
    fn handler() {
        #[derive(Debug, PartialEq)]
        struct Info {
            hello: String,
        }

        impl Extract for Info {
            type Error = Error;

            fn extract<'a>(_: &'a mut Context) -> BoxFuture<'a, Result<Self, Self::Error>> {
                Box::pin(async {
                    Ok(Info {
                        hello: "world".to_owned(),
                    })
                })
            }
        }

        #[derive(Debug, PartialEq)]
        struct User {
            id: usize,
        }

        impl Extract for User {
            type Error = Error;

            fn extract<'a>(_: &'a mut Context) -> BoxFuture<'a, Result<Self, Self::Error>> {
                Box::pin(async {
                    // Err(anyhow!("User Error"))
                    Ok(User { id: 0 })
                })
            }
        }

        /// Helper method for extractors testing
        pub async fn extract<T: Extract>(cx: &mut Context) -> Result<T, T::Error> {
            T::extract(cx).await
        }

        block_on(async move {
            let mut cx = Context::from(http::Request::new("hello".into()));

            let r_0 = extract::<Info>(&mut cx).await.unwrap();

            assert_eq!(
                r_0,
                Info {
                    hello: "world".to_owned(),
                }
            );

            let r_1 = cx.extract::<Info>().await.unwrap();

            assert_eq!(
                r_1,
                Info {
                    hello: "world".to_owned(),
                }
            );

            let r = extract::<Option<Info>>(&mut cx).await.unwrap();

            assert_eq!(
                r,
                Some(Info {
                    hello: "world".to_owned(),
                })
            );

            let r0 = extract::<(Info, User)>(&mut cx).await.unwrap();
            let r1 = extract::<(User, Info)>(&mut cx).await.unwrap();
            let r2 = cx.extract::<(User, Info)>().await.unwrap();

            assert_eq!(r0.0, r1.1);
            assert_eq!(r0.1, r1.0);
            assert_eq!(r0.0, r2.1);
            assert_eq!(r1.0, r2.0);

            fn make_handler<F, Args>(handler: F) -> Box<dyn Handler>
            where
                F: HandlerBase<Args> + Send + Sync + 'static,
                Args: Extract + Send + Sync + 'static,
                Args::Error: Into<Response> + Send,
            {
                Box::new(HandlerWrapper::new(handler))
            }

            async fn a() -> Response {
                Response::new()
            }

            let h = make_handler(a);
            let mut cx = Context::from(http::Request::new("hello".into()));
            let r = h.call(&mut cx).await;
            assert!(r.is_ok());

            async fn b(i: Info, u: User) -> Result<Response> {
                assert_eq!(
                    i,
                    Info {
                        hello: "world".to_owned(),
                    }
                );
                assert_eq!(u, User { id: 0 });
                Ok(Response::new())
            }
            let h = make_handler(b);
            let mut cx = Context::from(http::Request::new("hello".into()));
            let r = h.call(&mut cx).await;
            assert!(r.is_ok());

            let c = || async { Response::new() };
            let h = make_handler(c);
            let mut cx = Context::from(http::Request::new("hello".into()));
            let r = h.call(&mut cx).await;
            assert!(r.is_ok());

            let d = || Box::pin(async { anyhow!("throws error and converts to response") });
            let h = make_handler(d);
            let mut cx = Context::from(http::Request::new("hello".into()));
            let hh = h.clone_handler();
            let r = h.call(&mut cx).await;
            let mut cx = Context::from(http::Request::new("hello".into()));
            let r0 = hh.call(&mut cx).await;
            assert_eq!(r.is_ok(), r0.is_ok());

            async fn e(u: User) -> Result<Response> {
                assert_eq!(u, User { id: 0 });
                Ok(Response::new())
            }
            let h = make_handler(e);
            let mut cx = Context::from(http::Request::new("hello".into()));
            let r = h.call(&mut cx).await;
            assert!(r.is_ok());

            impl Extract for usize {
                type Error = Error;

                fn extract<'a>(_: &'a mut Context) -> BoxFuture<'a, Result<Self, Self::Error>> {
                    Box::pin(async { Ok(0) })
                }
            }

            async fn f(u: User, n: usize) -> &'static str {
                assert_eq!(u, User { id: 0 });
                assert_eq!(n, 0);
                "Hello world"
            }
            let h = make_handler(f);
            let mut cx = Context::from(http::Request::new("hello".into()));
            let r = h.call(&mut cx).await;
            assert!(r.is_ok());
            let r = Handler::call(&h.clone_handler(), &mut cx).await;
            assert!(r.is_ok());

            assert_eq!(f.call(cx.extract().await.unwrap()).await, "Hello world");
            assert_eq!(
                f.call(cx.extract().await.unwrap()).await,
                HandlerBase::call(&f, cx.extract().await.unwrap()).await
            );

            let mut cx = Context::from(http::Request::new("hello".into()));
            let r = Handler::call(&h, &mut cx).await;
            assert!(r.is_ok());
            let r = Handler::call(&h.clone_handler(), &mut cx).await;
            assert!(r.is_ok());
        });
    }

    #[test]
    fn handler_with_context() {
        block_on(async move {
            fn make_middle(
                f: impl for<'a> Middleware<'a, Context, Output = Result<Response>>,
            ) -> Box<DynMiddleware> {
                Box::new(f)
            }

            #[derive(Debug, PartialEq)]
            struct Language {
                name: String,
            }

            impl Extract for Language {
                type Error = Error;

                fn extract<'a>(_: &'a mut Context) -> BoxFuture<'a, Result<Self, Self::Error>> {
                    Box::pin(async {
                        Ok(Language {
                            name: "rust".to_owned(),
                        })
                    })
                }
            }

            async fn hello(lang: Language) -> &'static str {
                assert_eq!(
                    lang,
                    Language {
                        name: "rust".to_owned()
                    }
                );

                "Hello"
            }

            async fn world(cx: &mut Context, lang: Language) -> &'static str {
                assert_eq!(cx.method(), "GET");
                assert_eq!(
                    lang,
                    Language {
                        name: "rust".to_owned()
                    }
                );

                "World"
            }

            let mut cx = Context::from(http::Request::new("hello".into()));

            let f: Box<dyn Handler> = Box::new(HandlerWrapper::new(hello));
            let r = f.call(&mut cx).await;
            assert!(r.is_ok());

            let f: Box<DynMiddleware> = make_middle(HandlerWrapper::new(hello));
            let r = f.call(&mut cx).await;
            assert!(r.is_ok());

            let f: Box<DynMiddleware> = make_middle(HandlerSuper::new(world));
            let r = f.call(&mut cx).await;
            assert!(r.is_ok());
        });
    }
}