Skip to main content

lean_ctx/core/providers/
cache.rs

1use std::collections::HashMap;
2use std::sync::Mutex;
3use std::time::{Duration, Instant};
4
5static PROVIDER_CACHE: std::sync::LazyLock<Mutex<ProviderCache>> =
6    std::sync::LazyLock::new(|| Mutex::new(ProviderCache::new()));
7
8struct CacheEntry {
9    data: String,
10    expires_at: Instant,
11}
12
13struct ProviderCache {
14    entries: HashMap<String, CacheEntry>,
15}
16
17impl ProviderCache {
18    fn new() -> Self {
19        Self {
20            entries: HashMap::new(),
21        }
22    }
23
24    fn get(&mut self, key: &str) -> Option<&str> {
25        self.entries.retain(|_, v| v.expires_at > Instant::now());
26        self.entries.get(key).map(|e| e.data.as_str())
27    }
28
29    fn set(&mut self, key: String, data: String, ttl: Duration) {
30        self.entries.insert(
31            key,
32            CacheEntry {
33                data,
34                expires_at: Instant::now() + ttl,
35            },
36        );
37    }
38}
39
40pub fn get_cached(key: &str) -> Option<String> {
41    PROVIDER_CACHE
42        .lock()
43        .ok()
44        .and_then(|mut c| c.get(key).map(std::string::ToString::to_string))
45}
46
47pub fn set_cached(key: &str, data: &str, ttl_secs: u64) {
48    if let Ok(mut cache) = PROVIDER_CACHE.lock() {
49        cache.set(
50            key.to_string(),
51            data.to_string(),
52            Duration::from_secs(ttl_secs),
53        );
54    }
55}