1mod events;
13
14use eyre::{Context, Result};
15use mbx_cache_core::{
16 ActionPrediction, CacheDigest, CacheDirectory, LocalCas, RemoteActionResult, RustcMetadata,
17 TaskActionManifest, is_task_identity, task_manifest_actions,
18};
19use serde::{Deserialize, Serialize};
20use std::collections::{BTreeMap, BTreeSet, HashSet};
21use std::path::{Component, Path, PathBuf};
22use std::time::{Duration, SystemTime, UNIX_EPOCH};
23
24const CAS_DIR: &str = "cas/v1";
25const ACTION_RESULTS_DIR: &str = "action-results/v1";
26const CHECKOUTS_DIR: &str = "checkouts/v1";
27const SWEEP_STAMP: &str = "gc/v1/last-sweep";
28const SWEEP_LOCK: &str = "gc/v1/sweep.lock";
29const CHECKOUT_RECORD_VERSION: u8 = 1;
30const BUILD_RECEIPTS_DIR: &str = "build-receipts/v1";
31const BUILD_RECEIPT_VERSION: u8 = 1;
32const EXPORT_MANIFEST: &str = "mbx-cache-export-v1.json";
33const EXPORT_VERSION: u8 = 2;
34const LEGACY_EXPORT_VERSION: u8 = 1;
35
36const SESSION_RETENTION: Duration = Duration::from_secs(7 * 24 * 60 * 60);
37const MAX_SESSIONS: usize = 256;
38
39const CHECKOUT_RETENTION: Duration = Duration::from_secs(30 * 24 * 60 * 60);
49
50#[derive(Debug, Default, PartialEq, Eq)]
51pub struct StoreStats {
52 pub objects: u64,
53 pub object_bytes: u64,
54 pub action_results: u64,
55 pub action_result_bytes: u64,
56 pub live_checkouts: u64,
57 pub stale_checkouts: u64,
62}
63
64impl StoreStats {
65 pub fn total_bytes(&self) -> u64 {
66 self.object_bytes.saturating_add(self.action_result_bytes)
67 }
68}
69
70#[derive(Debug, Default, PartialEq, Eq)]
71pub struct GcOutcome {
72 pub removed_objects: u64,
73 pub removed_action_results: u64,
74 pub removed_checkout_records: u64,
75 pub removed_session_streams: u64,
78 pub removed_bytes: u64,
79 pub remaining_bytes: u64,
80}
81
82#[derive(Debug, PartialEq, Eq)]
83pub struct ProjectUsage {
84 pub workspace_root: PathBuf,
85 pub identities: u64,
86 pub action_bytes: u64,
87 pub target_bytes: u64,
88 pub live: bool,
89}
90
91#[derive(Debug, PartialEq, Eq)]
92pub struct LargestEntry {
93 pub kind: &'static str,
94 pub path: PathBuf,
95 pub bytes: u64,
96}
97
98#[derive(Debug, Default, PartialEq, Eq)]
99pub struct VerifyOutcome {
100 pub checked_objects: u64,
101 pub checked_action_results: u64,
102 pub problems: Vec<PathBuf>,
103}
104
105#[derive(Debug, Default, PartialEq, Eq)]
106pub struct RemoveProjectOutcome {
107 pub removed_checkout_records: u64,
108}
109
110#[derive(Debug, Default, PartialEq, Eq)]
111pub struct TransferOutcome {
112 pub actions: u64,
113 pub objects: u64,
114 pub bytes: u64,
115}
116
117#[derive(Debug)]
119#[non_exhaustive]
120pub struct ImportOutcome {
121 pub transfer: TransferOutcome,
122 pub attachments: BTreeMap<String, CacheDigest>,
123}
124
125#[derive(Debug, Default)]
127pub struct ExportAdditions {
128 pub attachments: BTreeMap<String, CacheDigest>,
130 pub objects: BTreeSet<CacheDigest>,
132}
133
134#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
136pub struct WorkspaceTarget {
137 pub workspace_root: PathBuf,
138 pub target_dir: PathBuf,
139}
140
141#[derive(Debug, Serialize, Deserialize)]
142#[serde(deny_unknown_fields)]
143struct ExportManifest {
144 version: u8,
145 tasks: Vec<TaskActionManifest>,
146 actions: Vec<CacheDigest>,
147 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
148 attachments: BTreeMap<String, CacheDigest>,
149 #[serde(default, skip_serializing_if = "Vec::is_empty")]
150 objects: Vec<CacheDigest>,
151}
152
153#[derive(Debug, Clone, Serialize, Deserialize)]
155#[serde(deny_unknown_fields)]
156struct BuildReceipt {
157 version: u8,
158 workspace_root: PathBuf,
159 identity: String,
160 completed_nanos: u64,
161 #[serde(default, skip_serializing_if = "Option::is_none")]
162 group: Option<String>,
163 predictions: Vec<ActionPrediction>,
164}
165
166pub fn record_build_receipt(
168 store: &Path,
169 run: &str,
170 identity: &str,
171 workspace_root: &Path,
172 group: Option<&str>,
173 predictions: Vec<ActionPrediction>,
174) -> Result<()> {
175 if !is_task_identity(run) || !is_task_identity(identity) {
176 eyre::bail!("invalid build receipt identity");
177 }
178 if !(TaskActionManifest {
179 version: 1,
180 task: identity.to_owned(),
181 predictions: predictions.clone(),
182 })
183 .validate()
184 {
185 eyre::bail!("invalid build receipt prediction");
186 }
187 if let Some(group) = group {
188 validate_export_group(group)?;
189 }
190 if group.is_none()
195 && read_build_receipt(&latest_receipt_path(store, workspace_root)).is_some_and(|latest| {
196 latest.identity == identity
197 && latest.workspace_root == workspace_root
198 && latest.group.is_none()
199 && latest.predictions == predictions
200 })
201 {
202 return Ok(());
203 }
204 let key = workspace_key(workspace_root);
205 let lock_path = store
206 .join(BUILD_RECEIPTS_DIR)
207 .join("locks")
208 .join(format!("{key}.lock"));
209 std::fs::create_dir_all(lock_path.parent().expect("receipt lock has a parent"))?;
210 let mut lock = fslock::LockFile::open(&lock_path)?;
211 lock.lock()?;
212 let completed_nanos = SystemTime::now()
213 .duration_since(UNIX_EPOCH)
214 .map(|elapsed| elapsed.as_nanos().try_into().unwrap_or(u64::MAX))
215 .unwrap_or_default();
216 let receipt = BuildReceipt {
217 version: BUILD_RECEIPT_VERSION,
218 workspace_root: workspace_root.to_path_buf(),
219 identity: identity.to_owned(),
220 completed_nanos,
221 group: group.map(str::to_owned),
222 predictions,
223 };
224 let bytes = serde_json::to_vec(&receipt)?;
225 write_atomic(&latest_receipt_path(store, workspace_root), &bytes)?;
226 if let Some(group) = group {
227 write_atomic(&group_receipt_path(store, group, run), &bytes)?;
228 }
229 Ok(())
230}
231
232fn workspace_key(workspace_root: &Path) -> String {
233 CacheDigest::blake3(workspace_root.to_string_lossy().as_bytes()).hash
234}
235
236fn latest_receipt_path(store: &Path, workspace_root: &Path) -> PathBuf {
237 store
238 .join(BUILD_RECEIPTS_DIR)
239 .join("checkouts")
240 .join(format!("{}.json", workspace_key(workspace_root)))
241}
242
243fn group_receipt_path(store: &Path, group: &str, run: &str) -> PathBuf {
244 store
245 .join(BUILD_RECEIPTS_DIR)
246 .join("groups")
247 .join(group_key(group))
248 .join(format!("{run}.json"))
249}
250
251fn group_key(group: &str) -> String {
252 CacheDigest::blake3(group.as_bytes()).hash
253}
254
255fn read_build_receipt(path: &Path) -> Option<BuildReceipt> {
256 let bytes = std::fs::read(path).ok()?;
257 let receipt = serde_json::from_slice::<BuildReceipt>(&bytes).ok()?;
258 let valid = TaskActionManifest {
259 version: 1,
260 task: receipt.identity.clone(),
261 predictions: receipt.predictions.clone(),
262 }
263 .validate();
264 (receipt.version == BUILD_RECEIPT_VERSION && valid).then_some(receipt)
265}
266
267fn validate_export_group(group: &str) -> Result<()> {
268 if group.is_empty() || group.len() > 256 || group.chars().any(char::is_control) {
269 eyre::bail!("invalid build export group");
270 }
271 Ok(())
272}
273
274pub fn export_checkout(
276 store: &Path,
277 workspace_root: &Path,
278 archive: &Path,
279) -> Result<TransferOutcome> {
280 let receipt = read_build_receipt(&latest_receipt_path(store, workspace_root))
281 .filter(|receipt| receipt.workspace_root == workspace_root)
282 .ok_or_else(|| {
283 eyre::eyre!(
284 "no completed mbx build is recorded for {}",
285 workspace_root.display()
286 )
287 })?;
288 export_receipts(store, vec![receipt], archive, ExportAdditions::default())
289}
290
291pub fn checkout_workspace_target(
293 store: &Path,
294 workspace_root: &Path,
295) -> Result<Option<WorkspaceTarget>> {
296 let Some(receipt) = read_build_receipt(&latest_receipt_path(store, workspace_root))
297 .filter(|receipt| receipt.workspace_root == workspace_root)
298 else {
299 return Ok(None);
300 };
301 Ok(workspace_target_for_receipt(store, &receipt))
302}
303
304pub fn group_workspace_targets(store: &Path, group: &str) -> Result<Vec<WorkspaceTarget>> {
306 validate_export_group(group)?;
307 let root = store
308 .join(BUILD_RECEIPTS_DIR)
309 .join("groups")
310 .join(group_key(group));
311 let targets = walk_files(&root)?
312 .into_iter()
313 .filter_map(|entry| read_build_receipt(&entry.path))
314 .filter(|receipt| receipt.group.as_deref() == Some(group))
315 .filter_map(|receipt| workspace_target_for_receipt(store, &receipt))
316 .collect::<BTreeSet<_>>();
317 Ok(targets.into_iter().collect())
318}
319
320fn workspace_target_for_receipt(store: &Path, receipt: &BuildReceipt) -> Option<WorkspaceTarget> {
321 let record = read_checkout_record(&checkout_record_path(
322 store,
323 &receipt.identity,
324 &receipt.workspace_root,
325 ))?;
326 (record.workspace_root == receipt.workspace_root && record.target_dir != record.workspace_root)
327 .then_some(WorkspaceTarget {
328 workspace_root: record.workspace_root,
329 target_dir: record.target_dir,
330 })
331}
332
333pub fn export_checkout_with(
335 store: &Path,
336 workspace_root: &Path,
337 archive: &Path,
338 additions: ExportAdditions,
339) -> Result<TransferOutcome> {
340 let receipt = read_build_receipt(&latest_receipt_path(store, workspace_root))
341 .filter(|receipt| receipt.workspace_root == workspace_root)
342 .ok_or_else(|| {
343 eyre::eyre!(
344 "no completed mbx build is recorded for {}",
345 workspace_root.display()
346 )
347 })?;
348 export_receipts(store, vec![receipt], archive, additions)
349}
350
351pub fn export_group(store: &Path, group: &str, archive: &Path) -> Result<TransferOutcome> {
353 export_group_with(store, group, archive, ExportAdditions::default())
354}
355
356pub fn export_group_with(
358 store: &Path,
359 group: &str,
360 archive: &Path,
361 additions: ExportAdditions,
362) -> Result<TransferOutcome> {
363 validate_export_group(group)?;
364 let root = store
365 .join(BUILD_RECEIPTS_DIR)
366 .join("groups")
367 .join(group_key(group));
368 let receipts = walk_files(&root)?
369 .into_iter()
370 .filter_map(|entry| read_build_receipt(&entry.path).map(|receipt| (entry.path, receipt)))
371 .filter(|(_, receipt)| receipt.group.as_deref() == Some(group))
372 .collect::<Vec<_>>();
373 if receipts.is_empty() {
374 eyre::bail!("no completed mbx builds are recorded for export group {group:?}");
375 }
376 let outcome = export_receipts(
377 store,
378 receipts
379 .iter()
380 .map(|(_, receipt)| receipt.clone())
381 .collect(),
382 archive,
383 additions,
384 )?;
385 for (path, _) in receipts {
390 std::fs::remove_file(path)?;
391 }
392 let _ = std::fs::remove_dir(root);
393 Ok(outcome)
394}
395
396fn export_receipts(
397 store: &Path,
398 mut receipts: Vec<BuildReceipt>,
399 archive: &Path,
400 additions: ExportAdditions,
401) -> Result<TransferOutcome> {
402 receipts.sort_by(|left, right| {
403 left.completed_nanos
404 .cmp(&right.completed_nanos)
405 .then_with(|| {
406 fn key(prediction: &ActionPrediction) -> (&CacheDigest, &CacheDigest, &str, &str) {
409 (
410 &prediction.invocation,
411 &prediction.action,
412 &prediction.adapter,
413 &prediction.payload,
414 )
415 }
416 left.predictions
417 .iter()
418 .map(key)
419 .cmp(right.predictions.iter().map(key))
420 })
421 });
422 let mut actions = BTreeSet::new();
423 let mut tasks = BTreeMap::new();
424 for receipt in receipts {
425 actions.extend(
426 receipt
427 .predictions
428 .iter()
429 .map(|prediction| prediction.action.clone()),
430 );
431 let predictions = tasks.entry(receipt.identity).or_insert_with(BTreeMap::new);
434 predictions.extend(
435 receipt
436 .predictions
437 .into_iter()
438 .map(|prediction| (prediction.invocation.clone(), prediction)),
439 );
440 }
441 let tasks = tasks
442 .into_iter()
443 .map(|(task, predictions)| TaskActionManifest {
444 version: 1,
445 task,
446 predictions: predictions.into_values().collect(),
447 })
448 .collect::<Vec<_>>();
449 if tasks.iter().any(|task| !task.validate()) {
450 eyre::bail!("combined export predictions exceed task manifest limits");
451 }
452 validate_export_additions(&additions)?;
453 let (mut objects, result_paths) = strict_closure(store, &actions)?;
454 let cas = LocalCas::new(store);
455 for digest in &additions.objects {
456 require_object(&cas, &mut objects, digest)?;
457 }
458 let parent = archive
459 .parent()
460 .filter(|parent| !parent.as_os_str().is_empty())
461 .unwrap_or_else(|| Path::new("."));
462 std::fs::create_dir_all(parent)?;
463 let temporary = tempfile::Builder::new()
464 .prefix(".mbx-export-")
465 .tempfile_in(parent)?;
466 let mut builder = tar::Builder::new(temporary.reopen()?);
467 append_bytes(
468 &mut builder,
469 Path::new(EXPORT_MANIFEST),
470 &serde_json::to_vec(&ExportManifest {
471 version: if additions.attachments.is_empty() && additions.objects.is_empty() {
472 LEGACY_EXPORT_VERSION
473 } else {
474 EXPORT_VERSION
475 },
476 tasks,
477 actions: actions.iter().cloned().collect(),
478 attachments: additions.attachments.clone(),
479 objects: additions.objects.iter().cloned().collect(),
480 })?,
481 )?;
482 for path in objects.iter().chain(result_paths.iter()) {
483 append_file(&mut builder, store, path)?;
484 }
485 builder.finish()?;
486 drop(builder);
487 temporary
488 .persist(archive)
489 .map_err(|error| error.error)
490 .wrap_err_with(|| format!("failed to publish {}", archive.display()))?;
491 let bytes = std::fs::metadata(archive)?.len();
492 Ok(TransferOutcome {
493 actions: actions.len() as u64,
494 objects: objects.len() as u64,
495 bytes,
496 })
497}
498
499pub fn import_archive(store: &Path, archive: &Path) -> Result<TransferOutcome> {
501 Ok(import_archive_with_attachments(store, archive)?.transfer)
502}
503
504pub fn import_archive_with_attachments(store: &Path, archive: &Path) -> Result<ImportOutcome> {
506 let staging = tempfile::tempdir()?;
507 let file = std::fs::File::open(archive)
508 .wrap_err_with(|| format!("failed to open {}", archive.display()))?;
509 let mut bundle = tar::Archive::new(file);
510 let mut seen = BTreeSet::new();
511 for entry in bundle.entries()? {
512 let mut entry = entry?;
513 let entry_type = entry.header().entry_type();
514 if !entry_type.is_file() && !entry_type.is_gnu_sparse() {
515 eyre::bail!("cache export contains a non-file entry");
516 }
517 let path = entry.path()?.into_owned();
518 validate_archive_path(&path)?;
519 if !seen.insert(path.clone()) {
520 eyre::bail!("cache export contains duplicate entry {}", path.display());
521 }
522 let destination = staging.path().join(&path);
523 std::fs::create_dir_all(destination.parent().expect("entry has a parent"))?;
524 entry.unpack(&destination)?;
528 }
529 let manifest: ExportManifest =
530 serde_json::from_slice(&std::fs::read(staging.path().join(EXPORT_MANIFEST))?)?;
531 let actions = manifest.actions.iter().cloned().collect::<BTreeSet<_>>();
532 let task_identities = manifest
533 .tasks
534 .iter()
535 .map(|task| task.task.as_str())
536 .collect::<BTreeSet<_>>();
537 if !matches!(manifest.version, LEGACY_EXPORT_VERSION | EXPORT_VERSION)
538 || (manifest.version == LEGACY_EXPORT_VERSION
539 && (!manifest.attachments.is_empty() || !manifest.objects.is_empty()))
540 || manifest.tasks.is_empty()
541 || actions.len() != manifest.actions.len()
542 || task_identities.len() != manifest.tasks.len()
543 || manifest.tasks.iter().any(|task| !task.validate())
544 || manifest
545 .actions
546 .iter()
547 .any(|action| action.algorithm != "blake3" || action.validate().is_err())
548 || manifest.tasks.iter().any(|task| {
549 task.predictions
550 .iter()
551 .any(|prediction| !actions.contains(&prediction.action))
552 })
553 || manifest
554 .attachments
555 .keys()
556 .any(|name| !valid_attachment_name(name))
557 || manifest.attachments.values().any(|digest| {
558 digest.algorithm != "blake3"
559 || digest.validate().is_err()
560 || !manifest.objects.contains(digest)
561 })
562 || manifest.objects.iter().collect::<BTreeSet<_>>().len() != manifest.objects.len()
563 || manifest
564 .objects
565 .iter()
566 .any(|digest| digest.algorithm != "blake3" || digest.validate().is_err())
567 {
568 eyre::bail!("unsupported or invalid cache export manifest");
569 }
570 let (mut objects, result_paths) = strict_closure(staging.path(), &actions)
571 .wrap_err("cache export is incomplete or corrupt")?;
572 let staged_cas = LocalCas::new(staging.path());
573 for digest in &manifest.objects {
574 require_object(&staged_cas, &mut objects, digest)
575 .wrap_err("cache export attachment is incomplete or corrupt")?;
576 }
577
578 let cas = LocalCas::new(store);
579 for path in &objects {
580 let relative = path.strip_prefix(staging.path())?;
581 let source = staging.path().join(relative);
582 let digest = addressed_digest(staging.path(), &source, false)
583 .ok_or_else(|| eyre::eyre!("invalid cache object path {}", relative.display()))?;
584 cas.adopt_verified_file(&digest, &source)?;
588 }
589 let action_cache = mbx_cache_core::LocalActionCache::new(store);
590 for path in &result_paths {
591 let result: RemoteActionResult = serde_json::from_slice(&std::fs::read(path)?)?;
592 action_cache.store(&result)?;
593 }
594 for task in manifest.tasks {
595 merge_imported_manifest(store, task)?;
596 }
597 Ok(ImportOutcome {
598 transfer: TransferOutcome {
599 actions: actions.len() as u64,
600 objects: objects.len() as u64,
601 bytes: std::fs::metadata(archive)?.len(),
602 },
603 attachments: manifest.attachments,
604 })
605}
606
607fn validate_export_additions(additions: &ExportAdditions) -> Result<()> {
608 if additions
609 .attachments
610 .keys()
611 .any(|name| !valid_attachment_name(name))
612 || additions
613 .attachments
614 .values()
615 .any(|digest| !additions.objects.contains(digest))
616 || additions
617 .objects
618 .iter()
619 .any(|digest| digest.algorithm != "blake3" || digest.validate().is_err())
620 {
621 eyre::bail!("invalid cache export attachment");
622 }
623 Ok(())
624}
625
626fn valid_attachment_name(name: &str) -> bool {
627 !name.is_empty()
628 && name.len() <= 128
629 && name
630 .bytes()
631 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
632}
633
634fn strict_closure(
635 store: &Path,
636 actions: &BTreeSet<CacheDigest>,
637) -> Result<(BTreeSet<PathBuf>, BTreeSet<PathBuf>)> {
638 let cas = LocalCas::new(store);
639 let action_cache = mbx_cache_core::LocalActionCache::new(store);
640 let mut objects = BTreeSet::new();
641 let mut results = BTreeSet::new();
642 let mut directories = BTreeSet::new();
643 for action in actions {
644 let result = action_cache
645 .find(action)?
646 .ok_or_else(|| eyre::eyre!("action result is missing for {}", action.hash))?;
647 results.insert(action_cache.path_for(action)?);
648 require_object(&cas, &mut objects, &result.action)?;
649 if let Some(metadata) = &result.metadata {
650 require_object(&cas, &mut objects, metadata)?;
651 let captured: CapturedOutput =
652 serde_json::from_slice(&std::fs::read(cas.path_for(metadata)?)?)
653 .wrap_err("action metadata is invalid")?;
654 require_object(&cas, &mut objects, &captured.stdout)?;
655 require_object(&cas, &mut objects, &captured.stderr)?;
656 }
657 if let Some(root) = &result.output_root {
658 require_object(&cas, &mut objects, root)?;
659 let mut pending = vec![root.clone()];
660 while let Some(digest) = pending.pop() {
661 if !directories.insert(digest.clone()) {
662 continue;
663 }
664 let directory: CacheDirectory =
665 serde_json::from_slice(&std::fs::read(cas.path_for(&digest)?)?)
666 .wrap_err("output directory is invalid")?;
667 for file in directory.files {
668 require_object(&cas, &mut objects, &file.digest)?;
669 }
670 for child in directory.directories {
671 require_object(&cas, &mut objects, &child.digest)?;
672 pending.push(child.digest);
673 }
674 }
675 }
676 }
677 Ok((objects, results))
678}
679
680#[derive(Deserialize)]
681struct CapturedOutput {
682 stdout: CacheDigest,
683 stderr: CacheDigest,
684}
685
686fn merge_imported_manifest(destination: &Path, mut imported: TaskActionManifest) -> Result<()> {
687 let identity = imported.task.clone();
688 let destination_path = task_manifest_path(destination, &identity);
689 if let Ok(bytes) = std::fs::read(&destination_path)
690 && let Ok(existing) = serde_json::from_slice::<TaskActionManifest>(&bytes)
691 && existing.task == identity
692 && existing.validate()
693 {
694 let mut predictions = imported
695 .predictions
696 .into_iter()
697 .map(|prediction| (prediction.invocation.clone(), prediction))
698 .collect::<BTreeMap<_, _>>();
699 predictions.extend(
700 existing
701 .predictions
702 .iter()
703 .cloned()
704 .map(|prediction| (prediction.invocation.clone(), prediction)),
705 );
706 imported.predictions = predictions.into_values().collect();
707 if !imported.validate() {
708 return Ok(());
709 }
710 }
711 write_atomic(&destination_path, &serde_json::to_vec(&imported)?)
712}
713
714fn require_object(
715 cas: &LocalCas,
716 objects: &mut BTreeSet<PathBuf>,
717 digest: &CacheDigest,
718) -> Result<()> {
719 let expected = cas.path_for(digest)?;
720 if objects.contains(&expected) {
721 return Ok(());
722 }
723 let path = cas
724 .find(digest)?
725 .ok_or_else(|| eyre::eyre!("cache object is missing for {}", digest.hash))?;
726 objects.insert(path);
727 Ok(())
728}
729
730fn task_manifest_path(store: &Path, identity: &str) -> PathBuf {
731 store
732 .join("task-manifests/v1")
733 .join(format!("{identity}.json"))
734}
735
736fn append_file(builder: &mut tar::Builder<std::fs::File>, root: &Path, path: &Path) -> Result<()> {
737 let name = path.strip_prefix(root)?;
738 builder.append_path_with_name(path, name)?;
739 Ok(())
740}
741
742fn append_bytes(
743 builder: &mut tar::Builder<std::fs::File>,
744 name: &Path,
745 bytes: &[u8],
746) -> Result<()> {
747 let mut header = tar::Header::new_gnu();
748 header.set_size(bytes.len() as u64);
749 header.set_mode(0o644);
750 header.set_cksum();
751 builder.append_data(&mut header, name, bytes)?;
752 Ok(())
753}
754
755fn validate_archive_path(path: &Path) -> Result<()> {
756 if path.as_os_str().is_empty()
757 || path.is_absolute()
758 || path
759 .components()
760 .any(|component| !matches!(component, Component::Normal(_)))
761 {
762 eyre::bail!("cache export contains unsafe path {}", path.display());
763 }
764 let text = path.to_string_lossy();
765 if text != EXPORT_MANIFEST
766 && !text.starts_with("cas/v1/")
767 && !text.starts_with("action-results/v1/")
768 {
769 eyre::bail!("cache export contains unexpected path {}", path.display());
770 }
771 Ok(())
772}
773
774#[derive(Debug, Clone, Serialize, Deserialize)]
781#[serde(deny_unknown_fields)]
782struct CheckoutRecord {
783 version: u8,
784 workspace_root: PathBuf,
785 target_dir: PathBuf,
786 updated_secs: u64,
787}
788
789pub fn stats(store: &Path) -> Result<StoreStats> {
791 let objects = walk_files(&store.join(CAS_DIR))?;
792 let results = walk_files(&store.join(ACTION_RESULTS_DIR))?;
793 let checkouts = scan_checkouts(store)?;
794 Ok(StoreStats {
795 objects: objects.len() as u64,
796 object_bytes: objects.iter().map(|entry| entry.size).sum(),
797 action_results: results.len() as u64,
798 action_result_bytes: results.iter().map(|entry| entry.size).sum(),
799 live_checkouts: checkouts.live_records,
800 stale_checkouts: checkouts.stale_records.len() as u64,
801 })
802}
803
804fn checkout_target_bytes(sizes: &mut BTreeMap<PathBuf, u64>, record: &CheckoutRecord) -> u64 {
811 if record.target_dir == record.workspace_root {
812 return 0;
813 }
814 cached_tree_bytes(sizes, &record.target_dir)
815}
816
817pub fn projects(store: &Path) -> Result<Vec<ProjectUsage>> {
823 let mut projects: BTreeMap<PathBuf, (BTreeSet<String>, bool, u64)> = BTreeMap::new();
824 let mut target_sizes = BTreeMap::new();
825 let root = store.join(CHECKOUTS_DIR);
826 for identity_entry in read_dir_or_empty(&root)? {
827 let identity = identity_entry.file_name().to_string_lossy().into_owned();
828 if !is_task_identity(&identity) || !identity_entry.file_type()?.is_dir() {
829 continue;
830 }
831 for entry in walk_files(&identity_entry.path())? {
832 let Some(record) = read_checkout_record(&entry.path) else {
833 continue;
834 };
835 let project = projects.entry(record.workspace_root.clone()).or_default();
836 if claim_is_live(store, &record) {
837 project.0.insert(identity.clone());
838 project.1 = true;
839 }
840 project.2 = project
841 .2
842 .max(checkout_target_bytes(&mut target_sizes, &record));
843 }
844 }
845 let action_cache = mbx_cache_core::LocalActionCache::new(store);
846 let mut usages = Vec::new();
847 for (workspace_root, (identities, live, target_bytes)) in projects {
848 let mut paths = rooted_objects(store, &identities)?;
849 for identity in &identities {
850 for action in task_manifest_actions(store, identity).unwrap_or_default() {
851 if let Ok(path) = action_cache.path_for(&action) {
852 paths.insert(path);
853 }
854 }
855 }
856 let action_bytes = paths
857 .iter()
858 .filter_map(|path| std::fs::metadata(path).ok())
859 .map(|metadata| metadata.len())
860 .sum();
861 usages.push(ProjectUsage {
862 workspace_root,
863 identities: identities.len() as u64,
864 action_bytes,
865 target_bytes,
866 live,
867 });
868 }
869 usages.sort_by(|left, right| {
870 right
871 .action_bytes
872 .saturating_add(right.target_bytes)
873 .cmp(&left.action_bytes.saturating_add(left.target_bytes))
874 .then_with(|| left.workspace_root.cmp(&right.workspace_root))
875 });
876 Ok(usages)
877}
878
879pub fn largest(store: &Path, limit: usize) -> Result<Vec<LargestEntry>> {
881 let mut entries = Vec::new();
882 for (kind, root, action_result) in [
883 ("object", store.join(CAS_DIR), false),
884 ("action result", store.join(ACTION_RESULTS_DIR), true),
885 ] {
886 entries.extend(
887 walk_files(&root)?
888 .into_iter()
889 .filter(|entry| addressed_digest(store, &entry.path, action_result).is_some())
890 .map(|entry| LargestEntry {
891 kind,
892 path: entry.path,
893 bytes: entry.size,
894 }),
895 );
896 }
897 entries.sort_by(|left, right| {
898 right
899 .bytes
900 .cmp(&left.bytes)
901 .then_with(|| left.path.cmp(&right.path))
902 });
903 entries.truncate(limit);
904 Ok(entries)
905}
906
907pub fn verify(store: &Path) -> Result<VerifyOutcome> {
909 let cas = LocalCas::new(store);
910 let action_cache = mbx_cache_core::LocalActionCache::new(store);
911 let virtually_removed = HashSet::new();
914 let mut outcome = VerifyOutcome::default();
915 for entry in walk_files(&store.join(CAS_DIR))? {
916 let Some(digest) = addressed_digest(store, &entry.path, false) else {
917 continue;
918 };
919 outcome.checked_objects += 1;
920 if !matches!(cas.find(&digest), Ok(Some(_))) {
921 outcome.problems.push(entry.path);
922 }
923 }
924 for entry in walk_files(&store.join(ACTION_RESULTS_DIR))? {
925 let Some(digest) = addressed_digest(store, &entry.path, true) else {
926 continue;
927 };
928 outcome.checked_action_results += 1;
929 if !matches!(action_cache.find(&digest), Ok(Some(_)))
930 || action_result_is_dangling(&cas, &entry.path, &virtually_removed)?
931 {
932 outcome.problems.push(entry.path);
933 }
934 }
935 outcome.problems.sort();
936 Ok(outcome)
937}
938
939pub fn remove_project(store: &Path, workspace_root: &Path) -> Result<RemoveProjectOutcome> {
941 let mut outcome = RemoveProjectOutcome::default();
942 for entry in walk_files(&store.join(CHECKOUTS_DIR))? {
943 if read_checkout_record(&entry.path)
944 .is_some_and(|record| record.workspace_root == workspace_root)
945 {
946 std::fs::remove_file(&entry.path)?;
947 outcome.removed_checkout_records += 1;
948 if let Some(parent) = entry.path.parent() {
949 let _ = std::fs::remove_dir(parent);
950 }
951 }
952 }
953 match std::fs::remove_file(latest_receipt_path(store, workspace_root)) {
954 Ok(()) => {}
955 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
956 Err(error) => return Err(error.into()),
957 }
958 Ok(outcome)
959}
960
961pub fn record_checkout(
973 store: &Path,
974 identity: &str,
975 workspace_root: &Path,
976 target_dir: &Path,
977) -> Result<()> {
978 let record = CheckoutRecord {
979 version: CHECKOUT_RECORD_VERSION,
980 workspace_root: workspace_root.to_path_buf(),
981 target_dir: target_dir.to_path_buf(),
982 updated_secs: SystemTime::now()
983 .duration_since(UNIX_EPOCH)
984 .map(|since| since.as_secs())
985 .unwrap_or_default(),
986 };
987 let mut contents = serde_json::to_vec(&record)?;
988 contents.push(b'\n');
989 write_advisory(
992 &checkout_record_path(store, identity, workspace_root),
993 &contents,
994 )
995}
996
997fn checkout_record_path(store: &Path, identity: &str, workspace_root: &Path) -> PathBuf {
998 let key = CacheDigest::blake3(workspace_root.to_string_lossy().as_bytes()).hash;
1002 store
1003 .join(CHECKOUTS_DIR)
1004 .join(identity)
1005 .join(format!("{key}.json"))
1006}
1007
1008pub fn gc(store: &Path, max_bytes: u64) -> Result<GcOutcome> {
1018 gc_with_mode(store, max_bytes, false)
1019}
1020
1021pub fn gc_dry_run(store: &Path, max_bytes: u64) -> Result<GcOutcome> {
1023 gc_with_mode(store, max_bytes, true)
1024}
1025
1026fn gc_with_mode(store: &Path, max_bytes: u64, dry_run: bool) -> Result<GcOutcome> {
1027 let mut objects = walk_files(&store.join(CAS_DIR))?;
1028 let results = walk_files(&store.join(ACTION_RESULTS_DIR))?;
1029 let mut live_bytes = objects
1030 .iter()
1031 .chain(results.iter())
1032 .map(|entry| entry.size)
1033 .sum::<u64>();
1034
1035 let mut outcome = GcOutcome::default();
1036
1037 let checkouts = scan_checkouts(store)?;
1040 for path in &checkouts.stale_records {
1041 if dry_run || matches!(remove(path)?, Removal::Removed) {
1042 outcome.removed_checkout_records += 1;
1043 }
1044 if !dry_run && let Some(parent) = path.parent() {
1047 let _ = std::fs::remove_dir(parent);
1048 }
1049 }
1050
1051 let mut virtually_removed = HashSet::new();
1052 if live_bytes > max_bytes {
1053 let mut rooted = rooted_objects(store, &checkouts.live_identities)?;
1057 rooted.extend(rooted_action_objects(
1064 store,
1065 grouped_receipt_actions(store)?,
1066 ));
1067 objects.sort_by_cached_key(|entry| (rooted.contains(&entry.path), entry.used));
1071 let evicted = evict_objects(&objects, &rooted, live_bytes, max_bytes, |path| {
1072 if dry_run {
1073 virtually_removed.insert(path.to_path_buf());
1074 Ok(Removal::Removed)
1075 } else {
1076 remove(path)
1077 }
1078 })?;
1079 live_bytes = evicted.remaining_bytes;
1080 outcome.removed_objects += evicted.removed_objects;
1081 outcome.removed_bytes += evicted.removed_bytes;
1082 }
1083
1084 let cas = LocalCas::new(store);
1089 for entry in &results {
1090 if action_result_is_dangling(&cas, &entry.path, &virtually_removed)? {
1091 match if dry_run {
1092 Removal::Removed
1093 } else {
1094 remove(&entry.path)?
1095 } {
1096 Removal::Removed => {
1097 live_bytes = live_bytes.saturating_sub(entry.size);
1098 outcome.removed_action_results += 1;
1099 outcome.removed_bytes += entry.size;
1100 }
1101 Removal::Missing => live_bytes = live_bytes.saturating_sub(entry.size),
1102 Removal::Blocked => {}
1103 }
1104 }
1105 }
1106
1107 let sessions = prune_sessions(store, dry_run)?;
1108 outcome.removed_session_streams += sessions.removed_streams;
1109 outcome.removed_bytes += sessions.removed_bytes;
1110
1111 outcome.remaining_bytes = live_bytes;
1112 Ok(outcome)
1113}
1114
1115#[derive(Debug, Default, PartialEq, Eq)]
1116struct SessionPrune {
1117 removed_streams: u64,
1118 removed_bytes: u64,
1119}
1120
1121fn prune_sessions(store: &Path, dry_run: bool) -> Result<SessionPrune> {
1122 let mut prune = SessionPrune::default();
1123 let ids = events::session_ids(store);
1124 let surplus = ids.len().saturating_sub(MAX_SESSIONS);
1125 for (index, id) in ids.iter().enumerate() {
1126 let paths = events::session_paths(store, id);
1127 let metadata = match std::fs::metadata(&paths.events) {
1128 Ok(metadata) => metadata,
1129 Err(_) => continue,
1130 };
1131 let stale = metadata
1132 .modified()
1133 .ok()
1134 .and_then(|at| SystemTime::now().duration_since(at).ok())
1135 .is_some_and(|age| age > SESSION_RETENTION);
1136 if index >= surplus && !stale {
1137 continue;
1138 }
1139 if events::session_is_live(store, id) {
1140 continue;
1141 }
1142 if dry_run {
1143 prune.removed_streams += 1;
1144 prune.removed_bytes += metadata.len();
1145 continue;
1146 }
1147 if matches!(remove(&paths.events)?, Removal::Removed) {
1148 prune.removed_streams += 1;
1149 prune.removed_bytes += metadata.len();
1150 let _ = std::fs::remove_file(&paths.lock);
1151 }
1152 }
1153 if !dry_run {
1154 for lock in events::orphaned_locks(store) {
1155 let _ = std::fs::remove_file(lock);
1156 }
1157 }
1158 Ok(prune)
1159}
1160
1161pub fn sweep_if_due(store: &Path, max_bytes: u64, interval: Duration) -> Result<Option<GcOutcome>> {
1167 if !claim_sweep(store, interval)? {
1168 return Ok(None);
1169 }
1170 gc(store, max_bytes).map(Some)
1171}
1172
1173pub fn claim_sweep(store: &Path, interval: Duration) -> Result<bool> {
1175 let lock_path = store.join(SWEEP_LOCK);
1176 std::fs::create_dir_all(lock_path.parent().expect("sweep lock has a parent"))?;
1177 let mut lock = fslock::LockFile::open(&lock_path)?;
1178 lock.lock()?;
1179
1180 let stamp = store.join(SWEEP_STAMP);
1181 if let Ok(metadata) = std::fs::metadata(&stamp)
1182 && let Ok(modified) = metadata.modified()
1183 && let Ok(since) = modified.elapsed()
1184 && since < interval
1185 {
1186 return Ok(false);
1187 }
1188 write_atomic(&stamp, b"")?;
1189 Ok(true)
1190}
1191
1192struct CheckoutScan {
1194 live_identities: BTreeSet<String>,
1195 live_records: u64,
1196 stale_records: Vec<PathBuf>,
1197}
1198
1199fn scan_checkouts(store: &Path) -> Result<CheckoutScan> {
1200 let root = store.join(CHECKOUTS_DIR);
1201 let mut scan = CheckoutScan {
1202 live_identities: BTreeSet::new(),
1203 live_records: 0,
1204 stale_records: Vec::new(),
1205 };
1206 let listing = match std::fs::read_dir(&root) {
1207 Ok(listing) => listing,
1208 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(scan),
1209 Err(error) => {
1210 return Err(error).wrap_err_with(|| format!("failed to read {}", root.display()));
1211 }
1212 };
1213 for entry in listing {
1214 let entry = entry?;
1215 let name = entry.file_name().to_string_lossy().into_owned();
1216 if !is_task_identity(&name) || !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
1222 continue;
1223 }
1224 for record in walk_files(&entry.path())? {
1225 match read_checkout_record(&record.path) {
1226 Some(checkout) if claim_is_live(store, &checkout) => {
1227 scan.live_identities.insert(name.clone());
1228 scan.live_records += 1;
1229 }
1230 Some(_) => scan.stale_records.push(record.path),
1231 None => {}
1234 }
1235 }
1236 }
1237 Ok(scan)
1238}
1239
1240fn read_checkout_record(path: &Path) -> Option<CheckoutRecord> {
1241 let bytes = std::fs::read(path).ok()?;
1242 let record = serde_json::from_slice::<CheckoutRecord>(&bytes).ok()?;
1243 (record.version == CHECKOUT_RECORD_VERSION).then_some(record)
1244}
1245
1246fn grouped_receipt_actions(store: &Path) -> Result<BTreeSet<CacheDigest>> {
1248 let root = store.join(BUILD_RECEIPTS_DIR).join("groups");
1249 Ok(walk_files(&root)?
1250 .into_iter()
1251 .filter_map(|entry| read_build_receipt(&entry.path))
1252 .flat_map(|receipt| receipt.predictions.into_iter())
1253 .map(|prediction| prediction.action)
1254 .collect())
1255}
1256
1257fn claim_is_live(store: &Path, record: &CheckoutRecord) -> bool {
1260 checkout_is_live_on(store, &record.workspace_root) && !claim_has_expired(record)
1261}
1262
1263fn claim_has_expired(record: &CheckoutRecord) -> bool {
1264 let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH) else {
1265 return false;
1266 };
1267 now.as_secs()
1268 .saturating_sub(record.updated_secs)
1269 .gt(&CHECKOUT_RETENTION.as_secs())
1270}
1271
1272pub fn checkout_is_live_on(store: &Path, workspace_root: &Path) -> bool {
1285 if !matches!(workspace_root.try_exists(), Ok(false)) {
1286 return true;
1287 }
1288
1289 let Ok(store_metadata) = std::fs::metadata(store) else {
1290 return true;
1291 };
1292 for ancestor in workspace_root.ancestors().skip(1) {
1293 match std::fs::metadata(ancestor) {
1294 Ok(ancestor_metadata) => {
1295 return !same_filesystem(store, &store_metadata, ancestor, &ancestor_metadata);
1296 }
1297 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1298 Err(_) => return true,
1299 }
1300 }
1301 true
1302}
1303
1304pub fn checkout_is_live(workspace_root: &Path) -> bool {
1310 let Some(parent) = workspace_root.parent() else {
1311 return true;
1312 };
1313 checkout_is_live_on(parent, workspace_root)
1314}
1315
1316#[cfg(unix)]
1317fn same_filesystem(
1318 _a_path: &Path,
1319 a: &std::fs::Metadata,
1320 _b_path: &Path,
1321 b: &std::fs::Metadata,
1322) -> bool {
1323 use std::os::unix::fs::MetadataExt as _;
1324 a.dev() == b.dev()
1325}
1326
1327#[cfg(windows)]
1328fn same_filesystem(
1329 a_path: &Path,
1330 _a: &std::fs::Metadata,
1331 b_path: &Path,
1332 _b: &std::fs::Metadata,
1333) -> bool {
1334 windows_volume_name(a_path).is_some_and(|volume| windows_volume_name(b_path) == Some(volume))
1335}
1336
1337#[cfg(windows)]
1338fn windows_volume_name(path: &Path) -> Option<Vec<u16>> {
1339 use std::os::windows::ffi::OsStrExt as _;
1340 use windows_sys::Win32::Storage::FileSystem::{
1341 GetVolumeNameForVolumeMountPointW, GetVolumePathNameW,
1342 };
1343
1344 let path = path
1345 .as_os_str()
1346 .encode_wide()
1347 .chain(Some(0))
1348 .collect::<Vec<_>>();
1349 let mut mount = vec![0_u16; 261];
1353 if unsafe { GetVolumePathNameW(path.as_ptr(), mount.as_mut_ptr(), mount.len() as u32) } == 0 {
1356 return None;
1357 }
1358 let mut volume = vec![0_u16; 261];
1359 if unsafe {
1362 GetVolumeNameForVolumeMountPointW(mount.as_ptr(), volume.as_mut_ptr(), volume.len() as u32)
1363 } == 0
1364 {
1365 return None;
1366 }
1367 volume.truncate(volume.iter().position(|unit| *unit == 0)?);
1368 Some(volume)
1369}
1370
1371#[cfg(not(any(unix, windows)))]
1372fn same_filesystem(
1373 _a_path: &Path,
1374 _a: &std::fs::Metadata,
1375 _b_path: &Path,
1376 _b: &std::fs::Metadata,
1377) -> bool {
1378 false
1379}
1380
1381fn rooted_objects(store: &Path, identities: &BTreeSet<String>) -> Result<HashSet<PathBuf>> {
1389 let mut actions = BTreeSet::new();
1390 for identity in identities {
1391 let manifest_actions = match task_manifest_actions(store, identity) {
1394 Ok(actions) => actions,
1395 Err(error) => {
1396 log::debug!("could not read the manifest for {identity}: {error}");
1397 continue;
1398 }
1399 };
1400 actions.extend(manifest_actions);
1401 }
1402 Ok(rooted_action_objects(store, actions))
1403}
1404
1405fn rooted_action_objects(
1407 store: &Path,
1408 actions: impl IntoIterator<Item = CacheDigest>,
1409) -> HashSet<PathBuf> {
1410 let cas = LocalCas::new(store);
1411 let mut rooted = HashSet::new();
1412 let mut visited = BTreeSet::new();
1413 for action in actions {
1414 let Some(result) = read_action_result(store, &action) else {
1415 continue;
1416 };
1417 root_digest(&cas, &mut rooted, &result.action);
1418 if let Some(metadata) = &result.metadata {
1419 root_digest(&cas, &mut rooted, metadata);
1420 if let Some(rustc) = read_rustc_metadata(&cas, metadata) {
1427 root_digest(&cas, &mut rooted, &rustc.stdout);
1428 root_digest(&cas, &mut rooted, &rustc.stderr);
1429 }
1430 }
1431 if let Some(output_root) = &result.output_root {
1432 root_digest(&cas, &mut rooted, output_root);
1433 root_tree(&cas, output_root, &mut rooted, &mut visited);
1434 }
1435 }
1436 rooted
1437}
1438
1439fn read_action_result(store: &Path, action: &CacheDigest) -> Option<RemoteActionResult> {
1440 let path = mbx_cache_core::LocalActionCache::new(store)
1441 .path_for(action)
1442 .ok()?;
1443 let bytes = std::fs::read(path).ok()?;
1444 serde_json::from_slice(&bytes).ok()
1445}
1446
1447fn root_tree(
1448 cas: &LocalCas,
1449 output_root: &CacheDigest,
1450 rooted: &mut HashSet<PathBuf>,
1451 visited: &mut BTreeSet<CacheDigest>,
1452) {
1453 let mut pending = vec![output_root.clone()];
1454 while let Some(digest) = pending.pop() {
1455 if !visited.insert(digest.clone()) {
1456 continue;
1457 }
1458 let Some(directory) = read_directory(cas, &digest) else {
1459 continue;
1460 };
1461 for file in &directory.files {
1462 root_digest(cas, rooted, &file.digest);
1463 }
1464 for child in &directory.directories {
1465 root_digest(cas, rooted, &child.digest);
1466 pending.push(child.digest.clone());
1467 }
1468 }
1469}
1470
1471fn read_rustc_metadata(cas: &LocalCas, digest: &CacheDigest) -> Option<RustcMetadata> {
1472 let bytes = std::fs::read(cas.path_for(digest).ok()?).ok()?;
1473 serde_json::from_slice(&bytes).ok()
1474}
1475
1476fn read_directory(cas: &LocalCas, digest: &CacheDigest) -> Option<CacheDirectory> {
1477 let bytes = std::fs::read(cas.path_for(digest).ok()?).ok()?;
1478 serde_json::from_slice(&bytes).ok()
1479}
1480
1481fn root_digest(cas: &LocalCas, rooted: &mut HashSet<PathBuf>, digest: &CacheDigest) {
1482 if let Ok(path) = cas.path_for(digest) {
1483 rooted.insert(path);
1484 }
1485}
1486
1487#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1488enum Removal {
1489 Removed,
1490 Missing,
1491 Blocked,
1492}
1493
1494fn remove(path: &Path) -> Result<Removal> {
1495 match std::fs::remove_file(path) {
1496 Ok(()) => Ok(Removal::Removed),
1497 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Removal::Missing),
1499 Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => {
1504 log::debug!("could not evict {}: {error}", path.display());
1505 Ok(Removal::Blocked)
1506 }
1507 Err(error) => Err(error).wrap_err_with(|| format!("failed to evict {}", path.display())),
1508 }
1509}
1510
1511#[derive(Debug, Default, PartialEq, Eq)]
1512struct ObjectEvictions {
1513 removed_objects: u64,
1514 removed_bytes: u64,
1515 remaining_bytes: u64,
1516}
1517
1518fn evict_objects(
1521 objects: &[Entry],
1522 rooted: &HashSet<PathBuf>,
1523 mut live_bytes: u64,
1524 max_bytes: u64,
1525 mut remove_file: impl FnMut(&Path) -> Result<Removal>,
1526) -> Result<ObjectEvictions> {
1527 let mut outcome = ObjectEvictions::default();
1528 let mut blocked_unrooted = false;
1529 for entry in objects {
1530 if live_bytes <= max_bytes {
1531 break;
1532 }
1533 let is_rooted = rooted.contains(&entry.path);
1534 if is_rooted && blocked_unrooted {
1535 break;
1539 }
1540 match remove_file(&entry.path)? {
1541 Removal::Removed => {
1542 live_bytes = live_bytes.saturating_sub(entry.size);
1543 outcome.removed_objects += 1;
1544 outcome.removed_bytes += entry.size;
1545 }
1546 Removal::Missing => live_bytes = live_bytes.saturating_sub(entry.size),
1547 Removal::Blocked if !is_rooted => blocked_unrooted = true,
1548 Removal::Blocked => {}
1549 }
1550 }
1551 outcome.remaining_bytes = live_bytes;
1552 Ok(outcome)
1553}
1554
1555fn action_result_is_dangling(
1573 cas: &LocalCas,
1574 path: &Path,
1575 virtually_removed: &HashSet<PathBuf>,
1576) -> Result<bool> {
1577 let bytes = match std::fs::read(path) {
1578 Ok(bytes) => bytes,
1579 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
1580 Err(error) => {
1581 return Err(error).wrap_err_with(|| format!("failed to read {}", path.display()));
1582 }
1583 };
1584 let Ok(result) = serde_json::from_slice::<RemoteActionResult>(&bytes) else {
1586 return Ok(false);
1587 };
1588 for digest in [
1589 Some(&result.action),
1590 result.metadata.as_ref(),
1591 result.output_root.as_ref(),
1592 ]
1593 .into_iter()
1594 .flatten()
1595 {
1596 match cas.path_for(digest) {
1597 Ok(path) => {
1598 if virtually_removed.contains(&path) || !path.exists() {
1599 return Ok(true);
1600 }
1601 }
1602 Err(_) => return Ok(true),
1604 }
1605 }
1606 Ok(false)
1607}
1608
1609struct Entry {
1610 path: PathBuf,
1611 size: u64,
1612 used: SystemTime,
1613}
1614
1615fn walk_files(root: &Path) -> Result<Vec<Entry>> {
1616 let mut entries = Vec::new();
1617 let mut pending = vec![root.to_path_buf()];
1618 while let Some(directory) = pending.pop() {
1619 let listing = match std::fs::read_dir(&directory) {
1620 Ok(listing) => listing,
1621 Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
1622 Err(error) => {
1623 return Err(error)
1624 .wrap_err_with(|| format!("failed to read {}", directory.display()));
1625 }
1626 };
1627 for entry in listing {
1628 let entry = entry?;
1629 let metadata = match entry.metadata() {
1630 Ok(metadata) => metadata,
1631 Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
1633 Err(error) => return Err(error.into()),
1634 };
1635 if metadata.is_dir() {
1636 pending.push(entry.path());
1637 } else if metadata.is_file() {
1638 let used = metadata
1639 .accessed()
1640 .or_else(|_| metadata.modified())
1641 .unwrap_or(SystemTime::UNIX_EPOCH);
1642 entries.push(Entry {
1643 path: entry.path(),
1644 size: metadata.len(),
1645 used,
1646 });
1647 }
1648 }
1649 }
1650 Ok(entries)
1651}
1652
1653fn read_dir_or_empty(root: &Path) -> Result<Vec<std::fs::DirEntry>> {
1654 match std::fs::read_dir(root) {
1655 Ok(entries) => entries
1656 .collect::<std::io::Result<Vec<_>>>()
1657 .map_err(Into::into),
1658 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
1659 Err(error) => Err(error).wrap_err_with(|| format!("failed to read {}", root.display())),
1660 }
1661}
1662
1663fn digest_from_path(path: &Path, action_result: bool) -> Option<CacheDigest> {
1664 let name = path.file_name()?.to_str()?;
1665 let name = if action_result {
1666 name.strip_suffix(".json")?
1667 } else {
1668 name
1669 };
1670 let (hash, size) = name.rsplit_once('-')?;
1671 let algorithm = path.parent()?.parent()?.file_name()?.to_str()?.to_string();
1672 let digest = CacheDigest {
1673 algorithm,
1674 hash: hash.to_string(),
1675 size: size.parse().ok()?,
1676 };
1677 digest.validate().ok()?;
1678 Some(digest)
1679}
1680
1681fn addressed_digest(store: &Path, path: &Path, action_result: bool) -> Option<CacheDigest> {
1682 let digest = digest_from_path(path, action_result)?;
1683 let canonical = if action_result {
1684 mbx_cache_core::LocalActionCache::new(store)
1685 .path_for(&digest)
1686 .ok()?
1687 } else {
1688 LocalCas::new(store).path_for(&digest).ok()?
1689 };
1690 (canonical == path).then_some(digest)
1691}
1692
1693fn cached_tree_bytes(cache: &mut BTreeMap<PathBuf, u64>, root: &Path) -> u64 {
1694 *cache
1695 .entry(root.to_path_buf())
1696 .or_insert_with(|| tree_bytes(root))
1697}
1698
1699fn tree_bytes(root: &Path) -> u64 {
1700 let Ok(root_metadata) = std::fs::metadata(root) else {
1701 return 0;
1702 };
1703 if root_metadata.is_file() {
1704 return root_metadata.len();
1705 }
1706 let Ok(entries) = std::fs::read_dir(root) else {
1707 return 0;
1708 };
1709 let mut bytes = 0_u64;
1710 let mut pending = entries
1711 .filter_map(std::result::Result::ok)
1712 .map(|entry| entry.path())
1713 .collect::<Vec<_>>();
1714 while let Some(path) = pending.pop() {
1715 let Ok(metadata) = std::fs::symlink_metadata(&path) else {
1716 continue;
1717 };
1718 if metadata.is_file() {
1719 bytes = bytes.saturating_add(metadata.len());
1720 } else if metadata.is_dir()
1721 && let Ok(entries) = std::fs::read_dir(path)
1722 {
1723 pending.extend(
1724 entries
1725 .filter_map(std::result::Result::ok)
1726 .map(|entry| entry.path()),
1727 );
1728 }
1729 }
1730 bytes
1731}
1732
1733#[cfg(test)]
1734#[path = "store_tests.rs"]
1735mod tests;
1736
1737fn write_advisory(path: &Path, contents: &[u8]) -> Result<()> {
1740 let parent = path
1741 .parent()
1742 .filter(|parent| !parent.as_os_str().is_empty())
1743 .ok_or_else(|| eyre::eyre!("path has no parent: {}", path.display()))?;
1744 std::fs::create_dir_all(parent)
1745 .wrap_err_with(|| format!("failed to create {}", parent.display()))?;
1746 let mut temporary = tempfile::Builder::new()
1747 .prefix(".mbx-")
1748 .tempfile_in(parent)?;
1749 use std::io::Write as _;
1750 temporary.write_all(contents)?;
1751 temporary
1752 .persist(path)
1753 .map_err(|error| error.error)
1754 .wrap_err_with(|| format!("failed atomic write: {}", path.display()))?;
1755 Ok(())
1756}
1757
1758fn write_atomic(path: &Path, contents: &[u8]) -> Result<()> {
1759 let parent = path
1760 .parent()
1761 .filter(|parent| !parent.as_os_str().is_empty())
1762 .ok_or_else(|| eyre::eyre!("path has no parent: {}", path.display()))?;
1763 std::fs::create_dir_all(parent)
1764 .wrap_err_with(|| format!("failed to create {}", parent.display()))?;
1765 let mut temporary = tempfile::Builder::new()
1766 .prefix(".mbx-")
1767 .tempfile_in(parent)?;
1768 use std::io::Write as _;
1769 temporary.write_all(contents)?;
1770 temporary.as_file_mut().sync_all()?;
1771 temporary
1772 .persist(path)
1773 .map_err(|error| error.error)
1774 .wrap_err_with(|| format!("failed atomic write: {}", path.display()))?;
1775 Ok(())
1776}