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` via a subprocess, which returns success if the process exists
124/// and the current user has permission to signal it.
125/// On non-Unix platforms, always returns `false` (conservatively assumes the process is dead).
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            .map(|o| o.status.success())
142            .unwrap_or(false)
143    }
144    #[cfg(not(unix))]
145    {
146        let _ = pid;
147        false
148    }
149}
150
151/// Write a PID file atomically using `O_CREAT | O_EXCL` to prevent TOCTOU races.
152///
153/// # Errors
154///
155/// Returns an error if the PID file directory cannot be created, the file already exists,
156/// or the file cannot be written.
157pub fn write_pid_file(path: &str) -> std::io::Result<()> {
158    use std::io::Write as _;
159    let expanded = expand_tilde(path);
160    let path = std::path::Path::new(&expanded);
161    if let Some(parent) = path.parent() {
162        std::fs::create_dir_all(parent)?;
163    }
164    let mut file = std::fs::OpenOptions::new()
165        .write(true)
166        .create_new(true)
167        .open(path)?;
168    file.write_all(std::process::id().to_string().as_bytes())
169}
170
171/// Read the PID from a PID file.
172///
173/// # Errors
174///
175/// Returns an error if the file cannot be read or the content is not a valid PID.
176pub fn read_pid_file(path: &str) -> std::io::Result<u32> {
177    let expanded = expand_tilde(path);
178    let content = std::fs::read_to_string(&expanded)?;
179    content
180        .trim()
181        .parse::<u32>()
182        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
183}
184
185/// Remove the PID file.
186///
187/// # Errors
188///
189/// Returns an error if the file cannot be removed.
190pub fn remove_pid_file(path: &str) -> std::io::Result<()> {
191    let expanded = expand_tilde(path);
192    match std::fs::remove_file(&expanded) {
193        Ok(()) => Ok(()),
194        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
195        Err(e) => Err(e),
196    }
197}
198
199fn expand_tilde(path: &str) -> String {
200    if let Some(rest) = path.strip_prefix("~/")
201        && let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))
202    {
203        return format!("{}/{rest}", home.to_string_lossy());
204    }
205    path.to_owned()
206}
207
208#[cfg(test)]
209mod tests {
210    #![allow(clippy::field_reassign_with_default)]
211
212    use super::*;
213
214    #[test]
215    fn expand_tilde_with_home() {
216        let result = expand_tilde("~/test/file.pid");
217        assert!(!result.starts_with("~/"));
218    }
219
220    #[test]
221    fn expand_tilde_absolute_unchanged() {
222        assert_eq!(expand_tilde("/tmp/zeph.pid"), "/tmp/zeph.pid");
223    }
224
225    #[test]
226    fn pid_file_roundtrip() {
227        let dir = tempfile::tempdir().unwrap();
228        let path = dir.path().join("test.pid");
229        let path_str = path.to_string_lossy().to_string();
230
231        write_pid_file(&path_str).unwrap();
232        let pid = read_pid_file(&path_str).unwrap();
233        assert_eq!(pid, std::process::id());
234        remove_pid_file(&path_str).unwrap();
235        assert!(!path.exists());
236    }
237
238    #[test]
239    fn remove_nonexistent_pid_file_ok() {
240        assert!(remove_pid_file("/tmp/nonexistent_zeph_test.pid").is_ok());
241    }
242
243    #[test]
244    fn read_invalid_pid_file() {
245        let dir = tempfile::tempdir().unwrap();
246        let path = dir.path().join("bad.pid");
247        std::fs::write(&path, "not_a_number").unwrap();
248        assert!(read_pid_file(&path.to_string_lossy()).is_err());
249    }
250
251    #[tokio::test]
252    async fn supervisor_tracks_components() {
253        let config = DaemonConfig::default();
254        let (_tx, rx) = watch::channel(false);
255        let mut supervisor = DaemonSupervisor::new(&config, rx);
256
257        let handle = tokio::spawn(async { Ok::<(), DaemonError>(()) });
258        supervisor.add_component(ComponentHandle::new("test", handle));
259        assert_eq!(supervisor.component_count(), 1);
260    }
261
262    #[tokio::test]
263    async fn supervisor_detects_finished_component() {
264        let config = DaemonConfig::default();
265        let (_tx, rx) = watch::channel(false);
266        let mut supervisor = DaemonSupervisor::new(&config, rx);
267
268        let handle = tokio::spawn(async { Ok::<(), DaemonError>(()) });
269        tokio::time::sleep(Duration::from_millis(10)).await;
270        supervisor.add_component(ComponentHandle::new("finished", handle));
271        supervisor.check_health();
272
273        let statuses = supervisor.component_statuses();
274        assert_eq!(statuses.len(), 1);
275        assert!(matches!(statuses[0].1, ComponentStatus::Failed(_)));
276    }
277
278    #[tokio::test]
279    async fn supervisor_shutdown() {
280        let config = DaemonConfig {
281            health_interval_secs: 1,
282            ..DaemonConfig::default()
283        };
284        let (tx, rx) = watch::channel(false);
285        let mut supervisor = DaemonSupervisor::new(&config, rx);
286
287        let run_handle = tokio::spawn(async move { supervisor.run().await });
288        tokio::time::sleep(Duration::from_millis(50)).await;
289        let _ = tx.send(true);
290        tokio::time::timeout(Duration::from_secs(2), run_handle)
291            .await
292            .expect("supervisor should stop on shutdown")
293            .expect("task should complete");
294    }
295
296    #[test]
297    fn component_status_eq() {
298        assert_eq!(ComponentStatus::Running, ComponentStatus::Running);
299        assert_eq!(ComponentStatus::Stopped, ComponentStatus::Stopped);
300        assert_ne!(ComponentStatus::Running, ComponentStatus::Stopped);
301    }
302
303    #[test]
304    fn is_process_alive_current_process() {
305        let pid = std::process::id();
306        assert!(is_process_alive(pid), "current process must be alive");
307    }
308
309    #[test]
310    fn is_process_alive_nonexistent_pid() {
311        // u32::MAX is effectively guaranteed to not be a valid running PID.
312        assert!(
313            !is_process_alive(u32::MAX),
314            "PID u32::MAX must not be alive"
315        );
316    }
317}