1#[cfg(feature = "signals")]
4use std::process;
5use std::sync::Arc;
6use std::sync::atomic::{AtomicBool, Ordering};
7#[cfg(feature = "signals")]
8use std::sync::{Mutex, OnceLock, PoisonError};
9use std::thread;
10use std::time::{Duration, Instant};
11
12const WAIT_STEP: Duration = Duration::from_millis(250);
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum StopReason {
18 Requested,
20 TimeLimit,
22}
23
24#[derive(Debug, Clone, Default)]
30pub struct Stop {
31 requested: Arc<AtomicBool>,
32 deadline: Option<Instant>,
33}
34
35impl Stop {
36 #[must_use]
38 pub fn new() -> Self {
39 Self::default()
40 }
41
42 #[must_use]
44 pub fn with_max_runtime(mut self, runtime: Duration) -> Self {
45 self.deadline = Instant::now().checked_add(runtime);
46 self
47 }
48
49 pub fn request(&self) {
51 self.requested.store(true, Ordering::SeqCst);
52 }
53
54 #[must_use]
56 pub fn reason(&self) -> Option<StopReason> {
57 self.reason_at(Instant::now())
58 }
59
60 fn reason_at(&self, now: Instant) -> Option<StopReason> {
61 if self.requested.load(Ordering::SeqCst) {
62 Some(StopReason::Requested)
63 } else if self.deadline.is_some_and(|deadline| now >= deadline) {
64 Some(StopReason::TimeLimit)
65 } else {
66 None
67 }
68 }
69
70 #[must_use]
72 pub fn wait(&self, duration: Duration) -> Option<StopReason> {
73 let end = Instant::now().checked_add(duration);
74 loop {
75 if let Some(reason) = self.reason() {
76 return Some(reason);
77 }
78 let left = end.map_or(WAIT_STEP, |end| {
79 end.saturating_duration_since(Instant::now())
80 });
81 if left.is_zero() {
82 return None;
83 }
84 thread::sleep(left.min(WAIT_STEP));
85 }
86 }
87}
88
89#[cfg(feature = "signals")]
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum Signal {
93 First,
95 Again,
97}
98
99#[cfg(feature = "signals")]
101#[derive(Debug, thiserror::Error)]
102#[error("cannot handle Ctrl+C, SIGTERM and SIGHUP: {0}")]
103pub struct SignalError(String);
104
105#[cfg(feature = "signals")]
107const AGAIN_EXIT_STATUS: i32 = 130;
108
109#[cfg(feature = "signals")]
111struct Listener {
112 stop: Stop,
113 notify: Box<dyn Fn(Signal) + Send>,
114}
115
116#[cfg(feature = "signals")]
117static LISTENER: Mutex<Option<Listener>> = Mutex::new(None);
118
119#[cfg(feature = "signals")]
121static INSTALLED: OnceLock<Result<(), String>> = OnceLock::new();
122
123#[cfg(feature = "signals")]
126fn dispatch() {
127 let listener = LISTENER.lock().unwrap_or_else(PoisonError::into_inner);
128 let Some(listener) = listener.as_ref() else {
129 exit_now();
130 };
131 let signal = listener.stop.advance();
132 (listener.notify)(signal);
133 if signal == Signal::Again {
134 exit_now();
135 }
136}
137
138#[cfg(feature = "signals")]
139impl Stop {
140 pub fn on_signals(
153 &self,
154 notify: impl Fn(Signal) + Send + 'static,
155 ) -> Result<SignalGuard, SignalError> {
156 INSTALLED
157 .get_or_init(|| ctrlc::set_handler(dispatch).map_err(|e| e.to_string()))
158 .clone()
159 .map_err(SignalError)?;
160 *LISTENER.lock().unwrap_or_else(PoisonError::into_inner) = Some(Listener {
161 stop: self.clone(),
162 notify: Box::new(notify),
163 });
164 Ok(SignalGuard {
165 requested: Arc::clone(&self.requested),
166 })
167 }
168
169 fn advance(&self) -> Signal {
171 if self.requested.swap(true, Ordering::SeqCst) {
172 Signal::Again
173 } else {
174 Signal::First
175 }
176 }
177}
178
179#[cfg(feature = "signals")]
182#[must_use = "dropping the guard makes the next signal end the process at once"]
183#[derive(Debug)]
184pub struct SignalGuard {
185 requested: Arc<AtomicBool>,
186}
187
188#[cfg(feature = "signals")]
189impl Drop for SignalGuard {
190 fn drop(&mut self) {
191 let mut listener = LISTENER.lock().unwrap_or_else(PoisonError::into_inner);
192 if listener
193 .as_ref()
194 .is_some_and(|l| Arc::ptr_eq(&l.stop.requested, &self.requested))
195 {
196 *listener = None;
197 }
198 }
199}
200
201#[cfg(feature = "signals")]
202#[expect(
203 clippy::exit,
204 reason = "a second signal ends the process at once, which is what it asks for"
205)]
206fn exit_now() -> ! {
207 process::exit(AGAIN_EXIT_STATUS)
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213
214 #[test]
215 fn nothing_asks_without_a_request_or_a_limit() {
216 assert_eq!(Stop::new().reason(), None);
217 }
218
219 #[test]
220 fn a_request_is_seen_by_every_clone() {
221 let stop = Stop::new();
222 let clone = stop.clone();
223 assert_eq!(clone.reason(), None);
224 stop.request();
225 assert_eq!(clone.reason(), Some(StopReason::Requested));
226 }
227
228 #[test]
229 fn the_time_limit_asks_once_it_has_passed() {
230 let stop = Stop::new().with_max_runtime(Duration::from_mins(1));
231 let now = Instant::now();
232 assert_eq!(stop.reason_at(now), None);
233 assert_eq!(stop.reason_at(now + Duration::from_secs(59)), None);
234 assert_eq!(
235 stop.reason_at(now + Duration::from_mins(2)),
236 Some(StopReason::TimeLimit)
237 );
238 assert_eq!(
239 Stop::new().with_max_runtime(Duration::ZERO).reason(),
240 Some(StopReason::TimeLimit)
241 );
242 }
243
244 #[test]
245 fn a_runtime_too_long_to_count_is_no_limit() {
246 assert_eq!(Stop::new().with_max_runtime(Duration::MAX).reason(), None);
247 }
248
249 #[test]
250 fn a_request_is_reported_before_the_time_limit() {
251 let stop = Stop::new().with_max_runtime(Duration::ZERO);
252 stop.request();
253 assert_eq!(stop.reason(), Some(StopReason::Requested));
254 }
255
256 #[test]
257 fn waiting_ends_early_on_a_request_and_late_without_one() {
258 let started = Instant::now();
259 let asked = Stop::new();
260 asked.request();
261 assert_eq!(
262 asked.wait(Duration::from_mins(1)),
263 Some(StopReason::Requested)
264 );
265 assert!(started.elapsed() < Duration::from_secs(10));
266 assert_eq!(Stop::new().wait(Duration::from_millis(30)), None);
267 }
268
269 #[test]
270 fn waiting_ends_at_the_time_limit() {
271 let stop = Stop::new().with_max_runtime(Duration::from_millis(30));
272 assert_eq!(
273 stop.wait(Duration::from_mins(1)),
274 Some(StopReason::TimeLimit)
275 );
276 }
277
278 #[cfg(feature = "signals")]
279 #[test]
280 fn the_first_signal_requests_and_every_later_one_asks_to_stop_at_once() {
281 let stop = Stop::new();
282 assert_eq!(stop.advance(), Signal::First);
283 assert_eq!(stop.reason(), Some(StopReason::Requested));
284 assert_eq!(stop.advance(), Signal::Again);
285 assert_eq!(stop.advance(), Signal::Again);
286 }
287
288 #[cfg(feature = "signals")]
290 #[test]
291 fn the_handler_tells_the_latest_stop_while_its_guard_lives() {
292 let listens = |stop: &Stop| {
293 LISTENER
294 .lock()
295 .unwrap()
296 .as_ref()
297 .is_some_and(|l| Arc::ptr_eq(&l.stop.requested, &stop.requested))
298 };
299 let (first, second) = (Stop::new(), Stop::new());
300 let first_guard = first.on_signals(|_| {}).unwrap();
301 assert!(listens(&first));
302 let second_guard = second.on_signals(|_| {}).unwrap();
303 assert!(listens(&second));
304 drop(first_guard);
306 assert!(listens(&second));
307 drop(second_guard);
308 assert!(LISTENER.lock().unwrap().is_none());
309 }
310
311 #[cfg(feature = "signals")]
312 #[test]
313 fn a_signal_after_a_request_asks_to_stop_at_once() {
314 let stop = Stop::new();
315 stop.request();
316 assert_eq!(stop.advance(), Signal::Again);
317 }
318}