Skip to main content

vlorql_core/cache/
traits.rs

1//! Generic [`Cache`] trait and a no-op implementation.
2//!
3//! The [`Cache`] trait is the single abstraction used by all caching
4//! layers in VlorQl.  A no-op implementation ([`NoopCache`]) is provided
5//! so callers that do not need caching can use it without conditional
6//! logic.
7
8use std::collections::HashMap;
9use std::hash::Hash;
10use std::sync::Mutex;
11
12/// A generic key-value cache with thread-safe operations.
13///
14/// Implementations must be [`Send`] + [`Sync`] so they can be shared
15/// across async tasks and stored in an `Arc`.
16///
17/// # Examples
18///
19/// ```
20/// use vlorql_core::cache::{Cache, NoopCache};
21///
22/// let cache = NoopCache::<u64, String>::new();
23/// assert!(cache.get(&42).is_none());
24/// cache.insert(42, "hello".to_owned());
25/// assert_eq!(cache.size(), 0); // NoopCache never stores anything
26/// ```
27pub trait Cache<K: Eq + Hash, V: Clone>: Send + Sync {
28    /// Returns the cached value for `key`, or `None` on a miss.
29    fn get(&self, key: &K) -> Option<V>;
30
31    /// Inserts a value into the cache.
32    ///
33    /// Returns the previous value associated with the key, if any.
34    fn insert(&self, key: K, value: V) -> Option<V>;
35
36    /// Removes the entry for `key` from the cache.
37    fn invalidate(&self, key: &K);
38
39    /// Removes all entries from the cache.
40    fn clear(&self);
41
42    /// Returns the number of entries currently in the cache.
43    fn size(&self) -> u64;
44}
45
46// ---------------------------------------------------------------------------
47// NoopCache — a cache that never stores anything
48// ---------------------------------------------------------------------------
49
50/// A cache that discards every inserted value.
51///
52/// Useful as a default when no caching is desired; it avoids branching
53/// on `Option<impl Cache>` throughout the codebase.
54#[derive(Debug, Default)]
55pub struct NoopCache<K, V> {
56    _marker: std::marker::PhantomData<(K, V)>,
57}
58
59impl<K, V> NoopCache<K, V> {
60    /// Creates a new no-op cache.
61    #[must_use]
62    pub fn new() -> Self {
63        Self {
64            _marker: std::marker::PhantomData,
65        }
66    }
67}
68
69impl<K: Eq + Hash + Send + Sync, V: Clone + Send + Sync> Cache<K, V> for NoopCache<K, V> {
70    fn get(&self, _key: &K) -> Option<V> {
71        None
72    }
73
74    fn insert(&self, _key: K, _value: V) -> Option<V> {
75        None
76    }
77
78    fn invalidate(&self, _key: &K) {}
79
80    fn clear(&self) {}
81
82    fn size(&self) -> u64 {
83        0
84    }
85}
86
87// ---------------------------------------------------------------------------
88// MemoryCache — a simple in-memory HashMap-backed cache
89// ---------------------------------------------------------------------------
90
91/// A simple in-memory cache backed by a `HashMap`.
92///
93/// This is the default implementation for most use cases.  It is not
94/// LRU or TTL-aware; entries live until explicitly invalidated or the
95/// cache is dropped.
96///
97/// # Examples
98///
99/// ```
100/// use vlorql_core::cache::{Cache, MemoryCache};
101///
102/// let cache = MemoryCache::new();
103/// assert!(cache.get(&"key").is_none());
104/// cache.insert("key", 42u64);
105/// assert_eq!(cache.get(&"key"), Some(42));
106/// assert_eq!(cache.size(), 1);
107/// ```
108#[derive(Debug)]
109pub struct MemoryCache<K, V> {
110    inner: Mutex<HashMap<K, V>>,
111}
112
113impl<K, V> MemoryCache<K, V> {
114    /// Creates a new empty in-memory cache.
115    #[must_use]
116    pub fn new() -> Self {
117        Self {
118            inner: Mutex::new(HashMap::new()),
119        }
120    }
121
122    /// Creates an empty in-memory cache with the specified capacity.
123    #[must_use]
124    pub fn with_capacity(capacity: usize) -> Self {
125        Self {
126            inner: Mutex::new(HashMap::with_capacity(capacity)),
127        }
128    }
129}
130
131impl<K, V> Default for MemoryCache<K, V> {
132    fn default() -> Self {
133        Self::new()
134    }
135}
136
137impl<K: Eq + Hash + Send + Sync, V: Clone + Send> Cache<K, V> for MemoryCache<K, V> {
138    fn get(&self, key: &K) -> Option<V> {
139        let map = self.inner.lock().unwrap_or_else(|e| e.into_inner());
140        map.get(key).cloned()
141    }
142
143    fn insert(&self, key: K, value: V) -> Option<V> {
144        let mut map = self.inner.lock().unwrap_or_else(|e| e.into_inner());
145        map.insert(key, value)
146    }
147
148    fn invalidate(&self, key: &K) {
149        let mut map = self.inner.lock().unwrap_or_else(|e| e.into_inner());
150        map.remove(key);
151    }
152
153    fn clear(&self) {
154        let mut map = self.inner.lock().unwrap_or_else(|e| e.into_inner());
155        map.clear();
156    }
157
158    fn size(&self) -> u64 {
159        let map = self.inner.lock().unwrap_or_else(|e| e.into_inner());
160        map.len() as u64
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    #[test]
169    fn noop_cache_never_stores() {
170        let cache = NoopCache::<u64, String>::new();
171        assert_eq!(cache.size(), 0);
172        assert!(cache.get(&1).is_none());
173        cache.insert(1, "hello".to_owned());
174        assert_eq!(cache.size(), 0);
175        assert!(cache.get(&1).is_none());
176    }
177
178    #[test]
179    fn memory_cache_insert_and_get() {
180        let cache = MemoryCache::new();
181        assert!(cache.get(&"a").is_none());
182        cache.insert("a", 10);
183        assert_eq!(cache.get(&"a"), Some(10));
184        assert_eq!(cache.size(), 1);
185    }
186
187    #[test]
188    fn memory_cache_overwrite() {
189        let cache = MemoryCache::new();
190        cache.insert("x", 1);
191        let prev = cache.insert("x", 2);
192        assert_eq!(prev, Some(1));
193        assert_eq!(cache.get(&"x"), Some(2));
194    }
195
196    #[test]
197    fn memory_cache_invalidate() {
198        let cache = MemoryCache::new();
199        cache.insert("k", "v".to_owned());
200        assert_eq!(cache.size(), 1);
201        cache.invalidate(&"k");
202        assert!(cache.get(&"k").is_none());
203        assert_eq!(cache.size(), 0);
204    }
205
206    #[test]
207    fn memory_cache_clear() {
208        let cache = MemoryCache::new();
209        cache.insert("a", 1);
210        cache.insert("b", 2);
211        assert_eq!(cache.size(), 2);
212        cache.clear();
213        assert_eq!(cache.size(), 0);
214    }
215
216    #[test]
217    fn memory_cache_with_capacity() {
218        let cache = MemoryCache::<&str, u64>::with_capacity(100);
219        assert_eq!(cache.size(), 0);
220    }
221}