use std::cell::RefCell;
use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use crate::sync::lock;
#[cfg(feature = "store")]
use crate::{Error, ErrorKind, Result};
#[cfg(feature = "store")]
pub(crate) const STEPS: std::ffi::c_int = 1000;
#[derive(Clone)]
pub struct CancellationToken {
inner: Arc<Inner>,
}
struct Inner {
cancelled: AtomicBool,
timeout: Option<(Instant, Duration)>,
stops: Mutex<Stops>,
}
#[derive(Default)]
struct Stops {
#[cfg(feature = "store")]
next: u64,
each: Vec<(u64, Stop)>,
}
type Stop = Arc<dyn Fn() + Send + Sync>;
thread_local! {
static SCOPE: RefCell<Vec<Arc<Inner>>> = const { RefCell::new(Vec::new()) };
}
impl CancellationToken {
pub fn new() -> Self {
Self::stopping_at(None)
}
pub fn timeout(after: Duration) -> Self {
Self::stopping_at(Instant::now().checked_add(after).map(|at| (at, after)))
}
fn stopping_at(timeout: Option<(Instant, Duration)>) -> Self {
let inner = Inner { cancelled: AtomicBool::new(false), timeout, stops: Mutex::default() };
Self { inner: Arc::new(inner) }
}
pub fn cancel(&self) {
if self.inner.cancelled.swap(true, Ordering::SeqCst) {
return;
}
let stops = lock(&self.inner.stops);
for (_, stop) in &stops.each {
stop();
}
}
pub fn is_cancelled(&self) -> bool {
self.inner.stopped()
}
pub fn run<T>(&self, call: impl FnOnce() -> T) -> T {
let _scope = Scope::enter(Arc::clone(&self.inner));
call()
}
#[cfg(any(feature = "wire", feature = "mcp"))]
fn same(&self, other: &CancellationToken) -> bool {
Arc::ptr_eq(&self.inner, &other.inner)
}
}
impl Default for CancellationToken {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for CancellationToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut debug = f.debug_struct("CancellationToken");
debug.field("cancelled", &self.inner.cancelled.load(Ordering::SeqCst));
if let Some((_, after)) = self.inner.timeout {
debug.field("timeout", &after);
}
debug.finish()
}
}
#[cfg(any(feature = "wire", feature = "mcp"))]
pub(crate) struct Tokens<K> {
by_id: Mutex<std::collections::HashMap<K, CancellationToken>>,
}
#[cfg(any(feature = "wire", feature = "mcp"))]
impl<K: Eq + std::hash::Hash> Tokens<K> {
pub(crate) fn start(&self, id: K) -> CancellationToken {
let token = CancellationToken::new();
lock(&self.by_id).insert(id, token.clone());
token
}
#[cfg(feature = "mcp")]
pub(crate) fn holds(&self, id: &K) -> bool {
lock(&self.by_id).contains_key(id)
}
pub(crate) fn cancel(&self, id: &K) {
if let Some(token) = lock(&self.by_id).get(id) {
token.cancel();
}
}
pub(crate) fn finish(&self, id: &K, token: &CancellationToken) {
let mut by_id = lock(&self.by_id);
if by_id.get(id).is_some_and(|kept| kept.same(token)) {
by_id.remove(id);
}
}
pub(crate) fn cancel_all(&self) {
let tokens: Vec<CancellationToken> = lock(&self.by_id).drain().map(|(_, token)| token).collect();
tokens.iter().for_each(CancellationToken::cancel);
}
}
#[cfg(any(feature = "wire", feature = "mcp"))]
impl<K> Default for Tokens<K> {
fn default() -> Self {
Tokens { by_id: Mutex::default() }
}
}
impl Inner {
fn stopped(&self) -> bool {
self.cancelled.load(Ordering::SeqCst) || self.timeout.is_some_and(|(at, _)| Instant::now() >= at)
}
}
#[cfg(feature = "store")]
impl Inner {
fn refusal(&self, what: impl FnOnce() -> String) -> Option<Error> {
if self.cancelled.load(Ordering::SeqCst) {
return Some(Error::new(ErrorKind::Cancelled, what()));
}
let (at, after) = self.timeout?;
let past = Instant::now() >= at;
past.then(|| Error::new(ErrorKind::Cancelled, format!("{} past its timeout of {after:?}", what())))
}
fn add(&self, stop: Stop) -> u64 {
let mut stops = lock(&self.stops);
let id = stops.next;
stops.next += 1;
stops.each.push((id, stop));
id
}
fn remove(&self, id: u64) {
lock(&self.stops).each.retain(|(kept, _)| *kept != id);
}
}
struct Scope;
impl Scope {
fn enter(inner: Arc<Inner>) -> Scope {
SCOPE.with(|scope| scope.borrow_mut().push(inner));
Scope
}
}
impl Drop for Scope {
fn drop(&mut self) {
SCOPE.with(|scope| scope.borrow_mut().pop());
}
}
#[cfg(feature = "store")]
pub(crate) struct Given {
stops: Vec<(Arc<Inner>, u64)>,
}
#[cfg(feature = "store")]
impl Drop for Given {
fn drop(&mut self) {
for (inner, id) in &self.stops {
inner.remove(*id);
}
}
}
#[cfg(any(all(feature = "async", feature = "store"), feature = "records"))]
#[derive(Clone, Default)]
pub(crate) struct Captured(Vec<Arc<Inner>>);
#[cfg(any(all(feature = "async", feature = "store"), feature = "records"))]
pub(crate) fn captured() -> Captured {
Captured(SCOPE.with(|scope| scope.try_borrow().map(|scope| scope.clone()).unwrap_or_default()))
}
#[cfg(any(all(feature = "async", feature = "store"), feature = "records"))]
impl Captured {
pub(crate) fn run<T>(&self, own: Option<&CancellationToken>, call: impl FnOnce() -> T) -> T {
let tokens = self.0.iter().cloned().chain(own.map(|token| Arc::clone(&token.inner)));
let _scopes: Vec<Scope> = tokens.map(Scope::enter).collect();
call()
}
}
#[cfg(any(all(feature = "async", feature = "store"), feature = "records"))]
impl fmt::Debug for Captured {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Captured({} tokens)", self.0.len())
}
}
#[cfg(feature = "store")]
pub(crate) fn in_scope() -> bool {
SCOPE.with(|scope| scope.try_borrow().is_ok_and(|scope| !scope.is_empty()))
}
#[cfg(feature = "store")]
pub(crate) fn stopped() -> bool {
SCOPE.with(|scope| scope.try_borrow().is_ok_and(|scope| scope.iter().any(|inner| inner.stopped())))
}
#[cfg(feature = "store")]
pub(crate) fn check(what: impl FnOnce() -> String) -> Result<()> {
let refused = SCOPE.with(|scope| {
let scope = scope.try_borrow().ok()?;
let stopped = scope.iter().find(|inner| inner.stopped())?;
stopped.refusal(what)
});
refused.map_or(Ok(()), Err)
}
#[cfg(feature = "store")]
pub(crate) fn deadline() -> Option<Instant> {
SCOPE.with(|scope| {
let scope = scope.try_borrow().ok()?;
scope.iter().filter_map(|inner| inner.timeout.map(|(at, _)| at)).min()
})
}
#[cfg(feature = "store")]
pub(crate) fn on_cancel(stop: impl Fn() + Send + Sync + 'static) -> Option<Given> {
let scope: Vec<Arc<Inner>> = SCOPE.with(|scope| scope.try_borrow().map(|scope| scope.clone()).unwrap_or_default());
if scope.is_empty() {
return None;
}
let stop: Stop = Arc::new(stop);
let stops = scope.into_iter().map(|inner| (Arc::clone(&inner), inner.add(Arc::clone(&stop)))).collect();
Some(Given { stops })
}
#[cfg(feature = "store")]
pub(crate) fn named(error: Error, what: impl FnOnce() -> String) -> Error {
if error.kind() != ErrorKind::Cancelled {
return error;
}
check(what).err().unwrap_or(error)
}
#[cfg(all(test, feature = "store"))]
#[path = "cancel_tests.rs"]
mod tests;