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
use std::{
    error::Error,
    fmt::{self, Debug},
    ops::Deref,
    panic::Location,
};

use backtrace::Backtrace;
use chrono::{DateTime, Local};
use http::Extensions;
use once_cell::sync::OnceCell;
use parking_lot::RwLock;

use crate::Problem;

static REPORTER: OnceCell<Box<dyn ProblemReporter + Send + Sync>> = OnceCell::new();

#[track_caller]
pub(crate) fn capture_handler(error: &(dyn Error + 'static)) -> Box<dyn eyre::EyreHandler> {
    let mut report = Box::default();

    if let Some(reporter) = global_reporter() {
        reporter.capture_error_context(&mut report, error);
    }

    report
}

pub(crate) fn global_reporter() -> Option<&'static dyn ProblemReporter> {
    REPORTER.get().map(|r| &**r as &'static dyn ProblemReporter)
}

/// Sets the current global reporter.
///
/// # Panics
///
/// This function panics if it is called twice.
pub fn set_global_reporter<R>(reporter: R)
where
    R: ProblemReporter + Send + Sync + 'static,
{
    // Can't use `.expect` as `R` is not (and should not) be `Debug`.
    if REPORTER.set(Box::new(reporter)).is_err() {
        panic!("Global problem reporter set twice! Did you call `problem::reporter::set_global_reporter` twice?");
    }
}

/// A type responsible for capturing and report [`Problem`] errors.
///
/// The crate doesn't provide a default implementation of this trait,
/// as how you report your service's errors depends on your infrastructure.
pub trait ProblemReporter {
    /// Capture extra information about the error context and saves it
    /// inside the given report.
    ///
    /// Note that this will be called even for client-related errors,
    /// like NotFound or UnprocessableEntity, during the error _creation_
    /// (this is why we don't pass a [`Problem`] instance here). So try
    /// to be conservative on what you do in this method to prevent making
    /// error handling an expensive operation.
    fn capture_error_context(&'static self, report: &mut Report, error: &(dyn Error + 'static));

    /// Says if we should report the error or not.
    fn should_report_error(&'static self, problem: &Problem) -> bool;

    /// Reports the error.
    ///
    /// This will only be called if [`ProblemReporter::should_report_error`]
    /// returns `true`.
    fn report_error(&'static self, problem: &Problem);
}

/// Location dependent problem report content.
///
/// This type contains information about a given error, primarily the
/// backtrace, location and timestamp of the error, although reporters may
/// include extra information.
///
/// Note that the [`Backtrace`] is NOT resolved during creation, to prevent
/// wasting time on the creation of non-reported errors.
pub struct Report {
    backtrace: RwLock<Backtrace>,
    location: &'static Location<'static>,
    timestamp: DateTime<Local>,
    extensions: Extensions,
}

impl Default for Report {
    #[track_caller]
    fn default() -> Self {
        Self {
            backtrace: RwLock::new(Backtrace::new_unresolved()),
            location: Location::caller(),
            timestamp: Local::now(),
            extensions: Extensions::new(),
        }
    }
}

impl Report {
    /// Resolves and returns a reference to the error backtrace.
    pub fn backtrace(&self) -> impl Deref<Target = Backtrace> + '_ {
        self.backtrace.write().resolve();
        self.backtrace.read()
    }

    /// Returns a reference to the _unresolved_ backtrace.
    #[inline(always)]
    pub fn backtrace_unresolved(&self) -> impl Deref<Target = Backtrace> + '_ {
        self.backtrace.read()
    }

    /// Returns the location where the error happened.
    ///
    /// We try our best to fetch the correct location of the error by
    /// marking everything that may create a [`Problem`] with `#[track_caller]`.
    #[inline(always)]
    pub fn location(&self) -> &'static Location<'static> {
        self.location
    }

    /// Returns the timestamp of when the error was captured.
    #[inline(always)]
    pub fn timestamp(&self) -> DateTime<Local> {
        self.timestamp
    }

    /// Inserts an arbitrary data into the report.
    #[inline(always)]
    pub fn insert<T: Send + Sync + 'static>(&mut self, val: T) {
        self.extensions.insert(val);
    }

    /// Get data inserted in the report via [`Self::insert`].
    ///
    /// Returns `None` if no data with the given type is found.
    #[inline(always)]
    pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
        self.extensions.get()
    }
}

impl eyre::EyreHandler for Report {
    fn debug(&self, error: &(dyn Error + 'static), f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Error at {} ({}, {}): ",
            self.location.file(),
            self.location.line(),
            self.location.column()
        )?;

        write!(f, "{}", error)?;

        // Causes.
        if error.source().is_some() {
            writeln!(f, "\n\nCaused by:")?;

            let mut curr = error.source();
            let mut idx = 0;
            while let Some(err) = curr {
                writeln!(f, "  {idx}: {err}")?;
                curr = err.source();
                idx += 1;
            }
        }

        // TODO: print backtrace based on backtrace style.
        // TODO(internal): Open-Source Backtrace cleaning solution.
        //
        // Initially, this used to print a cleaned-up version of the
        // backtrace, but the process had very TM-specific filters and was
        // specific to a format that our error reporting infrastructure understood.
        //
        // We'll one day open source it when we've a more general solution to
        // the problem, as this is definitively _extremely_ useful.
        (*self.backtrace()).fmt(f)
    }

    fn track_caller(&mut self, location: &'static Location<'static>) {
        self.location = location;
    }
}

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

    #[test]
    fn test_report() {
        let rep = Report::default();

        assert_eq!(rep.location().line(), line!() - 2);
        assert_eq!(rep.location().file(), file!());

        std::thread::sleep(std::time::Duration::from_millis(10));

        assert!(rep.timestamp() < Local::now());
        assert!(!rep.backtrace_unresolved().frames().is_empty());

        let symbols_count = rep
            .backtrace()
            .frames()
            .iter()
            .flat_map(|f| f.symbols())
            .count();

        assert!(symbols_count > 0);
    }

    #[test]
    fn test_report_extensions() {
        let mut rep = Report::default();

        rep.insert(2usize);

        assert_eq!(rep.get(), Some(&2usize));

        assert!(rep.get::<String>().is_none());
    }
}