1use core::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
8
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11#[repr(u16)]
12pub enum DiagnosticCode {
13 Runtime = 1,
15 Registration = 2,
17 ExcelCall = 3,
19 ThunkFailure = 4,
21 ReturnFailure = 5,
23 ReleaseFailure = 6,
25 OwnershipInvariant = 7,
27 SinkPanic = 8,
29 Dispatcher = 9,
31}
32
33#[derive(Clone, Copy, Debug, Eq, PartialEq)]
34#[repr(u8)]
35pub enum DiagnosticSeverity {
37 Debug,
39 Info,
41 Warn,
43 Error,
45}
46
47#[derive(Clone, Copy, Debug, Eq, PartialEq)]
49pub struct DiagnosticEvent {
50 pub sequence: u64,
52 pub correlation_id: u64,
54 pub code: DiagnosticCode,
56 pub severity: DiagnosticSeverity,
58 pub excel_code: i32,
60}
61
62impl DiagnosticEvent {
63 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 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
90pub trait DiagnosticSink: Send + Sync {
96 fn record(&self, event: DiagnosticEvent);
98}
99
100pub 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
109pub 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
131pub 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}