Skip to main content

capsule_library/library/
cache.rs

1//! Adaptive cache eviction โ€” the client-side "Space Recovery" sweep.
2//!
3//! Keeps the reclaimable cache (the `cache/` tree plus fetched-but-unpinned originals) within a
4//! byte budget by evicting least-recently-accessed representations first, with tier order
5//! (original โ†’ preview โ†’ thumbnail) breaking recency ties. Pinned representations, device-owned
6//! originals, the canonical `media/` files, and the `library.sqlite` index are never touched.
7//! The budget is a plain parameter: `capsule-sdk::cache_budget` derives it from the current
8//! connection class and passes it in, so this sweep stays a pure function of the index and budget.
9//!
10//! SSoT: design/filesystem/client ยง Space Recovery.
11
12use std::fs;
13use std::path::Path;
14
15use crate::db::DatabaseDriver;
16use crate::db::rows::CachedRepresentationRow;
17
18/// What an eviction sweep reclaimed.
19#[derive(Debug, Default, PartialEq)]
20pub struct EvictionReport {
21    /// The representations evicted, worst-first (least-recently-accessed).
22    pub evicted: Vec<CachedRepresentationRow>,
23    /// Total bytes reclaimed.
24    pub bytes_reclaimed: i64,
25}
26
27/// Reclaim cached representations until the reclaimable set fits within `budget_bytes`. Deletes
28/// each evicted representation's cache file from disk and removes its index row. A cache file that
29/// is already gone is treated as reclaimed (not an error) and its stale row is still dropped.
30/// Pinned and device-owned originals are never evicted by this automatic path; canonical `media/`
31/// files are never candidates (they are not tracked in `cached_representations`).
32pub fn cache_sweep(
33    db: &DatabaseDriver,
34    budget_bytes: i64,
35) -> Result<EvictionReport, rusqlite::Error> {
36    let candidates = db.eviction_candidates(budget_bytes)?;
37    let mut report = EvictionReport::default();
38    for row in candidates {
39        let _ = fs::remove_file(Path::new(&row.path));
40        db.remove_representation(&row.uuid, &row.tier)?;
41        report.bytes_reclaimed += row.bytes;
42        report.evicted.push(row);
43    }
44    Ok(report)
45}
46
47#[cfg(test)]
48mod tests;