Skip to main content

fallow_cli/signal/
registry.rs

1//! Process-wide registry of live spawned-child PIDs.
2//!
3//! Keyed by a monotonic `AtomicU64` counter rather than `Child::id()`
4//! because POSIX recycles PIDs aggressively on long-running runners; a
5//! recycled PID would collide with a previously-deregistered entry.
6//!
7//! Stores PIDs (not `Child` handles): the `ScopedChild` wrapper owns
8//! the `Child` outright so it can call `wait_with_output` / `wait`
9//! normally, and the signal handler kills by PID via a `kill -9
10//! <pid>` shell subprocess on Unix (avoids adding `libc` as a
11//! workspace dep) or `OpenProcess + TerminateProcess` on Windows. No
12//! ownership transfer, no race between wait and kill.
13
14use std::sync::atomic::{AtomicU64, Ordering};
15use std::sync::{Mutex, OnceLock};
16use std::time::{Duration, Instant};
17
18use rustc_hash::FxHashMap;
19
20static NEXT_ID: AtomicU64 = AtomicU64::new(1);
21static REGISTRY: OnceLock<Mutex<FxHashMap<u64, u32>>> = OnceLock::new();
22
23/// One-shot guard: repeated signals during drain (signal storm) no-op
24/// the second-and-onwards entries.
25static DRAINING: AtomicU64 = AtomicU64::new(0);
26
27fn registry() -> &'static Mutex<FxHashMap<u64, u32>> {
28    REGISTRY.get_or_init(|| Mutex::new(FxHashMap::default()))
29}
30
31/// Register `pid`. Returns a monotonic key the caller stores in their
32/// `ScopedChild` for deregister at wait/drop time.
33pub(super) fn register(pid: u32) -> u64 {
34    let id = NEXT_ID.fetch_add(1, Ordering::SeqCst);
35    registry()
36        .lock()
37        .unwrap_or_else(|e| e.into_inner())
38        .insert(id, pid);
39    id
40}
41
42/// Remove the registry entry for `id`. Idempotent.
43pub(super) fn deregister(id: u64) {
44    registry()
45        .lock()
46        .unwrap_or_else(|e| e.into_inner())
47        .remove(&id);
48}
49
50/// Snapshot every registered PID and kill each. Polls for liveness
51/// with a bounded budget. Caller is the platform signal handler thread.
52///
53/// First-call-wins via the `DRAINING` guard: subsequent invocations
54/// during the same shutdown skip the body to avoid re-entering the
55/// lock under signal storm.
56pub(super) fn drain_and_kill() {
57    if DRAINING
58        .compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst)
59        .is_err()
60    {
61        return;
62    }
63
64    let pids: Vec<u32> = {
65        registry()
66            .lock()
67            .unwrap_or_else(|e| e.into_inner())
68            .drain()
69            .map(|(_id, pid)| pid)
70            .collect()
71    };
72
73    for pid in &pids {
74        kill_pid(*pid);
75    }
76
77    let deadline = Instant::now() + drain_budget();
78    while Instant::now() < deadline {
79        if !pids.iter().copied().any(pid_is_alive) {
80            return;
81        }
82        std::thread::sleep(Duration::from_millis(50));
83    }
84}
85
86#[cfg(unix)]
87fn kill_pid(pid: u32) {
88    let _ = std::process::Command::new("kill")
89        .args(["-9", &pid.to_string()])
90        .stdout(std::process::Stdio::null())
91        .stderr(std::process::Stdio::null())
92        .status();
93}
94
95#[cfg(windows)]
96#[expect(
97    unsafe_code,
98    reason = "FFI to Win32 OpenProcess/TerminateProcess/CloseHandle; preconditions documented inline"
99)]
100fn kill_pid(pid: u32) {
101    use windows_sys::Win32::Foundation::{CloseHandle, FALSE, HANDLE};
102    use windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_TERMINATE, TerminateProcess};
103    // SAFETY: OpenProcess returns null on failure (which we check),
104    // TerminateProcess with exit code 1 is a no-op if the handle is
105    // null. CloseHandle on a valid handle is well-defined.
106    unsafe {
107        let handle: HANDLE = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
108        if handle.is_null() {
109            return;
110        }
111        let _ = TerminateProcess(handle, 1);
112        let _ = CloseHandle(handle);
113    }
114}
115
116#[cfg(not(any(unix, windows)))]
117fn kill_pid(_pid: u32) {}
118
119#[cfg(unix)]
120fn pid_is_alive(pid: u32) -> bool {
121    std::process::Command::new("kill")
122        .args(["-0", &pid.to_string()])
123        .stdout(std::process::Stdio::null())
124        .stderr(std::process::Stdio::null())
125        .status()
126        .is_ok_and(|s| s.success())
127}
128
129#[cfg(windows)]
130#[expect(
131    unsafe_code,
132    reason = "FFI to Win32 OpenProcess/WaitForSingleObject/CloseHandle; preconditions documented inline"
133)]
134fn pid_is_alive(pid: u32) -> bool {
135    use windows_sys::Win32::Foundation::{CloseHandle, FALSE, HANDLE, WAIT_OBJECT_0};
136    use windows_sys::Win32::System::Threading::{
137        OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, WaitForSingleObject,
138    };
139    // SAFETY: identical safety contract as kill_pid.
140    unsafe {
141        let handle: HANDLE = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
142        if handle.is_null() {
143            return false;
144        }
145        let result = WaitForSingleObject(handle, 0);
146        let _ = CloseHandle(handle);
147        result != WAIT_OBJECT_0
148    }
149}
150
151#[cfg(not(any(unix, windows)))]
152fn pid_is_alive(_pid: u32) -> bool {
153    false
154}
155
156#[cfg(unix)]
157const fn drain_budget() -> Duration {
158    Duration::from_millis(500)
159}
160
161#[cfg(windows)]
162const fn drain_budget() -> Duration {
163    Duration::from_millis(1500)
164}
165
166#[cfg(not(any(unix, windows)))]
167const fn drain_budget() -> Duration {
168    Duration::from_millis(500)
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    #[test]
176    fn register_deregister_roundtrip() {
177        let id = register(42);
178        assert!(id > 0);
179        deregister(id);
180        deregister(id);
181    }
182
183    #[test]
184    fn ids_are_monotonic() {
185        let a = register(100);
186        let b = register(200);
187        assert!(b > a);
188        deregister(a);
189        deregister(b);
190    }
191}