Skip to main content

klauthed_data/cache/
memory.rs

1//! In-process cache (moka) sized and TTL'd from a [`CacheConfig`].
2
3use std::hash::Hash;
4use std::time::Duration;
5
6use klauthed_core::config::CacheConfig;
7use moka::future::Cache;
8
9/// Build an in-memory cache whose capacity and default TTL come from `config`
10/// (`max_entries` and `default_ttl_secs`).
11///
12/// The backend field is not enforced here — this is the in-memory path by
13/// construction — so it can also back a Redis-configured service in tests or
14/// as a local fallback. The key/value types are chosen by the caller.
15pub fn build_memory_cache<K, V>(config: &CacheConfig) -> Cache<K, V>
16where
17    K: Hash + Eq + Send + Sync + 'static,
18    V: Clone + Send + Sync + 'static,
19{
20    Cache::builder()
21        .max_capacity(config.max_entries)
22        .time_to_live(Duration::from_secs(config.default_ttl_secs))
23        .build()
24}
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29
30    #[tokio::test]
31    async fn builds_and_stores_values() {
32        let config = CacheConfig { max_entries: 100, default_ttl_secs: 60, ..Default::default() };
33        let cache: Cache<String, u32> = build_memory_cache(&config);
34
35        cache.insert("answer".to_string(), 42).await;
36        assert_eq!(cache.get("answer").await, Some(42));
37    }
38}