1#![doc = include_str!("../README.md")]
2#![warn(missing_docs)]
3
4mod constants;
5
6#[cfg(feature = "process-scoped-cache")]
7use std::cell::Cell;
8use std::env;
9use std::fs;
10use std::fs::OpenOptions;
11use std::io;
12use std::path::{Path, PathBuf};
13#[cfg(feature = "process-scoped-cache")]
14use std::sync::atomic::{AtomicU64, Ordering};
15use std::time::{Duration, SystemTime, UNIX_EPOCH};
16
17use constants::{CACHE_DIR_NAME, CARGO_TOML_FILE_NAME};
18#[cfg(feature = "os-cache-dir")]
19use directories::ProjectDirs;
20#[cfg(feature = "process-scoped-cache")]
21use tempfile::{Builder, TempDir};
22
23#[cfg(feature = "os-cache-dir")]
24fn project_dirs_or_not_found(project_dirs: Option<ProjectDirs>) -> io::Result<ProjectDirs> {
25 project_dirs.ok_or_else(|| {
26 io::Error::new(
27 io::ErrorKind::NotFound,
28 "could not resolve an OS cache directory for the provided project identity",
29 )
30 })
31}
32
33#[derive(Clone, Debug, PartialEq, Eq, Default)]
44pub struct EvictPolicy {
45 pub max_files: Option<usize>,
50 pub max_bytes: Option<u64>,
60 pub max_age: Option<Duration>,
64}
65
66#[derive(Clone, Debug, PartialEq, Eq, Default)]
68pub struct EvictionReport {
69 pub marked_for_eviction: Vec<PathBuf>,
71}
72
73#[derive(Clone, Debug)]
74struct FileEntry {
75 path: PathBuf,
76 modified: SystemTime,
77 len: u64,
78}
79
80#[derive(Clone, Debug, PartialEq, Eq)]
81pub struct CacheRoot {
87 root: PathBuf,
88}
89
90impl CacheRoot {
91 pub fn from_discovery() -> io::Result<Self> {
104 let cwd = env::current_dir()?;
105 let anchor = find_crate_root(&cwd).unwrap_or(cwd);
106 let anchor = anchor.canonicalize().unwrap_or(anchor);
110 let root = anchor.join(CACHE_DIR_NAME);
111 Ok(Self { root })
112 }
113
114 pub fn from_root<P: Into<PathBuf>>(root: P) -> Self {
116 Self { root: root.into() }
117 }
118
119 #[cfg(feature = "os-cache-dir")]
142 pub fn from_project_dirs(
143 qualifier: &str,
144 organization: &str,
145 application: &str,
146 ) -> io::Result<Self> {
147 let project_dirs =
148 project_dirs_or_not_found(ProjectDirs::from(qualifier, organization, application))?;
149
150 Ok(Self {
151 root: project_dirs.cache_dir().to_path_buf(),
152 })
153 }
154
155 #[cfg(feature = "process-scoped-cache")]
166 pub fn from_tempdir() -> io::Result<Self> {
167 let root = TempDir::new()?.keep();
168 Ok(Self { root })
169 }
170
171 pub fn path(&self) -> &Path {
173 &self.root
174 }
175
176 pub fn group<P: AsRef<Path>>(&self, relative_group: P) -> CacheGroup {
185 let path = self.root.join(relative_group.as_ref());
186 CacheGroup { path }
187 }
188
189 pub fn group_path<P: AsRef<Path>>(&self, relative_group: P) -> PathBuf {
191 self.root.join(relative_group.as_ref())
192 }
193
194 pub fn ensure_group<P: AsRef<Path>>(&self, relative_group: P) -> io::Result<PathBuf> {
196 self.ensure_group_with_policy(relative_group, None)
197 }
198
199 pub fn ensure_group_with_policy<P: AsRef<Path>>(
204 &self,
205 relative_group: P,
206 policy: Option<&EvictPolicy>,
207 ) -> io::Result<PathBuf> {
208 let group = self.group(relative_group);
209 group.ensure_dir_with_policy(policy)?;
210 Ok(group.path().to_path_buf())
211 }
212
213 pub fn cache_path<P: AsRef<Path>, Q: AsRef<Path>>(
217 &self,
218 cache_dir: P,
219 relative_path: Q,
220 ) -> PathBuf {
221 let rel = relative_path.as_ref();
222 if rel.is_absolute() {
223 return rel.to_path_buf();
224 }
225 self.group(cache_dir).entry_path(rel)
226 }
227}
228
229#[derive(Clone, Copy, Debug, PartialEq, Eq)]
234pub enum CacheSource {
235 Explicit,
237 EnvVar,
239 ProjectDiscovery,
241 OsCacheDir,
243 CwdFallback,
246}
247
248#[derive(Clone, Debug)]
270pub struct CacheResolver {
271 pub explicit: Option<PathBuf>,
273 pub env_var: Option<String>,
276 pub allow_project_discovery: bool,
278 #[cfg(feature = "os-cache-dir")]
282 pub project_dirs: Option<(String, String, String)>,
283 pub allow_cwd_fallback: bool,
287}
288
289impl Default for CacheResolver {
290 fn default() -> Self {
291 Self {
292 explicit: None,
293 env_var: None,
294 allow_project_discovery: true,
295 #[cfg(feature = "os-cache-dir")]
296 project_dirs: None,
297 allow_cwd_fallback: false,
298 }
299 }
300}
301
302impl CacheResolver {
303 pub fn resolve(&self) -> io::Result<(CacheRoot, CacheSource)> {
305 if let Some(p) = &self.explicit {
307 return Ok((CacheRoot::from_root(p.clone()), CacheSource::Explicit));
308 }
309 if let Some(name) = &self.env_var
311 && let Ok(v) = env::var(name)
312 && !v.is_empty()
313 {
314 return Ok((CacheRoot::from_root(v), CacheSource::EnvVar));
315 }
316 if self.allow_project_discovery
320 && let Some(anchor) = discover_anchor()?
321 {
322 return Ok((
323 CacheRoot {
324 root: anchor.join(CACHE_DIR_NAME),
325 },
326 CacheSource::ProjectDiscovery,
327 ));
328 }
329 #[cfg(feature = "os-cache-dir")]
331 if let Some((q, o, a)) = &self.project_dirs {
332 let dirs = project_dirs_or_not_found(ProjectDirs::from(q, o, a))?;
333 return Ok((
334 CacheRoot {
335 root: dirs.cache_dir().to_path_buf(),
336 },
337 CacheSource::OsCacheDir,
338 ));
339 }
340 if self.allow_cwd_fallback {
342 let cwd = env::current_dir()?;
343 let anchor = cwd.canonicalize().unwrap_or(cwd);
344 return Ok((
345 CacheRoot {
346 root: anchor.join(CACHE_DIR_NAME),
347 },
348 CacheSource::CwdFallback,
349 ));
350 }
351 Err(io::Error::new(
352 io::ErrorKind::NotFound,
353 format!(
354 "no cache location: {}{}; no OS cache identity is configured",
355 if self.allow_project_discovery {
356 "no Cargo workspace above the working directory"
357 } else {
358 "project discovery is disabled"
359 },
360 match &self.env_var {
361 Some(n) => format!(" and ${n} is unset"),
362 None => " and no env-var override is configured".to_string(),
363 },
364 ),
365 ))
366 }
367}
368
369fn discover_anchor() -> io::Result<Option<PathBuf>> {
373 let cwd = env::current_dir()?;
374 Ok(find_crate_root(&cwd).map(|a| a.canonicalize().unwrap_or(a)))
375}
376
377#[derive(Clone, Debug, PartialEq, Eq)]
378pub struct CacheGroup {
383 path: PathBuf,
384}
385
386impl CacheGroup {
387 pub fn path(&self) -> &Path {
389 &self.path
390 }
391
392 pub fn ensure_dir(&self) -> io::Result<&Path> {
394 self.ensure_dir_with_policy(None)
395 }
396
397 pub fn ensure_dir_with_policy(&self, policy: Option<&EvictPolicy>) -> io::Result<&Path> {
403 fs::create_dir_all(&self.path)?;
404 if let Some(policy) = policy {
405 apply_evict_policy(&self.path, policy)?;
406 }
407 Ok(&self.path)
408 }
409
410 pub fn eviction_report(&self, policy: &EvictPolicy) -> io::Result<EvictionReport> {
419 build_eviction_report(&self.path, policy)
420 }
421
422 pub fn subgroup<P: AsRef<Path>>(&self, relative_group: P) -> Self {
424 Self {
425 path: self.path.join(relative_group.as_ref()),
426 }
427 }
428
429 pub fn entry_path<P: AsRef<Path>>(&self, relative_file: P) -> PathBuf {
431 self.path.join(relative_file.as_ref())
432 }
433
434 pub fn touch<P: AsRef<Path>>(&self, relative_file: P) -> io::Result<PathBuf> {
437 let entry = self.entry_path(relative_file);
438 if let Some(parent) = entry.parent() {
439 fs::create_dir_all(parent)?;
440 }
441 OpenOptions::new().create(true).append(true).open(&entry)?;
442 Ok(entry)
443 }
444}
445
446#[cfg(feature = "process-scoped-cache")]
459#[derive(Debug)]
460pub struct ProcessScopedCacheGroup {
461 process_group: CacheGroup,
462 _temp_dir: TempDir,
463}
464
465#[cfg(feature = "process-scoped-cache")]
466impl ProcessScopedCacheGroup {
467 pub fn new<P: AsRef<Path>>(root: &CacheRoot, relative_group: P) -> io::Result<Self> {
469 Self::from_group(root.group(relative_group))
470 }
471
472 pub fn from_group(base_group: CacheGroup) -> io::Result<Self> {
474 base_group.ensure_dir()?;
475 let pid = std::process::id();
476 let temp_dir = Builder::new()
477 .prefix(&format!("pid-{pid}-"))
478 .tempdir_in(base_group.path())?;
479 let process_group = CacheGroup {
480 path: temp_dir.path().to_path_buf(),
481 };
482
483 Ok(Self {
484 process_group,
485 _temp_dir: temp_dir,
486 })
487 }
488
489 pub fn path(&self) -> &Path {
491 self.process_group.path()
492 }
493
494 pub fn process_group(&self) -> CacheGroup {
496 self.process_group.clone()
497 }
498
499 pub fn thread_group(&self) -> CacheGroup {
504 self.process_group
505 .subgroup(format!("thread-{}", current_thread_cache_group_id()))
506 }
507
508 pub fn ensure_thread_group(&self) -> io::Result<CacheGroup> {
510 let group = self.thread_group();
511 group.ensure_dir()?;
512 Ok(group)
513 }
514
515 pub fn thread_entry_path<P: AsRef<Path>>(&self, relative_file: P) -> PathBuf {
517 self.thread_group().entry_path(relative_file)
518 }
519
520 pub fn touch_thread_entry<P: AsRef<Path>>(&self, relative_file: P) -> io::Result<PathBuf> {
522 self.ensure_thread_group()?.touch(relative_file)
523 }
524}
525
526#[cfg(feature = "process-scoped-cache")]
527fn current_thread_cache_group_id() -> u64 {
528 thread_local! {
529 static THREAD_GROUP_ID: Cell<Option<u64>> = const { Cell::new(None) };
530 }
531
532 static NEXT_THREAD_GROUP_ID: AtomicU64 = AtomicU64::new(1);
533
534 THREAD_GROUP_ID.with(|slot| {
535 if let Some(id) = slot.get() {
536 id
537 } else {
538 let id = NEXT_THREAD_GROUP_ID.fetch_add(1, Ordering::Relaxed);
539 slot.set(Some(id));
540 id
541 }
542 })
543}
544
545fn find_crate_root(start: &Path) -> Option<PathBuf> {
546 let mut current = start.to_path_buf();
547 let mut nearest: Option<PathBuf> = None;
548 loop {
549 let cargo_path = current.join(CARGO_TOML_FILE_NAME);
550 if cargo_path.is_file() {
551 if nearest.is_none() {
552 nearest = Some(current.clone());
553 }
554 if let Ok(content) = fs::read_to_string(&cargo_path)
555 && content.lines().any(|line| line.trim() == "[workspace]")
556 {
557 return Some(current);
558 }
559 }
560 if !current.pop() {
561 return nearest;
562 }
563 }
564}
565
566fn apply_evict_policy(root: &Path, policy: &EvictPolicy) -> io::Result<()> {
567 let report = build_eviction_report(root, policy)?;
568
569 for path in report.marked_for_eviction {
570 let _ = fs::remove_file(path);
571 }
572
573 Ok(())
574}
575
576fn sort_entries_oldest_first(entries: &mut [FileEntry]) {
577 entries.sort_by(|a, b| {
578 let ta = a
579 .modified
580 .duration_since(UNIX_EPOCH)
581 .unwrap_or(Duration::ZERO);
582 let tb = b
583 .modified
584 .duration_since(UNIX_EPOCH)
585 .unwrap_or(Duration::ZERO);
586 ta.cmp(&tb).then_with(|| a.path.cmp(&b.path))
587 });
588}
589
590fn build_eviction_report(root: &Path, policy: &EvictPolicy) -> io::Result<EvictionReport> {
591 let mut entries = collect_files(root)?;
592 let mut marked_for_eviction = Vec::new();
593
594 if let Some(max_age) = policy.max_age {
595 let now = SystemTime::now();
596 let mut survivors = Vec::with_capacity(entries.len());
597 for entry in entries {
598 let age = now.duration_since(entry.modified).unwrap_or(Duration::ZERO);
599 if age >= max_age {
600 marked_for_eviction.push(entry.path);
601 } else {
602 survivors.push(entry);
603 }
604 }
605 entries = survivors;
606 }
607
608 sort_entries_oldest_first(&mut entries);
609
610 if let Some(max_files) = policy.max_files
611 && entries.len() > max_files
612 {
613 let to_remove = entries.len() - max_files;
614 for entry in entries.iter().take(to_remove) {
615 marked_for_eviction.push(entry.path.clone());
616 }
617 entries = entries.into_iter().skip(to_remove).collect();
618 sort_entries_oldest_first(&mut entries);
619 }
620
621 if let Some(max_bytes) = policy.max_bytes {
622 let mut total: u64 = entries.iter().map(|e| e.len).sum();
623 if total > max_bytes {
624 for entry in &entries {
625 if total <= max_bytes {
626 break;
627 }
628 marked_for_eviction.push(entry.path.clone());
629 total = total.saturating_sub(entry.len);
630 }
631 }
632 }
633
634 Ok(EvictionReport {
635 marked_for_eviction,
636 })
637}
638
639fn collect_files(root: &Path) -> io::Result<Vec<FileEntry>> {
640 let mut out = Vec::new();
641 collect_files_recursive(root, &mut out)?;
642 Ok(out)
643}
644
645fn collect_files_recursive(dir: &Path, out: &mut Vec<FileEntry>) -> io::Result<()> {
646 for entry in fs::read_dir(dir)? {
647 let entry = entry?;
648 let path = entry.path();
649 let meta = entry.metadata()?;
650 if meta.is_dir() {
651 collect_files_recursive(&path, out)?;
652 } else if meta.is_file() {
653 out.push(FileEntry {
654 path,
655 modified: meta.modified().unwrap_or(UNIX_EPOCH),
656 len: meta.len(),
657 });
658 }
659 }
660 Ok(())
661}
662
663#[cfg(test)]
664mod tests {
665 use super::*;
666 use std::collections::BTreeSet;
667 use std::sync::{Mutex, MutexGuard, OnceLock};
675 use tempfile::TempDir;
676
677 fn cwd_lock() -> &'static Mutex<()> {
681 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
682 LOCK.get_or_init(|| Mutex::new(()))
683 }
684
685 struct CwdGuard {
690 previous: PathBuf,
691 _cwd_lock: MutexGuard<'static, ()>,
694 }
695
696 impl CwdGuard {
697 fn swap_to(path: &Path) -> io::Result<Self> {
698 let cwd_lock_guard = cwd_lock().lock().expect("acquire cwd test lock");
701 let previous = env::current_dir()?;
702 env::set_current_dir(path)?;
703 Ok(Self {
704 previous,
705 _cwd_lock: cwd_lock_guard,
706 })
707 }
708 }
709
710 impl Drop for CwdGuard {
711 fn drop(&mut self) {
712 let _ = env::set_current_dir(&self.previous);
713 }
714 }
715
716 #[test]
717 fn from_discovery_uses_cwd_dot_cache_when_no_cargo_toml() {
718 let tmp = TempDir::new().expect("tempdir");
719 let _guard = CwdGuard::swap_to(tmp.path()).expect("set cwd");
720
721 let cache = CacheRoot::from_discovery().expect("discover");
722 let got = cache.path().to_path_buf();
723 let expected = tmp
724 .path()
725 .canonicalize()
726 .expect("canonicalize temp path")
727 .join(CACHE_DIR_NAME);
728 assert_eq!(got, expected);
729 }
730
731 #[test]
732 fn from_discovery_prefers_nearest_crate_root() {
733 let tmp = TempDir::new().expect("tempdir");
734 let crate_root = tmp.path().join("workspace");
735 let nested = crate_root.join("src").join("nested");
736 fs::create_dir_all(&nested).expect("create nested");
737 fs::write(
738 crate_root.join(CARGO_TOML_FILE_NAME),
739 "[package]\nname='x'\nversion='0.1.0'\nedition='2024'\n",
740 )
741 .expect("write cargo");
742
743 let _guard = CwdGuard::swap_to(&nested).expect("set cwd");
744 let cache = CacheRoot::from_discovery().expect("discover");
745 let got = cache.path().to_path_buf();
746 let expected = crate_root
747 .canonicalize()
748 .expect("canonicalize crate root")
749 .join(CACHE_DIR_NAME);
750 assert_eq!(got, expected);
751 }
752
753 #[test]
754 fn from_discovery_prefers_workspace_root_over_subcrate() {
755 let tmp = TempDir::new().expect("tempdir");
756 let workspace_root = tmp.path().join("workspace");
757 let sub_crate = workspace_root.join("crates").join("my-crate");
758 fs::create_dir_all(&sub_crate).expect("create sub-crate");
759 fs::write(
761 workspace_root.join(CARGO_TOML_FILE_NAME),
762 "[workspace]\n[package]\nname='workspace-root'\nversion='0.1.0'\nedition='2024'\n",
763 )
764 .expect("write workspace Cargo.toml");
765 fs::write(
767 sub_crate.join(CARGO_TOML_FILE_NAME),
768 "[package]\nname='my-crate'\nversion='0.1.0'\nedition='2024'\n",
769 )
770 .expect("write sub-crate Cargo.toml");
771
772 let _guard = CwdGuard::swap_to(&sub_crate).expect("set cwd");
773 let cache = CacheRoot::from_discovery().expect("discover");
774 let got = cache.path().to_path_buf();
775 let expected = workspace_root
776 .canonicalize()
777 .expect("canonicalize workspace root")
778 .join(CACHE_DIR_NAME);
779 assert_eq!(got, expected);
780 }
781
782 #[cfg(unix)]
783 #[test]
784 fn from_discovery_skips_permission_denied_cargo_toml_and_falls_back_to_cwd() {
785 use std::os::unix::fs::PermissionsExt;
786
787 let tmp = TempDir::new().expect("tempdir");
788 fs::write(tmp.path().join(CARGO_TOML_FILE_NAME), "[workspace]").expect("write Cargo.toml");
789 fs::set_permissions(
792 tmp.path().join(CARGO_TOML_FILE_NAME),
793 std::fs::Permissions::from_mode(0o000),
794 )
795 .expect("set permissions");
796
797 let _guard = CwdGuard::swap_to(tmp.path()).expect("set cwd");
798 let cache = CacheRoot::from_discovery().expect("discover");
799 let expected = tmp
801 .path()
802 .canonicalize()
803 .expect("canonicalize")
804 .join(CACHE_DIR_NAME);
805 assert_eq!(cache.path(), expected);
806
807 fs::set_permissions(
809 tmp.path().join(CARGO_TOML_FILE_NAME),
810 std::fs::Permissions::from_mode(0o644),
811 )
812 .expect("restore permissions");
813 }
814
815 #[test]
816 fn from_root_supports_arbitrary_path_and_grouping() {
817 let tmp = TempDir::new().expect("tempdir");
818 let root = CacheRoot::from_root(tmp.path().join("custom-cache-root"));
819 let group = root.group("taxonomy/v1");
820
821 assert_eq!(group.path(), root.path().join("taxonomy/v1").as_path());
822 }
823
824 #[test]
825 fn group_path_building_and_dir_creation() {
826 let tmp = TempDir::new().expect("tempdir");
827 let cache = CacheRoot::from_root(tmp.path());
828 let group = cache.group("artifacts/json");
829
830 let nested_group = group.subgroup("v1");
831 let ensured = nested_group.ensure_dir().expect("ensure nested dir");
832 let expected_group_suffix = Path::new("artifacts").join("json").join("v1");
833 assert!(ensured.ends_with(&expected_group_suffix));
834 assert!(ensured.exists());
835
836 let entry = nested_group.entry_path("a/b/cache.json");
837 let expected_entry_suffix = Path::new("artifacts")
838 .join("json")
839 .join("v1")
840 .join("a")
841 .join("b")
842 .join("cache.json");
843 assert!(entry.ends_with(&expected_entry_suffix));
844 }
845
846 #[test]
847 fn touch_creates_blank_file_and_is_idempotent() {
848 let tmp = TempDir::new().expect("tempdir");
849 let cache = CacheRoot::from_root(tmp.path());
850 let group = cache.group("artifacts/json");
851
852 let touched = group.touch("a/b/cache.json").expect("touch file");
853 assert!(touched.exists());
854 let meta = fs::metadata(&touched).expect("metadata");
855 assert_eq!(meta.len(), 0);
856
857 let touched_again = group.touch("a/b/cache.json").expect("touch file again");
858 assert_eq!(touched_again, touched);
859 let meta_again = fs::metadata(&touched_again).expect("metadata again");
860 assert_eq!(meta_again.len(), 0);
861 }
862
863 #[test]
864 fn touch_with_root_group_and_empty_relative_path_errors() {
865 let root = CacheRoot::from_root("/");
866 let group = root.group("");
867
868 let result = group.touch("");
869 assert!(result.is_err());
870 }
871
872 #[test]
873 fn from_discovery_cache_path_uses_root_and_group() {
874 let tmp = TempDir::new().expect("tempdir");
875 let crate_root = tmp.path().join("workspace");
876 let nested = crate_root.join("src").join("nested");
877 fs::create_dir_all(&nested).expect("create nested");
878 fs::write(
879 crate_root.join(CARGO_TOML_FILE_NAME),
880 "[package]\nname='x'\nversion='0.1.0'\nedition='2024'\n",
881 )
882 .expect("write cargo");
883
884 let _guard = CwdGuard::swap_to(&nested).expect("set cwd");
885 let p = CacheRoot::from_discovery()
886 .expect("discover")
887 .cache_path("taxonomy", "taxonomy_cache.json");
888 let parent = p.parent().expect("cache path parent");
889 fs::create_dir_all(parent).expect("create cache parent");
890 let expected_dir = crate_root.join(CACHE_DIR_NAME).join("taxonomy");
894 fs::create_dir_all(&expected_dir).expect("create expected cache parent");
895 let got_parent = p
896 .parent()
897 .expect("cache path parent")
898 .canonicalize()
899 .expect("canonicalize cache parent");
900 let expected_parent = crate_root
901 .join(CACHE_DIR_NAME)
902 .join("taxonomy")
903 .canonicalize()
904 .expect("canonicalize expected parent");
905 assert_eq!(got_parent, expected_parent);
906 assert_eq!(
907 p.file_name().and_then(|s| s.to_str()),
908 Some("taxonomy_cache.json")
909 );
910 }
911
912 #[test]
913 fn from_discovery_ignores_other_custom_cache_dir_names() {
914 let tmp = TempDir::new().expect("tempdir");
915 let crate_root = tmp.path().join("workspace");
916 let nested = crate_root.join("src").join("nested");
917 fs::create_dir_all(&nested).expect("create nested");
918 fs::write(
919 crate_root.join(CARGO_TOML_FILE_NAME),
920 "[package]\nname='x'\nversion='0.1.0'\nedition='2024'\n",
921 )
922 .expect("write cargo");
923
924 fs::create_dir_all(crate_root.join(".cache-v2")).expect("create custom cache dir");
926
927 let _guard = CwdGuard::swap_to(&nested).expect("set cwd");
928 let cache = CacheRoot::from_discovery().expect("discover");
929
930 let expected = crate_root
932 .canonicalize()
933 .expect("canonicalize crate root")
934 .join(CACHE_DIR_NAME);
935 assert_eq!(cache.path(), expected);
936 }
937
938 #[test]
939 fn cache_path_preserves_absolute_paths() {
940 let root = CacheRoot::from_root("/tmp/project");
941 let absolute = PathBuf::from("/tmp/custom/cache.json");
942 let resolved = root.cache_path(CACHE_DIR_NAME, &absolute);
943 assert_eq!(resolved, absolute);
944 }
945
946 struct EnvGuard {
957 name: String,
958 prior: Option<String>,
959 }
960
961 impl EnvGuard {
962 fn take(name: &str) -> Self {
963 Self {
964 name: name.to_string(),
965 prior: env::var(name).ok(),
966 }
967 }
968 }
969
970 impl Drop for EnvGuard {
971 fn drop(&mut self) {
972 unsafe {
977 match &self.prior {
978 Some(v) => env::set_var(&self.name, v),
979 None => env::remove_var(&self.name),
980 }
981 }
982 }
983 }
984
985 #[test]
986 fn resolver_explicit_wins_over_everything() {
987 let tmp = TempDir::new().expect("tempdir");
988 let _guard = CwdGuard::swap_to(tmp.path()).expect("set cwd");
989 let name = "CACHE_MANAGER_TEST_RESOLVER_EXPLICIT";
990 let _env_guard = EnvGuard::take(name);
991 unsafe { env::set_var(name, tmp.path().join("env-root")) };
993 fs::write(tmp.path().join("Cargo.toml"), "[workspace]\n").expect("write cargo");
995
996 let explicit = tmp.path().join("explicit-root");
997 let r = CacheResolver {
998 explicit: Some(explicit.clone()),
999 env_var: Some(name.to_string()),
1000 ..CacheResolver::default()
1001 };
1002 let (root, source) = r.resolve().expect("resolve");
1003 assert_eq!(source, CacheSource::Explicit);
1004 assert_eq!(root.path(), explicit.as_path());
1005 }
1006
1007 #[test]
1008 fn resolver_env_var_second_and_skips_empty() {
1009 let tmp = TempDir::new().expect("tempdir");
1010 let _guard = CwdGuard::swap_to(tmp.path()).expect("set cwd");
1011 let name = "CACHE_MANAGER_TEST_RESOLVER_ENV";
1012 unsafe { env::set_var(name, "sentinel") };
1016 {
1017 let _env_guard = EnvGuard::take(name);
1018
1019 unsafe { env::set_var(name, "") };
1022 let r = CacheResolver {
1023 env_var: Some(name.to_string()),
1024 ..CacheResolver::default()
1025 };
1026 let err = r.resolve().expect_err("empty env must fall through");
1027 assert_eq!(err.kind(), io::ErrorKind::NotFound);
1028 assert!(
1029 format!("{err}").contains(name),
1030 "error must name the env var: {err}"
1031 );
1032
1033 let env_root = tmp.path().join("env-root");
1035 unsafe { env::set_var(name, &env_root) };
1037 let (root, source) = r.resolve().expect("resolve");
1038 assert_eq!(source, CacheSource::EnvVar);
1039 assert_eq!(root.path(), env_root.as_path());
1040 }
1041 assert_eq!(env::var(name).as_deref(), Ok("sentinel"));
1043 unsafe { env::remove_var(name) };
1045 }
1046
1047 #[test]
1048 fn resolver_project_discovery_third() {
1049 let tmp = TempDir::new().expect("tempdir");
1050 let crate_root = tmp.path().join("workspace");
1051 let nested = crate_root.join("src").join("nested");
1052 fs::create_dir_all(&nested).expect("create nested");
1053 fs::write(
1054 crate_root.join(CARGO_TOML_FILE_NAME),
1055 "[package]\nname='x'\nversion='0.1.0'\nedition='2024'\n",
1056 )
1057 .expect("write cargo");
1058 let _guard = CwdGuard::swap_to(&nested).expect("set cwd");
1059
1060 let (root, source) = CacheResolver::default().resolve().expect("resolve");
1061 assert_eq!(source, CacheSource::ProjectDiscovery);
1062 let expected = crate_root
1063 .canonicalize()
1064 .expect("canonicalize")
1065 .join(CACHE_DIR_NAME);
1066 assert_eq!(root.path(), expected.as_path());
1067 }
1068
1069 #[test]
1070 fn resolver_no_workspace_without_identity_is_not_found_not_cwd() {
1071 let tmp = TempDir::new().expect("tempdir");
1074 let bare = tmp.path().join("bare");
1075 fs::create_dir_all(&bare).expect("create bare");
1076 let _guard = CwdGuard::swap_to(&bare).expect("set cwd");
1077
1078 let err = CacheResolver::default()
1079 .resolve()
1080 .expect_err("must not fall back to CWD");
1081 assert_eq!(err.kind(), io::ErrorKind::NotFound);
1082 assert!(
1083 !bare.join(CACHE_DIR_NAME).exists(),
1084 "resolver must not create anything on failure"
1085 );
1086 }
1087
1088 #[test]
1089 fn resolver_cwd_fallback_is_explicit_opt_in() {
1090 let tmp = TempDir::new().expect("tempdir");
1091 let bare = tmp.path().join("bare");
1092 fs::create_dir_all(&bare).expect("create bare");
1093 let _guard = CwdGuard::swap_to(&bare).expect("set cwd");
1094
1095 let r = CacheResolver {
1096 allow_cwd_fallback: true,
1097 ..CacheResolver::default()
1098 };
1099 let (root, source) = r.resolve().expect("resolve");
1100 assert_eq!(source, CacheSource::CwdFallback);
1101 let expected = bare
1102 .canonicalize()
1103 .expect("canonicalize")
1104 .join(CACHE_DIR_NAME);
1105 assert_eq!(root.path(), expected.as_path());
1106 }
1107
1108 #[test]
1109 fn resolver_discovery_opt_out_skips_to_not_found() {
1110 let tmp = TempDir::new().expect("tempdir");
1111 let crate_root = tmp.path().join("workspace");
1112 fs::create_dir_all(&crate_root).expect("create root");
1113 fs::write(crate_root.join(CARGO_TOML_FILE_NAME), "[workspace]\n").expect("write cargo");
1114 let _guard = CwdGuard::swap_to(&crate_root).expect("set cwd");
1115
1116 let r = CacheResolver {
1117 allow_project_discovery: false,
1118 ..CacheResolver::default()
1119 };
1120 let err = r.resolve().expect_err("discovery disabled → NotFound");
1121 assert_eq!(err.kind(), io::ErrorKind::NotFound);
1122 let msg = format!("{err}");
1125 assert!(
1126 msg.contains("project discovery is disabled"),
1127 "wrong error state: {msg}"
1128 );
1129 assert!(
1130 !msg.contains("no Cargo workspace above"),
1131 "false audit trail: {msg}"
1132 );
1133 }
1134
1135 #[cfg(feature = "os-cache-dir")]
1136 #[test]
1137 fn resolver_os_cache_dir_when_no_workspace() {
1138 let tmp = TempDir::new().expect("tempdir");
1139 let bare = tmp.path().join("bare");
1140 fs::create_dir_all(&bare).expect("create bare");
1141 let _guard = CwdGuard::swap_to(&bare).expect("set cwd");
1142
1143 let r = CacheResolver {
1144 project_dirs: Some((
1145 "com".to_string(),
1146 "CacheManagerTests".to_string(),
1147 "ResolverOsCache".to_string(),
1148 )),
1149 ..CacheResolver::default()
1150 };
1151 let (root, source) = r.resolve().expect("resolve");
1152 assert_eq!(source, CacheSource::OsCacheDir);
1153 let expected = ProjectDirs::from("com", "CacheManagerTests", "ResolverOsCache")
1154 .expect("project dirs")
1155 .cache_dir()
1156 .to_path_buf();
1157 assert_eq!(root.path(), expected.as_path());
1158 }
1159
1160 #[cfg(feature = "os-cache-dir")]
1161 #[test]
1162 fn resolver_env_beats_os_cache_and_explicit_beats_env() {
1163 let tmp = TempDir::new().expect("tempdir");
1164 let bare = tmp.path().join("bare");
1165 fs::create_dir_all(&bare).expect("create bare");
1166 let _guard = CwdGuard::swap_to(&bare).expect("set cwd");
1167 let name = "CACHE_MANAGER_TEST_RESOLVER_PRECEDENCE";
1168 let _env_guard = EnvGuard::take(name);
1169 let env_root = tmp.path().join("env-root");
1170 unsafe { env::set_var(name, &env_root) };
1172
1173 let os_only = CacheResolver {
1174 project_dirs: Some((
1175 "com".to_string(),
1176 "CacheManagerTests".to_string(),
1177 "ResolverPrecedence".to_string(),
1178 )),
1179 ..CacheResolver::default()
1180 };
1181 let (_, source) = os_only.resolve().expect("resolve");
1183 assert_eq!(source, CacheSource::OsCacheDir);
1184
1185 let with_env = CacheResolver {
1187 env_var: Some(name.to_string()),
1188 ..os_only.clone()
1189 };
1190 let (root, source) = with_env.resolve().expect("resolve");
1191 assert_eq!(source, CacheSource::EnvVar);
1192 assert_eq!(root.path(), env_root.as_path());
1193
1194 let explicit = tmp.path().join("explicit-root");
1196 let with_explicit = CacheResolver {
1197 explicit: Some(explicit.clone()),
1198 ..with_env
1199 };
1200 let (root, source) = with_explicit.resolve().expect("resolve");
1201 assert_eq!(source, CacheSource::Explicit);
1202 assert_eq!(root.path(), explicit.as_path());
1203 }
1204
1205 #[cfg(feature = "os-cache-dir")]
1206 #[test]
1207 fn from_project_dirs_matches_directories_cache_dir() {
1208 let qualifier = "com";
1209 let organization = "CacheManagerTests";
1210 let application = "CacheManagerOsCacheRoot";
1211
1212 let expected = ProjectDirs::from(qualifier, organization, application)
1213 .expect("project dirs")
1214 .cache_dir()
1215 .to_path_buf();
1216
1217 let root = CacheRoot::from_project_dirs(qualifier, organization, application)
1218 .expect("from project dirs");
1219
1220 assert_eq!(root.path(), expected.as_path());
1221 }
1222
1223 #[cfg(feature = "os-cache-dir")]
1224 #[test]
1225 fn project_dirs_or_not_found_returns_not_found_for_none() {
1226 let err =
1227 project_dirs_or_not_found(None).expect_err("none project dirs should map to not found");
1228 assert_eq!(err.kind(), io::ErrorKind::NotFound);
1229 }
1230
1231 #[cfg(feature = "process-scoped-cache")]
1232 #[test]
1233 fn from_tempdir_creates_existing_writable_root() {
1234 let root = CacheRoot::from_tempdir().expect("from tempdir");
1235 assert!(root.path().is_dir());
1236
1237 let probe_group = root.group("probe");
1238 let probe_file = probe_group.touch("writable.txt").expect("touch probe");
1239 assert!(probe_file.is_file());
1240
1241 fs::remove_dir_all(root.path()).expect("cleanup temp root");
1242 }
1243
1244 #[test]
1245 fn ensure_dir_with_policy_max_files() {
1246 let tmp = TempDir::new().expect("tempdir");
1247 let cache = CacheRoot::from_root(tmp.path());
1248 let group = cache.group("artifacts");
1249 group.ensure_dir().expect("ensure dir");
1250
1251 fs::write(group.entry_path("a.txt"), b"1").expect("write a");
1252 fs::write(group.entry_path("b.txt"), b"1").expect("write b");
1253 fs::write(group.entry_path("c.txt"), b"1").expect("write c");
1254
1255 let policy = EvictPolicy {
1256 max_files: Some(2),
1257 ..EvictPolicy::default()
1258 };
1259 group
1260 .ensure_dir_with_policy(Some(&policy))
1261 .expect("ensure with policy");
1262
1263 let files = collect_files(group.path()).expect("collect files");
1264 assert_eq!(files.len(), 2);
1265 }
1266
1267 #[test]
1268 fn ensure_dir_with_policy_max_bytes() {
1269 let tmp = TempDir::new().expect("tempdir");
1270 let cache = CacheRoot::from_root(tmp.path());
1271 let group = cache.group("artifacts");
1272 group.ensure_dir().expect("ensure dir");
1273
1274 fs::write(group.entry_path("a.bin"), vec![1u8; 5]).expect("write a");
1275 fs::write(group.entry_path("b.bin"), vec![1u8; 5]).expect("write b");
1276 fs::write(group.entry_path("c.bin"), vec![1u8; 5]).expect("write c");
1277
1278 let policy = EvictPolicy {
1279 max_bytes: Some(10),
1280 ..EvictPolicy::default()
1281 };
1282 group
1283 .ensure_dir_with_policy(Some(&policy))
1284 .expect("ensure with policy");
1285
1286 let total: u64 = collect_files(group.path())
1287 .expect("collect files")
1288 .iter()
1289 .map(|f| f.len)
1290 .sum();
1291 assert!(total <= 10);
1292 }
1293
1294 #[test]
1295 fn ensure_dir_with_policy_max_age_zero_evicts_all() {
1296 let tmp = TempDir::new().expect("tempdir");
1297 let cache = CacheRoot::from_root(tmp.path());
1298 let group = cache.group("artifacts");
1299 group.ensure_dir().expect("ensure dir");
1300
1301 fs::write(group.entry_path("a.txt"), b"1").expect("write a");
1302 fs::write(group.entry_path("b.txt"), b"1").expect("write b");
1303
1304 let policy = EvictPolicy {
1305 max_age: Some(Duration::ZERO),
1306 ..EvictPolicy::default()
1307 };
1308 group
1309 .ensure_dir_with_policy(Some(&policy))
1310 .expect("ensure with policy");
1311
1312 let files = collect_files(group.path()).expect("collect files");
1313 assert!(files.is_empty());
1314 }
1315
1316 #[test]
1317 fn eviction_report_matches_applied_evictions() {
1318 let tmp = TempDir::new().expect("tempdir");
1319 let cache = CacheRoot::from_root(tmp.path());
1320 let group = cache.group("artifacts");
1321 group.ensure_dir().expect("ensure dir");
1322
1323 fs::write(group.entry_path("a.bin"), vec![1u8; 5]).expect("write a");
1324 fs::write(group.entry_path("b.bin"), vec![1u8; 5]).expect("write b");
1325 fs::write(group.entry_path("c.bin"), vec![1u8; 5]).expect("write c");
1326
1327 let policy = EvictPolicy {
1328 max_bytes: Some(10),
1329 ..EvictPolicy::default()
1330 };
1331
1332 let before: BTreeSet<PathBuf> = collect_files(group.path())
1333 .expect("collect before")
1334 .into_iter()
1335 .map(|f| f.path)
1336 .collect();
1337
1338 let report = group.eviction_report(&policy).expect("eviction report");
1339 let planned: BTreeSet<PathBuf> = report.marked_for_eviction.iter().cloned().collect();
1340
1341 group
1342 .ensure_dir_with_policy(Some(&policy))
1343 .expect("ensure with policy");
1344
1345 let after: BTreeSet<PathBuf> = collect_files(group.path())
1346 .expect("collect after")
1347 .into_iter()
1348 .map(|f| f.path)
1349 .collect();
1350
1351 let expected_after: BTreeSet<PathBuf> = before.difference(&planned).cloned().collect();
1352 assert_eq!(after, expected_after);
1353 }
1354
1355 #[test]
1356 fn no_policy_and_default_policy_report_do_not_mark_evictions() {
1357 let tmp = TempDir::new().expect("tempdir");
1358 let cache = CacheRoot::from_root(tmp.path());
1359 let group = cache.group("artifacts");
1360 group.ensure_dir().expect("ensure dir");
1361
1362 fs::write(group.entry_path("a.txt"), b"1").expect("write a");
1363 fs::write(group.entry_path("b.txt"), b"1").expect("write b");
1364
1365 let report = group
1366 .eviction_report(&EvictPolicy::default())
1367 .expect("eviction report");
1368 assert!(report.marked_for_eviction.is_empty());
1369
1370 group
1371 .ensure_dir_with_policy(None)
1372 .expect("ensure with no policy");
1373
1374 let files = collect_files(group.path()).expect("collect files");
1375 assert_eq!(files.len(), 2);
1376 }
1377
1378 #[test]
1379 fn eviction_policy_applies_in_documented_order() {
1380 let tmp = TempDir::new().expect("tempdir");
1381 let cache = CacheRoot::from_root(tmp.path());
1382 let group = cache.group("artifacts");
1383 group.ensure_dir().expect("ensure dir");
1384
1385 fs::write(group.entry_path("old.txt"), vec![1u8; 1]).expect("write old");
1386
1387 std::thread::sleep(Duration::from_millis(300));
1388
1389 fs::write(group.entry_path("b.bin"), vec![1u8; 7]).expect("write b");
1390 fs::write(group.entry_path("c.bin"), vec![1u8; 6]).expect("write c");
1391 fs::write(group.entry_path("d.bin"), vec![1u8; 1]).expect("write d");
1392
1393 let policy = EvictPolicy {
1394 max_age: Some(Duration::from_millis(200)),
1395 max_files: Some(2),
1396 max_bytes: Some(5),
1397 };
1398
1399 let report = group.eviction_report(&policy).expect("eviction report");
1400 let evicted_names: Vec<String> = report
1401 .marked_for_eviction
1402 .iter()
1403 .map(|path| {
1404 path.file_name()
1405 .and_then(|name| name.to_str())
1406 .expect("evicted file name")
1407 .to_string()
1408 })
1409 .collect();
1410
1411 assert_eq!(evicted_names, vec!["old.txt", "b.bin", "c.bin"]);
1412
1413 group
1414 .ensure_dir_with_policy(Some(&policy))
1415 .expect("apply policy");
1416
1417 let remaining_names: BTreeSet<String> = collect_files(group.path())
1418 .expect("collect remaining")
1419 .into_iter()
1420 .map(|entry| {
1421 entry
1422 .path
1423 .file_name()
1424 .and_then(|name| name.to_str())
1425 .expect("remaining file name")
1426 .to_string()
1427 })
1428 .collect();
1429
1430 assert_eq!(remaining_names, BTreeSet::from(["d.bin".to_string()]));
1431 }
1432
1433 #[test]
1434 fn sort_entries_uses_path_as_tie_break_for_equal_modified_time() {
1435 let same_time = UNIX_EPOCH + Duration::from_secs(1_234_567);
1436 let mut entries = vec![
1437 FileEntry {
1438 path: PathBuf::from("z.bin"),
1439 modified: same_time,
1440 len: 1,
1441 },
1442 FileEntry {
1443 path: PathBuf::from("a.bin"),
1444 modified: same_time,
1445 len: 1,
1446 },
1447 FileEntry {
1448 path: PathBuf::from("m.bin"),
1449 modified: same_time,
1450 len: 1,
1451 },
1452 ];
1453
1454 sort_entries_oldest_first(&mut entries);
1455
1456 let ordered_paths: Vec<PathBuf> = entries.into_iter().map(|entry| entry.path).collect();
1457 assert_eq!(
1458 ordered_paths,
1459 vec![
1460 PathBuf::from("a.bin"),
1461 PathBuf::from("m.bin"),
1462 PathBuf::from("z.bin")
1463 ]
1464 );
1465 }
1466
1467 #[test]
1468 fn single_root_supports_distinct_policies_per_subdirectory() {
1469 let tmp = TempDir::new().expect("tempdir");
1470 let cache = CacheRoot::from_root(tmp.path());
1471
1472 let images = cache.group("artifacts/images");
1473 let reports = cache.group("artifacts/reports");
1474
1475 images.ensure_dir().expect("ensure images dir");
1476 reports.ensure_dir().expect("ensure reports dir");
1477
1478 fs::write(images.entry_path("img1.bin"), vec![1u8; 5]).expect("write img1");
1479 fs::write(images.entry_path("img2.bin"), vec![1u8; 5]).expect("write img2");
1480 fs::write(images.entry_path("img3.bin"), vec![1u8; 5]).expect("write img3");
1481
1482 fs::write(reports.entry_path("a.txt"), b"1").expect("write report a");
1483 fs::write(reports.entry_path("b.txt"), b"1").expect("write report b");
1484 fs::write(reports.entry_path("c.txt"), b"1").expect("write report c");
1485
1486 let images_policy = EvictPolicy {
1487 max_bytes: Some(10),
1488 ..EvictPolicy::default()
1489 };
1490 let reports_policy = EvictPolicy {
1491 max_files: Some(1),
1492 ..EvictPolicy::default()
1493 };
1494
1495 images
1496 .ensure_dir_with_policy(Some(&images_policy))
1497 .expect("apply images policy");
1498 reports
1499 .ensure_dir_with_policy(Some(&reports_policy))
1500 .expect("apply reports policy");
1501
1502 let images_total: u64 = collect_files(images.path())
1503 .expect("collect images files")
1504 .iter()
1505 .map(|f| f.len)
1506 .sum();
1507 assert!(images_total <= 10);
1508
1509 let reports_files = collect_files(reports.path()).expect("collect reports files");
1510 assert_eq!(reports_files.len(), 1);
1511 }
1512
1513 #[test]
1514 fn group_path_and_ensure_group_create_expected_directory() {
1515 let tmp = TempDir::new().expect("tempdir");
1516 let cache = CacheRoot::from_root(tmp.path());
1517
1518 let expected = tmp.path().join("a/b/c");
1519 assert_eq!(cache.group_path("a/b/c"), expected);
1520
1521 let ensured = cache.ensure_group("a/b/c").expect("ensure group");
1522 assert_eq!(ensured, expected);
1523 assert!(ensured.is_dir());
1524 }
1525
1526 #[test]
1527 fn ensure_group_with_policy_applies_eviction_rules() {
1528 let tmp = TempDir::new().expect("tempdir");
1529 let cache = CacheRoot::from_root(tmp.path());
1530
1531 cache
1532 .ensure_group_with_policy("artifacts", None)
1533 .expect("ensure group without policy");
1534
1535 let group = cache.group("artifacts");
1536 fs::write(group.entry_path("a.bin"), vec![1u8; 1]).expect("write a");
1537 fs::write(group.entry_path("b.bin"), vec![1u8; 1]).expect("write b");
1538 fs::write(group.entry_path("c.bin"), vec![1u8; 1]).expect("write c");
1539
1540 let policy = EvictPolicy {
1541 max_files: Some(1),
1542 ..EvictPolicy::default()
1543 };
1544
1545 let ensured = cache
1546 .ensure_group_with_policy("artifacts", Some(&policy))
1547 .expect("ensure group with policy");
1548 assert_eq!(ensured, group.path());
1549
1550 let files = collect_files(group.path()).expect("collect files");
1551 assert_eq!(files.len(), 1);
1552 }
1553
1554 #[test]
1555 fn cache_path_joins_relative_paths_under_group() {
1556 let tmp = TempDir::new().expect("tempdir");
1557 let cache = CacheRoot::from_root(tmp.path());
1558
1559 let got = cache.cache_path(CACHE_DIR_NAME, "tool/v1/data.bin");
1560 let expected = tmp
1561 .path()
1562 .join(CACHE_DIR_NAME)
1563 .join("tool")
1564 .join("v1")
1565 .join("data.bin");
1566 assert_eq!(got, expected);
1567 }
1568
1569 #[test]
1570 fn subgroup_touch_creates_parent_directories() {
1571 let tmp = TempDir::new().expect("tempdir");
1572 let cache = CacheRoot::from_root(tmp.path());
1573 let subgroup = cache.group("artifacts").subgroup("json/v1");
1574
1575 let touched = subgroup
1576 .touch("nested/output.bin")
1577 .expect("touch subgroup entry");
1578
1579 assert!(touched.is_file());
1580 assert!(subgroup.path().join("nested").is_dir());
1581 }
1582
1583 #[test]
1584 fn eviction_report_errors_when_group_directory_is_missing() {
1585 let tmp = TempDir::new().expect("tempdir");
1586 let cache = CacheRoot::from_root(tmp.path());
1587 let missing = cache.group("does-not-exist");
1588
1589 let err = missing
1590 .eviction_report(&EvictPolicy::default())
1591 .expect_err("eviction report should fail for missing directory");
1592 assert_eq!(err.kind(), io::ErrorKind::NotFound);
1593 }
1594
1595 #[test]
1596 fn eviction_policy_scans_nested_subdirectories_recursively() {
1597 let tmp = TempDir::new().expect("tempdir");
1598 let cache = CacheRoot::from_root(tmp.path());
1599 let group = cache.group("artifacts");
1600 group.ensure_dir().expect("ensure dir");
1601
1602 fs::create_dir_all(group.entry_path("nested/deeper")).expect("create nested dirs");
1603 fs::write(group.entry_path("root.bin"), vec![1u8; 1]).expect("write root");
1604 fs::write(group.entry_path("nested/a.bin"), vec![1u8; 1]).expect("write nested a");
1605 fs::write(group.entry_path("nested/deeper/b.bin"), vec![1u8; 1]).expect("write nested b");
1606
1607 let policy = EvictPolicy {
1608 max_files: Some(1),
1609 ..EvictPolicy::default()
1610 };
1611
1612 group
1613 .ensure_dir_with_policy(Some(&policy))
1614 .expect("apply recursive policy");
1615
1616 let remaining = collect_files(group.path()).expect("collect remaining");
1617 assert_eq!(remaining.len(), 1);
1618 }
1619
1620 #[cfg(unix)]
1621 #[test]
1622 fn collect_files_recursive_ignores_non_file_non_directory_entries() {
1623 use std::os::unix::net::UnixListener;
1624
1625 let tmp = TempDir::new().expect("tempdir");
1626 let cache = CacheRoot::from_root(tmp.path());
1627 let group = cache.group("artifacts");
1628 group.ensure_dir().expect("ensure dir");
1629
1630 let socket_path = group.entry_path("live.sock");
1631 let _listener = UnixListener::bind(&socket_path).expect("bind unix socket");
1632
1633 fs::write(group.entry_path("a.bin"), vec![1u8; 1]).expect("write file");
1634
1635 let files = collect_files(group.path()).expect("collect files");
1636 assert_eq!(files.len(), 1);
1637 assert_eq!(files[0].path, group.entry_path("a.bin"));
1638 }
1639
1640 #[test]
1641 fn max_bytes_policy_under_threshold_does_not_evict() {
1642 let tmp = TempDir::new().expect("tempdir");
1643 let cache = CacheRoot::from_root(tmp.path());
1644 let group = cache.group("artifacts");
1645 group.ensure_dir().expect("ensure dir");
1646
1647 fs::write(group.entry_path("a.bin"), vec![1u8; 2]).expect("write a");
1648 fs::write(group.entry_path("b.bin"), vec![1u8; 3]).expect("write b");
1649
1650 let policy = EvictPolicy {
1651 max_bytes: Some(10),
1652 ..EvictPolicy::default()
1653 };
1654
1655 let report = group.eviction_report(&policy).expect("eviction report");
1656 assert!(report.marked_for_eviction.is_empty());
1657
1658 group
1659 .ensure_dir_with_policy(Some(&policy))
1660 .expect("ensure with policy");
1661
1662 let files = collect_files(group.path()).expect("collect files");
1663 assert_eq!(files.len(), 2);
1664 }
1665
1666 #[test]
1667 fn cwd_guard_swap_to_returns_error_for_missing_directory() {
1668 let tmp = TempDir::new().expect("tempdir");
1669 let missing = tmp.path().join("missing-dir");
1670
1671 let result = CwdGuard::swap_to(&missing);
1672 assert!(result.is_err());
1673 assert_eq!(
1674 result.err().expect("expected missing-dir error").kind(),
1675 io::ErrorKind::NotFound
1676 );
1677 }
1678
1679 #[test]
1680 fn ensure_dir_equals_ensure_dir_with_policy_none() {
1681 let tmp = TempDir::new().expect("tempdir");
1682 let cache = CacheRoot::from_root(tmp.path());
1683 let group = cache.group("artifacts/eq");
1684
1685 let p1 = group.ensure_dir().expect("ensure dir");
1686 fs::write(group.entry_path("keep.txt"), b"keep").expect("write file");
1689
1690 let p2 = group
1691 .ensure_dir_with_policy(None)
1692 .expect("ensure dir with None policy");
1693
1694 assert_eq!(p1, p2);
1695 assert!(group.entry_path("keep.txt").exists());
1696 }
1697
1698 #[test]
1699 fn ensure_group_equals_ensure_group_with_policy_none() {
1700 let tmp = TempDir::new().expect("tempdir");
1701 let cache = CacheRoot::from_root(tmp.path());
1702
1703 let p1 = cache.ensure_group("artifacts/roots").expect("ensure group");
1704 let group = cache.group("artifacts/roots");
1705 fs::write(group.entry_path("keep_root.txt"), b"keep").expect("write file");
1707
1708 let p2 = cache
1709 .ensure_group_with_policy("artifacts/roots", None)
1710 .expect("ensure group with None policy");
1711
1712 assert_eq!(p1, p2);
1713 assert!(group.entry_path("keep_root.txt").exists());
1714 }
1715
1716 #[cfg(feature = "process-scoped-cache")]
1717 #[test]
1718 fn process_scoped_cache_respects_root_and_group_assignments() {
1719 let tmp = TempDir::new().expect("tempdir");
1720 let root = CacheRoot::from_root(tmp.path().join("custom-root"));
1721
1722 let scoped = ProcessScopedCacheGroup::new(&root, "artifacts/session").expect("create");
1723 let expected_prefix = root.group("artifacts/session").path().to_path_buf();
1724
1725 assert!(scoped.path().starts_with(&expected_prefix));
1726 assert!(scoped.path().exists());
1727 }
1728
1729 #[cfg(feature = "process-scoped-cache")]
1730 #[test]
1731 fn process_scoped_cache_deletes_directory_on_drop() {
1732 let tmp = TempDir::new().expect("tempdir");
1733 let root = CacheRoot::from_root(tmp.path());
1734
1735 let process_dir = {
1736 let scoped = ProcessScopedCacheGroup::new(&root, "artifacts").expect("create");
1737 let p = scoped.path().to_path_buf();
1738 assert!(p.exists());
1739 p
1740 };
1741
1742 assert!(!process_dir.exists());
1743 }
1744
1745 #[cfg(feature = "process-scoped-cache")]
1746 #[test]
1747 fn process_scoped_cache_thread_group_is_stable_per_thread() {
1748 let tmp = TempDir::new().expect("tempdir");
1749 let root = CacheRoot::from_root(tmp.path());
1750 let scoped = ProcessScopedCacheGroup::new(&root, "artifacts").expect("create");
1751
1752 let first = scoped.thread_group().path().to_path_buf();
1753 let second = scoped.thread_group().path().to_path_buf();
1754
1755 assert_eq!(first, second);
1756 }
1757
1758 #[cfg(feature = "process-scoped-cache")]
1759 #[test]
1760 fn process_scoped_cache_thread_group_differs_across_threads() {
1761 let tmp = TempDir::new().expect("tempdir");
1762 let root = CacheRoot::from_root(tmp.path());
1763 let scoped = ProcessScopedCacheGroup::new(&root, "artifacts").expect("create");
1764
1765 let main_thread_group = scoped.thread_group().path().to_path_buf();
1766 let other_thread_group = std::thread::spawn(current_thread_cache_group_id)
1767 .join()
1768 .expect("join thread");
1769
1770 let expected_other = scoped
1771 .process_group()
1772 .subgroup(format!("thread-{other_thread_group}"))
1773 .path()
1774 .to_path_buf();
1775
1776 assert_ne!(main_thread_group, expected_other);
1777 }
1778
1779 #[cfg(feature = "process-scoped-cache")]
1780 #[test]
1781 fn process_scoped_cache_from_group_uses_given_base_group() {
1782 let tmp = TempDir::new().expect("tempdir");
1783 let root = CacheRoot::from_root(tmp.path());
1784 let base_group = root.group("artifacts/custom-base");
1785
1786 let scoped = ProcessScopedCacheGroup::from_group(base_group.clone()).expect("create");
1787
1788 assert!(scoped.path().starts_with(base_group.path()));
1789 assert_eq!(scoped.process_group().path(), scoped.path());
1790 }
1791
1792 #[cfg(feature = "process-scoped-cache")]
1793 #[test]
1794 fn process_scoped_cache_thread_entry_path_matches_touch_location() {
1795 let tmp = TempDir::new().expect("tempdir");
1796 let root = CacheRoot::from_root(tmp.path());
1797 let scoped = ProcessScopedCacheGroup::new(&root, "artifacts").expect("create");
1798
1799 let planned = scoped.thread_entry_path("nested/data.bin");
1800 let touched = scoped
1801 .touch_thread_entry("nested/data.bin")
1802 .expect("touch thread entry");
1803
1804 assert_eq!(planned, touched);
1805 assert!(touched.exists());
1806 }
1807
1808 #[cfg(feature = "process-scoped-cache")]
1809 #[test]
1810 fn touch_thread_entry_creates_entry_under_thread_group() {
1811 let tmp = TempDir::new().expect("tempdir");
1812 let root = CacheRoot::from_root(tmp.path());
1813 let scoped = ProcessScopedCacheGroup::new(&root, "artifacts").expect("create");
1814
1815 let entry = scoped
1816 .touch_thread_entry("nested/data.bin")
1817 .expect("touch thread entry");
1818
1819 assert!(entry.exists());
1820 assert!(entry.starts_with(scoped.path()));
1821 let thread_group = scoped.thread_group().path().to_path_buf();
1822 assert!(entry.starts_with(&thread_group));
1823 }
1824}