yahf 0.0.2

Yet Another HTTP Framework focused on DX
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
707
708
709
710
711
712
//! Struct to setup and run the HTTP Server

use hyper_rustls::TlsAcceptor;

use std::{
    convert::Infallible,
    ops::{Deref, DerefMut},
    sync::Arc,
};

use tokio_rustls::rustls::ServerConfig;

use crate::{
    handler::Runner,
    middleware::{AfterMiddleware, PreMiddleware},
    request::{self, Request},
    response::Response,
    result::InternalResult,
    router::Router,
};

use futures::Future;
use http::StatusCode;
use hyper::{
    server::conn::{AddrIncoming, AddrStream},
    service::{make_service_fn, service_fn},
};

use request::Method;

/// Configuration and runtime for the HTTP Server
///
/// It's used to set define [`routes`](crate::handler::Runner), [`global middlewares`](crate::middleware) and [`start listening`](crate::server::Server::listen) for requests
///
/// An example of usage:
/// ```rust,no_run
/// use yahf::server::Server;
///
/// #[tokio::main]
/// async fn main() {
///     let server = Server::new().get(
///         "/",
///         || async { "Hello world".to_string() },
///         &(),
///         &String::with_capacity(0),
///     );
///
///     server
///         .listen(([127, 0, 0, 1], 8000).into())
///         .await
///         .unwrap();
/// }
/// ```
pub struct Server<PreM, AfterM> {
    router: Router<PreM, AfterM>,
}

impl<PreM, FutP, ResultP, AfterM, FutA, ResultA> Deref for Server<PreM, AfterM>
where
    PreM: PreMiddleware<FutCallResponse = FutP>,
    FutP: Future<Output = ResultP>,
    ResultP: Into<InternalResult<Request<String>>>,
    AfterM: AfterMiddleware<FutCallResponse = FutA>,
    FutA: Future<Output = ResultA>,
    ResultA: Into<InternalResult<Response<String>>>,
{
    type Target = Router<PreM, AfterM>;

    fn deref(&self) -> &Self::Target {
        &self.router
    }
}

impl<PreM, FutP, ResultP, AfterM, FutA, ResultA> DerefMut for Server<PreM, AfterM>
where
    PreM: PreMiddleware<FutCallResponse = FutP>,
    FutP: Future<Output = ResultP>,
    ResultP: Into<InternalResult<Request<String>>>,
    AfterM: AfterMiddleware<FutCallResponse = FutA>,
    FutA: Future<Output = ResultA>,
    ResultA: Into<InternalResult<Response<String>>>,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.router
    }
}

impl Server<(), ()> {
    /// Create a new [Server]
    pub fn new() -> Server<
        impl PreMiddleware<
            FutCallResponse = impl Future<Output = impl Into<InternalResult<Request<String>>>>,
        >,
        impl AfterMiddleware<
            FutCallResponse = impl Future<Output = impl Into<InternalResult<Response<String>>>>,
        >,
    > {
        Server {
            router: Router::new(),
        }
    }
}

macro_rules! method_reroute {
    ($method: ident, $method_ref: literal, $method_name: literal) => {
        #[doc = std::concat!("Bind a [`handler`](crate::handler::Runner) to a ",$method_ref, " and a `path`, with a")]
        /// [`Serializer`](crate::serializer::BodySerializer) and
        /// [`Deserializer`](crate::deserializer::BodyDeserializer)
        ///
        /// ```rust
        /// # use yahf::router::Router;
        /// # async fn some_handler(req: String) -> String { req }
        /// # type Computation = String;
        /// # let serializer = String::with_capacity(0);
        /// # let deserializer = String::with_capacity(0);
        /// # let router = Router::new();
        #[doc = std::concat!( "router.", $method_name, "(\"/desired/path\", some_handler, &deserializer, &serializer);")]
        /// ```
        pub fn $method<FnIn, FnOut, Deserializer, Serializer, R>(
            mut self,
            path: &'static str,
            handler: R,
            deserializer: &Deserializer,
            serializer: &Serializer,
        ) -> Self
        where
            R: 'static + Runner<(FnIn, Deserializer), (FnOut, Serializer)>,
            FnIn: 'static,
            FnOut: 'static,
            Deserializer: 'static,
            Serializer: 'static,
        {
            let router = self.router;
            let router = router.$method(path, handler, deserializer, serializer);
            self.router = router;
            self
        }
    };
}

impl<PreM, FutP, ResultP, AfterM, FutA, ResultA> Server<PreM, AfterM>
where
    PreM: PreMiddleware<FutCallResponse = FutP> + 'static,
    FutP: Future<Output = ResultP> + std::marker::Send + 'static,
    ResultP: Into<InternalResult<Request<String>>> + std::marker::Send + 'static,
    AfterM: AfterMiddleware<FutCallResponse = FutA> + 'static,
    FutA: Future<Output = ResultA> + std::marker::Send + 'static,
    ResultA: Into<InternalResult<Response<String>>> + std::marker::Send + 'static,
{
    method_reroute!(get, "[`GET Method`](crate::request::Method::GET)", "get");
    method_reroute!(put, "[`PUT Method`](crate::request::Method::PUT)", "put");
    method_reroute!(
        delete,
        "[`DELETE Method`](crate::request::Method::DELETE)",
        "delete"
    );
    method_reroute!(
        post,
        "[`POST Method`](crate::request::Method::POST)",
        "post"
    );
    method_reroute!(
        trace,
        "[`TRACE Method`](crate::request::Method::TRACE)",
        "trace"
    );
    method_reroute!(
        options,
        "[`OPTIONS Method`](crate::request::Method::OPTIONS)",
        "options"
    );
    method_reroute!(
        connect,
        "[`CONNECT Method`](crate::request::Method::CONNECT)",
        "connect"
    );
    method_reroute!(
        patch,
        "[`PATCH Method`](crate::request::Method::PATCH)",
        "patch"
    );
    method_reroute!(
        head,
        "[`HEAD Method`](crate::request::Method::HEAD)",
        "head"
    );
    method_reroute!(all, "[`HTTP method`](crate::request::Method)", "all");

    /// Bind a [`handler`](crate::handler::Runner) to a [`HTTP method`](crate::request::Method) and a `path`, with a
    /// [`Serializer`](crate::serializer::BodySerializer) and
    /// [`Deserializer`](crate::deserializer::BodyDeserializer)
    ///
    /// ```rust
    /// # use yahf::router::Router;
    /// # use yahf::request::Method;
    /// # async fn some_handler(req: String) -> String { req }
    /// # type Computation = String;
    /// # let serializer = String::with_capacity(0);
    /// # let deserializer = String::with_capacity(0);
    /// # let router = Router::new();
    /// router.method(Method::GET, "/desired/path", some_handler, &deserializer, &serializer);
    /// ```
    pub fn method<FnIn, FnOut, Deserializer, Serializer, R>(
        mut self,
        method: Method,
        path: &'static str,
        handler: R,
        deserializer: &Deserializer,
        serializer: &Serializer,
    ) -> Self
    where
        R: 'static + Runner<(FnIn, Deserializer), (FnOut, Serializer)>,
        FnIn: 'static,
        FnOut: 'static,
        Deserializer: 'static,
        Serializer: 'static,
    {
        let router = self.router;
        let router = router.method(method, path, handler, deserializer, serializer);
        self.router = router;
        self
    }

    /// Extend the [Server] with a [Router] and return the new [Server]
    ///
    /// A example:
    ///
    /// ```rust
    /// # use yahf::request::Request;
    /// # use yahf::router::Router;
    ///# use yahf::result::Result;
    ///# use serde::Deserialize;
    ///# use serde::Serialize;
    ///# use yahf::handler::Json;
    /// #
    /// # #[derive(Deserialize, Serialize)]
    /// # struct Computation { value: u64 }
    /// #
    /// async fn logger(req: Result<Request<String>>) -> Result<Request<String>>
    /// # { req }
    /// #
    /// async fn some_computation(req: Computation) -> Computation
    /// # {req}
    /// #
    /// // Define `Server` with a Logger `PreMiddleware`
    /// let server = Router::new().pre(logger);
    /// // Define `Router` with a router to "/desired/path"
    /// let router = Router::new().get("/desired/path", some_computation, &Json::default(), &Json::default());
    ///
    /// // A server with all routes of the Server plus all routes of B with logger applied to.
    /// // This also concatenate the server's middlewares with router's middleware, so any new
    /// // Route will have both middlewares
    /// let server_final = server.router(router);
    /// ```
    ///
    /// By extending server with router, we're basically applying the middlewares of the server to
    /// routes of the middleware, adding Router routes to the Server and then concatenating Server's middlewares with Router's middlewares
    pub fn router<OtherPreM, OtherAfterM, OtherFutA, OtherFutP, OtherResultP, OtherResultA>(
        self,
        router: Router<OtherPreM, OtherAfterM>,
    ) -> Self
    where
        OtherPreM: PreMiddleware<FutCallResponse = OtherFutP> + 'static,
        OtherAfterM: AfterMiddleware<FutCallResponse = OtherFutA> + 'static,
        OtherFutP: Future<Output = OtherResultP> + Send,
        OtherFutA: Future<Output = OtherResultA> + Send,
        OtherResultP: Into<InternalResult<Request<String>>> + Send,
        OtherResultA: Into<InternalResult<Response<String>>> + Send,
    {
        let new_router = self.router.router(router);
        Self { router: new_router }
    }

    /// Append a [`PreMiddleware`] on the
    /// [`PreMiddleware`] and return the [Server]
    pub fn pre<NewPreM, NewFut, NewResultP>(
        self,
        middleware: NewPreM,
    ) -> Server<impl PreMiddleware<FutCallResponse = impl Future<Output = NewResultP>>, AfterM>
    where
        NewPreM: PreMiddleware<FutCallResponse = NewFut>,
        NewFut: Future<Output = NewResultP>,
        NewResultP: Into<InternalResult<Request<String>>>,
    {
        let new_router = self.router.pre(middleware);

        Server { router: new_router }
    }

    /// Append a [`AfterMiddleware`] on the
    /// [`AfterMiddleware`] and return the [Server]
    pub fn after<NewAfterM, NewFut, NewResultA>(
        self,
        middleware: NewAfterM,
    ) -> Server<PreM, impl AfterMiddleware<FutCallResponse = impl Future<Output = NewResultA>>>
    where
        NewAfterM: AfterMiddleware<FutCallResponse = NewFut>,
        NewFut: Future<Output = NewResultA>,
        NewResultA: Into<InternalResult<Response<String>>>,
    {
        let new_router = self.router.after(middleware);

        Server { router: new_router }
    }

    /// Start listening for [Requests](crate::request::Request) on the
    /// [address](std::net::SocketAddr)
    pub async fn listen(self, addr: std::net::SocketAddr) -> Result<(), hyper::Error> {
        let server = Arc::new(self);
        let make_svc = make_service_fn(move |_: &AddrStream| {
            let server = server.clone();
            let service = service_fn(move |req| handle_req(server.clone(), req));
            async move { Ok::<_, Infallible>(service) }
        });

        let server = hyper::Server::bind(&addr).serve(make_svc);
        server.await?;
        Ok(())
    }

    /// Start securely listening for [Requests](crate::request::Request) on the
    /// [address](std::net::SocketAddr) using the [rustls
    /// config](tokio_rustls::rustls::ServerConfig)
    ///
    /// [A example]( https://github.com/lucasduartesobreira/yahf/tree/main/examples/tls )
    pub async fn listen_rustls(
        self,
        config: ServerConfig,
        addr: std::net::SocketAddr,
    ) -> Result<(), hyper::Error> {
        let server = Arc::new(self);
        let make_svc = make_service_fn(move |_| {
            let server = server.clone();
            let service = service_fn(move |req| handle_req(server.clone(), req));
            async move { Ok::<_, Infallible>(service) }
        });
        let addr_inc = AddrIncoming::bind(&addr).unwrap();

        let listener = TlsAcceptor::builder()
            .with_tls_config(config)
            .with_all_versions_alpn()
            .with_incoming(addr_inc);

        let server = hyper::Server::builder(listener).serve(make_svc);
        server.await?;
        Ok(())
    }
}

async fn handle_req<PreM, FutP, ResultP, AfterM, FutA, ResultA>(
    server: Arc<Server<PreM, AfterM>>,
    req: hyper::Request<hyper::Body>,
) -> Result<hyper::Response<hyper::Body>, Box<dyn std::error::Error + Send + Sync>>
where
    PreM: PreMiddleware<FutCallResponse = FutP> + 'static,
    FutP: Future<Output = ResultP> + std::marker::Send + 'static,
    ResultP: Into<InternalResult<Request<String>>> + std::marker::Send + 'static,
    AfterM: AfterMiddleware<FutCallResponse = FutA> + 'static,
    FutA: Future<Output = ResultA> + std::marker::Send + 'static,
    ResultA: Into<InternalResult<Response<String>>> + std::marker::Send + 'static,
{
    let handler = server.find_route(req.method(), req.uri().path());

    let handler = match handler {
        Some(handler) => handler,
        None => {
            return Ok(hyper::Response::builder()
                .status(StatusCode::NOT_FOUND)
                .body(hyper::Body::empty())
                .unwrap());
        }
    };

    let (parts, body) = req.into_parts();
    let str = String::from_utf8(
        hyper::body::to_bytes(body)
            .await?
            .to_vec(),
    )?;
    let req_new = hyper::Request::from_parts(parts, str);

    let (parts, body) = handler
        .call(Ok(Request::from(req_new)))
        .await
        .map_or_else(|err| err.into(), |res| res)
        .into_inner()
        .into_parts();

    let body = hyper::Body::from(body);

    Ok(hyper::Response::from_parts(parts, body))
}

#[cfg(test)]
mod test {

    use std::net::SocketAddr;

    use futures::Future;
    use hyper::{Body, Client};

    use crate::{
        error::Error,
        middleware::{AfterMiddleware, PreMiddleware},
        request::{Method, Request},
        response::Response,
        result::InternalResult,
        server::Server,
    };

    struct TestReq {
        req: hyper::Request<hyper::Body>,
        res: hyper::Response<&'static str>,
    }

    async fn run_req<PreM, FutP, ResultP, AfterM, FutA, ResultA>(
        server: Server<PreM, AfterM>,
        addr: SocketAddr,
        test_req: TestReq,
    ) -> Result<(), hyper::Error>
    where
        PreM: PreMiddleware<FutCallResponse = FutP> + 'static,
        FutP: Future<Output = ResultP> + std::marker::Send + 'static,
        ResultP: Into<InternalResult<Request<String>>> + std::marker::Send + 'static,
        AfterM: AfterMiddleware<FutCallResponse = FutA> + 'static,
        FutA: Future<Output = ResultA> + std::marker::Send + 'static,
        ResultA: Into<InternalResult<Response<String>>> + std::marker::Send + 'static,
    {
        tokio::spawn(server.listen(addr));

        let TestReq {
            mut req,
            res: expected_res,
        } = test_req;

        *req.uri_mut() = format!("http://localhost:{}/", addr.port())
            .parse()
            .unwrap();

        let client = Client::new();
        let response = client.request(req).await?;

        assert!(response.status() == expected_res.status());

        let body_str = String::from_utf8(
            hyper::body::to_bytes(response.into_body())
                .await
                .unwrap()
                .to_vec(),
        )
        .unwrap();

        assert!(body_str.as_str() == expected_res.into_body());

        Ok(())
    }

    macro_rules! test_with_server {
        ($name: ident, $server: expr, $ip: literal, $req: expr, $res: expr) => {
            #[tokio::test]
            async fn $name() {
                let server = $server;
                let response = run_req(
                    server,
                    $ip.parse().unwrap(),
                    TestReq {
                        req: $req,
                        res: $res,
                    },
                )
                .await;

                assert!(response.is_ok(), "{:?}", response);
            }
        };
    }

    macro_rules! test_server_method {
        ($name: ident, $method: ident, $req: expr, $ip: literal) => {
            #[tokio::test]
            async fn $name() {
                let server = Server::new().$method(
                    "/",
                    || async { String::from("Hello world!") },
                    &(),
                    &String::with_capacity(0),
                );
                let response = run_req(
                    server,
                    $ip.parse().unwrap(),
                    TestReq {
                        req: $req,
                        res: hyper::Response::new("Hello world!"),
                    },
                )
                .await;

                assert!(response.is_ok(), "{:?}", response);
            }
        };
    }

    test_server_method!(
        test_server_get,
        get,
        hyper::Request::builder()
            .method(Method::GET)
            .body(Body::from(""))
            .unwrap(),
        "127.0.0.1:8000"
    );
    test_server_method!(
        test_server_post,
        post,
        hyper::Request::builder()
            .method(Method::POST)
            .body(Body::from(""))
            .unwrap(),
        "127.0.0.1:8001"
    );
    test_server_method!(
        test_server_put,
        put,
        hyper::Request::builder()
            .method(Method::PUT)
            .body(Body::from(""))
            .unwrap(),
        "127.0.0.1:8002"
    );
    test_server_method!(
        test_server_delete,
        delete,
        hyper::Request::builder()
            .method(Method::DELETE)
            .body(Body::from(""))
            .unwrap(),
        "127.0.0.1:8003"
    );
    test_server_method!(
        test_server_patch,
        patch,
        hyper::Request::builder()
            .method(Method::PATCH)
            .body(Body::from(""))
            .unwrap(),
        "127.0.0.1:8004"
    );

    #[tokio::test]
    async fn test_server_head() {
        let server = Server::new().head(
            "/",
            || async { String::from("Hello world!") },
            &(),
            &String::with_capacity(0),
        );
        let response = run_req(
            server,
            "127.0.0.1:8005"
                .parse()
                .unwrap(),
            TestReq {
                req: hyper::Request::builder()
                    .method(Method::HEAD)
                    .body(Body::from(""))
                    .unwrap(),
                res: hyper::Response::new(""),
            },
        )
        .await;

        assert!(response.is_ok(), "{:?}", response);
    }
    test_server_method!(
        test_server_options,
        options,
        hyper::Request::builder()
            .method(Method::OPTIONS)
            .body(Body::from(""))
            .unwrap(),
        "127.0.0.1:8006"
    );
    test_server_method!(
        test_server_trace,
        trace,
        hyper::Request::builder()
            .method(Method::TRACE)
            .body(Body::from(""))
            .unwrap(),
        "127.0.0.1:8007"
    );
    test_server_method!(
        test_server_all,
        all,
        hyper::Request::builder()
            .method(Method::GET)
            .body(Body::from(""))
            .unwrap(),
        "127.0.0.1:8008"
    );
    test_with_server!(
        test_pre_error,
        Server::new()
            .pre(|_| async {
                crate::result::Result::from(Err(Error::new("PreMiddleware error".into(), 422)))
            })
            .get(
                "/",
                || async { "Hello world".to_owned() },
                &(),
                &String::with_capacity(0)
            ),
        "127.0.0.1:8009",
        hyper::Request::builder()
            .method(Method::GET)
            .body(Body::from(""))
            .unwrap(),
        hyper::Response::builder()
            .status(422)
            .body("PreMiddleware error")
            .unwrap()
    );

    test_with_server!(
        test_pre_error_handled,
        Server::new()
            .pre(|_| async {
                crate::result::Result::from(Err(Error::new("PreMiddleware error".into(), 422)))
            })
            .pre(|req: crate::result::Result<Request<String>>| async {
                crate::result::Result::from(req.into_inner().map_or_else(
                    |_| {
                        Ok(crate::request::Request::new(String::from(
                            "PreMiddleware fixed error",
                        )))
                    },
                    Ok,
                ))
            })
            .get(
                "/",
                || async { "Hello world".to_owned() },
                &(),
                &String::with_capacity(0)
            ),
        "127.0.0.1:8010",
        hyper::Request::builder()
            .method(Method::GET)
            .body(Body::from(""))
            .unwrap(),
        hyper::Response::builder()
            .status(200)
            .body("Hello world")
            .unwrap()
    );

    test_with_server!(
        test_after_error,
        Server::new()
            .after(|_| async {
                crate::result::Result::from(Err(Error::new("AfterMiddleware error".into(), 422)))
            })
            .get(
                "/",
                || async { "Hello world".to_owned() },
                &(),
                &String::with_capacity(0)
            ),
        "127.0.0.1:8011",
        hyper::Request::builder()
            .method(Method::GET)
            .body(Body::from(""))
            .unwrap(),
        hyper::Response::builder()
            .status(422)
            .body("AfterMiddleware error")
            .unwrap()
    );

    test_with_server!(
        test_after_error_handled,
        Server::new()
            .after(|_| async {
                crate::result::Result::from(Err(Error::new("AfterMiddleware error".into(), 422)))
            })
            .after(|res: crate::result::Result<Response<String>>| async {
                crate::result::Result::from(res.into_inner().map_or_else(
                    |_| {
                        Ok(crate::response::Response::new(
                            "AfterMiddleware Handled Error".to_owned(),
                        ))
                    },
                    Ok,
                ))
            })
            .get(
                "/",
                || async { "Hello world".to_owned() },
                &(),
                &String::with_capacity(0)
            ),
        "127.0.0.1:8012",
        hyper::Request::builder()
            .method(Method::GET)
            .body(Body::from(""))
            .unwrap(),
        hyper::Response::builder()
            .status(200)
            .body("AfterMiddleware Handled Error")
            .unwrap()
    );
}