1use std::sync::Arc;
36use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
37use std::time::Duration;
38
39use astrs_wire::StopCause;
40use tokio::task::JoinHandle;
41
42use crate::events::{Event, EventSource};
43use crate::runtime::NodeRuntime;
44
45pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_secs(2);
50
51#[must_use]
70pub fn process_exists(pid: u32) -> bool {
71 #[cfg(unix)]
72 {
73 let Ok(raw) = i32::try_from(pid) else {
74 return false;
75 };
76 let Some(pid) = rustix::process::Pid::from_raw(raw) else {
77 return false;
78 };
79 match rustix::process::test_kill_process(pid) {
80 Ok(()) => true,
81 Err(error) => error == rustix::io::Errno::PERM,
85 }
86 }
87 #[cfg(not(unix))]
88 {
89 let _ = pid;
90 true
91 }
92}
93
94#[derive(Debug)]
96pub struct OrphanGuard {
97 parent: u32,
99 stop: Arc<AtomicBool>,
101 fired: Arc<AtomicBool>,
103 polls: Arc<AtomicU64>,
105 task: JoinHandle<()>,
107}
108
109impl OrphanGuard {
110 #[must_use]
112 pub fn watch(
113 parent: u32,
114 runtime: &NodeRuntime,
115 source: Arc<EventSource>,
116 interval: Duration,
117 ) -> Self {
118 let stop = Arc::new(AtomicBool::new(false));
119 let fired = Arc::new(AtomicBool::new(false));
120 let polls = Arc::new(AtomicU64::new(0));
121 let task = {
122 let stop = Arc::clone(&stop);
123 let fired = Arc::clone(&fired);
124 let polls = Arc::clone(&polls);
125 runtime.spawn(async move {
126 let interval = interval.max(Duration::from_millis(10));
127 loop {
128 tokio::time::sleep(interval).await;
129 if stop.load(Ordering::Acquire) || source.is_closed() {
130 return;
131 }
132 polls.fetch_add(1, Ordering::Relaxed);
133 if process_exists(parent) {
134 continue;
135 }
136 fired.store(true, Ordering::Release);
137 source.push_control(Event::Error(format!(
138 "the supervising process {parent} exited; this node is orphaned"
139 )));
140 source.push_control(Event::Stop(StopCause::DaemonShutdown));
141 return;
142 }
143 })
144 };
145 Self {
146 parent,
147 stop,
148 fired,
149 polls,
150 task,
151 }
152 }
153
154 #[must_use]
156 pub fn maybe_watch(
157 parent: Option<u32>,
158 runtime: &NodeRuntime,
159 source: Arc<EventSource>,
160 interval: Duration,
161 ) -> Option<Self> {
162 parent.map(|parent| Self::watch(parent, runtime, source, interval))
163 }
164
165 #[must_use]
167 pub const fn parent(&self) -> u32 {
168 self.parent
169 }
170
171 #[must_use]
173 pub fn has_fired(&self) -> bool {
174 self.fired.load(Ordering::Acquire)
175 }
176
177 #[must_use]
179 pub fn poll_count(&self) -> u64 {
180 self.polls.load(Ordering::Relaxed)
181 }
182
183 pub fn stop(&self) {
187 self.stop.store(true, Ordering::Release);
188 }
189}
190
191impl Drop for OrphanGuard {
192 fn drop(&mut self) {
193 self.stop();
194 self.task.abort();
195 }
196}
197
198#[cfg(test)]
199mod tests {
200 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
201
202 use super::*;
203
204 #[test]
205 fn this_process_exists_and_an_impossible_pid_does_not() {
206 assert!(process_exists(std::process::id()));
207 assert!(!process_exists(u32::MAX));
210 }
211
212 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
213 async fn a_live_parent_keeps_the_node_running() {
214 let source = Arc::new(EventSource::new());
215 let runtime = NodeRuntime::acquire().unwrap();
216 let guard = OrphanGuard::watch(
217 std::process::id(),
218 &runtime,
219 Arc::clone(&source),
220 Duration::from_millis(10),
221 );
222 tokio::time::sleep(Duration::from_millis(80)).await;
223 assert!(!guard.has_fired());
224 assert!(guard.poll_count() >= 1, "the watch is actually polling");
225 assert!(source.try_next().is_none());
226 assert_eq!(guard.parent(), std::process::id());
227 }
228
229 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
230 async fn a_dead_parent_stops_the_node() {
231 let source = Arc::new(EventSource::new());
232 let runtime = NodeRuntime::acquire().unwrap();
233 let _guard = OrphanGuard::watch(
234 u32::MAX,
235 &runtime,
236 Arc::clone(&source),
237 Duration::from_millis(10),
238 );
239 for _ in 0..200 {
240 if let Some(event) = source.try_next() {
241 let Event::Error(message) = event else {
242 panic!("expected the orphan report first");
243 };
244 assert!(message.contains("orphaned"), "{message}");
245 let stop = source.try_next().unwrap();
246 assert!(stop.is_stop());
247 return;
248 }
249 tokio::time::sleep(Duration::from_millis(10)).await;
250 }
251 panic!("the guard never fired");
252 }
253
254 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
255 async fn stopping_the_guard_ends_the_watch() {
256 let source = Arc::new(EventSource::new());
257 let runtime = NodeRuntime::acquire().unwrap();
258 let guard = OrphanGuard::watch(
259 u32::MAX,
260 &runtime,
261 Arc::clone(&source),
262 Duration::from_millis(500),
263 );
264 guard.stop();
265 drop(guard);
266 tokio::time::sleep(Duration::from_millis(30)).await;
267 assert!(source.try_next().is_none(), "a stopped guard says nothing");
268 }
269
270 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
271 async fn no_parent_means_no_guard() {
272 let source = Arc::new(EventSource::new());
273 let runtime = NodeRuntime::acquire().unwrap();
274 assert!(OrphanGuard::maybe_watch(None, &runtime, source, DEFAULT_POLL_INTERVAL).is_none());
275 }
276
277 #[test]
278 fn the_default_interval_is_documented() {
279 assert_eq!(DEFAULT_POLL_INTERVAL, Duration::from_secs(2));
280 }
281}