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
//! Defines types for a middleware pipeline

pub mod chain;
pub mod set;
pub mod single;

use log::trace;
use std::pin::Pin;

use crate::handler::HandlerFuture;
use crate::middleware::chain::{MiddlewareChain, NewMiddlewareChain};
use crate::middleware::NewMiddleware;
use crate::state::{request_id, State};

/// When using middleware, one or more `Middleware` are combined to form a `Pipeline`.
/// `Middleware` are invoked strictly in the order they're added to the `Pipeline`.
///
/// At `Request` dispatch time, the `Middleware` are created from the `NewMiddleware` values given
/// to the `PipelineBuilder`, and combined with a `Handler` created from the `NewHandler` provided
/// to `Pipeline::call`.  These `Middleware` and `Handler` values are used for a single `Request`.
///
/// # Examples
///
/// ```rust
/// # extern crate gotham;
/// # #[macro_use]
/// # extern crate gotham_derive;
/// # extern crate hyper;
/// # extern crate mime;
/// #
/// # use std::pin::Pin;
/// #
/// # use gotham::helpers::http::response::create_response;
/// # use gotham::state::State;
/// # use gotham::handler::HandlerFuture;
/// # use gotham::middleware::Middleware;
/// # use gotham::pipeline::new_pipeline;
/// # use gotham::pipeline::single::*;
/// # use gotham::router::builder::*;
/// # use gotham::test::TestServer;
/// # use hyper::{Body, Response, StatusCode};
/// #
/// #[derive(StateData)]
/// struct MiddlewareData {
///     vec: Vec<i32>
/// }
///
/// #[derive(NewMiddleware, Copy, Clone)]
/// struct MiddlewareOne;
///
/// impl Middleware for MiddlewareOne {
///     // Implementation elided.
///     // Appends `1` to `MiddlewareData.vec`
/// #     fn call<Chain>(self, mut state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
/// #         where Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static
/// #     {
/// #         state.put(MiddlewareData { vec: vec![1] });
/// #         chain(state)
/// #     }
/// }
///
/// #[derive(NewMiddleware, Copy, Clone)]
/// struct MiddlewareTwo;
///
/// impl Middleware for MiddlewareTwo {
///     // Implementation elided.
///     // Appends `2` to `MiddlewareData.vec`
/// #     fn call<Chain>(self, mut state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
/// #         where Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static
/// #     {
/// #         state.borrow_mut::<MiddlewareData>().vec.push(2);
/// #         chain(state)
/// #     }
/// }
///
/// #[derive(NewMiddleware, Copy, Clone)]
/// struct MiddlewareThree;
///
/// impl Middleware for MiddlewareThree {
///     // Implementation elided.
///     // Appends `3` to `MiddlewareData.vec`
/// #     fn call<Chain>(self, mut state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
/// #         where Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static
/// #     {
/// #         state.borrow_mut::<MiddlewareData>().vec.push(3);
/// #         chain(state)
/// #     }
/// }
///
/// fn handler(state: State) -> (State, Response<Body>) {
///     let body = {
///        let data = state.borrow::<MiddlewareData>();
///        format!("{:?}", data.vec)
///     };
///
///     let res = create_response(&state,
///                               StatusCode::OK,
///                               mime::TEXT_PLAIN,
///                               body);
///
///     (state, res)
/// }
///
/// fn main() {
///     let (chain, pipelines) = single_pipeline(
///         new_pipeline()
///             .add(MiddlewareOne)
///             .add(MiddlewareTwo)
///             .add(MiddlewareThree)
///             .build()
///     );
///
///     let router = build_router(chain, pipelines, |route| {
///         route.get("/").to(handler);
///     });
///
///     let test_server = TestServer::new(router).unwrap();
///     let response = test_server.client().get("http://example.com/").perform().unwrap();
///     assert_eq!(response.status(), StatusCode::OK);
///     assert_eq!(response.read_utf8_body().unwrap(), "[1, 2, 3]");
/// }
/// ```
pub struct Pipeline<T>
where
    T: NewMiddlewareChain,
{
    chain: T,
}

/// Represents an instance of a `Pipeline`. Returned from `Pipeline::construct()`.
struct PipelineInstance<T>
where
    T: MiddlewareChain,
{
    chain: T,
}

impl<T> Pipeline<T>
where
    T: NewMiddlewareChain,
{
    /// Constructs an instance of this `Pipeline` by creating all `Middleware` instances required
    /// to serve a request. If any middleware fails creation, its error will be returned.
    fn construct(&self) -> anyhow::Result<PipelineInstance<T::Instance>> {
        Ok(PipelineInstance {
            chain: self.chain.construct()?,
        })
    }
}

impl<T> PipelineInstance<T>
where
    T: MiddlewareChain,
{
    /// Serves a request using this `PipelineInstance`. Requests that pass through all `Middleware`
    /// will be served with the `f` function.
    fn call<F>(self, state: State, f: F) -> Pin<Box<HandlerFuture>>
    where
        F: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static,
    {
        trace!("[{}] calling middleware", request_id(&state));
        self.chain.call(state, f)
    }
}

/// Begins defining a new pipeline.
///
/// See `PipelineBuilder` for information on using `new_pipeline()`.
pub fn new_pipeline() -> PipelineBuilder<()> {
    trace!(" starting pipeline construction");
    // See: `impl NewMiddlewareChain for ()`
    PipelineBuilder { t: () }
}

/// Constructs a pipeline from a single middleware.
pub fn single_middleware<M>(m: M) -> Pipeline<(M, ())>
where
    M: NewMiddleware,
    M::Instance: Send + 'static,
{
    new_pipeline().add(m).build()
}

/// Allows a pipeline to be defined by adding `NewMiddleware` values, and building a `Pipeline`.
///
/// # Examples
///
/// ```rust
/// # extern crate gotham;
/// # #[macro_use]
/// # extern crate gotham_derive;
/// #
/// # use std::pin::Pin;
/// #
/// # use gotham::state::State;
/// # use gotham::handler::HandlerFuture;
/// # use gotham::middleware::Middleware;
/// # use gotham::pipeline::new_pipeline;
/// #
/// # #[derive(NewMiddleware, Copy, Clone)]
/// # struct MiddlewareOne;
/// #
/// # #[derive(NewMiddleware, Copy, Clone)]
/// # struct MiddlewareTwo;
/// #
/// # #[derive(NewMiddleware, Copy, Clone)]
/// # struct MiddlewareThree;
/// #
/// # impl Middleware for MiddlewareOne {
/// #   fn call<Chain>(self, state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
/// #       where Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static
/// #   {
/// #       chain(state)
/// #   }
/// # }
/// #
/// # impl Middleware for MiddlewareTwo {
/// #   fn call<Chain>(self, state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
/// #       where Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static
/// #   {
/// #       chain(state)
/// #   }
/// # }
/// #
/// # impl Middleware for MiddlewareThree {
/// #   fn call<Chain>(self, state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
/// #       where Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static
/// #   {
/// #       chain(state)
/// #   }
/// # }
/// #
/// # fn main() {
/// new_pipeline()
///     .add(MiddlewareOne)
///     .add(MiddlewareTwo)
///     .add(MiddlewareThree)
///     .build();
/// # }
/// ```
///
/// The pipeline defined here is invoked in this order:
///
/// `(&mut state)` &rarr; `MiddlewareOne` &rarr; `MiddlewareTwo` &rarr; `MiddlewareThree` &rarr;
/// `handler` (provided later, when building the router)
pub struct PipelineBuilder<T>
where
    T: NewMiddlewareChain,
{
    t: T,
}

impl<T> PipelineBuilder<T>
where
    T: NewMiddlewareChain,
{
    /// Builds a `Pipeline`, which contains all middleware in the order provided via `add` and is
    /// ready to process requests via a `NewHandler` provided to `Pipeline::call`.
    pub fn build(self) -> Pipeline<T>
    where
        T: NewMiddlewareChain,
    {
        Pipeline { chain: self.t }
    }

    /// Adds a `NewMiddleware` which will create a `Middleware` during request dispatch.
    pub fn add<M>(self, m: M) -> PipelineBuilder<(M, T)>
    where
        M: NewMiddleware,
        M::Instance: Send + 'static,
        Self: Sized,
    {
        // "cons" the most recently added `NewMiddleware` onto the front of the list. This is
        // essentially building an HList-style tuple in reverse order. So for a call like:
        //
        //     new_pipeline().add(MiddlewareOne).add(MiddlewareTwo).add(MiddlewareThree)
        //
        // The resulting `PipelineBuilder` will be:
        //
        //     PipelineBuilder { t: (MiddlewareThree, (MiddlewareTwo, (MiddlewareOne, ()))) }
        //
        // An empty `PipelineBuilder` is represented as:
        //
        //     PipelineBuilder { t: () }
        trace!(" adding middleware to pipeline");
        PipelineBuilder { t: (m, self.t) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use futures::prelude::*;
    use hyper::{Body, Response, StatusCode};

    use crate::handler::Handler;
    use crate::middleware::Middleware;
    use crate::state::StateData;
    use crate::test::TestServer;

    fn handler(state: State) -> (State, Response<Body>) {
        let number = state.borrow::<Number>().value;
        (
            state,
            Response::builder()
                .status(StatusCode::OK)
                .body(format!("{}", number).into())
                .unwrap(),
        )
    }

    #[derive(Clone)]
    struct Number {
        value: i32,
    }

    impl NewMiddleware for Number {
        type Instance = Number;

        fn new_middleware(&self) -> anyhow::Result<Number> {
            Ok(self.clone())
        }
    }

    impl Middleware for Number {
        fn call<Chain>(self, mut state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
        where
            Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static,
            Self: Sized,
        {
            state.put(self.clone());
            chain(state)
        }
    }

    impl StateData for Number {}

    struct Addition {
        value: i32,
    }

    impl NewMiddleware for Addition {
        type Instance = Addition;

        fn new_middleware(&self) -> anyhow::Result<Addition> {
            Ok(Addition { ..*self })
        }
    }

    impl Middleware for Addition {
        fn call<Chain>(self, mut state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
        where
            Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static,
            Self: Sized,
        {
            state.borrow_mut::<Number>().value += self.value;
            chain(state)
        }
    }

    struct Multiplication {
        value: i32,
    }

    impl NewMiddleware for Multiplication {
        type Instance = Multiplication;

        fn new_middleware(&self) -> anyhow::Result<Multiplication> {
            Ok(Multiplication { ..*self })
        }
    }

    impl Middleware for Multiplication {
        fn call<Chain>(self, mut state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
        where
            Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + 'static,
            Self: Sized,
        {
            state.borrow_mut::<Number>().value *= self.value;
            chain(state)
        }
    }

    #[test]
    fn pipeline_ordering_test() {
        let test_server = TestServer::new(|| {
            let pipeline = new_pipeline()
                .add(Number { value: 0 }) // 0
                .add(Addition { value: 1 }) // 1
                .add(Multiplication { value: 2 }) // 2
                .add(Addition { value: 1 }) // 3
                .add(Multiplication { value: 2 }) // 6
                .add(Addition { value: 2 }) // 8
                .add(Multiplication { value: 3 }) // 24
                .build();

            Ok(move |state| match pipeline.construct() {
                Ok(p) => p.call(state, |state| handler.handle(state)),
                Err(e) => future::err((state, e.into())).boxed(),
            })
        })
        .unwrap();

        let response = test_server
            .client()
            .get("http://localhost/")
            .perform()
            .unwrap();

        let buf = response.read_body().unwrap();
        assert_eq!(buf.as_slice(), b"24");
    }
}