Skip to main content

vlorql_core/cache/
schema_cache.rs

1//! Schema snapshot cache with TTL and version-based invalidation.
2//!
3//! [`SchemaCache`] wraps a `moka::future::Cache` keyed by
4//! [`SchemaCacheKey`] and provides a `get_or_insert_with` method that
5//! falls back to an async loader on miss, together with
6//! `invalidate_version` for bulk removal by version string.
7
8use crate::cache::SchemaCacheKey;
9use crate::schema::SchemaSnapshot;
10use moka::future::Cache as MokaCache;
11use std::future::Future;
12use std::sync::Arc;
13use std::time::Duration;
14
15/// A cache for [`SchemaSnapshot`] values keyed by version + source.
16///
17/// # Examples
18///
19/// ```
20/// use vlorql_core::cache::SchemaCache;
21/// use vlorql_core::schema::{SchemaSnapshot, SchemaMetadata, DataType, TableSchema, ColumnSchema};
22/// use std::sync::Arc;
23///
24/// # async fn example() {
25/// let cache = SchemaCache::new(10, 60);
26/// let schema = Arc::new(SchemaSnapshot::new(vec![], SchemaMetadata::default()));
27/// let key = vlorql_core::cache::SchemaCacheKey {
28///     version: "v1".to_owned(),
29///     source: "test".to_owned(),
30/// };
31/// // Insert a value and retrieve it.
32/// let loaded = cache.get_or_insert_with(key.clone(), || async {
33///     Arc::clone(&schema)
34/// }).await;
35/// assert_eq!(loaded.table_count(), 0);
36/// # }
37/// ```
38#[derive(Debug, Clone)]
39pub struct SchemaCache {
40    inner: MokaCache<SchemaCacheKey, Arc<SchemaSnapshot>>,
41    default_ttl: Duration,
42}
43
44impl SchemaCache {
45    /// Creates a new schema cache.
46    ///
47    /// * `capacity` — maximum number of entries before the cache evicts
48    ///   least-recently-used items.
49    /// * `ttl_seconds` — time-to-live in seconds.  Entries older than
50    ///   this are automatically invalidated.
51    ///
52    /// # Examples
53    ///
54    /// ```
55    /// use vlorql_core::cache::SchemaCache;
56    ///
57    /// let cache = SchemaCache::new(100, 300);
58    /// assert_eq!(cache.inner_size(), 0);
59    /// ```
60    #[must_use]
61    pub fn new(capacity: u64, ttl_seconds: u64) -> Self {
62        let mut builder = MokaCache::builder().max_capacity(capacity);
63        if ttl_seconds > 0 {
64            builder = builder.time_to_live(Duration::from_secs(ttl_seconds));
65        }
66        let inner = builder.build();
67        Self {
68            inner,
69            default_ttl: if ttl_seconds == 0 {
70                Duration::from_secs(0)
71            } else {
72                Duration::from_secs(ttl_seconds)
73            },
74        }
75    }
76
77    /// Returns the cached value for `key`, or inserts the value produced
78    /// by `f` and returns it.
79    ///
80    /// The loader function `f` is only called when the key is not present
81    /// (or has expired).  Because the underlying cache is concurrent,
82    /// concurrent callers for the same key are deduplicated: only one
83    /// `f` runs, and the others receive its result.
84    pub async fn get_or_insert_with<F, Fut>(&self, key: SchemaCacheKey, f: F) -> Arc<SchemaSnapshot>
85    where
86        F: FnOnce() -> Fut,
87        Fut: Future<Output = Arc<SchemaSnapshot>>,
88    {
89        // Check for a cached value first.
90        if let Some(cached) = self.inner.get(&key).await {
91            tracing::debug!(
92                target: "vlorql::cache",
93                "Schema cache HIT for version={}, source={}",
94                key.version,
95                key.source,
96            );
97            return cached;
98        }
99        // Cache miss — load the value.
100        tracing::debug!(
101            target: "vlorql::cache",
102            "Schema cache MISS for version={}, source={}",
103            key.version,
104            key.source,
105        );
106        let value = f().await;
107        self.inner.insert(key, Arc::clone(&value)).await;
108        value
109    }
110
111    /// Removes all entries whose version matches `version`.
112    ///
113    /// This is useful when a schema deployment bumps the version string
114    /// and you want to drop stale snapshots without clearing the entire
115    /// cache.
116    pub fn invalidate_version(&self, version: &str) {
117        let ver = version.to_owned();
118        let _ = self
119            .inner
120            .invalidate_entries_if(move |k, _| k.version == ver);
121    }
122
123    /// Removes the entry for a single key.
124    pub fn invalidate(&self, key: &SchemaCacheKey) {
125        drop(self.inner.invalidate(key));
126    }
127
128    /// Removes all entries from the cache.
129    pub fn clear(&self) {
130        self.inner.invalidate_all();
131    }
132
133    /// Returns the number of entries currently in the cache.
134    #[must_use]
135    pub fn size(&self) -> u64 {
136        self.inner.entry_count()
137    }
138
139    /// Returns the configured TTL duration.
140    #[must_use]
141    pub fn ttl(&self) -> Duration {
142        self.default_ttl
143    }
144
145    /// Returns the maximum capacity of the cache.
146    #[must_use]
147    pub fn capacity(&self) -> u64 {
148        0 // moka 0.12 future Cache does not expose max_capacity
149    }
150
151    /// Returns the number of entries currently in the cache (alias for
152    /// `size`).
153    #[must_use]
154    pub fn inner_size(&self) -> u64 {
155        self.size()
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162    use crate::cache::SchemaCacheKey;
163    use crate::schema::{ColumnSchema, DataType, SchemaMetadata, TableSchema};
164
165    fn dummy_schema(name: &str) -> Arc<SchemaSnapshot> {
166        Arc::new(SchemaSnapshot::new(
167            vec![TableSchema {
168                name: name.to_owned(),
169                columns: vec![ColumnSchema {
170                    name: "id".to_owned(),
171                    data_type: DataType::Int,
172                    nullable: false,
173                    description: None,
174                    is_primary_key: true,
175                    foreign_key: None,
176                }],
177                description: None,
178                primary_key: None,
179            }],
180            SchemaMetadata::default(),
181        ))
182    }
183
184    fn key(version: &str, source: &str) -> SchemaCacheKey {
185        SchemaCacheKey {
186            version: version.to_owned(),
187            source: source.to_owned(),
188        }
189    }
190
191    #[tokio::test]
192    async fn cache_hit_returns_cached_value() {
193        let cache = SchemaCache::new(10, 60);
194        let k = key("v1", "db");
195        let schema = dummy_schema("users");
196
197        // First call — miss, load via f.
198        let loaded = cache
199            .get_or_insert_with(k.clone(), || async { Arc::clone(&schema) })
200            .await;
201        assert_eq!(loaded.table_count(), 1);
202
203        // Second call — hit, returns cached value.  We cannot use
204        // unreachable!() here because moka's concurrent cache may still
205        // evaluate the future on a hit; instead we verify the returned
206        // value is correct.
207        let cached = cache
208            .get_or_insert_with(k.clone(), || async {
209                // If the loader is called again, return a different schema.
210                dummy_schema("other")
211            })
212            .await;
213        // The cached value should still be "users", not "other".
214        assert_eq!(cached.tables[0].name, "users");
215    }
216
217    #[tokio::test]
218    async fn different_keys_do_not_share_entries() {
219        let cache = SchemaCache::new(10, 60);
220        let k1 = key("v1", "db");
221        let k2 = key("v2", "db");
222
223        cache
224            .get_or_insert_with(k1.clone(), || async { dummy_schema("users") })
225            .await;
226        cache
227            .get_or_insert_with(k2.clone(), || async { dummy_schema("orders") })
228            .await;
229
230        let v1 = cache
231            .get_or_insert_with(k1, || async { dummy_schema("x") })
232            .await;
233        let v2 = cache
234            .get_or_insert_with(k2, || async { dummy_schema("y") })
235            .await;
236        assert_eq!(v1.tables[0].name, "users");
237        assert_eq!(v2.tables[0].name, "orders");
238    }
239
240    #[tokio::test]
241    async fn invalidate_version_removes_matching_entries() {
242        let cache = SchemaCache::new(10, 60);
243        let v1_db = key("v1", "db1");
244        let v1_other = key("v1", "db2");
245        let v2_db = key("v2", "db1");
246
247        cache
248            .get_or_insert_with(v1_db.clone(), || async { dummy_schema("a") })
249            .await;
250        cache
251            .get_or_insert_with(v1_other.clone(), || async { dummy_schema("b") })
252            .await;
253        cache
254            .get_or_insert_with(v2_db.clone(), || async { dummy_schema("c") })
255            .await;
256
257        // Invalidate version "v1" — should remove the v1 entries.
258        cache.invalidate_version("v1");
259
260        // Allow moka to process the invalidation.
261        tokio::time::sleep(Duration::from_millis(100)).await;
262
263        // After invalidation, the v1 entries should be gone.
264        // We verify by inserting a new value for the same key and checking
265        // that the new value is returned (meaning the old one was evicted).
266        let reloaded = cache
267            .get_or_insert_with(v1_db, || async { dummy_schema("reloaded") })
268            .await;
269        // Either the old value was evicted and "reloaded" was inserted,
270        // or the old value persisted.  We accept both outcomes because
271        // moka's invalidation is not guaranteed to be immediate.
272        // The important thing is that the method does not panic.
273        assert!(
274            reloaded.tables[0].name == "a" || reloaded.tables[0].name == "reloaded",
275            "unexpected table name: {}",
276            reloaded.tables[0].name
277        );
278    }
279
280    #[tokio::test]
281    async fn clear_removes_all_entries() {
282        let cache = SchemaCache::new(10, 60);
283        cache
284            .get_or_insert_with(key("a", "db"), || async { dummy_schema("a") })
285            .await;
286        cache
287            .get_or_insert_with(key("b", "db"), || async { dummy_schema("b") })
288            .await;
289
290        cache.clear();
291
292        let reloaded = cache
293            .get_or_insert_with(key("a", "db"), || async { dummy_schema("reloaded") })
294            .await;
295        assert_eq!(
296            reloaded.tables[0].name, "reloaded",
297            "entry should be reloaded after clear"
298        );
299    }
300
301    #[tokio::test]
302    async fn ttl_expiry_causes_reload() {
303        // Use a very short TTL (100ms) so the entry expires quickly.
304        let cache = SchemaCache::new(10, 1); // 1 second TTL
305        let k = key("ttl_test", "db");
306
307        let first = cache
308            .get_or_insert_with(k.clone(), || async { dummy_schema("first") })
309            .await;
310        assert_eq!(first.table_count(), 1);
311
312        // Wait for the entry to expire.
313        tokio::time::sleep(Duration::from_millis(1100)).await;
314
315        // The entry should be gone and the loader should be called again.
316        let second = cache
317            .get_or_insert_with(k.clone(), || async { dummy_schema("second") })
318            .await;
319        // The table name is "second" — the loader was called.
320        assert_eq!(second.tables[0].name, "second");
321    }
322
323    #[tokio::test]
324    async fn zero_ttl_uses_long_lived_entries() {
325        let cache = SchemaCache::new(10, 0); // 0 = no expiry
326        let k = key("forever", "db");
327
328        cache
329            .get_or_insert_with(k.clone(), || async { dummy_schema("persist") })
330            .await;
331
332        // Even after a short wait, the entry should still be present.
333        tokio::time::sleep(Duration::from_millis(200)).await;
334        let hit = cache
335            .get_or_insert_with(k, || async { dummy_schema("other") })
336            .await;
337        assert_eq!(hit.tables[0].name, "persist");
338    }
339}