folder-auto-banner 0.7.14

Folder Auto Banner — A directory listing with instant context
Documentation
//! Cache module — TTL-based file cache for expensive operations
//!
//! Stores cached values as JSON files in a per-user cache directory keyed by
//! project path. Each entry has a timestamp; expired entries are ignored.

use anyhow::{Context, Result};
use std::path::PathBuf;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

const MAX_CACHE_ENTRY_BYTES: u64 = 16 * 1024 * 1024;

/// File-based TTL cache
pub struct Cache {
    dir: PathBuf,
}

impl Cache {
    /// Create a new cache instance.
    ///
    /// Lives under the per-user cache dir (XDG: `$XDG_CACHE_HOME/fab` or
    /// `~/.cache/fab`), created with 0700 so another local user or a
    /// pre-created symlink in the world-writable `/tmp` cannot redirect or
    /// read the daemon's cache writes. Falls back to the per-user data dir
    /// if no cache dir can be resolved.
    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 a stale attacker-owned entry exists (e.g. a symlink), refuse to
        // write through it rather than silently chmodding the target.
        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 })
    }

    /// Get cache file path for a given key
    fn path_for(&self, key: &str) -> PathBuf {
        let hash = fnv1a_64(key.as_bytes());
        self.dir.join(format!("{:016x}.json", hash))
    }

    /// Get a cached value if it exists and is not expired
    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()?;

        // Parse as generic JSON to extract timestamp
        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
        }
    }

    /// Store a value in the cache
    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");
        }
        // Atomic write: temp file in the same dir + rename, so a crash or a
        // concurrent reader never observes a torn JSON file.
        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(())
    }

    /// Clear expired entries (best-effort cleanup)
    #[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());
                            }
                        }
                    }
                }
            }
        }
    }
}

/// 64-bit FNV-1a hash — fast, non-cryptographic, and deterministic across
/// platforms and compiler releases.
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
}

/// Build a cache key from a path and a feature name
pub fn cache_key(path: &std::path::Path, feature: &str) -> String {
    format!("{}:{}", path.to_string_lossy(), feature)
}

/// Resolve the per-user cache directory: XDG cache, else per-user data dir,
/// else error (callers treat a missing cache as "no caching").
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")
}

/// Pin directory permissions to 0700 (create_dir_all applies the umask,
/// which could leave the dir world-readable).
#[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;

    // All cache tests share the real per-user cache dir, and cleanup(0)
    // deletes every entry in it — including entries another test wrote
    // milliseconds earlier. Serialize the dir-touching tests so parallel
    // threads cannot delete each other's entries mid-assertion.
    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));

        // Cleanup
        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();
        // Get with 0 TTL should always expire
        let result: Option<String> = cache.get(&key, Duration::from_secs(0));
        assert_eq!(result, None);

        // Cleanup
        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();
        // Cleanup with 0 max_age should remove everything
        cache.cleanup(Duration::from_secs(0));

        // Verify removed (may fail if file was recreated, but should be gone)
        let path = cache.path_for(&key);
        // Note: cleanup is best-effort, so we just verify the function runs
        let _ = path;
    }
}