Skip to main content

vantage_live/cache/
mem.rs

1//! In-memory cache backed by a `HashMap` under a `tokio::sync::RwLock`.
2//!
3//! Best fit for tests, short-lived processes, and the inner loop of UI
4//! development where you want the wrapping-and-invalidation logic without
5//! disk I/O.
6
7use async_trait::async_trait;
8use std::collections::HashMap;
9use std::sync::Arc;
10use tokio::sync::RwLock;
11use vantage_core::Result;
12
13use super::{Cache, CachedRows};
14
15/// Thread-safe `HashMap`-backed cache. Cheap to clone — the inner state is
16/// `Arc`-shared.
17#[derive(Clone, Default)]
18pub struct MemCache {
19    inner: Arc<RwLock<HashMap<String, CachedRows>>>,
20}
21
22impl MemCache {
23    pub fn new() -> Self {
24        Self::default()
25    }
26}
27
28#[async_trait]
29impl Cache for MemCache {
30    async fn get(&self, key: &str) -> Result<Option<CachedRows>> {
31        Ok(self.inner.read().await.get(key).cloned())
32    }
33
34    async fn put(&self, key: &str, rows: CachedRows) -> Result<()> {
35        self.inner.write().await.insert(key.to_string(), rows);
36        Ok(())
37    }
38
39    async fn invalidate_prefix(&self, prefix: &str) -> Result<()> {
40        self.inner
41            .write()
42            .await
43            .retain(|k, _| !k.starts_with(prefix));
44        Ok(())
45    }
46}