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
//! Panic reporter middleware.
//!
//! See [`PanicReporter`] for docs.

use std::{
    any::Any,
    future::{ready, Ready},
    panic::{self, AssertUnwindSafe},
    rc::Rc,
};

use actix_web::dev::{forward_ready, Service, Transform};
use futures_core::future::LocalBoxFuture;
use futures_util::FutureExt as _;

type PanicCallback = Rc<dyn Fn(&(dyn Any + Send))>;

/// A middleware that triggers a callback when the worker is panicking.
///
/// Mostly useful for logging or metrics publishing. The callback received the object with which
/// panic was originally invoked to allow down-casting.
///
/// # Examples
///
/// ```no_run
/// # use actix_web::App;
/// use actix_web_lab::middleware::PanicReporter;
/// # mod metrics {
/// #   macro_rules! increment_counter {
/// #       ($tt:tt) => {{}};
/// #   }
/// #   pub(crate) use increment_counter;
/// # }
///
/// App::new().wrap(PanicReporter::new(|_| metrics::increment_counter!("panic")))
///     # ;
/// ```
#[derive(Clone)]
pub struct PanicReporter {
    cb: PanicCallback,
}

impl PanicReporter {
    /// Constructs new panic reporter middleware with `callback`.
    pub fn new(callback: impl Fn(&(dyn Any + Send)) + 'static) -> Self {
        Self {
            cb: Rc::new(callback),
        }
    }
}

impl std::fmt::Debug for PanicReporter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PanicReporter")
            .field("cb", &"<callback>")
            .finish()
    }
}

impl<S, Req> Transform<S, Req> for PanicReporter
where
    S: Service<Req>,
    S::Future: 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Transform = PanicReporterMiddleware<S>;
    type InitError = ();
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(PanicReporterMiddleware {
            service: Rc::new(service),
            cb: Rc::clone(&self.cb),
        }))
    }
}

pub struct PanicReporterMiddleware<S> {
    service: Rc<S>,
    cb: PanicCallback,
}

impl<S, Req> Service<Req> for PanicReporterMiddleware<S>
where
    S: Service<Req>,
    S::Future: 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = LocalBoxFuture<'static, Result<S::Response, S::Error>>;

    forward_ready!(service);

    fn call(&self, req: Req) -> Self::Future {
        let cb = Rc::clone(&self.cb);

        // catch panics in service call
        AssertUnwindSafe(self.service.call(req))
            .catch_unwind()
            .map(move |maybe_res| match maybe_res {
                Ok(res) => res,
                Err(panic_err) => {
                    // invoke callback with panic arg
                    (cb)(&panic_err);

                    // continue unwinding
                    panic::resume_unwind(panic_err)
                }
            })
            .boxed_local()
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    };

    use actix_web::{
        dev::Service as _,
        test,
        web::{self, ServiceConfig},
        App,
    };

    use super::*;

    fn configure_test_app(cfg: &mut ServiceConfig) {
        cfg.route("/", web::get().to(|| async { "content" })).route(
            "/disco",
            #[allow(unreachable_code)]
            web::get().to(|| async {
                panic!("the disco");
                ""
            }),
        );
    }

    #[actix_web::test]
    async fn report_when_panics_occur() {
        let triggered = Arc::new(AtomicBool::new(false));

        let app = App::new()
            .wrap(PanicReporter::new({
                let triggered = Arc::clone(&triggered);
                move |_| {
                    triggered.store(true, Ordering::SeqCst);
                }
            }))
            .configure(configure_test_app);

        let app = test::init_service(app).await;

        let req = test::TestRequest::with_uri("/").to_request();
        assert!(app.call(req).await.is_ok());
        assert!(!triggered.load(Ordering::SeqCst));

        let req = test::TestRequest::with_uri("/disco").to_request();
        assert!(AssertUnwindSafe(app.call(req))
            .catch_unwind()
            .await
            .is_err());
        assert!(triggered.load(Ordering::SeqCst));
    }
}