use anyhow::{Context, Result};
use std::path::PathBuf;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
const MAX_CACHE_ENTRY_BYTES: u64 = 16 * 1024 * 1024;
pub struct Cache {
dir: PathBuf,
}
impl Cache {
pub fn new() -> Result<Self> {
let dir = cache_dir()?;
std::fs::create_dir_all(&dir)
.with_context(|| format!("Failed to create cache dir: {:?}", dir))?;
if std::fs::symlink_metadata(&dir)?.file_type().is_symlink() {
anyhow::bail!("cache dir {:?} is a symlink; refusing to use it", dir);
}
set_private(&dir)?;
Ok(Cache { dir })
}
fn path_for(&self, key: &str) -> PathBuf {
let hash = fnv1a_64(key.as_bytes());
self.dir.join(format!("{:016x}.json", hash))
}
pub fn get<T: serde::Serialize + for<'de> serde::Deserialize<'de>>(
&self,
key: &str,
ttl: Duration,
) -> Option<T> {
let path = self.path_for(key);
let metadata = std::fs::symlink_metadata(&path).ok()?;
if metadata.file_type().is_symlink()
|| metadata.is_dir()
|| metadata.len() > MAX_CACHE_ENTRY_BYTES
{
return None;
}
let content = std::fs::read_to_string(&path).ok()?;
let parsed: serde_json::Value = serde_json::from_str(&content).ok()?;
let timestamp_ms = parsed.get("timestamp_ms")?.as_u64()?;
let now_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
if now_ms.saturating_sub(timestamp_ms) < ttl.as_millis() as u64 {
let value = serde_json::from_value(parsed.get("value")?.clone()).ok()?;
Some(value)
} else {
None
}
}
pub fn set<T: serde::Serialize>(&self, key: &str, value: T) -> Result<()> {
let now_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
let entry = serde_json::json!({
"value": value,
"timestamp_ms": now_ms,
});
let path = self.path_for(key);
let content = serde_json::to_string(&entry)?;
if content.len() as u64 > MAX_CACHE_ENTRY_BYTES {
anyhow::bail!("cache entry exceeds the maximum size");
}
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let tmp = self.dir.join(format!(
"{}.{}.{}.tmp",
path.file_name().unwrap_or_default().to_string_lossy(),
std::process::id(),
nonce
));
use std::io::Write;
let mut tmp_file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp)?;
if let Err(e) = tmp_file.write_all(content.as_bytes()) {
let _ = std::fs::remove_file(&tmp);
return Err(e.into());
}
tmp_file.sync_all()?;
drop(tmp_file);
if let Err(e) = std::fs::rename(&tmp, &path) {
let _ = std::fs::remove_file(&tmp);
return Err(e.into());
}
Ok(())
}
#[allow(dead_code)]
pub fn cleanup(&self, max_age: Duration) {
if let Ok(entries) = std::fs::read_dir(&self.dir) {
let now_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
for entry in entries.flatten() {
if let Ok(content) = std::fs::read_to_string(entry.path()) {
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(ts) = parsed.get("timestamp_ms").and_then(|v| v.as_u64()) {
if now_ms.saturating_sub(ts) > max_age.as_millis() as u64 {
let _ = std::fs::remove_file(entry.path());
}
}
}
}
}
}
}
}
fn fnv1a_64(bytes: &[u8]) -> u64 {
const FNV_OFFSET: u64 = 0xcbf29ce484222325;
const FNV_PRIME: u64 = 0x100000001b3;
let mut h = FNV_OFFSET;
for b in bytes {
h ^= *b as u64;
h = h.wrapping_mul(FNV_PRIME);
}
h
}
pub fn cache_key(path: &std::path::Path, feature: &str) -> String {
format!("{}:{}", path.to_string_lossy(), feature)
}
fn cache_dir() -> Result<PathBuf> {
if let Some(proj_dirs) = directories::ProjectDirs::from("com", "fab", "fab") {
let cache = proj_dirs.cache_dir().to_path_buf();
if !cache.as_os_str().is_empty() {
return Ok(cache);
}
return Ok(proj_dirs.data_dir().join("cache"));
}
anyhow::bail!("could not determine a per-user cache directory")
}
#[cfg(unix)]
fn set_private(dir: &std::path::Path) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
Ok(())
}
#[cfg(not(unix))]
fn set_private(_dir: &std::path::Path) -> Result<()> {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
static CACHE_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[test]
fn test_cache_set_and_get() {
let _guard = CACHE_TEST_LOCK.lock().unwrap();
let cache = Cache::new().unwrap();
let key = format!("test-key-{}", std::process::id());
let value: String = "hello".to_string();
cache.set(&key, &value).unwrap();
let result: Option<String> = cache.get(&key, Duration::from_secs(60));
assert_eq!(result, Some(value));
let _ = std::fs::remove_file(cache.path_for(&key));
}
#[test]
fn test_cache_expired() {
let _guard = CACHE_TEST_LOCK.lock().unwrap();
let cache = Cache::new().unwrap();
let key = format!("test-expired-{}", std::process::id());
cache.set(&key, "value".to_string()).unwrap();
let result: Option<String> = cache.get(&key, Duration::from_secs(0));
assert_eq!(result, None);
let _ = std::fs::remove_file(cache.path_for(&key));
}
#[test]
fn test_cache_key_format() {
let path = PathBuf::from("/home/user/project");
let key = cache_key(&path, "build");
assert_eq!(key, "/home/user/project:build");
}
#[test]
fn test_cache_cleanup() {
let _guard = CACHE_TEST_LOCK.lock().unwrap();
let cache = Cache::new().unwrap();
let key = format!("test-cleanup-{}", std::process::id());
cache.set(&key, "value".to_string()).unwrap();
cache.cleanup(Duration::from_secs(0));
let path = cache.path_for(&key);
let _ = path;
}
}