rootcause 0.12.1

A flexible, ergonomic, and inspectable error reporting library for Rust
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
//! Report creation hooks for automatic report modification.
//!
//! This module provides hooks that run automatically when errors are created,
//! allowing you to attach metadata or modify reports without changing the code
//! that creates the errors.
//!
//! **Note:** Hooks affect ALL errors globally. If you only need to attach data
//! to a specific error, use `.attach()` directly instead of hooks.
//!
//! # Hook Types (use in order of complexity)
//!
//! 1. **Closures** - Simplest: Just return a value to attach
//!
//!    ```rust
//!    # use rootcause::hooks::Hooks;
//!    Hooks::new().attachment_collector(|| "some data")
//!    # ;
//!    ```
//!
//! 2. **[`AttachmentCollector`]** - Simple: Collect and attach specific data
//!    automatically to every error. Use when you always want to attach the same
//!    type of information.
//!
//! 3. **[`ReportCreationHook`]** - Advanced: Full access to the report for
//!    conditional logic. Use when you need to inspect the error type or context
//!    before deciding what to attach.
//!
//! # Examples
//!
//! ## Simple: Using a Closure
//!
//! The easiest way to attach data to all errors:
//!
//! ```
//! use rootcause::hooks::Hooks;
//!
//! // Attach a request ID to every error
//! Hooks::new()
//!     .attachment_collector(|| format!("Request ID: {}", get_request_id()))
//!     .install()
//!     .expect("failed to install hooks");
//!
//! fn get_request_id() -> u64 {
//!     42
//! }
//! ```
//!
//! ## Medium: Custom Attachment Collector
//!
//! When you need to attach structured data or use a custom handler, implement
//! [`AttachmentCollector`]:
//!
//! ```
//! use rootcause::{
//!     hooks::{Hooks, report_creation::AttachmentCollector},
//!     prelude::*,
//! };
//!
//! // Simulates data from an external system monitoring crate
//! #[derive(Debug)]
//! struct SystemLoad {
//!     cpu_percent: f32,
//!     memory_used_mb: u64,
//! }
//!
//! fn get_system_load() -> SystemLoad {
//!     // In real code, this would call an external crate like `sysinfo`
//!     SystemLoad {
//!         cpu_percent: 45.2,
//!         memory_used_mb: 2048,
//!     }
//! }
//!
//! struct SystemLoadCollector;
//!
//! impl AttachmentCollector<SystemLoad> for SystemLoadCollector {
//!     type Handler = handlers::Debug;
//!
//!     fn collect(&self) -> SystemLoad {
//!         get_system_load()
//!     }
//! }
//!
//! Hooks::new()
//!     .attachment_collector(SystemLoadCollector)
//!     .install()
//!     .expect("failed to install hooks");
//! ```
//!
//! ## Advanced: Custom Report Creation Hook
//!
//! When you need conditional logic based on the error type, implement
//! [`ReportCreationHook`]:
//!
//! ```
//! use rootcause::{
//!     ReportMut,
//!     hooks::{Hooks, report_creation::ReportCreationHook},
//!     markers::{Dynamic, Local, SendSync},
//!     prelude::*,
//! };
//!
//! // Hook that adds retry hints only for retryable I/O errors
//! struct RetryHintHook;
//!
//! impl ReportCreationHook for RetryHintHook {
//!     fn on_local_creation(&self, mut report: ReportMut<'_, Dynamic, Local>) {
//!         // Only attach hint for I/O errors where retry might help
//!         if let Some(io_err) = report.downcast_current_context::<std::io::Error>() {
//!             if matches!(
//!                 io_err.kind(),
//!                 std::io::ErrorKind::TimedOut | std::io::ErrorKind::ConnectionRefused
//!             ) {
//!                 report
//!                     .attachments_mut()
//!                     .push(report_attachment!("Retry may succeed").into());
//!             }
//!         }
//!     }
//!
//!     fn on_sendsync_creation(&self, mut report: ReportMut<'_, Dynamic, SendSync>) {
//!         // Same logic for Send+Sync errors
//!         if let Some(io_err) = report.downcast_current_context::<std::io::Error>() {
//!             if matches!(
//!                 io_err.kind(),
//!                 std::io::ErrorKind::TimedOut | std::io::ErrorKind::ConnectionRefused
//!             ) {
//!                 report
//!                     .attachments_mut()
//!                     .push(report_attachment!("Retry may succeed").into());
//!             }
//!         }
//!     }
//! }
//!
//! Hooks::new()
//!     .report_creation_hook(RetryHintHook)
//!     .install()
//!     .expect("failed to install hooks");
//! ```

use alloc::boxed::Box;
use core::fmt;

use rootcause_internals::handlers::AttachmentHandler;

use crate::{
    ReportMut, handlers,
    hooks::{
        HookCallback, HookData,
        builtin_hooks::location::{Location, LocationHandler},
        use_hooks,
    },
    markers::{Dynamic, Local, SendSync},
    report_attachment::ReportAttachment,
};

/// Internal trait for stored report creation hooks.
pub(crate) trait StoredReportCreationHook: 'static + Send + Sync + core::fmt::Debug {
    #[track_caller]
    fn on_local_creation(&self, report: ReportMut<'_, Dynamic, Local>);

    #[track_caller]
    fn on_sendsync_creation(&self, report: ReportMut<'_, Dynamic, SendSync>);
}

/// A hook that is called whenever a report is created.
///
/// Report creation hooks provide a way to automatically modify or enhance
/// reports as they are being created, without requiring changes to the code
/// that creates the reports. This is useful for adding consistent metadata,
/// logging, or performing other side effects.
///
/// If you only need to add attachments, then consider using an
/// [`AttachmentCollector`] instead, as it gives you an easier to use API
/// for this use case.
///
/// # Examples
///
/// ```
/// use rootcause::{
///     ReportMut,
///     hooks::{Hooks, report_creation::ReportCreationHook},
///     markers::{Dynamic, Local, SendSync},
///     prelude::*,
/// };
///
/// struct LoggingHook;
///
/// impl ReportCreationHook for LoggingHook {
///     fn on_local_creation(&self, mut report: ReportMut<'_, Dynamic, Local>) {
///         println!("Local report created: {}", report);
///         let attachment = report_attachment!("Logged by LoggingHook");
///         report.attachments_mut().push(attachment.into());
///     }
///
///     fn on_sendsync_creation(&self, mut report: ReportMut<'_, Dynamic, SendSync>) {
///         println!("SendSync report created: {}", report);
///         let attachment = report_attachment!("Logged by LoggingHook");
///         report.attachments_mut().push(attachment.into());
///     }
/// }
///
/// // Install the hook globally
/// Hooks::new()
///     .report_creation_hook(LoggingHook)
///     .install()
///     .expect("failed to install hooks");
/// ```
pub trait ReportCreationHook: 'static + Send + Sync {
    /// Called when a [`Local`] report is created.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{
    ///     ReportMut,
    ///     hooks::report_creation::ReportCreationHook,
    ///     markers::{Dynamic, Local, SendSync},
    ///     report_attachment,
    /// };
    ///
    /// struct ThreadInfoHook;
    /// impl ReportCreationHook for ThreadInfoHook {
    ///     fn on_local_creation(&self, mut report: ReportMut<'_, Dynamic, Local>) {
    ///         let thread_id = format!("Thread: {:?}", std::thread::current().id());
    ///         report
    ///             .attachments_mut()
    ///             .push(report_attachment!(thread_id).into());
    ///     }
    ///
    ///     fn on_sendsync_creation(&self, _report: ReportMut<'_, Dynamic, SendSync>) {}
    /// }
    /// ```
    #[track_caller]
    fn on_local_creation(&self, report: ReportMut<'_, Dynamic, Local>);

    /// Called when a [`SendSync`] report is created.
    ///
    /// # Examples
    ///
    /// ```
    /// use rootcause::{
    ///     ReportMut,
    ///     hooks::report_creation::ReportCreationHook,
    ///     markers::{Dynamic, Local, SendSync},
    ///     report_attachment,
    /// };
    ///
    /// struct ProcessInfoHook;
    /// impl ReportCreationHook for ProcessInfoHook {
    ///     fn on_local_creation(&self, _report: ReportMut<'_, Dynamic, Local>) {}
    ///
    ///     fn on_sendsync_creation(&self, mut report: ReportMut<'_, Dynamic, SendSync>) {
    ///         let process_id = format!("Process ID: {}", std::process::id());
    ///         report
    ///             .attachments_mut()
    ///             .push(report_attachment!(process_id).into());
    ///     }
    /// }
    /// ```
    #[track_caller]
    fn on_sendsync_creation(&self, report: ReportMut<'_, Dynamic, SendSync>);
}

pub(crate) fn creation_hook_to_stored_hook<H>(hook: H) -> Box<dyn StoredReportCreationHook>
where
    H: ReportCreationHook + Send + Sync + 'static,
{
    struct Hook<H> {
        hook: H,
    }

    impl<H> core::fmt::Debug for Hook<H> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "CreationHook<{}>", core::any::type_name::<H>(),)
        }
    }

    impl<H> StoredReportCreationHook for Hook<H>
    where
        H: ReportCreationHook,
    {
        fn on_local_creation(&self, report: ReportMut<'_, Dynamic, Local>) {
            self.hook.on_local_creation(report);
        }

        fn on_sendsync_creation(&self, report: ReportMut<'_, Dynamic, SendSync>) {
            self.hook.on_sendsync_creation(report);
        }
    }

    let hook: Hook<H> = Hook { hook };
    Box::new(hook)
}

pub(crate) fn attachment_hook_to_stored_hook<A, H, C>(
    collector: C,
) -> Box<dyn StoredReportCreationHook>
where
    A: 'static + Send + Sync,
    H: AttachmentHandler<A>,
    C: AttachmentCollector<A> + Send + Sync + 'static,
{
    struct Hook<A, Handler, Collector> {
        collector: Collector,
        _handled_type: core::marker::PhantomData<fn(A) -> A>,
        _handler: core::marker::PhantomData<fn(Handler) -> Handler>,
    }

    impl<A, Handler, Collector> core::fmt::Debug for Hook<A, Handler, Collector> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(
                f,
                "AttachmentCollector<{}, {}, {}>",
                core::any::type_name::<A>(),
                core::any::type_name::<Handler>(),
                core::any::type_name::<Collector>(),
            )
        }
    }

    impl<A, Handler, Collector> StoredReportCreationHook for Hook<A, Handler, Collector>
    where
        A: 'static + Send + Sync,
        Handler: AttachmentHandler<A>,
        Collector: AttachmentCollector<A> + Send + Sync,
    {
        #[track_caller]
        fn on_local_creation(&self, mut report: ReportMut<'_, Dynamic, Local>) {
            let attachment = self.collector.collect();
            report
                .attachments_mut()
                .push(ReportAttachment::new_local_custom::<Handler>(attachment).into_dynamic());
        }

        #[track_caller]
        fn on_sendsync_creation(&self, mut report: ReportMut<'_, Dynamic, SendSync>) {
            let attachment = self.collector.collect();
            report
                .attachments_mut()
                .push(ReportAttachment::new_sendsync_custom::<Handler>(attachment).into_dynamic());
        }
    }

    let hook = Hook {
        collector,
        _handled_type: core::marker::PhantomData,
        _handler: core::marker::PhantomData,
    };
    let hook: Box<Hook<A, H, C>> = Box::new(hook);

    hook
}

/// A hook that collects data to be automatically attached to reports when they
/// are created.
///
/// Attachment collector hooks provide a specialized way to automatically
/// collect and attach specific types of data to all reports. Unlike
/// [`ReportCreationHook`], which provides full access to the report, attachment
/// collectors are focused solely on gathering data to be attached.
///
/// # Automatic Implementation
///
/// This trait is automatically implemented for any closure that returns a value
/// implementing [`Display`] and [`Debug`], using [`handlers::Display`] as the
/// handler:
///
/// [`Display`]: core::fmt::Display
/// [`Debug`]: core::fmt::Debug
///
/// ```
/// use rootcause::hooks::Hooks;
///
/// // This closure automatically implements AttachmentCollector<String>
/// Hooks::new()
///     .attachment_collector(|| "timestamp".to_string())
///     .install()
///     .expect("failed to install hooks");
/// ```
///
/// # Examples
///
/// ## Custom Collector Implementation
///
/// ```
/// use rootcause::{
///     hooks::{Hooks, report_creation::AttachmentCollector},
///     prelude::*,
/// };
///
/// struct SystemInfoCollector;
///
/// impl AttachmentCollector<String> for SystemInfoCollector {
///     type Handler = handlers::Display;
///
///     fn collect(&self) -> String {
///         format!(
///             "OS: {}, Arch: {}",
///             std::env::consts::OS,
///             std::env::consts::ARCH
///         )
///     }
/// }
///
/// // Install the collector globally
/// Hooks::new()
///     .attachment_collector(SystemInfoCollector)
///     .install()
///     .expect("failed to install hooks");
/// ```
///
/// ## Using a Closure
///
/// ```
/// use rootcause::hooks::Hooks;
///
/// // Install a closure that collects the current working directory
/// Hooks::new()
///     .attachment_collector(|| {
///         std::env::current_dir()
///             .map(|p| p.display().to_string())
///             .unwrap_or_else(|_| "unknown".to_string())
///     })
///     .install()
///     .expect("failed to install hooks");
/// ```
pub trait AttachmentCollector<A>: 'static + Send + Sync {
    /// The handler type used to format the collected data.
    type Handler: AttachmentHandler<A>;

    /// Collects the data to be attached to a report.
    ///
    /// This method is called once for each report creation and should return
    /// the data that will be attached to the report. The data will be formatted
    /// using the associated [`Handler`](Self::Handler) type.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::SystemTime;
    ///
    /// use rootcause::hooks::report_creation::AttachmentCollector;
    ///
    /// struct TimestampCollector;
    /// impl AttachmentCollector<String> for TimestampCollector {
    ///     type Handler = rootcause::handlers::Display;
    ///
    ///     fn collect(&self) -> String {
    ///         // Collect current timestamp to attach to reports
    ///         match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
    ///             Ok(duration) => format!("Timestamp: {}s", duration.as_secs()),
    ///             Err(_) => "Timestamp: unknown".to_string(),
    ///         }
    ///     }
    /// }
    /// ```
    #[track_caller]
    fn collect(&self) -> A;
}

impl<A, F> AttachmentCollector<A> for F
where
    A: 'static + core::fmt::Display + core::fmt::Debug,
    F: 'static + Send + Sync + Fn() -> A,
{
    type Handler = handlers::Display;

    #[track_caller]
    fn collect(&self) -> A {
        (self)()
    }
}

#[track_caller]
pub(crate) fn run_creation_hooks_local(report: ReportMut<'_, Dynamic, Local>) {
    struct Inner<'a>(ReportMut<'a, Dynamic, Local>);
    impl HookCallback<()> for Inner<'_> {
        fn call(self, hook_data: Option<&HookData>) {
            let mut report = self.0;
            if let Some(hook_data) = hook_data {
                for hook in &hook_data.report_creation {
                    hook.on_local_creation(report.as_mut());
                }
            } else {
                report.attachments_mut().push(
                    ReportAttachment::new_local_custom::<LocationHandler>(Location::caller())
                        .into_dynamic(),
                );
            }
        }
    }

    use_hooks(Inner(report))
}

#[track_caller]
pub(crate) fn run_creation_hooks_sendsync(report: ReportMut<'_, Dynamic, SendSync>) {
    struct Inner<'a>(ReportMut<'a, Dynamic, SendSync>);
    impl HookCallback<()> for Inner<'_> {
        fn call(self, hook_data: Option<&HookData>) {
            let mut report = self.0;
            if let Some(hook_data) = hook_data {
                for hook in &hook_data.report_creation {
                    hook.on_sendsync_creation(report.as_mut());
                }
            } else {
                report.attachments_mut().push(
                    ReportAttachment::new_sendsync_custom::<LocationHandler>(Location::caller())
                        .into_dynamic(),
                );
            }
        }
    }

    use_hooks(Inner(report))
}