gotham/middleware/
chain.rs

1//! Defines the types for connecting multiple middleware into a "chain" when forming a pipeline.
2#![allow(unsafe_code)]
3
4use log::trace;
5
6use std::panic::RefUnwindSafe;
7use std::pin::Pin;
8
9use crate::handler::HandlerFuture;
10use crate::middleware::{Middleware, NewMiddleware};
11use crate::state::{request_id, State};
12
13/// A recursive type representing a pipeline, which is used to spawn a `MiddlewareChain`.
14///
15/// This type should never be implemented outside of Gotham, does not form part of the public API,
16/// and is subject to change without notice.
17#[doc(hidden)]
18pub unsafe trait NewMiddlewareChain: RefUnwindSafe + Sized {
19    type Instance: MiddlewareChain;
20
21    /// Create and return a new `MiddlewareChain` value.
22    fn construct(&self) -> anyhow::Result<Self::Instance>;
23}
24
25unsafe impl<T, U> NewMiddlewareChain for (T, U)
26where
27    T: NewMiddleware,
28    T::Instance: Send + 'static,
29    U: NewMiddlewareChain,
30{
31    type Instance = (T::Instance, U::Instance);
32
33    fn construct(&self) -> anyhow::Result<Self::Instance> {
34        // This works as a recursive `map` over the "list" of `NewMiddleware`, and is used in
35        // creating the `Middleware` instances for serving a single request.
36        //
37        // The reversed order is preserved in the return value.
38        trace!(" adding middleware instance to pipeline");
39        let (ref nm, ref tail) = *self;
40        Ok((nm.new_middleware()?, tail.construct()?))
41    }
42}
43
44unsafe impl NewMiddlewareChain for () {
45    type Instance = ();
46
47    fn construct(&self) -> anyhow::Result<Self::Instance> {
48        // () marks the end of the list, so is returned as-is.
49        trace!(" completed middleware pipeline construction");
50        Ok(())
51    }
52}
53
54/// A recursive type representing an instance of a pipeline, which is used to process a single
55/// request.
56///
57/// This type should never be implemented outside of Gotham, does not form part of the public API,
58/// and is subject to change without notice.
59#[doc(hidden)]
60pub unsafe trait MiddlewareChain: Sized {
61    /// Recursive function for processing middleware and chaining to the given function.
62    fn call<F>(self, state: State, f: F) -> Pin<Box<HandlerFuture>>
63    where
64        F: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static;
65}
66
67unsafe impl MiddlewareChain for () {
68    fn call<F>(self, state: State, f: F) -> Pin<Box<HandlerFuture>>
69    where
70        F: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static,
71    {
72        // At the last item in the `MiddlewareChain`, the function is invoked to serve the
73        // request. `f` is the nested function of all `Middleware` and the `Handler`.
74        //
75        // In the case of 0 middleware, `f` is the function created in `MiddlewareChain::call`
76        // which invokes the `Handler` directly.
77        trace!("pipeline complete, invoking handler");
78        f(state)
79    }
80}
81
82unsafe impl<T, U> MiddlewareChain for (T, U)
83where
84    T: Middleware + Send + 'static,
85    U: MiddlewareChain,
86{
87    fn call<F>(self, state: State, f: F) -> Pin<Box<HandlerFuture>>
88    where
89        F: FnOnce(State) -> Pin<Box<HandlerFuture>> + Send + 'static,
90    {
91        let (m, p) = self;
92        // Construct the function from the inside, out. Starting with a function which calls the
93        // `Handler`, and then creating a new function which calls the `Middleware` with the
94        // previous function as the `chain` argument, we end up with a structure somewhat like
95        // this (using `m0`, `m1`, `m2` as middleware names, where `m2` is the last middleware
96        // before the `Handler`):
97        //
98        //  move |state| {
99        //      m0.call(state, move |state| {
100        //          m1.call(state, move |state| {
101        //              m2.call(state, move |state| handler.call(state))
102        //          })
103        //      })
104        //  }
105        //
106        // The resulting function is called by `<() as MiddlewareChain>::call`
107        trace!("[{}] executing middleware", request_id(&state));
108        p.call(state, move |state| m.call(state, f))
109    }
110}