Files
prometeu-runtime/crates/console/prometeu-vm/src/string_ledger.rs
T

207 lines
7.6 KiB
Rust

//! Allocation-identity accounting over ordinary Arc<str> values.
//! The ledger never owns string content strongly. Native owners retain an
//! explicit provenance lease; guest slots remain Arc<str>, with no drop wrapper.
use crate::resource_budget::{
BudgetVec, Reservation, ResourceFailure, ResourceReason, RuntimeBudget, RuntimeResource as Q,
};
use prometeu_bytecode::Value;
use std::sync::{Arc, Mutex, MutexGuard, Weak};
#[derive(Debug)]
struct Entry {
content: Weak<str>,
_bytes: Reservation,
_allocation: Reservation,
}
#[derive(Debug)]
struct Domain {
budget: RuntimeBudget,
entries: BudgetVec<Entry>,
_state: Reservation,
}
#[derive(Debug, Clone)]
pub(crate) struct StringLedger(Arc<Mutex<Domain>>);
/// Host/tool retention must retain provenance along with the Arc. This is
/// boundary metadata, never a replacement for Value::String/StringSlot.
#[derive(Debug, Clone)]
pub(crate) struct StringLease {
content: Arc<str>,
domain: StringLedger,
}
impl StringLease {
pub(crate) fn content(&self) -> &Arc<str> {
&self.content
}
pub(crate) fn domain(&self) -> &StringLedger {
&self.domain
}
}
impl StringLedger {
pub(crate) fn new(budget: RuntimeBudget) -> Result<Self, ResourceFailure> {
let state = budget.reserve(
Q::AuxiliaryBytes,
budget.bytes::<Mutex<Domain>>(1, Q::AuxiliaryBytes)? + 2 * size_of::<usize>() as u64,
)?;
let entries = BudgetVec::new(&budget, Q::AuxiliaryBytes);
Ok(Self(Arc::new(Mutex::new(Domain { budget, entries, _state: state }))))
}
fn domain(&self) -> MutexGuard<'_, Domain> {
self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// Safepoint reconciliation is bounded by the accepted allocation count.
/// Retain compacts in place; unused capacity remains charged until drop.
pub(crate) fn reconcile(&self) -> usize {
self.domain().reconcile()
}
pub(crate) fn tracked_allocations(&self) -> usize {
self.domain().entries.len()
}
pub(crate) fn retains(&self, content: &Arc<str>) -> bool {
let address = Arc::as_ptr(content);
self.domain().entries.iter().any(|entry| std::ptr::eq(entry.content.as_ptr(), address))
}
pub(crate) fn lease(&self, content: &Arc<str>) -> Option<StringLease> {
self.retains(content)
.then(|| StringLease { content: content.clone(), domain: self.clone() })
}
/// Imports always materialize a distinct allocation in the destination
/// domain. Assignment/call/storage of existing guest Arcs uses Arc::clone.
pub(crate) fn import(&self, text: &str) -> Result<Arc<str>, ResourceFailure> {
let mut domain = self.domain();
let charges = domain.prepare(text.len())?;
// Rust's stable Arc allocation can abort on physical allocator failure;
// quotas and fallible ledger/buffer growth are checked before this call.
let content: Arc<str> = Arc::from(text);
domain.publish(&content, charges);
Ok(content)
}
pub(crate) fn concat(&self, left: &str, right: &str) -> Result<Arc<str>, ResourceFailure> {
let mut domain = self.domain();
let len = left.len().checked_add(right.len()).ok_or_else(|| {
domain.budget.failure(Q::StringBytes, ResourceReason::SizeOverflow, u64::MAX)
})?;
let charges = domain.prepare(len)?;
// The temporary buffer and eventual content coexist. Its actual
// capacity is accounted independently, not hidden by the final length.
let mut buffer = BudgetVec::<u8>::new(&domain.budget, Q::TemporaryBytes);
buffer.reserve(len)?;
buffer.extend_from_slice(left.as_bytes())?;
buffer.extend_from_slice(right.as_bytes())?;
let text = std::str::from_utf8(&buffer).expect("concatenating UTF-8 preserves validity");
let content: Arc<str> = Arc::from(text);
domain.publish(&content, charges);
Ok(content)
}
pub(crate) fn format(&self, value: &Value) -> Result<Arc<str>, ResourceFailure> {
self.format_values(&[value])
}
pub(crate) fn concat_values(
&self,
left: &Value,
right: &Value,
) -> Result<Arc<str>, ResourceFailure> {
self.format_values(&[left, right])
}
fn format_values(&self, values: &[&Value]) -> Result<Arc<str>, ResourceFailure> {
let mut domain = self.domain();
let mut counter = SizeCounter(0);
for value in values {
value.write_text(&mut counter).map_err(|_| {
domain.budget.failure(Q::StringBytes, ResourceReason::SizeOverflow, u64::MAX)
})?;
}
let charges = domain.prepare(counter.0)?;
let mut writer =
TextBuffer { bytes: BudgetVec::new(&domain.budget, Q::TemporaryBytes), failure: None };
writer.bytes.reserve(counter.0)?;
for value in values {
if value.write_text(&mut writer).is_err() {
return Err(writer.failure.expect("bounded writer records its resource failure"));
}
}
let text = std::str::from_utf8(&writer.bytes).expect("Value text is UTF-8");
let content: Arc<str> = Arc::from(text);
domain.publish(&content, charges);
Ok(content)
}
}
struct SizeCounter(usize);
impl std::fmt::Write for SizeCounter {
fn write_str(&mut self, text: &str) -> std::fmt::Result {
self.0 = self.0.checked_add(text.len()).ok_or(std::fmt::Error)?;
Ok(())
}
}
struct TextBuffer {
bytes: BudgetVec<u8>,
failure: Option<ResourceFailure>,
}
impl std::fmt::Write for TextBuffer {
fn write_str(&mut self, text: &str) -> std::fmt::Result {
self.bytes.extend_from_slice(text.as_bytes()).map_err(|failure| {
self.failure = Some(failure);
std::fmt::Error
})
}
}
struct Charges {
bytes: Reservation,
allocation: Reservation,
}
impl Domain {
fn reconcile(&mut self) -> usize {
let before = self.entries.len();
self.entries.retain(|entry| entry.content.strong_count() != 0);
before - self.entries.len()
}
fn reserve_content(&self, len: u64) -> Result<Charges, ResourceFailure> {
let bytes = self.budget.reserve(Q::StringBytes, len)?;
let allocation = self.budget.reserve(Q::StringAllocations, 1)?;
Ok(Charges { bytes, allocation })
}
fn prepare(&mut self, len: usize) -> Result<Charges, ResourceFailure> {
let len = u64::try_from(len).map_err(|_| {
self.budget.failure(Q::StringBytes, ResourceReason::SizeOverflow, u64::MAX)
})?;
self.budget.check(Q::IndividualStringBytes, len)?;
let charges = match self.reserve_content(len) {
Ok(charges) => charges,
Err(failure) if failure.reason == ResourceReason::Limit => {
// One bounded pressure pass; never remove a live allocation.
self.reconcile();
self.reserve_content(len)?
}
Err(failure) => return Err(failure),
};
if let Err(failure) = self.entries.reserve(1) {
if failure.reason != ResourceReason::Limit {
return Err(failure);
}
self.reconcile();
self.entries.reserve(1)?;
}
Ok(charges)
}
fn publish(&mut self, content: &Arc<str>, charges: Charges) {
self.entries
.push(Entry {
content: Arc::downgrade(content),
_bytes: charges.bytes,
_allocation: charges.allocation,
})
.expect("prepare reserved one ledger record before materialization");
}
}
#[cfg(test)]
mod tests;