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
//! Middlewares for using Sentry in Merino.

use crate::errors::HandlerError;
use actix_web::{
    body::MessageBody,
    dev::{Service, ServiceRequest, ServiceResponse, Transform},
    error::Error as ActixError,
    ResponseError,
};
use futures_util::future::LocalBoxFuture;
use sentry::protocol::Event;
use std::{
    error::Error as StdError,
    fmt,
    future::{ready, Ready},
    task::{Context, Poll},
};

/// Wrapper for Sentry error reporting, since no version of sentry-actix is
/// compatible with our stack. Old versions don't have modern Actix middlewares,
/// and new versions require servers newer than ours.
#[derive(Debug, Default)]
pub struct Sentry;

impl<S, B> Transform<S, ServiceRequest> for Sentry
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    B: 'static + MessageBody,
    B::Error: ResponseError,
    S::Future: 'static,
    S::Error: fmt::Debug,
{
    type Response = S::Response;
    type Error = ActixError;
    type InitError = ();
    type Transform = SentryMiddleware<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(SentryMiddleware { service }))
    }
}

/// Middleware to catch events from request handlers and send them to Sentry.
#[derive(Debug)]
pub struct SentryMiddleware<S> {
    /// The wrapped service
    service: S,
}

impl<S> SentryMiddleware<S> {
    /// Custom `sentry::event_from_error` for `HandlerError`
    ///
    /// `sentry::event_from_error` can't access `std::Error` backtraces as its
    /// `backtrace()` method is currently Rust nightly only. This function works
    /// against `HandlerError` instead to access its backtrace.
    pub fn event_from_error(err: &HandlerError) -> Event<'static> {
        let mut exceptions = vec![Self::exception_from_error_with_backtrace(err)];

        let mut source = err.source();
        while let Some(err) = source {
            let exception = if let Some(err) = err.downcast_ref() {
                Self::exception_from_error_with_backtrace(err)
            } else {
                Self::exception_from_error(err)
            };
            exceptions.push(exception);
            source = err.source();
        }

        exceptions.reverse();
        Event {
            exception: exceptions.into(),
            level: sentry::protocol::Level::Error,
            ..Default::default()
        }
    }

    /// Custom `exception_from_error` support function for `HandlerError`
    ///
    /// Based moreso on sentry_failure's `exception_from_single_fail`.
    fn exception_from_error_with_backtrace(err: &HandlerError) -> sentry::protocol::Exception {
        let mut exception = Self::exception_from_error(err);
        // format the stack trace with alternate debug to get addresses
        let bt = format!("{:#?}", err.backtrace);
        exception.stacktrace = sentry_backtrace::parse_stacktrace(&bt);
        exception
    }

    /// Exact copy of sentry's unfortunately private `exception_from_error`
    fn exception_from_error<E: StdError + ?Sized>(err: &E) -> sentry::protocol::Exception {
        let dbg = format!("{:?}", err);
        sentry::protocol::Exception {
            ty: sentry::parse_type_from_debug(&dbg).to_owned(),
            value: Some(err.to_string()),
            ..Default::default()
        }
    }
}

impl<S, B> Service<ServiceRequest> for SentryMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError>,
    B: 'static + MessageBody,
    S::Future: 'static,
    B::Error: ResponseError,
    S::Error: fmt::Debug,
{
    type Response = S::Response;
    type Error = ActixError;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.service.poll_ready(cx).map_err(|error| {
            tracing::error!(
                r#type = "web.sentry.polling-error",
                ?error,
                "Error polling service"
            );
            HandlerError::internal().into()
        })
    }

    #[tracing::instrument(level = "DEBUG", skip(self, req))]
    fn call(&self, req: ServiceRequest) -> Self::Future {
        // sentry
        let hub = sentry::Hub::current();
        let transaction = if let Some(name) = req.match_name() {
            Some(String::from(name))
        } else {
            req.match_pattern()
        };
        hub.configure_scope(|scope| {
            scope.set_transaction(transaction.as_deref());
        });

        let fut = self.service.call(req);

        Box::pin(async move {
            let response = fut.await.map_err(|error| {
                tracing::error!(r#type = "web.sentry.handler-error", ?error, "handler error");
                HandlerError::internal()
            })?;
            tracing::trace!(?response, "checking response for errors");

            match response.response().error() {
                None => (),
                Some(error) => {
                    tracing::trace!(?error, "Found error on response");
                    if let Some(handler_error) = error.as_error::<HandlerError>() {
                        hub.capture_event(Self::event_from_error(handler_error));
                    }
                }
            }

            Ok(response)
        })
    }
}