viz-router 0.2.0-alpha

Viz Router
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
use core::fmt;

use viz_core::{
    handler::{Next, Transform},
    Body, BoxHandler, FnExt, FromRequest, Handler, HandlerExt, IntoResponse, Method, Request,
    Responder, ResponderExt, Response, Result,
};

macro_rules! repeat {
    ($macro:ident $($name:ident $verb:tt )+) => {
        $(
            $macro!($name $verb);
        )+
    };
}

macro_rules! export_internal_verb {
    ($name:ident $verb:tt) => {
        #[doc = concat!(" Appends a route, handle HTTP verb `", stringify!($verb), "`.")]
        pub fn $name<H, O>(self, handler: H) -> Self
        where
            H: Handler<Request<Body>, Output = Result<O>> + Clone,
            O: IntoResponse + Send + Sync + 'static,
        {
            self.on(Method::$verb, handler)
        }
    };
}

#[cfg(feature = "ext")]
macro_rules! export_internal_verb_ext {
    ($name:ident $verb:tt) => {
        #[doc = concat!(" Appends a route, handle HTTP verb `", stringify!($verb), "` with multiple parameters.")]
        pub fn $name<H, O, I>(self, handler: H) -> Self
        where
            I: FromRequest + Send + Sync + 'static,
            I::Error: IntoResponse + Send + Sync,
            H: FnExt<I, Output = Result<O>>,
            O: IntoResponse + Send + Sync + 'static,
        {
            self.on_ext(Method::$verb, handler)
        }
    };
}

macro_rules! export_verb {
    ($name:ident $verb:ty) => {
        #[doc = concat!(" Appends a route, handle HTTP verb `", stringify!($verb), "`.")]
        pub fn $name<H, O>(handler: H) -> Route
        where
            H: Handler<Request<Body>, Output = Result<O>> + Clone,
            O: IntoResponse + Send + Sync + 'static,
        {
            Route::new().$name(handler)
        }
    };
}

#[cfg(feature = "ext")]
macro_rules! export_verb_ext {
    ($name:ident $verb:ty) => {
        #[doc = concat!(" Appends a route, handle HTTP verb `", stringify!($verb), "` with multiple parameters.")]
        pub fn $name<H, O, I>(handler: H) -> Route
        where
            I: FromRequest + Send + Sync + 'static,
            I::Error: IntoResponse + Send + Sync,
            H: FnExt<I, Output = Result<O>>,
            O: IntoResponse + Send + Sync + 'static,
        {
            Route::new().$name(handler)
        }
    };
}

#[derive(Clone)]
pub struct Route {
    pub(crate) methods: Vec<(Method, BoxHandler)>,
}

impl fmt::Debug for Route {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Route")
            .field(
                "methods",
                &self
                    .methods
                    .iter()
                    .map(|(m, _)| m)
                    .collect::<Vec<&Method>>(),
            )
            .finish()
    }
}

impl Route {
    pub fn new() -> Self {
        Self {
            methods: Vec::new(),
        }
    }

    pub fn push(mut self, method: Method, handler: BoxHandler) -> Self {
        match self
            .methods
            .iter_mut()
            .find(|(m, _)| m == method)
            .map(|(_, e)| e)
        {
            Some(h) => *h = handler,
            None => self.methods.push((method, handler)),
        }

        self
    }

    /// Appends a route, with a HTTP verb and handler.
    pub fn on<H, O>(self, method: Method, handler: H) -> Self
    where
        H: Handler<Request<Body>, Output = Result<O>> + Clone,
        O: IntoResponse + Send + Sync + 'static,
    {
        self.push(method, Responder::new(handler).boxed())
    }

    /// Appends a route, with a HTTP verb and handler.
    pub fn any<H, O>(self, handler: H) -> Self
    where
        H: Handler<Request<Body>, Output = Result<O>> + Clone,
        O: IntoResponse + Send + Sync + 'static,
    {
        [
            Method::GET,
            Method::POST,
            Method::PUT,
            Method::DELETE,
            Method::HEAD,
            Method::OPTIONS,
            Method::CONNECT,
            Method::PATCH,
            Method::TRACE,
        ]
        .into_iter()
        .fold(self, |route, method| route.on(method, handler.clone()))
    }

    repeat!(
        export_internal_verb
        get GET
        post POST
        put PUT
        delete DELETE
        head HEAD
        options OPTIONS
        connect CONNECT
        patch PATCH
        trace TRACE
    );

    pub fn with<T>(self, t: T) -> Self
    where
        T: Transform<BoxHandler>,
        T::Output: Handler<Request<Body>, Output = Result<Response<Body>>>,
    {
        self.into_iter()
            .map(|(method, handler)| (method, t.transform(handler).boxed()))
            .collect()
    }

    pub fn with_handler<F>(self, f: F) -> Self
    where
        F: Handler<Next<Request<Body>, BoxHandler>, Output = Result<Response<Body>>> + Clone,
    {
        self.into_iter()
            .map(|(method, handler)| (method, handler.around(f.clone()).boxed()))
            .collect()
    }

    pub fn map_handler<F>(self, f: F) -> Self
    where
        F: Fn(BoxHandler) -> BoxHandler,
    {
        self.into_iter()
            .map(|(method, handler)| (method, f(handler)))
            .collect()
    }
}

#[cfg(feature = "ext")]
impl Route {
    /// Appends a route, with a HTTP verb and handler.
    pub fn on_ext<H, O, I>(self, method: Method, handler: H) -> Self
    where
        I: FromRequest + Send + Sync + 'static,
        I::Error: IntoResponse + Send + Sync,
        H: FnExt<I, Output = Result<O>>,
        O: IntoResponse + Send + Sync + 'static,
    {
        self.push(method, ResponderExt::new(handler).boxed())
    }

    /// Appends a route, with a HTTP verb and handler.
    pub fn any_ext<H, O, I>(self, handler: H) -> Self
    where
        I: FromRequest + Send + Sync + 'static,
        I::Error: IntoResponse + Send + Sync,
        H: FnExt<I, Output = Result<O>>,
        O: IntoResponse + Send + Sync + 'static,
    {
        [
            Method::GET,
            Method::POST,
            Method::PUT,
            Method::DELETE,
            Method::HEAD,
            Method::OPTIONS,
            Method::CONNECT,
            Method::PATCH,
            Method::TRACE,
        ]
        .into_iter()
        .fold(self, |route, method| route.on_ext(method, handler.clone()))
    }

    repeat!(
        export_internal_verb_ext
        get_ext GET
        post_ext POST
        put_ext PUT
        delete_ext DELETE
        head_ext HEAD
        options_ext OPTIONS
        connect_ext CONNECT
        patch_ext PATCH
        trace_ext TRACE
    );
}

impl IntoIterator for Route {
    type Item = (Method, BoxHandler);

    type IntoIter = std::vec::IntoIter<(Method, BoxHandler)>;

    fn into_iter(self) -> Self::IntoIter {
        self.methods.into_iter()
    }
}

impl FromIterator<(Method, BoxHandler)> for Route {
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = (Method, BoxHandler)>,
    {
        Self {
            methods: iter.into_iter().collect(),
        }
    }
}

/// Appends a route, with a HTTP verb and handler.
pub fn on<H, O>(method: Method, handler: H) -> Route
where
    H: Handler<Request<Body>, Output = Result<O>> + Clone,
    O: IntoResponse + Send + Sync + 'static,
{
    Route::new().on(method, handler)
}

repeat!(
    export_verb
    get GET
    post POST
    put PUT
    delete DELETE
    head HEAD
    options OPTIONS
    connect CONNECT
    patch PATCH
    trace TRACE
);

/// Appends a route, with handler by any HTTP verbs.
pub fn any<H, O>(handler: H) -> Route
where
    H: Handler<Request<Body>, Output = Result<O>> + Clone,
    O: IntoResponse + Send + Sync + 'static,
{
    Route::new().any(handler)
}

#[cfg(feature = "ext")]
/// Appends a route, with a HTTP verb and multiple parameters of handler.
pub fn on_ext<H, O, I>(method: Method, handler: H) -> Route
where
    I: FromRequest + Send + Sync + 'static,
    I::Error: IntoResponse + Send + Sync,
    H: FnExt<I, Output = Result<O>>,
    O: IntoResponse + Send + Sync + 'static,
{
    Route::new().on_ext(method, handler)
}

#[cfg(feature = "ext")]
repeat!(
    export_verb_ext
    get_ext GET
    post_ext POST
    put_ext PUT
    delete_ext DELETE
    head_ext HEAD
    options_ext OPTIONS
    connect_ext CONNECT
    patch_ext PATCH
    trace_ext TRACE
);

/// Appends a route, with multiple parameters of handler by any HTTP verbs.
pub fn any_ext<H, O, I>(handler: H) -> Route
where
    I: FromRequest + Send + Sync + 'static,
    I::Error: IntoResponse + Send + Sync,
    H: FnExt<I, Output = Result<O>>,
    O: IntoResponse + Send + Sync + 'static,
{
    Route::new().any_ext(handler)
}

#[cfg(test)]
mod tests {
    use super::Route;
    use std::sync::Arc;
    use viz_core::{
        async_trait,
        handler::Transform,
        types::{self, Data, Query},
        Body, Handler, HandlerExt, IntoResponse, Method, Next, Request, Response, Result,
    };

    #[tokio::test]
    async fn route() -> anyhow::Result<()> {
        async fn handler(_: Request<Body>) -> Result<impl IntoResponse> {
            Ok(())
        }

        struct Logger;

        impl Logger {
            fn new() -> Self {
                Self
            }
        }

        impl<H: Clone> Transform<H> for Logger {
            type Output = LoggerHandler<H>;

            fn transform(&self, h: H) -> Self::Output {
                LoggerHandler(h.clone())
            }
        }

        #[derive(Clone)]
        struct LoggerHandler<H>(H);

        #[async_trait]
        impl<H> Handler<Request<Body>> for LoggerHandler<H>
        where
            H: Handler<Request<Body>> + Clone,
        {
            type Output = H::Output;

            async fn call(&self, req: Request<Body>) -> Self::Output {
                dbg!("before logger");
                let res = self.0.call(req).await;
                dbg!("after logger");
                res
            }
        }

        async fn before(req: Request<Body>) -> Result<Request<Body>> {
            dbg!("before req");
            Ok(req)
        }

        async fn after(res: Result<Response<Body>>) -> Result<Response<Body>> {
            dbg!("after res");
            res
        }

        async fn around<H, O>((req, handler): Next<Request<Body>, H>) -> Result<Response<Body>>
        where
            H: Handler<Request<Body>, Output = Result<O>> + Clone,
            O: IntoResponse + Send + Sync + 'static,
        {
            dbg!("around before");
            let res = handler.call(req).await.map(IntoResponse::into_response);
            dbg!("around after");
            res
        }

        async fn around_1<H, O>((req, handler): Next<Request<Body>, H>) -> Result<Response<Body>>
        where
            H: Handler<Request<Body>, Output = Result<O>> + Clone,
            O: IntoResponse + Send + Sync + 'static,
        {
            dbg!("around before --- 1");
            let res = handler.call(req).await.map(IntoResponse::into_response);
            dbg!("around after  --- 1");
            res
        }

        async fn around_2<H>((req, handler): Next<Request<Body>, H>) -> Result<Response<Body>>
        where
            H: Handler<Request<Body>, Output = Result<Response<Body>>> + Clone,
        {
            dbg!("around before ---> 2");
            let res = handler.call(req).await;
            dbg!("around after  <--- 2");
            res
        }

        #[derive(Clone)]
        struct Around2 {
            name: String,
        }

        #[async_trait]
        impl<H, I, O> Handler<Next<I, H>> for Around2
        where
            I: Send + 'static,
            H: Handler<I, Output = Result<O>> + Clone,
        {
            type Output = H::Output;

            async fn call(&self, (i, h): Next<I, H>) -> Self::Output {
                dbg!(format!("around before --- {}", &self.name));
                let res = h.call(i).await;
                dbg!(format!("around after  --- {}", &self.name));
                res
            }
        }

        #[derive(Clone)]
        struct Around3 {
            name: String,
        }

        #[async_trait]
        impl<H, O> Handler<Next<Request<Body>, H>> for Around3
        where
            H: Handler<Request<Body>, Output = Result<O>> + Clone,
            O: IntoResponse,
        {
            type Output = Result<Response<Body>>;

            async fn call(&self, (i, h): Next<Request<Body>, H>) -> Self::Output {
                dbg!(format!("around before --- {}", &self.name));
                let res = h.call(i).await.map(IntoResponse::into_response);
                dbg!(format!("around after  --- {}", &self.name));
                res
            }
        }

        #[derive(Clone)]
        struct Around4 {
            name: String,
        }

        #[async_trait]
        impl<H> Handler<Next<Request<Body>, H>> for Around4
        where
            H: Handler<Request<Body>, Output = Result<Response<Body>>> + Clone,
        {
            type Output = Result<Response<Body>>;

            async fn call(&self, (i, h): Next<Request<Body>, H>) -> Self::Output {
                dbg!(format!("around before ---> {}", &self.name));
                let res = h.call(i).await;
                dbg!(format!("around after  <--- {}", &self.name));
                res
            }
        }

        async fn ext(q: Query<usize>, d: Data<Arc<String>>) -> Result<impl IntoResponse> {
            dbg!(377);
            Ok(vec![233])
        }

        let route = Route::new()
            .any_ext(ext)
            .on(Method::GET, handler.before(before))
            .on(Method::POST, handler.after(after))
            .put(handler.around(Around2 {
                name: "handler around".to_string(),
            }))
            .with(Logger::new())
            .map_handler(|handler| {
                handler
                    .before(before)
                    .around(Around4 {
                        name: "4".to_string(),
                    })
                    .after(after)
                    .around(around_2)
                    .around(Around2 {
                        name: "2".to_string(),
                    })
                    .around(around)
                    .around(around_1)
                    .around(Around3 {
                        name: "3".to_string(),
                    })
                    .with(Logger::new())
                    .boxed()
            })
            .with_handler(around)
            .with_handler(around_1)
            .with_handler(around_2)
            .with_handler(Around2 {
                name: "2 with handler".to_string(),
            })
            .with_handler(Around3 {
                name: "3 with handler".to_string(),
            })
            .with_handler(Around4 {
                name: "4 with handler".to_string(),
            })
            // .with(viz_core::middleware::cookie::Config::new())
            .into_iter()
            .map(|(method, handler)| (method, handler))
            // .filter(|(method, _)| method != Method::GET)
            .collect::<Route>();

        dbg!(std::mem::size_of_val(&route));

        let (_, h) = route
            .methods
            .iter()
            .filter(|(m, _)| m == Method::GET)
            .nth(0)
            .unwrap();

        let res = match h.call(Request::default()).await {
            Ok(r) => r,
            Err(e) => e.into_response(),
        };

        dbg!(res);

        Ok(())
    }
}