bhandaar 0.1.0-alpha.1

On-disk LRU/TTL file cache for Rust with cross-process concurrency via flock(2)
Documentation
//! On-disk file operations with atomic writes for safety.
//!
//! Uses atomic write pattern (write to temp, then rename) to prevent corruption
//! when multiple threads/processes access the same file.
//!
//! IMPORTANT: Each write uses a unique temp file name (via atomic counter)
//! to prevent data corruption when multiple threads write concurrently.

use std::fs;
use std::io;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};

use crate::metadata::EntryMeta;

/// Atomic counter for generating unique temp file names.
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Write data to a file atomically (unique temp file + rename).
///
/// Uses a unique temp file name per write to prevent corruption
/// when multiple threads write concurrently.
pub fn write_data(path: &Path, data: &[u8]) -> io::Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }

    // Generate unique temp file name to prevent concurrent write corruption
    let counter = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
    let temp_path = path.with_file_name(format!(
        "{}.{}.tmp",
        path.file_stem().unwrap().to_str().unwrap(),
        counter
    ));
    fs::write(&temp_path, data)?;

    // Atomic rename
    fs::rename(&temp_path, path)?;

    Ok(())
}

/// Read data from a file.
pub fn read_data(path: &Path) -> io::Result<Vec<u8>> {
    fs::read(path)
}

/// Delete a file, returning Ok(true) if deleted, Ok(false) if not found.
///
/// Also cleans up any orphaned temp files in the same directory.
pub fn delete_file(path: &Path) -> io::Result<bool> {
    // Clean up any orphaned temp files (unique names, can't predict them)
    if let Some(parent) = path.parent() {
        if let Some(stem) = path.file_stem() {
            if let Ok(entries) = fs::read_dir(parent) {
                for entry in entries.flatten() {
                    let name = entry.file_name();
                    if let Some(name_str) = name.to_str() {
                        if name_str.starts_with(stem.to_str().unwrap_or("")) 
                            && name_str.ends_with(".tmp") 
                        {
                            let _ = fs::remove_file(entry.path());
                        }
                    }
                }
            }
        }
    }

    match fs::remove_file(path) {
        Ok(()) => Ok(true),
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
        Err(e) => Err(e),
    }
}

/// Write metadata to a sidecar file atomically.
pub fn write_meta(path: &Path, meta: &EntryMeta) -> Result<(), crate::error::BhandaarError> {
    let bytes = meta.to_bytes()?;
    write_data(path, &bytes)?;
    Ok(())
}

/// Read metadata from a sidecar file.
///
/// If the file is corrupted or partially written, returns CorruptedMetadata
/// instead of panicking.
pub fn read_meta(path: &Path) -> Result<EntryMeta, crate::error::BhandaarError> {
    // Try to read the main file
    let bytes = match fs::read(path) {
        Ok(b) => b,
        Err(e) if e.kind() == io::ErrorKind::NotFound => {
            return Err(crate::error::BhandaarError::CorruptedMetadata(path.to_path_buf()));
        }
        Err(e) => return Err(crate::error::BhandaarError::Io(e)),
    };

    // Try to deserialize
    EntryMeta::from_bytes(&bytes).map_err(|e| {
        crate::error::BhandaarError::SerializationError(e)
    })
}

#[allow(dead_code)]
/// Check if a file exists.
pub fn file_exists(path: &Path) -> bool {
    path.exists()
}

#[allow(dead_code)]
/// Get the size of a file in bytes.
pub fn file_size(path: &Path) -> io::Result<u64> {
    let metadata = fs::metadata(path)?;
    Ok(metadata.len())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn write_and_read_data() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.dat");

        write_data(&path, b"hello world").unwrap();
        let data = read_data(&path).unwrap();
        assert_eq!(data, b"hello world");
    }

    #[test]
    fn atomic_write_prevents_corruption() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("atomic.dat");

        // Write data
        write_data(&path, b"initial").unwrap();
        assert_eq!(read_data(&path).unwrap(), b"initial");

        // Overwrite atomically
        write_data(&path, b"updated").unwrap();
        assert_eq!(read_data(&path).unwrap(), b"updated");

        // Temp file should not exist
        assert!(!path.with_extension("tmp").exists());
    }

    #[test]
    fn write_data_creates_parent_dirs() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a/b/c/test.dat");

        write_data(&path, b"nested").unwrap();
        assert!(path.exists());
    }

    #[test]
    fn delete_existing_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("to_delete.dat");

        write_data(&path, b"data").unwrap();
        let deleted = delete_file(&path).unwrap();
        assert!(deleted);
        assert!(!path.exists());
    }

    #[test]
    fn delete_nonexistent_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("does_not_exist.dat");

        let deleted = delete_file(&path).unwrap();
        assert!(!deleted);
    }

    #[test]
    fn write_and_read_meta() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.dat.meta");

        let meta = EntryMeta::new("key".to_string(), 1024, Some(Duration::from_secs(60)));
        write_meta(&path, &meta).unwrap();

        let restored = read_meta(&path).unwrap();
        assert_eq!(meta.key, restored.key);
        assert_eq!(meta.size, restored.size);
    }

    #[test]
    fn read_meta_returns_error_for_missing_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("missing.dat.meta");

        let result = read_meta(&path);
        assert!(result.is_err());
    }

    #[test]
    fn file_size_works() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("sized.dat");

        write_data(&path, b"12345").unwrap();
        let size = file_size(&path).unwrap();
        assert_eq!(size, 5);
    }
}