Skip to main content

docsrs_cli/cache/disk/
maintain.rs

1//! Space accounting: inventory, eviction, and wholesale removal.
2//!
3//! Everything here derives from one scan of the entry directory, so the number
4//! `stats` reports and the number eviction acts on can never disagree. The
5//! directory itself is the source of truth: a key is only trusted after
6//! [`DiskCache::paths_for_key`] accepts it, so a tampered filename is skipped
7//! instead of being turned back into a path.
8
9use std::fs;
10
11use tracing::debug;
12
13use crate::cache::meta::read_meta_file;
14use crate::cache::types::EntryOnDisk;
15use crate::cache::types::{CACHE_LAYOUT, CACHE_PARSER_VERSION, CacheClearResult, CacheStats};
16use crate::error::{AppResult, IoOp, io_at};
17
18use super::DiskCache;
19
20impl DiskCache {
21    /// Remove every entry under `http/v1` (temps included).
22    ///
23    /// # Errors
24    ///
25    /// Returns [`crate::error::ErrorKind::Internal`] when the cache directory cannot
26    /// be read.
27    pub fn clear(&self) -> AppResult<CacheClearResult> {
28        let dir = self.entry_dir();
29        let mut removed_entries = 0u64;
30        let mut freed_bytes = 0u64;
31        if dir.is_dir() {
32            for entry in fs::read_dir(&dir).map_err(io_at(IoOp::ReadDir, &dir))? {
33                let entry = entry.map_err(io_at(IoOp::Remove, &dir))?;
34                let path = entry.path();
35                let len = entry.metadata().map(|m| m.len()).unwrap_or(0);
36                if path.is_file() {
37                    if path
38                        .file_name()
39                        .and_then(|n| n.to_str())
40                        .is_some_and(|n| n.ends_with(".meta.json"))
41                    {
42                        removed_entries = removed_entries.saturating_add(1);
43                    }
44                    freed_bytes = freed_bytes.saturating_add(len);
45                    let _ = fs::remove_file(&path);
46                }
47            }
48        }
49        Ok(CacheClearResult {
50            root: self.root().display().to_string(),
51            removed_entries,
52            freed_bytes,
53        })
54    }
55
56    /// Inventory of on-disk entries and budget.
57    pub fn stats(&self) -> CacheStats {
58        let entries = self.scan_entries();
59        let total_bytes = entries.iter().map(|e| e.bytes).sum();
60        CacheStats {
61            root: self.root().display().to_string(),
62            layout: CACHE_LAYOUT.to_string(),
63            entries: entries.len() as u64,
64            total_bytes,
65            max_bytes: self.max_bytes(),
66            ttl_secs: self.ttl().as_secs(),
67            parser_version: CACHE_PARSER_VERSION.to_string(),
68        }
69    }
70
71    fn scan_entries(&self) -> Vec<EntryOnDisk> {
72        let dir = self.entry_dir();
73        let mut out = Vec::new();
74        let Ok(rd) = fs::read_dir(&dir) else {
75            return out;
76        };
77        for entry in rd.flatten() {
78            let path = entry.path();
79            let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
80                continue;
81            };
82            let Some(key) = name.strip_suffix(".meta.json") else {
83                continue;
84            };
85            let Some((meta_path, body_path)) = self.paths_for_key(key) else {
86                continue;
87            };
88            if !meta_path.is_file() || !body_path.is_file() {
89                continue;
90            }
91            let meta_len = fs::metadata(&meta_path).map(|m| m.len()).unwrap_or(0);
92            let body_len = fs::metadata(&body_path).map(|m| m.len()).unwrap_or(0);
93            let stored_at = read_meta_file(&meta_path)
94                .map(|m| m.stored_at_unix)
95                .unwrap_or(0);
96            out.push(EntryOnDisk {
97                key: key.to_string(),
98                stored_at_unix: stored_at,
99                bytes: meta_len.saturating_add(body_len),
100            });
101        }
102        out
103    }
104
105    /// Evict oldest entries until total size is within `max_bytes`.
106    /// Never deletes `keep_key` (the entry just written).
107    pub(super) fn enforce_max_bytes(&self, keep_key: Option<&str>) {
108        if self.max_bytes() == 0 {
109            return;
110        }
111        loop {
112            let mut entries = self.scan_entries();
113            let total: u64 = entries.iter().map(|e| e.bytes).sum();
114            if total <= self.max_bytes() {
115                break;
116            }
117            entries.sort_by_key(|e| e.stored_at_unix);
118            let victim = entries
119                .iter()
120                .find(|e| keep_key.is_none_or(|k| k != e.key.as_str()));
121            let Some(v) = victim else {
122                break;
123            };
124            debug!(key = %v.key, "cache evict for budget");
125            let _ = self.remove_entry(&v.key);
126        }
127    }
128
129    pub(super) fn remove_entry(&self, key_hex_str: &str) -> AppResult<()> {
130        let Some((meta_path, body_path)) = self.paths_for_key(key_hex_str) else {
131            return Ok(());
132        };
133        let _ = fs::remove_file(meta_path);
134        let _ = fs::remove_file(body_path);
135        Ok(())
136    }
137}