Skip to main content

kakemono/common/
cancel.rs

1//! Stopping a conversion from another thread, or after a time limit.
2//!
3//! A [`CancelToken`] is made current on a thread by [`CancelToken::run`];
4//! the pipeline calls [`check`] at its natural stopping points (each page,
5//! each stage, each chunk of a download), and the worker threads it starts
6//! inherit the token ([`current`], [`CancelToken::enter`]). Once the token is
7//! cancelled, or past its deadline, the next [`check`] unwinds the stack up
8//! to [`CancelToken::run`], which returns [`Cancelled`]: the functions of the
9//! pipeline keep their signatures, and everything they hold is dropped on the
10//! way, as for an early return.
11//!
12//! [`check`] reads one atomic flag (and the clock when a deadline is set):
13//! the checks are at most a few per page, so they cost nothing measurable.
14//! Without a current token, [`check`] does nothing.
15
16use std::cell::RefCell;
17use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
18use std::sync::Arc;
19use std::sync::atomic::{AtomicU8, Ordering};
20use std::time::{Duration, Instant};
21
22/// Why a conversion stopped before its end.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24#[non_exhaustive]
25pub enum Cancelled {
26    /// [`CancelToken::cancel`] was called (on the token or on its parent).
27    Requested,
28    /// The deadline of the token (or of its parent) passed.
29    TimedOut,
30}
31
32impl std::fmt::Display for Cancelled {
33    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        formatter.write_str(match self {
35            Self::Requested => "the conversion was cancelled",
36            Self::TimedOut => "the conversion took longer than its time limit",
37        })
38    }
39}
40
41impl std::error::Error for Cancelled {}
42
43/// [`Inner::stopped`]: not stopped (yet).
44const RUNNING: u8 = 0;
45/// [`Inner::stopped`]: [`Cancelled::Requested`].
46const REQUESTED: u8 = 1;
47/// [`Inner::stopped`]: [`Cancelled::TimedOut`].
48const TIMED_OUT: u8 = 2;
49
50/// What a token holds, shared by its clones.
51#[derive(Debug)]
52struct Inner {
53    /// Why this token stopped, once it is known: [`RUNNING`], [`REQUESTED`]
54    /// (set by [`CancelToken::cancel`]) or [`TIMED_OUT`] (set when its
55    /// deadline is seen passed). The first one set stays, so that a token
56    /// cancelled after its deadline was seen, or the reverse, keeps the
57    /// cause that came first.
58    stopped: AtomicU8,
59    /// When the work must stop, if it has a time limit.
60    deadline: Option<Instant>,
61    /// A token whose cancellation (or deadline) stops this one too.
62    parent: Option<CancelToken>,
63}
64
65/// A request to stop a conversion, shared by the thread that runs it and
66/// those that may stop it (clones share the same request).
67///
68/// ```
69/// use kakemono::{CancelToken, Cancelled, Paper};
70/// # fn main() -> anyhow::Result<()> {
71/// let token = CancelToken::new();
72/// let stopper = token.clone();
73/// // Elsewhere, e.g. when the user closes the window: stopper.cancel();
74/// # stopper.cancel();
75/// let analysis = token.run(|| -> anyhow::Result<_> {
76///     let paper = Paper::from_path("tests/data/1602.03837v1.pdf")?;
77///     Ok(paper.analyze())
78/// });
79/// assert_eq!(analysis.err(), Some(Cancelled::Requested));
80/// # Ok(())
81/// # }
82/// ```
83#[derive(Debug, Clone)]
84pub struct CancelToken(Arc<Inner>);
85
86impl Default for CancelToken {
87    fn default() -> Self {
88        Self::new()
89    }
90}
91
92impl CancelToken {
93    /// A token with no time limit, not cancelled.
94    #[must_use]
95    pub fn new() -> Self {
96        Self::make(None, None)
97    }
98
99    /// A token that times out `limit` from now.
100    #[must_use]
101    pub fn with_timeout(limit: Duration) -> Self {
102        Self::make(Instant::now().checked_add(limit), None)
103    }
104
105    /// A token stopped by this one (by its cancellation or its deadline), and
106    /// by its own: cancelling it does not cancel this one. `limit` is its own
107    /// time limit, from now.
108    #[must_use]
109    pub fn child(&self, limit: Option<Duration>) -> Self {
110        Self::make(
111            limit.and_then(|limit| Instant::now().checked_add(limit)),
112            Some(self.clone()),
113        )
114    }
115
116    /// A token with these fields.
117    fn make(deadline: Option<Instant>, parent: Option<Self>) -> Self {
118        Self(Arc::new(Inner {
119            stopped: AtomicU8::new(RUNNING),
120            deadline,
121            parent,
122        }))
123    }
124
125    /// Asks the work running with this token (and its children) to stop.
126    /// It stops at its next stopping point, normally within a page.
127    pub fn cancel(&self) {
128        // A token already stopped keeps its cause.
129        let _ = self
130            .0
131            .stopped
132            .compare_exchange(RUNNING, REQUESTED, Ordering::Relaxed, Ordering::Relaxed);
133    }
134
135    /// Why the work must stop, or `None` while it may go on.
136    #[must_use]
137    pub fn state(&self) -> Option<Cancelled> {
138        let found = self.cause()?;
139        // Kept on this token too, so that a later `cancel` of it does not
140        // change why it stopped.
141        Some(
142            match self
143                .0
144                .stopped
145                .compare_exchange(RUNNING, found, Ordering::Relaxed, Ordering::Relaxed)
146            {
147                Ok(_) => found,
148                Err(known) => known,
149            },
150        )
151        .map(|code| {
152            if code == TIMED_OUT {
153                Cancelled::TimedOut
154            } else {
155                Cancelled::Requested
156            }
157        })
158    }
159
160    /// Why this token must stop ([`REQUESTED`] or [`TIMED_OUT`]), from it
161    /// and its parents: a cause already known comes first, since a deadline
162    /// seen passed now may have passed after it.
163    fn cause(&self) -> Option<u8> {
164        let chain = || std::iter::successors(Some(self), |token| token.0.parent.as_ref());
165        if let Some(known) = chain()
166            .map(|token| token.0.stopped.load(Ordering::Relaxed))
167            .find(|&code| code != RUNNING)
168        {
169            return Some(known);
170        }
171        let now = Instant::now();
172        let CancelToken(inner) = chain().find(|token| token.0.deadline.is_some_and(|deadline| now >= deadline))?;
173        // Recorded where it passed, unless a cancellation came meanwhile.
174        Some(
175            match inner
176                .stopped
177                .compare_exchange(RUNNING, TIMED_OUT, Ordering::Relaxed, Ordering::Relaxed)
178            {
179                Ok(_) => TIMED_OUT,
180                Err(known) => known,
181            },
182        )
183    }
184
185    /// Runs `work` on this thread with this token current, and returns its
186    /// result, or why it stopped early. Work that ends normally keeps its
187    /// result, even when the token was cancelled meanwhile; work is not
188    /// started with a token already cancelled.
189    ///
190    /// The work stops by unwinding its stack, as a panic does but without
191    /// the panic hook, so:
192    /// - the program must be built with `panic = "unwind"` (the default):
193    ///   with `panic = "abort"`, a cancellation aborts the process;
194    /// - a `catch_unwind` inside `work` (one of yours, or a library's) sees
195    ///   the cancellation as a panic: let a payload of type [`Cancelled`]
196    ///   go on with `std::panic::resume_unwind`;
197    /// - a `run` inside `work` makes its own token current until it
198    ///   returns: give it a [`child`](Self::child) of this one, so that
199    ///   cancelling this one stops it too;
200    /// - threads that `work` starts itself do not see the token: only the
201    ///   library's own worker threads do.
202    ///
203    /// # Errors
204    /// [`Cancelled`] when the token was cancelled, or timed out, before
205    /// `work` ended.
206    ///
207    /// # Panics
208    /// When `work` panics: the panic goes on.
209    pub fn run<R>(&self, work: impl FnOnce() -> R) -> Result<R, Cancelled> {
210        if let Some(stopped) = self.state() {
211            return Err(stopped);
212        }
213        let entered = self.enter();
214        let outcome = catch_unwind(AssertUnwindSafe(work));
215        drop(entered);
216        match outcome {
217            Ok(result) => Ok(result),
218            Err(payload) => match payload.downcast::<Cancelled>() {
219                Ok(stopped) => Err(*stopped),
220                Err(payload) => resume_unwind(payload),
221            },
222        }
223    }
224
225    /// Makes this token current on this thread until the guard is dropped
226    /// (then the one before is current again). A [`check`] that finds it
227    /// cancelled unwinds: only call this where [`run`](Self::run) or a
228    /// thread that hands panics on (such as a scoped thread) is above.
229    pub(crate) fn enter(&self) -> Entered {
230        Entered(CURRENT.with(|current| current.replace(Some(self.clone()))))
231    }
232}
233
234thread_local! {
235    /// The token of the work running on this thread.
236    static CURRENT: RefCell<Option<CancelToken>> = const { RefCell::new(None) };
237}
238
239/// Makes the token before current again when dropped (see
240/// [`CancelToken::enter`]).
241pub(crate) struct Entered(Option<CancelToken>);
242
243impl Drop for Entered {
244    fn drop(&mut self) {
245        let before = self.0.take();
246        CURRENT.with(|current| *current.borrow_mut() = before);
247    }
248}
249
250/// The token of the work running on this thread, for the threads it
251/// starts: each makes it current with [`enter`].
252pub(crate) fn current() -> Option<CancelToken> {
253    CURRENT.with(|current| current.borrow().clone())
254}
255
256/// Makes `token` current on this thread, if there is one (see
257/// [`CancelToken::enter`]): for worker threads, with the token of the
258/// thread that started them.
259pub(crate) fn enter(token: Option<&CancelToken>) -> Option<Entered> {
260    token.map(CancelToken::enter)
261}
262
263/// A stopping point: unwinds to [`CancelToken::run`] when the current token
264/// is cancelled or timed out; does nothing otherwise, or without a token.
265///
266/// Call it only where no lock shared beyond the work is held and no value
267/// shared beyond it is half changed: the unwinding drops what it crosses.
268pub(crate) fn check() {
269    let stopped = CURRENT.with(|current| current.borrow().as_ref().and_then(CancelToken::state));
270    if let Some(stopped) = stopped {
271        // `resume_unwind` does not call the panic hook: nothing is printed.
272        resume_unwind(Box::new(stopped));
273    }
274}
275
276/// A stopping point for loops whose steps are too small for a [`check`]
277/// each (the events of an XML part): [`Pace::tick`] checks once every
278/// [`Pace::STEPS`] steps.
279#[derive(Debug, Default)]
280pub(crate) struct Pace(u32);
281
282impl Pace {
283    /// Steps between two checks: a few microseconds of work each, so the
284    /// checks stay far apart in time and close enough for a cancellation.
285    pub(crate) const STEPS: u32 = 4096;
286
287    /// One step: a [`check`] every [`Self::STEPS`] of them.
288    pub(crate) fn tick(&mut self) {
289        self.0 += 1;
290        if self.0 >= Self::STEPS {
291            self.0 = 0;
292            check();
293        }
294    }
295}
296
297/// How often [`blocking`] and [`sleep`] look at the current token while
298/// they wait: the longest they make a cancellation wait.
299#[cfg(any(feature = "net", test))]
300const WAIT_POLL: Duration = Duration::from_millis(10);
301
302/// Runs `work`, a call that blocks without stopping points of its own (a
303/// request waiting for its answer), and returns its result; with a current
304/// token, on a thread of its own, while this one [`check`]s every
305/// [`WAIT_POLL`]. Work left so goes on until it ends by itself, its result
306/// dropped: it gets the token (`None` without one) to stop early where it
307/// can, between the chunks of a download.
308///
309/// # Panics
310/// When `work` panics, or its thread cannot be started.
311#[cfg(any(feature = "net", test))]
312pub(crate) fn blocking<R: Send + 'static>(work: impl FnOnce(Option<CancelToken>) -> R + Send + 'static) -> R {
313    let Some(token) = current() else {
314        return work(None);
315    };
316    check();
317    let (sender, result) = std::sync::mpsc::sync_channel(1);
318    let worker = token.clone();
319    let handle = std::thread::Builder::new()
320        .name("kakemono-wait".into())
321        .spawn(move || {
322            // The receiver is gone when the caller stopped waiting.
323            let _ = sender.send(work(Some(worker)));
324        })
325        .expect("cannot start a thread");
326    loop {
327        match result.recv_timeout(WAIT_POLL) {
328            Ok(result) => return result,
329            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => check(),
330            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => match handle.join() {
331                Err(payload) => resume_unwind(payload),
332                Ok(()) => unreachable!("the worker sends its result before it ends"),
333            },
334        }
335    }
336}
337
338/// Sleeps for `wait`, returning early (by unwinding, as [`check`]) when the
339/// current token stops.
340#[cfg(any(feature = "net", test))]
341pub(crate) fn sleep(wait: Duration) {
342    let end = Instant::now() + wait;
343    loop {
344        check();
345        let now = Instant::now();
346        if now >= end {
347            return;
348        }
349        std::thread::sleep((end - now).min(WAIT_POLL));
350    }
351}
352
353#[cfg(test)]
354mod tests {
355    use super::{CancelToken, Cancelled, check, current};
356    use std::time::Duration;
357
358    #[test]
359    fn work_that_ends_keeps_its_result() {
360        let token = CancelToken::new();
361        assert_eq!(
362            token.run(|| {
363                check();
364                7
365            }),
366            Ok(7)
367        );
368        assert!(current().is_none(), "the token is no longer current");
369    }
370
371    #[test]
372    fn a_cancelled_token_stops_at_the_next_check() {
373        let token = CancelToken::new();
374        let mut reached = false;
375        let outcome = token.run(|| {
376            token.cancel();
377            check();
378            reached = true;
379        });
380        assert_eq!(outcome, Err(Cancelled::Requested));
381        assert!(!reached);
382        assert!(current().is_none());
383    }
384
385    #[test]
386    fn work_does_not_start_with_a_cancelled_token() {
387        let token = CancelToken::new();
388        token.cancel();
389        let mut started = false;
390        assert_eq!(token.run(|| started = true), Err(Cancelled::Requested));
391        assert!(!started);
392    }
393
394    #[test]
395    fn a_deadline_times_out() {
396        let token = CancelToken::with_timeout(Duration::from_millis(20));
397        let outcome = token.run(|| {
398            loop {
399                check();
400                std::thread::sleep(Duration::from_millis(1));
401            }
402        });
403        assert_eq!(outcome, Err(Cancelled::TimedOut));
404    }
405
406    #[test]
407    fn a_parent_stops_its_children_but_not_the_reverse() {
408        let parent = CancelToken::new();
409        let child = parent.child(None);
410        child.cancel();
411        assert_eq!(parent.state(), None);
412        let other = parent.child(Some(Duration::from_secs(60)));
413        parent.cancel();
414        assert_eq!(other.state(), Some(Cancelled::Requested));
415    }
416
417    #[test]
418    fn other_panics_go_on() {
419        let token = CancelToken::new();
420        let outcome = std::panic::catch_unwind(|| token.run(|| panic!("boom")));
421        assert!(outcome.is_err());
422        assert!(current().is_none());
423    }
424
425    #[test]
426    fn a_blocking_call_is_left_when_cancelled() {
427        // Without a token it runs on this thread.
428        assert!(super::blocking(|token| token.is_none()));
429        // The call sees the token.
430        assert_eq!(
431            CancelToken::new().run(|| super::blocking(|token| token.is_some())),
432            Ok(true)
433        );
434        // A call that outlasts the time limit is left, and ends by itself.
435        let token = CancelToken::with_timeout(Duration::from_millis(30));
436        let start = std::time::Instant::now();
437        let outcome = token.run(|| super::blocking(|_| std::thread::sleep(Duration::from_millis(800))));
438        assert_eq!(outcome, Err(Cancelled::TimedOut));
439        assert!(start.elapsed() < Duration::from_secs(2));
440        // A call that ends gives its result.
441        assert_eq!(CancelToken::new().run(|| super::blocking(|_| 5)), Ok(5));
442    }
443
444    #[test]
445    fn a_panic_in_a_blocking_call_goes_on() {
446        let token = CancelToken::new();
447        let outcome = std::panic::catch_unwind(|| token.run(|| super::blocking(|_| panic!("boom"))));
448        assert!(outcome.is_err());
449    }
450
451    #[test]
452    fn a_sleep_ends_at_a_cancellation() {
453        let start = std::time::Instant::now();
454        super::sleep(Duration::from_millis(5));
455        assert!(start.elapsed() >= Duration::from_millis(5));
456        let token = CancelToken::with_timeout(Duration::from_millis(20));
457        let start = std::time::Instant::now();
458        assert_eq!(
459            token.run(|| super::sleep(Duration::from_secs(10))),
460            Err(Cancelled::TimedOut)
461        );
462        assert!(start.elapsed() < Duration::from_secs(2));
463    }
464
465    #[test]
466    fn a_pace_checks_once_in_many_steps() {
467        let token = CancelToken::new();
468        let steps = std::cell::Cell::new(0);
469        let outcome = token.run(|| {
470            let mut pace = super::Pace::default();
471            token.cancel();
472            loop {
473                pace.tick();
474                steps.set(steps.get() + 1);
475            }
476        });
477        assert_eq!(outcome, Err::<(), _>(Cancelled::Requested));
478        assert_eq!(steps.get(), super::Pace::STEPS - 1);
479    }
480
481    #[test]
482    fn the_first_cause_stays() {
483        // Cancelled, then past the deadline: cancelled.
484        let parent = CancelToken::new();
485        let child = parent.child(Some(Duration::from_millis(1)));
486        parent.cancel();
487        std::thread::sleep(Duration::from_millis(5));
488        assert_eq!(child.state(), Some(Cancelled::Requested));
489        // Past the deadline (and seen so), then cancelled: timed out.
490        let token = CancelToken::with_timeout(Duration::from_millis(1));
491        std::thread::sleep(Duration::from_millis(5));
492        assert_eq!(token.state(), Some(Cancelled::TimedOut));
493        token.cancel();
494        assert_eq!(token.state(), Some(Cancelled::TimedOut));
495        // A parent past its deadline stops its child as timed out.
496        let parent = CancelToken::with_timeout(Duration::from_millis(1));
497        let child = parent.child(None);
498        std::thread::sleep(Duration::from_millis(5));
499        assert_eq!(child.state(), Some(Cancelled::TimedOut));
500        child.cancel();
501        assert_eq!(child.state(), Some(Cancelled::TimedOut));
502    }
503
504    #[test]
505    fn the_reasons_read_well() {
506        assert_eq!(Cancelled::Requested.to_string(), "the conversion was cancelled");
507        assert!(Cancelled::TimedOut.to_string().contains("time limit"));
508        assert_eq!(CancelToken::default().state(), None);
509    }
510
511    #[test]
512    fn runs_nest() {
513        let outer = CancelToken::new();
514        let inner = CancelToken::new();
515        let outcome = outer.run(|| {
516            let nested = inner.run(|| {
517                inner.cancel();
518                check();
519            });
520            assert_eq!(nested, Err(Cancelled::Requested));
521            check(); // the outer token is current again, and not cancelled
522            1
523        });
524        assert_eq!(outcome, Ok(1));
525    }
526}