kakemono 0.22.3

Convert PDF, Word and EPUB documents and web pages to HTML, Markdown, EPUB, LaTeX and JSON in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! Stopping a conversion from another thread, or after a time limit.
//!
//! A [`CancelToken`] is made current on a thread by [`CancelToken::run`];
//! the pipeline calls [`check`] at its natural stopping points (each page,
//! each stage, each chunk of a download), and the worker threads it starts
//! inherit the token ([`current`], [`CancelToken::enter`]). Once the token is
//! cancelled, or past its deadline, the next [`check`] unwinds the stack up
//! to [`CancelToken::run`], which returns [`Cancelled`]: the functions of the
//! pipeline keep their signatures, and everything they hold is dropped on the
//! way, as for an early return.
//!
//! [`check`] reads one atomic flag (and the clock when a deadline is set):
//! the checks are at most a few per page, so they cost nothing measurable.
//! Without a current token, [`check`] does nothing.

use std::cell::RefCell;
use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
use std::sync::Arc;
use std::sync::atomic::{AtomicU8, Ordering};
use std::time::{Duration, Instant};

/// Why a conversion stopped before its end.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Cancelled {
    /// [`CancelToken::cancel`] was called (on the token or on its parent).
    Requested,
    /// The deadline of the token (or of its parent) passed.
    TimedOut,
}

impl std::fmt::Display for Cancelled {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::Requested => "the conversion was cancelled",
            Self::TimedOut => "the conversion took longer than its time limit",
        })
    }
}

impl std::error::Error for Cancelled {}

/// [`Inner::stopped`]: not stopped (yet).
const RUNNING: u8 = 0;
/// [`Inner::stopped`]: [`Cancelled::Requested`].
const REQUESTED: u8 = 1;
/// [`Inner::stopped`]: [`Cancelled::TimedOut`].
const TIMED_OUT: u8 = 2;

/// What a token holds, shared by its clones.
#[derive(Debug)]
struct Inner {
    /// Why this token stopped, once it is known: [`RUNNING`], [`REQUESTED`]
    /// (set by [`CancelToken::cancel`]) or [`TIMED_OUT`] (set when its
    /// deadline is seen passed). The first one set stays, so that a token
    /// cancelled after its deadline was seen, or the reverse, keeps the
    /// cause that came first.
    stopped: AtomicU8,
    /// When the work must stop, if it has a time limit.
    deadline: Option<Instant>,
    /// A token whose cancellation (or deadline) stops this one too.
    parent: Option<CancelToken>,
}

/// A request to stop a conversion, shared by the thread that runs it and
/// those that may stop it (clones share the same request).
///
/// ```
/// use kakemono::{CancelToken, Cancelled, Paper};
/// # fn main() -> anyhow::Result<()> {
/// let token = CancelToken::new();
/// let stopper = token.clone();
/// // Elsewhere, e.g. when the user closes the window: stopper.cancel();
/// # stopper.cancel();
/// let analysis = token.run(|| -> anyhow::Result<_> {
///     let paper = Paper::from_path("tests/data/1602.03837v1.pdf")?;
///     Ok(paper.analyze())
/// });
/// assert_eq!(analysis.err(), Some(Cancelled::Requested));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct CancelToken(Arc<Inner>);

impl Default for CancelToken {
    fn default() -> Self {
        Self::new()
    }
}

impl CancelToken {
    /// A token with no time limit, not cancelled.
    #[must_use]
    pub fn new() -> Self {
        Self::make(None, None)
    }

    /// A token that times out `limit` from now.
    #[must_use]
    pub fn with_timeout(limit: Duration) -> Self {
        Self::make(Instant::now().checked_add(limit), None)
    }

    /// A token stopped by this one (by its cancellation or its deadline), and
    /// by its own: cancelling it does not cancel this one. `limit` is its own
    /// time limit, from now.
    #[must_use]
    pub fn child(&self, limit: Option<Duration>) -> Self {
        Self::make(
            limit.and_then(|limit| Instant::now().checked_add(limit)),
            Some(self.clone()),
        )
    }

    /// A token with these fields.
    fn make(deadline: Option<Instant>, parent: Option<Self>) -> Self {
        Self(Arc::new(Inner {
            stopped: AtomicU8::new(RUNNING),
            deadline,
            parent,
        }))
    }

    /// Asks the work running with this token (and its children) to stop.
    /// It stops at its next stopping point, normally within a page.
    pub fn cancel(&self) {
        // A token already stopped keeps its cause.
        let _ = self
            .0
            .stopped
            .compare_exchange(RUNNING, REQUESTED, Ordering::Relaxed, Ordering::Relaxed);
    }

    /// Why the work must stop, or `None` while it may go on.
    #[must_use]
    pub fn state(&self) -> Option<Cancelled> {
        let found = self.cause()?;
        // Kept on this token too, so that a later `cancel` of it does not
        // change why it stopped.
        Some(
            match self
                .0
                .stopped
                .compare_exchange(RUNNING, found, Ordering::Relaxed, Ordering::Relaxed)
            {
                Ok(_) => found,
                Err(known) => known,
            },
        )
        .map(|code| {
            if code == TIMED_OUT {
                Cancelled::TimedOut
            } else {
                Cancelled::Requested
            }
        })
    }

    /// Why this token must stop ([`REQUESTED`] or [`TIMED_OUT`]), from it
    /// and its parents: a cause already known comes first, since a deadline
    /// seen passed now may have passed after it.
    fn cause(&self) -> Option<u8> {
        let chain = || std::iter::successors(Some(self), |token| token.0.parent.as_ref());
        if let Some(known) = chain()
            .map(|token| token.0.stopped.load(Ordering::Relaxed))
            .find(|&code| code != RUNNING)
        {
            return Some(known);
        }
        let now = Instant::now();
        let CancelToken(inner) = chain().find(|token| token.0.deadline.is_some_and(|deadline| now >= deadline))?;
        // Recorded where it passed, unless a cancellation came meanwhile.
        Some(
            match inner
                .stopped
                .compare_exchange(RUNNING, TIMED_OUT, Ordering::Relaxed, Ordering::Relaxed)
            {
                Ok(_) => TIMED_OUT,
                Err(known) => known,
            },
        )
    }

    /// Runs `work` on this thread with this token current, and returns its
    /// result, or why it stopped early. Work that ends normally keeps its
    /// result, even when the token was cancelled meanwhile; work is not
    /// started with a token already cancelled.
    ///
    /// The work stops by unwinding its stack, as a panic does but without
    /// the panic hook, so:
    /// - the program must be built with `panic = "unwind"` (the default):
    ///   with `panic = "abort"`, a cancellation aborts the process;
    /// - a `catch_unwind` inside `work` (one of yours, or a library's) sees
    ///   the cancellation as a panic: let a payload of type [`Cancelled`]
    ///   go on with `std::panic::resume_unwind`;
    /// - a `run` inside `work` makes its own token current until it
    ///   returns: give it a [`child`](Self::child) of this one, so that
    ///   cancelling this one stops it too;
    /// - threads that `work` starts itself do not see the token: only the
    ///   library's own worker threads do.
    ///
    /// # Errors
    /// [`Cancelled`] when the token was cancelled, or timed out, before
    /// `work` ended.
    ///
    /// # Panics
    /// When `work` panics: the panic goes on.
    pub fn run<R>(&self, work: impl FnOnce() -> R) -> Result<R, Cancelled> {
        if let Some(stopped) = self.state() {
            return Err(stopped);
        }
        let entered = self.enter();
        let outcome = catch_unwind(AssertUnwindSafe(work));
        drop(entered);
        match outcome {
            Ok(result) => Ok(result),
            Err(payload) => match payload.downcast::<Cancelled>() {
                Ok(stopped) => Err(*stopped),
                Err(payload) => resume_unwind(payload),
            },
        }
    }

    /// Makes this token current on this thread until the guard is dropped
    /// (then the one before is current again). A [`check`] that finds it
    /// cancelled unwinds: only call this where [`run`](Self::run) or a
    /// thread that hands panics on (such as a scoped thread) is above.
    pub(crate) fn enter(&self) -> Entered {
        Entered(CURRENT.with(|current| current.replace(Some(self.clone()))))
    }
}

thread_local! {
    /// The token of the work running on this thread.
    static CURRENT: RefCell<Option<CancelToken>> = const { RefCell::new(None) };
}

/// Makes the token before current again when dropped (see
/// [`CancelToken::enter`]).
pub(crate) struct Entered(Option<CancelToken>);

impl Drop for Entered {
    fn drop(&mut self) {
        let before = self.0.take();
        CURRENT.with(|current| *current.borrow_mut() = before);
    }
}

/// The token of the work running on this thread, for the threads it
/// starts: each makes it current with [`enter`].
pub(crate) fn current() -> Option<CancelToken> {
    CURRENT.with(|current| current.borrow().clone())
}

/// Makes `token` current on this thread, if there is one (see
/// [`CancelToken::enter`]): for worker threads, with the token of the
/// thread that started them.
pub(crate) fn enter(token: Option<&CancelToken>) -> Option<Entered> {
    token.map(CancelToken::enter)
}

/// A stopping point: unwinds to [`CancelToken::run`] when the current token
/// is cancelled or timed out; does nothing otherwise, or without a token.
///
/// Call it only where no lock shared beyond the work is held and no value
/// shared beyond it is half changed: the unwinding drops what it crosses.
pub(crate) fn check() {
    let stopped = CURRENT.with(|current| current.borrow().as_ref().and_then(CancelToken::state));
    if let Some(stopped) = stopped {
        // `resume_unwind` does not call the panic hook: nothing is printed.
        resume_unwind(Box::new(stopped));
    }
}

/// A stopping point for loops whose steps are too small for a [`check`]
/// each (the events of an XML part): [`Pace::tick`] checks once every
/// [`Pace::STEPS`] steps.
#[derive(Debug, Default)]
pub(crate) struct Pace(u32);

impl Pace {
    /// Steps between two checks: a few microseconds of work each, so the
    /// checks stay far apart in time and close enough for a cancellation.
    pub(crate) const STEPS: u32 = 4096;

    /// One step: a [`check`] every [`Self::STEPS`] of them.
    pub(crate) fn tick(&mut self) {
        self.0 += 1;
        if self.0 >= Self::STEPS {
            self.0 = 0;
            check();
        }
    }
}

/// How often [`blocking`] and [`sleep`] look at the current token while
/// they wait: the longest they make a cancellation wait.
#[cfg(any(feature = "net", test))]
const WAIT_POLL: Duration = Duration::from_millis(10);

/// Runs `work`, a call that blocks without stopping points of its own (a
/// request waiting for its answer), and returns its result; with a current
/// token, on a thread of its own, while this one [`check`]s every
/// [`WAIT_POLL`]. Work left so goes on until it ends by itself, its result
/// dropped: it gets the token (`None` without one) to stop early where it
/// can, between the chunks of a download.
///
/// # Panics
/// When `work` panics, or its thread cannot be started.
#[cfg(any(feature = "net", test))]
pub(crate) fn blocking<R: Send + 'static>(work: impl FnOnce(Option<CancelToken>) -> R + Send + 'static) -> R {
    let Some(token) = current() else {
        return work(None);
    };
    check();
    let (sender, result) = std::sync::mpsc::sync_channel(1);
    let worker = token.clone();
    let handle = std::thread::Builder::new()
        .name("kakemono-wait".into())
        .spawn(move || {
            // The receiver is gone when the caller stopped waiting.
            let _ = sender.send(work(Some(worker)));
        })
        .expect("cannot start a thread");
    loop {
        match result.recv_timeout(WAIT_POLL) {
            Ok(result) => return result,
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => check(),
            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => match handle.join() {
                Err(payload) => resume_unwind(payload),
                Ok(()) => unreachable!("the worker sends its result before it ends"),
            },
        }
    }
}

/// Sleeps for `wait`, returning early (by unwinding, as [`check`]) when the
/// current token stops.
#[cfg(any(feature = "net", test))]
pub(crate) fn sleep(wait: Duration) {
    let end = Instant::now() + wait;
    loop {
        check();
        let now = Instant::now();
        if now >= end {
            return;
        }
        std::thread::sleep((end - now).min(WAIT_POLL));
    }
}

#[cfg(test)]
mod tests {
    use super::{CancelToken, Cancelled, check, current};
    use std::time::Duration;

    #[test]
    fn work_that_ends_keeps_its_result() {
        let token = CancelToken::new();
        assert_eq!(
            token.run(|| {
                check();
                7
            }),
            Ok(7)
        );
        assert!(current().is_none(), "the token is no longer current");
    }

    #[test]
    fn a_cancelled_token_stops_at_the_next_check() {
        let token = CancelToken::new();
        let mut reached = false;
        let outcome = token.run(|| {
            token.cancel();
            check();
            reached = true;
        });
        assert_eq!(outcome, Err(Cancelled::Requested));
        assert!(!reached);
        assert!(current().is_none());
    }

    #[test]
    fn work_does_not_start_with_a_cancelled_token() {
        let token = CancelToken::new();
        token.cancel();
        let mut started = false;
        assert_eq!(token.run(|| started = true), Err(Cancelled::Requested));
        assert!(!started);
    }

    #[test]
    fn a_deadline_times_out() {
        let token = CancelToken::with_timeout(Duration::from_millis(20));
        let outcome = token.run(|| {
            loop {
                check();
                std::thread::sleep(Duration::from_millis(1));
            }
        });
        assert_eq!(outcome, Err(Cancelled::TimedOut));
    }

    #[test]
    fn a_parent_stops_its_children_but_not_the_reverse() {
        let parent = CancelToken::new();
        let child = parent.child(None);
        child.cancel();
        assert_eq!(parent.state(), None);
        let other = parent.child(Some(Duration::from_secs(60)));
        parent.cancel();
        assert_eq!(other.state(), Some(Cancelled::Requested));
    }

    #[test]
    fn other_panics_go_on() {
        let token = CancelToken::new();
        let outcome = std::panic::catch_unwind(|| token.run(|| panic!("boom")));
        assert!(outcome.is_err());
        assert!(current().is_none());
    }

    #[test]
    fn a_blocking_call_is_left_when_cancelled() {
        // Without a token it runs on this thread.
        assert!(super::blocking(|token| token.is_none()));
        // The call sees the token.
        assert_eq!(
            CancelToken::new().run(|| super::blocking(|token| token.is_some())),
            Ok(true)
        );
        // A call that outlasts the time limit is left, and ends by itself.
        let token = CancelToken::with_timeout(Duration::from_millis(30));
        let start = std::time::Instant::now();
        let outcome = token.run(|| super::blocking(|_| std::thread::sleep(Duration::from_millis(800))));
        assert_eq!(outcome, Err(Cancelled::TimedOut));
        assert!(start.elapsed() < Duration::from_secs(2));
        // A call that ends gives its result.
        assert_eq!(CancelToken::new().run(|| super::blocking(|_| 5)), Ok(5));
    }

    #[test]
    fn a_panic_in_a_blocking_call_goes_on() {
        let token = CancelToken::new();
        let outcome = std::panic::catch_unwind(|| token.run(|| super::blocking(|_| panic!("boom"))));
        assert!(outcome.is_err());
    }

    #[test]
    fn a_sleep_ends_at_a_cancellation() {
        let start = std::time::Instant::now();
        super::sleep(Duration::from_millis(5));
        assert!(start.elapsed() >= Duration::from_millis(5));
        let token = CancelToken::with_timeout(Duration::from_millis(20));
        let start = std::time::Instant::now();
        assert_eq!(
            token.run(|| super::sleep(Duration::from_secs(10))),
            Err(Cancelled::TimedOut)
        );
        assert!(start.elapsed() < Duration::from_secs(2));
    }

    #[test]
    fn a_pace_checks_once_in_many_steps() {
        let token = CancelToken::new();
        let steps = std::cell::Cell::new(0);
        let outcome = token.run(|| {
            let mut pace = super::Pace::default();
            token.cancel();
            loop {
                pace.tick();
                steps.set(steps.get() + 1);
            }
        });
        assert_eq!(outcome, Err::<(), _>(Cancelled::Requested));
        assert_eq!(steps.get(), super::Pace::STEPS - 1);
    }

    #[test]
    fn the_first_cause_stays() {
        // Cancelled, then past the deadline: cancelled.
        let parent = CancelToken::new();
        let child = parent.child(Some(Duration::from_millis(1)));
        parent.cancel();
        std::thread::sleep(Duration::from_millis(5));
        assert_eq!(child.state(), Some(Cancelled::Requested));
        // Past the deadline (and seen so), then cancelled: timed out.
        let token = CancelToken::with_timeout(Duration::from_millis(1));
        std::thread::sleep(Duration::from_millis(5));
        assert_eq!(token.state(), Some(Cancelled::TimedOut));
        token.cancel();
        assert_eq!(token.state(), Some(Cancelled::TimedOut));
        // A parent past its deadline stops its child as timed out.
        let parent = CancelToken::with_timeout(Duration::from_millis(1));
        let child = parent.child(None);
        std::thread::sleep(Duration::from_millis(5));
        assert_eq!(child.state(), Some(Cancelled::TimedOut));
        child.cancel();
        assert_eq!(child.state(), Some(Cancelled::TimedOut));
    }

    #[test]
    fn the_reasons_read_well() {
        assert_eq!(Cancelled::Requested.to_string(), "the conversion was cancelled");
        assert!(Cancelled::TimedOut.to_string().contains("time limit"));
        assert_eq!(CancelToken::default().state(), None);
    }

    #[test]
    fn runs_nest() {
        let outer = CancelToken::new();
        let inner = CancelToken::new();
        let outcome = outer.run(|| {
            let nested = inner.run(|| {
                inner.cancel();
                check();
            });
            assert_eq!(nested, Err(Cancelled::Requested));
            check(); // the outer token is current again, and not cancelled
            1
        });
        assert_eq!(outcome, Ok(1));
    }
}