brinkhaustools/
heartbeat.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
use std::collections::HashMap;
use std::sync::RwLock;
use std::time::{Duration, Instant};

use serde_json::Value;

use crate::status::StatusSource;

struct HeartbeatEntry {
    deadline: Instant,
    timeout: Duration,
}

/// Watchdog engine for detecting hung tasks.
///
/// Register heartbeats with a timeout. If a heartbeat is not refreshed
/// before the timeout, `all_ok()` returns `false` and `expired()` names
/// the offenders.
pub struct HeartbeatEngine {
    default_timeout: Duration,
    status_name: String,
    entries: RwLock<HashMap<String, HeartbeatEntry>>,
}

impl HeartbeatEngine {
    pub fn new(default_timeout: Duration) -> Self {
        Self::with_status_name(default_timeout, "Heartbeat manager")
    }

    /// Like [`new`](Self::new), but with a custom [`StatusSource`] node name
    /// (consumers compose their own status trees and need stable keys).
    pub fn with_status_name(default_timeout: Duration, status_name: impl Into<String>) -> Self {
        Self {
            default_timeout,
            status_name: status_name.into(),
            entries: RwLock::new(HashMap::new()),
        }
    }

    /// Register or refresh a heartbeat. Uses default timeout if `timeout` is None.
    pub fn register(&self, id: &str, timeout: Option<Duration>) {
        let t = timeout.unwrap_or(self.default_timeout);
        let mut entries = self.entries.write().unwrap();
        entries.insert(
            id.to_string(),
            HeartbeatEntry {
                deadline: Instant::now() + t,
                timeout: t,
            },
        );
    }

    /// Refresh a heartbeat's timer.
    pub fn refresh(&self, id: &str) {
        let mut entries = self.entries.write().unwrap();
        if let Some(entry) = entries.get_mut(id) {
            entry.deadline = Instant::now() + entry.timeout;
        }
    }

    /// Stop tracking a heartbeat.
    pub fn cancel(&self, id: &str) {
        let mut entries = self.entries.write().unwrap();
        entries.remove(id);
    }

    /// Returns `false` if any heartbeat has timed out.
    pub fn all_ok(&self) -> bool {
        let entries = self.entries.read().unwrap();
        let now = Instant::now();
        entries.values().all(|e| now < e.deadline)
    }

    /// IDs of all heartbeats whose deadline has passed, sorted.
    ///
    /// This is the watchdog query: callers act on the named offenders
    /// (diagnosis codes, restart paths) instead of deriving them from the
    /// informal `get_status()` JSON.
    pub fn expired(&self) -> Vec<String> {
        let entries = self.entries.read().unwrap();
        let now = Instant::now();
        let mut expired: Vec<String> = entries
            .iter()
            .filter(|(_, e)| now >= e.deadline)
            .map(|(id, _)| id.clone())
            .collect();
        expired.sort();
        expired
    }
}

impl StatusSource for HeartbeatEngine {
    fn get_status(&self) -> Value {
        let entries = self.entries.read().unwrap();
        let now = Instant::now();
        let mut result = serde_json::Map::new();
        for (id, entry) in entries.iter() {
            let remaining = entry.deadline.saturating_duration_since(now);
            result.insert(
                id.clone(),
                serde_json::json!({
                    "remaining_sec": remaining.as_secs_f64(),
                    "timeout_sec": entry.timeout.as_secs_f64(),
                }),
            );
        }
        Value::Object(result)
    }

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

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

impl Default for HeartbeatEngine {
    fn default() -> Self {
        Self::new(Duration::from_secs(300))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;

    #[test]
    fn test_register_and_ok() {
        let engine = HeartbeatEngine::new(Duration::from_secs(300));
        engine.register("worker", None);
        assert!(engine.all_ok());
    }

    #[test]
    fn test_timeout_detected() {
        let engine = HeartbeatEngine::new(Duration::from_millis(100));
        engine.register("worker", Some(Duration::from_millis(100)));
        assert!(engine.all_ok());
        thread::sleep(Duration::from_millis(200));
        assert!(!engine.all_ok());
    }

    #[test]
    fn test_refresh_resets_timer() {
        let engine = HeartbeatEngine::new(Duration::from_millis(150));
        engine.register("worker", Some(Duration::from_millis(150)));
        thread::sleep(Duration::from_millis(100));
        engine.refresh("worker");
        thread::sleep(Duration::from_millis(100));
        assert!(engine.all_ok()); // Should still be OK after refresh
    }

    #[test]
    fn test_cancel_removes() {
        let engine = HeartbeatEngine::new(Duration::from_millis(50));
        engine.register("worker", Some(Duration::from_millis(50)));
        engine.cancel("worker");
        thread::sleep(Duration::from_millis(100));
        assert!(engine.all_ok()); // Cancelled, so no timeout
    }

    #[test]
    fn test_get_status_format() {
        let engine = HeartbeatEngine::new(Duration::from_secs(300));
        engine.register("worker", None);
        let status = engine.get_status();
        assert!(status["worker"]["remaining_sec"].as_f64().unwrap() > 0.0);
        assert_eq!(status["worker"]["timeout_sec"].as_f64().unwrap(), 300.0);
    }

    #[test]
    fn test_get_name() {
        let engine = HeartbeatEngine::new(Duration::from_secs(300));
        assert_eq!(engine.get_name(), "Heartbeat manager");
    }

    #[test]
    fn test_expired_names_offenders_sorted() {
        let engine = HeartbeatEngine::new(Duration::from_secs(300));
        engine.register("ok", None);
        engine.register("late-b", Some(Duration::from_millis(50)));
        engine.register("late-a", Some(Duration::from_millis(50)));
        assert!(engine.expired().is_empty());
        thread::sleep(Duration::from_millis(100));
        assert_eq!(
            engine.expired(),
            vec!["late-a".to_string(), "late-b".to_string()]
        );
        assert!(!engine.all_ok());
        engine.refresh("late-a");
        assert_eq!(engine.expired(), vec!["late-b".to_string()]);
    }

    #[test]
    fn test_custom_status_name() {
        let engine = HeartbeatEngine::with_status_name(Duration::from_secs(300), "heartbeat");
        assert_eq!(engine.get_name(), "heartbeat");
    }
}