Skip to main content

cache_manager/
lib.rs

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/// Optional eviction controls applied by `CacheGroup::ensure_dir_with_policy`
34/// and `CacheRoot::ensure_group_with_policy`.
35///
36/// Rules are enforced in this order:
37/// 1. `max_age` (remove files older than or equal to threshold)
38/// 2. `max_files` (keep at most N files)
39/// 3. `max_bytes` (keep total bytes at or below threshold)
40///
41/// For `max_files` and `max_bytes`, candidates are ordered by modified time
42/// ascending (oldest first), then by path for deterministic tie-breaking.
43#[derive(Clone, Debug, PartialEq, Eq, Default)]
44pub struct EvictPolicy {
45    /// Maximum number of files to keep under the managed directory tree.
46    ///
47    /// If exceeded, the oldest files are removed first until the count is
48    /// `<= max_files`.
49    pub max_files: Option<usize>,
50    /// Maximum total size in bytes to keep under the managed directory tree.
51    ///
52    /// If exceeded, files are removed oldest-first until total bytes are
53    /// `<= max_bytes`.
54    ///
55    /// Notes:
56    /// - The limit applies to regular files recursively under the directory.
57    /// - Directories are not counted toward the byte total.
58    /// - Enforced only when using a policy-aware `ensure_*_with_policy` call.
59    pub max_bytes: Option<u64>,
60    /// Maximum file age allowed under the managed directory tree.
61    ///
62    /// Files with age `>= max_age` are removed.
63    pub max_age: Option<Duration>,
64}
65
66/// Files selected for eviction by policy evaluation.
67#[derive(Clone, Debug, PartialEq, Eq, Default)]
68pub struct EvictionReport {
69    /// Absolute paths marked for eviction, in the order they would be applied.
70    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)]
81/// Represents a discovered or explicit cache root directory.
82///
83/// Use `CacheRoot::from_discovery()` to find the nearest crate root from the
84/// current working directory and anchor caches under `.cache`, or
85/// `CacheRoot::from_root(...)` to construct one from an explicit path.
86pub struct CacheRoot {
87    root: PathBuf,
88}
89
90impl CacheRoot {
91    /// Discover the cache root by searching parent directories for `Cargo.toml`.
92    ///
93    /// The discovered cache root is always
94    /// `<workspace-root-or-crate-root-or-cwd>/.cache`.
95    ///
96    /// Note: `from_discovery` only uses the configured `CACHE_DIR_NAME` (by
97    /// default `.cache`) as the discovered cache directory. It does not
98    /// detect or prefer other custom directory names (for example
99    /// `.cache-v2`). To use a non-standard cache root name use
100    /// `CacheRoot::from_root(...)` with an explicit path.
101    ///
102    /// Falls back to the current working directory when no crate root is found.
103    pub fn from_discovery() -> io::Result<Self> {
104        let cwd = env::current_dir()?;
105        let anchor = find_crate_root(&cwd).unwrap_or(cwd);
106        // Prefer a canonicalized anchor when possible to avoid surprising
107        // differences between logically-equal paths (symlinks, tempdir
108        // representations, etc.) used by callers and tests.
109        let anchor = anchor.canonicalize().unwrap_or(anchor);
110        let root = anchor.join(CACHE_DIR_NAME);
111        Ok(Self { root })
112    }
113
114    /// Create a `CacheRoot` from an explicit filesystem path.
115    pub fn from_root<P: Into<PathBuf>>(root: P) -> Self {
116        Self { root: root.into() }
117    }
118
119    /// Create a `CacheRoot` from an OS-native per-user cache directory for
120    /// the given project identity.
121    ///
122    /// This API is available when the `os-cache-dir` feature is enabled and
123    /// uses [`directories::ProjectDirs`] internally.
124    ///
125    /// The returned path is OS-specific and typically resolves to:
126    /// - macOS: `~/Library/Caches/<app>`
127    /// - Linux: `$XDG_CACHE_HOME/<app>` or `~/.cache/<app>`
128    /// - Windows: `%LOCALAPPDATA%\\<org>\\<app>\\cache`
129    ///
130    /// Parameters are passed directly to `ProjectDirs::from(qualifier,
131    /// organization, application)`.
132    ///
133    /// `qualifier` is a DNS-like namespace component used primarily on some
134    /// platforms (notably macOS) to form a unique app identity. Common values
135    /// include:
136    /// - `"com"` (for apps under a `com.<org>.<app>` naming scheme)
137    /// - `"org"` (for apps under an `org.<org>.<app>` naming scheme)
138    ///
139    /// Example:
140    /// `CacheRoot::from_project_dirs("com", "Acme", "WidgetTool")`.
141    #[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    /// Create a `CacheRoot` using a newly-created directory under the system
156    /// temporary directory.
157    ///
158    /// This API is available when the `process-scoped-cache` feature is
159    /// enabled (which provides the `tempfile` dependency).
160    ///
161    /// The directory is intentionally persisted and returned as the cache root,
162    /// so it is **not** automatically deleted when this function returns.
163    /// Callers who want cleanup should remove `root.path()` explicitly when
164    /// finished.
165    #[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    /// Return the underlying path for this `CacheRoot`.
172    pub fn path(&self) -> &Path {
173        &self.root
174    }
175
176    // --- combined resolution -------------------------------------------------
177    //
178    // [`CacheResolver`] implements the "no surprises" contract documented on
179    // that type: fixed precedence, no silent `<cwd>/.cache` scattering, and
180    // the winning source always reported. Prefer it over hand-rolled
181    // `match env::var(...)` chains in binaries.
182
183    /// Build a `CacheGroup` for a relative subdirectory under this root.
184    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    /// Resolve a relative group path to an absolute `PathBuf` under this root.
190    pub fn group_path<P: AsRef<Path>>(&self, relative_group: P) -> PathBuf {
191        self.root.join(relative_group.as_ref())
192    }
193
194    /// Ensure the given group directory exists, creating parents as required.
195    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    /// Ensure the given group exists and optionally apply an eviction policy.
200    ///
201    /// When `policy` is `Some`, files will be evaluated and removed according
202    /// to the `EvictPolicy` rules. Passing `None` performs only directory creation.
203    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    /// Resolve a cache entry path given a cache directory (relative to the root)
214    /// and a relative entry path. Absolute `relative_path` values are returned
215    /// unchanged.
216    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/// Where a [`CacheResolver`]-resolved cache root came from. Returned alongside
230/// the root so binaries can announce it (e.g.
231/// `cache: ~/Library/Caches/com.acme.tool (os-cache-dir)`) — cache placement
232/// must never be silent.
233#[derive(Clone, Copy, Debug, PartialEq, Eq)]
234pub enum CacheSource {
235    /// Explicit `--dir`-style path; wins over everything.
236    Explicit,
237    /// Environment variable (see [`CacheResolver::env_var`]).
238    EnvVar,
239    /// Cargo workspace/crate discovery (`<workspace>/.cache`).
240    ProjectDiscovery,
241    /// OS-native per-user cache dir (`os-cache-dir` feature).
242    OsCacheDir,
243    /// Last-resort `<cwd>/.cache`; only reachable when the caller explicitly
244    /// sets [`CacheResolver::allow_cwd_fallback`].
245    CwdFallback,
246}
247
248/// Combined cache-root resolution with a fixed, documented precedence and no
249/// silent `<cwd>/.cache` scattering.
250///
251/// Precedence (first hit wins, the rest are never consulted):
252/// 1. [`CacheResolver::explicit`] — an explicit path (CLI `--dir`).
253/// 2. [`CacheResolver::env_var`] — a non-empty env var value.
254/// 3. Cargo workspace discovery (`<workspace>/.cache`), unless
255///    [`CacheResolver::allow_project_discovery`] is false.
256/// 4. OS user cache dir for the `project_dirs` identity (requires the
257///    `os-cache-dir` feature; without it this arm is compiled out).
258///
259/// When nothing matches, `resolve()` returns `Err` (kind `NotFound`) naming
260/// the env var and OS identity that would fix it — it NEVER silently falls
261/// back to `<cwd>/.cache`. Opt into that legacy behavior per call site with
262/// [`CacheResolver::allow_cwd_fallback`] (default `false`).
263///
264/// Recommended convention: binaries announce the winner on stderr at startup,
265/// e.g. `tracing::info!("cache: {} ({:?})", root.path().display(), source)`.
266///
267/// Zero breaking change: [`CacheRoot::from_discovery`] keeps its exact
268/// current semantics (including the CWD fallback) for existing users.
269#[derive(Clone, Debug)]
270pub struct CacheResolver {
271    /// Explicit path; wins over everything. Usually a CLI `--dir` flag.
272    pub explicit: Option<PathBuf>,
273    /// Env var name consulted next (e.g. `"WINDOWS_HEADLESS_QEMU_DIR"`).
274    /// Only non-empty values count; unset-or-empty falls through.
275    pub env_var: Option<String>,
276    /// Consult Cargo workspace discovery. Default `true`.
277    pub allow_project_discovery: bool,
278    /// OS cache identity `(qualifier, organization, application)` passed to
279    /// `ProjectDirs::from`. `None` (default) disables the OS-cache arm.
280    /// Available only with the `os-cache-dir` feature.
281    #[cfg(feature = "os-cache-dir")]
282    pub project_dirs: Option<(String, String, String)>,
283    /// DANGEROUS, default `false`: allow `<cwd>/.cache` as a last resort
284    /// (the [`CacheSource::CwdFallback`] source). Enabling this is a
285    /// conscious, greppable opt-in — each shell CWD grows its own cache.
286    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    /// Resolve to `(root, source)` following the documented precedence.
304    pub fn resolve(&self) -> io::Result<(CacheRoot, CacheSource)> {
305        // 1. Explicit path.
306        if let Some(p) = &self.explicit {
307            return Ok((CacheRoot::from_root(p.clone()), CacheSource::Explicit));
308        }
309        // 2. Env var (non-empty values only).
310        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        // 3. Cargo workspace discovery (distinguishes "found a workspace"
317        // from "would fall back to CWD" — unlike from_discovery, no silent
318        // fallback here).
319        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        // 4. OS user cache dir.
330        #[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        // 5. Explicit last-resort opt-in only.
341        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
369/// Anchor dir for project discovery (`Some`) or `None` when no `Cargo.toml`
370/// exists above the CWD. Split out of [`find_crate_root`] so the resolver can
371/// tell "found a workspace" from "would fall back to CWD".
372fn 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)]
378/// A group (subdirectory) under a `CacheRoot` that manages cache entries.
379///
380/// Use `CacheRoot::group(...)` to construct a `CacheGroup` rooted under a
381/// `CacheRoot`.
382pub struct CacheGroup {
383    path: PathBuf,
384}
385
386impl CacheGroup {
387    /// Return the path of this cache group.
388    pub fn path(&self) -> &Path {
389        &self.path
390    }
391
392    /// Ensure the group directory exists on disk, creating parents as needed.
393    /// Normalizes permissions on the way in (see [`ensure_writable_tree`]):
394    /// the cache owns its directories, so a group dir is always left
395    /// owner-writable.
396    pub fn ensure_dir(&self) -> io::Result<&Path> {
397        self.ensure_dir_with_policy(None)
398    }
399
400    /// Ensures this directory exists, then applies optional eviction.
401    ///
402    /// Eviction is applied recursively to files under this directory. The
403    /// policy is best-effort for removals: individual delete failures are
404    /// ignored so initialization can continue.
405    pub fn ensure_dir_with_policy(&self, policy: Option<&EvictPolicy>) -> io::Result<&Path> {
406        fs::create_dir_all(&self.path)?;
407        // Normalize before anything else touches the tree (and before
408        // eviction deletes from it): read-only leftovers break both.
409        ensure_writable_tree(&self.path)?;
410        if let Some(policy) = policy {
411            apply_evict_policy(&self.path, policy)?;
412        }
413        Ok(&self.path)
414    }
415
416    /// Returns a report of files that would be evicted under `policy`.
417    ///
418    /// This does not delete files. The selection order matches the internal
419    /// order used by `ensure_dir_with_policy`.
420    /// Return a report of files that would be evicted by `policy`.
421    ///
422    /// The report is non-destructive and mirrors the selection used by
423    /// `ensure_dir_with_policy` so it can be used for previewing or testing.
424    pub fn eviction_report(&self, policy: &EvictPolicy) -> io::Result<EvictionReport> {
425        build_eviction_report(&self.path, policy)
426    }
427
428    /// Create a nested subgroup under this group.
429    pub fn subgroup<P: AsRef<Path>>(&self, relative_group: P) -> Self {
430        Self {
431            path: self.path.join(relative_group.as_ref()),
432        }
433    }
434
435    /// Resolve a relative entry path under this group.
436    pub fn entry_path<P: AsRef<Path>>(&self, relative_file: P) -> PathBuf {
437        self.path.join(relative_file.as_ref())
438    }
439
440    /// Create or update (touch) a file under this group, creating parent
441    /// directories as needed. Returns the absolute path to the entry.
442    pub fn touch<P: AsRef<Path>>(&self, relative_file: P) -> io::Result<PathBuf> {
443        let entry = self.entry_path(relative_file);
444        if let Some(parent) = entry.parent() {
445            fs::create_dir_all(parent)?;
446        }
447        OpenOptions::new().create(true).append(true).open(&entry)?;
448        Ok(entry)
449    }
450}
451
452/// Process-scoped cache group handle with per-thread subgroup helpers.
453///
454/// This type is available when the `process-scoped-cache` feature is enabled.
455///
456/// It creates an auto-generated process subdirectory under a user-selected
457/// base cache group. The backing directory is removed when this handle is
458/// dropped during normal process shutdown.
459///
460/// Notes:
461/// - Cleanup is best-effort and is not guaranteed after abnormal termination
462///   (for example `SIGKILL` or process crash).
463/// - All paths still respect the caller-provided `CacheRoot` and base group.
464#[cfg(feature = "process-scoped-cache")]
465#[derive(Debug)]
466pub struct ProcessScopedCacheGroup {
467    process_group: CacheGroup,
468    _temp_dir: TempDir,
469}
470
471#[cfg(feature = "process-scoped-cache")]
472impl ProcessScopedCacheGroup {
473    /// Create a process-scoped cache handle under `root.group(relative_group)`.
474    pub fn new<P: AsRef<Path>>(root: &CacheRoot, relative_group: P) -> io::Result<Self> {
475        Self::from_group(root.group(relative_group))
476    }
477
478    /// Create a process-scoped cache handle under an existing base group.
479    pub fn from_group(base_group: CacheGroup) -> io::Result<Self> {
480        base_group.ensure_dir()?;
481        let pid = std::process::id();
482        let temp_dir = Builder::new()
483            .prefix(&format!("pid-{pid}-"))
484            .tempdir_in(base_group.path())?;
485        let process_group = CacheGroup {
486            path: temp_dir.path().to_path_buf(),
487        };
488
489        Ok(Self {
490            process_group,
491            _temp_dir: temp_dir,
492        })
493    }
494
495    /// Return the process-scoped directory path.
496    pub fn path(&self) -> &Path {
497        self.process_group.path()
498    }
499
500    /// Return the process-scoped cache group.
501    pub fn process_group(&self) -> CacheGroup {
502        self.process_group.clone()
503    }
504
505    /// Return the subgroup for the current thread.
506    ///
507    /// Each thread gets a stable, process-local incremental id (`thread-<n>`)
508    /// for the process lifetime.
509    pub fn thread_group(&self) -> CacheGroup {
510        self.process_group
511            .subgroup(format!("thread-{}", current_thread_cache_group_id()))
512    }
513
514    /// Ensure and return the subgroup for the current thread.
515    pub fn ensure_thread_group(&self) -> io::Result<CacheGroup> {
516        let group = self.thread_group();
517        group.ensure_dir()?;
518        Ok(group)
519    }
520
521    /// Build an entry path inside the current thread subgroup.
522    pub fn thread_entry_path<P: AsRef<Path>>(&self, relative_file: P) -> PathBuf {
523        self.thread_group().entry_path(relative_file)
524    }
525
526    /// Touch an entry inside the current thread subgroup.
527    pub fn touch_thread_entry<P: AsRef<Path>>(&self, relative_file: P) -> io::Result<PathBuf> {
528        self.ensure_thread_group()?.touch(relative_file)
529    }
530}
531
532#[cfg(feature = "process-scoped-cache")]
533fn current_thread_cache_group_id() -> u64 {
534    thread_local! {
535        static THREAD_GROUP_ID: Cell<Option<u64>> = const { Cell::new(None) };
536    }
537
538    static NEXT_THREAD_GROUP_ID: AtomicU64 = AtomicU64::new(1);
539
540    THREAD_GROUP_ID.with(|slot| {
541        if let Some(id) = slot.get() {
542            id
543        } else {
544            let id = NEXT_THREAD_GROUP_ID.fetch_add(1, Ordering::Relaxed);
545            slot.set(Some(id));
546            id
547        }
548    })
549}
550
551fn find_crate_root(start: &Path) -> Option<PathBuf> {
552    let mut current = start.to_path_buf();
553    let mut nearest: Option<PathBuf> = None;
554    loop {
555        let cargo_path = current.join(CARGO_TOML_FILE_NAME);
556        if cargo_path.is_file() {
557            if nearest.is_none() {
558                nearest = Some(current.clone());
559            }
560            if let Ok(content) = fs::read_to_string(&cargo_path)
561                && content.lines().any(|line| line.trim() == "[workspace]")
562            {
563                return Some(current);
564            }
565        }
566        if !current.pop() {
567            return nearest;
568        }
569    }
570}
571
572fn apply_evict_policy(root: &Path, policy: &EvictPolicy) -> io::Result<()> {
573    let report = build_eviction_report(root, policy)?;
574
575    for path in report.marked_for_eviction {
576        let _ = fs::remove_file(path);
577    }
578
579    Ok(())
580}
581
582fn sort_entries_oldest_first(entries: &mut [FileEntry]) {
583    entries.sort_by(|a, b| {
584        let ta = a
585            .modified
586            .duration_since(UNIX_EPOCH)
587            .unwrap_or(Duration::ZERO);
588        let tb = b
589            .modified
590            .duration_since(UNIX_EPOCH)
591            .unwrap_or(Duration::ZERO);
592        ta.cmp(&tb).then_with(|| a.path.cmp(&b.path))
593    });
594}
595
596fn build_eviction_report(root: &Path, policy: &EvictPolicy) -> io::Result<EvictionReport> {
597    let mut entries = collect_files(root)?;
598    let mut marked_for_eviction = Vec::new();
599
600    if let Some(max_age) = policy.max_age {
601        let now = SystemTime::now();
602        let mut survivors = Vec::with_capacity(entries.len());
603        for entry in entries {
604            let age = now.duration_since(entry.modified).unwrap_or(Duration::ZERO);
605            if age >= max_age {
606                marked_for_eviction.push(entry.path);
607            } else {
608                survivors.push(entry);
609            }
610        }
611        entries = survivors;
612    }
613
614    sort_entries_oldest_first(&mut entries);
615
616    if let Some(max_files) = policy.max_files
617        && entries.len() > max_files
618    {
619        let to_remove = entries.len() - max_files;
620        for entry in entries.iter().take(to_remove) {
621            marked_for_eviction.push(entry.path.clone());
622        }
623        entries = entries.into_iter().skip(to_remove).collect();
624        sort_entries_oldest_first(&mut entries);
625    }
626
627    if let Some(max_bytes) = policy.max_bytes {
628        let mut total: u64 = entries.iter().map(|e| e.len).sum();
629        if total > max_bytes {
630            for entry in &entries {
631                if total <= max_bytes {
632                    break;
633                }
634                marked_for_eviction.push(entry.path.clone());
635                total = total.saturating_sub(entry.len);
636            }
637        }
638    }
639
640    Ok(EvictionReport {
641        marked_for_eviction,
642    })
643}
644
645fn collect_files(root: &Path) -> io::Result<Vec<FileEntry>> {
646    let mut out = Vec::new();
647    collect_files_recursive(root, &mut out)?;
648    Ok(out)
649}
650
651fn collect_files_recursive(dir: &Path, out: &mut Vec<FileEntry>) -> io::Result<()> {
652    for entry in fs::read_dir(dir)? {
653        let entry = entry?;
654        let path = entry.path();
655        let meta = entry.metadata()?;
656        if meta.is_dir() {
657            collect_files_recursive(&path, out)?;
658        } else if meta.is_file() {
659            out.push(FileEntry {
660                path,
661                modified: meta.modified().unwrap_or(UNIX_EPOCH),
662                len: meta.len(),
663            });
664        }
665    }
666    Ok(())
667}
668
669/// Counts of cache entries made owner-writable by [`ensure_writable_tree`].
670#[derive(Clone, Debug, Default, PartialEq, Eq)]
671pub struct WritableReport {
672    /// Regular files that gained owner-write (Unix) or lost the readonly
673    /// flag (Windows).
674    pub files_fixed: u64,
675    /// Directories that gained owner-write (Unix) or lost the readonly
676    /// flag (Windows).
677    pub dirs_fixed: u64,
678}
679
680/// Ensure every entry under `root` (inclusive) is owner-writable, so later
681/// cache operations (attribute changes, rotation, deletion) never fail on
682/// read-only modes inherited from release archives.
683///
684/// Call it once, right after extracting an archive into its final cache
685/// location. It fixes the observed failure where `0444` files from release
686/// tarballs made post-extract steps (e.g. macOS `xattr -dr` quarantine
687/// strips, Windows tree deletion on rotation) fail with permission errors.
688/// There is deliberately no staging concept in this crate: validity of a
689/// cached tree is the presence of the caller's sentinel file, so a killed
690/// fetch leaves a sentinel-less tree the next run simply refetches.
691///
692/// Semantics, by platform:
693/// - Unix: sets the owner-write bit (`0o200`), preserving every other
694///   mode bit. Never broadens group/other access.
695/// - Windows (and other non-Unix): clears the readonly flag. This is the
696///   portable `set_readonly(false)` behavior.
697///
698/// Security contract:
699/// - Symlinks are never followed and never modified (a malicious archive
700///   cannot redirect the walk outside `root`, and link targets keep their
701///   modes).
702/// - Traversal stays under `root`: recursion only descends into
703///   directories reached via `read_dir` from `root`.
704/// - Deterministic order (sorted entries), so repeated runs behave
705///   identically.
706/// - Fail-closed: the first I/O error aborts with the offending path in
707///   the message.
708///
709/// Returns counts of fixed entries; a second run over the same tree
710/// reports zeros.
711pub fn ensure_writable_tree(root: &Path) -> io::Result<WritableReport> {
712    // Probe once, up front: a symlinked root would send the walk outside
713    // the tree it claims to normalize (fail closed), and a file root has
714    // no children to descend into (fix in place, no read_dir).
715    let meta = fs::symlink_metadata(root).map_err(|e| path_error(root, e))?;
716    if meta.file_type().is_symlink() {
717        return Err(io::Error::new(
718            io::ErrorKind::InvalidInput,
719            format!("cache permissions ({}): root is a symlink", root.display()),
720        ));
721    }
722    let mut report = WritableReport::default();
723    if meta.is_file() {
724        fix_one(root, &mut report).map_err(|e| path_error(root, e))?;
725        return Ok(report);
726    }
727    ensure_writable_recursive(root, &mut report)?;
728    Ok(report)
729}
730
731fn ensure_writable_recursive(dir: &Path, report: &mut WritableReport) -> io::Result<()> {
732    fix_one(dir, report).map_err(|e| path_error(dir, e))?;
733    let mut entries: Vec<_> = fs::read_dir(dir)
734        .map_err(|e| path_error(dir, e))?
735        .collect::<Result<_, _>>()
736        .map_err(|e| path_error(dir, e))?;
737    entries.sort_by_key(|e| e.file_name());
738    for entry in entries {
739        let path = entry.path();
740        // `symlink_metadata`: never follow links. Files are fixed in place;
741        // symlinks route through `fix_one` (no-op guard) so the guard
742        // stays covered; other special nodes keep their modes.
743        let meta = fs::symlink_metadata(&path).map_err(|e| path_error(&path, e))?;
744        if meta.is_dir() {
745            ensure_writable_recursive(&path, report)?;
746        } else if meta.is_file() || meta.file_type().is_symlink() {
747            // Route symlinks through `fix_one` so its no-op guard stays
748            // covered: link itself and target keep their modes.
749            fix_one(&path, report).map_err(|e| path_error(&path, e))?;
750        }
751    }
752    Ok(())
753}
754
755/// Clear the read-only state of one real file or directory, counting the
756/// fix. Symlinks never reach modification: `ensure_writable_recursive`
757/// only calls this on the root and on `is_file()` entries probed via
758/// `symlink_metadata`, but the guard below makes it structural — even a
759/// symlinked root keeps its link (and its target) untouched.
760fn fix_one(path: &Path, report: &mut WritableReport) -> io::Result<()> {
761    let meta = fs::symlink_metadata(path)?;
762    if meta.file_type().is_symlink() {
763        return Ok(());
764    }
765    #[cfg(unix)]
766    {
767        use std::os::unix::fs::PermissionsExt;
768        // Directories need owner rwx (0o700): read-only-plus-write (0o600)
769        // still denies listing and traversal, which aborts the walk below
770        // with EACCES. Files need owner-write only (0o200): nothing else
771        // may change.
772        let required = if meta.is_dir() { 0o700 } else { 0o200 };
773        let mode = meta.permissions().mode();
774        if mode & required != required {
775            let mut permissions = meta.permissions();
776            permissions.set_mode(mode | required);
777            fs::set_permissions(path, permissions)?;
778            if meta.is_dir() {
779                report.dirs_fixed += 1;
780            } else {
781                report.files_fixed += 1;
782            }
783        }
784    }
785    #[cfg(not(unix))]
786    {
787        let mut permissions = meta.permissions();
788        if permissions.readonly() {
789            // `set_readonly(false)` is correct here: this block only compiles
790            // on non-Unix targets (Windows), where it clears the readonly
791            // attribute. The `permissions_set_readonly_false` lint warns
792            // about Unix semantics (world-writable), which do not apply.
793            #[allow(clippy::permissions_set_readonly_false)]
794            permissions.set_readonly(false);
795            fs::set_permissions(path, permissions)?;
796            if meta.is_dir() {
797                report.dirs_fixed += 1;
798            } else {
799                report.files_fixed += 1;
800            }
801        }
802    }
803    Ok(())
804}
805
806fn path_error(path: &Path, e: io::Error) -> io::Error {
807    io::Error::new(
808        e.kind(),
809        format!("cache permissions ({}): {e}", path.display()),
810    )
811}
812
813#[cfg(test)]
814mod tests {
815    use super::*;
816    use std::collections::BTreeSet;
817    // Serialize tests that mutate the process working directory.
818    //
819    // Many unit tests temporarily call `env::set_current_dir` to exercise
820    // discovery behavior. Because the process CWD is global, those tests
821    // can race when run in parallel and cause flaky failures (different
822    // tests observing different CWDs). We use a global `Mutex<()>` to
823    // serialize CWD-changing tests so they run one at a time.
824    use std::sync::{Mutex, MutexGuard, OnceLock};
825    use tempfile::TempDir;
826
827    /// Return the global mutex used to serialize tests that change the
828    /// process current working directory. Stored in a `OnceLock` so it is
829    /// initialized on first use and lives for the duration of the process.
830    fn cwd_lock() -> &'static Mutex<()> {
831        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
832        LOCK.get_or_init(|| Mutex::new(()))
833    }
834
835    /// Test helper that temporarily changes the process current working
836    /// directory and restores it when dropped. While alive it also holds
837    /// the global `cwd_lock()` so no two tests can race by changing the
838    /// CWD concurrently.
839    struct CwdGuard {
840        previous: PathBuf,
841        // Hold the guard so the lock remains taken for the lifetime of
842        // this `CwdGuard` instance.
843        _cwd_lock: MutexGuard<'static, ()>,
844    }
845
846    impl CwdGuard {
847        fn swap_to(path: &Path) -> io::Result<Self> {
848            // Acquire the global lock before mutating the CWD to avoid
849            // races with other tests that also change the CWD.
850            let cwd_lock_guard = cwd_lock().lock().expect("acquire cwd test lock");
851            let previous = env::current_dir()?;
852            env::set_current_dir(path)?;
853            Ok(Self {
854                previous,
855                _cwd_lock: cwd_lock_guard,
856            })
857        }
858    }
859
860    impl Drop for CwdGuard {
861        fn drop(&mut self) {
862            let _ = env::set_current_dir(&self.previous);
863        }
864    }
865
866    #[test]
867    fn from_discovery_uses_cwd_dot_cache_when_no_cargo_toml() {
868        let tmp = TempDir::new().expect("tempdir");
869        let _guard = CwdGuard::swap_to(tmp.path()).expect("set cwd");
870
871        let cache = CacheRoot::from_discovery().expect("discover");
872        let got = cache.path().to_path_buf();
873        let expected = tmp
874            .path()
875            .canonicalize()
876            .expect("canonicalize temp path")
877            .join(CACHE_DIR_NAME);
878        assert_eq!(got, expected);
879    }
880
881    #[test]
882    fn from_discovery_prefers_nearest_crate_root() {
883        let tmp = TempDir::new().expect("tempdir");
884        let crate_root = tmp.path().join("workspace");
885        let nested = crate_root.join("src").join("nested");
886        fs::create_dir_all(&nested).expect("create nested");
887        fs::write(
888            crate_root.join(CARGO_TOML_FILE_NAME),
889            "[package]\nname='x'\nversion='0.1.0'\nedition='2024'\n",
890        )
891        .expect("write cargo");
892
893        let _guard = CwdGuard::swap_to(&nested).expect("set cwd");
894        let cache = CacheRoot::from_discovery().expect("discover");
895        let got = cache.path().to_path_buf();
896        let expected = crate_root
897            .canonicalize()
898            .expect("canonicalize crate root")
899            .join(CACHE_DIR_NAME);
900        assert_eq!(got, expected);
901    }
902
903    #[test]
904    fn from_discovery_prefers_workspace_root_over_subcrate() {
905        let tmp = TempDir::new().expect("tempdir");
906        let workspace_root = tmp.path().join("workspace");
907        let sub_crate = workspace_root.join("crates").join("my-crate");
908        fs::create_dir_all(&sub_crate).expect("create sub-crate");
909        // Workspace root Cargo.toml with [workspace] section.
910        fs::write(
911            workspace_root.join(CARGO_TOML_FILE_NAME),
912            "[workspace]\n[package]\nname='workspace-root'\nversion='0.1.0'\nedition='2024'\n",
913        )
914        .expect("write workspace Cargo.toml");
915        // Sub-crate Cargo.toml without [workspace].
916        fs::write(
917            sub_crate.join(CARGO_TOML_FILE_NAME),
918            "[package]\nname='my-crate'\nversion='0.1.0'\nedition='2024'\n",
919        )
920        .expect("write sub-crate Cargo.toml");
921
922        let _guard = CwdGuard::swap_to(&sub_crate).expect("set cwd");
923        let cache = CacheRoot::from_discovery().expect("discover");
924        let got = cache.path().to_path_buf();
925        let expected = workspace_root
926            .canonicalize()
927            .expect("canonicalize workspace root")
928            .join(CACHE_DIR_NAME);
929        assert_eq!(got, expected);
930    }
931
932    #[cfg(unix)]
933    #[test]
934    fn from_discovery_skips_permission_denied_cargo_toml_and_falls_back_to_cwd() {
935        use std::os::unix::fs::PermissionsExt;
936
937        let tmp = TempDir::new().expect("tempdir");
938        fs::write(tmp.path().join(CARGO_TOML_FILE_NAME), "[workspace]").expect("write Cargo.toml");
939        // Remove read permission — is_file() returns true but
940        // read_to_string fails with PermissionDenied.
941        fs::set_permissions(
942            tmp.path().join(CARGO_TOML_FILE_NAME),
943            std::fs::Permissions::from_mode(0o000),
944        )
945        .expect("set permissions");
946
947        let _guard = CwdGuard::swap_to(tmp.path()).expect("set cwd");
948        let cache = CacheRoot::from_discovery().expect("discover");
949        // Falls back to cwd/.cache since Cargo.toml can't be read.
950        let expected = tmp
951            .path()
952            .canonicalize()
953            .expect("canonicalize")
954            .join(CACHE_DIR_NAME);
955        assert_eq!(cache.path(), expected);
956
957        // Restore so TempDir cleanup can remove the file.
958        fs::set_permissions(
959            tmp.path().join(CARGO_TOML_FILE_NAME),
960            std::fs::Permissions::from_mode(0o644),
961        )
962        .expect("restore permissions");
963    }
964
965    #[test]
966    fn from_root_supports_arbitrary_path_and_grouping() {
967        let tmp = TempDir::new().expect("tempdir");
968        let root = CacheRoot::from_root(tmp.path().join("custom-cache-root"));
969        let group = root.group("taxonomy/v1");
970
971        assert_eq!(group.path(), root.path().join("taxonomy/v1").as_path());
972    }
973
974    #[test]
975    fn group_path_building_and_dir_creation() {
976        let tmp = TempDir::new().expect("tempdir");
977        let cache = CacheRoot::from_root(tmp.path());
978        let group = cache.group("artifacts/json");
979
980        let nested_group = group.subgroup("v1");
981        let ensured = nested_group.ensure_dir().expect("ensure nested dir");
982        let expected_group_suffix = Path::new("artifacts").join("json").join("v1");
983        assert!(ensured.ends_with(&expected_group_suffix));
984        assert!(ensured.exists());
985
986        let entry = nested_group.entry_path("a/b/cache.json");
987        let expected_entry_suffix = Path::new("artifacts")
988            .join("json")
989            .join("v1")
990            .join("a")
991            .join("b")
992            .join("cache.json");
993        assert!(entry.ends_with(&expected_entry_suffix));
994    }
995
996    #[test]
997    fn touch_creates_blank_file_and_is_idempotent() {
998        let tmp = TempDir::new().expect("tempdir");
999        let cache = CacheRoot::from_root(tmp.path());
1000        let group = cache.group("artifacts/json");
1001
1002        let touched = group.touch("a/b/cache.json").expect("touch file");
1003        assert!(touched.exists());
1004        let meta = fs::metadata(&touched).expect("metadata");
1005        assert_eq!(meta.len(), 0);
1006
1007        let touched_again = group.touch("a/b/cache.json").expect("touch file again");
1008        assert_eq!(touched_again, touched);
1009        let meta_again = fs::metadata(&touched_again).expect("metadata again");
1010        assert_eq!(meta_again.len(), 0);
1011    }
1012
1013    #[test]
1014    fn touch_with_root_group_and_empty_relative_path_errors() {
1015        let root = CacheRoot::from_root("/");
1016        let group = root.group("");
1017
1018        let result = group.touch("");
1019        assert!(result.is_err());
1020    }
1021
1022    #[test]
1023    fn from_discovery_cache_path_uses_root_and_group() {
1024        let tmp = TempDir::new().expect("tempdir");
1025        let crate_root = tmp.path().join("workspace");
1026        let nested = crate_root.join("src").join("nested");
1027        fs::create_dir_all(&nested).expect("create nested");
1028        fs::write(
1029            crate_root.join(CARGO_TOML_FILE_NAME),
1030            "[package]\nname='x'\nversion='0.1.0'\nedition='2024'\n",
1031        )
1032        .expect("write cargo");
1033
1034        let _guard = CwdGuard::swap_to(&nested).expect("set cwd");
1035        let p = CacheRoot::from_discovery()
1036            .expect("discover")
1037            .cache_path("taxonomy", "taxonomy_cache.json");
1038        let parent = p.parent().expect("cache path parent");
1039        fs::create_dir_all(parent).expect("create cache parent");
1040        // Ensure the expected (non-canonicalized) parent path also exists
1041        // so canonicalization succeeds on platforms where temporary paths
1042        // may differ from the discovered/canonicalized root.
1043        let expected_dir = crate_root.join(CACHE_DIR_NAME).join("taxonomy");
1044        fs::create_dir_all(&expected_dir).expect("create expected cache parent");
1045        let got_parent = p
1046            .parent()
1047            .expect("cache path parent")
1048            .canonicalize()
1049            .expect("canonicalize cache parent");
1050        let expected_parent = crate_root
1051            .join(CACHE_DIR_NAME)
1052            .join("taxonomy")
1053            .canonicalize()
1054            .expect("canonicalize expected parent");
1055        assert_eq!(got_parent, expected_parent);
1056        assert_eq!(
1057            p.file_name().and_then(|s| s.to_str()),
1058            Some("taxonomy_cache.json")
1059        );
1060    }
1061
1062    #[test]
1063    fn from_discovery_ignores_other_custom_cache_dir_names() {
1064        let tmp = TempDir::new().expect("tempdir");
1065        let crate_root = tmp.path().join("workspace");
1066        let nested = crate_root.join("src").join("nested");
1067        fs::create_dir_all(&nested).expect("create nested");
1068        fs::write(
1069            crate_root.join(CARGO_TOML_FILE_NAME),
1070            "[package]\nname='x'\nversion='0.1.0'\nedition='2024'\n",
1071        )
1072        .expect("write cargo");
1073
1074        // Create a non-standard cache directory name at the crate root.
1075        fs::create_dir_all(crate_root.join(".cache-v2")).expect("create custom cache dir");
1076
1077        let _guard = CwdGuard::swap_to(&nested).expect("set cwd");
1078        let cache = CacheRoot::from_discovery().expect("discover");
1079
1080        // from_discovery should still resolve to `<crate_root>/.cache` (not `.cache-v2`).
1081        let expected = crate_root
1082            .canonicalize()
1083            .expect("canonicalize crate root")
1084            .join(CACHE_DIR_NAME);
1085        assert_eq!(cache.path(), expected);
1086    }
1087
1088    #[test]
1089    fn cache_path_preserves_absolute_paths() {
1090        let root = CacheRoot::from_root("/tmp/project");
1091        let absolute = PathBuf::from("/tmp/custom/cache.json");
1092        let resolved = root.cache_path(CACHE_DIR_NAME, &absolute);
1093        assert_eq!(resolved, absolute);
1094    }
1095
1096    // --- CacheResolver ------------------------------------------------------
1097    //
1098    // Every test below holds CwdGuard (global CWD mutex) even when it only
1099    // mutates env vars: env is process-global too, and the shared lock is
1100    // what serializes these tests against each other and the CWD tests.
1101
1102    /// RAII guard for a process-global env var: captures the prior value on
1103    /// creation and restores it in `Drop`, so a panicking assertion can never
1104    /// poison the environment for later tests. Bind as `_env_guard` and keep
1105    /// it alive for the whole test.
1106    struct EnvGuard {
1107        name: String,
1108        prior: Option<String>,
1109    }
1110
1111    impl EnvGuard {
1112        fn take(name: &str) -> Self {
1113            Self {
1114                name: name.to_string(),
1115                prior: env::var(name).ok(),
1116            }
1117        }
1118    }
1119
1120    impl Drop for EnvGuard {
1121        fn drop(&mut self) {
1122            // SAFETY: process-global env mutation is sound here because every
1123            // test that touches env holds the shared `cwd_lock()`, so no two
1124            // tests can race, and this exact var is restored to its prior
1125            // value (no other thread observes these test-scoped names).
1126            unsafe {
1127                match &self.prior {
1128                    Some(v) => env::set_var(&self.name, v),
1129                    None => env::remove_var(&self.name),
1130                }
1131            }
1132        }
1133    }
1134
1135    #[test]
1136    fn resolver_explicit_wins_over_everything() {
1137        let tmp = TempDir::new().expect("tempdir");
1138        let _guard = CwdGuard::swap_to(tmp.path()).expect("set cwd");
1139        let name = "CACHE_MANAGER_TEST_RESOLVER_EXPLICIT";
1140        let _env_guard = EnvGuard::take(name);
1141        // SAFETY: serialized by CwdGuard's global lock; test-scoped name.
1142        unsafe { env::set_var(name, tmp.path().join("env-root")) };
1143        // Also plant a workspace: explicit must still win over discovery.
1144        fs::write(tmp.path().join("Cargo.toml"), "[workspace]\n").expect("write cargo");
1145
1146        let explicit = tmp.path().join("explicit-root");
1147        let r = CacheResolver {
1148            explicit: Some(explicit.clone()),
1149            env_var: Some(name.to_string()),
1150            ..CacheResolver::default()
1151        };
1152        let (root, source) = r.resolve().expect("resolve");
1153        assert_eq!(source, CacheSource::Explicit);
1154        assert_eq!(root.path(), explicit.as_path());
1155    }
1156
1157    #[test]
1158    fn resolver_env_var_second_and_skips_empty() {
1159        let tmp = TempDir::new().expect("tempdir");
1160        let _guard = CwdGuard::swap_to(tmp.path()).expect("set cwd");
1161        let name = "CACHE_MANAGER_TEST_RESOLVER_ENV";
1162        // Pre-seed a sentinel: proves EnvGuard restores a prior value
1163        // (not just the unset case) when it drops.
1164        // SAFETY: serialized by CwdGuard's global lock; test-scoped name.
1165        unsafe { env::set_var(name, "sentinel") };
1166        {
1167            let _env_guard = EnvGuard::take(name);
1168
1169            // Empty counts as unset → NotFound (no workspace, no identity).
1170            // SAFETY: same serialization; guard restores on unwind.
1171            unsafe { env::set_var(name, "") };
1172            let r = CacheResolver {
1173                env_var: Some(name.to_string()),
1174                ..CacheResolver::default()
1175            };
1176            let err = r.resolve().expect_err("empty env must fall through");
1177            assert_eq!(err.kind(), io::ErrorKind::NotFound);
1178            assert!(
1179                format!("{err}").contains(name),
1180                "error must name the env var: {err}"
1181            );
1182
1183            // Non-empty wins.
1184            let env_root = tmp.path().join("env-root");
1185            // SAFETY: same serialization; guard restores on unwind.
1186            unsafe { env::set_var(name, &env_root) };
1187            let (root, source) = r.resolve().expect("resolve");
1188            assert_eq!(source, CacheSource::EnvVar);
1189            assert_eq!(root.path(), env_root.as_path());
1190        }
1191        // Guard dropped here: prior sentinel value must be back.
1192        assert_eq!(env::var(name).as_deref(), Ok("sentinel"));
1193        // SAFETY: test cleanup of a test-scoped name; suite holds the lock.
1194        unsafe { env::remove_var(name) };
1195    }
1196
1197    #[test]
1198    fn resolver_project_discovery_third() {
1199        let tmp = TempDir::new().expect("tempdir");
1200        let crate_root = tmp.path().join("workspace");
1201        let nested = crate_root.join("src").join("nested");
1202        fs::create_dir_all(&nested).expect("create nested");
1203        fs::write(
1204            crate_root.join(CARGO_TOML_FILE_NAME),
1205            "[package]\nname='x'\nversion='0.1.0'\nedition='2024'\n",
1206        )
1207        .expect("write cargo");
1208        let _guard = CwdGuard::swap_to(&nested).expect("set cwd");
1209
1210        let (root, source) = CacheResolver::default().resolve().expect("resolve");
1211        assert_eq!(source, CacheSource::ProjectDiscovery);
1212        let expected = crate_root
1213            .canonicalize()
1214            .expect("canonicalize")
1215            .join(CACHE_DIR_NAME);
1216        assert_eq!(root.path(), expected.as_path());
1217    }
1218
1219    #[test]
1220    fn resolver_no_workspace_without_identity_is_not_found_not_cwd() {
1221        // Bare dir, no Cargo.toml anywhere above, no identity configured:
1222        // the whole point of the resolver — NEVER silently <cwd>/.cache.
1223        let tmp = TempDir::new().expect("tempdir");
1224        let bare = tmp.path().join("bare");
1225        fs::create_dir_all(&bare).expect("create bare");
1226        let _guard = CwdGuard::swap_to(&bare).expect("set cwd");
1227
1228        let err = CacheResolver::default()
1229            .resolve()
1230            .expect_err("must not fall back to CWD");
1231        assert_eq!(err.kind(), io::ErrorKind::NotFound);
1232        assert!(
1233            !bare.join(CACHE_DIR_NAME).exists(),
1234            "resolver must not create anything on failure"
1235        );
1236    }
1237
1238    #[test]
1239    fn resolver_cwd_fallback_is_explicit_opt_in() {
1240        let tmp = TempDir::new().expect("tempdir");
1241        let bare = tmp.path().join("bare");
1242        fs::create_dir_all(&bare).expect("create bare");
1243        let _guard = CwdGuard::swap_to(&bare).expect("set cwd");
1244
1245        let r = CacheResolver {
1246            allow_cwd_fallback: true,
1247            ..CacheResolver::default()
1248        };
1249        let (root, source) = r.resolve().expect("resolve");
1250        assert_eq!(source, CacheSource::CwdFallback);
1251        let expected = bare
1252            .canonicalize()
1253            .expect("canonicalize")
1254            .join(CACHE_DIR_NAME);
1255        assert_eq!(root.path(), expected.as_path());
1256    }
1257
1258    #[test]
1259    fn resolver_discovery_opt_out_skips_to_not_found() {
1260        let tmp = TempDir::new().expect("tempdir");
1261        let crate_root = tmp.path().join("workspace");
1262        fs::create_dir_all(&crate_root).expect("create root");
1263        fs::write(crate_root.join(CARGO_TOML_FILE_NAME), "[workspace]\n").expect("write cargo");
1264        let _guard = CwdGuard::swap_to(&crate_root).expect("set cwd");
1265
1266        let r = CacheResolver {
1267            allow_project_discovery: false,
1268            ..CacheResolver::default()
1269        };
1270        let err = r.resolve().expect_err("discovery disabled → NotFound");
1271        assert_eq!(err.kind(), io::ErrorKind::NotFound);
1272        // Error must describe the actual path taken: discovery was skipped,
1273        // not attempted-and-failed.
1274        let msg = format!("{err}");
1275        assert!(
1276            msg.contains("project discovery is disabled"),
1277            "wrong error state: {msg}"
1278        );
1279        assert!(
1280            !msg.contains("no Cargo workspace above"),
1281            "false audit trail: {msg}"
1282        );
1283    }
1284
1285    #[cfg(feature = "os-cache-dir")]
1286    #[test]
1287    fn resolver_os_cache_dir_when_no_workspace() {
1288        let tmp = TempDir::new().expect("tempdir");
1289        let bare = tmp.path().join("bare");
1290        fs::create_dir_all(&bare).expect("create bare");
1291        let _guard = CwdGuard::swap_to(&bare).expect("set cwd");
1292
1293        let r = CacheResolver {
1294            project_dirs: Some((
1295                "com".to_string(),
1296                "CacheManagerTests".to_string(),
1297                "ResolverOsCache".to_string(),
1298            )),
1299            ..CacheResolver::default()
1300        };
1301        let (root, source) = r.resolve().expect("resolve");
1302        assert_eq!(source, CacheSource::OsCacheDir);
1303        let expected = ProjectDirs::from("com", "CacheManagerTests", "ResolverOsCache")
1304            .expect("project dirs")
1305            .cache_dir()
1306            .to_path_buf();
1307        assert_eq!(root.path(), expected.as_path());
1308    }
1309
1310    #[cfg(feature = "os-cache-dir")]
1311    #[test]
1312    fn resolver_env_beats_os_cache_and_explicit_beats_env() {
1313        let tmp = TempDir::new().expect("tempdir");
1314        let bare = tmp.path().join("bare");
1315        fs::create_dir_all(&bare).expect("create bare");
1316        let _guard = CwdGuard::swap_to(&bare).expect("set cwd");
1317        let name = "CACHE_MANAGER_TEST_RESOLVER_PRECEDENCE";
1318        let _env_guard = EnvGuard::take(name);
1319        let env_root = tmp.path().join("env-root");
1320        // SAFETY: serialized by CwdGuard's global lock; test-scoped name.
1321        unsafe { env::set_var(name, &env_root) };
1322
1323        let os_only = CacheResolver {
1324            project_dirs: Some((
1325                "com".to_string(),
1326                "CacheManagerTests".to_string(),
1327                "ResolverPrecedence".to_string(),
1328            )),
1329            ..CacheResolver::default()
1330        };
1331        // Env not consulted (no env_var configured) → OS cache.
1332        let (_, source) = os_only.resolve().expect("resolve");
1333        assert_eq!(source, CacheSource::OsCacheDir);
1334
1335        // Env configured → env wins over OS cache.
1336        let with_env = CacheResolver {
1337            env_var: Some(name.to_string()),
1338            ..os_only.clone()
1339        };
1340        let (root, source) = with_env.resolve().expect("resolve");
1341        assert_eq!(source, CacheSource::EnvVar);
1342        assert_eq!(root.path(), env_root.as_path());
1343
1344        // Explicit wins over env.
1345        let explicit = tmp.path().join("explicit-root");
1346        let with_explicit = CacheResolver {
1347            explicit: Some(explicit.clone()),
1348            ..with_env
1349        };
1350        let (root, source) = with_explicit.resolve().expect("resolve");
1351        assert_eq!(source, CacheSource::Explicit);
1352        assert_eq!(root.path(), explicit.as_path());
1353    }
1354
1355    #[cfg(feature = "os-cache-dir")]
1356    #[test]
1357    fn from_project_dirs_matches_directories_cache_dir() {
1358        let qualifier = "com";
1359        let organization = "CacheManagerTests";
1360        let application = "CacheManagerOsCacheRoot";
1361
1362        let expected = ProjectDirs::from(qualifier, organization, application)
1363            .expect("project dirs")
1364            .cache_dir()
1365            .to_path_buf();
1366
1367        let root = CacheRoot::from_project_dirs(qualifier, organization, application)
1368            .expect("from project dirs");
1369
1370        assert_eq!(root.path(), expected.as_path());
1371    }
1372
1373    #[cfg(feature = "os-cache-dir")]
1374    #[test]
1375    fn project_dirs_or_not_found_returns_not_found_for_none() {
1376        let err =
1377            project_dirs_or_not_found(None).expect_err("none project dirs should map to not found");
1378        assert_eq!(err.kind(), io::ErrorKind::NotFound);
1379    }
1380
1381    #[cfg(feature = "process-scoped-cache")]
1382    #[test]
1383    fn from_tempdir_creates_existing_writable_root() {
1384        let root = CacheRoot::from_tempdir().expect("from tempdir");
1385        assert!(root.path().is_dir());
1386
1387        let probe_group = root.group("probe");
1388        let probe_file = probe_group.touch("writable.txt").expect("touch probe");
1389        assert!(probe_file.is_file());
1390
1391        fs::remove_dir_all(root.path()).expect("cleanup temp root");
1392    }
1393
1394    #[test]
1395    fn ensure_dir_with_policy_max_files() {
1396        let tmp = TempDir::new().expect("tempdir");
1397        let cache = CacheRoot::from_root(tmp.path());
1398        let group = cache.group("artifacts");
1399        group.ensure_dir().expect("ensure dir");
1400
1401        fs::write(group.entry_path("a.txt"), b"1").expect("write a");
1402        fs::write(group.entry_path("b.txt"), b"1").expect("write b");
1403        fs::write(group.entry_path("c.txt"), b"1").expect("write c");
1404
1405        let policy = EvictPolicy {
1406            max_files: Some(2),
1407            ..EvictPolicy::default()
1408        };
1409        group
1410            .ensure_dir_with_policy(Some(&policy))
1411            .expect("ensure with policy");
1412
1413        let files = collect_files(group.path()).expect("collect files");
1414        assert_eq!(files.len(), 2);
1415    }
1416
1417    #[test]
1418    fn ensure_dir_with_policy_max_bytes() {
1419        let tmp = TempDir::new().expect("tempdir");
1420        let cache = CacheRoot::from_root(tmp.path());
1421        let group = cache.group("artifacts");
1422        group.ensure_dir().expect("ensure dir");
1423
1424        fs::write(group.entry_path("a.bin"), vec![1u8; 5]).expect("write a");
1425        fs::write(group.entry_path("b.bin"), vec![1u8; 5]).expect("write b");
1426        fs::write(group.entry_path("c.bin"), vec![1u8; 5]).expect("write c");
1427
1428        let policy = EvictPolicy {
1429            max_bytes: Some(10),
1430            ..EvictPolicy::default()
1431        };
1432        group
1433            .ensure_dir_with_policy(Some(&policy))
1434            .expect("ensure with policy");
1435
1436        let total: u64 = collect_files(group.path())
1437            .expect("collect files")
1438            .iter()
1439            .map(|f| f.len)
1440            .sum();
1441        assert!(total <= 10);
1442    }
1443
1444    #[test]
1445    fn ensure_dir_with_policy_max_age_zero_evicts_all() {
1446        let tmp = TempDir::new().expect("tempdir");
1447        let cache = CacheRoot::from_root(tmp.path());
1448        let group = cache.group("artifacts");
1449        group.ensure_dir().expect("ensure dir");
1450
1451        fs::write(group.entry_path("a.txt"), b"1").expect("write a");
1452        fs::write(group.entry_path("b.txt"), b"1").expect("write b");
1453
1454        let policy = EvictPolicy {
1455            max_age: Some(Duration::ZERO),
1456            ..EvictPolicy::default()
1457        };
1458        group
1459            .ensure_dir_with_policy(Some(&policy))
1460            .expect("ensure with policy");
1461
1462        let files = collect_files(group.path()).expect("collect files");
1463        assert!(files.is_empty());
1464    }
1465
1466    #[test]
1467    fn eviction_report_matches_applied_evictions() {
1468        let tmp = TempDir::new().expect("tempdir");
1469        let cache = CacheRoot::from_root(tmp.path());
1470        let group = cache.group("artifacts");
1471        group.ensure_dir().expect("ensure dir");
1472
1473        fs::write(group.entry_path("a.bin"), vec![1u8; 5]).expect("write a");
1474        fs::write(group.entry_path("b.bin"), vec![1u8; 5]).expect("write b");
1475        fs::write(group.entry_path("c.bin"), vec![1u8; 5]).expect("write c");
1476
1477        let policy = EvictPolicy {
1478            max_bytes: Some(10),
1479            ..EvictPolicy::default()
1480        };
1481
1482        let before: BTreeSet<PathBuf> = collect_files(group.path())
1483            .expect("collect before")
1484            .into_iter()
1485            .map(|f| f.path)
1486            .collect();
1487
1488        let report = group.eviction_report(&policy).expect("eviction report");
1489        let planned: BTreeSet<PathBuf> = report.marked_for_eviction.iter().cloned().collect();
1490
1491        group
1492            .ensure_dir_with_policy(Some(&policy))
1493            .expect("ensure with policy");
1494
1495        let after: BTreeSet<PathBuf> = collect_files(group.path())
1496            .expect("collect after")
1497            .into_iter()
1498            .map(|f| f.path)
1499            .collect();
1500
1501        let expected_after: BTreeSet<PathBuf> = before.difference(&planned).cloned().collect();
1502        assert_eq!(after, expected_after);
1503    }
1504
1505    #[test]
1506    fn no_policy_and_default_policy_report_do_not_mark_evictions() {
1507        let tmp = TempDir::new().expect("tempdir");
1508        let cache = CacheRoot::from_root(tmp.path());
1509        let group = cache.group("artifacts");
1510        group.ensure_dir().expect("ensure dir");
1511
1512        fs::write(group.entry_path("a.txt"), b"1").expect("write a");
1513        fs::write(group.entry_path("b.txt"), b"1").expect("write b");
1514
1515        let report = group
1516            .eviction_report(&EvictPolicy::default())
1517            .expect("eviction report");
1518        assert!(report.marked_for_eviction.is_empty());
1519
1520        group
1521            .ensure_dir_with_policy(None)
1522            .expect("ensure with no policy");
1523
1524        let files = collect_files(group.path()).expect("collect files");
1525        assert_eq!(files.len(), 2);
1526    }
1527
1528    #[test]
1529    fn eviction_policy_applies_in_documented_order() {
1530        let tmp = TempDir::new().expect("tempdir");
1531        let cache = CacheRoot::from_root(tmp.path());
1532        let group = cache.group("artifacts");
1533        group.ensure_dir().expect("ensure dir");
1534
1535        fs::write(group.entry_path("old.txt"), vec![1u8; 1]).expect("write old");
1536
1537        std::thread::sleep(Duration::from_millis(300));
1538
1539        fs::write(group.entry_path("b.bin"), vec![1u8; 7]).expect("write b");
1540        fs::write(group.entry_path("c.bin"), vec![1u8; 6]).expect("write c");
1541        fs::write(group.entry_path("d.bin"), vec![1u8; 1]).expect("write d");
1542
1543        let policy = EvictPolicy {
1544            max_age: Some(Duration::from_millis(200)),
1545            max_files: Some(2),
1546            max_bytes: Some(5),
1547        };
1548
1549        let report = group.eviction_report(&policy).expect("eviction report");
1550        let evicted_names: Vec<String> = report
1551            .marked_for_eviction
1552            .iter()
1553            .map(|path| {
1554                path.file_name()
1555                    .and_then(|name| name.to_str())
1556                    .expect("evicted file name")
1557                    .to_string()
1558            })
1559            .collect();
1560
1561        assert_eq!(evicted_names, vec!["old.txt", "b.bin", "c.bin"]);
1562
1563        group
1564            .ensure_dir_with_policy(Some(&policy))
1565            .expect("apply policy");
1566
1567        let remaining_names: BTreeSet<String> = collect_files(group.path())
1568            .expect("collect remaining")
1569            .into_iter()
1570            .map(|entry| {
1571                entry
1572                    .path
1573                    .file_name()
1574                    .and_then(|name| name.to_str())
1575                    .expect("remaining file name")
1576                    .to_string()
1577            })
1578            .collect();
1579
1580        assert_eq!(remaining_names, BTreeSet::from(["d.bin".to_string()]));
1581    }
1582
1583    #[test]
1584    fn sort_entries_uses_path_as_tie_break_for_equal_modified_time() {
1585        let same_time = UNIX_EPOCH + Duration::from_secs(1_234_567);
1586        let mut entries = vec![
1587            FileEntry {
1588                path: PathBuf::from("z.bin"),
1589                modified: same_time,
1590                len: 1,
1591            },
1592            FileEntry {
1593                path: PathBuf::from("a.bin"),
1594                modified: same_time,
1595                len: 1,
1596            },
1597            FileEntry {
1598                path: PathBuf::from("m.bin"),
1599                modified: same_time,
1600                len: 1,
1601            },
1602        ];
1603
1604        sort_entries_oldest_first(&mut entries);
1605
1606        let ordered_paths: Vec<PathBuf> = entries.into_iter().map(|entry| entry.path).collect();
1607        assert_eq!(
1608            ordered_paths,
1609            vec![
1610                PathBuf::from("a.bin"),
1611                PathBuf::from("m.bin"),
1612                PathBuf::from("z.bin")
1613            ]
1614        );
1615    }
1616
1617    #[test]
1618    fn single_root_supports_distinct_policies_per_subdirectory() {
1619        let tmp = TempDir::new().expect("tempdir");
1620        let cache = CacheRoot::from_root(tmp.path());
1621
1622        let images = cache.group("artifacts/images");
1623        let reports = cache.group("artifacts/reports");
1624
1625        images.ensure_dir().expect("ensure images dir");
1626        reports.ensure_dir().expect("ensure reports dir");
1627
1628        fs::write(images.entry_path("img1.bin"), vec![1u8; 5]).expect("write img1");
1629        fs::write(images.entry_path("img2.bin"), vec![1u8; 5]).expect("write img2");
1630        fs::write(images.entry_path("img3.bin"), vec![1u8; 5]).expect("write img3");
1631
1632        fs::write(reports.entry_path("a.txt"), b"1").expect("write report a");
1633        fs::write(reports.entry_path("b.txt"), b"1").expect("write report b");
1634        fs::write(reports.entry_path("c.txt"), b"1").expect("write report c");
1635
1636        let images_policy = EvictPolicy {
1637            max_bytes: Some(10),
1638            ..EvictPolicy::default()
1639        };
1640        let reports_policy = EvictPolicy {
1641            max_files: Some(1),
1642            ..EvictPolicy::default()
1643        };
1644
1645        images
1646            .ensure_dir_with_policy(Some(&images_policy))
1647            .expect("apply images policy");
1648        reports
1649            .ensure_dir_with_policy(Some(&reports_policy))
1650            .expect("apply reports policy");
1651
1652        let images_total: u64 = collect_files(images.path())
1653            .expect("collect images files")
1654            .iter()
1655            .map(|f| f.len)
1656            .sum();
1657        assert!(images_total <= 10);
1658
1659        let reports_files = collect_files(reports.path()).expect("collect reports files");
1660        assert_eq!(reports_files.len(), 1);
1661    }
1662
1663    #[test]
1664    fn group_path_and_ensure_group_create_expected_directory() {
1665        let tmp = TempDir::new().expect("tempdir");
1666        let cache = CacheRoot::from_root(tmp.path());
1667
1668        let expected = tmp.path().join("a/b/c");
1669        assert_eq!(cache.group_path("a/b/c"), expected);
1670
1671        let ensured = cache.ensure_group("a/b/c").expect("ensure group");
1672        assert_eq!(ensured, expected);
1673        assert!(ensured.is_dir());
1674    }
1675
1676    #[test]
1677    fn ensure_group_with_policy_applies_eviction_rules() {
1678        let tmp = TempDir::new().expect("tempdir");
1679        let cache = CacheRoot::from_root(tmp.path());
1680
1681        cache
1682            .ensure_group_with_policy("artifacts", None)
1683            .expect("ensure group without policy");
1684
1685        let group = cache.group("artifacts");
1686        fs::write(group.entry_path("a.bin"), vec![1u8; 1]).expect("write a");
1687        fs::write(group.entry_path("b.bin"), vec![1u8; 1]).expect("write b");
1688        fs::write(group.entry_path("c.bin"), vec![1u8; 1]).expect("write c");
1689
1690        let policy = EvictPolicy {
1691            max_files: Some(1),
1692            ..EvictPolicy::default()
1693        };
1694
1695        let ensured = cache
1696            .ensure_group_with_policy("artifacts", Some(&policy))
1697            .expect("ensure group with policy");
1698        assert_eq!(ensured, group.path());
1699
1700        let files = collect_files(group.path()).expect("collect files");
1701        assert_eq!(files.len(), 1);
1702    }
1703
1704    #[test]
1705    fn cache_path_joins_relative_paths_under_group() {
1706        let tmp = TempDir::new().expect("tempdir");
1707        let cache = CacheRoot::from_root(tmp.path());
1708
1709        let got = cache.cache_path(CACHE_DIR_NAME, "tool/v1/data.bin");
1710        let expected = tmp
1711            .path()
1712            .join(CACHE_DIR_NAME)
1713            .join("tool")
1714            .join("v1")
1715            .join("data.bin");
1716        assert_eq!(got, expected);
1717    }
1718
1719    #[test]
1720    fn subgroup_touch_creates_parent_directories() {
1721        let tmp = TempDir::new().expect("tempdir");
1722        let cache = CacheRoot::from_root(tmp.path());
1723        let subgroup = cache.group("artifacts").subgroup("json/v1");
1724
1725        let touched = subgroup
1726            .touch("nested/output.bin")
1727            .expect("touch subgroup entry");
1728
1729        assert!(touched.is_file());
1730        assert!(subgroup.path().join("nested").is_dir());
1731    }
1732
1733    #[test]
1734    fn eviction_report_errors_when_group_directory_is_missing() {
1735        let tmp = TempDir::new().expect("tempdir");
1736        let cache = CacheRoot::from_root(tmp.path());
1737        let missing = cache.group("does-not-exist");
1738
1739        let err = missing
1740            .eviction_report(&EvictPolicy::default())
1741            .expect_err("eviction report should fail for missing directory");
1742        assert_eq!(err.kind(), io::ErrorKind::NotFound);
1743    }
1744
1745    #[test]
1746    fn eviction_policy_scans_nested_subdirectories_recursively() {
1747        let tmp = TempDir::new().expect("tempdir");
1748        let cache = CacheRoot::from_root(tmp.path());
1749        let group = cache.group("artifacts");
1750        group.ensure_dir().expect("ensure dir");
1751
1752        fs::create_dir_all(group.entry_path("nested/deeper")).expect("create nested dirs");
1753        fs::write(group.entry_path("root.bin"), vec![1u8; 1]).expect("write root");
1754        fs::write(group.entry_path("nested/a.bin"), vec![1u8; 1]).expect("write nested a");
1755        fs::write(group.entry_path("nested/deeper/b.bin"), vec![1u8; 1]).expect("write nested b");
1756
1757        let policy = EvictPolicy {
1758            max_files: Some(1),
1759            ..EvictPolicy::default()
1760        };
1761
1762        group
1763            .ensure_dir_with_policy(Some(&policy))
1764            .expect("apply recursive policy");
1765
1766        let remaining = collect_files(group.path()).expect("collect remaining");
1767        assert_eq!(remaining.len(), 1);
1768    }
1769
1770    #[cfg(unix)]
1771    #[test]
1772    fn collect_files_recursive_ignores_non_file_non_directory_entries() {
1773        use std::os::unix::net::UnixListener;
1774
1775        let tmp = TempDir::new().expect("tempdir");
1776        let cache = CacheRoot::from_root(tmp.path());
1777        let group = cache.group("artifacts");
1778        group.ensure_dir().expect("ensure dir");
1779
1780        let socket_path = group.entry_path("live.sock");
1781        let _listener = UnixListener::bind(&socket_path).expect("bind unix socket");
1782
1783        fs::write(group.entry_path("a.bin"), vec![1u8; 1]).expect("write file");
1784
1785        let files = collect_files(group.path()).expect("collect files");
1786        assert_eq!(files.len(), 1);
1787        assert_eq!(files[0].path, group.entry_path("a.bin"));
1788    }
1789
1790    #[test]
1791    fn max_bytes_policy_under_threshold_does_not_evict() {
1792        let tmp = TempDir::new().expect("tempdir");
1793        let cache = CacheRoot::from_root(tmp.path());
1794        let group = cache.group("artifacts");
1795        group.ensure_dir().expect("ensure dir");
1796
1797        fs::write(group.entry_path("a.bin"), vec![1u8; 2]).expect("write a");
1798        fs::write(group.entry_path("b.bin"), vec![1u8; 3]).expect("write b");
1799
1800        let policy = EvictPolicy {
1801            max_bytes: Some(10),
1802            ..EvictPolicy::default()
1803        };
1804
1805        let report = group.eviction_report(&policy).expect("eviction report");
1806        assert!(report.marked_for_eviction.is_empty());
1807
1808        group
1809            .ensure_dir_with_policy(Some(&policy))
1810            .expect("ensure with policy");
1811
1812        let files = collect_files(group.path()).expect("collect files");
1813        assert_eq!(files.len(), 2);
1814    }
1815
1816    #[test]
1817    fn cwd_guard_swap_to_returns_error_for_missing_directory() {
1818        let tmp = TempDir::new().expect("tempdir");
1819        let missing = tmp.path().join("missing-dir");
1820
1821        let result = CwdGuard::swap_to(&missing);
1822        assert!(result.is_err());
1823        assert_eq!(
1824            result.err().expect("expected missing-dir error").kind(),
1825            io::ErrorKind::NotFound
1826        );
1827    }
1828
1829    #[test]
1830    fn ensure_dir_equals_ensure_dir_with_policy_none() {
1831        let tmp = TempDir::new().expect("tempdir");
1832        let cache = CacheRoot::from_root(tmp.path());
1833        let group = cache.group("artifacts/eq");
1834
1835        let p1 = group.ensure_dir().expect("ensure dir");
1836        // create a file so we can verify calling the policy-aware
1837        // variant with `None` does not remove or alter contents.
1838        fs::write(group.entry_path("keep.txt"), b"keep").expect("write file");
1839
1840        let p2 = group
1841            .ensure_dir_with_policy(None)
1842            .expect("ensure dir with None policy");
1843
1844        assert_eq!(p1, p2);
1845        assert!(group.entry_path("keep.txt").exists());
1846    }
1847
1848    #[test]
1849    fn ensure_group_equals_ensure_group_with_policy_none() {
1850        let tmp = TempDir::new().expect("tempdir");
1851        let cache = CacheRoot::from_root(tmp.path());
1852
1853        let p1 = cache.ensure_group("artifacts/roots").expect("ensure group");
1854        let group = cache.group("artifacts/roots");
1855        // create a file to ensure no-op policy does not remove it
1856        fs::write(group.entry_path("keep_root.txt"), b"keep").expect("write file");
1857
1858        let p2 = cache
1859            .ensure_group_with_policy("artifacts/roots", None)
1860            .expect("ensure group with None policy");
1861
1862        assert_eq!(p1, p2);
1863        assert!(group.entry_path("keep_root.txt").exists());
1864    }
1865
1866    #[cfg(feature = "process-scoped-cache")]
1867    #[test]
1868    fn process_scoped_cache_respects_root_and_group_assignments() {
1869        let tmp = TempDir::new().expect("tempdir");
1870        let root = CacheRoot::from_root(tmp.path().join("custom-root"));
1871
1872        let scoped = ProcessScopedCacheGroup::new(&root, "artifacts/session").expect("create");
1873        let expected_prefix = root.group("artifacts/session").path().to_path_buf();
1874
1875        assert!(scoped.path().starts_with(&expected_prefix));
1876        assert!(scoped.path().exists());
1877    }
1878
1879    #[cfg(feature = "process-scoped-cache")]
1880    #[test]
1881    fn process_scoped_cache_deletes_directory_on_drop() {
1882        let tmp = TempDir::new().expect("tempdir");
1883        let root = CacheRoot::from_root(tmp.path());
1884
1885        let process_dir = {
1886            let scoped = ProcessScopedCacheGroup::new(&root, "artifacts").expect("create");
1887            let p = scoped.path().to_path_buf();
1888            assert!(p.exists());
1889            p
1890        };
1891
1892        assert!(!process_dir.exists());
1893    }
1894
1895    #[cfg(feature = "process-scoped-cache")]
1896    #[test]
1897    fn process_scoped_cache_thread_group_is_stable_per_thread() {
1898        let tmp = TempDir::new().expect("tempdir");
1899        let root = CacheRoot::from_root(tmp.path());
1900        let scoped = ProcessScopedCacheGroup::new(&root, "artifacts").expect("create");
1901
1902        let first = scoped.thread_group().path().to_path_buf();
1903        let second = scoped.thread_group().path().to_path_buf();
1904
1905        assert_eq!(first, second);
1906    }
1907
1908    #[cfg(feature = "process-scoped-cache")]
1909    #[test]
1910    fn process_scoped_cache_thread_group_differs_across_threads() {
1911        let tmp = TempDir::new().expect("tempdir");
1912        let root = CacheRoot::from_root(tmp.path());
1913        let scoped = ProcessScopedCacheGroup::new(&root, "artifacts").expect("create");
1914
1915        let main_thread_group = scoped.thread_group().path().to_path_buf();
1916        let other_thread_group = std::thread::spawn(current_thread_cache_group_id)
1917            .join()
1918            .expect("join thread");
1919
1920        let expected_other = scoped
1921            .process_group()
1922            .subgroup(format!("thread-{other_thread_group}"))
1923            .path()
1924            .to_path_buf();
1925
1926        assert_ne!(main_thread_group, expected_other);
1927    }
1928
1929    #[cfg(feature = "process-scoped-cache")]
1930    #[test]
1931    fn process_scoped_cache_from_group_uses_given_base_group() {
1932        let tmp = TempDir::new().expect("tempdir");
1933        let root = CacheRoot::from_root(tmp.path());
1934        let base_group = root.group("artifacts/custom-base");
1935
1936        let scoped = ProcessScopedCacheGroup::from_group(base_group.clone()).expect("create");
1937
1938        assert!(scoped.path().starts_with(base_group.path()));
1939        assert_eq!(scoped.process_group().path(), scoped.path());
1940    }
1941
1942    #[cfg(feature = "process-scoped-cache")]
1943    #[test]
1944    fn process_scoped_cache_thread_entry_path_matches_touch_location() {
1945        let tmp = TempDir::new().expect("tempdir");
1946        let root = CacheRoot::from_root(tmp.path());
1947        let scoped = ProcessScopedCacheGroup::new(&root, "artifacts").expect("create");
1948
1949        let planned = scoped.thread_entry_path("nested/data.bin");
1950        let touched = scoped
1951            .touch_thread_entry("nested/data.bin")
1952            .expect("touch thread entry");
1953
1954        assert_eq!(planned, touched);
1955        assert!(touched.exists());
1956    }
1957
1958    #[cfg(feature = "process-scoped-cache")]
1959    #[test]
1960    fn touch_thread_entry_creates_entry_under_thread_group() {
1961        let tmp = TempDir::new().expect("tempdir");
1962        let root = CacheRoot::from_root(tmp.path());
1963        let scoped = ProcessScopedCacheGroup::new(&root, "artifacts").expect("create");
1964
1965        let entry = scoped
1966            .touch_thread_entry("nested/data.bin")
1967            .expect("touch thread entry");
1968
1969        assert!(entry.exists());
1970        assert!(entry.starts_with(scoped.path()));
1971        let thread_group = scoped.thread_group().path().to_path_buf();
1972        assert!(entry.starts_with(&thread_group));
1973    }
1974}