use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::sync::{Arc, OnceLock};
#[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 }
}
pub fn actor(&self) -> &str {
&self.actor
}
pub fn reason(&self) -> &str {
&self.reason
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum StopStatus {
StoppedNow,
AlreadyStopped,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StopOutcome {
status: StopStatus,
record: StopRecord,
}
impl StopOutcome {
pub fn status(&self) -> StopStatus {
self.status
}
pub fn record(&self) -> &StopRecord {
&self.record
}
}
#[derive(Clone, Debug, Default)]
pub struct CocoshigaStop {
record: Arc<OnceLock<StopRecord>>,
}
impl CocoshigaStop {
pub fn new() -> Self {
Self::default()
}
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 })
}
pub fn is_stopped(&self) -> bool {
self.record.get().is_some()
}
pub fn record(&self) -> Option<StopRecord> {
self.record.get().cloned()
}
pub fn checkpoint(&self) -> Result<(), Stopped> {
match self.record() {
Some(record) => Err(Stopped { record }),
None => Ok(()),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RequestError {
EmptyActor,
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 {}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Stopped {
record: StopRecord,
}
impl Stopped {
pub fn record(&self) -> &StopRecord {
&self.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
);
}
}