miniextendr_api/panic_telemetry.rs
1//! Structured panic telemetry for debugging Rust panics that become R errors.
2//!
3//! Three separate panic→R-error paths exist in miniextendr (ALTREP trampolines,
4//! connection callbacks, and unwind_protect). This module provides a unified
5//! hook point that fires before each panic is converted to an R error.
6//!
7//! # Relationship to the three emission paths
8//!
9//! This module is **observability, not emission**. It does not raise R
10//! conditions and does not change how panics become errors; it only lets a
11//! caller observe them. The three actual emission paths are documented on
12//! [`crate::error_value`]:
13//!
14//! - `panic!(msg)` — escape hatch; tagged-SEXP with `kind = "panic"`.
15//! - [`crate::error!`] / [`crate::warning!`] / [`crate::message!`] /
16//! [`crate::condition!`] — typed conditions via `RCondition` panic payloads.
17//! - `Result<_, E: std::error::Error>` with [`crate::condition::AsRError`] —
18//! value-style propagation; tagged-SEXP with `kind = "result_err"`.
19//!
20//! `fire` is invoked from each catch site *before* the panic message is encoded
21//! into a tagged condition value, so a registered hook sees every Rust-origin
22//! failure regardless of which of the three paths produced it. Typical uses:
23//! routing to `tracing` / `log`, capturing stack snapshots for crash reports,
24//! or surfacing the panic message in test harnesses where R's stderr is
25//! buffered. The hook must not raise R conditions itself (it runs inside the
26//! panic-handling path) and must not panic — secondary panics from the hook
27//! are caught and silently suppressed by `fire` (this crate, `pub(crate)`).
28//!
29//! # Usage
30//!
31//! ```ignore
32//! use miniextendr_api::panic_telemetry::{set_panic_telemetry_hook, PanicReport, PanicSource};
33//!
34//! set_panic_telemetry_hook(|report| {
35//! eprintln!("[{:?}] panic: {}", report.source, report.message);
36//! });
37//! ```
38//!
39//! # Threads
40//!
41//! Every panic→R-error boundary runs on R's main thread, so the hook lives
42//! there: a thread-local slot, set and fired on that thread, and the closure
43//! need not be `Send` or `Sync`. A hook set on another thread stays in that
44//! thread's slot and never sees the main thread's panics.
45//!
46//! # Performance
47//!
48//! `fire()` reads a thread-local slot and, with a hook set, clones its `Rc`.
49//! The hook only fires on panic paths, never on hot paths.
50
51use std::cell::RefCell;
52use std::panic::{AssertUnwindSafe, catch_unwind};
53use std::rc::Rc;
54
55/// Describes where a panic originated before being converted to an R error.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum PanicSource {
58 /// Panic inside an ALTREP trampoline (caught by `catch_altrep_panic`).
59 Altrep,
60 /// Panic inside `with_r_unwind_protect` (caught by `with_r_unwind_protect_sourced`).
61 UnwindProtect,
62 /// Panic inside a connection callback trampoline.
63 Connection,
64}
65
66/// A structured panic report passed to the telemetry hook.
67pub struct PanicReport<'a> {
68 /// The panic message (extracted from the panic payload).
69 pub message: &'a str,
70 /// Which panic→R-error boundary caught this panic.
71 pub source: PanicSource,
72}
73
74type Hook = Rc<dyn Fn(&PanicReport)>;
75
76std::thread_local! {
77 static HOOK: RefCell<Option<Hook>> = const { RefCell::new(None) };
78}
79
80/// Register a panic telemetry hook on R's main thread.
81///
82/// The hook is called with a [`PanicReport`] each time a Rust panic is about
83/// to be converted into an R error. Only one hook can be active at a time;
84/// calling this again replaces (and drops) the previous hook.
85///
86/// Call it on R's main thread, where every panic→R-error boundary runs (see
87/// [Threads](self#threads)). It is safe to call `set_panic_telemetry_hook` or
88/// `clear_panic_telemetry_hook` from within a hook: the slot is not borrowed
89/// while the hook runs.
90pub fn set_panic_telemetry_hook(f: impl Fn(&PanicReport) + 'static) {
91 // `replace` hands the previous hook back after the borrow ends, so its
92 // destructor may set or clear the hook too.
93 drop(HOOK.replace(Some(Rc::new(f))));
94}
95
96/// Remove the current panic telemetry hook, if any.
97pub fn clear_panic_telemetry_hook() {
98 drop(HOOK.take());
99}
100
101/// Fire the telemetry hook if one is set.
102///
103/// Called internally at each panic→R-error conversion site.
104///
105/// The hook is cloned (as `Rc`) out of the slot before it runs, so it can
106/// call `set_panic_telemetry_hook` or `clear_panic_telemetry_hook`. Secondary
107/// panics from the hook are caught and silently suppressed.
108pub(crate) fn fire(message: &str, source: PanicSource) {
109 let hook = HOOK.with_borrow(Option::clone);
110
111 if let Some(hook) = hook {
112 let report = PanicReport { message, source };
113 // Suppress secondary panics from the hook — we're already on a
114 // panic→R-error path and a double-panic would abort.
115 let _ = catch_unwind(AssertUnwindSafe(|| hook(&report)));
116 }
117}
118
119#[cfg(test)]
120mod tests;