Skip to main content

zeph_core/
daemon.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Daemon supervisor for component lifecycle management.
5
6use std::time::Duration;
7
8use tokio::sync::watch;
9use tokio::task::JoinHandle;
10
11use crate::config::DaemonConfig;
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum ComponentStatus {
15    Running,
16    Failed(String),
17    Stopped,
18}
19
20/// Error type for daemon component task failures.
21#[derive(Debug, thiserror::Error)]
22pub enum DaemonError {
23    #[error("task error: {0}")]
24    Task(String),
25    #[error("shutdown error: {0}")]
26    Shutdown(String),
27}
28
29pub struct ComponentHandle {
30    pub name: String,
31    handle: JoinHandle<Result<(), DaemonError>>,
32    pub status: ComponentStatus,
33    pub restart_count: u32,
34}
35
36impl ComponentHandle {
37    #[must_use]
38    pub fn new(name: impl Into<String>, handle: JoinHandle<Result<(), DaemonError>>) -> Self {
39        Self {
40            name: name.into(),
41            handle,
42            status: ComponentStatus::Running,
43            restart_count: 0,
44        }
45    }
46
47    #[must_use]
48    pub fn is_finished(&self) -> bool {
49        self.handle.is_finished()
50    }
51}
52
53pub struct DaemonSupervisor {
54    components: Vec<ComponentHandle>,
55    health_interval: Duration,
56    _max_backoff: Duration,
57    shutdown_rx: watch::Receiver<bool>,
58}
59
60impl DaemonSupervisor {
61    #[must_use]
62    pub fn new(config: &DaemonConfig, shutdown_rx: watch::Receiver<bool>) -> Self {
63        Self {
64            components: Vec::new(),
65            health_interval: Duration::from_secs(config.health_interval_secs),
66            _max_backoff: Duration::from_secs(config.max_restart_backoff_secs),
67            shutdown_rx,
68        }
69    }
70
71    pub fn add_component(&mut self, handle: ComponentHandle) {
72        self.components.push(handle);
73    }
74
75    #[must_use]
76    pub fn component_count(&self) -> usize {
77        self.components.len()
78    }
79
80    /// Run the health monitoring loop until shutdown signal.
81    pub async fn run(&mut self) {
82        let mut interval = tokio::time::interval(self.health_interval);
83        loop {
84            tokio::select! {
85                _ = interval.tick() => {
86                    self.check_health();
87                }
88                _ = self.shutdown_rx.changed() => {
89                    if *self.shutdown_rx.borrow() {
90                        tracing::info!("daemon supervisor shutting down");
91                        break;
92                    }
93                }
94            }
95        }
96    }
97
98    fn check_health(&mut self) {
99        for component in &mut self.components {
100            if component.status == ComponentStatus::Running && component.is_finished() {
101                component.status = ComponentStatus::Failed("task exited".into());
102                component.restart_count += 1;
103                tracing::warn!(
104                    component = %component.name,
105                    restarts = component.restart_count,
106                    "component exited unexpectedly"
107                );
108            }
109        }
110    }
111
112    #[must_use]
113    pub fn component_statuses(&self) -> Vec<(&str, &ComponentStatus)> {
114        self.components
115            .iter()
116            .map(|c| (c.name.as_str(), &c.status))
117            .collect()
118    }
119}
120
121/// Check whether a process with the given PID is currently alive.
122///
123/// On Unix, uses `kill -0` which returns success if the process exists and the current user
124/// has permission to signal it.
125/// On Windows, uses `tasklist /FI "PID eq <pid>"` and checks for the PID in the output.
126#[must_use]
127pub fn is_process_alive(pid: u32) -> bool {
128    #[cfg(unix)]
129    {
130        // PIDs on Unix are signed (pid_t = i32); u32::MAX wraps to -1 which would
131        // signal every process, so reject anything that does not fit in a positive i32.
132        let Ok(signed) = i32::try_from(pid) else {
133            return false;
134        };
135        if signed <= 0 {
136            return false;
137        }
138        std::process::Command::new("kill")
139            .args(["-0", &signed.to_string()])
140            .output()
141            .is_ok_and(|o| o.status.success())
142    }
143    #[cfg(windows)]
144    {
145        std::process::Command::new("tasklist")
146            .args(["/FI", &format!("PID eq {pid}"), "/NH", "/FO", "CSV"])
147            .output()
148            .map(|o| {
149                let stdout = String::from_utf8_lossy(&o.stdout);
150                // tasklist outputs lines like: "process.exe","PID","..."
151                // We look for the PID appearing as a quoted field.
152                stdout.contains(&format!("\"{pid}\""))
153            })
154            .unwrap_or(false)
155    }
156    #[cfg(not(any(unix, windows)))]
157    {
158        let _ = pid;
159        false
160    }
161}
162
163/// Write a PID file atomically using `O_CREAT | O_EXCL` to prevent TOCTOU races.
164///
165/// # Errors
166///
167/// Returns an error if the PID file directory cannot be created, the file already exists,
168/// or the file cannot be written.
169pub fn write_pid_file(path: &str) -> std::io::Result<()> {
170    use std::io::Write as _;
171    let expanded = expand_tilde(path);
172    let path = std::path::Path::new(&expanded);
173    if let Some(parent) = path.parent() {
174        std::fs::create_dir_all(parent)?;
175    }
176    let mut file = std::fs::OpenOptions::new()
177        .write(true)
178        .create_new(true)
179        .open(path)?;
180    file.write_all(std::process::id().to_string().as_bytes())
181}
182
183/// Read the PID from a PID file.
184///
185/// # Errors
186///
187/// Returns an error if the file cannot be read or the content is not a valid PID.
188pub fn read_pid_file(path: &str) -> std::io::Result<u32> {
189    let expanded = expand_tilde(path);
190    let content = std::fs::read_to_string(&expanded)?;
191    content
192        .trim()
193        .parse::<u32>()
194        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
195}
196
197/// Remove the PID file.
198///
199/// # Errors
200///
201/// Returns an error if the file cannot be removed.
202pub fn remove_pid_file(path: &str) -> std::io::Result<()> {
203    let expanded = expand_tilde(path);
204    match std::fs::remove_file(&expanded) {
205        Ok(()) => Ok(()),
206        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
207        Err(e) => Err(e),
208    }
209}
210
211fn expand_tilde(path: &str) -> String {
212    if let Some(rest) = path.strip_prefix("~/")
213        && let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))
214    {
215        return format!("{}/{rest}", home.to_string_lossy());
216    }
217    path.to_owned()
218}
219
220#[cfg(test)]
221mod tests {
222    #![allow(clippy::field_reassign_with_default)]
223
224    use super::*;
225
226    #[test]
227    fn expand_tilde_with_home() {
228        let result = expand_tilde("~/test/file.pid");
229        assert!(!result.starts_with("~/"));
230    }
231
232    #[test]
233    fn expand_tilde_absolute_unchanged() {
234        assert_eq!(expand_tilde("/tmp/zeph.pid"), "/tmp/zeph.pid");
235    }
236
237    #[test]
238    fn pid_file_roundtrip() {
239        let dir = tempfile::tempdir().unwrap();
240        let path = dir.path().join("test.pid");
241        let path_str = path.to_string_lossy().to_string();
242
243        write_pid_file(&path_str).unwrap();
244        let pid = read_pid_file(&path_str).unwrap();
245        assert_eq!(pid, std::process::id());
246        remove_pid_file(&path_str).unwrap();
247        assert!(!path.exists());
248    }
249
250    #[test]
251    fn remove_nonexistent_pid_file_ok() {
252        assert!(remove_pid_file("/tmp/nonexistent_zeph_test.pid").is_ok());
253    }
254
255    #[test]
256    fn read_invalid_pid_file() {
257        let dir = tempfile::tempdir().unwrap();
258        let path = dir.path().join("bad.pid");
259        std::fs::write(&path, "not_a_number").unwrap();
260        assert!(read_pid_file(&path.to_string_lossy()).is_err());
261    }
262
263    #[tokio::test]
264    async fn supervisor_tracks_components() {
265        let config = DaemonConfig::default();
266        let (_tx, rx) = watch::channel(false);
267        let mut supervisor = DaemonSupervisor::new(&config, rx);
268
269        let handle = tokio::spawn(async { Ok::<(), DaemonError>(()) });
270        supervisor.add_component(ComponentHandle::new("test", handle));
271        assert_eq!(supervisor.component_count(), 1);
272    }
273
274    #[tokio::test]
275    async fn supervisor_detects_finished_component() {
276        let config = DaemonConfig::default();
277        let (_tx, rx) = watch::channel(false);
278        let mut supervisor = DaemonSupervisor::new(&config, rx);
279
280        let handle = tokio::spawn(async { Ok::<(), DaemonError>(()) });
281        tokio::time::sleep(Duration::from_millis(10)).await;
282        supervisor.add_component(ComponentHandle::new("finished", handle));
283        supervisor.check_health();
284
285        let statuses = supervisor.component_statuses();
286        assert_eq!(statuses.len(), 1);
287        assert!(matches!(statuses[0].1, ComponentStatus::Failed(_)));
288    }
289
290    #[tokio::test]
291    async fn supervisor_shutdown() {
292        let config = DaemonConfig {
293            health_interval_secs: 1,
294            ..DaemonConfig::default()
295        };
296        let (tx, rx) = watch::channel(false);
297        let mut supervisor = DaemonSupervisor::new(&config, rx);
298
299        let run_handle = tokio::spawn(async move { supervisor.run().await });
300        tokio::time::sleep(Duration::from_millis(50)).await;
301        let _ = tx.send(true);
302        tokio::time::timeout(Duration::from_secs(2), run_handle)
303            .await
304            .expect("supervisor should stop on shutdown")
305            .expect("task should complete");
306    }
307
308    #[test]
309    fn component_status_eq() {
310        assert_eq!(ComponentStatus::Running, ComponentStatus::Running);
311        assert_eq!(ComponentStatus::Stopped, ComponentStatus::Stopped);
312        assert_ne!(ComponentStatus::Running, ComponentStatus::Stopped);
313    }
314
315    #[test]
316    fn is_process_alive_current_process() {
317        let pid = std::process::id();
318        assert!(is_process_alive(pid), "current process must be alive");
319    }
320
321    #[test]
322    fn is_process_alive_nonexistent_pid() {
323        // u32::MAX is effectively guaranteed to not be a valid running PID.
324        assert!(
325            !is_process_alive(u32::MAX),
326            "PID u32::MAX must not be alive"
327        );
328    }
329}