1mod encode;
4
5use std::any::type_name;
6use std::collections::BTreeMap;
7use std::error::Error;
8use std::fmt;
9use std::io;
10use std::panic::{self, AssertUnwindSafe, Location};
11use std::slice;
12use std::sync::Arc;
13
14use serde_json::Value;
15
16use flareapp_otlp::now_unix_nanos;
17
18pub(crate) use self::encode::fields_to_json;
19use crate::debug::flare_debug;
20use crate::entry_point::{EntryPoint, current_span_entry_point, resolve_entry_point};
21use crate::level::Level;
22use crate::scope::Scope;
23use crate::source_path;
24
25#[derive(Clone, Copy, PartialEq, Eq, Hash)]
29pub struct ReportId(u128);
30
31const UUID_VERSION_BITS: u128 = 0xf << 76;
33
34const UUID_VERSION_4: u128 = 0x4 << 76;
36
37const UUID_VARIANT_BITS: u128 = 0x3 << 62;
39
40const UUID_VARIANT_STANDARD: u128 = 0x2 << 62;
42
43impl ReportId {
44 fn random() -> Self {
46 let id = fastrand::u128(..);
47 let id = (id & !UUID_VERSION_BITS) | UUID_VERSION_4;
48 let id = (id & !UUID_VARIANT_BITS) | UUID_VARIANT_STANDARD;
49
50 Self(id)
51 }
52}
53
54impl fmt::Display for ReportId {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 let id = self.0;
57
58 write!(
59 f,
60 "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
61 id >> 96,
62 (id >> 80) & 0xffff,
63 (id >> 64) & 0xffff,
64 (id >> 48) & 0xffff,
65 id & 0xffff_ffff_ffff,
66 )
67 }
68}
69
70impl fmt::Debug for ReportId {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 write!(f, "ReportId({self})")
73 }
74}
75
76#[expect(
78 clippy::struct_field_names,
79 reason = "field names mirror Flare's frame format"
80)]
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct Frame {
83 pub file: String,
85 pub line_number: u32,
87 pub column_number: Option<u32>,
89 pub method: Option<String>,
91 pub class: Option<String>,
93 pub is_application_frame: bool,
96 pub instruction_addr: Option<usize>,
100}
101
102impl Frame {
103 pub fn from_location(location: &Location<'_>) -> Self {
105 Self {
106 file: location.file().to_owned(),
107 line_number: location.line(),
108 column_number: Some(location.column()),
109 method: None,
110 class: None,
111 is_application_frame: true,
112 instruction_addr: None,
113 }
114 }
115}
116
117#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct DebugImage {
122 pub debug_id: String,
125 pub image_addr: usize,
127 pub image_size: usize,
129 pub code_file: Option<String>,
136}
137
138#[derive(Debug, Default)]
140pub struct StackTrace {
141 pub frames: Vec<Frame>,
143 pub debug_images: Vec<DebugImage>,
145}
146
147pub trait ResolveFrames: Send + fmt::Debug {
155 fn resolve(self: Box<Self>, location: &Frame) -> StackTrace;
161}
162
163#[derive(Debug)]
165pub struct Report {
166 id: ReportId,
167 exception_class: String,
168 message: String,
169 level: Option<Level>,
170 handled: bool,
171 seen_at_unix_nano: u64,
172 location: Frame,
175 frames: Option<Box<dyn ResolveFrames>>,
178 context: BTreeMap<String, Value>,
179 attributes: BTreeMap<String, Value>,
180 scope: Scope,
181 pub(crate) entry_point: Option<EntryPoint>,
186 application_path: Option<String>,
187}
188
189impl Report {
190 pub fn new<C, M>(exception_class: C, message: M, location: &Location<'_>) -> Self
217 where
218 C: Into<String>,
219 M: Into<String>,
220 {
221 let location = Frame::from_location(location);
222
223 Self {
224 id: ReportId::random(),
225 exception_class: exception_class.into(),
226 message: message.into(),
227 level: None,
228 handled: true,
229 seen_at_unix_nano: now_unix_nanos(),
230 location,
231 frames: None,
232 context: BTreeMap::new(),
233 attributes: BTreeMap::new(),
234 scope: Scope::default(),
235 entry_point: None,
236 application_path: None,
237 }
238 }
239
240 pub fn from_error<E: ReportableError + ?Sized>(error: &E, location: &Location<'_>) -> Self {
247 Self::new(exception_class(error), error.to_string(), location)
248 }
249
250 pub fn from_erased_error(error: &(dyn Error + 'static), location: &Location<'_>) -> Self {
257 let class =
258 erased_exception_class(error).unwrap_or_else(|| FALLBACK_EXCEPTION_CLASS.to_owned());
259
260 Self::new(class, error.to_string(), location)
261 }
262
263 pub fn from_message<M: Into<String>>(
265 message: M,
266 level: Level,
267 location: &Location<'_>,
268 ) -> Self {
269 let mut report = Self::new("Log", message, location);
270 report.level = Some(level);
271
272 report
273 }
274
275 pub fn id(&self) -> ReportId {
277 self.id
278 }
279
280 pub fn exception_class(&self) -> &str {
282 &self.exception_class
283 }
284
285 pub fn set_exception_class<C: Into<String>>(&mut self, exception_class: C) {
287 self.exception_class = exception_class.into();
288 }
289
290 pub fn message(&self) -> &str {
292 &self.message
293 }
294
295 pub fn handled(&self) -> bool {
297 self.handled
298 }
299
300 pub fn set_handled(&mut self, handled: bool) {
302 self.handled = handled;
303 }
304
305 pub fn set_context<K: Into<String>, V: Into<Value>>(&mut self, key: K, value: V) {
307 self.context.insert(key.into(), value.into());
308 }
309
310 pub fn set_attribute<K: Into<String>, V: Into<Value>>(&mut self, key: K, value: V) {
312 self.attributes.insert(key.into(), value.into());
313 }
314
315 pub fn set_location(&mut self, location: Frame) {
319 self.location = location;
320 }
321
322 pub fn set_frames<R: ResolveFrames + 'static>(&mut self, frames: R) {
324 self.frames = Some(Box::new(frames));
325 }
326
327 pub(crate) fn attach(
332 &mut self,
333 scope: Scope,
334 application_path: Option<String>,
335 workspace_root: Option<&str>,
336 ) {
337 self.scope = scope;
338 self.application_path = application_path;
339
340 if self.location.is_application_frame {
341 self.location.file = source_path::absolute(workspace_root, &self.location.file);
342 }
343 }
344
345 pub(crate) fn resolve_entry_point(&mut self) {
355 if self.entry_point.is_none() {
356 self.entry_point = Some(resolve_entry_point(current_span_entry_point));
357 }
358 }
359
360 pub(crate) fn resolve_frames(mut self, debug: bool) -> ResolvedReport {
370 let stack_trace = self
371 .frames
372 .take()
373 .map_or_else(StackTrace::default, |frames| {
374 panic::catch_unwind(AssertUnwindSafe(|| frames.resolve(&self.location)))
375 .unwrap_or_else(|_| {
376 flare_debug!(
377 debug,
378 WARN,
379 "resolving the stack trace panicked, so the only frame is the report location"
380 );
381
382 StackTrace::default()
383 })
384 });
385
386 ResolvedReport {
387 report: self,
388 stack_trace,
389 }
390 }
391}
392
393#[derive(Debug)]
398pub(crate) struct ResolvedReport {
399 report: Report,
400 stack_trace: StackTrace,
401}
402
403impl ResolvedReport {
404 fn frames(&self) -> &[Frame] {
407 if self.stack_trace.frames.is_empty() {
408 slice::from_ref(&self.report.location)
409 } else {
410 &self.stack_trace.frames
411 }
412 }
413
414 fn debug_images(&self) -> &[DebugImage] {
416 &self.stack_trace.debug_images
417 }
418}
419
420pub(crate) const FALLBACK_EXCEPTION_CLASS: &str = "Error";
422
423pub trait ReportableError: Error + sealed::Sealed {
439 fn as_dyn_error(&self) -> &(dyn Error + 'static);
442}
443
444impl<E: Error + 'static> ReportableError for E {
445 fn as_dyn_error(&self) -> &(dyn Error + 'static) {
446 self
447 }
448}
449
450impl ReportableError for dyn Error + 'static {
451 fn as_dyn_error(&self) -> &(dyn Error + 'static) {
452 self
453 }
454}
455
456impl ReportableError for dyn Error + Send + 'static {
457 fn as_dyn_error(&self) -> &(dyn Error + 'static) {
458 self
459 }
460}
461
462impl ReportableError for dyn Error + Send + Sync + 'static {
463 fn as_dyn_error(&self) -> &(dyn Error + 'static) {
464 self
465 }
466}
467
468mod sealed {
469 use std::error::Error;
470
471 pub trait Sealed {}
474
475 impl<E: Error + 'static> Sealed for E {}
476 impl Sealed for dyn Error + 'static {}
477 impl Sealed for dyn Error + Send + 'static {}
478 impl Sealed for dyn Error + Send + Sync + 'static {}
479}
480
481fn exception_class<E: ReportableError + ?Sized>(error: &E) -> String {
492 let type_name = inner_type_name(type_name::<E>());
493 if !type_name.starts_with("dyn ") {
494 return type_name.to_owned();
495 }
496
497 erased_exception_class(error.as_dyn_error())
498 .unwrap_or_else(|| FALLBACK_EXCEPTION_CLASS.to_owned())
499}
500
501fn inner_type_name(mut name: &str) -> &str {
508 let wrappers =
511 [type_name::<Box<()>>(), type_name::<Arc<()>>()].map(|wrapper| wrapper.strip_suffix("()>"));
512 while let Some(inner) = name.strip_prefix('&').or_else(|| {
513 wrappers
514 .iter()
515 .flatten()
516 .find_map(|prefix| name.strip_prefix(prefix)?.strip_suffix('>'))
517 }) {
518 name = inner;
519 }
520
521 name
522}
523
524pub fn erased_exception_class(error: &(dyn Error + 'static)) -> Option<String> {
533 let error = without_arcs(error);
534 if error.is::<io::Error>() {
535 return Some(type_name::<io::Error>().to_owned());
536 }
537
538 debug_name(&format!("{error:?}")).map(str::to_owned)
539}
540
541fn without_arcs<'a>(mut error: &'a (dyn Error + 'static)) -> &'a (dyn Error + 'static) {
546 loop {
547 error = if let Some(arc) = error.downcast_ref::<Arc<dyn Error + Send + Sync>>() {
548 arc.as_ref()
549 } else if let Some(arc) = error.downcast_ref::<Arc<dyn Error + Send>>() {
550 arc.as_ref()
551 } else if let Some(arc) = error.downcast_ref::<Arc<dyn Error>>() {
552 arc.as_ref()
553 } else {
554 return error;
555 };
556 }
557}
558
559fn debug_name(debug: &str) -> Option<&str> {
563 let is_name_character = |character: char| character.is_alphanumeric() || character == '_';
564 if !debug.starts_with(is_name_character) {
565 return None;
566 }
567
568 let mut rest = debug.trim_start_matches(is_name_character);
570 while let Some(after) = rest.strip_prefix("::")
571 && after.starts_with(is_name_character)
572 {
573 rest = after.trim_start_matches(is_name_character);
574 }
575
576 debug.get(..debug.len() - rest.len())
577}
578
579#[cfg(test)]
580mod tests {
581 use std::io;
582 use std::path::Path;
583
584 use super::*;
585
586 #[derive(Debug)]
587 struct OrderFailed {
588 order_id: u32,
589 }
590
591 impl fmt::Display for OrderFailed {
592 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
593 write!(f, "order {} failed", self.order_id)
594 }
595 }
596
597 impl Error for OrderFailed {}
598
599 #[test]
600 fn report_ids_are_uuid_v4() {
601 let id = ReportId::random().to_string();
602
603 assert_eq!(id.len(), 36);
604 assert_eq!(id.chars().nth(14), Some('4'));
605 assert!(matches!(id.chars().nth(19), Some('8' | '9' | 'a' | 'b')));
606 }
607
608 #[test]
609 fn uses_the_type_name_as_exception_class() {
610 assert_eq!(
611 exception_class(&OrderFailed { order_id: 7 }),
612 "flareapp_core::report::tests::OrderFailed"
613 );
614 }
615
616 #[test]
617 fn a_static_reference_to_an_error_has_the_class_of_the_error() {
618 static ERROR: OrderFailed = OrderFailed { order_id: 7 };
619 static REFERENCE: &OrderFailed = &ERROR;
620
621 assert_eq!(exception_class(&REFERENCE), exception_class(&ERROR));
622 assert_eq!(exception_class(&&REFERENCE), exception_class(&ERROR));
623 }
624
625 #[test]
626 fn an_error_in_a_box_or_an_arc_has_the_class_of_the_error() {
627 let expected = exception_class(&OrderFailed { order_id: 7 });
628
629 let boxed = Box::new(OrderFailed { order_id: 7 });
630 let shared = Arc::new(OrderFailed { order_id: 7 });
631 let both = Arc::new(Box::new(OrderFailed { order_id: 7 }));
632 assert_eq!(exception_class(&boxed), expected);
633 assert_eq!(exception_class(&shared), expected);
634 assert_eq!(exception_class(&both), expected);
635 }
636
637 #[test]
638 fn an_arc_of_a_dyn_error_has_the_debug_name() {
639 let error: Arc<dyn Error + Send + Sync> = Arc::new(OrderFailed { order_id: 7 });
640
641 assert_eq!(exception_class(&error), "OrderFailed");
642 }
643
644 #[test]
645 fn a_reference_to_a_dyn_error_has_the_debug_name() {
646 let error: &dyn Error = &OrderFailed { order_id: 7 };
647
648 assert_eq!(exception_class(&error), "OrderFailed");
649 }
650
651 #[test]
652 fn from_error_uses_the_exception_class_of_the_error() {
653 let error = OrderFailed { order_id: 7 };
654 let shared = Arc::new(OrderFailed { order_id: 7 });
655 let as_dyn: &(dyn Error + 'static) = &error;
656
657 let by_value = Report::from_error(&error, Location::caller());
658 let by_arc = Report::from_error(&shared, Location::caller());
659 let by_dyn = Report::from_error(as_dyn, Location::caller());
660
661 assert_eq!(by_arc.exception_class(), by_value.exception_class());
662 assert_eq!(by_dyn.exception_class(), "OrderFailed");
663 }
664
665 #[test]
666 fn io_errors_are_named_after_their_std_type() {
667 let error = io::Error::other("disk full");
668
669 assert!(exception_class(&error).ends_with("io::error::Error"));
672 }
673
674 #[test]
675 fn uses_the_debug_name_for_dyn_errors() {
676 let error: Box<dyn Error> = Box::new(OrderFailed { order_id: 7 });
677
678 assert_eq!(exception_class(&*error), "OrderFailed");
679 }
680
681 #[test]
682 fn a_dyn_io_error_keeps_its_type_name() {
683 let error: Box<dyn Error> = Box::new(io::Error::other("disk full"));
684
685 let class = exception_class(error.as_ref());
686
687 assert!(class.ends_with("io::error::Error"), "{class}");
688 }
689
690 #[test]
691 fn an_io_error_in_an_arc_of_a_dyn_error_keeps_its_type_name() {
692 let error: Arc<dyn Error + Send + Sync> = Arc::new(io::Error::other("disk full"));
693
694 let class = exception_class(&error);
695
696 assert!(class.ends_with("io::error::Error"), "{class}");
697 }
698
699 #[test]
700 fn reports_of_dyn_io_errors_keep_their_type_name() {
701 let error: Box<dyn Error + Send + Sync> = Box::new(io::Error::other("disk full"));
702
703 let report = Report::from_error(error.as_ref(), Location::caller());
704
705 let class = report.exception_class();
706 assert!(class.ends_with("io::error::Error"), "{class}");
707 }
708
709 #[test]
710 fn hidden_io_errors_in_an_arc_keep_their_type_name() {
711 let error: Arc<dyn Error + Send + Sync> = Arc::new(io::Error::other("disk full"));
712
713 let class = erased_exception_class(&error).unwrap();
714
715 assert!(class.ends_with("io::error::Error"), "{class}");
716 }
717
718 #[test]
719 fn hidden_io_errors_keep_their_type_name() {
720 let error: Box<dyn Error> = Box::new(io::Error::other("disk full"));
721
722 let class = erased_exception_class(error.as_ref()).unwrap();
723
724 assert!(class.ends_with("io::error::Error"));
725 }
726
727 #[test]
728 fn other_hidden_errors_get_their_debug_name() {
729 let error: Box<dyn Error> = Box::new(OrderFailed { order_id: 7 });
730
731 let class = erased_exception_class(error.as_ref());
732
733 assert_eq!(class.as_deref(), Some("OrderFailed"));
734 }
735
736 #[test]
738 fn hidden_errors_keep_the_path_their_debug_output_starts_with() {
739 struct RequestFailed;
740
741 impl fmt::Debug for RequestFailed {
742 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
743 f.debug_struct("reqwest::Error")
744 .field("kind", &"Request")
745 .finish()
746 }
747 }
748
749 impl fmt::Display for RequestFailed {
750 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
751 f.write_str("error sending request")
752 }
753 }
754
755 impl Error for RequestFailed {}
756
757 assert_eq!(
758 erased_exception_class(&RequestFailed).as_deref(),
759 Some("reqwest::Error")
760 );
761 }
762
763 #[test]
764 fn debug_names_end_where_the_name_ends() {
765 assert_eq!(
766 debug_name("Database(SqliteError { code: 1 })"),
767 Some("Database")
768 );
769 assert_eq!(debug_name("Error: boom"), Some("Error"));
770 assert_eq!(debug_name("my_app::Error::"), Some("my_app::Error"));
771 }
772
773 #[test]
774 fn debug_output_that_starts_without_a_name_has_no_debug_name() {
775 assert_eq!(debug_name("\"plain message\""), None);
776 assert_eq!(debug_name("::Error"), None);
777 assert_eq!(debug_name(""), None);
778 }
779
780 #[test]
781 fn hidden_errors_without_a_debug_name_have_no_class() {
782 let error: Box<dyn Error> = "plain message".into();
783
784 assert_eq!(erased_exception_class(error.as_ref()), None);
785 }
786
787 #[test]
788 fn reports_of_hidden_io_errors_keep_their_type_name() {
789 let error: Box<dyn Error> = Box::new(io::Error::other("disk full"));
790
791 let report = Report::from_erased_error(error.as_ref(), Location::caller());
792
793 let class = report.exception_class();
794 assert!(class.ends_with("io::error::Error"), "{class}");
795 }
796
797 #[test]
798 fn reports_of_hidden_errors_without_a_debug_name_are_named_error() {
799 let error: Box<dyn Error> = "plain message".into();
800
801 let report = Report::from_erased_error(error.as_ref(), Location::caller());
802
803 assert_eq!(report.exception_class(), "Error");
804 }
805
806 #[test]
807 fn reports_of_hidden_errors_have_the_display_output_as_message() {
808 let error: Box<dyn Error> = Box::new(OrderFailed { order_id: 7 });
809
810 let report = Report::from_erased_error(error.as_ref(), Location::caller());
811
812 assert_eq!(report.message(), "order 7 failed");
813 }
814
815 #[test]
816 fn messages_are_logs() {
817 let report = Report::from_message("Stock low", Level::Warning, Location::caller());
818
819 assert_eq!(report.exception_class(), "Log");
820 assert_eq!(report.level, Some(Level::Warning));
821 }
822
823 #[test]
824 fn falls_back_to_the_report_location_without_frames() {
825 #[derive(Debug)]
826 struct NoFrames;
827
828 impl ResolveFrames for NoFrames {
829 fn resolve(self: Box<Self>, _location: &Frame) -> StackTrace {
830 StackTrace::default()
831 }
832 }
833
834 let mut report = Report::new("Panic", "boom", Location::caller());
835 report.set_frames(NoFrames);
836 let resolved = report.resolve_frames(false);
837
838 assert_eq!(resolved.frames().len(), 1);
839 assert!(resolved.frames()[0].file.ends_with("mod.rs"));
840 }
841
842 #[test]
843 fn a_panic_while_resolving_frames_does_not_stop_the_worker_thread() {
844 #[derive(Debug)]
845 struct PanicsOnResolve;
846
847 impl ResolveFrames for PanicsOnResolve {
848 fn resolve(self: Box<Self>, _location: &Frame) -> StackTrace {
849 panic!("cannot read the debug info");
850 }
851 }
852
853 let transport = crate::test_support::run(
854 |config| config,
855 || {
856 let client = crate::current().unwrap();
857 let mut first = Report::new("First", "one", Location::caller());
858 first.set_frames(PanicsOnResolve);
859 client.send_report(first);
860 client.send_report(Report::new("Second", "two", Location::caller()));
861 },
862 );
863
864 let reports: Vec<Value> = transport
865 .requests()
866 .iter()
867 .filter(|request| request.signal == crate::transport::Signal::Errors)
868 .map(crate::test_support::json)
869 .collect();
870 let classes: Vec<&Value> = reports
871 .iter()
872 .map(|report| &report["exceptionClass"])
873 .collect();
874 assert_eq!(classes, ["First", "Second"]);
875 assert_eq!(reports[0]["stacktrace"].as_array().map(Vec::len), Some(1));
876 }
877
878 #[test]
879 fn a_report_without_a_stack_trace_has_no_debug_images() {
880 let report = Report::new("Panic", "boom", Location::caller());
881
882 assert_eq!(report.resolve_frames(false).debug_images(), []);
883 }
884
885 fn located_at(file: &str, is_application_frame: bool) -> Report {
886 let mut report = Report::new("Panic", "boom", Location::caller());
887 report.set_location(Frame {
888 file: file.to_owned(),
889 line_number: 12,
890 column_number: None,
891 method: None,
892 class: None,
893 is_application_frame,
894 instruction_addr: None,
895 });
896
897 report
898 }
899
900 #[test]
901 fn the_report_location_gets_the_workspace_root() {
902 let mut report = located_at("crates/app/src/main.rs", true);
903
904 report.attach(Scope::default(), None, Some("/code/shop"));
905 let resolved = report.resolve_frames(false);
906
907 assert_eq!(
909 Path::new(&resolved.frames()[0].file),
910 Path::new("/code/shop/crates/app/src/main.rs")
911 );
912 }
913
914 #[test]
915 fn an_unknown_location_keeps_its_path() {
916 let mut report = located_at("<unknown>", false);
917
918 report.attach(Scope::default(), None, Some("/code/shop"));
919
920 assert_eq!(report.resolve_frames(false).frames()[0].file, "<unknown>");
921 }
922
923 #[test]
924 fn an_absolute_location_keeps_its_path() {
925 let mut report = located_at("/cargo/registry/src/axum-0.8.9/src/lib.rs", true);
926
927 report.attach(Scope::default(), None, Some("/code/shop"));
928
929 assert_eq!(
930 report.resolve_frames(false).frames()[0].file,
931 "/cargo/registry/src/axum-0.8.9/src/lib.rs"
932 );
933 }
934}