Skip to main content

stop_cigarette/
lib.rs

1//! Cooperative, first-wins STOP signals.
2//!
3//! The **Cocoshiga STOP principle** has four invariants:
4//!
5//! 1. the first valid STOP wins;
6//! 2. its actor and reason remain immutable;
7//! 3. all clones observe the same STOP;
8//! 4. subsequent requests are idempotent.
9//!
10//! ```
11//! use stop_cigarette::{CocoshigaStop, StopStatus};
12//!
13//! let signal = CocoshigaStop::new();
14//! let worker_signal = signal.clone();
15//!
16//! let outcome = signal.request_stop("operator", "unsafe condition")?;
17//! assert_eq!(outcome.status(), StopStatus::StoppedNow);
18//! assert!(worker_signal.is_stopped());
19//! assert_eq!(
20//!     worker_signal.record().expect("a stop was requested").actor(),
21//!     "operator"
22//! );
23//! # Ok::<(), stop_cigarette::RequestError>(())
24//! ```
25
26use std::error::Error;
27use std::fmt::{self, Display, Formatter};
28use std::sync::{Arc, OnceLock};
29
30/// Immutable provenance for the first accepted STOP request.
31#[derive(Clone, Debug, PartialEq, Eq, Hash)]
32pub struct StopRecord {
33    actor: String,
34    reason: String,
35}
36
37impl StopRecord {
38    fn new(actor: String, reason: String) -> Self {
39        Self { actor, reason }
40    }
41
42    /// The party or subsystem that requested STOP.
43    pub fn actor(&self) -> &str {
44        &self.actor
45    }
46
47    /// The reason supplied with the STOP request.
48    pub fn reason(&self) -> &str {
49        &self.reason
50    }
51}
52
53/// Whether a request established STOP or found it already established.
54#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
55pub enum StopStatus {
56    /// This request became the immutable first STOP.
57    StoppedNow,
58    /// An earlier valid request had already established STOP.
59    AlreadyStopped,
60}
61
62/// Result of a valid STOP request.
63#[derive(Clone, Debug, PartialEq, Eq)]
64pub struct StopOutcome {
65    status: StopStatus,
66    record: StopRecord,
67}
68
69impl StopOutcome {
70    /// Indicates whether this request won the first-STOP race.
71    pub fn status(&self) -> StopStatus {
72        self.status
73    }
74
75    /// Returns the canonical first STOP record.
76    ///
77    /// For an already-stopped signal, this is the original record rather than
78    /// the actor and reason from the later request.
79    pub fn record(&self) -> &StopRecord {
80        &self.record
81    }
82}
83
84/// A cloneable cooperative STOP signal.
85///
86/// Clones share one atomic, write-once record. This type is safe to send and
87/// share between threads.
88#[derive(Clone, Debug, Default)]
89pub struct CocoshigaStop {
90    record: Arc<OnceLock<StopRecord>>,
91}
92
93impl CocoshigaStop {
94    /// Creates an open signal with no STOP record.
95    pub fn new() -> Self {
96        Self::default()
97    }
98
99    /// Requests STOP and preserves the first valid request.
100    ///
101    /// Empty or whitespace-only fields are rejected without changing the
102    /// signal. Concurrent calls are linearized by the write-once record.
103    pub fn request_stop(
104        &self,
105        actor: impl Into<String>,
106        reason: impl Into<String>,
107    ) -> Result<StopOutcome, RequestError> {
108        let actor = actor.into();
109        let reason = reason.into();
110        if actor.trim().is_empty() {
111            return Err(RequestError::EmptyActor);
112        }
113        if reason.trim().is_empty() {
114            return Err(RequestError::EmptyReason);
115        }
116
117        let attempted = StopRecord::new(actor, reason);
118        let status = if self.record.set(attempted).is_ok() {
119            StopStatus::StoppedNow
120        } else {
121            StopStatus::AlreadyStopped
122        };
123        let record = self
124            .record
125            .get()
126            .expect("OnceLock contains a value after set succeeds or fails")
127            .clone();
128        Ok(StopOutcome { status, record })
129    }
130
131    /// Returns true after the first valid STOP request.
132    pub fn is_stopped(&self) -> bool {
133        self.record.get().is_some()
134    }
135
136    /// Returns a snapshot of the canonical STOP record.
137    pub fn record(&self) -> Option<StopRecord> {
138        self.record.get().cloned()
139    }
140
141    /// Cooperative guard for work that must not start after STOP.
142    ///
143    /// This checks the signal at the instant of the call. Long-running work
144    /// should call it again at suitable interruption points.
145    pub fn checkpoint(&self) -> Result<(), Stopped> {
146        match self.record() {
147            Some(record) => Err(Stopped { record }),
148            None => Ok(()),
149        }
150    }
151}
152
153/// Validation failure for a STOP request.
154#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
155#[non_exhaustive]
156pub enum RequestError {
157    /// The actor is empty or contains only whitespace.
158    EmptyActor,
159    /// The reason is empty or contains only whitespace.
160    EmptyReason,
161}
162
163impl Display for RequestError {
164    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
165        f.write_str(match self {
166            Self::EmptyActor => "STOP actor cannot be empty",
167            Self::EmptyReason => "STOP reason cannot be empty",
168        })
169    }
170}
171
172impl Error for RequestError {}
173
174/// Error returned when a checkpoint observes STOP.
175#[derive(Clone, Debug, PartialEq, Eq)]
176pub struct Stopped {
177    record: StopRecord,
178}
179
180impl Stopped {
181    /// Returns the canonical first STOP record.
182    pub fn record(&self) -> &StopRecord {
183        &self.record
184    }
185
186    /// Consumes the error and returns its STOP record.
187    pub fn into_record(self) -> StopRecord {
188        self.record
189    }
190}
191
192impl Display for Stopped {
193    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
194        write!(
195            f,
196            "stopped by {}: {}",
197            self.record.actor(),
198            self.record.reason()
199        )
200    }
201}
202
203impl Error for Stopped {}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208    use std::sync::{Arc, Barrier};
209    use std::thread;
210
211    #[test]
212    fn signal_starts_open() {
213        let signal = CocoshigaStop::new();
214        assert!(!signal.is_stopped());
215        assert!(signal.record().is_none());
216        assert!(signal.checkpoint().is_ok());
217    }
218
219    #[test]
220    fn first_valid_stop_is_immutable() {
221        let signal = CocoshigaStop::new();
222        let first = signal.request_stop("alice", "hazard").unwrap();
223        let second = signal.request_stop("bob", "later reason").unwrap();
224
225        assert_eq!(first.status(), StopStatus::StoppedNow);
226        assert_eq!(second.status(), StopStatus::AlreadyStopped);
227        assert_eq!(second.record().actor(), "alice");
228        assert_eq!(second.record().reason(), "hazard");
229        assert_eq!(signal.record(), Some(first.record().clone()));
230    }
231
232    #[test]
233    fn clones_share_the_stop() {
234        let signal = CocoshigaStop::new();
235        let worker = signal.clone();
236        signal.request_stop("operator", "maintenance").unwrap();
237
238        let stopped = worker.checkpoint().unwrap_err();
239        assert_eq!(stopped.record().actor(), "operator");
240        assert_eq!(stopped.record().reason(), "maintenance");
241    }
242
243    #[test]
244    fn invalid_requests_do_not_stop_the_signal() {
245        let signal = CocoshigaStop::new();
246        assert_eq!(
247            signal.request_stop(" ", "reason").unwrap_err(),
248            RequestError::EmptyActor
249        );
250        assert_eq!(
251            signal.request_stop("actor", "").unwrap_err(),
252            RequestError::EmptyReason
253        );
254        assert!(!signal.is_stopped());
255    }
256
257    #[test]
258    fn exactly_one_concurrent_request_wins() {
259        const WORKERS: usize = 8;
260        let signal = CocoshigaStop::new();
261        let barrier = Arc::new(Barrier::new(WORKERS));
262        let handles: Vec<_> = (0..WORKERS)
263            .map(|index| {
264                let signal = signal.clone();
265                let barrier = barrier.clone();
266                thread::spawn(move || {
267                    barrier.wait();
268                    signal
269                        .request_stop(format!("worker-{index}"), "race")
270                        .unwrap()
271                        .status()
272                })
273            })
274            .collect();
275
276        let statuses: Vec<_> = handles
277            .into_iter()
278            .map(|handle| handle.join().unwrap())
279            .collect();
280        assert_eq!(
281            statuses
282                .iter()
283                .filter(|&&status| status == StopStatus::StoppedNow)
284                .count(),
285            1
286        );
287        assert_eq!(
288            statuses
289                .iter()
290                .filter(|&&status| status == StopStatus::AlreadyStopped)
291                .count(),
292            WORKERS - 1
293        );
294    }
295}