use anyhow::Result;
use std::path::PathBuf;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub struct Cache {
dir: PathBuf,
}
impl Cache {
pub fn new() -> Result<Self> {
let dir = std::env::temp_dir().join("f-cache");
std::fs::create_dir_all(&dir)?;
Ok(Cache { dir })
}
fn path_for(&self, key: &str) -> PathBuf {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
key.hash(&mut hasher);
let hash = format!("{:016x}", hasher.finish());
self.dir.join(format!("{}.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 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)?;
std::fs::write(&path, content)?;
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());
}
}
}
}
}
}
}
}
pub fn cache_key(path: &std::path::Path, feature: &str) -> String {
format!("{}:{}", path.to_string_lossy(), feature)
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn test_cache_set_and_get() {
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 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 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;
}
}