flareapp 0.1.0

Report errors, logs and traces from Rust applications to Flare.
Documentation
//! Reports the error that `main` returned. `#[flareapp::main]` uses this module.
//!
//! Rust only promises `Debug` for the error type of `main`, but most errors have
//! more to offer. The macro calls `.report()` on `&&&MainError(error)`, and Rust's
//! method lookup picks the first [`ReportMainError`] implementation that fits the
//! error type:
//!
//! 1. `Box<dyn Error>` and `anyhow::Error`, which do not implement `Error`
//!    themselves.
//! 2. Any type that implements `Error`.
//! 3. Any other type, with its `Debug` text as the message.
//!
//! Each step is implemented for one less `&` than the step before. Rust tries the
//! receiver with all three `&` first, then removes one at a time, so the most
//! specific step that applies wins. This trick is called "autoref
//! specialization".

use std::error::Error;
use std::fmt::Debug;

use flareapp_core::Report;

/// The error that `main` returned.
#[derive(Debug)]
pub struct MainError<'a, E: ?Sized>(pub &'a E);

/// Reports the error that `main` returned, in the best way its type allows.
pub trait ReportMainError {
    /// Reports the error.
    fn report(&self);
}

// Step 1: error types that do not implement `Error`, but hold one.
impl ReportMainError for &&MainError<'_, Box<dyn Error>> {
    #[track_caller]
    fn report(&self) {
        report_boxed(self.0.as_ref());
    }
}

impl ReportMainError for &&MainError<'_, Box<dyn Error + Send + Sync>> {
    #[track_caller]
    fn report(&self) {
        report_boxed(self.0.as_ref());
    }
}

#[cfg(feature = "anyhow")]
impl ReportMainError for &&MainError<'_, anyhow::Error> {
    #[track_caller]
    fn report(&self) {
        flareapp_anyhow::report(self.0);
    }
}

/// Reports a boxed error. The type of a boxed error is hidden, so the report comes
/// from [`Report::from_erased_error`].
#[track_caller]
fn report_boxed(error: &(dyn Error + 'static)) {
    crate::capture_and_send(
        |location| Report::from_erased_error(error, location),
        |_| {},
    );
}

// Step 2: types that implement `Error`.
impl<E: Error + ?Sized> ReportMainError for &MainError<'_, E> {
    #[track_caller]
    fn report(&self) {
        crate::report_error(self.0);
    }
}

// Step 3: any other type, which `main` requires to implement `Debug`.
impl<E: Debug + ?Sized> ReportMainError for MainError<'_, E> {
    #[track_caller]
    fn report(&self) {
        crate::capture_and_send(
            |location| {
                Report::new(
                    std::any::type_name::<E>(),
                    format!("{:?}", self.0),
                    location,
                )
            },
            |_| {},
        );
    }
}

/// Reports the error that `main` returned. `#[flareapp::main]` calls this macro.
#[doc(hidden)]
#[macro_export]
macro_rules! __report_main_error {
    ($error:expr) => {{
        use $crate::__private::ReportMainError as _;
        (&&&$crate::__private::MainError($error)).report();
    }};
}

#[cfg(test)]
#[cfg(feature = "macros")]
mod tests {
    use std::error::Error;
    use std::sync::LazyLock;

    use serde_json::Value;

    use flareapp_core::Config;
    use flareapp_core::test_support::{self, FakeTransport};

    static TRANSPORT: LazyLock<FakeTransport> = LazyLock::new(FakeTransport::default);

    fn test_config() -> Config {
        Config::new().api_key("secret").transport(TRANSPORT.clone())
    }

    /// Runs `main`, then returns the reports it sent.
    fn reports_of<T, F: FnOnce() -> T>(main: F) -> Vec<Value> {
        let _serial = test_support::serial();
        TRANSPORT.clear();

        main();

        TRANSPORT.bodies("/v1/errors")
    }

    /// Asserts that no frame of the reporting code is left in `frames`. The tests
    /// live in the `flareapp` crate, so their own frames are removed too.
    fn assert_no_reporting_frames(frames: &Value) {
        for frame in frames.as_array().unwrap() {
            let method = frame["method"].as_str().unwrap_or_default();
            assert!(
                !method.starts_with("report"),
                "reporting frame left in the stack trace: {method}"
            );
        }
    }

    #[derive(Debug)]
    #[expect(dead_code, reason = "the code is only read through `Debug`")]
    struct ExitCode(u8);

    #[test]
    fn reports_a_std_error_returned_from_main() {
        #[crate::main(crate = "crate", config = test_config)]
        fn main() -> Result<(), std::io::Error> {
            Err(std::io::Error::other("disk full"))
        }

        let reports = reports_of(main);

        assert_eq!(reports.len(), 1);
        let class = reports[0]["exceptionClass"].as_str().unwrap();
        assert!(class.ends_with("io::error::Error"), "{class}");
        assert_eq!(reports[0]["message"], "disk full");
    }

    #[test]
    fn reports_a_boxed_error_returned_from_main() {
        #[crate::main(crate = "crate", config = test_config)]
        fn main() -> Result<(), Box<dyn Error>> {
            Err(std::io::Error::other("disk full"))?;

            Ok(())
        }

        let reports = reports_of(main);

        let class = reports[0]["exceptionClass"].as_str().unwrap();
        assert!(class.ends_with("io::error::Error"), "{class}");
    }

    #[test]
    fn reports_the_debug_text_of_other_error_types() {
        #[crate::main(crate = "crate", config = test_config)]
        fn main() -> Result<(), ExitCode> {
            Err(ExitCode(3))
        }

        let reports = reports_of(main);

        let class = reports[0]["exceptionClass"].as_str().unwrap();
        assert!(class.ends_with("ExitCode"), "{class}");
        assert_eq!(reports[0]["message"], "ExitCode(3)");
    }

    #[test]
    fn the_stack_trace_starts_at_the_main_attribute() {
        let attribute_line = line!() + 1;
        #[crate::main(crate = "crate", config = test_config)]
        fn main() -> Result<(), ExitCode> {
            Err(ExitCode(3))
        }

        let reports = reports_of(main);
        let frames = &reports[0]["stacktrace"];

        assert_eq!(frames[0]["lineNumber"], attribute_line);
        assert_no_reporting_frames(frames);
    }

    #[test]
    fn the_stack_trace_of_a_boxed_error_starts_at_the_main_attribute() {
        let attribute_line = line!() + 1;
        #[crate::main(crate = "crate", config = test_config)]
        fn main() -> Result<(), Box<dyn Error>> {
            Err(std::io::Error::other("disk full"))?;

            Ok(())
        }

        let reports = reports_of(main);
        let frames = &reports[0]["stacktrace"];

        assert_eq!(frames[0]["lineNumber"], attribute_line);
        assert_no_reporting_frames(frames);
    }

    #[test]
    fn sends_nothing_when_main_succeeds() {
        #[crate::main(crate = "crate", config = test_config)]
        fn main() -> Result<(), std::io::Error> {
            Ok(())
        }

        assert_eq!(reports_of(main), Vec::<Value>::new());
    }

    #[test]
    fn keeps_flare_running_for_a_main_without_a_return_type() {
        #[crate::main(crate = "crate", config = test_config, environment = "testing")]
        fn main() {
            crate::report_message("still running", crate::Level::Info);
        }

        let reports = reports_of(main);

        assert_eq!(reports[0]["message"], "still running");
        assert_eq!(reports[0]["attributes"]["service.stage"], "testing");
    }
}