Skip to main content

bhandaar/
metadata.rs

1use serde::{Deserialize, Serialize};
2use std::time::{SystemTime, UNIX_EPOCH};
3
4/// Metadata for a cached entry, stored as a sidecar file.
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct EntryMeta {
7    /// Original user-provided key.
8    pub key: String,
9    /// Size of the cached file in bytes.
10    pub size: u64,
11    /// Creation timestamp (nanos since UNIX epoch) — used for TTL.
12    pub created_at: u64,
13    /// Last access timestamp (nanos since UNIX epoch) — used for LRU.
14    pub last_accessed: u64,
15    /// TTL expiry timestamp (nanos since UNIX epoch), None = never expires.
16    pub expires_at: Option<u64>,
17}
18
19impl EntryMeta {
20    /// Create a new entry metadata with current timestamps.
21    pub fn new(key: String, size: u64, ttl: Option<std::time::Duration>) -> Self {
22        let now = current_time_nanos();
23        let expires_at = ttl.map(|d| now + duration_to_nanos(d));
24
25        Self {
26            key,
27            size,
28            created_at: now,
29            last_accessed: now,
30            expires_at,
31        }
32    }
33
34    /// Check if this entry has expired.
35    pub fn is_expired(&self) -> bool {
36        match self.expires_at {
37            Some(expires) => current_time_nanos() >= expires,
38            None => false,
39        }
40    }
41
42    /// Update the last_accessed timestamp to now.
43    pub fn touch(&mut self) {
44        self.last_accessed = current_time_nanos();
45    }
46
47    /// Serialize this metadata to bytes (bincode).
48    pub fn to_bytes(&self) -> Result<Vec<u8>, bincode::Error> {
49        bincode::serialize(self)
50    }
51
52    /// Deserialize metadata from bytes (bincode).
53    pub fn from_bytes(bytes: &[u8]) -> Result<Self, bincode::Error> {
54        bincode::deserialize(bytes)
55    }
56}
57
58/// Get current time in nanos since UNIX epoch.
59fn current_time_nanos() -> u64 {
60    SystemTime::now()
61        .duration_since(UNIX_EPOCH)
62        .unwrap_or_default()
63        .as_nanos() as u64
64}
65
66/// Convert a Duration to nanos.
67fn duration_to_nanos(d: std::time::Duration) -> u64 {
68    d.as_nanos() as u64
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    #[test]
76    fn new_entry_meta_has_correct_fields() {
77        let meta = EntryMeta::new("test-key".to_string(), 1024, None);
78        assert_eq!(meta.key, "test-key");
79        assert_eq!(meta.size, 1024);
80        assert!(meta.created_at > 0);
81        assert_eq!(meta.last_accessed, meta.created_at);
82        assert!(meta.expires_at.is_none());
83    }
84
85    #[test]
86    fn new_entry_meta_with_ttl_sets_expires_at() {
87        let ttl = std::time::Duration::from_secs(3600);
88        let meta = EntryMeta::new("key".to_string(), 512, Some(ttl));
89        assert!(meta.expires_at.is_some());
90        assert!(meta.expires_at.unwrap() > meta.created_at);
91    }
92
93    #[test]
94    fn is_expired_returns_false_when_no_ttl() {
95        let meta = EntryMeta::new("key".to_string(), 100, None);
96        assert!(!meta.is_expired());
97    }
98
99    #[test]
100    fn is_expired_returns_true_when_past_ttl() {
101        let meta = EntryMeta {
102            key: "key".to_string(),
103            size: 100,
104            created_at: 0,
105            last_accessed: 0,
106            expires_at: Some(1), // Already expired
107        };
108        assert!(meta.is_expired());
109    }
110
111    #[test]
112    fn touch_updates_last_accessed() {
113        let mut meta = EntryMeta::new("key".to_string(), 100, None);
114        let original = meta.last_accessed;
115        // Small delay to ensure timestamp changes
116        std::thread::sleep(std::time::Duration::from_millis(1));
117        meta.touch();
118        assert!(meta.last_accessed >= original);
119    }
120
121    #[test]
122    fn serialization_roundtrip() {
123        let meta = EntryMeta::new("test".to_string(), 2048, Some(std::time::Duration::from_secs(60)));
124        let bytes = meta.to_bytes().unwrap();
125        let restored = EntryMeta::from_bytes(&bytes).unwrap();
126        assert_eq!(meta.key, restored.key);
127        assert_eq!(meta.size, restored.size);
128        assert_eq!(meta.created_at, restored.created_at);
129        assert_eq!(meta.last_accessed, restored.last_accessed);
130        assert_eq!(meta.expires_at, restored.expires_at);
131    }
132}