ctb_workspace_ipc/router/
heartbeat.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Heartbeat monitoring and liveness tracking for child processes.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::process_manager::ProcessManager;
30use crate::types::{ConnectionId, ProcessId};
31use std::collections::HashMap;
32use std::sync::{Arc, Mutex};
33use std::time::Duration;
34use tokio::time::{self, Instant};
35
36use tracing::Instrument as _;
37
38/// Tracks connection heartbeats and terminates associated processes when
39/// liveness timeouts are exceeded.
40
41#[derive(Debug)]
42pub struct HeartbeatTracker {
43    process_manager: Arc<dyn ProcessManager>,
44    check_interval: Duration,
45    /// Maximum silence before a connection is considered dead. `None` disables
46    /// timeouts.
47    max_silence: Option<Duration>,
48    state: Mutex<HashMap<ConnectionId, HeartbeatEntry>>,
49}
50
51#[derive(Debug, Clone)]
52struct HeartbeatEntry {
53    pid: ProcessId,
54    last_heartbeat: Instant,
55}
56
57impl HeartbeatTracker {
58    /// Create a new tracker and start a background checker task.
59    ///
60    /// `allowed_missed_intervals` controls after how many consecutive missed
61    /// intervals the connection is considered dead.
62    pub fn new(
63        process_manager: Arc<dyn ProcessManager>,
64        check_interval: Duration,
65        allowed_missed_intervals: u32,
66    ) -> Arc<Self> {
67        let max_silence = check_interval.checked_mul(allowed_missed_intervals);
68        let tracker = Arc::new(Self {
69            process_manager,
70            check_interval,
71            max_silence,
72            state: Mutex::new(HashMap::new()),
73        });
74        Self::spawn_checker(tracker.clone());
75        tracker
76    }
77
78    fn spawn_checker(tracker: Arc<Self>) {
79        let _ = tokio::spawn(async move {
80            tracker.run_checker().await;
81        });
82    }
83
84    async fn run_checker(self: Arc<Self>) {
85        let mut interval = time::interval(self.check_interval);
86
87        loop {
88            interval.tick().await;
89
90            let Some(max_silence) = self.max_silence else {
91                continue;
92            };
93
94            let now = Instant::now();
95            let to_terminate: Vec<(ConnectionId, ProcessId)> = {
96                let state_lock = self.state.lock();
97                let state = match state_lock {
98                    Ok(s) => s,
99                    Err(_) => break, // Poisoned
100                };
101                state
102                    .iter()
103                    .filter_map(|(conn_id, entry)| {
104                        let since = now.duration_since(entry.last_heartbeat);
105                        if since > max_silence {
106                            Some((*conn_id, entry.pid))
107                        } else {
108                            None
109                        }
110                    })
111                    .collect()
112            };
113
114            if to_terminate.is_empty() {
115                continue;
116            }
117
118            for (conn_id, pid) in to_terminate {
119                let span = tracing::info_span!(
120                    "ipc.heartbeat.timeout",
121                    conn_id = %conn_id,
122                    process_id = %pid
123                );
124
125                async {
126                    let _ =
127                        self.process_manager.terminate_tree(pid, true).await;
128                    if let Ok(mut state) = self.state.lock() {
129                        state.remove(&conn_id);
130                    }
131                }
132                .instrument(span)
133                .await;
134            }
135        }
136    }
137
138    /// Start tracking a connection and its owning process.
139    pub fn track_connection(&self, connection: ConnectionId, pid: ProcessId) {
140        let entry = HeartbeatEntry {
141            pid,
142            last_heartbeat: Instant::now(),
143        };
144
145        if let Ok(mut state) = self.state.lock() {
146            state.insert(connection, entry);
147        }
148    }
149
150    /// Record an observed heartbeat from the given connection.
151    pub fn record_heartbeat(&self, connection: &ConnectionId) {
152        if let Ok(mut state) = self.state.lock()
153            && let Some(entry) = state.get_mut(connection)
154        {
155            entry.last_heartbeat = Instant::now();
156        }
157    }
158
159    /// Stop tracking the given connection.
160    pub fn remove(&self, connection: &ConnectionId) {
161        if let Ok(mut state) = self.state.lock() {
162            state.remove(connection);
163        }
164    }
165
166    /// Check if a connection is currently tracked (test-only).
167    #[cfg(test)]
168    pub(super) fn is_tracked(&self, connection: &ConnectionId) -> bool {
169        if let Ok(state) = self.state.lock() {
170            state.contains_key(connection)
171        } else {
172            false
173        }
174    }
175}
176
177#[cfg(test)]
178#[allow(
179    clippy::panic,
180    clippy::expect_used,
181    clippy::unwrap_used,
182    clippy::unwrap_in_result,
183    clippy::panic_in_result_fn,
184    clippy::indexing_slicing,
185    clippy::arithmetic_side_effects,
186    reason = "Standard repository test boilerplate"
187)]
188mod tests {
189    use super::*;
190
191    use crate::process_manager::MockProcessManager;
192    use crate::router::heartbeat;
193
194    use crate::types::ProcessId;
195    use anyhow::Result;
196
197    /// Heartbeat miss should trigger termination and cleanup.
198    #[crate::ctb_test("tokio")]
199    async fn heartbeat_miss_triggers_termination_and_cleanup() -> Result<()> {
200        let manager = Arc::new(MockProcessManager::default());
201        let tracker = heartbeat::HeartbeatTracker::new(
202            manager.clone(),
203            Duration::from_millis(20),
204            1,
205        );
206
207        let conn = ConnectionId::default();
208        let pid = ProcessId::default();
209        tracker.track_connection(conn, pid);
210
211        // Do not record any heartbeat; allow multiple intervals to pass.
212        tokio::time::sleep(Duration::from_millis(100)).await;
213
214        let terms = manager.terminations();
215        assert_eq!(terms.len(), 1);
216        assert_eq!(terms[0].0, pid);
217        assert!(terms[0].1);
218        assert!(!tracker.is_tracked(&conn));
219
220        Ok(())
221    }
222}