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    pub fn ensure_dir(&self) -> io::Result<&Path> {
394        self.ensure_dir_with_policy(None)
395    }
396
397    /// Ensures this directory exists, then applies optional eviction.
398    ///
399    /// Eviction is applied recursively to files under this directory. The
400    /// policy is best-effort for removals: individual delete failures are
401    /// ignored so initialization can continue.
402    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    /// Returns a report of files that would be evicted under `policy`.
411    ///
412    /// This does not delete files. The selection order matches the internal
413    /// order used by `ensure_dir_with_policy`.
414    /// Return a report of files that would be evicted by `policy`.
415    ///
416    /// The report is non-destructive and mirrors the selection used by
417    /// `ensure_dir_with_policy` so it can be used for previewing or testing.
418    pub fn eviction_report(&self, policy: &EvictPolicy) -> io::Result<EvictionReport> {
419        build_eviction_report(&self.path, policy)
420    }
421
422    /// Create a nested subgroup under this group.
423    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    /// Resolve a relative entry path under this group.
430    pub fn entry_path<P: AsRef<Path>>(&self, relative_file: P) -> PathBuf {
431        self.path.join(relative_file.as_ref())
432    }
433
434    /// Create or update (touch) a file under this group, creating parent
435    /// directories as needed. Returns the absolute path to the entry.
436    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/// Process-scoped cache group handle with per-thread subgroup helpers.
447///
448/// This type is available when the `process-scoped-cache` feature is enabled.
449///
450/// It creates an auto-generated process subdirectory under a user-selected
451/// base cache group. The backing directory is removed when this handle is
452/// dropped during normal process shutdown.
453///
454/// Notes:
455/// - Cleanup is best-effort and is not guaranteed after abnormal termination
456///   (for example `SIGKILL` or process crash).
457/// - All paths still respect the caller-provided `CacheRoot` and base group.
458#[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    /// Create a process-scoped cache handle under `root.group(relative_group)`.
468    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    /// Create a process-scoped cache handle under an existing base group.
473    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    /// Return the process-scoped directory path.
490    pub fn path(&self) -> &Path {
491        self.process_group.path()
492    }
493
494    /// Return the process-scoped cache group.
495    pub fn process_group(&self) -> CacheGroup {
496        self.process_group.clone()
497    }
498
499    /// Return the subgroup for the current thread.
500    ///
501    /// Each thread gets a stable, process-local incremental id (`thread-<n>`)
502    /// for the process lifetime.
503    pub fn thread_group(&self) -> CacheGroup {
504        self.process_group
505            .subgroup(format!("thread-{}", current_thread_cache_group_id()))
506    }
507
508    /// Ensure and return the subgroup for the current thread.
509    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    /// Build an entry path inside the current thread subgroup.
516    pub fn thread_entry_path<P: AsRef<Path>>(&self, relative_file: P) -> PathBuf {
517        self.thread_group().entry_path(relative_file)
518    }
519
520    /// Touch an entry inside the current thread subgroup.
521    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    // Serialize tests that mutate the process working directory.
668    //
669    // Many unit tests temporarily call `env::set_current_dir` to exercise
670    // discovery behavior. Because the process CWD is global, those tests
671    // can race when run in parallel and cause flaky failures (different
672    // tests observing different CWDs). We use a global `Mutex<()>` to
673    // serialize CWD-changing tests so they run one at a time.
674    use std::sync::{Mutex, MutexGuard, OnceLock};
675    use tempfile::TempDir;
676
677    /// Return the global mutex used to serialize tests that change the
678    /// process current working directory. Stored in a `OnceLock` so it is
679    /// initialized on first use and lives for the duration of the process.
680    fn cwd_lock() -> &'static Mutex<()> {
681        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
682        LOCK.get_or_init(|| Mutex::new(()))
683    }
684
685    /// Test helper that temporarily changes the process current working
686    /// directory and restores it when dropped. While alive it also holds
687    /// the global `cwd_lock()` so no two tests can race by changing the
688    /// CWD concurrently.
689    struct CwdGuard {
690        previous: PathBuf,
691        // Hold the guard so the lock remains taken for the lifetime of
692        // this `CwdGuard` instance.
693        _cwd_lock: MutexGuard<'static, ()>,
694    }
695
696    impl CwdGuard {
697        fn swap_to(path: &Path) -> io::Result<Self> {
698            // Acquire the global lock before mutating the CWD to avoid
699            // races with other tests that also change the CWD.
700            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        // Workspace root Cargo.toml with [workspace] section.
760        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        // Sub-crate Cargo.toml without [workspace].
766        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        // Remove read permission — is_file() returns true but
790        // read_to_string fails with PermissionDenied.
791        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        // Falls back to cwd/.cache since Cargo.toml can't be read.
800        let expected = tmp
801            .path()
802            .canonicalize()
803            .expect("canonicalize")
804            .join(CACHE_DIR_NAME);
805        assert_eq!(cache.path(), expected);
806
807        // Restore so TempDir cleanup can remove the file.
808        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        // Ensure the expected (non-canonicalized) parent path also exists
891        // so canonicalization succeeds on platforms where temporary paths
892        // may differ from the discovered/canonicalized root.
893        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        // Create a non-standard cache directory name at the crate root.
925        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        // from_discovery should still resolve to `<crate_root>/.cache` (not `.cache-v2`).
931        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    // --- CacheResolver ------------------------------------------------------
947    //
948    // Every test below holds CwdGuard (global CWD mutex) even when it only
949    // mutates env vars: env is process-global too, and the shared lock is
950    // what serializes these tests against each other and the CWD tests.
951
952    /// RAII guard for a process-global env var: captures the prior value on
953    /// creation and restores it in `Drop`, so a panicking assertion can never
954    /// poison the environment for later tests. Bind as `_env_guard` and keep
955    /// it alive for the whole test.
956    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            // SAFETY: process-global env mutation is sound here because every
973            // test that touches env holds the shared `cwd_lock()`, so no two
974            // tests can race, and this exact var is restored to its prior
975            // value (no other thread observes these test-scoped names).
976            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        // SAFETY: serialized by CwdGuard's global lock; test-scoped name.
992        unsafe { env::set_var(name, tmp.path().join("env-root")) };
993        // Also plant a workspace: explicit must still win over discovery.
994        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        // Pre-seed a sentinel: proves EnvGuard restores a prior value
1013        // (not just the unset case) when it drops.
1014        // SAFETY: serialized by CwdGuard's global lock; test-scoped name.
1015        unsafe { env::set_var(name, "sentinel") };
1016        {
1017            let _env_guard = EnvGuard::take(name);
1018
1019            // Empty counts as unset → NotFound (no workspace, no identity).
1020            // SAFETY: same serialization; guard restores on unwind.
1021            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            // Non-empty wins.
1034            let env_root = tmp.path().join("env-root");
1035            // SAFETY: same serialization; guard restores on unwind.
1036            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        // Guard dropped here: prior sentinel value must be back.
1042        assert_eq!(env::var(name).as_deref(), Ok("sentinel"));
1043        // SAFETY: test cleanup of a test-scoped name; suite holds the lock.
1044        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        // Bare dir, no Cargo.toml anywhere above, no identity configured:
1072        // the whole point of the resolver — NEVER silently <cwd>/.cache.
1073        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        // Error must describe the actual path taken: discovery was skipped,
1123        // not attempted-and-failed.
1124        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        // SAFETY: serialized by CwdGuard's global lock; test-scoped name.
1171        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        // Env not consulted (no env_var configured) → OS cache.
1182        let (_, source) = os_only.resolve().expect("resolve");
1183        assert_eq!(source, CacheSource::OsCacheDir);
1184
1185        // Env configured → env wins over OS cache.
1186        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        // Explicit wins over env.
1195        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        // create a file so we can verify calling the policy-aware
1687        // variant with `None` does not remove or alter contents.
1688        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        // create a file to ensure no-op policy does not remove it
1706        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}