Skip to main content

excel_api/
diagnostics.rs

1//! Bounded, non-panicking diagnostics for supportability-critical paths.
2//!
3//! Emission never calls Excel, allocates, formats, or invokes user code while
4//! another diagnostic is being emitted. Drop and `xlAutoFree12` deliberately
5//! do not emit events.
6
7use core::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
8
9/// Stable machine-readable diagnostic code. Formatting belongs to consumers.
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11#[repr(u16)]
12pub enum DiagnosticCode {
13    /// Runtime initialization, closing, or lifecycle state.
14    Runtime = 1,
15    /// Function or command registration work.
16    Registration = 2,
17    /// A typed Excel C API invocation.
18    ExcelCall = 3,
19    /// A generated callback thunk contained a failure or panic.
20    ThunkFailure = 4,
21    /// Return planning or materialization failed.
22    ReturnFailure = 5,
23    /// An owned resource could not be released as required.
24    ReleaseFailure = 6,
25    /// An internal ownership invariant was detected without panicking.
26    OwnershipInvariant = 7,
27    /// A consumer-provided diagnostic sink panicked.
28    SinkPanic = 8,
29    /// Cooperative dispatcher admission, drain, or retirement activity.
30    Dispatcher = 9,
31}
32
33#[derive(Clone, Copy, Debug, Eq, PartialEq)]
34#[repr(u8)]
35/// Severity assigned by the producer; no formatting or policy is implied.
36pub enum DiagnosticSeverity {
37    /// Verbose diagnostic information.
38    Debug,
39    /// Normal informational evidence.
40    Info,
41    /// A recoverable condition needing attention.
42    Warn,
43    /// A failed operation or invariant.
44    Error,
45}
46
47/// Pointer-free fixed-size event. `excel_code` preserves raw Excel status.
48#[derive(Clone, Copy, Debug, Eq, PartialEq)]
49pub struct DiagnosticEvent {
50    /// Monotonic process-local sequence assigned when the event is emitted.
51    pub sequence: u64,
52    /// Producer-provided correlation identifier, defaulting to [`Self::sequence`].
53    pub correlation_id: u64,
54    /// Stable machine-readable event category.
55    pub code: DiagnosticCode,
56    /// Producer-selected severity.
57    pub severity: DiagnosticSeverity,
58    /// Exact raw Excel return code when the event relates to an Excel call.
59    pub excel_code: i32,
60}
61
62impl DiagnosticEvent {
63    /// Creates an event before emission assigns its sequence number.
64    pub const fn new(code: DiagnosticCode, severity: DiagnosticSeverity, excel_code: i32) -> Self {
65        Self {
66            sequence: 0,
67            correlation_id: 0,
68            code,
69            severity,
70            excel_code,
71        }
72    }
73
74    /// Replaces the default correlation identifier for related event streams.
75    pub const fn with_correlation(mut self, correlation_id: u64) -> Self {
76        self.correlation_id = correlation_id;
77        self
78    }
79}
80
81const CAPACITY: usize = 64;
82static NEXT: AtomicU64 = AtomicU64::new(1);
83static WRITTEN: AtomicUsize = AtomicUsize::new(0);
84static EMITTING: AtomicBool = AtomicBool::new(false);
85static RING: std::sync::Mutex<[Option<DiagnosticEvent>; CAPACITY]> =
86    std::sync::Mutex::new([None; CAPACITY]);
87static USER_SINK: std::sync::Mutex<Option<&'static dyn DiagnosticSink>> =
88    std::sync::Mutex::new(None);
89
90/// Optional consumer for ordinary process diagnostics.
91///
92/// Implementations must not call Excel, block indefinitely, allocate in a
93/// guarded callback path, or call [`emit`] recursively. Panics are contained
94/// and the triggering event remains in the ring.
95pub trait DiagnosticSink: Send + Sync {
96    /// Receives one copied event outside Excel and ownership cleanup paths.
97    fn record(&self, event: DiagnosticEvent);
98}
99
100/// Install or remove the optional process-wide user sink before callbacks.
101/// A concurrently emitting callback is never blocked: it simply skips a sink
102/// whose configuration lock is unavailable.
103pub fn set_user_sink(sink: Option<&'static dyn DiagnosticSink>) {
104    if let Ok(mut slot) = USER_SINK.try_lock() {
105        *slot = sink;
106    }
107}
108
109/// Emit into the bounded process-local ring. Reentrant and poisoned paths drop
110/// the event rather than block, recurse, panic, allocate, or call Excel.
111pub fn emit(mut event: DiagnosticEvent) {
112    if EMITTING.swap(true, Ordering::Acquire) {
113        return;
114    }
115    event.sequence = NEXT.fetch_add(1, Ordering::Relaxed);
116    if event.correlation_id == 0 {
117        event.correlation_id = event.sequence;
118    }
119    if let Ok(mut ring) = RING.try_lock() {
120        let index = WRITTEN.fetch_add(1, Ordering::Relaxed) % CAPACITY;
121        ring[index] = Some(event);
122    }
123    if let Ok(sink) = USER_SINK.try_lock() {
124        if let Some(sink) = *sink {
125            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| sink.record(event)));
126        }
127    }
128    EMITTING.store(false, Ordering::Release);
129}
130
131/// Snapshot is intentionally for ordinary support tooling, never callbacks.
132pub fn snapshot() -> Vec<DiagnosticEvent> {
133    RING.lock()
134        .ok()
135        .map(|ring| ring.iter().flatten().copied().collect())
136        .unwrap_or_default()
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142    static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
143
144    #[test]
145    fn saturation_is_bounded_and_preserves_excel_codes() {
146        let _serial = TEST_LOCK.lock().unwrap();
147        for code in 0..(CAPACITY as i32 + 4) {
148            emit(DiagnosticEvent::new(
149                DiagnosticCode::ExcelCall,
150                DiagnosticSeverity::Error,
151                code,
152            ));
153        }
154        let events = snapshot();
155        assert!(events.len() <= CAPACITY);
156        assert!(
157            events
158                .iter()
159                .any(|event| event.excel_code == CAPACITY as i32 + 3)
160        );
161    }
162
163    struct PanickingSink;
164    impl DiagnosticSink for PanickingSink {
165        fn record(&self, _: DiagnosticEvent) {
166            panic!("test sink panic");
167        }
168    }
169    static PANICKING: PanickingSink = PanickingSink;
170
171    #[test]
172    fn sink_panic_and_reentrancy_do_not_escape() {
173        let _serial = TEST_LOCK.lock().unwrap();
174        set_user_sink(Some(&PANICKING));
175        emit(DiagnosticEvent::new(
176            DiagnosticCode::ThunkFailure,
177            DiagnosticSeverity::Error,
178            17,
179        ));
180        set_user_sink(None);
181        assert!(snapshot().iter().any(|event| event.excel_code == 17));
182    }
183}