#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ResourceKind {
OutputBytes,
MetadataBytes,
WorkingBytes,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
#[error("{resource:?} requires {required} bytes; limit is {limit}")]
pub struct LimitExceeded {
pub resource: ResourceKind,
pub limit: usize,
pub required: usize,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MemoryLimits {
output: usize,
metadata: usize,
working: usize,
}
impl Default for MemoryLimits {
fn default() -> Self {
Self {
output: 512 * 1024 * 1024,
metadata: 512 * 1024 * 1024,
working: 512 * 1024 * 1024,
}
}
}
impl MemoryLimits {
pub fn new() -> Self {
Self::default()
}
pub fn max_output_bytes(mut self, bytes: usize) -> Self {
self.output = bytes;
self
}
pub fn max_metadata_bytes(mut self, bytes: usize) -> Self {
self.metadata = bytes;
self
}
pub fn max_working_bytes(mut self, bytes: usize) -> Self {
self.working = bytes;
self
}
pub fn output_bytes(self) -> usize {
self.output
}
pub fn metadata_bytes(self) -> usize {
self.metadata
}
pub fn working_bytes(self) -> usize {
self.working
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ResourceEstimate {
output: usize,
metadata: usize,
working: usize,
}
impl ResourceEstimate {
pub(crate) fn new(output: usize, metadata: usize, working: usize) -> Self {
Self {
output,
metadata,
working,
}
}
pub fn output_bytes(self) -> usize {
self.output
}
pub fn metadata_bytes(self) -> usize {
self.metadata
}
pub fn working_bytes(self) -> usize {
self.working
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkLedger {
limit: u128,
used: u128,
}
impl WorkLedger {
pub const DEFAULT_PROCESSING_LIMIT: u128 = 40_000_000_000;
pub fn new(limit: u128) -> Self {
Self { limit, used: 0 }
}
pub fn processing_default() -> Self {
Self::new(Self::DEFAULT_PROCESSING_LIMIT)
}
pub fn used(&self) -> u128 {
self.used
}
pub fn limit(&self) -> u128 {
self.limit
}
pub(crate) fn charge(&mut self, units: u128) -> Result<(), ResourceError> {
let used = self
.used
.checked_add(units)
.ok_or(ResourceError::SizeOverflow)?;
if used > self.limit {
return Err(ResourceError::WorkLimit);
}
self.used = used;
Ok(())
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ResourceError {
SizeOverflow,
WorkLimit,
}