lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Per-call cancellation and operation phases.

use std::{
    cell::{Cell, RefCell},
    rc::Rc,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
};

use crate::{errors::OperationPhase, Error, Result};

/// A shared, single-use cancellation flag.
///
/// Clones observe the same flag across threads. Cancelling an operation does
/// not alter its input declaration or a previously completed output.
#[derive(Debug, Clone, Default)]
pub struct CancelToken(Arc<AtomicBool>);

impl CancelToken {
    /// Create an uncancelled token.
    pub fn new() -> Self {
        Self::default()
    }

    /// Permanently request cancellation.
    pub fn cancel(&self) {
        self.0.store(true, Ordering::Release);
    }

    /// Whether cancellation has been requested.
    pub fn is_cancelled(&self) -> bool {
        self.0.load(Ordering::Acquire)
    }
}

type InterruptCheck = dyn Fn(OperationPhase) -> Result<()> + Send + Sync;

/// Options for one synchronous native operation.
///
/// Cancellation and host interrupt checks apply to the whole request,
/// including preparation and publication for a direct file terminal.
#[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 {
    /// Request cancellation using the supplied shared token.
    #[must_use]
    pub fn cancellation(mut self, token: impl Into<Option<CancelToken>>) -> Self {
        self.cancellation = token.into();
        self
    }

    /// Borrow the configured cancellation token.
    pub fn get_cancellation(&self) -> Option<&CancelToken> {
        self.cancellation.as_ref()
    }

    /// Host-language interrupt integration. Called only at checkpoints on the
    /// initiating thread, outside renderer locks and before publication.
    #[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! {
    // All current native prepare/replay/encode stages are synchronous and run
    // on the initiating thread. Even a default nested public operation installs
    // a fresh scope, rather than borrowing its caller's cancellation.
    static ACTIVE: RefCell<Option<Rc<Operation>>> = const { RefCell::new(None) };
}

struct Scope(Option<Rc<Operation>>);

impl Drop for Scope {
    fn drop(&mut self) {
        // Dropping an application-owned interrupt closure must happen outside
        // the TLS borrow.
        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()))
}

/// Application callbacks may start independent operations or edit a declaration.
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()
}

/// Check only the native flag. Safe while a preparation resource is locked.
pub(crate) fn check() -> Result<()> {
    ACTIVE.with_borrow(|active| active.as_ref().map_or(Ok(()), |active| active.cancelled()))
}

/// A lock-free application interrupt boundary. Never borrow TLS across the hook.
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();
    }
}