use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::daemon_types::BannerData;
pub const CACHE_TTL: Duration = Duration::from_secs(300);
const CACHE_SUBDIR: &str = "banner_data";
pub fn cache_file_path(path: &Path) -> Option<PathBuf> {
let data_dir = data_dir()?;
let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
let hash = fnv1a_64(canonical.to_string_lossy().as_bytes());
Some(
data_dir
.join(CACHE_SUBDIR)
.join(format!("{:016x}.json", hash)),
)
}
fn data_dir() -> Option<PathBuf> {
let dir = directories::ProjectDirs::from("com", "fab", "fab")?
.data_dir()
.to_path_buf();
if !dir.exists() {
let _ = std::fs::create_dir_all(&dir);
}
Some(dir)
}
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_file_mtime(path: &Path) -> Option<SystemTime> {
let file = cache_file_path(path)?;
let meta = std::fs::metadata(&file).ok()?;
if meta.is_dir() {
return None;
}
meta.modified().ok()
}
pub fn directory_mtime(path: &Path) -> Option<SystemTime> {
let meta = std::fs::metadata(path).ok()?;
meta.modified().ok()
}
fn has_content_probe_ext(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
lower.ends_with(".txt")
|| lower.ends_with(".md")
|| lower.ends_with(".json")
|| lower.ends_with(".js")
|| lower.ends_with(".ts")
|| lower.ends_with(".jsx")
|| lower.ends_with(".tsx")
|| lower.ends_with(".rs")
|| lower.ends_with(".py")
|| lower.ends_with(".go")
|| lower.ends_with(".java")
|| lower.ends_with(".rb")
|| lower.ends_with(".c")
|| lower.ends_with(".cpp")
|| lower.ends_with(".h")
|| lower.ends_with(".hpp")
|| lower.ends_with(".sh")
|| lower.ends_with(".yaml")
|| lower.ends_with(".yml")
|| lower.ends_with(".toml")
|| lower.ends_with(".xml")
|| lower.ends_with(".html")
|| lower.ends_with(".css")
|| lower.ends_with(".scss")
|| lower.ends_with(".png")
|| lower.ends_with(".jpg")
|| lower.ends_with(".jpeg")
|| lower.ends_with(".gif")
|| lower.ends_with(".webp")
|| lower.ends_with(".bmp")
|| lower.ends_with(".tiff")
|| lower.ends_with(".zip")
|| lower.ends_with(".tar")
|| lower.ends_with(".gz")
|| lower.ends_with(".mp4")
|| lower.ends_with(".mov")
|| lower.ends_with(".mkv")
|| lower.ends_with(".webm")
|| lower.ends_with(".m4v")
}
pub fn max_descendant_mtime(path: &Path) -> Option<SystemTime> {
let entries = std::fs::read_dir(path).ok()?;
let mut max: Option<SystemTime> = None;
for entry in entries.flatten() {
let name = entry.file_name();
let name_str = name.to_string_lossy();
if !has_content_probe_ext(&name_str) {
continue;
}
if let Ok(meta) = entry.metadata() {
if meta.is_file() {
if let Ok(mtime) = meta.modified() {
max = Some(max.map_or(mtime, |m| m.max(mtime)));
}
}
}
}
max
}
pub fn is_cache_fresh(path: &Path) -> bool {
let Some(file_mtime) = cache_file_mtime(path) else {
return false;
};
let Ok(age) = SystemTime::now().duration_since(file_mtime) else {
return false;
};
if age >= CACHE_TTL {
return false;
}
if let Some(dir_mtime) = directory_mtime(path) {
if dir_mtime > file_mtime {
return false;
}
}
if let Some(max_child_mtime) = max_descendant_mtime(path) {
if max_child_mtime > file_mtime {
return false;
}
}
true
}
pub fn read_cache(path: &Path) -> Option<BannerData> {
let file = cache_file_path(path)?;
let meta = std::fs::metadata(&file).ok()?;
if meta.is_dir() {
tracing::warn!("Cache path is a directory, removing: {}", file.display());
let _ = std::fs::remove_dir(&file);
return None;
}
let bytes = std::fs::read(&file).ok()?;
serde_json::from_slice(&bytes).ok()
}
pub fn write_cache(path: &Path, data: &BannerData) -> std::io::Result<()> {
let Some(file) = cache_file_path(path) else {
return Ok(());
};
if let Some(parent) = file.parent() {
let _ = std::fs::create_dir_all(parent);
}
let bytes = match serde_json::to_vec(data) {
Ok(b) => b,
Err(e) => {
tracing::warn!("Failed to serialize banner data cache: {}", e);
return Ok(());
}
};
if let Ok(meta) = std::fs::metadata(&file) {
if meta.is_dir() {
tracing::warn!("Cache path is a directory, removing: {}", file.display());
let _ = std::fs::remove_dir(&file);
}
}
if let Err(e) = std::fs::write(&file, &bytes) {
tracing::warn!("Failed to write banner data cache: {}", e);
return Ok(());
}
let _ = SystemTime::now().duration_since(UNIX_EPOCH);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fs::{DirEntry, DirSummary, ProjectType};
use std::fs;
use std::time::Duration;
fn make_test_banner_data() -> BannerData {
BannerData {
summary: DirSummary {
total_items: 1,
total_size: 42,
files: 1,
dirs: 0,
top_items: vec![DirEntry {
name: "test.txt".to_string(),
path: PathBuf::from("/tmp/test.txt"),
is_dir: false,
is_file: true,
is_symlink: false,
is_exec: false,
size: 42,
modified: None,
perms: "rw-r--r--".to_string(),
owner: "dracon".to_string(),
group: "users".to_string(),
symlink_target: None,
symlink_valid: true,
content_probe: None,
}],
project_type: ProjectType::Generic,
last_modified: None,
build_status: None,
todo_info: None,
code_metrics: None,
port_info: None,
docker_info: None,
},
git_info: None,
}
}
#[test]
fn fnv1a_64_is_stable() {
assert_eq!(fnv1a_64(b""), 0xcbf29ce484222325);
assert_eq!(fnv1a_64(b"a"), 0xaf63dc4c8601ec8c);
assert_eq!(fnv1a_64(b"foobar"), 0x85944171f73967e8);
}
#[test]
fn fnv1a_64_changes_with_input() {
assert_ne!(fnv1a_64(b"a"), fnv1a_64(b"b"));
assert_ne!(fnv1a_64(b"abc"), fnv1a_64(b"abd"));
}
#[test]
fn cache_file_path_is_deterministic() {
let p = Path::new("/tmp/some/path");
let a = cache_file_path(p).unwrap();
let b = cache_file_path(p).unwrap();
assert_eq!(a, b);
}
#[test]
fn cache_file_path_differs_per_input() {
let a = cache_file_path(Path::new("/tmp/a")).unwrap();
let b = cache_file_path(Path::new("/tmp/b")).unwrap();
assert_ne!(a, b);
}
#[test]
fn cache_file_path_uses_hex_hash() {
let p = cache_file_path(Path::new("/tmp/test")).unwrap();
let fname = p.file_name().unwrap().to_str().unwrap();
assert_eq!(fname.len(), 21);
assert!(fname.ends_with(".json"));
let hash = &fname[..16];
assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));
}
#[test]
fn nonexistent_cache_is_not_fresh() {
assert!(!is_cache_fresh(Path::new(
"/tmp/this/path/should/not/exist/fab-test"
)));
}
#[test]
fn write_and_read_cache_roundtrip() {
let tmp = std::env::temp_dir().join(format!("fab-test-{}", std::process::id()));
let _ = fs::create_dir_all(&tmp);
let test_path = tmp.join("test_dir");
let _ = fs::create_dir_all(&test_path);
let data = make_test_banner_data();
write_cache(&test_path, &data).unwrap();
let cache_file = cache_file_path(&test_path).unwrap();
assert!(
cache_file.exists(),
"cache file should exist at {:?}",
cache_file
);
let read_back = read_cache(&test_path).expect("read_cache should succeed");
assert_eq!(read_back.summary.total_items, 1);
assert_eq!(read_back.summary.total_size, 42);
assert_eq!(read_back.summary.top_items.len(), 1);
assert_eq!(read_back.summary.top_items[0].name, "test.txt");
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn write_cache_creates_parent_dir() {
let tmp = std::env::temp_dir().join(format!("fab-test-parent-{}", std::process::id()));
let test_path = tmp.join("nested/test_dir");
let _ = fs::create_dir_all(&test_path);
let cache_file = cache_file_path(&test_path).unwrap();
let parent = cache_file.parent().unwrap();
let _ = fs::remove_dir_all(parent);
let data = make_test_banner_data();
write_cache(&test_path, &data).unwrap();
assert!(parent.exists(), "parent dir should be created");
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn read_cache_returns_none_for_missing_file() {
let result = read_cache(Path::new(
"/tmp/this/path/should/not/exist/fab-test-missing",
));
assert!(result.is_none());
}
#[test]
fn read_cache_handles_corrupt_json() {
let tmp = std::env::temp_dir().join(format!("fab-test-corrupt-{}", std::process::id()));
let _ = fs::create_dir_all(&tmp);
let test_path = tmp.join("test_dir");
let _ = fs::create_dir_all(&test_path);
let cache_file = cache_file_path(&test_path).unwrap();
if let Some(parent) = cache_file.parent() {
let _ = fs::create_dir_all(parent);
}
fs::write(&cache_file, b"{ this is not valid json").unwrap();
let result = read_cache(&test_path);
assert!(result.is_none(), "corrupt JSON should return None");
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn read_cache_handles_directory_at_cache_path() {
let tmp = std::env::temp_dir().join(format!("fab-test-dirpath-{}", std::process::id()));
let _ = fs::create_dir_all(&tmp);
let test_path = tmp.join("test_dir");
let _ = fs::create_dir_all(&test_path);
let cache_file = cache_file_path(&test_path).unwrap();
if let Some(parent) = cache_file.parent() {
let _ = fs::create_dir_all(parent);
}
let _ = fs::remove_file(&cache_file);
fs::create_dir(&cache_file).unwrap();
let result = read_cache(&test_path);
assert!(
result.is_none(),
"directory at cache path should return None"
);
assert!(!cache_file.exists(), "directory should be removed");
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn write_cache_replaces_directory_at_cache_path() {
let tmp = std::env::temp_dir().join(format!("fab-test-replace-{}", std::process::id()));
let _ = fs::create_dir_all(&tmp);
let test_path = tmp.join("test_dir");
let _ = fs::create_dir_all(&test_path);
let cache_file = cache_file_path(&test_path).unwrap();
if let Some(parent) = cache_file.parent() {
let _ = fs::create_dir_all(parent);
}
let _ = fs::remove_file(&cache_file);
fs::create_dir(&cache_file).unwrap();
let data = make_test_banner_data();
write_cache(&test_path, &data).unwrap();
assert!(
cache_file.is_file(),
"directory should be replaced with file"
);
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn is_cache_fresh_false_for_missing_file() {
assert!(!is_cache_fresh(Path::new(
"/tmp/this/path/should/not/exist/fab-fresh-test"
)));
}
#[test]
fn is_cache_fresh_true_for_recent_file() {
let tmp = std::env::temp_dir().join(format!("fab-test-isfresh-{}", std::process::id()));
let _ = fs::create_dir_all(&tmp);
let test_path = tmp.join("test_dir");
let _ = fs::create_dir_all(&test_path);
let data = make_test_banner_data();
write_cache(&test_path, &data).unwrap();
assert!(is_cache_fresh(&test_path));
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn is_cache_fresh_false_for_directory() {
let tmp = std::env::temp_dir().join(format!("fab-test-isdir-{}", std::process::id()));
let _ = fs::create_dir_all(&tmp);
let test_path = tmp.join("test_dir");
let _ = fs::create_dir_all(&test_path);
let cache_file = cache_file_path(&test_path).unwrap();
if let Some(parent) = cache_file.parent() {
let _ = fs::create_dir_all(parent);
}
let _ = fs::remove_file(&cache_file);
fs::create_dir(&cache_file).unwrap();
assert!(!is_cache_fresh(&test_path));
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn cache_ttl_is_5_minutes() {
assert_eq!(CACHE_TTL, Duration::from_secs(300));
}
}