use std::{
cell::{Cell, RefCell},
rc::Rc,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
use crate::{
errors::{BudgetResource, Diagnostic, DiagnosticKind, ErrorContext, 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>,
memory_limit_bytes: Option<u64>,
work_limit: Option<u64>,
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)
.field("memory_limit_bytes", &self.memory_limit_bytes)
.field("work_limit", &self.work_limit)
.finish_non_exhaustive()
}
}
impl OperationOptions {
#[must_use]
pub fn cancellation(mut self, token: impl Into<Option<CancelToken>>) -> Self {
self.cancellation = token.into();
self
}
#[must_use]
pub fn memory_limit_bytes(mut self, bytes: impl Into<Option<u64>>) -> Self {
self.memory_limit_bytes = bytes.into();
self
}
#[must_use]
pub fn work_limit(mut self, units: impl Into<Option<u64>>) -> Self {
self.work_limit = units.into();
self
}
pub fn get_cancellation(&self) -> Option<&CancelToken> {
self.cancellation.as_ref()
}
pub const fn get_memory_limit_bytes(&self) -> Option<u64> {
self.memory_limit_bytes
}
pub const fn get_work_limit(&self) -> Option<u64> {
self.work_limit
}
#[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,
scientific: Cell<bool>,
phase: Cell<OperationPhase>,
retained: Cell<u128>,
scratch: Cell<u128>,
work: Cell<u128>,
}
impl Operation {
fn cancelled(&self) -> Result<()> {
if self
.options
.cancellation
.as_ref()
.is_some_and(CancelToken::is_cancelled)
{
return Err(Error::Cancelled);
}
Ok(())
}
fn budget_error(
&self,
resource: BudgetResource,
required: u128,
limit: u64,
scientific: bool,
) -> Error {
let diagnostic = Diagnostic::new(
DiagnosticKind::BudgetExceeded {
resource,
required,
limit: u128::from(limit),
},
format!("operation {resource:?} requires {required}, exceeding the limit {limit}"),
)
.with_context(ErrorContext::new().with_operation(self.phase.get()));
if scientific || self.scientific.get() {
Error::Data(diagnostic)
} else {
Error::Render(diagnostic)
}
}
fn admit_memory(&self, bytes: u128, temporary: bool) -> Result<()> {
self.cancelled()?;
let Some(limit) = self.options.memory_limit_bytes else {
return Ok(());
};
let required = self
.retained
.get()
.saturating_add(self.scratch.get())
.saturating_add(bytes);
if required > u128::from(limit) {
return Err(self.budget_error(BudgetResource::MemoryBytes, required, limit, false));
}
let counter = if temporary {
&self.scratch
} else {
&self.retained
};
counter.set(counter.get() + bytes);
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> {
run_scoped(options, false, execute)
}
pub(crate) fn run_scientific<T>(
options: &OperationOptions,
execute: impl FnOnce() -> Result<T>,
) -> Result<T> {
run_scoped(options, true, execute)
}
fn run_scoped<T>(
options: &OperationOptions,
scientific: bool,
execute: impl FnOnce() -> Result<T>,
) -> Result<T> {
let current = Rc::new(Operation {
options: options.clone(),
scientific: Cell::new(scientific),
phase: Cell::new(OperationPhase::Check),
retained: Cell::new(0),
scratch: Cell::new(0),
work: Cell::new(0),
});
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) struct ScientificPreparation(Option<(Rc<Operation>, bool)>);
impl Drop for ScientificPreparation {
fn drop(&mut self) {
if let Some((operation, previous)) = &self.0 {
operation.scientific.set(*previous);
}
}
}
pub(crate) fn scientific_preparation() -> ScientificPreparation {
ScientificPreparation(ACTIVE.with_borrow(|active| {
active.as_ref().map(|operation| {
let previous = operation.scientific.replace(true);
(Rc::clone(operation), previous)
})
}))
}
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(())
}
fn admit_work(units: usize, scientific: bool) -> Result<()> {
ACTIVE.with_borrow(|active| {
let Some(active) = active else {
return Ok(());
};
active.cancelled()?;
if let Some(limit) = active.options.work_limit {
let required = active.work.get() + units as u128;
if required > u128::from(limit) {
return Err(active.budget_error(BudgetResource::Work, required, limit, scientific));
}
active.work.set(required);
}
Ok(())
})
}
pub(crate) fn work(units: usize) -> Result<()> {
admit_work(units, false)
}
pub(crate) fn scientific_work(units: usize) -> Result<()> {
admit_work(units, true)
}
pub(crate) fn capacity<T>(capacity: usize, len: usize, additional: usize) -> Result<()> {
check()?;
let required = len
.checked_add(additional)
.ok_or_else(|| Error::Render("operation storage capacity overflow".into()))?;
let growth = required.saturating_sub(capacity) as u128 * std::mem::size_of::<T>() as u128;
memory(growth)
}
pub(crate) fn vector<T>(values: &Vec<T>, additional: usize) -> Result<()> {
capacity::<T>(values.capacity(), values.len(), additional)
}
pub(crate) fn string(value: &String, additional: usize) -> Result<()> {
capacity::<u8>(value.capacity(), value.len(), additional)
}
pub(crate) fn memory(bytes: u128) -> Result<()> {
ACTIVE.with_borrow(|active| {
active
.as_ref()
.map_or(Ok(()), |active| active.admit_memory(bytes, false))
})
}
pub(crate) struct Scratch {
operation: Option<Rc<Operation>>,
bytes: u128,
}
impl Drop for Scratch {
fn drop(&mut self) {
if let Some(active) = &self.operation {
active.scratch.set(active.scratch.get() - self.bytes);
}
}
}
pub(crate) fn scratch(bytes: u128) -> Result<Scratch> {
let operation = ACTIVE.with_borrow(|active| {
active
.as_ref()
.filter(|active| active.options.memory_limit_bytes.is_some())
.cloned()
});
check()?;
if let Some(active) = &operation {
active.admit_memory(bytes, true)?;
}
Ok(Scratch { operation, bytes })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn owning_scientific_columns_admit_their_real_storage() {
let options = OperationOptions::default().memory_limit_bytes(0);
let categorical = run_scientific(&options, || {
crate::CategoryValues::new("category", ["A", "B"])
});
let rows = run_scientific(&options, || crate::data::SourceRows::new([10, 20]));
for error in [categorical.unwrap_err(), rows.unwrap_err()] {
let Error::Data(diagnostic) = error else {
panic!("scientific storage must report a data error");
};
assert!(matches!(diagnostic.kind(),
DiagnosticKind::BudgetExceeded { resource: BudgetResource::MemoryBytes, required, limit: 0 }
if *required > 0));
}
let original = crate::NumericValues::nullable("v", [Some(-0.), None, Some(f64::NAN)]);
let selected = original.select(&[2, 0, 1]).unwrap();
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));
}
#[test]
fn direct_terminal_consumes_one_shared_render_and_write_budget() {
let plot = crate::Plot::scatter(
crate::NumericValues::new("x", [0., 1., 2.]),
crate::NumericValues::new("y", [1., 0., 2.]),
)
.size(800, 600);
let work = run(&OperationOptions::default().work_limit(u64::MAX), || {
crate::orchestrator::render_scene(crate::orchestrator::root::RootSource::Plot(
plot.description(),
))?;
Ok(ACTIVE.with_borrow(|active| active.as_ref().unwrap().work.get()))
})
.unwrap();
let exact = OperationOptions::default().work_limit(u64::try_from(work).unwrap());
plot.render_with_operation(&exact).unwrap();
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("existing.svg");
std::fs::write(&path, b"old").unwrap();
let Err(Error::Render(diagnostic)) = plot.svg_preserve_text_with_operation(&path, &exact)
else {
panic!("direct terminal must not reset the render budget for publication");
};
assert!(matches!(diagnostic.kind(),
DiagnosticKind::BudgetExceeded { resource: BudgetResource::Work, required, limit }
if *required == work + 1 && *limit == work));
assert_eq!(
diagnostic.context().operation(),
Some(OperationPhase::Write)
);
assert_eq!(std::fs::read(&path).unwrap(), b"old");
assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);
}
}