Skip to main content

osmflow_sync/
stop.rs

1//! Asking a long update to stop: by a time limit, by code, or by Ctrl+C, SIGTERM and SIGHUP.
2
3#[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
12/// How long [`Stop::wait`] sleeps between looking at the clock and the request.
13const WAIT_STEP: Duration = Duration::from_millis(250);
14
15/// Why work was asked to stop.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum StopReason {
18    /// [`Stop::request`] was called: by code, or by the first signal after `Stop::on_signals`.
19    Requested,
20    /// The time set with [`Stop::with_max_runtime`] has passed.
21    TimeLimit,
22}
23
24/// A request to stop between units of work, shared by every clone: an update checks it before each batch of diffs and
25/// finishes the batch it has begun, so the database and its files stay consistent.
26///
27/// It stops on a time limit, on [`request`](Self::request) from any thread, and, with the `signals` feature, on
28/// Ctrl+C, SIGTERM and SIGHUP. A default `Stop` never asks.
29#[derive(Debug, Clone, Default)]
30pub struct Stop {
31    requested: Arc<AtomicBool>,
32    deadline: Option<Instant>,
33}
34
35impl Stop {
36    /// A stop that has not been asked for and has no time limit.
37    #[must_use]
38    pub fn new() -> Self {
39        Self::default()
40    }
41
42    /// Asks to stop once `runtime` has passed, counted from now. A runtime too long to represent is no limit.
43    #[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    /// Asks to stop, from any thread. It cannot be taken back.
50    pub fn request(&self) {
51        self.requested.store(true, Ordering::SeqCst);
52    }
53
54    /// Why to stop now, if it was requested or the time limit has passed; a request is reported first.
55    #[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    /// Sleeps for `duration`, or less if a stop is asked for in the meantime, and returns the reason it woke early.
71    #[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/// What a signal means, by how many came before it.
90#[cfg(feature = "signals")]
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum Signal {
93    /// The first Ctrl+C, SIGTERM or SIGHUP: a stop was requested, and the work in progress finishes first.
94    First,
95    /// Any later one: the process exits at once, as soon as the notification returns.
96    Again,
97}
98
99/// The signals could not be handled, because another handler was already installed or the system refused.
100#[cfg(feature = "signals")]
101#[derive(Debug, thiserror::Error)]
102#[error("cannot handle Ctrl+C, SIGTERM and SIGHUP: {0}")]
103pub struct SignalError(String);
104
105/// The exit status when a signal ends the process at once: 128 plus SIGINT, as shells report Ctrl+C.
106#[cfg(feature = "signals")]
107const AGAIN_EXIT_STATUS: i32 = 130;
108
109/// Who the process's one signal handler tells: the latest `Stop::on_signals`.
110#[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/// The result of installing the process's signal handler, which is done once.
120#[cfg(feature = "signals")]
121static INSTALLED: OnceLock<Result<(), String>> = OnceLock::new();
122
123/// The signal handler: records the signal on the listener's stop, tells it, and ends the process on a second one,
124/// or at once when no [`SignalGuard`] is alive, as it would end without a handler.
125#[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    /// Makes Ctrl+C, SIGTERM and SIGHUP ask this stop to stop, in two steps, while the returned guard is alive.
141    ///
142    /// The first signal calls [`request`](Self::request) and then `notify(Signal::First)`: the update finishes the
143    /// batch it has begun and returns. A second signal, or one that arrives after a request made in any other way,
144    /// calls `notify(Signal::Again)` and ends the process at once with exit status 130: the batch in progress is
145    /// rolled back with its transaction, and the next update repairs what it left half done, as after a crash.
146    ///
147    /// `notify` runs on the signal-handling thread, and is the place to tell the user, as osmflow itself prints
148    /// nothing. A process has one signal handler, which tells the stop of the latest call: calling this again, for
149    /// the next run, replaces the earlier stop and `notify`. Once the latest call's guard is dropped, a signal ends
150    /// the process at once with status 130, as without a handler. It fails if other code already installed a
151    /// handler for these signals.
152    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    /// Records a signal: the first asks to stop, and any later one, or one after a request, asks to stop at once.
170    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/// Keeps the signals asking a stop to stop, from [`Stop::on_signals`]: once dropped, a signal ends the process at
180/// once, unless a later call gave them to another stop.
181#[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    /// The one test of the process's handler, which tests running at the same time would share.
289    #[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        // The earlier guard no longer owns the handler, so dropping it changes nothing
305        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}