use std::{
collections::BTreeMap,
io,
path::{Path, PathBuf},
sync::{Mutex, OnceLock},
};
struct Budget {
used: u64,
max: u64,
}
static BUDGETS: OnceLock<Mutex<BTreeMap<PathBuf, Budget>>> = OnceLock::new();
pub(crate) struct CaptureBudget {
root: PathBuf,
}
impl CaptureBudget {
pub(crate) fn new(root: &Path, max: u64) -> io::Result<Self> {
let used = super::bytes(root)?;
if used > max {
return Err(io::Error::other(
"workspace already exceeds its capture budget",
));
}
BUDGETS
.get_or_init(Default::default)
.lock()
.unwrap()
.insert(root.into(), Budget { used, max });
Ok(Self { root: root.into() })
}
}
impl Drop for CaptureBudget {
fn drop(&mut self) {
BUDGETS
.get_or_init(Default::default)
.lock()
.unwrap()
.remove(&self.root);
}
}
pub(crate) fn reserve_copy(path: &Path, bytes: u64) -> io::Result<()> {
let mut budgets = BUDGETS.get_or_init(Default::default).lock().unwrap();
if let Some((_, budget)) = budgets
.iter_mut()
.filter(|(root, _)| path.starts_with(root))
.max_by_key(|(root, _)| root.components().count())
{
let existing = path.metadata().map_or(0, |m| m.len());
let next = budget
.used
.saturating_sub(existing)
.checked_add(bytes)
.ok_or_else(|| io::Error::other("capture size overflow"))?;
if next > budget.max {
return Err(io::Error::other(
"captured executable, software or input tree exceeds runtime.workspace.max_bytes; stream large named inputs or increase the explicit budget",
));
}
budget.used = next;
}
Ok(())
}