cache-manager
Directory-based cache and artifact path management with discovered .cache roots, grouped cache paths, and optional eviction on directory initialization.
- Tool-agnostic: any tool or library that can write to the filesystem can use
cache-manageras a managed cache/artifact path layout layer. - Zero runtime dependencies in the standard install (library consumers use only the Rust standard library).
- Optional feature
process-scoped-cache: adds one runtime dependency,tempfile, to support process/thread scoped sub-caches with automatic cleanup on normal shutdown. - Open-source + commercial-friendly licensing: dual-licensed under MIT or Apache-2.0, so it can be used in open-source and commercial projects.
- Built-in eviction policies: enforce cache limits by file age, file count, and total bytes, with deterministic oldest-first trimming.
- Predictable discovery + root control: discover
<crate-root>/.cacheautomatically or pin an explicit root withCacheRoot::from_root(...). - Composable cache layout API: create groups/subgroups and entry paths consistently across tools without custom path-joining logic.
- Suitable for artifact storage (build outputs, generated files, intermediate data, etc.).
- Suitable for monorepos or multi-crate workspaces that need centralized cache/artifact management via a shared root (for example with
CacheRoot::from_root(...)). This tool was designed to facilitate common cache directory management in a multi-crate workspace.
Tested on macOS, Linux, and Windows.
Usage
Mental model: root -> groups -> entries
CacheRoot: project/workspace anchor path.CacheGroup: subdirectory under a root where a class of cache files lives.- Entries: files under a group (for example
v1/index.bin).
CacheRoot and CacheGroup are lightweight path objects. Constructing them does not create directories.
Quick start
Using touch (convenient when you want this crate to create the file):
use CacheRoot;
let root = from_root;
let group = root.group;
// Create the group directory if needed
group.ensure_dir.expect;
// `index.bin` is just an example artifact filename that another program might generate
let entry: PathBuf = group.touch.expect;
println!;
Without touch (compute from group.path() and write with your own I/O):
use CacheRoot;
use fs;
let root = from_root;
let group = root.group;
group.ensure_dir.expect;
let entry_without_touch = group.path.join;
create_dir_all
.expect;
write.expect;
println!;
Filesystem effects
- Pure path operations:
CacheRoot::from_root,CacheRoot::cache_path,CacheRoot::group,CacheGroup::entry_path,CacheGroup::subgroup - Discovery helper (cwd/crate-root based):
CacheRoot::from_discovery - Create dirs:
CacheRoot::ensure_group,CacheGroup::ensure_dir - Create dirs + optional eviction:
CacheRoot::ensure_group_with_policy,CacheGroup::ensure_dir_with_policy - Create file (creates parents):
CacheGroup::touch
With feature process-scoped-cache enabled:
- Process-scoped group:
ProcessScopedCacheGroup::new,ProcessScopedCacheGroup::from_group - Per-thread subgroup:
ProcessScopedCacheGroup::thread_group,ProcessScopedCacheGroup::ensure_thread_group - Per-thread entry helpers:
ProcessScopedCacheGroup::thread_entry_path,ProcessScopedCacheGroup::touch_thread_entry
Note: eviction only runs when you pass a policy to the
*_with_policymethods.
Discovering cache paths
Discover a cache path for the current crate/workspace and resolve an entry path.
Note:
CacheRoot::from_discovery()?.cache_path(...)only computes a filesystem path — it does not create directories or files.
Behavior:
- Searches upward from the current working directory for a
Cargo.tomland uses<crate-root>/.cachewhen found; otherwise it falls back to<cwd>/.cache. - The discovered anchor (
crate rootorcwd) is canonicalized when possible to avoid surprising differences between logically-equal paths. - If the
relative_pathargument is absolute, it is returned unchanged.
use CacheRoot;
use Path;
// Compute a path like <crate-root>/.cache/tool/data.bin without creating it
let cache_path = from_discovery
.expect
.cache_path;
println!;
// Expected relative location under the discovered crate root:
assert!;
// The call only computes the path; it does not create files or directories
assert!;
// If you already have an absolute entry path, it's returned unchanged:
let absolute = from;
let kept = from_discovery
.expect
.cache_path;
assert_eq!;
Notes on discovery behavior
CacheRoot::from_discovery() deterministically anchors discovered cache
paths under the configured CACHE_DIR_NAME (default: .cache). It does
not scan for arbitrary directory names — creating a directory named
.cache-v2 at the crate root will not cause from_discovery() to use it.
If you want to use a custom cache root, construct it explicitly with
CacheRoot::from_root(...).
Eviction Policy
Use EvictPolicy with:
CacheGroup::ensure_dir_with_policy(...)CacheRoot::ensure_group_with_policy(...)CacheGroup::eviction_report(...)to preview which files would be evicted.
Apply policy directly to a CacheGroup:
use ;
let root = from_root;
let group = root.group;
let policy = EvictPolicy ;
group
.ensure_dir_with_policy
.expect;
Apply policy through CacheRoot convenience API:
use ;
use Duration;
let root = from_root;
let policy = EvictPolicy ;
root
.ensure_group_with_policy
.expect;
Preview evictions without deleting files:
use ;
let root = from_root;
let group = root.group;
let policy = EvictPolicy ;
let report = group.eviction_report.expect;
for path in report.marked_for_eviction
Policy fields:
max_age: remove files older than or equal to the age threshold.max_files: keep at most N files.max_bytes: keep total file bytes at or below the threshold.
Policies can be combined by setting multiple fields in one EvictPolicy.
When combined, all configured limits are enforced in order.
use EvictPolicy;
use Duration;
let combined = EvictPolicy ;
Eviction order is always:
max_agemax_filesmax_bytes
For max_files and max_bytes, files are evicted oldest-first by modified time (ascending), then by path for deterministic tie-breaking.
eviction_report(...) and ensure_*_with_policy(...) use the same selection logic.
How max_bytes works
- Scans regular files recursively under the managed directory.
- Sums
metadata.len()across those files. - If total exceeds
max_bytes, removes files oldest-first until total is<= max_bytes. - Directories are not counted as bytes.
- Enforcement happens only during policy-aware
ensure_*_with_policycalls (not continuously in the background).
Optional process/thread scoped caches
Enable feature flag:
Or, if editing Cargo.toml manually:
[]
= { = "<latest>", = ["process-scoped-cache"] }
Use ProcessScopedCacheGroup to create an auto-generated process subdirectory
under your assigned root/group, then derive a stable subgroup for each thread:
Behavior notes:
- Respects all configured roots/groups because process-scoped paths are always created under your provided
CacheRoot/CacheGroup. - The process subdirectory is deleted when the handle is dropped during normal process shutdown.
- Cleanup is best-effort; abnormal termination (for example
SIGKILLor crash) can leave stale directories.
Additional examples
Create or update a cache entry (ensures parent directories exist):
use CacheRoot;
let root = from_root;
let group = root.group;
let entry = group.touch.expect;
println!;
Per-subdirectory policies
Different subdirectories under the same CacheRoot can use independent policies; call ensure_dir_with_policy on each CacheGroup separately to apply per-group rules.
Note: calling CacheGroup::ensure_dir() is equivalent to CacheGroup::ensure_dir_with_policy(None). Likewise, CacheRoot::ensure_group(...) behaves the same as CacheRoot::ensure_group_with_policy(..., None).
Get the root path
To obtain the underlying filesystem path for a CacheRoot, use path():
use CacheRoot;
let root = from_root;
let root_path = root.path;
println!;
Also obtain a CacheGroup path and resolve an entry path under that group:
use CacheRoot;
let root = from_root;
let group = root.group;
let group_path = group.path;
println!;
let entry_path = group.entry_path;
println!;
License
cache-manager is primarily distributed under the terms of both the MIT license and the Apache License (Version 2.0).
See LICENSE-APACHE and LICENSE-MIT for details.