crumbkit_process/cancel.rs
1//! The handle that stops a run from another thread.
2
3use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
4
5use crate::notice::Notice;
6
7/// A handle that stops the runs that watch it.
8///
9/// A run watches a cancel that
10/// [`RunOptions::cancel`](crate::RunOptions::cancel) gave it.
11/// [`Cancel::cancel`] stops each watching run with its escalation, and the
12/// run ends as [`Stopped(Cancelled)`](crate::StopReason::Cancelled). A run that
13/// starts with a cancel that is already cancelled starts no child. Clones
14/// share one state, so any clone cancels, and a cancel stays cancelled.
15///
16/// Any thread may call [`Cancel::cancel`] at any time, before, during or
17/// after a run. A cancel that arrives once the run has seen the child's exit
18/// changes nothing, and the run gives the child's own end. When the run sees
19/// a cancel and the exit together, the exit wins. Otherwise the run gives
20/// `Stopped(Cancelled)`, which a cancel just after the exit can also give.
21/// [`ChildFinished::status`](crate::ChildFinished::status) gives the child's
22/// own status in each case.
23///
24/// The run does not poll a flag of the caller's. A tool whose stop request is a flag, such
25/// as one that a signal handler sets, polls that flag on a thread of its
26/// own and calls [`Cancel::cancel`] from there. A signal handler itself must
27/// not call it, because it takes a lock. Such a tool decides what the stop
28/// means from its own flag, because a status such as `Signal(2)` also
29/// follows a signal that another process sent.
30///
31/// ```
32/// use std::process::Command;
33/// use std::sync::Arc;
34/// use std::sync::atomic::{AtomicBool, Ordering};
35/// use std::time::Duration;
36///
37/// use crumbkit_process::{Cancel, RunOptions, run};
38///
39/// fn run_until(flag: &Arc<AtomicBool>, command: Command) -> bool {
40/// let cancel = Cancel::new();
41/// let done = Arc::new(AtomicBool::new(false));
42/// let poller = std::thread::spawn({
43/// let (flag, cancel, done) = (Arc::clone(flag), cancel.clone(), Arc::clone(&done));
44/// move || {
45/// while !done.load(Ordering::Relaxed) {
46/// if flag.load(Ordering::Relaxed) {
47/// cancel.cancel();
48/// return;
49/// }
50/// std::thread::sleep(Duration::from_millis(10));
51/// }
52/// }
53/// });
54/// let finished = run(command, &RunOptions::new().cancel(&cancel));
55/// done.store(true, Ordering::Relaxed);
56/// let _ = poller.join();
57/// finished.is_ok()
58/// }
59/// ```
60#[derive(Clone, Debug, Default)]
61pub struct Cancel(Arc<Mutex<Watched>>);
62
63/// Whether a cancel was cancelled, and the runs that watch it.
64#[derive(Debug, Default)]
65struct Watched {
66 cancelled: bool,
67 runs: Vec<Weak<Notice>>,
68}
69
70impl Cancel {
71 /// Returns a cancel that is not cancelled.
72 #[must_use]
73 pub fn new() -> Self {
74 Self::default()
75 }
76
77 /// Cancels every run that watches this cancel or that starts watching it
78 /// later.
79 pub fn cancel(&self) {
80 let mut watched = self.lock();
81 watched.cancelled = true;
82 for run in watched.runs.drain(..).filter_map(|run| run.upgrade()) {
83 run.set(|flags| flags.cancelled = true);
84 }
85 }
86
87 /// Returns true once [`Cancel::cancel`] has been called on this cancel or
88 /// a clone of it.
89 #[must_use]
90 pub fn is_cancelled(&self) -> bool {
91 self.lock().cancelled
92 }
93
94 /// Makes the run that `notice` wakes watch this cancel, and sets its
95 /// flag at once when this cancel is already cancelled. It forgets the
96 /// runs that have ended.
97 pub(crate) fn watch(&self, notice: &Arc<Notice>) {
98 let mut watched = self.lock();
99 if watched.cancelled {
100 notice.set(|flags| flags.cancelled = true);
101 return;
102 }
103 watched.runs.retain(|run| run.strong_count() > 0);
104 watched.runs.push(Arc::downgrade(notice));
105 }
106
107 /// Returns the locked state. Each holder only reads or changes it in one
108 /// step, so a panic while the lock was held leaves nothing half changed.
109 fn lock(&self) -> MutexGuard<'_, Watched> {
110 self.0.lock().unwrap_or_else(PoisonError::into_inner)
111 }
112}