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
//! Defines functionality for processing a request and trapping errors and panics in response
//! generation.

use std::panic::{catch_unwind, AssertUnwindSafe, UnwindSafe};

use futures_util::future::FutureExt;
use hyper::{Body, Response, StatusCode};
use log::error;

use crate::handler::{Handler, HandlerError, IntoResponse, NewHandler};
use crate::state::{request_id, State};

async fn handle<H>(
    handler: H,
    state: AssertUnwindSafe<State>,
) -> Result<(State, Response<Body>), (State, HandlerError)>
where
    H: Handler,
{
    let AssertUnwindSafe(state) = state;
    handler.handle(state).await
}

/// Instantiates a `Handler` from the given `NewHandler`, and invokes it with the request. If a
/// panic occurs from `NewHandler::new_handler` or `Handler::handle`, it is trapped and will result
/// in a `500 Internal Server Error` response.
///
/// Timing information is recorded and logged, except in the case of a panic where the timer is
/// moved and cannot be recovered.
pub async fn call_handler<T>(t: T, state: AssertUnwindSafe<State>) -> anyhow::Result<Response<Body>>
where
    T: NewHandler + Send + UnwindSafe,
{
    match catch_unwind(move || t.new_handler()) {
        Ok(handler) => {
            let unwind_result = AssertUnwindSafe(handle(handler?, state))
                .catch_unwind()
                .await;
            let result = match unwind_result {
                Ok(result) => result.map(|(_, res)| res),
                Err(_) => Ok(finalize_panic_response()),
            };
            Ok(match result {
                Ok(res) => res,
                Err((state, err)) => finalize_error_response(state, err),
            })
        }
        // Error while creating the handler from NewHandler
        Err(_) => Ok(finalize_panic_response()),
    }
}

fn finalize_error_response(state: State, err: HandlerError) -> Response<Body> {
    error!("[ERROR][{}][Error: {:?}]", request_id(&state), err);

    err.into_response(&state)
}

fn finalize_panic_response() -> Response<Body> {
    error!("[PANIC][A panic occurred while invoking the handler]");

    Response::builder()
        .status(StatusCode::INTERNAL_SERVER_ERROR)
        .body(Body::default())
        .unwrap()
}

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

    use futures_util::future;
    use hyper::{HeaderMap, Method, StatusCode};
    use std::io;
    use std::pin::Pin;

    use crate::handler::HandlerFuture;
    use crate::helpers::http::response::create_empty_response;
    use crate::state::set_request_id;

    #[test]
    fn success() {
        let new_handler = || {
            Ok(|state| {
                let res = create_empty_response(&state, StatusCode::ACCEPTED);
                (state, res)
            })
        };

        let mut state = State::new();
        state.put(HeaderMap::new());
        state.put(Method::GET);
        set_request_id(&mut state);

        let r = call_handler(&new_handler, AssertUnwindSafe(state));
        let response = futures_executor::block_on(r).unwrap();
        assert_eq!(response.status(), StatusCode::ACCEPTED);
    }

    #[test]
    fn async_success_repeat_poll() {
        let new_handler = || {
            Ok(|state| {
                let f = future::lazy(move |_| {
                    let res = create_empty_response(&state, StatusCode::ACCEPTED);
                    Ok((state, res))
                });

                let f = f.map(|v| v);
                let f = f.map(|v| v);
                let f = f.map(|v| v);

                f.boxed()
            })
        };

        let mut state = State::new();
        state.put(HeaderMap::new());
        state.put(Method::GET);
        set_request_id(&mut state);

        let r = call_handler(&new_handler, AssertUnwindSafe(state));
        let response = futures_executor::block_on(r).unwrap();
        assert_eq!(response.status(), StatusCode::ACCEPTED);
    }

    #[test]
    fn error() {
        let new_handler =
            || Ok(|state| future::err((state, io::Error::last_os_error().into())).boxed());

        let mut state = State::new();
        state.put(HeaderMap::new());
        state.put(Method::GET);
        set_request_id(&mut state);

        let r = call_handler(&new_handler, AssertUnwindSafe(state));
        let response = futures_executor::block_on(r).unwrap();
        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn panic() {
        #[allow(clippy::unnecessary_literal_unwrap)] // false positive? or bad description?
        let new_handler = || {
            Ok(|_| {
                let val: Option<Pin<Box<HandlerFuture>>> = None;
                val.expect("test panic")
            })
        };

        let mut state = State::new();
        state.put(HeaderMap::new());
        state.put(Method::GET);
        set_request_id(&mut state);

        let r = call_handler(&new_handler, AssertUnwindSafe(state));
        let response = futures_executor::block_on(r).unwrap();
        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn async_panic() {
        let new_handler = || Ok(|_| future::lazy(move |_| panic!("test panic")).boxed());

        let mut state = State::new();
        state.put(HeaderMap::new());
        state.put(Method::GET);
        set_request_id(&mut state);

        let r = call_handler(&new_handler, AssertUnwindSafe(state));
        let response = futures_executor::block_on(r).unwrap();
        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn async_panic_repeat_poll() {
        let new_handler = || {
            Ok(|_| {
                let f = future::lazy(move |_| panic!("test panic"));

                let f = f.map(|v| v);
                let f = f.map(|v| v);
                let f = f.map(|v| v);

                f.boxed()
            })
        };

        let mut state = State::new();
        state.put(HeaderMap::new());
        state.put(Method::GET);
        set_request_id(&mut state);

        let r = call_handler(&new_handler, AssertUnwindSafe(state));
        let response = futures_executor::block_on(r).unwrap();
        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn new_handler_panic() {
        struct PanicNewHandler;
        impl NewHandler for PanicNewHandler {
            type Instance = Self;

            fn new_handler(&self) -> anyhow::Result<Self::Instance> {
                panic!("Pannicked creating a new handler");
            }
        }

        impl Handler for PanicNewHandler {
            fn handle(self, _state: State) -> Pin<Box<HandlerFuture>> {
                unreachable!();
            }
        }

        let mut state = State::new();
        state.put(HeaderMap::new());
        state.put(Method::GET);
        set_request_id(&mut state);

        let new_handler = PanicNewHandler {};
        let r = call_handler(new_handler, AssertUnwindSafe(state));
        let response = futures_executor::block_on(r).unwrap();
        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }
}