use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
use astrs_wire::StopCause;
use tokio::task::JoinHandle;
use crate::events::{Event, EventSource};
use crate::runtime::NodeRuntime;
pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_secs(2);
#[must_use]
pub fn process_exists(pid: u32) -> bool {
#[cfg(unix)]
{
let Ok(raw) = i32::try_from(pid) else {
return false;
};
let Some(pid) = rustix::process::Pid::from_raw(raw) else {
return false;
};
match rustix::process::test_kill_process(pid) {
Ok(()) => true,
Err(error) => error == rustix::io::Errno::PERM,
}
}
#[cfg(not(unix))]
{
let _ = pid;
true
}
}
#[derive(Debug)]
pub struct OrphanGuard {
parent: u32,
stop: Arc<AtomicBool>,
fired: Arc<AtomicBool>,
polls: Arc<AtomicU64>,
task: JoinHandle<()>,
}
impl OrphanGuard {
#[must_use]
pub fn watch(
parent: u32,
runtime: &NodeRuntime,
source: Arc<EventSource>,
interval: Duration,
) -> Self {
let stop = Arc::new(AtomicBool::new(false));
let fired = Arc::new(AtomicBool::new(false));
let polls = Arc::new(AtomicU64::new(0));
let task = {
let stop = Arc::clone(&stop);
let fired = Arc::clone(&fired);
let polls = Arc::clone(&polls);
runtime.spawn(async move {
let interval = interval.max(Duration::from_millis(10));
loop {
tokio::time::sleep(interval).await;
if stop.load(Ordering::Acquire) || source.is_closed() {
return;
}
polls.fetch_add(1, Ordering::Relaxed);
if process_exists(parent) {
continue;
}
fired.store(true, Ordering::Release);
source.push_control(Event::Error(format!(
"the supervising process {parent} exited; this node is orphaned"
)));
source.push_control(Event::Stop(StopCause::DaemonShutdown));
return;
}
})
};
Self {
parent,
stop,
fired,
polls,
task,
}
}
#[must_use]
pub fn maybe_watch(
parent: Option<u32>,
runtime: &NodeRuntime,
source: Arc<EventSource>,
interval: Duration,
) -> Option<Self> {
parent.map(|parent| Self::watch(parent, runtime, source, interval))
}
#[must_use]
pub const fn parent(&self) -> u32 {
self.parent
}
#[must_use]
pub fn has_fired(&self) -> bool {
self.fired.load(Ordering::Acquire)
}
#[must_use]
pub fn poll_count(&self) -> u64 {
self.polls.load(Ordering::Relaxed)
}
pub fn stop(&self) {
self.stop.store(true, Ordering::Release);
}
}
impl Drop for OrphanGuard {
fn drop(&mut self) {
self.stop();
self.task.abort();
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn this_process_exists_and_an_impossible_pid_does_not() {
assert!(process_exists(std::process::id()));
assert!(!process_exists(u32::MAX));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_live_parent_keeps_the_node_running() {
let source = Arc::new(EventSource::new());
let runtime = NodeRuntime::acquire().unwrap();
let guard = OrphanGuard::watch(
std::process::id(),
&runtime,
Arc::clone(&source),
Duration::from_millis(10),
);
tokio::time::sleep(Duration::from_millis(80)).await;
assert!(!guard.has_fired());
assert!(guard.poll_count() >= 1, "the watch is actually polling");
assert!(source.try_next().is_none());
assert_eq!(guard.parent(), std::process::id());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_dead_parent_stops_the_node() {
let source = Arc::new(EventSource::new());
let runtime = NodeRuntime::acquire().unwrap();
let _guard = OrphanGuard::watch(
u32::MAX,
&runtime,
Arc::clone(&source),
Duration::from_millis(10),
);
for _ in 0..200 {
if let Some(event) = source.try_next() {
let Event::Error(message) = event else {
panic!("expected the orphan report first");
};
assert!(message.contains("orphaned"), "{message}");
let stop = source.try_next().unwrap();
assert!(stop.is_stop());
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("the guard never fired");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn stopping_the_guard_ends_the_watch() {
let source = Arc::new(EventSource::new());
let runtime = NodeRuntime::acquire().unwrap();
let guard = OrphanGuard::watch(
u32::MAX,
&runtime,
Arc::clone(&source),
Duration::from_millis(500),
);
guard.stop();
drop(guard);
tokio::time::sleep(Duration::from_millis(30)).await;
assert!(source.try_next().is_none(), "a stopped guard says nothing");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn no_parent_means_no_guard() {
let source = Arc::new(EventSource::new());
let runtime = NodeRuntime::acquire().unwrap();
assert!(OrphanGuard::maybe_watch(None, &runtime, source, DEFAULT_POLL_INTERVAL).is_none());
}
#[test]
fn the_default_interval_is_documented() {
assert_eq!(DEFAULT_POLL_INTERVAL, Duration::from_secs(2));
}
}