use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::daemon_types::{BannerData, MAX_IPC_FRAME_SIZE};
pub const CACHE_TTL: Duration = Duration::from_secs(300);
const MAX_DESCENDANT_ENTRIES: usize = 8192;
const CACHE_SUBDIR: &str = "banner_data";
pub fn cache_file_path(path: &Path) -> Option<PathBuf> {
let data_dir = data_dir()?;
let cache_dir = data_dir.join(CACHE_SUBDIR);
if let Ok(metadata) = std::fs::symlink_metadata(&cache_dir) {
if metadata.file_type().is_symlink() || !metadata.is_dir() {
return None;
}
}
let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
let hash = fnv1a_64(canonical.to_string_lossy().as_bytes());
Some(cache_dir.join(format!("{:016x}.json", hash)))
}
fn data_dir() -> Option<PathBuf> {
crate::state::get_data_dir().ok()
}
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::symlink_metadata(&file).ok()?;
if meta.file_type().is_symlink() || meta.is_dir() || meta.len() > MAX_IPC_FRAME_SIZE as u64 {
return None;
}
meta.modified().ok()
}
pub fn directory_mtime(path: &Path) -> Option<SystemTime> {
let meta = std::fs::metadata(path).ok()?;
meta.modified().ok()
}
pub fn is_content_probe_ext(lower_name: &str) -> bool {
lower_name.ends_with(".txt")
|| lower_name.ends_with(".md")
|| lower_name.ends_with(".json")
|| lower_name.ends_with(".js")
|| lower_name.ends_with(".ts")
|| lower_name.ends_with(".jsx")
|| lower_name.ends_with(".tsx")
|| lower_name.ends_with(".rs")
|| lower_name.ends_with(".py")
|| lower_name.ends_with(".go")
|| lower_name.ends_with(".java")
|| lower_name.ends_with(".rb")
|| lower_name.ends_with(".c")
|| lower_name.ends_with(".cpp")
|| lower_name.ends_with(".h")
|| lower_name.ends_with(".hpp")
|| lower_name.ends_with(".sh")
|| lower_name.ends_with(".yaml")
|| lower_name.ends_with(".yml")
|| lower_name.ends_with(".toml")
|| lower_name.ends_with(".xml")
|| lower_name.ends_with(".html")
|| lower_name.ends_with(".css")
|| lower_name.ends_with(".scss")
|| lower_name.ends_with(".png")
|| lower_name.ends_with(".jpg")
|| lower_name.ends_with(".jpeg")
|| lower_name.ends_with(".gif")
|| lower_name.ends_with(".webp")
|| lower_name.ends_with(".bmp")
|| lower_name.ends_with(".tiff")
|| lower_name.ends_with(".zip")
|| lower_name.ends_with(".tar")
|| lower_name.ends_with(".gz")
|| lower_name.ends_with(".mp4")
|| lower_name.ends_with(".mov")
|| lower_name.ends_with(".mkv")
|| lower_name.ends_with(".webm")
|| lower_name.ends_with(".m4v")
}
pub fn max_descendant_mtime(path: &Path) -> Option<SystemTime> {
fn walk(path: &Path, depth: usize, visited: &mut usize) -> Option<SystemTime> {
if depth > 8 || *visited >= MAX_DESCENDANT_ENTRIES {
return None;
}
let entries = std::fs::read_dir(path).ok()?;
let mut max: Option<SystemTime> = None;
let remaining = MAX_DESCENDANT_ENTRIES.saturating_sub(*visited);
for entry in entries.take(remaining).flatten() {
if *visited >= MAX_DESCENDANT_ENTRIES {
break;
}
*visited += 1;
let name_str = entry.file_name().to_string_lossy().to_string();
if let Ok(meta) = std::fs::symlink_metadata(entry.path()) {
if meta.file_type().is_symlink() {
continue;
}
if meta.is_dir() {
if matches!(
name_str.as_ref(),
".git" | "target" | "node_modules" | ".cache" | ".venv" | "build"
) {
continue;
}
if let Some(mtime) = walk(&entry.path(), depth + 1, visited) {
max = Some(max.map_or(mtime, |m| m.max(mtime)));
}
} else if meta.is_file() {
if !is_content_probe_ext(&name_str.to_ascii_lowercase()) {
continue;
}
if let Ok(mtime) = meta.modified() {
max = Some(max.map_or(mtime, |m| m.max(mtime)));
}
}
}
}
max
}
let mut visited = 0usize;
walk(path, 0, &mut visited)
}
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(config_mtime) = crate::state::Config::config_path()
.ok()
.and_then(|config| std::fs::metadata(config).ok())
.and_then(|metadata| metadata.modified().ok())
{
if config_mtime > file_mtime {
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::symlink_metadata(&file).ok()?;
if meta.file_type().is_symlink() {
tracing::warn!(
"Cache path is a symlink, refusing to read: {}",
file.display()
);
return None;
}
if meta.is_dir() {
tracing::warn!("Cache path is a directory, removing: {}", file.display());
let _ = std::fs::remove_dir(&file);
return None;
}
if meta.len() > MAX_IPC_FRAME_SIZE as u64 {
tracing::warn!(
"Cache file is too large, refusing to read: {}",
file.display()
);
return None;
}
let bytes = std::fs::read(&file).ok()?;
serde_json::from_slice(&bytes).ok()
}
pub fn remove_cache(path: &Path) {
if let Some(file) = cache_file_path(path) {
let _ = std::fs::remove_file(file);
}
}
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() {
if let Err(e) = std::fs::create_dir_all(parent) {
tracing::warn!("Failed to create banner data cache directory: {}", e);
return Ok(());
}
}
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 bytes.len() > MAX_IPC_FRAME_SIZE {
tracing::warn!(
"Serialized banner data cache exceeds the maximum size: {} bytes",
bytes.len()
);
return Ok(());
}
if let Ok(meta) = std::fs::symlink_metadata(&file) {
if meta.file_type().is_symlink() {
tracing::warn!(
"Cache path is a symlink, refusing to write: {}",
file.display()
);
return Ok(());
}
if meta.is_dir() {
tracing::warn!("Cache path is a directory, removing: {}", file.display());
let _ = std::fs::remove_dir(&file);
}
}
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let tmp = file.with_extension(format!("json.{}.{}.tmp", std::process::id(), nonce));
use std::io::Write;
let mut tmp_file = match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp)
{
Ok(file) => file,
Err(e) => {
tracing::warn!("Failed to create banner data cache temp file: {}", e);
return Ok(());
}
};
if let Err(e) = tmp_file.write_all(&bytes) {
let _ = std::fs::remove_file(&tmp);
tracing::warn!("Failed to write banner data cache: {}", e);
return Ok(());
}
if let Err(e) = tmp_file.sync_all() {
let _ = std::fs::remove_file(&tmp);
tracing::warn!("Failed to flush banner data cache: {}", e);
return Ok(());
}
drop(tmp_file);
if let Err(e) = std::fs::rename(&tmp, &file) {
let _ = std::fs::remove_file(&tmp);
tracing::warn!("Failed to rename banner data cache: {}", e);
return Ok(());
}
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,
truncated: false,
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 old_cache_without_truncated_field_still_deserializes() {
let data = make_test_banner_data();
let mut value = serde_json::to_value(&data).unwrap();
value
.get_mut("summary")
.and_then(serde_json::Value::as_object_mut)
.expect("serialized banner data must contain a summary object")
.remove("truncated");
let restored: BannerData = serde_json::from_value(value).unwrap();
assert!(!restored.summary.truncated);
}
#[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 data = make_test_banner_data();
write_cache(&test_path, &data).unwrap();
assert!(parent.exists(), "parent dir should exist");
assert!(cache_file.exists(), "cache file should exist");
let _ = fs::remove_file(&cache_file);
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 test_max_descendant_mtime_finds_nested_files() {
let tmp = std::env::temp_dir().join(format!("fab-test-nested-{}", std::process::id()));
let nested_dir = tmp.join("src").join("nested");
let _ = fs::create_dir_all(&nested_dir);
let nested_file = nested_dir.join("test.rs");
fs::write(&nested_file, "fn main() {}").unwrap();
let mtime = max_descendant_mtime(&tmp);
assert!(mtime.is_some(), "should find nested .rs file");
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn cache_ttl_is_5_minutes() {
assert_eq!(CACHE_TTL, Duration::from_secs(300));
}
}