1use std::error::Error;
27use std::fmt::{self, Display, Formatter};
28use std::sync::{Arc, OnceLock};
29
30#[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 pub fn actor(&self) -> &str {
44 &self.actor
45 }
46
47 pub fn reason(&self) -> &str {
49 &self.reason
50 }
51}
52
53#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
55pub enum StopStatus {
56 StoppedNow,
58 AlreadyStopped,
60}
61
62#[derive(Clone, Debug, PartialEq, Eq)]
64pub struct StopOutcome {
65 status: StopStatus,
66 record: StopRecord,
67}
68
69impl StopOutcome {
70 pub fn status(&self) -> StopStatus {
72 self.status
73 }
74
75 pub fn record(&self) -> &StopRecord {
80 &self.record
81 }
82}
83
84#[derive(Clone, Debug, Default)]
89pub struct CocoshigaStop {
90 record: Arc<OnceLock<StopRecord>>,
91}
92
93impl CocoshigaStop {
94 pub fn new() -> Self {
96 Self::default()
97 }
98
99 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 pub fn is_stopped(&self) -> bool {
133 self.record.get().is_some()
134 }
135
136 pub fn record(&self) -> Option<StopRecord> {
138 self.record.get().cloned()
139 }
140
141 pub fn checkpoint(&self) -> Result<(), Stopped> {
146 match self.record() {
147 Some(record) => Err(Stopped { record }),
148 None => Ok(()),
149 }
150 }
151}
152
153#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
155#[non_exhaustive]
156pub enum RequestError {
157 EmptyActor,
159 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#[derive(Clone, Debug, PartialEq, Eq)]
176pub struct Stopped {
177 record: StopRecord,
178}
179
180impl Stopped {
181 pub fn record(&self) -> &StopRecord {
183 &self.record
184 }
185
186 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}