mod encode;
use std::any::type_name;
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;
use std::io;
use std::panic::{self, AssertUnwindSafe, Location};
use std::slice;
use std::sync::Arc;
use serde_json::Value;
use flareapp_otlp::now_unix_nanos;
pub(crate) use self::encode::fields_to_json;
use crate::debug::flare_debug;
use crate::entry_point::{EntryPoint, current_span_entry_point, resolve_entry_point};
use crate::level::Level;
use crate::scope::Scope;
use crate::source_path;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct ReportId(u128);
const UUID_VERSION_BITS: u128 = 0xf << 76;
const UUID_VERSION_4: u128 = 0x4 << 76;
const UUID_VARIANT_BITS: u128 = 0x3 << 62;
const UUID_VARIANT_STANDARD: u128 = 0x2 << 62;
impl ReportId {
fn random() -> Self {
let id = fastrand::u128(..);
let id = (id & !UUID_VERSION_BITS) | UUID_VERSION_4;
let id = (id & !UUID_VARIANT_BITS) | UUID_VARIANT_STANDARD;
Self(id)
}
}
impl fmt::Display for ReportId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let id = self.0;
write!(
f,
"{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
id >> 96,
(id >> 80) & 0xffff,
(id >> 64) & 0xffff,
(id >> 48) & 0xffff,
id & 0xffff_ffff_ffff,
)
}
}
impl fmt::Debug for ReportId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ReportId({self})")
}
}
#[expect(
clippy::struct_field_names,
reason = "field names mirror Flare's frame format"
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Frame {
pub file: String,
pub line_number: u32,
pub column_number: Option<u32>,
pub method: Option<String>,
pub class: Option<String>,
pub is_application_frame: bool,
pub instruction_addr: Option<usize>,
}
impl Frame {
pub fn from_location(location: &Location<'_>) -> Self {
Self {
file: location.file().to_owned(),
line_number: location.line(),
column_number: Some(location.column()),
method: None,
class: None,
is_application_frame: true,
instruction_addr: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DebugImage {
pub debug_id: String,
pub image_addr: usize,
pub image_size: usize,
pub code_file: Option<String>,
}
#[derive(Debug, Default)]
pub struct StackTrace {
pub frames: Vec<Frame>,
pub debug_images: Vec<DebugImage>,
}
pub trait ResolveFrames: Send + fmt::Debug {
fn resolve(self: Box<Self>, location: &Frame) -> StackTrace;
}
#[derive(Debug)]
pub struct Report {
id: ReportId,
exception_class: String,
message: String,
level: Option<Level>,
handled: bool,
seen_at_unix_nano: u64,
location: Frame,
frames: Option<Box<dyn ResolveFrames>>,
context: BTreeMap<String, Value>,
attributes: BTreeMap<String, Value>,
scope: Scope,
pub(crate) entry_point: Option<EntryPoint>,
application_path: Option<String>,
}
impl Report {
pub fn new<C, M>(exception_class: C, message: M, location: &Location<'_>) -> Self
where
C: Into<String>,
M: Into<String>,
{
let location = Frame::from_location(location);
Self {
id: ReportId::random(),
exception_class: exception_class.into(),
message: message.into(),
level: None,
handled: true,
seen_at_unix_nano: now_unix_nanos(),
location,
frames: None,
context: BTreeMap::new(),
attributes: BTreeMap::new(),
scope: Scope::default(),
entry_point: None,
application_path: None,
}
}
pub fn from_error<E: ReportableError + ?Sized>(error: &E, location: &Location<'_>) -> Self {
Self::new(exception_class(error), error.to_string(), location)
}
pub fn from_erased_error(error: &(dyn Error + 'static), location: &Location<'_>) -> Self {
let class =
erased_exception_class(error).unwrap_or_else(|| FALLBACK_EXCEPTION_CLASS.to_owned());
Self::new(class, error.to_string(), location)
}
pub fn from_message<M: Into<String>>(
message: M,
level: Level,
location: &Location<'_>,
) -> Self {
let mut report = Self::new("Log", message, location);
report.level = Some(level);
report
}
pub fn id(&self) -> ReportId {
self.id
}
pub fn exception_class(&self) -> &str {
&self.exception_class
}
pub fn set_exception_class<C: Into<String>>(&mut self, exception_class: C) {
self.exception_class = exception_class.into();
}
pub fn message(&self) -> &str {
&self.message
}
pub fn handled(&self) -> bool {
self.handled
}
pub fn set_handled(&mut self, handled: bool) {
self.handled = handled;
}
pub fn set_context<K: Into<String>, V: Into<Value>>(&mut self, key: K, value: V) {
self.context.insert(key.into(), value.into());
}
pub fn set_attribute<K: Into<String>, V: Into<Value>>(&mut self, key: K, value: V) {
self.attributes.insert(key.into(), value.into());
}
pub fn set_location(&mut self, location: Frame) {
self.location = location;
}
pub fn set_frames<R: ResolveFrames + 'static>(&mut self, frames: R) {
self.frames = Some(Box::new(frames));
}
pub(crate) fn attach(
&mut self,
scope: Scope,
application_path: Option<String>,
workspace_root: Option<&str>,
) {
self.scope = scope;
self.application_path = application_path;
if self.location.is_application_frame {
self.location.file = source_path::absolute(workspace_root, &self.location.file);
}
}
pub(crate) fn resolve_entry_point(&mut self) {
if self.entry_point.is_none() {
self.entry_point = Some(resolve_entry_point(current_span_entry_point));
}
}
pub(crate) fn resolve_frames(mut self, debug: bool) -> ResolvedReport {
let stack_trace = self
.frames
.take()
.map_or_else(StackTrace::default, |frames| {
panic::catch_unwind(AssertUnwindSafe(|| frames.resolve(&self.location)))
.unwrap_or_else(|_| {
flare_debug!(
debug,
WARN,
"resolving the stack trace panicked, so the only frame is the report location"
);
StackTrace::default()
})
});
ResolvedReport {
report: self,
stack_trace,
}
}
}
#[derive(Debug)]
pub(crate) struct ResolvedReport {
report: Report,
stack_trace: StackTrace,
}
impl ResolvedReport {
fn frames(&self) -> &[Frame] {
if self.stack_trace.frames.is_empty() {
slice::from_ref(&self.report.location)
} else {
&self.stack_trace.frames
}
}
fn debug_images(&self) -> &[DebugImage] {
&self.stack_trace.debug_images
}
}
pub(crate) const FALLBACK_EXCEPTION_CLASS: &str = "Error";
pub trait ReportableError: Error + sealed::Sealed {
fn as_dyn_error(&self) -> &(dyn Error + 'static);
}
impl<E: Error + 'static> ReportableError for E {
fn as_dyn_error(&self) -> &(dyn Error + 'static) {
self
}
}
impl ReportableError for dyn Error + 'static {
fn as_dyn_error(&self) -> &(dyn Error + 'static) {
self
}
}
impl ReportableError for dyn Error + Send + 'static {
fn as_dyn_error(&self) -> &(dyn Error + 'static) {
self
}
}
impl ReportableError for dyn Error + Send + Sync + 'static {
fn as_dyn_error(&self) -> &(dyn Error + 'static) {
self
}
}
mod sealed {
use std::error::Error;
pub trait Sealed {}
impl<E: Error + 'static> Sealed for E {}
impl Sealed for dyn Error + 'static {}
impl Sealed for dyn Error + Send + 'static {}
impl Sealed for dyn Error + Send + Sync + 'static {}
}
fn exception_class<E: ReportableError + ?Sized>(error: &E) -> String {
let type_name = inner_type_name(type_name::<E>());
if !type_name.starts_with("dyn ") {
return type_name.to_owned();
}
erased_exception_class(error.as_dyn_error())
.unwrap_or_else(|| FALLBACK_EXCEPTION_CLASS.to_owned())
}
fn inner_type_name(mut name: &str) -> &str {
let wrappers =
[type_name::<Box<()>>(), type_name::<Arc<()>>()].map(|wrapper| wrapper.strip_suffix("()>"));
while let Some(inner) = name.strip_prefix('&').or_else(|| {
wrappers
.iter()
.flatten()
.find_map(|prefix| name.strip_prefix(prefix)?.strip_suffix('>'))
}) {
name = inner;
}
name
}
pub fn erased_exception_class(error: &(dyn Error + 'static)) -> Option<String> {
let error = without_arcs(error);
if error.is::<io::Error>() {
return Some(type_name::<io::Error>().to_owned());
}
debug_name(&format!("{error:?}")).map(str::to_owned)
}
fn without_arcs<'a>(mut error: &'a (dyn Error + 'static)) -> &'a (dyn Error + 'static) {
loop {
error = if let Some(arc) = error.downcast_ref::<Arc<dyn Error + Send + Sync>>() {
arc.as_ref()
} else if let Some(arc) = error.downcast_ref::<Arc<dyn Error + Send>>() {
arc.as_ref()
} else if let Some(arc) = error.downcast_ref::<Arc<dyn Error>>() {
arc.as_ref()
} else {
return error;
};
}
}
fn debug_name(debug: &str) -> Option<&str> {
let is_name_character = |character: char| character.is_alphanumeric() || character == '_';
if !debug.starts_with(is_name_character) {
return None;
}
let mut rest = debug.trim_start_matches(is_name_character);
while let Some(after) = rest.strip_prefix("::")
&& after.starts_with(is_name_character)
{
rest = after.trim_start_matches(is_name_character);
}
debug.get(..debug.len() - rest.len())
}
#[cfg(test)]
mod tests {
use std::io;
use std::path::Path;
use super::*;
#[derive(Debug)]
struct OrderFailed {
order_id: u32,
}
impl fmt::Display for OrderFailed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "order {} failed", self.order_id)
}
}
impl Error for OrderFailed {}
#[test]
fn report_ids_are_uuid_v4() {
let id = ReportId::random().to_string();
assert_eq!(id.len(), 36);
assert_eq!(id.chars().nth(14), Some('4'));
assert!(matches!(id.chars().nth(19), Some('8' | '9' | 'a' | 'b')));
}
#[test]
fn uses_the_type_name_as_exception_class() {
assert_eq!(
exception_class(&OrderFailed { order_id: 7 }),
"flareapp_core::report::tests::OrderFailed"
);
}
#[test]
fn a_static_reference_to_an_error_has_the_class_of_the_error() {
static ERROR: OrderFailed = OrderFailed { order_id: 7 };
static REFERENCE: &OrderFailed = &ERROR;
assert_eq!(exception_class(&REFERENCE), exception_class(&ERROR));
assert_eq!(exception_class(&&REFERENCE), exception_class(&ERROR));
}
#[test]
fn an_error_in_a_box_or_an_arc_has_the_class_of_the_error() {
let expected = exception_class(&OrderFailed { order_id: 7 });
let boxed = Box::new(OrderFailed { order_id: 7 });
let shared = Arc::new(OrderFailed { order_id: 7 });
let both = Arc::new(Box::new(OrderFailed { order_id: 7 }));
assert_eq!(exception_class(&boxed), expected);
assert_eq!(exception_class(&shared), expected);
assert_eq!(exception_class(&both), expected);
}
#[test]
fn an_arc_of_a_dyn_error_has_the_debug_name() {
let error: Arc<dyn Error + Send + Sync> = Arc::new(OrderFailed { order_id: 7 });
assert_eq!(exception_class(&error), "OrderFailed");
}
#[test]
fn a_reference_to_a_dyn_error_has_the_debug_name() {
let error: &dyn Error = &OrderFailed { order_id: 7 };
assert_eq!(exception_class(&error), "OrderFailed");
}
#[test]
fn from_error_uses_the_exception_class_of_the_error() {
let error = OrderFailed { order_id: 7 };
let shared = Arc::new(OrderFailed { order_id: 7 });
let as_dyn: &(dyn Error + 'static) = &error;
let by_value = Report::from_error(&error, Location::caller());
let by_arc = Report::from_error(&shared, Location::caller());
let by_dyn = Report::from_error(as_dyn, Location::caller());
assert_eq!(by_arc.exception_class(), by_value.exception_class());
assert_eq!(by_dyn.exception_class(), "OrderFailed");
}
#[test]
fn io_errors_are_named_after_their_std_type() {
let error = io::Error::other("disk full");
assert!(exception_class(&error).ends_with("io::error::Error"));
}
#[test]
fn uses_the_debug_name_for_dyn_errors() {
let error: Box<dyn Error> = Box::new(OrderFailed { order_id: 7 });
assert_eq!(exception_class(&*error), "OrderFailed");
}
#[test]
fn a_dyn_io_error_keeps_its_type_name() {
let error: Box<dyn Error> = Box::new(io::Error::other("disk full"));
let class = exception_class(error.as_ref());
assert!(class.ends_with("io::error::Error"), "{class}");
}
#[test]
fn an_io_error_in_an_arc_of_a_dyn_error_keeps_its_type_name() {
let error: Arc<dyn Error + Send + Sync> = Arc::new(io::Error::other("disk full"));
let class = exception_class(&error);
assert!(class.ends_with("io::error::Error"), "{class}");
}
#[test]
fn reports_of_dyn_io_errors_keep_their_type_name() {
let error: Box<dyn Error + Send + Sync> = Box::new(io::Error::other("disk full"));
let report = Report::from_error(error.as_ref(), Location::caller());
let class = report.exception_class();
assert!(class.ends_with("io::error::Error"), "{class}");
}
#[test]
fn hidden_io_errors_in_an_arc_keep_their_type_name() {
let error: Arc<dyn Error + Send + Sync> = Arc::new(io::Error::other("disk full"));
let class = erased_exception_class(&error).unwrap();
assert!(class.ends_with("io::error::Error"), "{class}");
}
#[test]
fn hidden_io_errors_keep_their_type_name() {
let error: Box<dyn Error> = Box::new(io::Error::other("disk full"));
let class = erased_exception_class(error.as_ref()).unwrap();
assert!(class.ends_with("io::error::Error"));
}
#[test]
fn other_hidden_errors_get_their_debug_name() {
let error: Box<dyn Error> = Box::new(OrderFailed { order_id: 7 });
let class = erased_exception_class(error.as_ref());
assert_eq!(class.as_deref(), Some("OrderFailed"));
}
#[test]
fn hidden_errors_keep_the_path_their_debug_output_starts_with() {
struct RequestFailed;
impl fmt::Debug for RequestFailed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("reqwest::Error")
.field("kind", &"Request")
.finish()
}
}
impl fmt::Display for RequestFailed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("error sending request")
}
}
impl Error for RequestFailed {}
assert_eq!(
erased_exception_class(&RequestFailed).as_deref(),
Some("reqwest::Error")
);
}
#[test]
fn debug_names_end_where_the_name_ends() {
assert_eq!(
debug_name("Database(SqliteError { code: 1 })"),
Some("Database")
);
assert_eq!(debug_name("Error: boom"), Some("Error"));
assert_eq!(debug_name("my_app::Error::"), Some("my_app::Error"));
}
#[test]
fn debug_output_that_starts_without_a_name_has_no_debug_name() {
assert_eq!(debug_name("\"plain message\""), None);
assert_eq!(debug_name("::Error"), None);
assert_eq!(debug_name(""), None);
}
#[test]
fn hidden_errors_without_a_debug_name_have_no_class() {
let error: Box<dyn Error> = "plain message".into();
assert_eq!(erased_exception_class(error.as_ref()), None);
}
#[test]
fn reports_of_hidden_io_errors_keep_their_type_name() {
let error: Box<dyn Error> = Box::new(io::Error::other("disk full"));
let report = Report::from_erased_error(error.as_ref(), Location::caller());
let class = report.exception_class();
assert!(class.ends_with("io::error::Error"), "{class}");
}
#[test]
fn reports_of_hidden_errors_without_a_debug_name_are_named_error() {
let error: Box<dyn Error> = "plain message".into();
let report = Report::from_erased_error(error.as_ref(), Location::caller());
assert_eq!(report.exception_class(), "Error");
}
#[test]
fn reports_of_hidden_errors_have_the_display_output_as_message() {
let error: Box<dyn Error> = Box::new(OrderFailed { order_id: 7 });
let report = Report::from_erased_error(error.as_ref(), Location::caller());
assert_eq!(report.message(), "order 7 failed");
}
#[test]
fn messages_are_logs() {
let report = Report::from_message("Stock low", Level::Warning, Location::caller());
assert_eq!(report.exception_class(), "Log");
assert_eq!(report.level, Some(Level::Warning));
}
#[test]
fn falls_back_to_the_report_location_without_frames() {
#[derive(Debug)]
struct NoFrames;
impl ResolveFrames for NoFrames {
fn resolve(self: Box<Self>, _location: &Frame) -> StackTrace {
StackTrace::default()
}
}
let mut report = Report::new("Panic", "boom", Location::caller());
report.set_frames(NoFrames);
let resolved = report.resolve_frames(false);
assert_eq!(resolved.frames().len(), 1);
assert!(resolved.frames()[0].file.ends_with("mod.rs"));
}
#[test]
fn a_panic_while_resolving_frames_does_not_stop_the_worker_thread() {
#[derive(Debug)]
struct PanicsOnResolve;
impl ResolveFrames for PanicsOnResolve {
fn resolve(self: Box<Self>, _location: &Frame) -> StackTrace {
panic!("cannot read the debug info");
}
}
let transport = crate::test_support::run(
|config| config,
|| {
let client = crate::current().unwrap();
let mut first = Report::new("First", "one", Location::caller());
first.set_frames(PanicsOnResolve);
client.send_report(first);
client.send_report(Report::new("Second", "two", Location::caller()));
},
);
let reports: Vec<Value> = transport
.requests()
.iter()
.filter(|request| request.signal == crate::transport::Signal::Errors)
.map(crate::test_support::json)
.collect();
let classes: Vec<&Value> = reports
.iter()
.map(|report| &report["exceptionClass"])
.collect();
assert_eq!(classes, ["First", "Second"]);
assert_eq!(reports[0]["stacktrace"].as_array().map(Vec::len), Some(1));
}
#[test]
fn a_report_without_a_stack_trace_has_no_debug_images() {
let report = Report::new("Panic", "boom", Location::caller());
assert_eq!(report.resolve_frames(false).debug_images(), []);
}
fn located_at(file: &str, is_application_frame: bool) -> Report {
let mut report = Report::new("Panic", "boom", Location::caller());
report.set_location(Frame {
file: file.to_owned(),
line_number: 12,
column_number: None,
method: None,
class: None,
is_application_frame,
instruction_addr: None,
});
report
}
#[test]
fn the_report_location_gets_the_workspace_root() {
let mut report = located_at("crates/app/src/main.rs", true);
report.attach(Scope::default(), None, Some("/code/shop"));
let resolved = report.resolve_frames(false);
assert_eq!(
Path::new(&resolved.frames()[0].file),
Path::new("/code/shop/crates/app/src/main.rs")
);
}
#[test]
fn an_unknown_location_keeps_its_path() {
let mut report = located_at("<unknown>", false);
report.attach(Scope::default(), None, Some("/code/shop"));
assert_eq!(report.resolve_frames(false).frames()[0].file, "<unknown>");
}
#[test]
fn an_absolute_location_keeps_its_path() {
let mut report = located_at("/cargo/registry/src/axum-0.8.9/src/lib.rs", true);
report.attach(Scope::default(), None, Some("/code/shop"));
assert_eq!(
report.resolve_frames(false).frames()[0].file,
"/cargo/registry/src/axum-0.8.9/src/lib.rs"
);
}
}