Skip to main content

skenion_runtime/
log_store.rs

1use std::{
2    collections::VecDeque,
3    sync::{Arc, Mutex},
4};
5
6use serde::{Deserialize, Serialize};
7use tokio::sync::broadcast;
8
9use crate::{
10    DiagnosticSeverity, RuntimeClockDiagnostic, RuntimeClockDiagnosticSeverity, RuntimeDiagnostic,
11    RuntimeIoDiagnostic, RuntimeIoDiagnosticSeverity, ShaderDiagnostic, ShaderDiagnosticSeverity,
12    unix_ms_timestamp,
13};
14
15pub const RUNTIME_LOG_SCHEMA: &str = "skenion.runtime.logs";
16pub const RUNTIME_LOG_SCHEMA_VERSION: &str = "0.1.0";
17pub const DEFAULT_RUNTIME_LOG_BACKLOG_LIMIT: usize = 200;
18const RUNTIME_LOG_CHANNEL_CAPACITY: usize = 512;
19
20#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
21#[serde(rename_all = "lowercase")]
22pub enum RuntimeLogSource {
23    Runtime,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
27#[serde(rename_all = "camelCase")]
28pub struct RuntimeLogEvent {
29    pub id: u64,
30    pub timestamp: String,
31    pub source: RuntimeLogSource,
32    pub level: DiagnosticSeverity,
33    pub code: Option<String>,
34    pub message: String,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
38#[serde(rename_all = "camelCase")]
39pub struct RuntimeLogRetention {
40    pub replay_limit: usize,
41    pub replay_levels: Vec<DiagnosticSeverity>,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
45#[serde(rename_all = "camelCase")]
46pub struct RuntimeLogSnapshotResponse {
47    pub schema: String,
48    pub schema_version: String,
49    pub ok: bool,
50    pub events: Vec<RuntimeLogEvent>,
51    pub retention: RuntimeLogRetention,
52    pub diagnostics: Vec<RuntimeDiagnostic>,
53}
54
55pub struct RuntimeLogStore {
56    inner: Arc<Mutex<RuntimeLogStoreInner>>,
57    sender: broadcast::Sender<RuntimeLogEvent>,
58}
59
60#[derive(Debug)]
61struct RuntimeLogStoreInner {
62    next_id: u64,
63    backlog_limit: usize,
64    warning_error_backlog: VecDeque<RuntimeLogEvent>,
65}
66
67impl RuntimeLogStore {
68    pub fn new(backlog_limit: usize) -> Self {
69        let (sender, _) = broadcast::channel(RUNTIME_LOG_CHANNEL_CAPACITY);
70        Self {
71            inner: Arc::new(Mutex::new(RuntimeLogStoreInner {
72                next_id: 1,
73                backlog_limit,
74                warning_error_backlog: VecDeque::with_capacity(backlog_limit),
75            })),
76            sender,
77        }
78    }
79
80    pub fn snapshot(&self) -> RuntimeLogSnapshotResponse {
81        let inner = self
82            .inner
83            .lock()
84            .expect("runtime log store lock should not be poisoned");
85        RuntimeLogSnapshotResponse {
86            schema: RUNTIME_LOG_SCHEMA.to_owned(),
87            schema_version: RUNTIME_LOG_SCHEMA_VERSION.to_owned(),
88            ok: true,
89            events: inner.warning_error_backlog.iter().cloned().collect(),
90            retention: RuntimeLogRetention {
91                replay_limit: inner.backlog_limit,
92                replay_levels: vec![DiagnosticSeverity::Warning, DiagnosticSeverity::Error],
93            },
94            diagnostics: Vec::new(),
95        }
96    }
97
98    pub fn subscribe(&self) -> broadcast::Receiver<RuntimeLogEvent> {
99        self.sender.subscribe()
100    }
101
102    pub fn record_runtime_diagnostics(&self, diagnostics: &[RuntimeDiagnostic]) {
103        for diagnostic in diagnostics {
104            self.push(
105                diagnostic.severity.clone(),
106                None,
107                diagnostic.message.clone(),
108            );
109        }
110    }
111
112    pub fn record_shader_diagnostics(&self, diagnostics: &[ShaderDiagnostic]) {
113        for diagnostic in diagnostics {
114            self.push(
115                shader_diagnostic_severity(&diagnostic.severity),
116                Some(diagnostic.code.clone()),
117                diagnostic.message.clone(),
118            );
119        }
120    }
121
122    pub fn record_clock_diagnostics(&self, diagnostics: &[RuntimeClockDiagnostic]) {
123        for diagnostic in diagnostics {
124            self.push(
125                clock_diagnostic_severity(&diagnostic.severity),
126                Some(diagnostic.code.clone()),
127                diagnostic.message.clone(),
128            );
129        }
130    }
131
132    pub fn record_io_diagnostics(&self, diagnostics: &[RuntimeIoDiagnostic]) {
133        for diagnostic in diagnostics {
134            self.push(
135                io_diagnostic_severity(&diagnostic.severity),
136                Some(diagnostic.code.clone()),
137                diagnostic.message.clone(),
138            );
139        }
140    }
141
142    fn push(&self, level: DiagnosticSeverity, code: Option<String>, message: String) {
143        let event = {
144            let mut inner = self
145                .inner
146                .lock()
147                .expect("runtime log store lock should not be poisoned");
148            let event = RuntimeLogEvent {
149                id: inner.next_id,
150                timestamp: unix_ms_timestamp(),
151                source: RuntimeLogSource::Runtime,
152                level: level.clone(),
153                code,
154                message,
155            };
156            inner.next_id = inner.next_id.saturating_add(1);
157            if matches!(
158                level,
159                DiagnosticSeverity::Warning | DiagnosticSeverity::Error
160            ) {
161                if inner.warning_error_backlog.len() == inner.backlog_limit {
162                    inner.warning_error_backlog.pop_front();
163                }
164                inner.warning_error_backlog.push_back(event.clone());
165            }
166            event
167        };
168
169        let _ = self.sender.send(event);
170    }
171}
172
173impl Default for RuntimeLogStore {
174    fn default() -> Self {
175        Self::new(DEFAULT_RUNTIME_LOG_BACKLOG_LIMIT)
176    }
177}
178
179fn clock_diagnostic_severity(severity: &RuntimeClockDiagnosticSeverity) -> DiagnosticSeverity {
180    match severity {
181        RuntimeClockDiagnosticSeverity::Error => DiagnosticSeverity::Error,
182        RuntimeClockDiagnosticSeverity::Warning => DiagnosticSeverity::Warning,
183    }
184}
185
186fn io_diagnostic_severity(severity: &RuntimeIoDiagnosticSeverity) -> DiagnosticSeverity {
187    match severity {
188        RuntimeIoDiagnosticSeverity::Error => DiagnosticSeverity::Error,
189        RuntimeIoDiagnosticSeverity::Warning => DiagnosticSeverity::Warning,
190    }
191}
192
193fn shader_diagnostic_severity(severity: &ShaderDiagnosticSeverity) -> DiagnosticSeverity {
194    match severity {
195        ShaderDiagnosticSeverity::Error => DiagnosticSeverity::Error,
196        ShaderDiagnosticSeverity::Warning => DiagnosticSeverity::Warning,
197        ShaderDiagnosticSeverity::Info => DiagnosticSeverity::Info,
198    }
199}
200
201#[cfg(test)]
202mod tests {
203    use crate::{
204        RuntimeClockDiagnostic, RuntimeClockDiagnosticSeverity, RuntimeIoDiagnostic,
205        RuntimeIoDiagnosticSeverity,
206    };
207
208    use super::*;
209
210    #[test]
211    fn runtime_log_store_replays_only_warning_and_error_backlog() {
212        let store = RuntimeLogStore::new(2);
213        store.record_runtime_diagnostics(&[RuntimeDiagnostic {
214            severity: DiagnosticSeverity::Info,
215            message: "connected".to_owned(),
216            code: None,
217            details: None,
218        }]);
219        store.record_runtime_diagnostics(&[RuntimeDiagnostic::warning("first warning")]);
220        store.record_runtime_diagnostics(&[RuntimeDiagnostic::error("first error")]);
221        store.record_runtime_diagnostics(&[RuntimeDiagnostic::warning("second warning")]);
222
223        let snapshot = store.snapshot();
224
225        assert_eq!(snapshot.events.len(), 2);
226        assert_eq!(snapshot.events[0].message, "first error");
227        assert_eq!(snapshot.events[1].message, "second warning");
228        assert_eq!(
229            snapshot.retention.replay_levels,
230            vec![DiagnosticSeverity::Warning, DiagnosticSeverity::Error]
231        );
232    }
233
234    #[test]
235    fn runtime_log_store_records_clock_io_and_shader_diagnostics() {
236        let store = RuntimeLogStore::new(8);
237        let mut receiver = store.subscribe();
238
239        store.record_clock_diagnostics(&[
240            RuntimeClockDiagnostic {
241                severity: RuntimeClockDiagnosticSeverity::Warning,
242                code: "clock-drift".to_owned(),
243                message: "clock drifted".to_owned(),
244            },
245            RuntimeClockDiagnostic {
246                severity: RuntimeClockDiagnosticSeverity::Error,
247                code: "clock-lost".to_owned(),
248                message: "clock lost".to_owned(),
249            },
250        ]);
251        store.record_io_diagnostics(&[
252            RuntimeIoDiagnostic {
253                severity: RuntimeIoDiagnosticSeverity::Warning,
254                code: "io-name".to_owned(),
255                message: "device name unavailable".to_owned(),
256            },
257            RuntimeIoDiagnostic {
258                severity: RuntimeIoDiagnosticSeverity::Error,
259                code: "io-host".to_owned(),
260                message: "device host unavailable".to_owned(),
261            },
262        ]);
263        store.record_shader_diagnostics(&[
264            ShaderDiagnostic {
265                severity: ShaderDiagnosticSeverity::Warning,
266                phase: crate::ShaderDiagnosticPhase::InterfaceAnalysis,
267                code: "shader-warning".to_owned(),
268                message: "shader warning".to_owned(),
269                line: None,
270                column: None,
271                end_line: None,
272                end_column: None,
273                uniform_id: None,
274                source: crate::ShaderDiagnosticSource::User,
275            },
276            ShaderDiagnostic {
277                severity: ShaderDiagnosticSeverity::Info,
278                phase: crate::ShaderDiagnosticPhase::InterfaceAnalysis,
279                code: "shader-info".to_owned(),
280                message: "shader note".to_owned(),
281                line: None,
282                column: None,
283                end_line: None,
284                end_column: None,
285                uniform_id: None,
286                source: crate::ShaderDiagnosticSource::User,
287            },
288        ]);
289
290        let snapshot = store.snapshot();
291
292        assert_eq!(snapshot.events.len(), 5);
293        assert_eq!(snapshot.events[0].level, DiagnosticSeverity::Warning);
294        assert_eq!(snapshot.events[1].level, DiagnosticSeverity::Error);
295        assert_eq!(snapshot.events[2].code.as_deref(), Some("io-name"));
296        assert_eq!(snapshot.events[3].code.as_deref(), Some("io-host"));
297        assert_eq!(snapshot.events[4].code.as_deref(), Some("shader-warning"));
298        assert_eq!(receiver.try_recv().unwrap().message, "clock drifted");
299    }
300}