flareapp-core 0.2.0

The core of the Flare client: config, the client, and the worker thread that sends data.
Documentation
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
//! Error reports: what Flare receives on `/v1/errors`.

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;

/// The id of one report, a random UUID. Flare calls it the tracking UUID.
///
/// Show it to your users ("error id: …"), so they can refer to one specific error.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct ReportId(u128);

/// The 4 bits of a UUID that hold its version.
const UUID_VERSION_BITS: u128 = 0xf << 76;

/// Version 4 in the version bits: a UUID made of random bits.
const UUID_VERSION_4: u128 = 0x4 << 76;

/// The 2 bits of a UUID that hold its variant.
const UUID_VARIANT_BITS: u128 = 0x3 << 62;

/// The variant `10` in the variant bits: the standard UUID layout of RFC 9562.
const UUID_VARIANT_STANDARD: u128 = 0x2 << 62;

impl ReportId {
    /// Creates a random version 4 UUID.
    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})")
    }
}

/// One line of a stack trace.
#[expect(
    clippy::struct_field_names,
    reason = "field names mirror Flare's frame format"
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Frame {
    /// The source file, like `/app/src/orders.rs`.
    pub file: String,
    /// The line in the source file.
    pub line_number: u32,
    /// The column in the source file, when known.
    pub column_number: Option<u32>,
    /// The function, like `create`.
    pub method: Option<String>,
    /// The module or type the function belongs to, like `my_app::orders::OrderService`.
    pub class: Option<String>,
    /// Whether the frame is part of your application, not of a dependency or the
    /// standard library.
    pub is_application_frame: bool,
    /// The address in memory that this frame returns to. Flare uses it to find the
    /// function, file and line in an uploaded debug file, so an app can ship a
    /// stripped binary. It is `None` when Flare must keep the frame as it is.
    pub instruction_addr: Option<usize>,
}

impl Frame {
    /// Creates a frame for a code location, like the place where a report was made.
    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,
        }
    }
}

/// A binary or library that was loaded in the app when the report was made.
///
/// Flare uses it to link the address of a frame to the debug file of that binary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DebugImage {
    /// The ID that links this binary to its debug file, like
    /// `f12a7db2-03d7-370d-a820-107402c0c6e7`.
    pub debug_id: String,
    /// The address in memory where the binary starts.
    pub image_addr: usize,
    /// The size of the binary in memory, in bytes.
    pub image_size: usize,
    /// The path of the binary or library, like
    /// `/usr/lib/system/libsystem_pthread.dylib`.
    ///
    /// Flare shows which library a frame is in, and tells system libraries apart
    /// from the binaries of the app. It is `None` when the operating system gives no
    /// path. On Linux, the main binary of the app has no path.
    pub code_file: Option<String>,
}

/// A stack trace after the worker thread resolved it.
#[derive(Debug, Default)]
pub struct StackTrace {
    /// The frames, innermost first.
    pub frames: Vec<Frame>,
    /// The binaries and libraries that hold the addresses of the frames.
    pub debug_images: Vec<DebugImage>,
}

/// A captured stack trace that is not resolved yet.
///
/// Resolving finds the function, file and line of each address in the stack
/// trace, and that is slow. So the worker thread resolves the stack trace, and
/// your code does not wait for it.
///
/// The `flareapp-backtrace` crate implements this trait.
pub trait ResolveFrames: Send + fmt::Debug {
    /// Resolves the stack trace and returns its frames.
    ///
    /// `location` is the place where the report was made. When the stack trace
    /// does not include `location`, an implementation can add `location` as the
    /// first frame.
    fn resolve(self: Box<Self>, location: &Frame) -> StackTrace;
}

/// One error, panic or message, on its way to Flare.
#[derive(Debug)]
pub struct Report {
    id: ReportId,
    exception_class: String,
    message: String,
    level: Option<Level>,
    handled: bool,
    seen_at_unix_nano: u64,
    /// The place where the report was made. It is the only frame when no stack
    /// trace is available.
    location: Frame,
    /// The captured stack trace. The worker thread resolves it with
    /// [`Report::resolve_frames`].
    frames: Option<Box<dyn ResolveFrames>>,
    context: BTreeMap<String, Value>,
    attributes: BTreeMap<String, Value>,
    scope: Scope,
    /// The entry point the report is filed under, set by
    /// [`Report::resolve_entry_point`] or by
    /// [`LogLine::to_report`](crate::LogLine::to_report). Without one, the report
    /// gets the command line of the process.
    pub(crate) entry_point: Option<EntryPoint>,
    application_path: Option<String>,
}

impl Report {
    /// Creates a report with an exception class and a message.
    ///
    /// `location` is the place where the report was made, like
    /// `std::panic::Location::caller()`. Without a stack trace, this place is the
    /// only frame of the report.
    ///
    /// # Examples
    ///
    /// `Location::caller()` returns the place that called the current function.
    /// Mark a helper function that creates reports with `#[track_caller]`. Then
    /// `Location::caller()` returns the place that called the helper, and not a
    /// place inside the helper:
    ///
    /// ```
    /// use std::panic::Location;
    ///
    /// use flareapp_core::Report;
    ///
    /// #[track_caller]
    /// fn payment_failed() -> Report {
    ///     Report::new("my_app::PaymentFailed", "payment failed", Location::caller())
    /// }
    ///
    /// // The location of this report is this line, not the line in the helper.
    /// let report = payment_failed();
    /// ```
    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,
        }
    }

    /// Creates a report for an error. The exception class is the Rust type of the
    /// error, and the message is its `Display` output.
    ///
    /// For a `dyn Error`, the exception class is the class that
    /// [`erased_exception_class`] returns. When that function finds no class, the
    /// class is `Error`.
    pub fn from_error<E: ReportableError + ?Sized>(error: &E, location: &Location<'_>) -> Self {
        Self::new(exception_class(error), error.to_string(), location)
    }

    /// Creates a report for an error whose type is hidden, like the error in a
    /// `Box<dyn Error>`. The message is the `Display` output of the error.
    ///
    /// The exception class is the class that [`erased_exception_class`] returns,
    /// so a `std::io::Error` gets its real type name. When that function finds no
    /// class, the class is `Error`.
    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)
    }

    /// Creates a report for a message, like a log line that needs attention.
    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
    }

    /// Returns the tracking id of the report.
    pub fn id(&self) -> ReportId {
        self.id
    }

    /// Returns the exception class, like `std::io::error::Error`.
    pub fn exception_class(&self) -> &str {
        &self.exception_class
    }

    /// Changes the exception class, which Flare groups errors by.
    pub fn set_exception_class<C: Into<String>>(&mut self, exception_class: C) {
        self.exception_class = exception_class.into();
    }

    /// Returns the message.
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Returns `true` when your code handled the error, and `false` for a panic.
    pub fn handled(&self) -> bool {
        self.handled
    }

    /// Marks the error as handled by your code (`true`, the default) or not.
    pub fn set_handled(&mut self, handled: bool) {
        self.handled = handled;
    }

    /// Adds a piece of context to this report only.
    pub fn set_context<K: Into<String>, V: Into<Value>>(&mut self, key: K, value: V) {
        self.context.insert(key.into(), value.into());
    }

    /// Adds an attribute to this report only, like `thread.name`.
    pub fn set_attribute<K: Into<String>, V: Into<Value>>(&mut self, key: K, value: V) {
        self.attributes.insert(key.into(), value.into());
    }

    /// Sets the place where the report was made, when it differs from the
    /// `location` given to [`Report::new`]. Without a stack trace, this place is
    /// the only frame.
    pub fn set_location(&mut self, location: Frame) {
        self.location = location;
    }

    /// Sets the stack trace. The worker thread resolves it before sending.
    pub fn set_frames<R: ResolveFrames + 'static>(&mut self, frames: R) {
        self.frames = Some(Box::new(frames));
    }

    /// Adds the scope and the application path, just before the report is queued.
    ///
    /// Also joins the report location with the workspace root, so the location has
    /// the same path as the frames from the debug info.
    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);
        }
    }

    /// Decides which entry point the report is filed under, in the order of the
    /// [`EntryPoint`] docs. This function keeps the entry point that a log
    /// line already resolved.
    ///
    /// Call this function on the thread that made the report, because the nested
    /// scopes and the `tracing` spans belong to that thread. The merged scope from
    /// [`Report::attach`] does not work here. A nested scope comes before the
    /// spans and the app-wide scope comes after them, but the merged scope mixes
    /// the two.
    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));
        }
    }

    /// Turns the captured stack trace into frames, and returns the report that
    /// the worker thread can encode. Resolving is slow, so only the worker thread
    /// calls this function.
    ///
    /// A [`ResolveFrames`] implementation can panic. A panic that nothing catches
    /// ends the worker thread, and the Flare client does not start a new worker
    /// thread. So this function catches the panic. The report then has the
    /// report location as its only frame. When `debug` is `true`, this function
    /// also prints a warning.
    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,
        }
    }
}

/// A report whose stack trace the worker thread resolved.
///
/// Only a resolved report can be encoded, so a report never goes out without its
/// frames. [`Report::resolve_frames`] creates it.
#[derive(Debug)]
pub(crate) struct ResolvedReport {
    report: Report,
    stack_trace: StackTrace,
}

impl ResolvedReport {
    /// Returns the frames. Without a stack trace, the place where the report was
    /// made is the only frame.
    fn frames(&self) -> &[Frame] {
        if self.stack_trace.frames.is_empty() {
            slice::from_ref(&self.report.location)
        } else {
            &self.stack_trace.frames
        }
    }

    /// Returns the binaries and libraries that hold the addresses of the frames.
    fn debug_images(&self) -> &[DebugImage] {
        &self.stack_trace.debug_images
    }
}

/// The exception class of an error without a name. Flare needs a non-empty one.
pub(crate) const FALLBACK_EXCEPTION_CLASS: &str = "Error";

/// An error that the Flare client can report: an error type that does not borrow
/// data, or a `dyn Error`.
///
/// [`Report::from_error`] and `flareapp::report_error` take this trait instead of
/// [`Error`]. For a `dyn Error`, the Flare client looks up the real type of the
/// error, like `std::io::Error`. Rust can only do that for an error that is
/// `'static`.
///
/// Every `'static` type that implements [`Error`] implements this trait.
/// `dyn Error`, `dyn Error + Send` and `dyn Error + Send + Sync` also implement
/// this trait. Other crates cannot implement this trait.
///
/// In a function argument, write `&(dyn Error + 'static)` instead of
/// `&dyn Error`. In that place, Rust reads `&dyn Error` as an error that can
/// borrow data, and such an error does not implement this trait.
pub trait ReportableError: Error + sealed::Sealed {
    /// Returns the error as a `dyn Error`, so the Flare client can look up the
    /// real type of the error.
    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;

    /// Stops other crates from implementing
    /// [`ReportableError`](super::ReportableError).
    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 {}
}

/// Returns the exception class for an error: its Rust type name.
///
/// A `Box`, an `Arc` or a `&'static` reference around an error has the same
/// class as the error. So `report_error(&error)` and
/// `report_error(&Arc::new(error))` give the same class. [`inner_type_name`]
/// removes these types from the type name.
///
/// A `dyn Error` has no type name at runtime, like the error in an
/// `Arc<dyn Error + Send + Sync>`. In that case, this function uses the class that
/// [`erased_exception_class`] returns.
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())
}

/// Removes every `&`, `Box` and `Arc` around a type name. For example,
/// `&alloc::sync::Arc<my_app::OrderFailed>` becomes `my_app::OrderFailed`.
///
/// The standard library implements [`Error`] for `&T`, `Box<T>` and `Arc<T>`, and
/// passes each call to `T`. Other types around an error, like `Rc<T>` and
/// `&mut T`, do not implement [`Error`].
fn inner_type_name(mut name: &str) -> &str {
    // The output of `type_name` can change between Rust versions, so the prefixes
    // come from `type_name` too, like `alloc::sync::Arc<`.
    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
}

/// Returns the exception class for an error whose type is hidden, like the error
/// in a `Box<dyn Error>` or the root cause of an `anyhow::Error`.
///
/// Rust has no type name for these at runtime. `std::io::Error` is common enough to
/// recognize, also inside an `Arc<dyn Error>`. Other errors get the name at the
/// start of their `Debug` output: the struct or enum variant name for derived
/// `Debug`, or a path like `reqwest::Error` that some crates print. Returns `None`
/// when that output does not start with a name, like a quoted message.
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)
}

/// Returns the error inside every `Arc<dyn Error>` around an error.
///
/// The type of an `Arc<dyn Error>` is the `Arc`, so a `std::io::Error` in the
/// `Arc` is only found after this function removes the `Arc`.
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;
        };
    }
}

/// Returns the name at the start of a `Debug` output, when it has one: a word like
/// `RowNotFound`, or a path like `reqwest::Error`, which some crates print in their
/// own `Debug` output.
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;
    }

    // Skip the first name, then each `::name` after it.
    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");

        // The path depends on the Rust version: older versions say `std::…`, newer
        // ones `core::…`.
        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"));
    }

    /// Like `reqwest::Error`, whose `Debug` output starts with its path.
    #[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);

        // `Path` compares components, so the `\` that Windows joins with matches `/`.
        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"
        );
    }
}