use std::cell::RefCell;
use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Cancelled {
Requested,
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 {}
#[derive(Debug)]
struct Inner {
cancelled: AtomicBool,
deadline: Option<Instant>,
parent: Option<CancelToken>,
}
#[derive(Debug, Clone)]
pub struct CancelToken(Arc<Inner>);
impl Default for CancelToken {
fn default() -> Self {
Self::new()
}
}
impl CancelToken {
#[must_use]
pub fn new() -> Self {
Self::make(None, None)
}
#[must_use]
pub fn with_timeout(limit: Duration) -> Self {
Self::make(Instant::now().checked_add(limit), None)
}
#[must_use]
pub fn child(&self, limit: Option<Duration>) -> Self {
Self::make(
limit.and_then(|limit| Instant::now().checked_add(limit)),
Some(self.clone()),
)
}
fn make(deadline: Option<Instant>, parent: Option<Self>) -> Self {
Self(Arc::new(Inner {
cancelled: AtomicBool::new(false),
deadline,
parent,
}))
}
pub fn cancel(&self) {
self.0.cancelled.store(true, Ordering::Relaxed);
}
#[must_use]
pub fn state(&self) -> Option<Cancelled> {
let mut token = Some(self);
while let Some(CancelToken(inner)) = token {
if inner.cancelled.load(Ordering::Relaxed) {
return Some(Cancelled::Requested);
}
if inner.deadline.is_some_and(|deadline| Instant::now() >= deadline) {
return Some(Cancelled::TimedOut);
}
token = inner.parent.as_ref();
}
None
}
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),
},
}
}
pub(crate) fn enter(&self) -> Entered {
Entered(CURRENT.with(|current| current.replace(Some(self.clone()))))
}
}
thread_local! {
static CURRENT: RefCell<Option<CancelToken>> = const { RefCell::new(None) };
}
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);
}
}
pub(crate) fn current() -> Option<CancelToken> {
CURRENT.with(|current| current.borrow().clone())
}
pub(crate) fn enter(token: Option<&CancelToken>) -> Option<Entered> {
token.map(CancelToken::enter)
}
pub(crate) fn check() {
let stopped = CURRENT.with(|current| current.borrow().as_ref().and_then(CancelToken::state));
if let Some(stopped) = stopped {
resume_unwind(Box::new(stopped));
}
}
#[derive(Debug, Default)]
pub(crate) struct Pace(u32);
impl Pace {
pub(crate) const STEPS: u32 = 4096;
pub(crate) fn tick(&mut self) {
self.0 += 1;
if self.0 >= Self::STEPS {
self.0 = 0;
check();
}
}
}
const WAIT_POLL: Duration = Duration::from_millis(10);
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 || {
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"),
},
}
}
}
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() {
assert!(super::blocking(|token| token.is_none()));
assert_eq!(
CancelToken::new().run(|| super::blocking(|token| token.is_some())),
Ok(true)
);
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));
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_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(); 1
});
assert_eq!(outcome, Ok(1));
}
}