use eyre::{Context, Result};
use mbx_cache_core::{
CacheDigest, CacheDirectory, LocalCas, RemoteActionResult, RustcMetadata, is_task_identity,
task_manifest_actions,
};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
const CAS_DIR: &str = "cas/v1";
const ACTION_RESULTS_DIR: &str = "action-results/v1";
const CHECKOUTS_DIR: &str = "checkouts/v1";
const SWEEP_STAMP: &str = "gc/v1/last-sweep";
const SWEEP_LOCK: &str = "gc/v1/sweep.lock";
const CHECKOUT_RECORD_VERSION: u8 = 1;
const CHECKOUT_RETENTION: Duration = Duration::from_secs(30 * 24 * 60 * 60);
#[derive(Debug, Default, PartialEq, Eq)]
pub struct StoreStats {
pub objects: u64,
pub object_bytes: u64,
pub action_results: u64,
pub action_result_bytes: u64,
pub live_checkouts: u64,
pub stale_checkouts: u64,
}
impl StoreStats {
pub fn total_bytes(&self) -> u64 {
self.object_bytes.saturating_add(self.action_result_bytes)
}
}
#[derive(Debug, Default, PartialEq, Eq)]
pub struct GcOutcome {
pub removed_objects: u64,
pub removed_action_results: u64,
pub removed_checkout_records: u64,
pub removed_bytes: u64,
pub remaining_bytes: u64,
}
#[derive(Debug, PartialEq, Eq)]
pub struct ProjectUsage {
pub workspace_root: PathBuf,
pub identities: u64,
pub action_bytes: u64,
pub target_bytes: u64,
pub live: bool,
}
#[derive(Debug, PartialEq, Eq)]
pub struct LargestEntry {
pub kind: &'static str,
pub path: PathBuf,
pub bytes: u64,
}
#[derive(Debug, Default, PartialEq, Eq)]
pub struct VerifyOutcome {
pub checked_objects: u64,
pub checked_action_results: u64,
pub problems: Vec<PathBuf>,
}
#[derive(Debug, Default, PartialEq, Eq)]
pub struct RemoveProjectOutcome {
pub removed_checkout_records: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct CheckoutRecord {
version: u8,
workspace_root: PathBuf,
target_dir: PathBuf,
updated_secs: u64,
}
pub fn stats(store: &Path) -> Result<StoreStats> {
let objects = walk_files(&store.join(CAS_DIR))?;
let results = walk_files(&store.join(ACTION_RESULTS_DIR))?;
let checkouts = scan_checkouts(store)?;
Ok(StoreStats {
objects: objects.len() as u64,
object_bytes: objects.iter().map(|entry| entry.size).sum(),
action_results: results.len() as u64,
action_result_bytes: results.iter().map(|entry| entry.size).sum(),
live_checkouts: checkouts.live_records,
stale_checkouts: checkouts.stale_records.len() as u64,
})
}
pub fn projects(store: &Path) -> Result<Vec<ProjectUsage>> {
let mut projects: BTreeMap<PathBuf, (BTreeSet<String>, bool, u64)> = BTreeMap::new();
let mut target_sizes = BTreeMap::new();
let root = store.join(CHECKOUTS_DIR);
for identity_entry in read_dir_or_empty(&root)? {
let identity = identity_entry.file_name().to_string_lossy().into_owned();
if !is_task_identity(&identity) || !identity_entry.file_type()?.is_dir() {
continue;
}
for entry in walk_files(&identity_entry.path())? {
let Some(record) = read_checkout_record(&entry.path) else {
continue;
};
let project = projects.entry(record.workspace_root.clone()).or_default();
if claim_is_live(&record) {
project.0.insert(identity.clone());
project.1 = true;
}
project.2 = project
.2
.max(cached_tree_bytes(&mut target_sizes, &record.target_dir));
}
}
let action_cache = mbx_cache_core::LocalActionCache::new(store);
let mut usages = Vec::new();
for (workspace_root, (identities, live, target_bytes)) in projects {
let mut paths = rooted_objects(store, &identities)?;
for identity in &identities {
for action in task_manifest_actions(store, identity).unwrap_or_default() {
if let Ok(path) = action_cache.path_for(&action) {
paths.insert(path);
}
}
}
let action_bytes = paths
.iter()
.filter_map(|path| std::fs::metadata(path).ok())
.map(|metadata| metadata.len())
.sum();
usages.push(ProjectUsage {
workspace_root,
identities: identities.len() as u64,
action_bytes,
target_bytes,
live,
});
}
usages.sort_by(|left, right| {
right
.action_bytes
.saturating_add(right.target_bytes)
.cmp(&left.action_bytes.saturating_add(left.target_bytes))
.then_with(|| left.workspace_root.cmp(&right.workspace_root))
});
Ok(usages)
}
pub fn largest(store: &Path, limit: usize) -> Result<Vec<LargestEntry>> {
let mut entries = Vec::new();
for (kind, root, action_result) in [
("object", store.join(CAS_DIR), false),
("action result", store.join(ACTION_RESULTS_DIR), true),
] {
entries.extend(
walk_files(&root)?
.into_iter()
.filter(|entry| addressed_digest(store, &entry.path, action_result).is_some())
.map(|entry| LargestEntry {
kind,
path: entry.path,
bytes: entry.size,
}),
);
}
entries.sort_by(|left, right| {
right
.bytes
.cmp(&left.bytes)
.then_with(|| left.path.cmp(&right.path))
});
entries.truncate(limit);
Ok(entries)
}
pub fn verify(store: &Path) -> Result<VerifyOutcome> {
let cas = LocalCas::new(store);
let action_cache = mbx_cache_core::LocalActionCache::new(store);
let virtually_removed = HashSet::new();
let mut outcome = VerifyOutcome::default();
for entry in walk_files(&store.join(CAS_DIR))? {
let Some(digest) = addressed_digest(store, &entry.path, false) else {
continue;
};
outcome.checked_objects += 1;
if !matches!(cas.find(&digest), Ok(Some(_))) {
outcome.problems.push(entry.path);
}
}
for entry in walk_files(&store.join(ACTION_RESULTS_DIR))? {
let Some(digest) = addressed_digest(store, &entry.path, true) else {
continue;
};
outcome.checked_action_results += 1;
if !matches!(action_cache.find(&digest), Ok(Some(_)))
|| action_result_is_dangling(&cas, &entry.path, &virtually_removed)?
{
outcome.problems.push(entry.path);
}
}
outcome.problems.sort();
Ok(outcome)
}
pub fn remove_project(store: &Path, workspace_root: &Path) -> Result<RemoveProjectOutcome> {
let mut outcome = RemoveProjectOutcome::default();
for entry in walk_files(&store.join(CHECKOUTS_DIR))? {
if read_checkout_record(&entry.path)
.is_some_and(|record| record.workspace_root == workspace_root)
{
std::fs::remove_file(&entry.path)?;
outcome.removed_checkout_records += 1;
if let Some(parent) = entry.path.parent() {
let _ = std::fs::remove_dir(parent);
}
}
}
Ok(outcome)
}
pub fn record_checkout(
store: &Path,
identity: &str,
workspace_root: &Path,
target_dir: &Path,
) -> Result<()> {
let record = CheckoutRecord {
version: CHECKOUT_RECORD_VERSION,
workspace_root: workspace_root.to_path_buf(),
target_dir: target_dir.to_path_buf(),
updated_secs: SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|since| since.as_secs())
.unwrap_or_default(),
};
let mut contents = serde_json::to_vec(&record)?;
contents.push(b'\n');
crate::util::write_atomic(
&checkout_record_path(store, identity, workspace_root),
&contents,
)
}
fn checkout_record_path(store: &Path, identity: &str, workspace_root: &Path) -> PathBuf {
let key = CacheDigest::blake3(workspace_root.to_string_lossy().as_bytes()).hash;
store
.join(CHECKOUTS_DIR)
.join(identity)
.join(format!("{key}.json"))
}
pub fn gc(store: &Path, max_bytes: u64) -> Result<GcOutcome> {
gc_with_mode(store, max_bytes, false)
}
pub fn gc_dry_run(store: &Path, max_bytes: u64) -> Result<GcOutcome> {
gc_with_mode(store, max_bytes, true)
}
fn gc_with_mode(store: &Path, max_bytes: u64, dry_run: bool) -> Result<GcOutcome> {
let mut objects = walk_files(&store.join(CAS_DIR))?;
let results = walk_files(&store.join(ACTION_RESULTS_DIR))?;
let mut live_bytes = objects
.iter()
.chain(results.iter())
.map(|entry| entry.size)
.sum::<u64>();
let mut outcome = GcOutcome::default();
let checkouts = scan_checkouts(store)?;
for path in &checkouts.stale_records {
if dry_run || matches!(remove(path)?, Removal::Removed) {
outcome.removed_checkout_records += 1;
}
if !dry_run && let Some(parent) = path.parent() {
let _ = std::fs::remove_dir(parent);
}
}
let mut virtually_removed = HashSet::new();
if live_bytes > max_bytes {
let rooted = rooted_objects(store, &checkouts.live_identities)?;
objects.sort_by_cached_key(|entry| (rooted.contains(&entry.path), entry.used));
let evicted = evict_objects(&objects, &rooted, live_bytes, max_bytes, |path| {
if dry_run {
virtually_removed.insert(path.to_path_buf());
Ok(Removal::Removed)
} else {
remove(path)
}
})?;
live_bytes = evicted.remaining_bytes;
outcome.removed_objects += evicted.removed_objects;
outcome.removed_bytes += evicted.removed_bytes;
}
let cas = LocalCas::new(store);
for entry in &results {
if action_result_is_dangling(&cas, &entry.path, &virtually_removed)? {
match if dry_run {
Removal::Removed
} else {
remove(&entry.path)?
} {
Removal::Removed => {
live_bytes = live_bytes.saturating_sub(entry.size);
outcome.removed_action_results += 1;
outcome.removed_bytes += entry.size;
}
Removal::Missing => live_bytes = live_bytes.saturating_sub(entry.size),
Removal::Blocked => {}
}
}
}
outcome.remaining_bytes = live_bytes;
Ok(outcome)
}
pub fn sweep_if_due(store: &Path, max_bytes: u64, interval: Duration) -> Result<Option<GcOutcome>> {
if !claim_sweep(store, interval)? {
return Ok(None);
}
gc(store, max_bytes).map(Some)
}
pub(crate) fn claim_sweep(store: &Path, interval: Duration) -> Result<bool> {
let lock_path = store.join(SWEEP_LOCK);
std::fs::create_dir_all(lock_path.parent().expect("sweep lock has a parent"))?;
let mut lock = fslock::LockFile::open(&lock_path)?;
lock.lock()?;
let stamp = store.join(SWEEP_STAMP);
if let Ok(metadata) = std::fs::metadata(&stamp)
&& let Ok(modified) = metadata.modified()
&& let Ok(since) = modified.elapsed()
&& since < interval
{
return Ok(false);
}
crate::util::write_atomic(&stamp, b"")?;
Ok(true)
}
struct CheckoutScan {
live_identities: BTreeSet<String>,
live_records: u64,
stale_records: Vec<PathBuf>,
}
fn scan_checkouts(store: &Path) -> Result<CheckoutScan> {
let root = store.join(CHECKOUTS_DIR);
let mut scan = CheckoutScan {
live_identities: BTreeSet::new(),
live_records: 0,
stale_records: Vec::new(),
};
let listing = match std::fs::read_dir(&root) {
Ok(listing) => listing,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(scan),
Err(error) => {
return Err(error).wrap_err_with(|| format!("failed to read {}", root.display()));
}
};
for entry in listing {
let entry = entry?;
let name = entry.file_name().to_string_lossy().into_owned();
if !is_task_identity(&name) || !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
continue;
}
for record in walk_files(&entry.path())? {
match read_checkout_record(&record.path) {
Some(checkout) if claim_is_live(&checkout) => {
scan.live_identities.insert(name.clone());
scan.live_records += 1;
}
Some(_) => scan.stale_records.push(record.path),
None => {}
}
}
}
Ok(scan)
}
fn read_checkout_record(path: &Path) -> Option<CheckoutRecord> {
let bytes = std::fs::read(path).ok()?;
let record = serde_json::from_slice::<CheckoutRecord>(&bytes).ok()?;
(record.version == CHECKOUT_RECORD_VERSION).then_some(record)
}
fn claim_is_live(record: &CheckoutRecord) -> bool {
checkout_is_live(&record.workspace_root) && !claim_has_expired(record)
}
fn claim_has_expired(record: &CheckoutRecord) -> bool {
let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH) else {
return false;
};
now.as_secs()
.saturating_sub(record.updated_secs)
.gt(&CHECKOUT_RETENTION.as_secs())
}
pub(crate) fn checkout_is_live(workspace_root: &Path) -> bool {
if !matches!(workspace_root.try_exists(), Ok(false)) {
return true;
}
match workspace_root.parent() {
Some(parent) => !matches!(parent.try_exists(), Ok(true)),
None => true,
}
}
fn rooted_objects(store: &Path, identities: &BTreeSet<String>) -> Result<HashSet<PathBuf>> {
let cas = LocalCas::new(store);
let mut rooted = HashSet::new();
let mut visited = BTreeSet::new();
for identity in identities {
let actions = match task_manifest_actions(store, identity) {
Ok(actions) => actions,
Err(error) => {
log::debug!("could not read the manifest for {identity}: {error}");
continue;
}
};
for action in actions {
let Some(result) = read_action_result(store, &action) else {
continue;
};
root_digest(&cas, &mut rooted, &result.action);
if let Some(metadata) = &result.metadata {
root_digest(&cas, &mut rooted, metadata);
if let Some(rustc) = read_rustc_metadata(&cas, metadata) {
root_digest(&cas, &mut rooted, &rustc.stdout);
root_digest(&cas, &mut rooted, &rustc.stderr);
}
}
if let Some(output_root) = &result.output_root {
root_digest(&cas, &mut rooted, output_root);
root_tree(&cas, output_root, &mut rooted, &mut visited);
}
}
}
Ok(rooted)
}
fn read_action_result(store: &Path, action: &CacheDigest) -> Option<RemoteActionResult> {
let path = mbx_cache_core::LocalActionCache::new(store)
.path_for(action)
.ok()?;
let bytes = std::fs::read(path).ok()?;
serde_json::from_slice(&bytes).ok()
}
fn root_tree(
cas: &LocalCas,
output_root: &CacheDigest,
rooted: &mut HashSet<PathBuf>,
visited: &mut BTreeSet<CacheDigest>,
) {
let mut pending = vec![output_root.clone()];
while let Some(digest) = pending.pop() {
if !visited.insert(digest.clone()) {
continue;
}
let Some(directory) = read_directory(cas, &digest) else {
continue;
};
for file in &directory.files {
root_digest(cas, rooted, &file.digest);
}
for child in &directory.directories {
root_digest(cas, rooted, &child.digest);
pending.push(child.digest.clone());
}
}
}
fn read_rustc_metadata(cas: &LocalCas, digest: &CacheDigest) -> Option<RustcMetadata> {
let bytes = std::fs::read(cas.path_for(digest).ok()?).ok()?;
serde_json::from_slice(&bytes).ok()
}
fn read_directory(cas: &LocalCas, digest: &CacheDigest) -> Option<CacheDirectory> {
let bytes = std::fs::read(cas.path_for(digest).ok()?).ok()?;
serde_json::from_slice(&bytes).ok()
}
fn root_digest(cas: &LocalCas, rooted: &mut HashSet<PathBuf>, digest: &CacheDigest) {
if let Ok(path) = cas.path_for(digest) {
rooted.insert(path);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Removal {
Removed,
Missing,
Blocked,
}
fn remove(path: &Path) -> Result<Removal> {
match std::fs::remove_file(path) {
Ok(()) => Ok(Removal::Removed),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Removal::Missing),
Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => {
log::debug!("could not evict {}: {error}", path.display());
Ok(Removal::Blocked)
}
Err(error) => Err(error).wrap_err_with(|| format!("failed to evict {}", path.display())),
}
}
#[derive(Debug, Default, PartialEq, Eq)]
struct ObjectEvictions {
removed_objects: u64,
removed_bytes: u64,
remaining_bytes: u64,
}
fn evict_objects(
objects: &[Entry],
rooted: &HashSet<PathBuf>,
mut live_bytes: u64,
max_bytes: u64,
mut remove_file: impl FnMut(&Path) -> Result<Removal>,
) -> Result<ObjectEvictions> {
let mut outcome = ObjectEvictions::default();
let mut blocked_unrooted = false;
for entry in objects {
if live_bytes <= max_bytes {
break;
}
let is_rooted = rooted.contains(&entry.path);
if is_rooted && blocked_unrooted {
break;
}
match remove_file(&entry.path)? {
Removal::Removed => {
live_bytes = live_bytes.saturating_sub(entry.size);
outcome.removed_objects += 1;
outcome.removed_bytes += entry.size;
}
Removal::Missing => live_bytes = live_bytes.saturating_sub(entry.size),
Removal::Blocked if !is_rooted => blocked_unrooted = true,
Removal::Blocked => {}
}
}
outcome.remaining_bytes = live_bytes;
Ok(outcome)
}
fn action_result_is_dangling(
cas: &LocalCas,
path: &Path,
virtually_removed: &HashSet<PathBuf>,
) -> Result<bool> {
let bytes = match std::fs::read(path) {
Ok(bytes) => bytes,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(error) => {
return Err(error).wrap_err_with(|| format!("failed to read {}", path.display()));
}
};
let Ok(result) = serde_json::from_slice::<RemoteActionResult>(&bytes) else {
return Ok(false);
};
for digest in [
Some(&result.action),
result.metadata.as_ref(),
result.output_root.as_ref(),
]
.into_iter()
.flatten()
{
match cas.path_for(digest) {
Ok(path) => {
if virtually_removed.contains(&path) || !path.exists() {
return Ok(true);
}
}
Err(_) => return Ok(true),
}
}
Ok(false)
}
struct Entry {
path: PathBuf,
size: u64,
used: SystemTime,
}
fn walk_files(root: &Path) -> Result<Vec<Entry>> {
let mut entries = Vec::new();
let mut pending = vec![root.to_path_buf()];
while let Some(directory) = pending.pop() {
let listing = match std::fs::read_dir(&directory) {
Ok(listing) => listing,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
Err(error) => {
return Err(error)
.wrap_err_with(|| format!("failed to read {}", directory.display()));
}
};
for entry in listing {
let entry = entry?;
let metadata = match entry.metadata() {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
Err(error) => return Err(error.into()),
};
if metadata.is_dir() {
pending.push(entry.path());
} else if metadata.is_file() {
let used = metadata
.accessed()
.or_else(|_| metadata.modified())
.unwrap_or(SystemTime::UNIX_EPOCH);
entries.push(Entry {
path: entry.path(),
size: metadata.len(),
used,
});
}
}
}
Ok(entries)
}
fn read_dir_or_empty(root: &Path) -> Result<Vec<std::fs::DirEntry>> {
match std::fs::read_dir(root) {
Ok(entries) => entries
.collect::<std::io::Result<Vec<_>>>()
.map_err(Into::into),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
Err(error) => Err(error).wrap_err_with(|| format!("failed to read {}", root.display())),
}
}
fn digest_from_path(path: &Path, action_result: bool) -> Option<CacheDigest> {
let name = path.file_name()?.to_str()?;
let name = if action_result {
name.strip_suffix(".json")?
} else {
name
};
let (hash, size) = name.rsplit_once('-')?;
let algorithm = path.parent()?.parent()?.file_name()?.to_str()?.to_string();
let digest = CacheDigest {
algorithm,
hash: hash.to_string(),
size: size.parse().ok()?,
};
digest.validate().ok()?;
Some(digest)
}
fn addressed_digest(store: &Path, path: &Path, action_result: bool) -> Option<CacheDigest> {
let digest = digest_from_path(path, action_result)?;
let canonical = if action_result {
mbx_cache_core::LocalActionCache::new(store)
.path_for(&digest)
.ok()?
} else {
LocalCas::new(store).path_for(&digest).ok()?
};
(canonical == path).then_some(digest)
}
fn cached_tree_bytes(cache: &mut BTreeMap<PathBuf, u64>, root: &Path) -> u64 {
*cache
.entry(root.to_path_buf())
.or_insert_with(|| tree_bytes(root))
}
fn tree_bytes(root: &Path) -> u64 {
let Ok(root_metadata) = std::fs::metadata(root) else {
return 0;
};
if root_metadata.is_file() {
return root_metadata.len();
}
let Ok(entries) = std::fs::read_dir(root) else {
return 0;
};
let mut bytes = 0_u64;
let mut pending = entries
.filter_map(std::result::Result::ok)
.map(|entry| entry.path())
.collect::<Vec<_>>();
while let Some(path) = pending.pop() {
let Ok(metadata) = std::fs::symlink_metadata(&path) else {
continue;
};
if metadata.is_file() {
bytes = bytes.saturating_add(metadata.len());
} else if metadata.is_dir()
&& let Ok(entries) = std::fs::read_dir(path)
{
pending.extend(
entries
.filter_map(std::result::Result::ok)
.map(|entry| entry.path()),
);
}
}
bytes
}
#[cfg(test)]
#[path = "store_tests.rs"]
mod tests;