kakemono/common/
cancel.rs1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24#[non_exhaustive]
25pub enum Cancelled {
26 Requested,
28 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
43const RUNNING: u8 = 0;
45const REQUESTED: u8 = 1;
47const TIMED_OUT: u8 = 2;
49
50#[derive(Debug)]
52struct Inner {
53 stopped: AtomicU8,
59 deadline: Option<Instant>,
61 parent: Option<CancelToken>,
63}
64
65#[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 #[must_use]
95 pub fn new() -> Self {
96 Self::make(None, None)
97 }
98
99 #[must_use]
101 pub fn with_timeout(limit: Duration) -> Self {
102 Self::make(Instant::now().checked_add(limit), None)
103 }
104
105 #[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 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 pub fn cancel(&self) {
128 let _ = self
130 .0
131 .stopped
132 .compare_exchange(RUNNING, REQUESTED, Ordering::Relaxed, Ordering::Relaxed);
133 }
134
135 #[must_use]
137 pub fn state(&self) -> Option<Cancelled> {
138 let found = self.cause()?;
139 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 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 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 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 pub(crate) fn enter(&self) -> Entered {
230 Entered(CURRENT.with(|current| current.replace(Some(self.clone()))))
231 }
232}
233
234thread_local! {
235 static CURRENT: RefCell<Option<CancelToken>> = const { RefCell::new(None) };
237}
238
239pub(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
250pub(crate) fn current() -> Option<CancelToken> {
253 CURRENT.with(|current| current.borrow().clone())
254}
255
256pub(crate) fn enter(token: Option<&CancelToken>) -> Option<Entered> {
260 token.map(CancelToken::enter)
261}
262
263pub(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(Box::new(stopped));
273 }
274}
275
276#[derive(Debug, Default)]
280pub(crate) struct Pace(u32);
281
282impl Pace {
283 pub(crate) const STEPS: u32 = 4096;
286
287 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#[cfg(any(feature = "net", test))]
300const WAIT_POLL: Duration = Duration::from_millis(10);
301
302#[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 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#[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 assert!(super::blocking(|token| token.is_none()));
429 assert_eq!(
431 CancelToken::new().run(|| super::blocking(|token| token.is_some())),
432 Ok(true)
433 );
434 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 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 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 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 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(); 1
523 });
524 assert_eq!(outcome, Ok(1));
525 }
526}