Skip to main content

lichtung_plot/
operation.rs

1//! Per-call cancellation and operation phases.
2
3use std::{
4    cell::{Cell, RefCell},
5    rc::Rc,
6    sync::{
7        atomic::{AtomicBool, Ordering},
8        Arc,
9    },
10};
11
12use crate::{errors::OperationPhase, Error, Result};
13
14/// A shared, single-use cancellation flag.
15///
16/// Clones observe the same flag across threads. Cancelling an operation does
17/// not alter its input declaration or a previously completed output.
18#[derive(Debug, Clone, Default)]
19pub struct CancelToken(Arc<AtomicBool>);
20
21impl CancelToken {
22    /// Create an uncancelled token.
23    pub fn new() -> Self {
24        Self::default()
25    }
26
27    /// Permanently request cancellation.
28    pub fn cancel(&self) {
29        self.0.store(true, Ordering::Release);
30    }
31
32    /// Whether cancellation has been requested.
33    pub fn is_cancelled(&self) -> bool {
34        self.0.load(Ordering::Acquire)
35    }
36}
37
38type InterruptCheck = dyn Fn(OperationPhase) -> Result<()> + Send + Sync;
39
40/// Options for one synchronous native operation.
41///
42/// Cancellation and host interrupt checks apply to the whole request,
43/// including preparation and publication for a direct file terminal.
44#[derive(Clone, Default)]
45pub struct OperationOptions {
46    cancellation: Option<CancelToken>,
47    interrupt_check: Option<Arc<InterruptCheck>>,
48}
49
50impl std::fmt::Debug for OperationOptions {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.debug_struct("OperationOptions")
53            .field("cancellation", &self.cancellation)
54            .finish_non_exhaustive()
55    }
56}
57
58impl OperationOptions {
59    /// Request cancellation using the supplied shared token.
60    #[must_use]
61    pub fn cancellation(mut self, token: impl Into<Option<CancelToken>>) -> Self {
62        self.cancellation = token.into();
63        self
64    }
65
66    /// Borrow the configured cancellation token.
67    pub fn get_cancellation(&self) -> Option<&CancelToken> {
68        self.cancellation.as_ref()
69    }
70
71    /// Host-language interrupt integration. Called only at checkpoints on the
72    /// initiating thread, outside renderer locks and before publication.
73    #[doc(hidden)]
74    #[must_use]
75    pub fn with_interrupt_check(
76        mut self,
77        check: impl Fn(OperationPhase) -> Result<()> + Send + Sync + 'static,
78    ) -> Self {
79        self.interrupt_check = Some(Arc::new(check));
80        self
81    }
82}
83
84struct Operation {
85    options: OperationOptions,
86    phase: Cell<OperationPhase>,
87}
88
89impl Operation {
90    fn cancelled(&self) -> Result<()> {
91        if self
92            .options
93            .cancellation
94            .as_ref()
95            .is_some_and(CancelToken::is_cancelled)
96        {
97            return Err(Error::Cancelled);
98        }
99        Ok(())
100    }
101}
102
103thread_local! {
104    // All current native prepare/replay/encode stages are synchronous and run
105    // on the initiating thread. Even a default nested public operation installs
106    // a fresh scope, rather than borrowing its caller's cancellation.
107    static ACTIVE: RefCell<Option<Rc<Operation>>> = const { RefCell::new(None) };
108}
109
110struct Scope(Option<Rc<Operation>>);
111
112impl Drop for Scope {
113    fn drop(&mut self) {
114        // Dropping an application-owned interrupt closure must happen outside
115        // the TLS borrow.
116        let previous = ACTIVE.with(|active| active.replace(self.0.take()));
117        drop(previous);
118    }
119}
120
121pub(crate) fn run<T>(options: &OperationOptions, execute: impl FnOnce() -> Result<T>) -> Result<T> {
122    let current = Rc::new(Operation {
123        options: options.clone(),
124        phase: Cell::new(OperationPhase::Check),
125    });
126    let _scope = Scope(ACTIVE.with(|active| active.replace(Some(current))));
127    checkpoint()?;
128    execute()
129}
130
131pub(crate) fn current_phase() -> Option<OperationPhase> {
132    ACTIVE.with_borrow(|active| active.as_ref().map(|active| active.phase.get()))
133}
134
135/// Application callbacks may start independent operations or edit a declaration.
136pub(crate) fn external<T>(call: impl FnOnce() -> T) -> T {
137    let _scope = Scope(ACTIVE.with(|active| active.replace(None)));
138    call()
139}
140
141pub(crate) fn phase(phase: OperationPhase) -> Result<()> {
142    ACTIVE.with_borrow(|active| {
143        if let Some(active) = active {
144            active.phase.set(phase);
145        }
146    });
147    checkpoint()
148}
149
150/// Check only the native flag. Safe while a preparation resource is locked.
151pub(crate) fn check() -> Result<()> {
152    ACTIVE.with_borrow(|active| active.as_ref().map_or(Ok(()), |active| active.cancelled()))
153}
154
155/// A lock-free application interrupt boundary. Never borrow TLS across the hook.
156pub(crate) fn checkpoint() -> Result<()> {
157    let active = ACTIVE.with_borrow(Clone::clone);
158    if let Some(active) = active {
159        active.cancelled()?;
160        if let Some(check) = &active.options.interrupt_check {
161            external(|| check(active.phase.get()))?;
162        }
163        active.cancelled()?;
164    }
165    Ok(())
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    #[test]
173    fn source_selection_observes_cancellation_and_independent_scopes() {
174        let original = crate::NumericValues::nullable("v", [Some(-0.), None, Some(f64::NAN)]);
175        let token = CancelToken::new();
176        let options = OperationOptions::default().cancellation(token.clone());
177        let result = run(&options, || {
178            token.cancel();
179            assert!(matches!(
180                crate::CategoryValues::new("category", ["A", "B"]),
181                Err(Error::Cancelled)
182            ));
183            assert!(matches!(
184                crate::data::SourceRows::new([10, 20]),
185                Err(Error::Cancelled)
186            ));
187            assert!(matches!(original.select(&[2, 0, 1]), Err(Error::Cancelled)));
188
189            let selected = run(&OperationOptions::default(), || original.select(&[2, 0, 1]))?;
190            assert!(selected.get(0).flatten().unwrap().is_nan());
191            assert_eq!(
192                selected.get(1).flatten().unwrap().to_bits(),
193                (-0.0_f64).to_bits()
194            );
195            assert_eq!(selected.get(2), Some(None));
196            check()
197        });
198        assert!(matches!(result, Err(Error::Cancelled)));
199        check().unwrap();
200    }
201}