stynx_code_services/diagnostics/
mod.rs1use std::collections::VecDeque;
2use std::sync::Mutex;
3
4const MAX_EVENTS: usize = 1000;
5
6#[derive(Debug, Clone)]
7pub struct DiagnosticEvent {
8 pub timestamp: u64,
9 pub event_type: String,
10 pub details: String,
11}
12
13pub trait DiagnosticTracker: Send + Sync {
14 fn record(&self, event: DiagnosticEvent);
15 fn recent(&self, n: usize) -> Vec<DiagnosticEvent>;
16}
17
18pub struct InMemoryTracker {
19 events: Mutex<VecDeque<DiagnosticEvent>>,
20}
21
22impl InMemoryTracker {
23 pub fn new() -> Self {
24 Self {
25 events: Mutex::new(VecDeque::new()),
26 }
27 }
28}
29
30fn now_secs() -> u64 {
31 std::time::SystemTime::now()
32 .duration_since(std::time::UNIX_EPOCH)
33 .unwrap_or_default()
34 .as_secs()
35}
36
37impl DiagnosticTracker for InMemoryTracker {
38 fn record(&self, mut event: DiagnosticEvent) {
39 if event.timestamp == 0 {
40 event.timestamp = now_secs();
41 }
42 let mut events = self.events.lock().unwrap_or_else(|e| e.into_inner());
43 if events.len() >= MAX_EVENTS {
44 events.pop_front();
45 }
46 events.push_back(event);
47 }
48
49 fn recent(&self, n: usize) -> Vec<DiagnosticEvent> {
50 let events = self.events.lock().unwrap_or_else(|e| e.into_inner());
51 events.iter().rev().take(n).cloned().collect()
52 }
53}