use crate::resource::WorkLedger;
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
#[derive(Clone, Debug, Default)]
pub struct CancellationToken(Arc<AtomicBool>);
impl CancellationToken {
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)
}
pub fn check(&self) -> Result<(), ExecutionError> {
if self.is_cancelled() {
Err(ExecutionError::Cancelled)
} else {
Ok(())
}
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ExecutionStage {
Preflight,
Processing,
AutoPhase,
NoiseEstimation,
Reconstruction,
Replay,
Reading,
Access,
Plot,
Snapshot,
Report,
Export,
Digest,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ProgressTotal {
Exact(u128),
UpperBound(u128),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ProgressEvent {
pub stage: ExecutionStage,
pub step_index: Option<usize>,
pub completed: u128,
pub total: Option<ProgressTotal>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub enum ExecutionError {
#[error("execution cancelled")]
Cancelled,
#[error("execution work budget exhausted")]
WorkLimit,
#[error("execution resource counter overflow")]
SizeOverflow,
}
enum Ledger<'a> {
Borrowed(&'a mut WorkLedger),
Owned(WorkLedger),
}
pub struct ExecutionContext<'a> {
ledger: Ledger<'a>,
cancellation: CancellationToken,
progress: Option<&'a mut dyn FnMut(ProgressEvent)>,
event: ProgressEvent,
io_bytes: u128,
peak_payload_bytes: usize,
pending_work: u128,
}
impl Default for ExecutionContext<'_> {
fn default() -> Self {
Self {
ledger: Ledger::Owned(WorkLedger::processing_default()),
cancellation: CancellationToken::new(),
progress: None,
event: ProgressEvent {
stage: ExecutionStage::Preflight,
step_index: None,
completed: 0,
total: None,
},
io_bytes: 0,
peak_payload_bytes: 0,
pending_work: 0,
}
}
}
impl<'a> ExecutionContext<'a> {
pub fn new(ledger: &'a mut WorkLedger) -> Self {
Self {
ledger: Ledger::Borrowed(ledger),
..Self::default()
}
}
pub fn with_cancellation(mut self, token: CancellationToken) -> Self {
self.cancellation = token;
self
}
pub fn with_progress(mut self, receiver: &'a mut dyn FnMut(ProgressEvent)) -> Self {
self.progress = Some(receiver);
self
}
pub fn cancellation(&self) -> &CancellationToken {
&self.cancellation
}
pub fn ledger(&self) -> &WorkLedger {
match &self.ledger {
Ledger::Borrowed(v) => v,
Ledger::Owned(v) => v,
}
}
pub fn io_bytes(&self) -> u128 {
self.io_bytes
}
pub fn peak_payload_bytes(&self) -> usize {
self.peak_payload_bytes
}
pub fn check_cancelled(&self) -> Result<(), ExecutionError> {
self.cancellation.check()
}
pub(crate) fn ensure_work(&self, units: u128) -> Result<(), ExecutionError> {
self.check_cancelled()?;
if units > self.ledger().limit() - self.ledger().used() {
Err(ExecutionError::WorkLimit)
} else {
Ok(())
}
}
pub(crate) fn charge(&mut self, units: u128) -> Result<(), ExecutionError> {
self.complete_work()?;
self.charge_without_progress(units)?;
self.pending_work = units;
Ok(())
}
pub(crate) fn charge_without_progress(&mut self, units: u128) -> Result<(), ExecutionError> {
self.ensure_work(units)?;
let ledger = match &mut self.ledger {
Ledger::Borrowed(v) => v,
Ledger::Owned(v) => v,
};
ledger.charge(units).map_err(Into::into)
}
pub(crate) fn complete_work(&mut self) -> Result<(), ExecutionError> {
let units = std::mem::take(&mut self.pending_work);
if units == 0 {
return self.check_cancelled();
}
self.advance(units)
}
pub(crate) fn begin(
&mut self,
stage: ExecutionStage,
step_index: Option<usize>,
total: Option<ProgressTotal>,
) -> Result<(), ExecutionError> {
self.check_cancelled()?;
self.pending_work = 0;
self.event = ProgressEvent {
stage,
step_index,
completed: 0,
total,
};
self.emit()
}
pub(crate) fn advance(&mut self, units: u128) -> Result<(), ExecutionError> {
self.check_cancelled()?;
self.event.completed = self
.event
.completed
.checked_add(units)
.ok_or(ExecutionError::SizeOverflow)?;
self.emit()
}
fn emit(&mut self) -> Result<(), ExecutionError> {
if let Some(receiver) = &mut self.progress {
receiver(self.event);
}
self.check_cancelled()
}
pub(crate) fn observe_payload(&mut self, bytes: usize) {
self.peak_payload_bytes = self.peak_payload_bytes.max(bytes);
}
pub(crate) fn io(&mut self, bytes: usize) -> Result<(), ExecutionError> {
self.io_bytes = self
.io_bytes
.checked_add(bytes as u128)
.ok_or(ExecutionError::SizeOverflow)?;
self.advance(bytes as u128)
}
}
impl From<crate::resource::ResourceError> for ExecutionError {
fn from(error: crate::resource::ResourceError) -> Self {
match error {
crate::resource::ResourceError::WorkLimit => Self::WorkLimit,
crate::resource::ResourceError::SizeOverflow => Self::SizeOverflow,
}
}
}