brinkhaustools/
diagnosis.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::status::StatusSource;

/// Severity level for a diagnosis message.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Severity {
    Info,
    Warning,
    Error,
}

/// A value filled into a placeholder of a [`MessagePart`].
///
/// Typed rather than pre-formatted, so the UI formats it in the operator's
/// language: a number with the locale's decimal separator, a duration as
/// "4 h 3 min" instead of "14595 s". Fixed point instead of `f64` keeps the
/// message comparable (`Eq`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiagParam {
    /// Inserted verbatim (a name, a foreign error text).
    Text(String),
    /// Fixed-point number `value · 10^-decimals`: 7179.5 is `{ value: 71795, decimals: 1 }`.
    Number { value: i64, decimals: u8 },
    /// A duration in whole seconds.
    Duration { seconds: i64 },
    /// A translatable value: a key with its own parameters, filled into the
    /// placeholder as a sentence fragment in the operator's language — e.g.
    /// a classified foreign error ("connection refused") inside a message
    /// instead of the driver's raw text. Nests arbitrarily.
    Keyed(MessagePart),
}

impl From<MessagePart> for DiagParam {
    fn from(part: MessagePart) -> Self {
        Self::Keyed(part)
    }
}

impl DiagParam {
    /// A count as a number parameter.
    #[must_use]
    pub fn count(n: usize) -> Self {
        Self::Number {
            value: i64::try_from(n).unwrap_or(i64::MAX),
            decimals: 0,
        }
    }

    /// A duration, rounded down to whole seconds.
    #[must_use]
    pub fn duration(d: Duration) -> Self {
        Self::Duration {
            seconds: i64::try_from(d.as_secs()).unwrap_or(i64::MAX),
        }
    }

    /// Wire form: text as string, number as JSON number, duration as
    /// `{"seconds": n}`, keyed value as `{"key": …, "params": {…}}`.
    #[must_use]
    pub fn to_json(&self) -> Value {
        match self {
            Self::Text(text) => Value::String(text.clone()),
            Self::Number { value, decimals } => {
                serde_json::json!(*value as f64 / 10_f64.powi(i32::from(*decimals)))
            }
            Self::Duration { seconds } => serde_json::json!({ "seconds": seconds }),
            Self::Keyed(part) => part.to_json(),
        }
    }
}

/// One translatable piece of a diagnosis message: a text key and the values
/// for its placeholders. The UI looks the key up in its own catalog and
/// fills in the parameters; the plain `message` stays the fallback.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MessagePart {
    pub key: String,
    pub params: BTreeMap<String, DiagParam>,
}

impl MessagePart {
    pub fn new(key: impl Into<String>, params: BTreeMap<String, DiagParam>) -> Self {
        Self {
            key: key.into(),
            params,
        }
    }

    /// A part without placeholders.
    pub fn key(key: impl Into<String>) -> Self {
        Self::new(key, BTreeMap::new())
    }

    /// Wire form: `{"key": …, "params": {name: value}}`.
    #[must_use]
    pub fn to_json(&self) -> Value {
        let params: serde_json::Map<String, Value> = self
            .params
            .iter()
            .map(|(name, value)| (name.clone(), value.to_json()))
            .collect();
        serde_json::json!({ "key": self.key, "params": params })
    }
}

/// A diagnostic message with a numeric code and optional auto-timeout.
#[derive(Debug, Clone)]
pub struct DiagnosisMessage {
    pub code: u16,
    /// Plain text: the fallback for UIs without the keys, and the text for
    /// logs and the fleet heartbeat.
    pub message: String,
    /// Translatable form of `message`; empty for an unkeyed message.
    pub parts: Vec<MessagePart>,
    pub severity: Severity,
    pub created_at_ms: i64,
    timeout_at: Option<Instant>,
}

type ChangeCallback = Box<dyn Fn() + Send + Sync>;

struct DiagnosisInner {
    messages: HashMap<u16, DiagnosisMessage>,
    observers: Vec<ChangeCallback>,
}

/// Engine for tracking diagnostic messages with numeric codes, severity, and auto-timeout.
///
/// Thread-safe. Implements [`StatusSource`] for integration with [`StatusEngine`](crate::StatusEngine).
pub struct SelfDiagnosisEngine {
    status_name: String,
    inner: Arc<RwLock<DiagnosisInner>>,
}

impl SelfDiagnosisEngine {
    pub fn new() -> Self {
        Self::with_status_name("RunTimeTests")
    }

    /// Like [`new`](Self::new), but with a custom [`StatusSource`] node name
    /// (consumers compose their own status trees and need stable keys; the
    /// historical default "RunTimeTests" stems from the ToolScope lineage).
    pub fn with_status_name(status_name: impl Into<String>) -> Self {
        Self {
            status_name: status_name.into(),
            inner: Arc::new(RwLock::new(DiagnosisInner {
                messages: HashMap::new(),
                observers: Vec::new(),
            })),
        }
    }

    /// Report a diagnostic message. Duplicate codes are ignored (first wins).
    pub fn notify(&self, code: u16, message: &str, severity: Severity) {
        self.insert(code, Vec::new(), message, severity, None);
    }

    /// Report a diagnostic message with auto-timeout.
    pub fn notify_with_timeout(
        &self,
        code: u16,
        message: &str,
        severity: Severity,
        timeout: Duration,
    ) {
        self.insert(code, Vec::new(), message, severity, Some(timeout));
    }

    /// Report a message the UI can translate: `parts` carry text keys and
    /// placeholder values, `fallback` is the plain text (logs, heartbeat,
    /// UIs without the keys). Duplicate codes are ignored (first wins).
    pub fn notify_keyed(
        &self,
        code: u16,
        parts: Vec<MessagePart>,
        fallback: &str,
        severity: Severity,
    ) {
        self.insert(code, parts, fallback, severity, None);
    }

    /// Like [`notify_keyed`](Self::notify_keyed), with auto-timeout.
    pub fn notify_keyed_with_timeout(
        &self,
        code: u16,
        parts: Vec<MessagePart>,
        fallback: &str,
        severity: Severity,
        timeout: Duration,
    ) {
        self.insert(code, parts, fallback, severity, Some(timeout));
    }

    fn insert(
        &self,
        code: u16,
        parts: Vec<MessagePart>,
        message: &str,
        severity: Severity,
        timeout: Option<Duration>,
    ) {
        let mut inner = self.inner.write().unwrap();
        if inner.messages.contains_key(&code) {
            return;
        }
        inner.messages.insert(
            code,
            DiagnosisMessage {
                code,
                message: message.to_string(),
                parts,
                severity,
                created_at_ms: chrono::Utc::now().timestamp_millis(),
                timeout_at: timeout.map(|t| Instant::now() + t),
            },
        );
        Self::notify_observers(&inner.observers);
    }

    /// Clear a diagnostic message by code.
    pub fn clear(&self, code: u16) {
        let mut inner = self.inner.write().unwrap();
        if inner.messages.remove(&code).is_some() {
            Self::notify_observers(&inner.observers);
        }
    }

    /// Get all active messages (expired ones are pruned).
    pub fn get_messages(&self) -> Vec<DiagnosisMessage> {
        let mut inner = self.inner.write().unwrap();
        let now = Instant::now();
        inner.messages.retain(|_, msg| {
            msg.timeout_at.is_none_or(|deadline| now < deadline)
        });
        inner.messages.values().cloned().collect()
    }

    /// Returns `true` if any active message has Error severity.
    pub fn has_errors(&self) -> bool {
        self.get_messages().iter().any(|m| m.severity == Severity::Error)
    }

    /// Register an observer callback that is called on every change (notify/clear).
    pub fn on_change<F: Fn() + Send + Sync + 'static>(&self, callback: F) {
        let mut inner = self.inner.write().unwrap();
        inner.observers.push(Box::new(callback));
    }

    /// Reset for testing.
    pub fn reset_for_testing(&self) {
        let mut inner = self.inner.write().unwrap();
        inner.messages.clear();
        inner.observers.clear();
    }

    fn notify_observers(observers: &[ChangeCallback]) {
        for cb in observers {
            cb();
        }
    }
}

impl Default for SelfDiagnosisEngine {
    fn default() -> Self {
        Self::new()
    }
}

impl StatusSource for SelfDiagnosisEngine {
    fn get_status(&self) -> Value {
        let messages = self.get_messages();
        let has_critical = messages.iter().any(|m| m.severity == Severity::Error);
        let msg_list: Vec<Value> = messages
            .iter()
            .map(|m| {
                let mut entry = serde_json::json!({
                    "code": m.code,
                    "messageForUI": m.message,
                    "critical": m.severity == Severity::Error,
                    "information": m.severity == Severity::Info,
                    "created_at_ms": m.created_at_ms,
                });
                // Only keyed messages carry the field: consumers that predate
                // it see exactly the old shape.
                if !m.parts.is_empty() {
                    entry["messageParts"] =
                        Value::Array(m.parts.iter().map(MessagePart::to_json).collect());
                }
                entry
            })
            .collect();
        serde_json::json!({
            "Source name": self.status_name,
            "System Status": !has_critical,
            "messages": msg_list,
        })
    }

    fn get_name(&self) -> &str {
        &self.status_name
    }

    fn refresh_interval(&self) -> Duration {
        Duration::from_secs(60)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    fn make_engine() -> SelfDiagnosisEngine {
        let e = SelfDiagnosisEngine::new();
        e.reset_for_testing();
        e
    }

    #[test]
    fn test_notify_and_get() {
        let e = make_engine();
        e.notify(100, "Test error", Severity::Error);
        let msgs = e.get_messages();
        assert_eq!(msgs.len(), 1);
        assert_eq!(msgs[0].code, 100);
        assert_eq!(msgs[0].severity, Severity::Error);
    }

    #[test]
    fn test_no_duplicate_codes() {
        let e = make_engine();
        e.notify(100, "First", Severity::Warning);
        e.notify(100, "Second", Severity::Warning);
        let msgs = e.get_messages();
        assert_eq!(msgs.len(), 1);
        assert_eq!(msgs[0].message, "First");
    }

    #[test]
    fn test_clear() {
        let e = make_engine();
        e.notify(100, "Error", Severity::Error);
        e.clear(100);
        assert_eq!(e.get_messages().len(), 0);
    }

    #[test]
    fn test_clear_nonexistent() {
        let e = make_engine();
        e.clear(999); // Should not panic
    }

    #[test]
    fn test_timeout_expiry() {
        let e = make_engine();
        e.notify_with_timeout(100, "Temporary", Severity::Info, Duration::from_millis(100));
        assert_eq!(e.get_messages().len(), 1);
        std::thread::sleep(Duration::from_millis(200));
        assert_eq!(e.get_messages().len(), 0);
    }

    #[test]
    fn test_get_status_format() {
        let e = make_engine();
        e.notify(100, "Warning", Severity::Info);
        let status = e.get_status();
        assert_eq!(status["Source name"], "RunTimeTests");
        assert_eq!(status["System Status"], true);
        let msgs = status["messages"].as_array().unwrap();
        assert_eq!(msgs.len(), 1);
        assert_eq!(msgs[0]["code"], 100);
        assert_eq!(msgs[0]["messageForUI"], "Warning");
        assert_eq!(msgs[0]["information"], true);
    }

    #[test]
    fn test_unkeyed_message_has_no_parts_field() {
        let e = make_engine();
        e.notify(100, "Plain", Severity::Warning);
        let status = e.get_status();
        assert!(status["messages"][0].get("messageParts").is_none());
    }

    #[test]
    fn test_keyed_message_wire_form() {
        let e = make_engine();
        let params = BTreeMap::from([
            ("machine".to_string(), DiagParam::Text("Mill 2".into())),
            ("lag".to_string(), DiagParam::Duration { seconds: 14595 }),
            (
                "limit".to_string(),
                DiagParam::Number {
                    value: 71795,
                    decimals: 1,
                },
            ),
            ("count".to_string(), DiagParam::count(3)),
            (
                "error".to_string(),
                DiagParam::Keyed(MessagePart::new(
                    "diag.error.refused",
                    BTreeMap::from([("detail".to_string(), DiagParam::Text("ECONNREFUSED".into()))]),
                )),
            ),
        ]);
        e.notify_keyed(
            2119,
            vec![
                MessagePart::new("diag.detail.2119", params),
                MessagePart::key("diag.detail.x"),
            ],
            "Mill 2: 14595 s behind",
            Severity::Warning,
        );
        let status = e.get_status();
        let m = &status["messages"][0];
        assert_eq!(m["messageForUI"], "Mill 2: 14595 s behind");
        let parts = m["messageParts"].as_array().unwrap();
        assert_eq!(parts.len(), 2);
        assert_eq!(parts[0]["key"], "diag.detail.2119");
        assert_eq!(parts[0]["params"]["machine"], "Mill 2");
        assert_eq!(
            parts[0]["params"]["lag"],
            serde_json::json!({ "seconds": 14595 })
        );
        assert_eq!(parts[0]["params"]["limit"], 7179.5);
        assert_eq!(parts[0]["params"]["count"], 3.0);
        assert_eq!(
            parts[0]["params"]["error"],
            serde_json::json!({ "key": "diag.error.refused", "params": { "detail": "ECONNREFUSED" } })
        );
        assert_eq!(parts[1]["params"], serde_json::json!({}));
        assert_eq!(e.get_messages()[0].parts.len(), 2);
    }

    #[test]
    fn test_keyed_first_wins_and_timeout() {
        let e = make_engine();
        e.notify(100, "First", Severity::Warning);
        e.notify_keyed(
            100,
            vec![MessagePart::key("k")],
            "Second",
            Severity::Warning,
        );
        assert!(e.get_messages()[0].parts.is_empty());
        e.notify_keyed_with_timeout(
            101,
            vec![MessagePart::key("k")],
            "Temporary",
            Severity::Info,
            Duration::from_millis(100),
        );
        assert_eq!(e.get_messages().len(), 2);
        std::thread::sleep(Duration::from_millis(200));
        assert_eq!(e.get_messages().len(), 1);
    }

    #[test]
    fn test_critical_sets_system_status_false() {
        let e = make_engine();
        e.notify(100, "Critical!", Severity::Error);
        let status = e.get_status();
        assert_eq!(status["System Status"], false);
    }

    #[test]
    fn test_get_name() {
        let e = make_engine();
        assert_eq!(e.get_name(), "RunTimeTests");
    }

    #[test]
    fn test_has_errors() {
        let e = make_engine();
        e.notify(100, "Info", Severity::Info);
        assert!(!e.has_errors());
        e.notify(200, "Error", Severity::Error);
        assert!(e.has_errors());
    }

    #[test]
    fn test_custom_status_name() {
        let e = SelfDiagnosisEngine::with_status_name("selfDiagnosis");
        e.notify(100, "msg", Severity::Info);
        assert_eq!(e.get_name(), "selfDiagnosis");
        assert_eq!(e.get_status()["Source name"], "selfDiagnosis");
    }

    #[test]
    fn test_on_change_observer() {
        let e = make_engine();
        let counter = Arc::new(AtomicUsize::new(0));
        let counter_clone = counter.clone();
        e.on_change(move || {
            counter_clone.fetch_add(1, Ordering::SeqCst);
        });
        e.notify(100, "test", Severity::Info);
        assert_eq!(counter.load(Ordering::SeqCst), 1);
        e.clear(100);
        assert_eq!(counter.load(Ordering::SeqCst), 2);
    }
}