use std::{
cell::{Cell, RefCell},
rc::Rc,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
use crate::{errors::OperationPhase, Error, Result};
#[derive(Debug, Clone, Default)]
pub struct CancelToken(Arc<AtomicBool>);
impl CancelToken {
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
self.0.store(true, Ordering::Release);
}
pub fn is_cancelled(&self) -> bool {
self.0.load(Ordering::Acquire)
}
}
type InterruptCheck = dyn Fn(OperationPhase) -> Result<()> + Send + Sync;
#[derive(Clone, Default)]
pub struct OperationOptions {
cancellation: Option<CancelToken>,
interrupt_check: Option<Arc<InterruptCheck>>,
}
impl std::fmt::Debug for OperationOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OperationOptions")
.field("cancellation", &self.cancellation)
.finish_non_exhaustive()
}
}
impl OperationOptions {
#[must_use]
pub fn cancellation(mut self, token: impl Into<Option<CancelToken>>) -> Self {
self.cancellation = token.into();
self
}
pub fn get_cancellation(&self) -> Option<&CancelToken> {
self.cancellation.as_ref()
}
#[doc(hidden)]
#[must_use]
pub fn with_interrupt_check(
mut self,
check: impl Fn(OperationPhase) -> Result<()> + Send + Sync + 'static,
) -> Self {
self.interrupt_check = Some(Arc::new(check));
self
}
}
struct Operation {
options: OperationOptions,
phase: Cell<OperationPhase>,
}
impl Operation {
fn cancelled(&self) -> Result<()> {
if self
.options
.cancellation
.as_ref()
.is_some_and(CancelToken::is_cancelled)
{
return Err(Error::Cancelled);
}
Ok(())
}
}
thread_local! {
static ACTIVE: RefCell<Option<Rc<Operation>>> = const { RefCell::new(None) };
}
struct Scope(Option<Rc<Operation>>);
impl Drop for Scope {
fn drop(&mut self) {
let previous = ACTIVE.with(|active| active.replace(self.0.take()));
drop(previous);
}
}
pub(crate) fn run<T>(options: &OperationOptions, execute: impl FnOnce() -> Result<T>) -> Result<T> {
let current = Rc::new(Operation {
options: options.clone(),
phase: Cell::new(OperationPhase::Check),
});
let _scope = Scope(ACTIVE.with(|active| active.replace(Some(current))));
checkpoint()?;
execute()
}
pub(crate) fn current_phase() -> Option<OperationPhase> {
ACTIVE.with_borrow(|active| active.as_ref().map(|active| active.phase.get()))
}
pub(crate) fn external<T>(call: impl FnOnce() -> T) -> T {
let _scope = Scope(ACTIVE.with(|active| active.replace(None)));
call()
}
pub(crate) fn phase(phase: OperationPhase) -> Result<()> {
ACTIVE.with_borrow(|active| {
if let Some(active) = active {
active.phase.set(phase);
}
});
checkpoint()
}
pub(crate) fn check() -> Result<()> {
ACTIVE.with_borrow(|active| active.as_ref().map_or(Ok(()), |active| active.cancelled()))
}
pub(crate) fn checkpoint() -> Result<()> {
let active = ACTIVE.with_borrow(Clone::clone);
if let Some(active) = active {
active.cancelled()?;
if let Some(check) = &active.options.interrupt_check {
external(|| check(active.phase.get()))?;
}
active.cancelled()?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn source_selection_observes_cancellation_and_independent_scopes() {
let original = crate::NumericValues::nullable("v", [Some(-0.), None, Some(f64::NAN)]);
let token = CancelToken::new();
let options = OperationOptions::default().cancellation(token.clone());
let result = run(&options, || {
token.cancel();
assert!(matches!(
crate::CategoryValues::new("category", ["A", "B"]),
Err(Error::Cancelled)
));
assert!(matches!(
crate::data::SourceRows::new([10, 20]),
Err(Error::Cancelled)
));
assert!(matches!(original.select(&[2, 0, 1]), Err(Error::Cancelled)));
let selected = run(&OperationOptions::default(), || original.select(&[2, 0, 1]))?;
assert!(selected.get(0).flatten().unwrap().is_nan());
assert_eq!(
selected.get(1).flatten().unwrap().to_bits(),
(-0.0_f64).to_bits()
);
assert_eq!(selected.get(2), Some(None));
check()
});
assert!(matches!(result, Err(Error::Cancelled)));
check().unwrap();
}
}