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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
//! Composable (a)synchronous HTTP request routing, guarding and decoding.
//!
//! This crate provides [Rocket]-inspired HTTP route definitions based on
//! attributes (`#[get("/user/{id}")]`). It is based on the [`hyper`]
//! and [`http`] crates, works on **stable Rust**, and supports writing both
//! synchronous and asynchronous (via [futures 0.1]) apps.
//!
//! Check out the examples below for a small taste of how this library can be
//! used. If you want to dive in deeper, you can check out the [`FromRequest`]
//! trait, which provides the custom derive that powers most of the magic in
//! this crate.
//!
//! [Rocket]: https://rocket.rs/
//! [`hyper`]: https://hyper.rs/
//! [`http`]: https://docs.rs/http
//! [futures 0.1]: https://docs.rs/futures/0.1
//! [`FromRequest`]: trait.FromRequest.html
//!
//! # Examples
//!
//! Use the hyper service adapter [`AsyncService`] to create your async
//! server without much boilerplate:
//!
//! ```
//! use hyper::{Server, Response, Body};
//! use hyperdrive::{service::AsyncService, FromRequest};
//! use futures::IntoFuture;
//!
//! #[derive(FromRequest)]
//! enum Route {
//!     #[get("/")]
//!     Index,
//!
//!     #[get("/users/{id}")]
//!     UserInfo { id: u32 },
//! }
//!
//! let srv = Server::bind(&"127.0.0.1:0".parse().unwrap())
//!     .serve(AsyncService::new(|route: Route, _| {
//!         match route {
//!             Route::Index => {
//!                 Ok(Response::new(Body::from("Hello World!"))).into_future()
//!             }
//!             Route::UserInfo { id } => {
//!                 // You could do an async database query to fetch the user data here
//!                 Ok(Response::new(Body::from(format!("User #{}", id)))).into_future()
//!             }
//!         }
//!     }));
//! ```
//!
//! If your app doesn't need to be asynchronous and you'd prefer to write sync
//! code, you can do that by using [`SyncService`]:
//!
//! ```
//! use hyper::{Server, Response, Body};
//! use hyperdrive::{service::SyncService, FromRequest};
//!
//! #[derive(FromRequest)]
//! enum Route {
//!     #[get("/")]
//!     Index,
//!
//!     #[get("/users/{id}")]
//!     UserInfo { id: u32 },
//! }
//!
//! let srv = Server::bind(&"127.0.0.1:0".parse().unwrap())
//!     .serve(SyncService::new(|route: Route, _| {
//!         // This closure can block freely, and has to return a `Response<Body>`
//!         match route {
//!             Route::Index => {
//!                 Response::new(Body::from("Hello World!"))
//!             },
//!             Route::UserInfo { id } => {
//!                 Response::new(Body::from(format!("User #{}", id)))
//!             }
//!         }
//!     }));
//! ```
//!
//! If the provided service adapters aren't sufficient for your use case, you
//! can always manually use the [`FromRequest`] methods, and hook it up to your
//! hyper `Service` manually:
//!
//! ```
//! use hyper::{Request, Response, Body, Method, service::Service};
//! use futures::Future;
//! use hyperdrive::{FromRequest, DefaultFuture, BoxedError, NoContext};
//!
//! #[derive(FromRequest)]
//! enum Route {
//!     #[get("/")]
//!     Index,
//!
//!     #[get("/users/{id}")]
//!     UserInfo { id: u32 },
//! }
//!
//! // Define your hyper `Service`:
//! struct MyService;
//!
//! impl Service for MyService {
//!     type ReqBody = Body;
//!     type ResBody = Body;
//!     type Error = BoxedError;
//!     type Future = DefaultFuture<Response<Body>, BoxedError>;
//!
//!     fn call(&mut self, req: Request<Body>) -> Self::Future {
//!         let is_head = req.method() == Method::HEAD;
//!         let future = Route::from_request(req, NoContext).and_then(|route| Ok(match route {
//!             Route::Index => {
//!                 Response::new(Body::from("Hello world!"))
//!             }
//!             Route::UserInfo { id } => {
//!                 Response::new(Body::from(format!("User #{} is secret!", id)))
//!             }
//!         })).map(move |resp| {
//!             if is_head {
//!                 // Response to HEAD requests must have an empty body
//!                 resp.map(|_| Body::empty())
//!             } else {
//!                 resp
//!             }
//!         });
//!
//!         Box::new(future)
//!     }
//! }
//! ```
//!
//! For detailed documentation on the custom derive syntax, refer to the docs of
//! [`FromRequest`].
//!
//! [`AsyncService`]: service/struct.AsyncService.html
//! [`SyncService`]: service/struct.SyncService.html
//! [`FromRequest`]: trait.FromRequest.html

/*

TODO:
* How to handle 2015/2018 compat with the proc-macro?
* Good example that fetches a session from a DB

*/
// Deny certain warnings inside doc tests / examples. When this isn't present, rustdoc doesn't show
// *any* warnings at all.
#![doc(test(attr(deny(unused_imports, unused_must_use))))]
#![doc(html_root_url = "https://docs.rs/hyperdrive/0.2.0")]
#![warn(missing_debug_implementations)]
#![warn(missing_docs)]
#![warn(rust_2018_idioms)]

pub mod body;
mod error;
mod readme;
pub mod service;

pub use error::*;
pub use hyperderive::*;

// Reexport public deps for use by the custom derive
pub use {futures, http, hyper, serde};

// These are hidden because the user never actually interacts with them. They're
// only used by the generated code internally.
#[doc(hidden)]
pub use {lazy_static::lazy_static, regex};

use futures::{Future, IntoFuture};
use std::sync::Arc;
use tokio::runtime::current_thread::Runtime;

/// A default boxed future that may be returned from [`FromRequest`],
/// [`FromBody`] and [`Guard`] implementations.
///
/// The future is required to be `Send` to allow running it on a multi-threaded
/// executor.
///
/// [`FromRequest`]: trait.FromRequest.html
/// [`FromBody`]: trait.FromBody.html
/// [`Guard`]: trait.Guard.html
pub type DefaultFuture<T, E> = Box<dyn Future<Item = T, Error = E> + Send>;

/// A boxed `std::error::Error` that can be used when the actual error type is
/// unknown.
pub type BoxedError = Box<dyn std::error::Error + Send + Sync>;

/// Trait for asynchronous conversion from HTTP requests.
///
/// # `#[derive(FromRequest)]`
///
/// This trait can be derived for enums to generate a request router and
/// decoder. Here's a simple example:
///
/// ```
/// use hyperdrive::{FromRequest, body::Json};
/// # use serde::Deserialize;
///
/// #[derive(FromRequest)]
/// enum Routes {
///     #[get("/")]
///     Index,
///
///     #[get("/users/{id}")]
///     User { id: u32 },
///
///     #[post("/login")]
///     Login {
///         #[body]
///         data: Json<Login>,
///     },
/// }
///
/// #[derive(Deserialize)]
/// struct Login {
///     email: String,
///     password: String,
/// }
/// ```
///
/// Calling `Routes::from_request` will result in `Routes::Index` for a `GET /`
/// request, and in `Routes::User` for a `GET /users/123` request, for example.
/// A `POST /login` request will end up as `Routes::Login`, decoding the POSTed
/// JSON body.
///
/// The generated `FromRequest` implementation will always use
/// [`DefaultFuture<Self, BoxedError>`][`DefaultFuture`] as the associated
/// `Result` type.
///
/// Note that the generated implementation will make use of `.and_then()` to
/// chain asynchronous operations instead of running them in parallel using
/// `join_all`. This is because it simplifies the code and doesn't require
/// making use of boxed futures everywhere in the generated code. Multiple
/// requests will still be handled in parallel, so this should not negatively
/// affect performance.
///
/// In order to keep the implementation simple and user code more easily
/// understandable, overlapping paths are not allowed (unless the paths are
/// *exactly* the same, and the method differs), so the following will fail to
/// compile:
///
/// ```compile_fail
/// use from_request::{FromRequest, body::Json};
/// # use serde::Deserialize;
///
/// #[derive(FromRequest)]  //~ ERROR: route `#[get("/users/me")]` overlaps with ...
/// enum Routes {
///     #[get("/users/{id}")]
///     User { id: u32 },
///
///     #[get("/users/me")]
///     Me,
/// }
/// ```
///
/// To fix this, you can define a custom type implementing `FromStr` and use
/// that:
///
/// ```
/// use hyperdrive::FromRequest;
/// # use std::str::FromStr;
/// # use std::num::ParseIntError;
///
/// #[derive(FromRequest)]
/// enum Routes {
///     #[get("/users/{id}")]
///     User { id: UserId },
/// }
///
/// enum UserId {
///     /// User by database ID.
///     Id(u32),
///     /// The currently logged-in user.
///     Me,
/// }
///
/// impl FromStr for UserId {
///     type Err = ParseIntError;
///
///     fn from_str(s: &str) -> Result<Self, Self::Err> {
///         if s == "me" {
///             Ok(UserId::Me)
///         } else {
///             Ok(UserId::Id(s.parse()?))
///         }
///     }
/// }
/// ```
///
/// ## Implicit `HEAD` routes
///
/// The custom derive will create a `HEAD` route for every defined `GET` route,
/// unless you define one yourself. If your app uses [`AsyncService`] or
/// [`SyncService`], those adapters will automatically take care of dropping the
/// body from the response to `HEAD` requests. If you manually call
/// [`FromRequest::from_request`][`from_request`], you have to make sure no body
/// is sent back for `HEAD` requests.
///
/// ## Extracting Request Data
///
/// The custom derive provides easy access to various kinds of data encoded in a
/// request:
///
/// * The Request path (`/users/or/other/stuff`)
/// * Query parameters (`?name=val`)
/// * The request body
///
/// ### Extracting Path Segments (`{field}` syntax)
///
/// In a route attribute, the `{field}` placeholder syntax will match a path
/// segment and convert it to the type of the named field using `FromStr`:
///
/// ```notrust
/// #[get("/users/{id}")]
/// ```
///
/// To extract multiple path segments this way, the `{field...}` syntax can be
/// used at the end of the path, which will consume the rest of the path:
///
/// ```notrust
/// #[get("/static/{path...}")]
/// ```
///
/// If the `FromStr` conversion fails, the generated `FromRequest`
/// implementation will bail out with an error (in other words, this feature
/// cannot be used to try multiple routes in sequence until one matches).
///
/// ### Extracting the request body (`#[body]` attribute)
///
/// Putting `#[body]` on a field of a variant will deserialize the request body
/// using the [`FromBody`] trait and store the result in the annotated field:
///
/// ```notrust
/// #[post("/login")]
/// Login {
///     #[body]
///     data: Json<Login>,
/// },
/// ```
///
/// The type of the field must implement [`FromBody`]. The [`body`] module
/// contains predefined adapters implementing that trait, which work with any
/// type implementing `Deserialize`.
///
/// ### Extracting query parameters (`#[query_params]` attribute)
///
/// The route attribute cannot match or extract query parameters (`?name=val`).
/// Instead, query parameters can be extracted by marking a field in the struct
/// with the `#[query_params]` attribute:
///
/// ```
/// use hyperdrive::FromRequest;
/// # use serde::Deserialize;
///
/// #[derive(FromRequest)]
/// enum Routes {
///     #[get("/users")]
///     UserList {
///         #[query_params]
///         pagination: Option<Pagination>,
///     },
/// }
///
/// #[derive(Deserialize)]
/// struct Pagination {
///     start_id: u32,
///     count: u32,
/// }
/// ```
///
/// A request like `GET /users?start_id=42&count=10` would thus end up with a
/// corresponding `Pagination` object, while `GET /users` would store `None` in
/// the `pagination` field.
///
/// The type of the `#[query_params]` field must implement serde's `Deserialize`
/// trait and the conversion will be performed using the `serde_urlencoded`
/// crate.
///
/// ## Guards
///
/// Guards can be used to prevent a route from being called when a condition is
/// not fulfilled (for example, when the user isn't logged in). They can also
/// extract arbitrary data from the request headers (eg. a session ID, or the
/// User-Agent string).
///
/// All fields that are neither mentioned in the route path nor annotated with
/// an attribute are considered guards and thus must implement the [`Guard`]
/// trait.
///
/// ```
/// use hyperdrive::{FromRequest, Guard};
/// # use hyperdrive::{BoxedError, NoContext};
/// # use std::sync::Arc;
///
/// struct User {
///     id: u32,
///     // ...
/// }
///
/// impl Guard for User {
///     // (omitted for brevity)
/// #     type Context = NoContext;
/// #     type Result = Result<Self, BoxedError>;
/// #     fn from_request(_: &Arc<http::Request<()>>, _: &NoContext) -> Result<Self, BoxedError> {
/// #         User { id: 0 }.id;
/// #         Ok(User { id: 0 })
/// #     }
/// }
///
/// #[derive(FromRequest)]
/// enum Route {
///     #[get("/login")]
///     LoginForm,
///
///     #[get("/staff")]
///     Staff {
///         // Require a logged-in user to make this request
///         user: User,
///     },
/// }
/// ```
///
/// ## Forwarding
///
/// A field whose type implements `FromRequest` can be marked with `#[forward]`.
/// The library will then generate code that invokes this nested `FromRequest`
/// implementation.
///
/// This feature can not be combined with `#[body]` inside the same variant,
/// since both consume the request body.
///
/// Currently, this is limited to `FromRequest` implementations that use the
/// same [`RequestContext`] as the outer type (ie. no automatic `AsRef`
/// conversion will take place).
///
/// A variant or struct defining a `#[forward]` field does not have to define
/// a route. If no other route matches, this variant will automatically be
/// created, and is considered a *fallback route*.
///
/// Combined with generics, this feature can be used to make request wrappers
/// that attach a guard or a guard group to any type implementing `FromRequest`:
///
/// ```
/// use hyperdrive::{FromRequest, Guard};
/// # use hyperdrive::{NoContext, BoxedError};
/// # use std::sync::Arc;
///
/// struct User;
/// impl Guard for User {
///     // (omitted for brevity)
/// #     type Context = NoContext;
/// #     type Result = Result<Self, BoxedError>;
/// #     fn from_request(_: &Arc<http::Request<()>>, _: &NoContext) -> Result<Self, BoxedError> {
/// #         Ok(User)
/// #     }
/// }
///
/// #[derive(FromRequest)]
/// struct Authenticated<T> {
///     user: User,
///
///     #[forward]
///     inner: T,
/// }
/// ```
///
/// ## Changing the `Context` type
///
/// By default, the generated code will use [`NoContext`] as the associated
/// `Context` type. You can change this to any other type that implements
/// [`RequestContext`] by putting a `#[context(MyContext)]` attribute on the
/// type:
///
/// ```
/// # struct MyDatabaseConnection;
/// use hyperdrive::{FromRequest, RequestContext};
///
/// #[derive(RequestContext)]
/// struct MyContext {
///     db: MyDatabaseConnection,
/// }
///
/// #[derive(FromRequest)]
/// #[context(MyContext)]
/// enum Routes {
///     #[get("/users")]
///     UserList,
/// }
/// ```
///
/// For more info on this, refer to the [`RequestContext`] trait.
///
/// [`AsyncService`]: service/struct.AsyncService.html
/// [`SyncService`]: service/struct.SyncService.html
/// [`FromBody`]: trait.FromBody.html
/// [`RequestContext`]: trait.RequestContext.html
/// [`Guard`]: trait.Guard.html
/// [`NoContext`]: struct.NoContext.html
/// [`DefaultFuture`]: type.DefaultFuture.html
/// [`body`]: body/index.html
/// [`from_request`]: #tymethod.from_request
pub trait FromRequest: Sized {
    /// A context parameter passed to [`from_request`].
    ///
    /// This can be used to pass application-specific data like a logger or a
    /// database connection around.
    ///
    /// If no context is needed, this should be set to [`NoContext`], which is a
    /// context type that can be obtained from any [`RequestContext`] via
    /// `AsRef`.
    ///
    /// [`from_request`]: #tymethod.from_request
    /// [`NoContext`]: struct.NoContext.html
    /// [`RequestContext`]: trait.RequestContext.html
    type Context: RequestContext;

    /// The future returned by [`from_request`].
    ///
    /// Because `impl Trait` cannot be used inside traits (and named
    /// existential types aren't yet stable), the type here might not be
    /// nameable. In that case, you can set it to
    /// [`DefaultFuture<Self, BoxedError>`][`DefaultFuture`] and box the
    /// returned future.
    ///
    /// [`DefaultFuture`]: type.DefaultFuture.html
    /// [`from_request`]: #tymethod.from_request
    type Future: Future<Item = Self, Error = BoxedError> + Send;

    /// Creates a `Self` from an HTTP request, asynchronously.
    ///
    /// This takes the request metadata, body, and a user-defined context. Only
    /// the body is consumed.
    ///
    /// Implementations of this function must not block, since this function is
    /// always run on a futures executor. If you need to perform blocking I/O or
    /// long-running computations, you can call [`tokio_threadpool::blocking`].
    ///
    /// # Parameters
    ///
    /// * **`request`**: HTTP request data (headers, path, method, etc.).
    /// * **`body`**: The streamed HTTP body.
    /// * **`context`**: The user-defined context.
    ///
    /// [`tokio_threadpool::blocking`]: ../tokio_threadpool/fn.blocking.html
    fn from_request_and_body(
        request: &Arc<http::Request<()>>,
        body: hyper::Body,
        context: Self::Context,
    ) -> Self::Future;

    /// Create a `Self` from an HTTP request, asynchronously.
    ///
    /// This consumes the request *and* the context.
    ///
    /// Implementations of this function must not block, since this function is
    /// always run on a futures executor. If you need to perform blocking I/O or
    /// long-running computations, you can call [`tokio_threadpool::blocking`].
    ///
    /// A blocking wrapper around this method is provided by
    /// [`from_request_sync`].
    ///
    /// # Parameters
    ///
    /// * **`request`**: An HTTP request from the `http` crate, containing a
    ///   `hyper::Body`.
    /// * **`context`**: User-defined context.
    ///
    /// [`from_request_sync`]: #method.from_request_sync
    /// [`tokio_threadpool::blocking`]: ../tokio_threadpool/fn.blocking.html
    fn from_request(request: http::Request<hyper::Body>, context: Self::Context) -> Self::Future {
        let (parts, body) = request.into_parts();
        let request = Arc::new(http::Request::from_parts(parts, ()));

        Self::from_request_and_body(&request, body, context)
    }

    /// Create a `Self` from an HTTP request, synchronously.
    ///
    /// This is a blocking version of [`from_request`]. The provided default
    /// implementation will internally create a single-threaded tokio runtime to
    /// perform the conversion and receive the request body.
    ///
    /// Note that this does not provide a way to *write* a blocking version of
    /// [`from_request`]. Implementors of this trait must always implement
    /// [`from_request`] in a non-blocking fashion, even if they *also*
    /// implement this method.
    ///
    /// [`from_request`]: #tymethod.from_request
    fn from_request_sync(
        request: http::Request<hyper::Body>,
        context: Self::Context,
    ) -> Result<Self, BoxedError> {
        let mut rt = Runtime::new().expect("couldn't start single-threaded tokio runtime");
        rt.block_on(Self::from_request(request, context).into_future())
    }
}

/// A request guard that checks a condition or extracts data out of an incoming
/// request.
///
/// For example, this could be used to extract an `Authorization` header and
/// verify user credentials, or to look up a session token in a database.
///
/// A `Guard` can not access the request body. If you need to do that, implement
/// [`FromBody`] instead.
///
/// # Examples
///
/// Define a guard that ensures that required request headers are present:
///
/// ```
/// # use hyperdrive::{Guard, NoContext, BoxedError};
/// # use std::sync::Arc;
/// struct MustFrobnicate;
///
/// impl Guard for MustFrobnicate {
///     type Context = NoContext;
///     type Result = Result<Self, BoxedError>;
///
///     fn from_request(request: &Arc<http::Request<()>>, context: &Self::Context) -> Self::Result {
///         if request.headers().contains_key("X-Frobnicate") {
///             Ok(MustFrobnicate)
///         } else {
///             let msg = "request did not contain mandatory `X-Frobnicate` header";
///             Err(String::from(msg).into())
///         }
///     }
/// }
/// ```
///
/// Use server settings stored in a [`RequestContext`] to exclude certain user
/// agents:
///
/// ```
/// # use hyperdrive::{Guard, RequestContext, BoxedError};
/// # use std::sync::Arc;
/// #[derive(RequestContext)]
/// struct ForbiddenAgents {
///     agents: Vec<String>,
/// }
///
/// struct RejectForbiddenAgents;
///
/// impl Guard for RejectForbiddenAgents {
///     type Context = ForbiddenAgents;
///     type Result = Result<Self, BoxedError>;
///
///     fn from_request(request: &Arc<http::Request<()>>, context: &Self::Context) -> Self::Result {
///         let agent = request.headers().get("User-Agent")
///             .ok_or_else(|| String::from("No User-Agent header"))?;
///
///         if context.agents.iter().any(|f| f == agent) {
///             Err(String::from("This User-Agent is forbidden!").into())
///         } else {
///             Ok(RejectForbiddenAgents)
///         }
///     }
/// }
/// ```
///
/// [`FromBody`]: trait.FromBody.html
/// [`RequestContext`]: trait.RequestContext.html
pub trait Guard: Sized {
    /// A context parameter passed to [`Guard::from_request`].
    ///
    /// This can be used to pass application-specific data like a database
    /// connection or server configuration (eg. for limiting the maximum HTTP
    /// request size) around.
    ///
    /// If no context is needed, this should be set to [`NoContext`].
    ///
    /// [`Guard::from_request`]: #tymethod.from_request
    /// [`NoContext`]: struct.NoContext.html
    type Context: RequestContext;

    /// The result returned by [`Guard::from_request`].
    ///
    /// Because `impl Trait` cannot be used inside traits (and named
    /// existential types aren't stable), the type here might not be
    /// nameable. In that case, you can set it to
    /// [`DefaultFuture<Self, Error>`][`DefaultFuture`] and box the returned
    /// future.
    ///
    /// If your guard doesn't need to return a future (eg. because it's just a
    /// parsing step), you can set this to `Result<Self, BoxedError>` and
    /// immediately return the result of the conversion.
    ///
    /// [`Guard::from_request`]: #tymethod.from_request
    /// [`DefaultFuture`]: type.DefaultFuture.html
    type Result: IntoFuture<Item = Self, Error = BoxedError>;

    /// Create an instance of this type from HTTP request data, asynchronously.
    ///
    /// This can inspect HTTP headers and other data provided by
    /// [`http::Request`], but can not access the body of the request. If access
    /// to the body is needed, [`FromBody`] must be implemented instead.
    ///
    /// Implementations of this function must not block, since this function is
    /// always run on a futures executor. If you need to perform blocking I/O or
    /// long-running computations, you can call [`tokio_threadpool::blocking`].
    ///
    /// # Parameters
    ///
    /// * **`request`**: An HTTP request (without body) from the `http` crate.
    /// * **`context`**: User-defined context needed by the guard.
    ///
    /// [`http::Request`]: ../http/request/struct.Request.html
    /// [`FromBody`]: trait.FromBody.html
    /// [`tokio_threadpool::blocking`]: ../tokio_threadpool/fn.blocking.html
    fn from_request(request: &Arc<http::Request<()>>, context: &Self::Context) -> Self::Result;
}

/// Asynchronous conversion from an HTTP request body.
///
/// Types implementing this trait are provided in the [`body`] module. They
/// allow easy deserialization from a variety of data formats.
///
/// # Examples
///
/// Collect the whole body and then deserialize it using a serde data format
/// crate `serde_whatever`:
///
/// ```
/// # use hyperdrive::{FromBody, NoContext, DefaultFuture, BoxedError};
/// # use futures::prelude::*;
/// # use serde_json as serde_whatever;
/// # use std::sync::Arc;
/// struct CustomFormat<T>(T);
///
/// impl<T: serde::de::DeserializeOwned + Send + 'static> FromBody for CustomFormat<T> {
///     type Context = NoContext;
///     type Result = DefaultFuture<Self, BoxedError>;
///
///     fn from_body(
///         request: &Arc<http::Request<()>>,
///         body: hyper::Body,
///         context: &Self::Context,
///     ) -> Self::Result {
///         Box::new(body.concat2().map_err(Into::into).and_then(|body| {
///             match serde_whatever::from_slice(&body) {
///                 Ok(t) => Ok(CustomFormat(t)),
///                 Err(e) => Err(e.into()),
///             }
///         }))
///     }
/// }
/// ```
///
/// Process the body stream on-the-fly and calculate a checksum by adding all
/// the bytes:
///
/// ```
/// # use hyperdrive::{FromBody, NoContext, DefaultFuture, BoxedError};
/// # use futures::prelude::*;
/// # use std::sync::Arc;
/// struct BodyChecksum(u8);
///
/// impl FromBody for BodyChecksum {
///     type Context = NoContext;
///     type Result = DefaultFuture<Self, BoxedError>;
///
///     fn from_body(
///         request: &Arc<http::Request<()>>,
///         body: hyper::Body,
///         context: &Self::Context,
///     ) -> Self::Result {
///         Box::new(body
///             .map_err(BoxedError::from)
///             .fold(0, |checksum, chunk| -> Result<_, BoxedError> {
///                 Ok(chunk.as_ref().iter()
///                     .fold(checksum, |checksum: u8, byte| {
///                         checksum.wrapping_add(*byte)
///                 }))
///             })
///             .map(|checksum| BodyChecksum(checksum))  // wrap it up to create a `Self`
///         )
///     }
/// }
/// ```
///
/// [`body`]: body/index.html
pub trait FromBody: Sized {
    /// A context parameter passed to [`from_body`].
    ///
    /// This can be used to pass application-specific data like a logger or a
    /// database connection around.
    ///
    /// If no context is needed, this should be set to [`NoContext`].
    ///
    /// [`from_body`]: #tymethod.from_body
    /// [`NoContext`]: struct.NoContext.html
    type Context: RequestContext;

    /// The result returned by [`from_body`].
    ///
    /// Because `impl Trait` cannot be used inside traits (and named
    /// existential types aren't stable), the type here might not be
    /// nameable. In that case, you can set it to
    /// [`DefaultFuture<Self, Error>`][`DefaultFuture`] and box the returned
    /// future.
    ///
    /// If your `FromBody` implementation doesn't need to return a future, you
    /// can set this to `Result<Self, BoxedError>` and immediately return the
    /// result of the conversion.
    ///
    /// [`DefaultFuture`]: type.DefaultFuture.html
    /// [`from_body`]: #tymethod.from_body
    type Result: IntoFuture<Item = Self, Error = BoxedError>;

    /// Create an instance of this type from an HTTP request body,
    /// asynchronously.
    ///
    /// This will consume the body, so only one `FromBody` type can be used for
    /// every processed request.
    ///
    /// Implementations of this function must not block, since this function is
    /// always run on a futures executor. If you need to perform blocking I/O or
    /// long-running computations, you can call [`tokio_threadpool::blocking`].
    ///
    /// **Note**: You probably want to limit the size of the body to prevent
    /// denial of service attacks.
    ///
    /// # Parameters
    ///
    /// * **`request`**: An HTTP request (without body) from the `http` crate.
    /// * **`body`**: The body stream. Implements `futures::Stream`.
    /// * **`context`**: User-defined context.
    ///
    /// [`Guard`]: trait.Guard.html
    /// [`tokio_threadpool::blocking`]: ../tokio_threadpool/fn.blocking.html
    fn from_body(
        request: &Arc<http::Request<()>>,
        body: hyper::Body,
        context: &Self::Context,
    ) -> Self::Result;
}

/// A default [`RequestContext`] containing no data.
///
/// This context type should be used in [`FromRequest`], [`FromBody`] and
/// [`Guard`] implementations whenever no application-specific context is
/// needed. It can be created from any [`RequestContext`] via
/// `AsRef<NoContext>`.
///
/// [`FromRequest`]: trait.FromRequest.html
/// [`FromBody`]: trait.FromBody.html
/// [`Guard`]: trait.Guard.html
/// [`RequestContext`]: trait.RequestContext.html
#[derive(Debug, Copy, Clone, Default)]
pub struct NoContext;

/// Trait for context types passed to [`FromRequest`], [`FromBody`] and
/// [`Guard`].
///
/// # `#[derive(RequestContext)]`
///
/// This trait can be derived automatically. This will also implement
/// `AsRef<Self>` and `AsRef<NoContext>`.
///
/// On structs, fields can also be annotated using `#[as_ref]`, which generates
/// an additional implementation of `AsRef` for that field (note that all
/// `#[as_ref]` fields must have distinct types). This will automatically use
/// the field's type as a context when required by a `FromRequest` impl.
///
/// # Examples
///
/// Create your own context that allows running database queries in [`Guard`]s
/// and elsewhere:
/// ```
/// # use hyperdrive::RequestContext;
/// # struct ConnectionPool {}
/// #[derive(RequestContext)]
/// struct MyContext {
///     db: ConnectionPool,
/// }
/// ```
///
/// Create a context that contains the above context and additional data:
/// ```
/// # use hyperdrive::RequestContext;
/// # struct Logger {}
/// # #[derive(RequestContext)]
/// # struct MyContext {}
/// #[derive(RequestContext)]
/// struct BigContext {
///     #[as_ref]
///     inner: MyContext,
///     logger: Logger,
/// }
/// ```
/// This context can be used in the same places where `MyContext` is accepted,
/// but provides additional data that may be used only by a few [`Guard`],
/// [`FromRequest`] or [`FromBody`] implementations.
///
/// [`Guard`]: trait.Guard.html
/// [`FromRequest`]: trait.FromRequest.html
/// [`FromBody`]: trait.FromBody.html
pub trait RequestContext: AsRef<Self> + AsRef<NoContext> {}

impl RequestContext for NoContext {}

impl AsRef<NoContext> for NoContext {
    fn as_ref(&self) -> &Self {
        &NoContext
    }
}

/// Turns a blocking closure into an asynchronous `Future`.
///
/// This function takes a blocking closure that does synchronous I/O or heavy
/// computations, and turns it into a well-behaved asynchronous `Future` by
/// running it on a thread pool.
///
/// The returned future will have `'static` lifetime if the passed closure and
/// the success and error types do.
///
/// This is a convenience wrapper around [`tokio_threadpool::blocking`].
///
/// [`tokio_threadpool::blocking`]: ../tokio_threadpool/fn.blocking.html
pub fn blocking<F, T, E>(f: F) -> impl Future<Item = T, Error = E>
where
    F: FnOnce() -> Result<T, E>,
{
    // Needs a small `Option` dance because `poll_fn` takes an `FnMut`
    let mut f = Some(f);

    futures::future::poll_fn(move || {
        tokio_threadpool::blocking(|| f.take().unwrap()()).map_err(|blocking_err| {
            // `blocking` only returns errors in critical situations:
            // - when the threadpool has already shut down
            // - when tokio isn't running
            // This wrapper just panics in that situation.
            panic!(
                "`tokio_threadpool::blocking` returned error: {}",
                blocking_err
            );
        })
    })
    .and_then(|result| result)
}