docsrs_cli/cache/disk.rs
1//! Disk cache handle: identity, key derivation, and the clock the entries carry.
2//!
3//! The three operations a cache performs answer different questions and fail in
4//! different ways, so each owns a child module: [`read`] decides whether an entry
5//! may be served, [`store`] makes a new entry durable, [`maintain`] keeps the
6//! directory inside its budget. What stays here is what all three share — the
7//! handle, the key-to-path rule, and `unix_now`.
8//!
9//! Child modules see the private fields of [`DiskCache`] because privacy in Rust
10//! extends downward, so the split costs no widened visibility.
11
12use std::path::{Path, PathBuf};
13use std::time::{Duration, SystemTime, UNIX_EPOCH};
14
15use tracing::debug;
16
17use super::hex::is_cache_key_hex;
18use super::types::CACHE_LAYOUT;
19
20mod maintain;
21mod read;
22mod store;
23
24/// Disk cache rooted at an XDG (or override) directory.
25#[derive(Debug, Clone)]
26pub struct DiskCache {
27 root: PathBuf,
28 ttl: Duration,
29 /// Soft cap on total body+meta bytes under `http/v1`. `0` = unlimited.
30 max_bytes: u64,
31 /// Same SSRF loopback policy as the owning [`crate::config::Config`].
32 allow_loopback: bool,
33}
34
35impl DiskCache {
36 /// Create a cache at `root` with the given TTL, byte budget, and loopback policy.
37 pub fn new(root: PathBuf, ttl: Duration, max_bytes: u64, allow_loopback: bool) -> Self {
38 Self {
39 root,
40 ttl,
41 max_bytes,
42 allow_loopback,
43 }
44 }
45
46 /// Absolute cache root directory.
47 pub fn root(&self) -> &Path {
48 &self.root
49 }
50
51 /// Configured entry time-to-live.
52 pub fn ttl(&self) -> Duration {
53 self.ttl
54 }
55
56 /// Soft size budget in bytes (`0` = unlimited).
57 pub fn max_bytes(&self) -> u64 {
58 self.max_bytes
59 }
60
61 fn entry_dir(&self) -> PathBuf {
62 self.root.join(CACHE_LAYOUT)
63 }
64
65 /// Build meta/body paths only for SHA-256 hex keys (64 lowercase hex digits).
66 ///
67 /// Refuses path traversal / odd filenames that could appear if on-disk names
68 /// are tampered (scan_entries reads directory entries as keys).
69 pub(super) fn paths_for_key(&self, key_hex_str: &str) -> Option<(PathBuf, PathBuf)> {
70 if !is_cache_key_hex(key_hex_str) {
71 debug!(%key_hex_str, "refuse cache path: key is not sha256 hex");
72 return None;
73 }
74 let dir = self.entry_dir();
75 Some((
76 dir.join(format!("{key_hex_str}.meta.json")),
77 dir.join(format!("{key_hex_str}.bin")),
78 ))
79 }
80}
81
82fn unix_now() -> u64 {
83 SystemTime::now()
84 .duration_since(UNIX_EPOCH)
85 .map(|d| d.as_secs())
86 .unwrap_or(0)
87}