use std::collections::BTreeMap;
use std::fmt;
use std::sync::{Arc, Mutex, MutexGuard};
use datumesh_core::{Args, Cell, FunctionDescriptor, Scalar};
use crate::error::EvalError;
pub trait Runtime: Send + Sync {
fn lang(&self) -> &str;
fn evaluate(
&self,
descriptor: &FunctionDescriptor,
cell: &Cell,
inputs: &mut dyn Inputs,
budget: &mut Budget,
) -> Result<Scalar, EvalError>;
fn asof_dependent(&self, descriptor: &FunctionDescriptor) -> bool {
let _ = descriptor;
false
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Input {
pub value: Scalar,
pub receipt_hash: String,
pub tx: String,
pub asof: String,
}
impl Input {
pub fn new(
value: Scalar,
receipt_hash: impl Into<String>,
tx: impl Into<String>,
asof: impl Into<String>,
) -> Input {
Input { value, receipt_hash: receipt_hash.into(), tx: tx.into(), asof: asof.into() }
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Member {
pub args: Args,
pub input: Input,
}
impl Member {
pub fn new(args: Args, input: Input) -> Member {
Member { args, input }
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Pattern {
Value(Scalar),
Open,
Range {
lo: Scalar,
hi: Scalar,
},
}
pub type SlicePattern = BTreeMap<String, Pattern>;
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct FnBinding {
pub fn_hash: String,
pub start: String,
pub descriptor: Arc<FunctionDescriptor>,
}
impl FnBinding {
pub fn new(fn_hash: impl Into<String>, start: impl Into<String>, descriptor: Arc<FunctionDescriptor>) -> FnBinding {
FnBinding { fn_hash: fn_hash.into(), start: start.into(), descriptor }
}
}
pub trait Inputs {
fn read(&mut self, fn_name: &str, args: &Args) -> Result<Scalar, EvalError>;
fn read_cell(&mut self, fn_name: &str, args: &Args) -> Result<Input, EvalError>;
fn read_asof(&mut self, fn_name: &str, args: &Args, t: &str) -> Result<Input, EvalError>;
fn read_slice(&mut self, fn_name: &str, pattern: &SlicePattern) -> Result<Vec<Member>, EvalError>;
fn read_versions(&mut self, fn_name: &str, args: &Args, from: &str, to: &str) -> Result<Vec<Input>, EvalError>;
fn read_pinned(&mut self, fn_name: &str, fn_hash: &str, args: &Args) -> Result<Input, EvalError> {
let _ = (fn_name, fn_hash, args);
Err(EvalError::Runtime("these inputs offer no pinned reads".into()))
}
fn binding(&mut self, fn_name: &str, at: Option<&str>) -> Result<Option<FnBinding>, EvalError>;
fn asof(&mut self) -> String;
fn binding_peek(&mut self, fn_name: &str, at: Option<&str>) -> Result<Option<FnBinding>, EvalError> {
self.binding(fn_name, at)
}
fn read_blob(&mut self, sha256: &str, length: u64) -> Result<Vec<u8>, EvalError> {
let _ = length;
Err(EvalError::BlobUnavailable {
sha256: sha256.to_string(),
reason: "these inputs offer no blob content".into(),
})
}
fn asof_compare(&mut self, t: &str) -> Result<std::cmp::Ordering, EvalError> {
datumesh_core::lexical::check_instant(t, "$.t").map_err(EvalError::InvalidInput)?;
Ok(t.cmp(self.asof().as_str()))
}
}
pub struct Budget {
meter: Arc<Mutex<Meter>>,
}
#[derive(Debug)]
pub(crate) struct Meter {
limit: u64,
work_limit: u64,
committed: u64,
pending: u64,
attempt: u64,
floor: u64,
work: u64,
pub(crate) exhausted: Exhausted,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Exhausted {
No,
Fuel,
Work,
}
impl Meter {
fn bound(&self) -> u64 {
self.committed.saturating_add(self.pending).saturating_add(self.attempt.max(self.floor))
}
}
impl Budget {
pub fn new(fuel: u64) -> Budget {
Budget::with_work(fuel, u64::MAX)
}
pub(crate) fn with_work(fuel: u64, work_limit: u64) -> Budget {
Budget {
meter: Arc::new(Mutex::new(Meter {
limit: fuel,
work_limit,
committed: 0,
pending: 0,
attempt: 0,
floor: 0,
work: 0,
exhausted: Exhausted::No,
})),
}
}
fn lock(&self) -> MutexGuard<'_, Meter> {
self.meter.lock().unwrap_or_else(|p| p.into_inner())
}
pub fn charge(&mut self, steps: u64) -> Result<(), EvalError> {
self.charge_shared(steps)
}
pub fn used(&self) -> u64 {
self.lock().attempt
}
pub fn remaining(&self) -> u64 {
let m = self.lock();
if m.exhausted != Exhausted::No {
return 0;
}
m.limit.saturating_sub(m.bound())
}
pub fn limit(&self) -> u64 {
self.lock().limit
}
pub fn is_exhausted(&self) -> bool {
self.lock().exhausted != Exhausted::No
}
pub(crate) fn exhausted(&self) -> Exhausted {
self.lock().exhausted
}
pub(crate) fn work_limit(&self) -> u64 {
self.lock().work_limit
}
pub(crate) fn share(&self) -> Budget {
Budget { meter: Arc::clone(&self.meter) }
}
pub(crate) fn charge_shared(&self, steps: u64) -> Result<(), EvalError> {
let mut m = self.lock();
if m.exhausted != Exhausted::No {
return Err(EvalError::BudgetExceeded { fuel: m.limit });
}
m.work = m.work.saturating_add(steps);
m.attempt = m.attempt.saturating_add(steps);
if m.bound() > m.limit {
m.exhausted = Exhausted::Fuel;
return Err(EvalError::BudgetExceeded { fuel: m.limit });
}
if m.work > m.work_limit {
m.exhausted = Exhausted::Work;
return Err(EvalError::BudgetExceeded { fuel: m.limit });
}
Ok(())
}
pub(crate) fn work(&self, steps: u64) -> Result<(), EvalError> {
let mut m = self.lock();
if m.exhausted != Exhausted::No {
return Err(EvalError::BudgetExceeded { fuel: m.limit });
}
m.work = m.work.saturating_add(steps);
if m.work > m.work_limit {
m.exhausted = Exhausted::Work;
return Err(EvalError::BudgetExceeded { fuel: m.limit });
}
Ok(())
}
pub(crate) fn begin_attempt(&self, floor: u64) {
let mut m = self.lock();
m.pending = m.pending.saturating_sub(floor);
m.attempt = 0;
m.floor = floor;
}
pub(crate) fn suspend_attempt(&self) -> u64 {
let mut m = self.lock();
let floor = m.attempt.max(m.floor);
m.pending = m.pending.saturating_add(floor);
m.attempt = 0;
m.floor = 0;
floor
}
pub(crate) fn release(&self, floor: u64) {
let mut m = self.lock();
m.pending = m.pending.saturating_sub(floor);
}
pub(crate) fn finish_attempt(&self) -> u64 {
let mut m = self.lock();
let used = m.attempt;
m.committed = m.committed.saturating_add(used);
m.attempt = 0;
m.floor = 0;
used
}
}
impl fmt::Debug for Budget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let m = self.lock();
f.debug_struct("Budget")
.field("limit", &m.limit)
.field("used", &m.attempt)
.field("committed", &m.committed)
.field("exhausted", &(m.exhausted != Exhausted::No))
.finish()
}
}