bhandaar 0.1.0-alpha.1

On-disk LRU/TTL file cache for Rust with cross-process concurrency via flock(2)
Documentation
use serde::{Deserialize, Serialize};
use std::time::{SystemTime, UNIX_EPOCH};

/// Metadata for a cached entry, stored as a sidecar file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntryMeta {
    /// Original user-provided key.
    pub key: String,
    /// Size of the cached file in bytes.
    pub size: u64,
    /// Creation timestamp (nanos since UNIX epoch) — used for TTL.
    pub created_at: u64,
    /// Last access timestamp (nanos since UNIX epoch) — used for LRU.
    pub last_accessed: u64,
    /// TTL expiry timestamp (nanos since UNIX epoch), None = never expires.
    pub expires_at: Option<u64>,
}

impl EntryMeta {
    /// Create a new entry metadata with current timestamps.
    pub fn new(key: String, size: u64, ttl: Option<std::time::Duration>) -> Self {
        let now = current_time_nanos();
        let expires_at = ttl.map(|d| now + duration_to_nanos(d));

        Self {
            key,
            size,
            created_at: now,
            last_accessed: now,
            expires_at,
        }
    }

    /// Check if this entry has expired.
    pub fn is_expired(&self) -> bool {
        match self.expires_at {
            Some(expires) => current_time_nanos() >= expires,
            None => false,
        }
    }

    /// Update the last_accessed timestamp to now.
    pub fn touch(&mut self) {
        self.last_accessed = current_time_nanos();
    }

    /// Serialize this metadata to bytes (bincode).
    pub fn to_bytes(&self) -> Result<Vec<u8>, bincode::Error> {
        bincode::serialize(self)
    }

    /// Deserialize metadata from bytes (bincode).
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, bincode::Error> {
        bincode::deserialize(bytes)
    }
}

/// Get current time in nanos since UNIX epoch.
fn current_time_nanos() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos() as u64
}

/// Convert a Duration to nanos.
fn duration_to_nanos(d: std::time::Duration) -> u64 {
    d.as_nanos() as u64
}

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

    #[test]
    fn new_entry_meta_has_correct_fields() {
        let meta = EntryMeta::new("test-key".to_string(), 1024, None);
        assert_eq!(meta.key, "test-key");
        assert_eq!(meta.size, 1024);
        assert!(meta.created_at > 0);
        assert_eq!(meta.last_accessed, meta.created_at);
        assert!(meta.expires_at.is_none());
    }

    #[test]
    fn new_entry_meta_with_ttl_sets_expires_at() {
        let ttl = std::time::Duration::from_secs(3600);
        let meta = EntryMeta::new("key".to_string(), 512, Some(ttl));
        assert!(meta.expires_at.is_some());
        assert!(meta.expires_at.unwrap() > meta.created_at);
    }

    #[test]
    fn is_expired_returns_false_when_no_ttl() {
        let meta = EntryMeta::new("key".to_string(), 100, None);
        assert!(!meta.is_expired());
    }

    #[test]
    fn is_expired_returns_true_when_past_ttl() {
        let meta = EntryMeta {
            key: "key".to_string(),
            size: 100,
            created_at: 0,
            last_accessed: 0,
            expires_at: Some(1), // Already expired
        };
        assert!(meta.is_expired());
    }

    #[test]
    fn touch_updates_last_accessed() {
        let mut meta = EntryMeta::new("key".to_string(), 100, None);
        let original = meta.last_accessed;
        // Small delay to ensure timestamp changes
        std::thread::sleep(std::time::Duration::from_millis(1));
        meta.touch();
        assert!(meta.last_accessed >= original);
    }

    #[test]
    fn serialization_roundtrip() {
        let meta = EntryMeta::new("test".to_string(), 2048, Some(std::time::Duration::from_secs(60)));
        let bytes = meta.to_bytes().unwrap();
        let restored = EntryMeta::from_bytes(&bytes).unwrap();
        assert_eq!(meta.key, restored.key);
        assert_eq!(meta.size, restored.size);
        assert_eq!(meta.created_at, restored.created_at);
        assert_eq!(meta.last_accessed, restored.last_accessed);
        assert_eq!(meta.expires_at, restored.expires_at);
    }
}