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
//! Defines types for `Middleware`, a reusable unit of logic that can apply to a group of requests
//! by being added to the `Pipeline` in a `Router`.

use std::panic::RefUnwindSafe;
use std::pin::Pin;

use crate::handler::HandlerFuture;
use crate::state::State;

pub mod chain;
pub mod cookie;
pub mod logger;
pub mod security;
#[cfg(feature = "session")]
pub mod session;
pub mod state;
pub mod timer;

#[cfg(feature = "derive")]
pub use gotham_derive::NewMiddleware;

/// `Middleware` has the opportunity to provide additional behaviour to the `Request` / `Response`
/// interaction. For example:
///
/// * The request can be halted due to some unmet precondition;
/// * Processing the request can be delayed until some other action has completed;
/// * Middleware-specific state data can be recorded in the `State` struct for use elsewhere;
/// * The returned future can be manipulated via continuations to provide additional behaviour
///   after the request completes.
///
/// # Examples
///
/// Taking no action, and immediately passing the `Request` through to the rest of the application:
///
/// ```rust
/// # #[macro_use]
/// # extern crate gotham_derive;
/// #
/// # use std::pin::Pin;
/// #
/// # use hyper::{Body, Response, StatusCode};
/// # use gotham::handler::HandlerFuture;
/// # use gotham::middleware::Middleware;
/// # use gotham::pipeline::*;
/// # use gotham::router::builder::*;
/// # use gotham::state::State;
/// # use gotham::test::TestServer;
/// #
/// #[derive(NewMiddleware, Copy, Clone)]
/// struct NoopMiddleware;
///
/// impl Middleware for NoopMiddleware {
///     fn call<Chain>(self, state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
///         where Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static
///     {
///         chain(state)
///     }
/// }
/// #
/// # fn main() {
/// #   let (chain, pipelines) = single_pipeline(
/// #       new_pipeline()
/// #           .add(NoopMiddleware)
/// #           .build()
/// #   );
/// #
/// #   let router = build_router(chain, pipelines, |route| {
/// #       route
/// #           .get("/")
/// #           .to_new_handler(|| {
/// #               Ok(|state| (state, Response::builder().status(StatusCode::ACCEPTED).body(Body::empty()).unwrap()))
/// #           });
/// #   });
/// #
/// #   let test_server = TestServer::new(router).unwrap();
/// #   let response = test_server.client().get("https://example.com/").perform().unwrap();
/// #   assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
///
/// Recording a piece of state data before passing the request through:
///
/// ```rust
/// # #[macro_use]
/// # extern crate gotham_derive;
/// #
/// # use std::pin::Pin;
/// #
/// # use hyper::{Response, StatusCode};
/// # use gotham::handler::HandlerFuture;
/// # use gotham::middleware::Middleware;
/// # use gotham::pipeline::*;
/// # use gotham::router::builder::*;
/// # use gotham::state::State;
/// # use gotham::test::TestServer;
/// #
/// #[derive(NewMiddleware, Copy, Clone)]
/// struct MiddlewareWithStateData;
///
/// #[derive(StateData)]
/// struct MiddlewareStateData {
///     i: i32,
/// }
///
/// impl Middleware for MiddlewareWithStateData {
///     fn call<Chain>(self, mut state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
///         where Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static
///     {
///         state.put(MiddlewareStateData { i: 10 });
///         chain(state)
///     }
/// }
/// #
/// # fn main() {
/// #   let (chain, pipelines) = single_pipeline(
/// #       new_pipeline()
/// #           .add(MiddlewareWithStateData)
/// #           .build()
/// #   );
/// #
/// #   let router = build_router(chain, pipelines, |route| {
/// #       route
/// #           .get("/")
/// #           .to_new_handler(|| {
/// #               Ok(|mut state: State| {
/// #                   let data = state.take::<MiddlewareStateData>();
/// #                   let body = format!("{}", data.i).into_bytes();
/// #                   (state, Response::builder().status(StatusCode::OK).body(body.into()).unwrap())
/// #               })
/// #           });
/// #   });
/// #
/// #   let test_server = TestServer::new(router).unwrap();
/// #   let response = test_server.client().get("https://example.com/").perform().unwrap();
/// #   assert_eq!(response.status(), StatusCode::OK);
/// #   let body = response.read_utf8_body().unwrap();
/// #   assert_eq!(&body, "10");
/// # }
/// ```
///
/// Decorating the response after the request has completed:
///
/// ```rust
/// # #[macro_use]
/// # extern crate gotham_derive;
/// #
/// # use std::pin::Pin;
/// #
/// # use futures_util::{FutureExt, TryFutureExt};
/// # use hyper::{Body, Response, StatusCode};
/// # use hyper::header::WARNING;
/// # use gotham::handler::HandlerFuture;
/// # use gotham::middleware::Middleware;
/// # use gotham::pipeline::*;
/// # use gotham::router::builder::*;
/// # use gotham::state::State;
/// # use gotham::test::TestServer;
/// #
/// #[derive(NewMiddleware, Copy, Clone)]
/// struct MiddlewareAddingResponseHeader;
///
/// impl Middleware for MiddlewareAddingResponseHeader {
///     fn call<Chain>(self, state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
///         where Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static
///     {
///         chain(state)
///             .map_ok(|(state, mut response)| {
///                 response.headers_mut().insert(WARNING, "299 example.com Deprecated".parse().unwrap());
///                 (state, response)
///             })
///             .boxed()
///     }
/// }
/// #
/// # fn main() {
/// #   let (chain, pipelines) = single_pipeline(
/// #       new_pipeline()
/// #           .add(MiddlewareAddingResponseHeader)
/// #           .build()
/// #   );
/// #
/// #   let router = build_router(chain, pipelines, |route| {
/// #       route
/// #           .get("/")
/// #           .to_new_handler(|| {
/// #               Ok(|state| (state, Response::builder().status(StatusCode::ACCEPTED).body(Body::empty()).unwrap()))
/// #           });
/// #   });
/// #
/// #   let test_server = TestServer::new(router).unwrap();
/// #   let response = test_server.client().get("https://example.com/").perform().unwrap();
/// #   assert_eq!(response.status(), StatusCode::ACCEPTED);
/// #
/// #   {
/// #       let warning = response.headers().get(WARNING).unwrap();
/// #       assert_eq!(warning, "299 example.com Deprecated");
/// #   }
/// # }
/// ```
///
/// Terminating the request early based on some arbitrary condition:
///
/// ```rust
/// # #[macro_use]
/// # extern crate gotham_derive;
/// #
/// # use std::pin::Pin;
/// #
/// # use hyper::{Body, Response, Method, StatusCode};
/// # use futures_util::future::{self, FutureExt};
/// # use gotham::helpers::http::response::create_empty_response;
/// # use gotham::handler::HandlerFuture;
/// # use gotham::middleware::Middleware;
/// # use gotham::pipeline::*;
/// # use gotham::router::builder::*;
/// # use gotham::state::{State, FromState};
/// # use gotham::test::TestServer;
/// #
/// #[derive(NewMiddleware, Copy, Clone)]
/// struct ConditionalMiddleware;
///
/// impl Middleware for ConditionalMiddleware {
///     fn call<Chain>(self, state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
///         where Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static
///     {
///         if *Method::borrow_from(&state) == Method::GET {
///             chain(state)
///         } else {
///             let response = create_empty_response(&state, StatusCode::METHOD_NOT_ALLOWED);
///             future::ok((state, response)).boxed()
///         }
///     }
/// }
/// #
/// # fn main() {
/// #   let (chain, pipelines) = single_pipeline(
/// #       new_pipeline()
/// #           .add(ConditionalMiddleware)
/// #           .build()
/// #   );
/// #
/// #   let router = build_router(chain, pipelines, |route| {
/// #       route
/// #           .get_or_head("/")
/// #           .to_new_handler(|| {
/// #               Ok(|state| (state, Response::builder().status(StatusCode::ACCEPTED).body(Body::empty()).unwrap()))
/// #           });
/// #   });
/// #
/// #   let test_server = TestServer::new(router).unwrap();
/// #
/// #   let response = test_server.client().get("https://example.com/").perform().unwrap();
/// #   assert_eq!(response.status(), StatusCode::ACCEPTED);
/// #
/// #   let response = test_server.client().head("https://example.com/").perform().unwrap();
/// #   assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
/// # }
/// ```
///
/// Asynchronous middleware, which continues the request after some action completes:
///
/// ```rust
/// # #[macro_use]
/// # extern crate gotham_derive;
/// #
/// # use std::pin::Pin;
/// #
/// # use futures_util::future::{self, FutureExt, TryFutureExt};
/// # use hyper::{Body, Response, StatusCode};
/// # use gotham::handler::HandlerFuture;
/// # use gotham::middleware::Middleware;
/// # use gotham::pipeline::*;
/// # use gotham::router::builder::*;
/// # use gotham::state::State;
/// # use gotham::test::TestServer;
/// #
/// #[derive(NewMiddleware, Copy, Clone)]
/// struct AsyncMiddleware;
///
/// impl Middleware for AsyncMiddleware {
///     fn call<Chain>(self, state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
///         where Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static
///     {
///         // This could be any asynchronous action. `future::lazy(_)` defers a function
///         // until the next cycle of tokio's event loop.
///         let f = future::lazy(|_| Ok(()));
///         f.and_then(move |_| chain(state)).boxed()
///     }
/// }
/// #
/// # fn main() {
/// #   let (chain, pipelines) = single_pipeline(
/// #       new_pipeline()
/// #           .add(AsyncMiddleware)
/// #           .build()
/// #   );
/// #
/// #   let router = build_router(chain, pipelines, |route| {
/// #       route
/// #           .get("/")
/// #           .to_new_handler(|| {
/// #               Ok(|state| (state, Response::builder().status(StatusCode::ACCEPTED).body(Body::empty()).unwrap()))
/// #           });
/// #   });
/// #
/// #   let test_server = TestServer::new(router).unwrap();
/// #   let response = test_server.client().get("https://example.com/").perform().unwrap();
/// #   assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
pub trait Middleware {
    /// Entry point to the middleware. To pass the request on to the application, the middleware
    /// invokes the `chain` function with the provided `state`.
    ///
    /// By convention, the middleware should:
    ///
    /// * Not modify any request components added to `State` by Gotham.
    /// * Avoid modifying parts of the `State` that don't strictly need to be modified to perform
    ///   its function.
    fn call<Chain>(self, state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
    where
        Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static,
        Self: Sized;
}

/// A type which is used to spawn new `Middleware` values. When implementing a `Middleware`, this
/// defines how instances of the `Middleware` are created.
///
/// This can be derived by `Middleware` that implement `Clone`, and will result in the following
/// implementation:
///
/// ```rust
/// # extern crate gotham;
/// #
/// # use std::pin::Pin;
/// #
/// # use gotham::middleware::{NewMiddleware, Middleware};
/// # use gotham::handler::HandlerFuture;
/// # use gotham::pipeline::new_pipeline;
/// # use gotham::state::State;
/// #
/// # #[allow(unused)]
/// # #[derive(Copy, Clone)]
/// struct MyMiddleware;
///
/// impl NewMiddleware for MyMiddleware {
///     type Instance = Self;
///
///     fn new_middleware(&self) -> anyhow::Result<Self::Instance> {
///         Ok(self.clone())
///     }
/// }
/// #
/// # impl Middleware for MyMiddleware {
/// #   fn call<Chain>(self, _state: State, _chain: Chain) -> Pin<Box<HandlerFuture>>
/// #       where Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + 'static
/// #   {
/// #       unimplemented!()
/// #   }
/// # }
/// #
/// # fn main() {
/// #   // Just for the implied type assertion.
/// #   new_pipeline().add(MyMiddleware).build();
/// # }
pub trait NewMiddleware: Sync + RefUnwindSafe {
    /// The type of `Middleware` created by the `NewMiddleware`.
    type Instance: Middleware;

    /// Create and return a new `Middleware` value.
    fn new_middleware(&self) -> anyhow::Result<Self::Instance>;
}