use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tracing::debug;
use super::hex::is_cache_key_hex;
use super::types::CACHE_LAYOUT;
mod maintain;
mod read;
mod store;
#[derive(Debug, Clone)]
pub struct DiskCache {
root: PathBuf,
ttl: Duration,
max_bytes: u64,
allow_loopback: bool,
}
impl DiskCache {
pub fn new(root: PathBuf, ttl: Duration, max_bytes: u64, allow_loopback: bool) -> Self {
Self {
root,
ttl,
max_bytes,
allow_loopback,
}
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn ttl(&self) -> Duration {
self.ttl
}
pub fn max_bytes(&self) -> u64 {
self.max_bytes
}
fn entry_dir(&self) -> PathBuf {
self.root.join(CACHE_LAYOUT)
}
pub(super) fn paths_for_key(&self, key_hex_str: &str) -> Option<(PathBuf, PathBuf)> {
if !is_cache_key_hex(key_hex_str) {
debug!(%key_hex_str, "refuse cache path: key is not sha256 hex");
return None;
}
let dir = self.entry_dir();
Some((
dir.join(format!("{key_hex_str}.meta.json")),
dir.join(format!("{key_hex_str}.bin")),
))
}
}
fn unix_now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}