1use std::collections::HashMap;
15use std::panic::{self, PanicHookInfo};
16use std::sync::{Arc, Mutex, OnceLock};
17use std::thread;
18
19use serde::{Deserialize, Serialize};
20use serde_json::{Value, json};
21use web_time::SystemTime;
22
23use observability_core::{
24 LogEntry,
25 domain::{LogSource, TraceContext},
26 traits::LogLevel,
27};
28
29use crate::error::{Result, StructuredLoggingError};
31use chrono::Utc;
32
33#[cfg(feature = "correlation-enhanced")]
36use crate::correlation::EnhancedTraceContext;
37
38#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct PanicHandlerConfig {
41 pub enable_structured_logging: bool,
43
44 pub enable_analytics: bool,
46
47 pub enable_context_preservation: bool,
49}
50
51impl Default for PanicHandlerConfig {
52 fn default() -> Self {
53 Self {
54 enable_structured_logging: true,
55 enable_analytics: true,
56 enable_context_preservation: true,
57 }
58 }
59}
60
61#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
63pub enum PanicSeverity {
64 Low,
66 Medium,
68 High,
70 Critical,
72}
73
74#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct StructuredPanicInfo {
77 pub message: String,
79
80 pub location: Option<String>,
82
83 pub thread_info: ThreadInfo,
85
86 pub timestamp: String,
88
89 pub severity: PanicSeverity,
91
92 pub trace_context: Option<TraceContext>,
94
95 #[cfg(feature = "correlation-enhanced")]
97 pub enhanced_context: Option<EnhancedTraceContext>,
98
99 pub metadata: HashMap<String, Value>,
101}
102
103#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct ThreadInfo {
106 pub name: Option<String>,
107 pub id: String,
108 pub is_main: bool,
109}
110
111impl ThreadInfo {
112 fn current() -> Self {
113 let current_thread = thread::current();
114 Self {
115 name: current_thread.name().map(|s| s.to_string()),
116 id: format!("{:?}", current_thread.id()),
117 is_main: current_thread.name() == Some("main"),
118 }
119 }
120}
121
122#[derive(Debug, Clone, Default, Serialize, Deserialize)]
124pub struct PanicStats {
125 pub total_panics: u64,
127
128 pub panics_by_severity: HashMap<String, u64>,
130
131 pub panics_by_thread: HashMap<String, u64>,
133
134 pub common_patterns: Vec<PanicPattern>,
136
137 pub last_panic_timestamp: Option<String>,
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct PanicPattern {
144 pub pattern: String,
145 pub count: u64,
146 pub first_seen: String,
147 pub last_seen: String,
148}
149
150pub struct PanicHandler {
152 config: PanicHandlerConfig,
153 stats: Arc<Mutex<PanicStats>>,
154}
155
156static PANIC_HANDLER: OnceLock<Arc<PanicHandler>> = OnceLock::new();
157
158impl PanicHandler {
159 pub fn new(config: PanicHandlerConfig) -> Result<Self> {
161 Ok(Self {
162 config,
163 stats: Arc::new(Mutex::new(PanicStats::default())),
164 })
165 }
166
167 pub fn install(config: PanicHandlerConfig) -> Result<()> {
169 let handler = Arc::new(Self::new(config)?);
170
171 if PANIC_HANDLER.set(handler.clone()).is_err() {
172 return Err(StructuredLoggingError::enhanced_config(
173 "Panic handler already installed",
174 ));
175 }
176
177 let handler_clone = handler.clone();
179 panic::set_hook(Box::new(move |panic_info| {
180 handler_clone.handle_panic(panic_info);
181 }));
182
183 log::info!("🔥 Structured panic handler installed for downstream observability");
184 Ok(())
185 }
186
187 fn handle_panic(&self, panic_info: &PanicHookInfo<'_>) {
189 if !self.config.enable_structured_logging {
190 return;
191 }
192
193 let structured_info = self.create_structured_info(panic_info);
195
196 self.log_structured_panic(&structured_info);
198
199 if self.config.enable_analytics {
201 self.update_panic_stats(&structured_info);
202 }
203 }
204
205 fn create_structured_info(&self, panic_info: &PanicHookInfo<'_>) -> StructuredPanicInfo {
207 let message = if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
208 s.to_string()
209 } else if let Some(s) = panic_info.payload().downcast_ref::<String>() {
210 s.clone()
211 } else {
212 "Unknown panic".to_string()
213 };
214
215 let location = panic_info
216 .location()
217 .map(|loc| format!("{}:{}:{}", loc.file(), loc.line(), loc.column()));
218
219 let trace_context = None; let severity = self.classify_panic_severity(&message);
223 let timestamp = SystemTime::now()
224 .duration_since(SystemTime::UNIX_EPOCH)
225 .map(|d| {
226 let secs = d.as_secs();
227 let nanos = d.subsec_nanos();
228 format!("{}.{:09}Z", secs, nanos)
229 })
230 .unwrap_or_else(|_| "unknown".to_string());
231
232 StructuredPanicInfo {
233 message,
234 location,
235 thread_info: ThreadInfo::current(),
236 timestamp,
237 severity,
238 trace_context,
239 #[cfg(feature = "correlation-enhanced")]
240 enhanced_context: None, metadata: HashMap::new(),
242 }
243 }
244
245 fn classify_panic_severity(&self, message: &str) -> PanicSeverity {
247 if message.contains("memory")
248 || message.contains("corruption")
249 || message.contains("segfault")
250 {
251 PanicSeverity::Critical
252 } else if message.contains("assertion") || message.contains("unreachable") {
253 PanicSeverity::High
254 } else if message.contains("unwrap") || message.contains("expect") {
255 PanicSeverity::Medium
256 } else {
257 PanicSeverity::Low
258 }
259 }
260
261 fn log_structured_panic(&self, panic_info: &StructuredPanicInfo) {
263 let _log_entry = LogEntry {
264 timestamp: Utc::now(),
265 level: LogLevel::Error,
266 message: format!("🔥 PANIC: {}", panic_info.message),
267 fields: json!({
268 "panic": {
269 "message": panic_info.message,
270 "location": panic_info.location,
271 "severity": panic_info.severity,
272 "thread": panic_info.thread_info,
273 "metadata": panic_info.metadata
274 },
275 "trace_context": panic_info.trace_context,
276 "operation": "panic_logging"
277 }),
278 trace_context: panic_info.trace_context.clone(),
279 source: LogSource {
280 module: Some("panic_handler".to_string()),
281 file: panic_info
282 .location
283 .as_ref()
284 .and_then(|loc| loc.split(':').next().map(|s| s.to_string())),
285 line: panic_info
286 .location
287 .as_ref()
288 .and_then(|loc| loc.split(':').nth(1).and_then(|s| s.parse().ok())),
289 target: Some("structured_logging::panic_handler".to_string()),
290 },
291 };
292
293 log::error!(
295 target: "panic_handler",
296 "🔥 Structured panic: {} at {} (severity: {:?})",
297 panic_info.message,
298 panic_info.location.as_deref().unwrap_or("unknown"),
299 panic_info.severity
300 );
301 }
302
303 fn update_panic_stats(&self, panic_info: &StructuredPanicInfo) {
305 if let Ok(mut stats) = self.stats.lock() {
306 stats.total_panics += 1;
307
308 let severity_key = format!("{:?}", panic_info.severity);
310 *stats.panics_by_severity.entry(severity_key).or_insert(0) += 1;
311
312 let thread_key = panic_info
314 .thread_info
315 .name
316 .clone()
317 .unwrap_or_else(|| panic_info.thread_info.id.clone());
318 *stats.panics_by_thread.entry(thread_key).or_insert(0) += 1;
319
320 stats.last_panic_timestamp = Some(panic_info.timestamp.clone());
322
323 let pattern = self.extract_panic_pattern(&panic_info.message);
325 let existing_pattern = stats
326 .common_patterns
327 .iter_mut()
328 .find(|p| p.pattern == pattern);
329
330 if let Some(existing) = existing_pattern {
331 existing.count += 1;
332 existing.last_seen = panic_info.timestamp.clone();
333 } else {
334 stats.common_patterns.push(PanicPattern {
335 pattern,
336 count: 1,
337 first_seen: panic_info.timestamp.clone(),
338 last_seen: panic_info.timestamp.clone(),
339 });
340 }
341
342 stats.common_patterns.sort_by(|a, b| b.count.cmp(&a.count));
344 stats.common_patterns.truncate(10);
345 }
346 }
347
348 fn extract_panic_pattern(&self, message: &str) -> String {
350 if message.contains("index out of bounds") {
351 "index_out_of_bounds".to_string()
352 } else if message.contains("unwrap") {
353 "unwrap_on_error".to_string()
354 } else if message.contains("assertion failed") {
355 "assertion_failed".to_string()
356 } else if message.contains("memory") {
357 "memory_error".to_string()
358 } else {
359 "other".to_string()
360 }
361 }
362
363 pub fn get_stats(&self) -> Result<PanicStats> {
365 self.stats
366 .lock()
367 .map(|stats| stats.clone())
368 .map_err(|_| StructuredLoggingError::enhanced_config("Failed to acquire stats lock"))
369 }
370
371 pub fn reset_stats(&self) -> Result<()> {
373 match self.stats.lock() {
374 Ok(mut stats) => {
375 *stats = PanicStats::default();
376 log::info!("📊 Panic statistics reset");
377 Ok(())
378 }
379 _ => Err(StructuredLoggingError::enhanced_config(
380 "Failed to acquire stats lock",
381 )),
382 }
383 }
384}
385
386pub fn install_panic_handler() -> Result<()> {
388 PanicHandler::install(PanicHandlerConfig::default())
389}
390
391pub fn install_panic_handler_with_config(config: PanicHandlerConfig) -> Result<()> {
393 PanicHandler::install(config)
394}
395
396pub fn get_panic_stats() -> Result<PanicStats> {
398 PANIC_HANDLER
399 .get()
400 .ok_or_else(|| StructuredLoggingError::enhanced_config("Panic handler not installed"))?
401 .get_stats()
402}
403
404pub fn reset_panic_stats() -> Result<()> {
406 PANIC_HANDLER
407 .get()
408 .ok_or_else(|| StructuredLoggingError::enhanced_config("Panic handler not installed"))?
409 .reset_stats()
410}
411
412#[macro_export]
414macro_rules! supervised {
415 ($body:expr_2021) => {{
416 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| $body)).map_err(|_| {
417 $crate::StructuredLoggingError::enhanced_config("Supervised operation panicked")
418 })
419 }};
420}
421
422#[cfg(test)]
423mod tests {
424 use super::*;
425
426 #[test]
427 fn test_panic_handler_config_default() {
428 let config = PanicHandlerConfig::default();
429 assert!(config.enable_structured_logging);
430 assert!(config.enable_analytics);
431 assert!(config.enable_context_preservation);
432 }
433
434 #[test]
435 fn test_panic_severity_classification() {
436 let config = PanicHandlerConfig::default();
437 let handler = PanicHandler::new(config).unwrap();
438
439 assert_eq!(
440 handler.classify_panic_severity("index out of bounds"),
441 PanicSeverity::Low
442 );
443
444 assert_eq!(
445 handler.classify_panic_severity("memory corruption detected"),
446 PanicSeverity::Critical
447 );
448
449 assert_eq!(
450 handler.classify_panic_severity("assertion failed"),
451 PanicSeverity::High
452 );
453
454 assert_eq!(
455 handler.classify_panic_severity("unwrap called on None"),
456 PanicSeverity::Medium
457 );
458 }
459
460 #[test]
461 fn test_supervised_macro() {
462 let result = supervised!({ 42 });
463 assert!(result.is_ok());
464 assert_eq!(result.unwrap(), 42);
465 }
466
467 #[test]
468 fn test_panic_pattern_extraction() {
469 let config = PanicHandlerConfig::default();
470 let handler = PanicHandler::new(config).unwrap();
471
472 assert_eq!(
473 handler.extract_panic_pattern("index out of bounds: the len is 0 but the index is 1"),
474 "index_out_of_bounds"
475 );
476 assert_eq!(
477 handler.extract_panic_pattern("called `Result::unwrap()` on an `Err` value"),
478 "unwrap_on_error"
479 );
480 assert_eq!(
481 handler.extract_panic_pattern("assertion failed: x == y"),
482 "assertion_failed"
483 );
484 assert_eq!(
485 handler.extract_panic_pattern("memory corruption"),
486 "memory_error"
487 );
488 assert_eq!(handler.extract_panic_pattern("something else"), "other");
489 }
490}