1use std::path::{Path, PathBuf};
43use std::time::Duration;
44
45use anyhow::{Context as _, Result, bail};
46use jiff::Timestamp;
47use serde::{Deserialize, Serialize};
48
49use crate::proc::{self, Quiet as _};
50
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53pub struct Owner {
54 pub run: String,
56 pub node: String,
58 pub seat: String,
61 pub pid: u32,
65 pub worktree: String,
68 pub head: String,
70}
71
72impl Owner {
73 #[must_use]
75 pub fn here(run: &str, node: &str, seat: &str, worktree: &Path, head: &str) -> Owner {
76 Owner {
77 run: run.to_owned(),
78 node: node.to_owned(),
79 seat: seat.to_owned(),
80 pid: std::process::id(),
81 worktree: worktree.display().to_string(),
82 head: head.to_owned(),
83 }
84 }
85}
86
87#[derive(Debug, Clone, Serialize, Deserialize)]
89struct LeaseFile {
90 cache_dir: String,
94 owner: Owner,
95 acquired_at: Timestamp,
96}
97
98#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum Status {
101 Free,
103 Active(Owner),
105 Stale(Owner),
107 Unknown,
110}
111
112#[derive(Debug, Clone, PartialEq, Eq)]
114pub enum Busy {
115 Active(Owner),
117 Unknown,
119 Contended,
121 Outputs,
123}
124
125impl Busy {
126 #[must_use]
128 pub fn describe(&self) -> String {
129 match self {
130 Busy::Active(o) => format!(
131 "held by run {} node {} seat {} (pid {})",
132 o.run, o.node, o.seat, o.pid
133 ),
134 Busy::Unknown => {
135 "an unreadable lease is present; refusing to guess who holds it".to_owned()
136 }
137 Busy::Outputs => {
138 "cache outputs are still owned by running tools or process cleanup".to_owned()
139 }
140 Busy::Contended => "lost a race for the lease; retrying".to_owned(),
141 }
142 }
143}
144
145#[derive(Debug)]
149pub struct Guard {
150 path: PathBuf,
151 released: bool,
152 outputs: Option<crate::retention::OutputLease>,
153}
154
155impl Guard {
156 fn new(path: PathBuf) -> Guard {
157 Guard {
158 path,
159 released: false,
160 outputs: None,
161 }
162 }
163
164 pub fn release(mut self) {
168 self.do_release();
169 }
170
171 fn do_release(&mut self) {
172 if !self.released {
173 let _ = std::fs::remove_file(&self.path);
174 self.released = true;
175 }
176 }
177}
178
179impl Drop for Guard {
180 fn drop(&mut self) {
181 self.do_release();
182 }
183}
184
185fn leases_dir(home: &Path) -> PathBuf {
189 home.join("cache-leases")
190}
191
192fn slug(cache_dir: &Path) -> String {
197 if let Some(id) = crate::build_target::generation(cache_dir) {
198 return format!("isolated-{id}");
199 }
200 let norm = normalize(cache_dir);
201 let mut readable: String = norm
202 .chars()
203 .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
204 .collect();
205 readable.truncate(80);
206 use std::hash::{Hash, Hasher};
207 let mut hasher = std::collections::hash_map::DefaultHasher::new();
208 norm.hash(&mut hasher);
209 format!("{readable}-{:08x}", hasher.finish() as u32)
210}
211
212fn normalize(p: &Path) -> String {
218 std::fs::canonicalize(p)
219 .map(|p| p.display().to_string())
220 .unwrap_or_else(|_| p.display().to_string())
221 .replace('\\', "/")
222 .to_ascii_lowercase()
223}
224
225fn lease_path(home: &Path, cache_dir: &Path) -> PathBuf {
226 leases_dir(home).join(format!("{}.json", slug(cache_dir)))
227}
228
229fn identity_path(home: &Path, cache_dir: &Path) -> PathBuf {
230 leases_dir(home).join(format!("{}.identity.json", slug(cache_dir)))
231}
232
233fn catalog_path(home: &Path, cache_dir: &Path) -> PathBuf {
234 leases_dir(home).join(format!("{}.catalog.json", slug(cache_dir)))
235}
236
237#[derive(Debug, Clone, Serialize, Deserialize)]
254struct CatalogRecord {
255 cache_dir: String,
256 last_owner: Owner,
257 last_used_at: Timestamp,
258}
259
260fn record_catalog(home: &Path, cache_dir: &Path, owner: &Owner) {
266 let path = catalog_path(home, cache_dir);
267 let record = CatalogRecord {
268 cache_dir: cache_dir.display().to_string(),
269 last_owner: owner.clone(),
270 last_used_at: Timestamp::now(),
271 };
272 let Ok(body) = serde_json::to_string_pretty(&record) else {
273 return;
274 };
275 let tmp = path.with_extension("json.tmp");
276 if std::fs::write(&tmp, &body).is_ok() {
277 let _ = std::fs::rename(&tmp, &path);
278 }
279}
280
281fn read_catalog(path: &Path) -> Option<CatalogRecord> {
286 let body = std::fs::read_to_string(path).ok()?;
287 serde_json::from_str(&body).ok()
288}
289
290fn read_lease(path: &Path) -> Option<LeaseFile> {
293 let body = std::fs::read_to_string(path).ok()?;
294 serde_json::from_str(&body).ok()
295}
296
297fn peek_cache_dir(path: &Path) -> Option<String> {
302 let body = std::fs::read_to_string(path).ok()?;
303 let value: serde_json::Value = serde_json::from_str(&body).ok()?;
304 value
305 .get("cache_dir")
306 .and_then(|v| v.as_str())
307 .map(str::to_owned)
308}
309
310fn classify(path: &Path) -> Status {
312 classify_with(path, proc::pid_alive)
313}
314
315fn classify_with<F: Fn(u32) -> bool>(path: &Path, alive: F) -> Status {
324 if !path.exists() {
325 return Status::Free;
326 }
327 let Some(lease) = read_lease(path) else {
328 return Status::Unknown;
329 };
330 let this_process = std::process::id();
331 if lease.owner.pid == this_process || alive(lease.owner.pid) {
332 Status::Active(lease.owner)
333 } else {
334 Status::Stale(lease.owner)
335 }
336}
337
338fn write_new(
343 path: &Path,
344 cache_dir: &Path,
345 owner: &Owner,
346 retry: crate::lock_file::Retry,
347) -> std::io::Result<()> {
348 write_lease(retry.create(path)?, cache_dir, owner)
349}
350
351fn write_lease(mut f: std::fs::File, cache_dir: &Path, owner: &Owner) -> std::io::Result<()> {
352 use std::io::Write as _;
353 let lease = LeaseFile {
354 cache_dir: cache_dir.display().to_string(),
355 owner: owner.clone(),
356 acquired_at: Timestamp::now(),
357 };
358 let body = serde_json::to_string_pretty(&lease).unwrap_or_default();
359 f.write_all(body.as_bytes())?;
360 Ok(())
361}
362
363pub enum AcquireOutcome {
365 Acquired(Guard),
367 Busy(Busy),
369}
370
371pub fn try_acquire(home: &Path, cache_dir: &Path, owner: &Owner) -> Result<AcquireOutcome> {
375 let Ok(_outputs) = crate::retention::OutputLease::cache(home, cache_dir, true) else {
376 return Ok(AcquireOutcome::Busy(Busy::Outputs));
377 };
378 try_acquire_with(home, cache_dir, owner, proc::pid_alive)
379}
380
381pub fn try_acquire_maintenance(
384 home: &Path,
385 cache_dir: &Path,
386 owner: &Owner,
387) -> Result<AcquireOutcome> {
388 crate::build_target::check_prune(home, cache_dir)?;
389 let Ok(outputs) = crate::retention::OutputLease::cache(home, cache_dir, true) else {
390 return Ok(AcquireOutcome::Busy(Busy::Outputs));
391 };
392 match try_acquire_with(home, cache_dir, owner, proc::pid_alive)? {
393 AcquireOutcome::Acquired(mut guard) => {
394 guard.outputs = Some(outputs);
395 Ok(AcquireOutcome::Acquired(guard))
396 }
397 busy => Ok(busy),
398 }
399}
400
401fn try_acquire_with<F: Fn(u32) -> bool + Copy>(
404 home: &Path,
405 cache_dir: &Path,
406 owner: &Owner,
407 alive: F,
408) -> Result<AcquireOutcome> {
409 try_acquire_before(
410 home,
411 cache_dir,
412 owner,
413 alive,
414 crate::lock_file::Retry::new(None),
415 )
416}
417
418fn try_acquire_before<F: Fn(u32) -> bool + Copy>(
419 home: &Path,
420 cache_dir: &Path,
421 owner: &Owner,
422 alive: F,
423 retry: crate::lock_file::Retry,
424) -> Result<AcquireOutcome> {
425 let dir = leases_dir(home);
426 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
427 let path = dir.join(format!("{}.json", slug(cache_dir)));
428
429 for _ in 0..2 {
435 let result = write_new(&path, cache_dir, owner, retry);
436 if let Some(outcome) = acquire_result(home, &path, cache_dir, owner, alive, result)? {
437 return Ok(outcome);
438 }
439 }
440 Ok(AcquireOutcome::Busy(Busy::Contended))
441}
442
443fn acquire_result(
445 home: &Path,
446 path: &Path,
447 cache_dir: &Path,
448 owner: &Owner,
449 alive: impl Fn(u32) -> bool + Copy,
450 result: std::io::Result<()>,
451) -> Result<Option<AcquireOutcome>> {
452 match result {
453 Ok(()) => {
454 record_catalog(home, cache_dir, owner);
455 return Ok(Some(AcquireOutcome::Acquired(Guard::new(path.to_owned()))));
456 }
457 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
458 Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
459 }
460 match classify_with(path, alive) {
461 Status::Free => {}
462 Status::Stale(_) => {
463 let _ = std::fs::remove_file(path);
464 }
465 Status::Active(o) => return Ok(Some(AcquireOutcome::Busy(Busy::Active(o)))),
466 Status::Unknown => return Ok(Some(AcquireOutcome::Busy(Busy::Unknown))),
467 }
468 Ok(None)
469}
470
471async fn try_acquire_async(
472 home: &Path,
473 cache_dir: &Path,
474 owner: &Owner,
475 retry: crate::lock_file::Retry,
476 cancel: &(dyn Fn() -> bool + Sync),
477) -> Result<Option<AcquireOutcome>> {
478 let Ok(_outputs) = crate::retention::OutputLease::cache(home, cache_dir, true) else {
479 return Ok(Some(AcquireOutcome::Busy(Busy::Outputs)));
480 };
481 let dir = leases_dir(home);
482 std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
483 let path = dir.join(format!("{}.json", slug(cache_dir)));
484 for _ in 0..2 {
485 let opened = retry
486 .run_async_unless(
487 || {
488 std::fs::OpenOptions::new()
489 .write(true)
490 .create_new(true)
491 .open(&path)
492 },
493 cancel,
494 )
495 .await;
496 let result = match opened {
497 Ok(Some(file)) => write_lease(file, cache_dir, owner),
498 Ok(None) => return Ok(None),
499 Err(error) => Err(error),
500 };
501 if let Some(outcome) =
502 acquire_result(home, &path, cache_dir, owner, proc::pid_alive, result)?
503 {
504 return Ok(Some(outcome));
505 }
506 }
507 Ok(Some(AcquireOutcome::Busy(Busy::Contended)))
508}
509
510#[must_use]
515pub fn in_use(home: &Path, cache_dir: &Path) -> bool {
516 let path = lease_path(home, cache_dir);
517 matches!(classify(&path), Status::Active(_) | Status::Unknown)
518 || crate::retention::OutputLease::cache(home, cache_dir, true).is_err()
519}
520
521pub const RESOURCE_HOLD: &str = "[resource] ";
524
525#[derive(Debug)]
527pub struct WaitTimeout(pub String);
528
529impl std::fmt::Display for WaitTimeout {
530 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
531 f.write_str(&self.0)
532 }
533}
534
535impl std::error::Error for WaitTimeout {}
536
537pub async fn wait_for(
546 home: &Path,
547 cache_dir: &Path,
548 owner: &Owner,
549 budget: Duration,
550 poll: Duration,
551) -> Result<Guard> {
552 match wait_for_unless(home, cache_dir, owner, budget, poll, &|| false).await? {
553 Some(g) => Ok(g),
554 None => bail!("the wait for the build cache was cancelled"),
555 }
556}
557
558pub async fn wait_for_unless(
563 home: &Path,
564 cache_dir: &Path,
565 owner: &Owner,
566 budget: Duration,
567 poll: Duration,
568 cancel: &(dyn Fn() -> bool + Sync),
569) -> Result<Option<Guard>> {
570 let start = std::time::Instant::now();
571 let retry = crate::lock_file::Retry::new(Some(start + budget));
574 loop {
575 let Some(acquired) = try_acquire_async(home, cache_dir, owner, retry, cancel).await? else {
576 return Ok(None);
577 };
578 match acquired {
579 AcquireOutcome::Acquired(g) => return Ok(Some(g)),
580 AcquireOutcome::Busy(busy) => {
581 if cancel() {
582 return Ok(None);
583 }
584 let elapsed = start.elapsed();
585 if elapsed >= budget {
586 return Err(WaitTimeout(format!(
587 "timed out after {}s waiting for the build cache at {} ({})",
588 budget.as_secs(),
589 cache_dir.display(),
590 busy.describe()
591 ))
592 .into());
593 }
594 tokio::time::sleep(poll.min(budget - elapsed)).await;
595 }
596 }
597 }
598}
599
600#[derive(Debug, Clone)]
606pub struct Entry {
607 pub cache_dir: String,
609 pub status: EntryStatus,
611}
612
613#[derive(Debug, Clone)]
615pub enum EntryStatus {
616 Active(Owner),
618 Stale(Owner),
620 Unknown,
622 Idle(Owner),
628 Outputs(Owner),
631}
632
633#[must_use]
641pub fn inventory(home: &Path) -> Vec<Entry> {
642 let mut entries = inventory_with(home, proc::pid_alive);
643 for entry in &mut entries {
644 if let EntryStatus::Idle(owner) | EntryStatus::Stale(owner) = &entry.status
645 && crate::retention::OutputLease::cache(home, Path::new(&entry.cache_dir), true)
646 .is_err()
647 {
648 entry.status = EntryStatus::Outputs(owner.clone());
649 }
650 }
651 entries
652}
653
654fn inventory_with<F: Fn(u32) -> bool + Copy>(home: &Path, alive: F) -> Vec<Entry> {
657 let dir = leases_dir(home);
658 let Ok(rd) = std::fs::read_dir(&dir) else {
659 return Vec::new();
660 };
661 let mut out = Vec::new();
662 for entry in rd.flatten() {
663 let path = entry.path();
664 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
665 continue;
666 };
667 if !name.ends_with(".json")
668 || name.ends_with(".identity.json")
669 || name.ends_with(".catalog.json")
670 {
671 continue;
672 }
673 let status = match classify_with(&path, alive) {
674 Status::Free => continue,
675 Status::Active(o) => EntryStatus::Active(o),
676 Status::Stale(o) => EntryStatus::Stale(o),
677 Status::Unknown => EntryStatus::Unknown,
678 };
679 let cache_dir = peek_cache_dir(&path)
685 .unwrap_or_else(|| format!("(unreadable lease file: {})", path.display()));
686 out.push(Entry { cache_dir, status });
687 }
688
689 if let Ok(rd) = std::fs::read_dir(&dir) {
695 for entry in rd.flatten() {
696 let path = entry.path();
697 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
698 continue;
699 };
700 let Some(stem) = name.strip_suffix(".catalog.json") else {
701 continue;
702 };
703 if dir.join(format!("{stem}.json")).exists() {
704 continue;
705 }
706 if let Some(record) = read_catalog(&path) {
707 out.push(Entry {
708 cache_dir: record.cache_dir,
709 status: EntryStatus::Idle(record.last_owner),
710 });
711 }
712 }
713 }
714
715 out.sort_by(|a, b| a.cache_dir.cmp(&b.cache_dir));
716 out
717}
718
719pub fn maintenance_prune(
728 home: &Path,
729 cache_dir: &Path,
730 limit: u64,
731) -> Result<Option<crate::disk::Prune>> {
732 maintenance_prune_keeping(home, cache_dir, limit, 0)
733}
734
735pub fn maintenance_prune_keeping(
742 home: &Path,
743 cache_dir: &Path,
744 limit: u64,
745 keep: u64,
746) -> Result<Option<crate::disk::Prune>> {
747 let owner = Owner {
748 run: "maintenance".to_owned(),
749 node: "prune".to_owned(),
750 seat: "janitor".to_owned(),
751 pid: std::process::id(),
752 worktree: String::new(),
753 head: String::new(),
754 };
755 match try_acquire_maintenance(home, cache_dir, &owner)? {
756 AcquireOutcome::Busy(_) => Ok(None),
757 AcquireOutcome::Acquired(guard) => {
758 let _cargo = crate::retention::cargo_locks(cache_dir)?;
759 let result = crate::disk::prune_dir_keeping(cache_dir, limit, keep)?;
760 guard.release();
761 Ok(Some(result))
762 }
763 }
764}
765
766#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
770pub struct Identity {
771 pub worktree: String,
773 pub head: String,
775}
776
777impl Identity {
778 #[must_use]
780 pub fn new(worktree: &Path, head: &str) -> Identity {
781 Identity {
782 worktree: worktree.display().to_string(),
783 head: head.to_owned(),
784 }
785 }
786}
787
788#[must_use]
793pub fn needs_refresh(home: &Path, cache_dir: &Path, current: &Identity) -> bool {
794 let path = identity_path(home, cache_dir);
795 let Ok(body) = std::fs::read_to_string(path) else {
796 return true;
797 };
798 match serde_json::from_str::<Identity>(&body) {
799 Ok(recorded) => &recorded != current,
800 Err(_) => true,
801 }
802}
803
804pub fn record_identity(home: &Path, cache_dir: &Path, identity: &Identity) -> Result<()> {
806 let path = identity_path(home, cache_dir);
807 if let Some(parent) = path.parent() {
808 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
809 }
810 let body = serde_json::to_string_pretty(identity).context("serialize cache identity")?;
811 let tmp = path.with_extension("json.tmp");
812 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
813 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
814 Ok(())
815}
816
817pub fn invalidate_identity(home: &Path, cache_dir: &Path) {
831 let _ = std::fs::remove_file(identity_path(home, cache_dir));
832}
833
834#[must_use]
840pub fn parse_workspace_package_names(metadata_json: &str) -> Vec<String> {
841 let Ok(value) = serde_json::from_str::<serde_json::Value>(metadata_json) else {
842 return Vec::new();
843 };
844 value
845 .get("packages")
846 .and_then(|p| p.as_array())
847 .map(|packages| {
848 packages
849 .iter()
850 .filter_map(|p| p.get("name").and_then(|n| n.as_str()))
851 .map(str::to_owned)
852 .collect()
853 })
854 .unwrap_or_default()
855}
856
857#[must_use]
861pub fn extract_manifest_paths(commands: &[String]) -> Vec<PathBuf> {
862 const KEY: &str = "--manifest-path";
863 let mut out: Vec<PathBuf> = Vec::new();
864 for command in commands {
865 let mut rest = command.as_str();
866 while let Some(at) = rest.find(KEY) {
867 rest = &rest[at + KEY.len()..];
868 let value = if let Some(r) = rest.strip_prefix('=') {
869 r
870 } else if rest.starts_with(char::is_whitespace) {
871 rest.trim_start()
872 } else {
873 continue;
874 };
875 let value = if let Some(s) = value.strip_prefix('\'') {
876 s.split('\'').next().unwrap_or("")
877 } else if let Some(s) = value.strip_prefix('"') {
878 s.split('"').next().unwrap_or("")
879 } else {
880 let end = value.find(char::is_whitespace).unwrap_or(value.len());
881 &value[..end]
882 };
883 if !value.is_empty() {
884 let path = PathBuf::from(value);
885 if !out.contains(&path) {
886 out.push(path);
887 }
888 }
889 }
890 }
891 out
892}
893
894#[derive(Debug, Clone, PartialEq, Eq)]
896pub enum Target {
897 Root,
899 Manifest(PathBuf),
901 Directory(PathBuf),
903}
904
905fn plan_targets(
910 worktree: &Path,
911 requested: &[Target],
912 exists: impl Fn(&Path) -> Result<bool>,
913) -> Result<Vec<Target>> {
914 let mut targets = Vec::new();
915 if exists(&worktree.join("Cargo.toml"))? {
916 targets.push(Target::Root);
917 }
918 for target in requested {
919 match target {
920 Target::Root => {}
921 Target::Manifest(m) => {
922 let full = worktree.join(m);
923 if exists(&full)? {
924 targets.push(Target::Manifest(full));
925 } else {
926 tracing::warn!(
927 manifest = %m.display(),
928 "build cache: --manifest-path from a verify command does not exist; skipped"
929 );
930 }
931 }
932 Target::Directory(dir) => {
933 match crate::build_target::command::resolve_dir(worktree, dir) {
936 Ok(full) if exists(&full.join("Cargo.toml"))? => {
937 targets.push(Target::Directory(full));
938 }
939 Ok(_) => {}
940 Err(e) => {
941 tracing::warn!(error = %e, "build cache: verification directory skipped")
942 }
943 }
944 }
945 }
946 }
947 Ok(targets)
948}
949
950fn file_exists(path: &Path) -> Result<bool> {
953 match std::fs::metadata(path) {
954 Ok(m) => Ok(m.is_file()),
955 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
956 Err(e) => Err(e).with_context(|| format!("stat {}", path.display())),
957 }
958}
959
960fn refresh_stale_packages(
968 worktree: &Path,
969 cache_dir: &Path,
970 manifests: &[Target],
971 isolated: bool,
972) -> Result<Option<Vec<String>>> {
973 let targets = plan_targets(worktree, manifests, file_exists)?;
974 if targets.is_empty() {
975 return Ok(None);
976 }
977 let mut all = Vec::new();
978 let mut failed = Vec::new();
979 for target in &targets {
980 let (cwd, manifest_arg) = match target {
981 Target::Root => (worktree, None),
982 Target::Manifest(m) => (worktree, Some(m)),
983 Target::Directory(dir) => (dir.as_path(), None),
984 };
985 let mut cmd = if isolated {
986 crate::build_target::command::cargo(cache_dir)?
987 } else {
988 std::process::Command::new("cargo")
989 };
990 if !isolated {
991 crate::build_target::command::clear_std(&mut cmd)?;
992 }
993 cmd.args(["metadata", "--no-deps", "--format-version", "1"]);
994 if let Some(m) = manifest_arg {
995 cmd.arg("--manifest-path").arg(m);
996 }
997 let meta = cmd
998 .current_dir(cwd)
999 .quiet()
1000 .output()
1001 .context("run `cargo metadata`")?;
1002 if !meta.status.success() {
1003 bail!(
1004 "cargo metadata failed: {}",
1005 String::from_utf8_lossy(&meta.stderr)
1006 );
1007 }
1008 let names = parse_workspace_package_names(&String::from_utf8_lossy(&meta.stdout));
1009 for name in &names {
1010 let mut clean = if isolated {
1011 crate::build_target::command::cargo(cache_dir)?
1012 } else {
1013 std::process::Command::new("cargo")
1014 };
1015 clean.arg("clean").arg("-p").arg(name);
1016 if let Some(m) = manifest_arg {
1017 clean.arg("--manifest-path").arg(m);
1018 }
1019 if !isolated {
1020 crate::build_target::command::clear_std(&mut clean)?;
1021 clean.arg("--target-dir").arg(cache_dir);
1022 }
1023 let out = clean
1024 .current_dir(cwd)
1025 .quiet()
1026 .output()
1027 .with_context(|| format!("cargo clean -p {name}"))?;
1028 if !out.status.success() {
1029 failed.push(format!(
1038 "{name}: {}",
1039 String::from_utf8_lossy(&out.stderr).trim()
1040 ));
1041 }
1042 }
1043 for n in names {
1044 if !all.contains(&n) {
1045 all.push(n);
1046 }
1047 }
1048 }
1049 if !failed.is_empty() {
1050 bail!(
1051 "cargo clean -p failed for {} package(s): {}",
1052 failed.len(),
1053 failed.join("; ")
1054 );
1055 }
1056 Ok(Some(all))
1057}
1058
1059const CACHEDIR_TAG: &str = "Signature: 8a477f597d28d172789f06886806bc55\n\
1061# This file is a cache directory tag created by cargo.\n\
1062# For information about cache directory tags see https://bford.info/cachedir/\n";
1063
1064fn restore_cachedir_tag(cache_dir: &Path) -> Result<bool> {
1073 use std::io::Write as _;
1074 if !cache_dir.is_dir() || !cache_dir.join(".rustc_info.json").is_file() {
1075 return Ok(false);
1076 }
1077 let tag = cache_dir.join("CACHEDIR.TAG");
1078 match std::fs::OpenOptions::new()
1079 .write(true)
1080 .create_new(true)
1081 .open(&tag)
1082 {
1083 Ok(mut f) => {
1084 f.write_all(CACHEDIR_TAG.as_bytes())
1085 .with_context(|| format!("write {}", tag.display()))?;
1086 Ok(true)
1087 }
1088 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
1089 Err(e) => Err(e).with_context(|| format!("create {}", tag.display())),
1090 }
1091}
1092
1093pub fn ensure_fresh(
1104 home: &Path,
1105 cache_dir: &Path,
1106 identity: &Identity,
1107 manifests: &[Target],
1108) -> Result<()> {
1109 ensure_fresh_with(home, cache_dir, identity, manifests, false)
1110}
1111
1112pub(crate) fn ensure_fresh_with(
1113 home: &Path,
1114 cache_dir: &Path,
1115 identity: &Identity,
1116 manifests: &[Target],
1117 isolated: bool,
1118) -> Result<()> {
1119 match restore_cachedir_tag(cache_dir) {
1120 Ok(true) => tracing::info!(
1121 cache = %cache_dir.display(),
1122 "build cache: restored a missing CACHEDIR.TAG"
1123 ),
1124 Ok(false) => {}
1125 Err(e) => tracing::warn!(error = %e, "build cache: could not restore CACHEDIR.TAG"),
1127 }
1128 if needs_refresh(home, cache_dir, identity) {
1129 let worktree = PathBuf::from(&identity.worktree);
1130 match refresh_stale_packages(&worktree, cache_dir, manifests, isolated)? {
1131 Some(cleaned) => tracing::info!(
1132 ?cleaned,
1133 cache = %cache_dir.display(),
1134 "build cache: source identity changed; cleaned the workspace's own packages before reuse"
1135 ),
1136 None => {
1137 tracing::warn!(
1142 cache = %cache_dir.display(),
1143 "build cache: no Cargo manifest found for the freshness check; skipping the package clean"
1144 );
1145 invalidate_identity(home, cache_dir);
1146 return Ok(());
1147 }
1148 }
1149 }
1150 record_identity(home, cache_dir, identity)
1151}
1152
1153#[cfg(test)]
1154mod tests {
1155 use super::*;
1156
1157 fn owner(pid: u32) -> Owner {
1158 Owner {
1159 run: "r1".to_owned(),
1160 node: "gate".to_owned(),
1161 seat: "gate".to_owned(),
1162 pid,
1163 worktree: "/w".to_owned(),
1164 head: "deadbeef".to_owned(),
1165 }
1166 }
1167
1168 #[test]
1169 fn a_missing_cachedir_tag_is_restored_only_for_a_cargo_target() {
1170 let t = tempfile::TempDir::new().expect("temp");
1171 let cache = t.path().join("cache");
1172 assert!(!restore_cachedir_tag(&cache).expect("missing dir"));
1173 assert!(!cache.exists(), "a missing directory is left for cargo");
1174
1175 std::fs::create_dir_all(&cache).expect("mkdir");
1176 assert!(!restore_cachedir_tag(&cache).expect("no rustc info"));
1177 assert!(!cache.join("CACHEDIR.TAG").exists());
1178
1179 std::fs::write(cache.join(".rustc_info.json"), "{}").expect("info");
1180 assert!(restore_cachedir_tag(&cache).expect("restore"));
1181 let body = std::fs::read_to_string(cache.join("CACHEDIR.TAG")).expect("tag");
1182 assert_eq!(
1183 body.lines().next(),
1184 Some("Signature: 8a477f597d28d172789f06886806bc55")
1185 );
1186
1187 std::fs::write(cache.join("CACHEDIR.TAG"), "custom").expect("custom");
1188 assert!(!restore_cachedir_tag(&cache).expect("existing"));
1189 assert_eq!(
1190 std::fs::read_to_string(cache.join("CACHEDIR.TAG")).expect("tag"),
1191 "custom"
1192 );
1193 }
1194
1195 #[test]
1196 fn an_uncontended_lease_is_acquired_and_freed_on_release() {
1197 let home = tempfile::TempDir::new().expect("temp");
1198 let cache = home.path().join("cache");
1199 let this = std::process::id();
1200 match try_acquire(home.path(), &cache, &owner(this)).expect("acquire") {
1201 AcquireOutcome::Acquired(g) => {
1202 assert!(in_use(home.path(), &cache), "held while the guard lives");
1203 g.release();
1204 }
1205 AcquireOutcome::Busy(b) => panic!("unexpectedly busy: {b:?}"),
1206 }
1207 assert!(!in_use(home.path(), &cache), "freed after release");
1208 }
1209
1210 #[test]
1211 fn a_lease_held_by_a_live_pid_is_reported_active_and_refuses_a_second_acquire() {
1212 let home = tempfile::TempDir::new().expect("temp");
1213 let cache = home.path().join("cache");
1214 let this = std::process::id();
1215 let _first =
1219 try_acquire(home.path(), &cache, &owner(this)).expect("first acquire succeeds");
1220 let mut second_owner = owner(this);
1221 second_owner.run = "r2".to_owned();
1222 match try_acquire(home.path(), &cache, &second_owner).expect("no io error") {
1223 AcquireOutcome::Busy(Busy::Active(held_by)) => assert_eq!(held_by.run, "r1"),
1224 other => panic!("expected Busy::Active, got a different outcome: {other:?}"),
1225 }
1226 assert!(in_use(home.path(), &cache));
1227 }
1228
1229 impl std::fmt::Debug for AcquireOutcome {
1230 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1231 match self {
1232 AcquireOutcome::Acquired(_) => write!(f, "Acquired"),
1233 AcquireOutcome::Busy(b) => write!(f, "Busy({b:?})"),
1234 }
1235 }
1236 }
1237
1238 #[test]
1239 fn a_lease_whose_pid_is_gone_is_stale_and_reclaimed_by_the_next_acquirer() {
1240 let home = tempfile::TempDir::new().expect("temp");
1241 let cache = home.path().join("cache");
1242 let dead_owner = owner(999_999);
1248 let path = lease_path(home.path(), &cache);
1249 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1250 write_new(
1251 &path,
1252 &cache,
1253 &dead_owner,
1254 crate::lock_file::Retry::new(None),
1255 )
1256 .expect("seed a stale lease");
1257 assert_eq!(
1258 classify_with(&path, |_| false),
1259 Status::Stale(dead_owner.clone())
1260 );
1261
1262 match try_acquire_with(home.path(), &cache, &owner(std::process::id()), |_| false)
1263 .expect("acquire")
1264 {
1265 AcquireOutcome::Acquired(_) => {}
1266 other => panic!("stale lease should have been reclaimed: {other:?}"),
1267 }
1268 }
1269
1270 #[test]
1271 fn an_unreadable_lease_is_unknown_and_never_reclaimed() {
1272 let home = tempfile::TempDir::new().expect("temp");
1273 let cache = home.path().join("cache");
1274 let path = lease_path(home.path(), &cache);
1275 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1276 std::fs::write(&path, b"not json").unwrap();
1277 assert_eq!(classify(&path), Status::Unknown);
1278 assert!(in_use(home.path(), &cache), "unknown counts as in use");
1279 match try_acquire(home.path(), &cache, &owner(std::process::id())).expect("no io error") {
1280 AcquireOutcome::Busy(Busy::Unknown) => {}
1281 other => panic!("expected Busy::Unknown, got {other:?}"),
1282 }
1283 }
1284
1285 #[tokio::test]
1286 async fn waiting_for_a_busy_lease_times_out_within_its_own_budget() {
1287 let home = tempfile::TempDir::new().expect("temp");
1288 let cache = home.path().join("cache");
1289 let _held = try_acquire(home.path(), &cache, &owner(std::process::id()))
1290 .expect("acquire")
1291 .pipe();
1292 let mut waiter = owner(std::process::id());
1293 waiter.run = "r2".to_owned();
1294 let started = std::time::Instant::now();
1295 let err = wait_for(
1296 home.path(),
1297 &cache,
1298 &waiter,
1299 Duration::from_millis(150),
1300 Duration::from_millis(20),
1301 )
1302 .await
1303 .expect_err("still held, must time out");
1304 assert!(started.elapsed() < Duration::from_secs(2), "bounded wait");
1305 assert!(
1306 err.to_string().contains("r1"),
1307 "names the current holder: {err}"
1308 );
1309 }
1310
1311 #[tokio::test]
1312 async fn a_wait_succeeds_as_soon_as_the_lease_is_released() {
1313 let home = tempfile::TempDir::new().expect("temp");
1314 let cache = home.path().join("cache");
1315 let guard =
1316 match try_acquire(home.path(), &cache, &owner(std::process::id())).expect("acquire") {
1317 AcquireOutcome::Acquired(g) => g,
1318 AcquireOutcome::Busy(b) => panic!("unexpectedly busy: {b:?}"),
1319 };
1320 let home_path = home.path().to_path_buf();
1321 let cache_path = cache.clone();
1322 let mut waiter = owner(std::process::id());
1323 waiter.run = "r2".to_owned();
1324 let wait = tokio::spawn(async move {
1325 wait_for(
1326 &home_path,
1327 &cache_path,
1328 &waiter,
1329 Duration::from_secs(5),
1330 Duration::from_millis(10),
1331 )
1332 .await
1333 });
1334 tokio::time::sleep(Duration::from_millis(50)).await;
1335 guard.release();
1336 let acquired = wait.await.expect("task").expect("acquire after release");
1337 acquired.release();
1338 }
1339
1340 #[test]
1341 fn inventory_reports_active_stale_and_unknown_but_not_free() {
1342 let home = tempfile::TempDir::new().expect("temp");
1343 let active_cache = home.path().join("active");
1344 let stale_cache = home.path().join("stale");
1345 let unknown_cache = home.path().join("unknown");
1346
1347 let _held =
1348 try_acquire(home.path(), &active_cache, &owner(std::process::id())).expect("acquire");
1349 let stale_path = lease_path(home.path(), &stale_cache);
1350 std::fs::create_dir_all(stale_path.parent().unwrap()).unwrap();
1351 write_new(
1352 &stale_path,
1353 &stale_cache,
1354 &owner(999_999),
1355 crate::lock_file::Retry::new(None),
1356 )
1357 .unwrap();
1358 let unknown_path = lease_path(home.path(), &unknown_cache);
1359 std::fs::write(&unknown_path, b"garbage").unwrap();
1360
1361 let entries = inventory_with(home.path(), |pid| pid == std::process::id());
1366 assert_eq!(entries.len(), 3, "{entries:?}");
1367 let by_dir = |dir: &Path| {
1368 entries
1369 .iter()
1370 .find(|e| e.cache_dir == dir.display().to_string())
1371 .unwrap_or_else(|| panic!("no entry for {}", dir.display()))
1372 };
1373 assert!(matches!(
1374 by_dir(&active_cache).status,
1375 EntryStatus::Active(_)
1376 ));
1377 assert!(matches!(by_dir(&stale_cache).status, EntryStatus::Stale(_)));
1378 let unknown = entries
1383 .iter()
1384 .find(|e| matches!(e.status, EntryStatus::Unknown))
1385 .unwrap_or_else(|| panic!("no Unknown entry: {entries:?}"));
1386 assert!(
1387 unknown
1388 .cache_dir
1389 .contains(&unknown_path.display().to_string()),
1390 "{unknown:?}"
1391 );
1392 }
1393
1394 #[test]
1395 fn a_released_lease_is_reported_idle_from_the_catalog_not_dropped_entirely() {
1396 let home = tempfile::TempDir::new().expect("temp");
1397 let cache = home.path().join("cache");
1398 let this = std::process::id();
1399
1400 match try_acquire(home.path(), &cache, &owner(this)).expect("acquire") {
1401 AcquireOutcome::Acquired(g) => g.release(),
1402 AcquireOutcome::Busy(b) => panic!("unexpectedly busy: {b:?}"),
1403 }
1404
1405 assert!(!in_use(home.path(), &cache));
1410 let entries = inventory_with(home.path(), |pid| pid == this);
1411 let entry = entries
1412 .iter()
1413 .find(|e| e.cache_dir == cache.display().to_string())
1414 .unwrap_or_else(|| panic!("no entry for a released cache: {entries:?}"));
1415 match &entry.status {
1416 EntryStatus::Idle(o) => assert_eq!(o.run, "r1"),
1417 other => panic!("expected Idle, got {other:?}"),
1418 }
1419 }
1420
1421 #[test]
1422 fn reacquiring_a_released_cache_reports_active_not_idle() {
1423 let home = tempfile::TempDir::new().expect("temp");
1424 let cache = home.path().join("cache");
1425 let this = std::process::id();
1426 match try_acquire(home.path(), &cache, &owner(this)).expect("acquire") {
1427 AcquireOutcome::Acquired(g) => g.release(),
1428 AcquireOutcome::Busy(b) => panic!("unexpectedly busy: {b:?}"),
1429 }
1430 let _held = try_acquire(home.path(), &cache, &owner(this)).expect("reacquire");
1431 let entries = inventory_with(home.path(), |pid| pid == this);
1432 assert_eq!(
1433 entries.len(),
1434 1,
1435 "the catalog row must not duplicate the live lease: {entries:?}"
1436 );
1437 assert!(matches!(entries[0].status, EntryStatus::Active(_)));
1438 }
1439
1440 #[test]
1441 fn maintenance_prune_refuses_a_cache_a_live_owner_holds() {
1442 let home = tempfile::TempDir::new().expect("temp");
1443 let cache = home.path().join("cache");
1444 std::fs::create_dir_all(&cache).unwrap();
1445 std::fs::write(cache.join("big"), vec![0u8; 100]).unwrap();
1446 let _held = try_acquire(home.path(), &cache, &owner(std::process::id())).expect("acquire");
1447
1448 let result = maintenance_prune(home.path(), &cache, 1).expect("no io error");
1449 assert!(
1450 result.is_none(),
1451 "must not prune while a live owner holds it"
1452 );
1453 assert!(cache.join("big").exists(), "nothing was deleted");
1454 }
1455
1456 #[test]
1457 fn maintenance_prune_acts_once_the_cache_is_free_and_releases_after() {
1458 let home = tempfile::TempDir::new().expect("temp");
1459 let cache = home.path().join("cache");
1460 std::fs::create_dir_all(&cache).unwrap();
1461 std::fs::write(cache.join("big"), vec![0u8; 100]).unwrap();
1462
1463 let pruned = maintenance_prune(home.path(), &cache, 1)
1464 .expect("no io error")
1465 .expect("cache was free");
1466 assert!(pruned.freed > 0);
1467 assert!(
1468 !in_use(home.path(), &cache),
1469 "the maintenance lease was released"
1470 );
1471 }
1472
1473 #[test]
1474 fn identity_drift_is_detected_once_and_then_settles() {
1475 let home = tempfile::TempDir::new().expect("temp");
1476 let cache = home.path().join("cache");
1477 let a = Identity {
1478 worktree: "/w/a".to_owned(),
1479 head: "aaaa".to_owned(),
1480 };
1481 let b = Identity {
1482 worktree: "/w/b".to_owned(),
1483 head: "bbbb".to_owned(),
1484 };
1485 assert!(
1486 needs_refresh(home.path(), &cache, &a),
1487 "nothing recorded yet"
1488 );
1489 record_identity(home.path(), &cache, &a).expect("record");
1490 assert!(
1491 !needs_refresh(home.path(), &cache, &a),
1492 "same identity, no refresh needed"
1493 );
1494 assert!(needs_refresh(home.path(), &cache, &b), "different source");
1495 record_identity(home.path(), &cache, &b).expect("record");
1496 assert!(!needs_refresh(home.path(), &cache, &b));
1497 }
1498
1499 #[test]
1500 fn invalidating_forgets_a_recorded_identity_so_the_next_check_refreshes() {
1501 let home = tempfile::TempDir::new().expect("temp");
1502 let cache = home.path().join("cache");
1503 let a = Identity {
1504 worktree: "/w/a".to_owned(),
1505 head: "aaaa".to_owned(),
1506 };
1507 record_identity(home.path(), &cache, &a).expect("record");
1508 assert!(!needs_refresh(home.path(), &cache, &a));
1509
1510 invalidate_identity(home.path(), &cache);
1515 assert!(
1516 needs_refresh(home.path(), &cache, &a),
1517 "invalidation must not be skippable by asking about the same identity again"
1518 );
1519
1520 invalidate_identity(home.path(), &home.path().join("never-recorded"));
1523 }
1524
1525 #[test]
1526 fn workspace_package_names_are_read_from_cargo_metadata_json() {
1527 let fixture = r#"{
1528 "packages": [
1529 {"name": "magi", "version": "0.1.0"},
1530 {"name": "magi-cli", "version": "0.1.0"}
1531 ],
1532 "workspace_members": []
1533 }"#;
1534 let mut names = parse_workspace_package_names(fixture);
1535 names.sort();
1536 assert_eq!(names, vec!["magi".to_owned(), "magi-cli".to_owned()]);
1537 assert_eq!(
1538 parse_workspace_package_names("not json"),
1539 Vec::<String>::new()
1540 );
1541 assert_eq!(parse_workspace_package_names("{}"), Vec::<String>::new());
1542 }
1543
1544 #[test]
1545 fn slugs_are_stable_and_filesystem_safe() {
1546 let a = slug(Path::new(r"C:\Users\op\Temp\magi-target"));
1547 let b = slug(Path::new(r"C:\Users\op\Temp\magi-target"));
1548 assert_eq!(a, b, "same input, same slug");
1549 assert!(
1550 a.chars()
1551 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'),
1552 "filesystem-safe: {a}"
1553 );
1554 }
1555
1556 #[test]
1557 fn busy_active_describes_the_holder() {
1558 let b = Busy::Active(owner(123));
1559 let s = b.describe();
1560 assert!(
1561 s.contains("r1") && s.contains("gate") && s.contains("123"),
1562 "{s}"
1563 );
1564 }
1565
1566 trait Pipe: Sized {
1567 fn pipe(self) -> Guard;
1568 }
1569 impl Pipe for AcquireOutcome {
1570 fn pipe(self) -> Guard {
1571 match self {
1572 AcquireOutcome::Acquired(g) => g,
1573 AcquireOutcome::Busy(b) => panic!("expected Acquired, got Busy({b:?})"),
1574 }
1575 }
1576 }
1577
1578 fn cmds(v: &[&str]) -> Vec<String> {
1579 v.iter().map(|s| (*s).to_owned()).collect()
1580 }
1581
1582 #[test]
1583 fn manifest_paths_are_read_in_every_spelling() {
1584 let got = extract_manifest_paths(&cmds(&[
1585 "cargo test --manifest-path tools/a/Cargo.toml",
1586 "cargo build --manifest-path=tools/b/Cargo.toml --release",
1587 "cargo fmt --manifest-path 'q q/Cargo.toml'",
1588 "cargo clippy --manifest-path \"d/Cargo.toml\" && cargo test --manifest-path tools/a/Cargo.toml",
1589 ]));
1590 let want: Vec<PathBuf> = [
1591 "tools/a/Cargo.toml",
1592 "tools/b/Cargo.toml",
1593 "q q/Cargo.toml",
1594 "d/Cargo.toml",
1595 ]
1596 .iter()
1597 .map(PathBuf::from)
1598 .collect();
1599 assert_eq!(got, want);
1600 assert!(extract_manifest_paths(&cmds(&["cargo test", "cd x && cargo test"])).is_empty());
1601 }
1602
1603 #[test]
1604 fn plan_targets_covers_blog_root_both_and_none() {
1605 let w = Path::new("/w");
1606 let only = |set: &'static [&'static str]| {
1607 move |p: &Path| Ok(set.iter().any(|s| p == Path::new(s)))
1608 };
1609 let m = vec![Target::Manifest(PathBuf::from(
1610 "tools/postprocess/Cargo.toml",
1611 ))];
1612 let blog = plan_targets(w, &m, only(&["/w/tools/postprocess/Cargo.toml"])).unwrap();
1613 assert_eq!(
1614 blog,
1615 vec![Target::Manifest(PathBuf::from(
1616 "/w/tools/postprocess/Cargo.toml"
1617 ))]
1618 );
1619 let root = plan_targets(w, &[], only(&["/w/Cargo.toml"])).unwrap();
1620 assert_eq!(root, vec![Target::Root]);
1621 let both = plan_targets(
1622 w,
1623 &m,
1624 only(&["/w/Cargo.toml", "/w/tools/postprocess/Cargo.toml"]),
1625 )
1626 .unwrap();
1627 assert_eq!(both.len(), 2);
1628 assert_eq!(both[0], Target::Root);
1629 assert!(plan_targets(w, &m, only(&[])).unwrap().is_empty());
1630 assert!(plan_targets(w, &[], only(&[])).unwrap().is_empty());
1631 }
1632
1633 #[test]
1634 fn subdirectory_refresh_targets_keep_cargo_working_directory() {
1635 let wt = tempfile::tempdir().unwrap();
1636 let sub = wt.path().join("src-tauri");
1637 std::fs::create_dir(&sub).unwrap();
1638 std::fs::write(sub.join("Cargo.toml"), "").unwrap();
1639 let requested = [
1640 Target::Directory("src-tauri".into()),
1641 Target::Directory("deleted".into()),
1642 ];
1643 let targets = plan_targets(wt.path(), &requested, file_exists).unwrap();
1644 assert_eq!(
1645 targets,
1646 [Target::Directory(
1647 crate::build_target::command::resolve_dir(wt.path(), Path::new("src-tauri"))
1648 .unwrap()
1649 )]
1650 );
1651 }
1652
1653 #[test]
1654 fn a_repo_without_a_reachable_manifest_passes_untouched() {
1655 let home = tempfile::TempDir::new().expect("temp");
1656 let wt = tempfile::TempDir::new().expect("temp");
1657 std::fs::create_dir_all(wt.path().join("sub")).unwrap();
1659 std::fs::write(wt.path().join("sub/Cargo.toml"), "").unwrap();
1660 let cache = home.path().join("cache");
1661 std::fs::create_dir_all(&cache).unwrap();
1662 std::fs::write(cache.join("artifact"), "x").unwrap();
1663 let old = Identity {
1664 worktree: "/w/old".to_owned(),
1665 head: "old".to_owned(),
1666 };
1667 record_identity(home.path(), &cache, &old).unwrap();
1668 let id = Identity::new(wt.path(), "head");
1669 ensure_fresh(home.path(), &cache, &id, &[]).expect("must not fail");
1670 assert_eq!(
1671 std::fs::read_to_string(cache.join("artifact")).unwrap(),
1672 "x"
1673 );
1674 assert!(
1675 needs_refresh(home.path(), &cache, &old),
1676 "identity was invalidated, not recorded"
1677 );
1678 assert!(needs_refresh(home.path(), &cache, &id));
1679 }
1680}