stop-cigarette 0.1.0

First-wins cooperative STOP signals with immutable reasons and shared propagation
Documentation
//! Cooperative, first-wins STOP signals.
//!
//! The **Cocoshiga STOP principle** has four invariants:
//!
//! 1. the first valid STOP wins;
//! 2. its actor and reason remain immutable;
//! 3. all clones observe the same STOP;
//! 4. subsequent requests are idempotent.
//!
//! ```
//! use stop_cigarette::{CocoshigaStop, StopStatus};
//!
//! let signal = CocoshigaStop::new();
//! let worker_signal = signal.clone();
//!
//! let outcome = signal.request_stop("operator", "unsafe condition")?;
//! assert_eq!(outcome.status(), StopStatus::StoppedNow);
//! assert!(worker_signal.is_stopped());
//! assert_eq!(
//!     worker_signal.record().expect("a stop was requested").actor(),
//!     "operator"
//! );
//! # Ok::<(), stop_cigarette::RequestError>(())
//! ```

use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::sync::{Arc, OnceLock};

/// Immutable provenance for the first accepted STOP request.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct StopRecord {
    actor: String,
    reason: String,
}

impl StopRecord {
    fn new(actor: String, reason: String) -> Self {
        Self { actor, reason }
    }

    /// The party or subsystem that requested STOP.
    pub fn actor(&self) -> &str {
        &self.actor
    }

    /// The reason supplied with the STOP request.
    pub fn reason(&self) -> &str {
        &self.reason
    }
}

/// Whether a request established STOP or found it already established.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum StopStatus {
    /// This request became the immutable first STOP.
    StoppedNow,
    /// An earlier valid request had already established STOP.
    AlreadyStopped,
}

/// Result of a valid STOP request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StopOutcome {
    status: StopStatus,
    record: StopRecord,
}

impl StopOutcome {
    /// Indicates whether this request won the first-STOP race.
    pub fn status(&self) -> StopStatus {
        self.status
    }

    /// Returns the canonical first STOP record.
    ///
    /// For an already-stopped signal, this is the original record rather than
    /// the actor and reason from the later request.
    pub fn record(&self) -> &StopRecord {
        &self.record
    }
}

/// A cloneable cooperative STOP signal.
///
/// Clones share one atomic, write-once record. This type is safe to send and
/// share between threads.
#[derive(Clone, Debug, Default)]
pub struct CocoshigaStop {
    record: Arc<OnceLock<StopRecord>>,
}

impl CocoshigaStop {
    /// Creates an open signal with no STOP record.
    pub fn new() -> Self {
        Self::default()
    }

    /// Requests STOP and preserves the first valid request.
    ///
    /// Empty or whitespace-only fields are rejected without changing the
    /// signal. Concurrent calls are linearized by the write-once record.
    pub fn request_stop(
        &self,
        actor: impl Into<String>,
        reason: impl Into<String>,
    ) -> Result<StopOutcome, RequestError> {
        let actor = actor.into();
        let reason = reason.into();
        if actor.trim().is_empty() {
            return Err(RequestError::EmptyActor);
        }
        if reason.trim().is_empty() {
            return Err(RequestError::EmptyReason);
        }

        let attempted = StopRecord::new(actor, reason);
        let status = if self.record.set(attempted).is_ok() {
            StopStatus::StoppedNow
        } else {
            StopStatus::AlreadyStopped
        };
        let record = self
            .record
            .get()
            .expect("OnceLock contains a value after set succeeds or fails")
            .clone();
        Ok(StopOutcome { status, record })
    }

    /// Returns true after the first valid STOP request.
    pub fn is_stopped(&self) -> bool {
        self.record.get().is_some()
    }

    /// Returns a snapshot of the canonical STOP record.
    pub fn record(&self) -> Option<StopRecord> {
        self.record.get().cloned()
    }

    /// Cooperative guard for work that must not start after STOP.
    ///
    /// This checks the signal at the instant of the call. Long-running work
    /// should call it again at suitable interruption points.
    pub fn checkpoint(&self) -> Result<(), Stopped> {
        match self.record() {
            Some(record) => Err(Stopped { record }),
            None => Ok(()),
        }
    }
}

/// Validation failure for a STOP request.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RequestError {
    /// The actor is empty or contains only whitespace.
    EmptyActor,
    /// The reason is empty or contains only whitespace.
    EmptyReason,
}

impl Display for RequestError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::EmptyActor => "STOP actor cannot be empty",
            Self::EmptyReason => "STOP reason cannot be empty",
        })
    }
}

impl Error for RequestError {}

/// Error returned when a checkpoint observes STOP.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Stopped {
    record: StopRecord,
}

impl Stopped {
    /// Returns the canonical first STOP record.
    pub fn record(&self) -> &StopRecord {
        &self.record
    }

    /// Consumes the error and returns its STOP record.
    pub fn into_record(self) -> StopRecord {
        self.record
    }
}

impl Display for Stopped {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "stopped by {}: {}",
            self.record.actor(),
            self.record.reason()
        )
    }
}

impl Error for Stopped {}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Barrier};
    use std::thread;

    #[test]
    fn signal_starts_open() {
        let signal = CocoshigaStop::new();
        assert!(!signal.is_stopped());
        assert!(signal.record().is_none());
        assert!(signal.checkpoint().is_ok());
    }

    #[test]
    fn first_valid_stop_is_immutable() {
        let signal = CocoshigaStop::new();
        let first = signal.request_stop("alice", "hazard").unwrap();
        let second = signal.request_stop("bob", "later reason").unwrap();

        assert_eq!(first.status(), StopStatus::StoppedNow);
        assert_eq!(second.status(), StopStatus::AlreadyStopped);
        assert_eq!(second.record().actor(), "alice");
        assert_eq!(second.record().reason(), "hazard");
        assert_eq!(signal.record(), Some(first.record().clone()));
    }

    #[test]
    fn clones_share_the_stop() {
        let signal = CocoshigaStop::new();
        let worker = signal.clone();
        signal.request_stop("operator", "maintenance").unwrap();

        let stopped = worker.checkpoint().unwrap_err();
        assert_eq!(stopped.record().actor(), "operator");
        assert_eq!(stopped.record().reason(), "maintenance");
    }

    #[test]
    fn invalid_requests_do_not_stop_the_signal() {
        let signal = CocoshigaStop::new();
        assert_eq!(
            signal.request_stop(" ", "reason").unwrap_err(),
            RequestError::EmptyActor
        );
        assert_eq!(
            signal.request_stop("actor", "").unwrap_err(),
            RequestError::EmptyReason
        );
        assert!(!signal.is_stopped());
    }

    #[test]
    fn exactly_one_concurrent_request_wins() {
        const WORKERS: usize = 8;
        let signal = CocoshigaStop::new();
        let barrier = Arc::new(Barrier::new(WORKERS));
        let handles: Vec<_> = (0..WORKERS)
            .map(|index| {
                let signal = signal.clone();
                let barrier = barrier.clone();
                thread::spawn(move || {
                    barrier.wait();
                    signal
                        .request_stop(format!("worker-{index}"), "race")
                        .unwrap()
                        .status()
                })
            })
            .collect();

        let statuses: Vec<_> = handles
            .into_iter()
            .map(|handle| handle.join().unwrap())
            .collect();
        assert_eq!(
            statuses
                .iter()
                .filter(|&&status| status == StopStatus::StoppedNow)
                .count(),
            1
        );
        assert_eq!(
            statuses
                .iter()
                .filter(|&&status| status == StopStatus::AlreadyStopped)
                .count(),
            WORKERS - 1
        );
    }
}