Skip to main content

oxdock_process/
pump.rs

1//! Event-driven pump mechanism shared by host plugins.
2//!
3//! Every byte pump in the tree (SSH legs, NET sockets, child stdio)
4//! follows one choreography: worker threads move bytes between pipes
5//! and sinks, and a supervisor thread ends the session when the workers
6//! finish, the child exits, or the task cancels. The mechanism here is
7//! the part that never varies: a cancellation fan-out hub, a blocking
8//! pipe read, and an exactly-once completion delivery that survives
9//! worker panics. Supervisors keep their own event loops (pty drain
10//! waits and memory linger semantics genuinely differ), but no
11//! supervisor anywhere polls: workers wake on pipe data or close, the
12//! hub wakes on cancel, and completions arrive as messages.
13//!
14//! The one rule senders must honor: queue the message first, then poke
15//! the hub. A supervisor drains its queue before every hub wait, so a
16//! poke can never arrive for a message it has not queued yet, and no
17//! wakeup is ever lost.
18
19use std::sync::Arc;
20use std::sync::Condvar;
21use std::sync::Mutex;
22use std::sync::atomic::{AtomicU64, Ordering};
23use std::sync::mpsc::Sender;
24
25use oxdock_pipe::{PipeInner, SharedInput};
26
27/// Copy buffer size: 8192 bytes per chunk. Sized for interactive
28/// latency, not bulk throughput; bulk legs chunk above this.
29pub const PUMP_CHUNK: usize = 8192;
30
31/// Cancellation fan-out for one pump session. One hub per supervised
32/// call, shared by its workers and supervisor: `mark_cancelled` ends
33/// every waiter at once, `poke` wakes the supervisor for a queued
34/// event without cancelling. Sequence-guarded, so a poke that lands
35/// between the supervisor's drain and its wait still wakes it.
36#[derive(Debug)]
37pub struct CancelHub {
38    state: Mutex<bool>,
39    woken: Condvar,
40    sequence: AtomicU64,
41    /// Live workers guarded through this hub. Bumped on entry and
42    /// dropped before delivery in `run_guarded`, so observing zero
43    /// means every worker already exited. Shared (not fresh) across
44    /// forks: cancellation scopes per task, telemetry per script run,
45    /// which keeps parallel tests hermetic without a global counter.
46    active: Arc<AtomicU64>,
47}
48
49impl CancelHub {
50    /// Fresh hub: not cancelled, sequence zero, private telemetry.
51    pub fn new() -> Self {
52        Self::with_counter(Arc::new(AtomicU64::new(0)))
53    }
54
55    /// Fresh hub sharing an external worker count. Forks use this so
56    /// per-task cancellation stays independent while telemetry still
57    /// attributes to the originating run.
58    pub fn with_counter(counter: Arc<AtomicU64>) -> Self {
59        Self {
60            state: Mutex::new(false),
61            woken: Condvar::new(),
62            sequence: AtomicU64::new(0),
63            active: counter,
64        }
65    }
66
67    /// The shared worker count, for forks to inherit.
68    pub fn worker_counter(&self) -> Arc<AtomicU64> {
69        Arc::clone(&self.active)
70    }
71
72    /// Workers currently inside `run_guarded` on this hub.
73    pub fn active_workers(&self) -> u64 {
74        self.active.load(Ordering::SeqCst)
75    }
76
77    /// Current sequence. A supervisor records it, drains its queue,
78    /// then waits: any poke since the drain changes the sequence and
79    /// the wait returns at once.
80    pub fn sequence(&self) -> u64 {
81        self.sequence.load(Ordering::SeqCst)
82    }
83
84    /// Whether cancellation was marked. Checked after every wake;
85    /// flag checks on a wake are not polling.
86    pub fn is_cancelled(&self) -> bool {
87        self.state.lock().map(|flag| *flag).unwrap_or(true)
88    }
89
90    /// Mark cancellation and wake every waiter. Idempotent. Holds
91    /// the state lock across the bump and the notify: a waiter holds
92    /// the same lock across its check-to-sleep transition, so the wake
93    /// can never slip between the check and the sleep.
94    pub fn mark_cancelled(&self) {
95        let mut flag = self
96            .state
97            .lock()
98            .unwrap_or_else(|poison| poison.into_inner());
99        *flag = true;
100        self.sequence.fetch_add(1, Ordering::SeqCst);
101        self.woken.notify_all();
102    }
103
104    /// Wake the supervisor for a queued event. No state change. Holds
105    /// the state lock for the same lost-wakeup reasoning as
106    /// [`CancelHub::mark_cancelled`]: the bump and the notify are one
107    /// atomic step against every waiter's check-to-sleep.
108    pub fn poke(&self) {
109        let flag = self
110            .state
111            .lock()
112            .unwrap_or_else(|poison| poison.into_inner());
113        self.sequence.fetch_add(1, Ordering::SeqCst);
114        self.woken.notify_all();
115        drop(flag);
116    }
117
118    /// Block until cancellation or a poke past `seen`. Returns the
119    /// cancellation flag with the current sequence. Spurious wakes
120    /// re-check the predicate, never escape. The sequence is read
121    /// while still holding the lock so the returned value predates
122    /// the wakeup decision it informs.
123    pub fn wait(&self, seen: u64) -> (bool, u64) {
124        let mut flag = self
125            .state
126            .lock()
127            .unwrap_or_else(|poison| poison.into_inner());
128        while !*flag && self.sequence.load(Ordering::SeqCst) == seen {
129            flag = self
130                .woken
131                .wait(flag)
132                .unwrap_or_else(|poison| poison.into_inner());
133        }
134        let cancelled = *flag;
135        let current = self.sequence.load(Ordering::SeqCst);
136        drop(flag);
137        (cancelled, current)
138    }
139}
140
141impl Default for CancelHub {
142    fn default() -> Self {
143        Self::new()
144    }
145}
146
147/// One blocking chunk read for pump workers. Script backends wake on
148/// data, close, or `PipeInner::cancel`; anything else blocks in the OS
149/// read until its own EOF. Never times out: cancellation arrives as
150/// EOF through `cancel`, not as a backstop tick.
151pub fn read_pump_chunk(reader: &SharedInput, buf: &mut [u8]) -> std::io::Result<usize> {
152    let mut guard = reader
153        .lock()
154        .map_err(|_| std::io::Error::other("pump input lock poisoned"))?;
155    guard.read(buf)
156}
157
158/// Run a worker body to completion, delivering `done` to `tx` exactly
159/// once whether the body returns or panics, then poking `hub` so a
160/// supervisor parked in [`CancelHub::wait`] ends its wait and drains
161/// the queue. A supervisor drains before every wait and the hub is
162/// sequence-guarded, so the completion can never arrive after the wait
163/// starts yet go unseen: send-then-poke is the one rule. A supervisor
164/// that waits on messages instead of joining handles must observe
165/// panics too, or a panicking worker strands it past scope end. The
166/// outcome (value or panic) rides in the message; the join handle just
167/// returns unit.
168pub fn run_guarded<T, M: Send>(
169    hub: &CancelHub,
170    tx: &Sender<M>,
171    done: impl FnOnce(std::thread::Result<T>) -> M,
172    body: impl FnOnce() -> T,
173) {
174    // Instance telemetry on the hub (not a global): bumped on entry
175    // and dropped when the body returns, before the completion send,
176    // so a received completion implies the decrement is visible.
177    // Reapers, watchers, and one-shot sleepers are not counted: each
178    // has a bounded termination proof (kill, explicit retire plus
179    // join, finite sleep), so only the unbounded-read set is watched.
180    hub.active.fetch_add(1, Ordering::SeqCst);
181    let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(body));
182    hub.active.fetch_sub(1, Ordering::SeqCst);
183    // Poke on drop so a panicking `done` still wakes the supervisor.
184    // The explicit poke below disarms this; the double wake would be
185    // harmless (sequence bump plus notify) but one wake is enough.
186    // All current `done` closures are infallible enum constructors.
187    struct PokeGuard<'a> {
188        hub: &'a CancelHub,
189        armed: bool,
190    }
191    impl Drop for PokeGuard<'_> {
192        fn drop(&mut self) {
193            if self.armed {
194                self.hub.poke();
195            }
196        }
197    }
198    let mut poke = PokeGuard { hub, armed: true };
199    let _ = tx.send(done(outcome));
200    hub.poke();
201    poke.armed = false;
202}
203
204/// RAII cancellation bridge for single-threaded pumps (no supervisor
205/// thread of their own to translate the hub). Arms a waiter that
206/// cancels each pipe when the hub fires; dropping the guard releases
207/// the waiter. The pump loop itself stays a blocking read: cancel
208/// arrives as EOF, never as a tick.
209pub struct CancelGuard {
210    hub: Arc<CancelHub>,
211    waiter: Option<std::thread::JoinHandle<()>>,
212    /// Rendezvous: the waiter signals after reading its sequence and
213    /// before parking, so a release that lands before the wait still
214    /// wakes it. A bare poke is edge-triggered and would be lost.
215    started: std::sync::mpsc::Receiver<()>,
216}
217
218impl CancelGuard {
219    /// Watch `hub`, cancelling every pipe in `pipes` on fire. The hub
220    /// must outlive the guard; pipes are usually task-scoped.
221    pub fn arm(hub: &Arc<CancelHub>, pipes: Vec<Arc<PipeInner>>) -> Self {
222        let watched = Arc::clone(hub);
223        let (started_tx, started_rx) = std::sync::mpsc::channel();
224        let waiter = std::thread::spawn(move || {
225            let seen = watched.sequence();
226            let _ = started_tx.send(());
227            let (cancelled, _) = watched.wait(seen);
228            if cancelled {
229                for pipe in &pipes {
230                    pipe.cancel();
231                }
232            }
233        });
234        Self {
235            hub: Arc::clone(hub),
236            waiter: Some(waiter),
237            started: started_rx,
238        }
239    }
240}
241
242impl Drop for CancelGuard {
243    fn drop(&mut self) {
244        // Rendezvous first (the waiter reached its wait), then poke
245        // (never cancel: the pump may have ended cleanly), then join:
246        // no thread outlives the pump. The poke also wakes any hub
247        // supervisor; its predicate re-check absorbs it.
248        let _ = self.started.recv();
249        self.hub.poke();
250        if let Some(waiter) = self.waiter.take() {
251            let _ = waiter.join();
252        }
253    }
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259
260    #[test]
261    fn hub_wait_returns_on_poke_without_cancelling() {
262        let hub = CancelHub::new();
263        let seen = hub.sequence();
264        hub.poke();
265        let (cancelled, next) = hub.wait(seen);
266        assert!(!cancelled);
267        assert_ne!(next, seen);
268    }
269
270    #[test]
271    fn hub_wait_wakes_on_cancel_from_another_thread() {
272        // Same contract the supervisors rely on: a thread parked in
273        // `wait` returns once `mark_cancelled` runs elsewhere.
274        let hub = Arc::new(CancelHub::new());
275        let parked = Arc::clone(&hub);
276        let waiter = std::thread::spawn(move || parked.wait(parked.sequence()));
277        std::thread::sleep(std::time::Duration::from_millis(50));
278        hub.mark_cancelled();
279        let (cancelled, _) = waiter.join().expect("waiter joins");
280        assert!(cancelled);
281    }
282
283    #[test]
284    fn guarded_delivery_survives_panic() {
285        let hub = CancelHub::new();
286        let (tx, rx) = std::sync::mpsc::channel();
287        run_guarded(
288            &hub,
289            &tx,
290            |outcome: std::thread::Result<u32>| outcome.is_err(),
291            || -> u32 { panic!("boom") },
292        );
293        assert!(rx.recv().expect("exactly one message"), "panic delivered");
294    }
295
296    #[test]
297    fn guarded_worker_gauge_balances() {
298        // The gauge brackets the body synchronously here (no threads),
299        // so this is deterministic: every entry pairs with exactly one
300        // exit, including through panics. Per-hub telemetry keeps it
301        // hermetic under parallel harnesses: no global to pollute.
302        let hub = CancelHub::new();
303        let (tx, rx) = std::sync::mpsc::channel();
304        assert_eq!(hub.active_workers(), 0);
305        run_guarded(
306            &hub,
307            &tx,
308            |outcome: std::thread::Result<u32>| outcome,
309            || {
310                assert_eq!(hub.active_workers(), 1, "entry counted");
311                41
312            },
313        );
314        run_guarded(
315            &hub,
316            &tx,
317            |outcome: std::thread::Result<u32>| outcome,
318            || -> u32 { panic!("boom") },
319        );
320        assert_eq!(hub.active_workers(), 0, "entries pair with exits");
321        drop((rx, hub));
322    }
323
324    #[test]
325    fn guard_cancels_pipes_on_fire_and_joins_on_drop() {
326        use oxdock_pipe::ScriptPipe;
327        let pipe = ScriptPipe::new();
328        let inner = pipe.pipe_inner();
329        let hub = Arc::new(CancelHub::new());
330        {
331            let _guard = CancelGuard::arm(&hub, vec![inner.clone()]);
332            hub.mark_cancelled();
333        }
334        assert!(inner.is_cancelled(), "waiter cancelled the pipe");
335    }
336}