Skip to main content

lean_ctx/core/providers/
cache.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use std::collections::HashMap;
4use std::sync::Mutex;
5use std::time::{Duration, Instant, SystemTime};
6
7const MAX_CACHE_ENTRIES: usize = 2048;
8const STALE_SERVE_GRACE: Duration = Duration::from_hours(1);
9
10/// Partition cached responses by the exact request and credential, not authorization state.
11/// Credential rotation misses the cache; same-credential revocation still follows cache TTL.
12pub(super) fn request_cache_key(
13    provider_id: &str,
14    request_url: &str,
15    credential: Option<&str>,
16) -> String {
17    let mut hasher = blake3::Hasher::new();
18    for component in [provider_id.as_bytes(), request_url.as_bytes()] {
19        hasher.update(&(component.len() as u64).to_be_bytes());
20        hasher.update(component);
21    }
22    let credential_marker = [u8::from(credential.is_some())];
23    hasher.update(&(credential_marker.len() as u64).to_be_bytes());
24    hasher.update(&credential_marker);
25    if let Some(credential) = credential {
26        hasher.update(&(credential.len() as u64).to_be_bytes());
27        hasher.update(credential.as_bytes());
28    }
29    format!("{provider_id}:request:v2:{}", hasher.finalize().to_hex())
30}
31
32static PROVIDER_CACHE: std::sync::LazyLock<Mutex<ProviderCache>> =
33    std::sync::LazyLock::new(|| Mutex::new(ProviderCache::new()));
34
35struct CacheEntry {
36    data: String,
37    expires_at: Instant,
38    provider_id: String,
39}
40
41struct StaleEntry {
42    data: String,
43    evicted_at: Instant,
44    provider_id: String,
45}
46
47/// Per-provider cache statistics.
48#[derive(Debug, Clone, Default)]
49pub struct ProviderCacheStats {
50    pub provider_id: String,
51    pub hits: u64,
52    pub misses: u64,
53    pub entry_count: usize,
54    pub last_fetch: Option<SystemTime>,
55}
56
57impl ProviderCacheStats {
58    pub fn hit_rate(&self) -> f64 {
59        let total = self.hits + self.misses;
60        if total == 0 {
61            return 0.0;
62        }
63        self.hits as f64 / total as f64
64    }
65}
66
67/// Global cache statistics across all providers.
68#[derive(Debug, Clone, Default)]
69pub struct CacheMetrics {
70    pub total_hits: u64,
71    pub total_misses: u64,
72    pub total_entries: usize,
73    pub stale_entries: usize,
74    pub max_entries: usize,
75    pub provider_stats: Vec<ProviderCacheStats>,
76}
77
78impl CacheMetrics {
79    pub fn total_hit_rate(&self) -> f64 {
80        let total = self.total_hits + self.total_misses;
81        if total == 0 {
82            return 0.0;
83        }
84        self.total_hits as f64 / total as f64
85    }
86}
87
88struct ProviderCache {
89    entries: HashMap<String, CacheEntry>,
90    access_order: Vec<String>,
91    stale_entries: HashMap<String, StaleEntry>,
92    hits: HashMap<String, u64>,
93    misses: HashMap<String, u64>,
94    last_fetch: HashMap<String, SystemTime>,
95}
96
97impl ProviderCache {
98    fn new() -> Self {
99        Self {
100            entries: HashMap::new(),
101            access_order: Vec::new(),
102            stale_entries: HashMap::new(),
103            hits: HashMap::new(),
104            misses: HashMap::new(),
105            last_fetch: HashMap::new(),
106        }
107    }
108
109    fn get(&mut self, key: &str) -> Option<&str> {
110        self.expire_entries();
111        self.purge_stale();
112        if let Some(entry) = self.entries.get(key) {
113            let provider_id = entry.provider_id.clone();
114            self.access_order.retain(|candidate| candidate != key);
115            self.access_order.push(key.to_string());
116            *self.hits.entry(provider_id).or_insert(0) += 1;
117            return self.entries.get(key).map(|entry| entry.data.as_str());
118        }
119        let provider_id = self.stale_entries.get(key).map_or_else(
120            || key.split(':').next().unwrap_or("unknown").to_string(),
121            |entry| entry.provider_id.clone(),
122        );
123        *self.misses.entry(provider_id.clone()).or_insert(0) += 1;
124        let stale = self.stale_entries.get(key)?;
125        tracing::warn!(key, provider_id, "serving stale provider cache entry");
126        Some(stale.data.as_str())
127    }
128
129    fn set(&mut self, key: String, data: String, ttl: Duration, provider_id: &str) {
130        self.last_fetch
131            .insert(provider_id.to_string(), SystemTime::now());
132        self.access_order.retain(|candidate| candidate != &key);
133        self.access_order.push(key.clone());
134        self.stale_entries.remove(&key);
135        self.entries.insert(
136            key,
137            CacheEntry {
138                data,
139                expires_at: Instant::now() + ttl,
140                provider_id: provider_id.to_string(),
141            },
142        );
143        self.enforce_lru_cap();
144    }
145
146    fn expire_entries(&mut self) {
147        let now = Instant::now();
148        let expired: Vec<_> = self
149            .entries
150            .iter()
151            .filter(|(_, entry)| entry.expires_at <= now)
152            .map(|(key, _)| key.clone())
153            .collect();
154        for key in expired {
155            self.move_to_stale(&key, now);
156        }
157    }
158
159    fn enforce_lru_cap(&mut self) {
160        let now = Instant::now();
161        while self.entries.len() > MAX_CACHE_ENTRIES {
162            let key = self.access_order.remove(0);
163            self.move_to_stale(&key, now);
164        }
165    }
166
167    fn move_to_stale(&mut self, key: &str, evicted_at: Instant) {
168        self.access_order.retain(|candidate| candidate != key);
169        if let Some(entry) = self.entries.remove(key) {
170            self.stale_entries.insert(
171                key.to_string(),
172                StaleEntry {
173                    data: entry.data,
174                    evicted_at,
175                    provider_id: entry.provider_id,
176                },
177            );
178        }
179    }
180
181    fn stale_entry_count(&self) -> usize {
182        self.stale_entries.len()
183    }
184
185    fn purge_stale(&mut self) {
186        let now = Instant::now();
187        self.stale_entries
188            .retain(|_, entry| entry.evicted_at + STALE_SERVE_GRACE > now);
189    }
190
191    fn invalidate_provider(&mut self, provider_id: &str) -> usize {
192        let before = self.entries.len();
193        self.entries.retain(|_, v| v.provider_id != provider_id);
194        self.access_order
195            .retain(|key| self.entries.contains_key(key));
196        self.stale_entries
197            .retain(|_, entry| entry.provider_id != provider_id);
198        before - self.entries.len()
199    }
200
201    fn invalidate_all(&mut self) -> usize {
202        let count = self.entries.len();
203        self.entries.clear();
204        self.access_order.clear();
205        self.stale_entries.clear();
206        count
207    }
208
209    fn metrics(&mut self) -> CacheMetrics {
210        self.expire_entries();
211        self.purge_stale();
212
213        let mut by_provider: HashMap<String, ProviderCacheStats> = HashMap::new();
214
215        for entry in self.entries.values() {
216            let stats = by_provider.entry(entry.provider_id.clone()).or_default();
217            stats.provider_id.clone_from(&entry.provider_id);
218            stats.entry_count += 1;
219        }
220
221        for (pid, &count) in &self.hits {
222            let stats = by_provider.entry(pid.clone()).or_default();
223            stats.provider_id.clone_from(pid);
224            stats.hits = count;
225        }
226        for (pid, &count) in &self.misses {
227            let stats = by_provider.entry(pid.clone()).or_default();
228            stats.provider_id.clone_from(pid);
229            stats.misses = count;
230        }
231        for (pid, &ts) in &self.last_fetch {
232            let stats = by_provider.entry(pid.clone()).or_default();
233            stats.provider_id.clone_from(pid);
234            stats.last_fetch = Some(ts);
235        }
236
237        let mut provider_stats: Vec<_> = by_provider.into_values().collect();
238        provider_stats.sort_by(|a, b| a.provider_id.cmp(&b.provider_id));
239
240        CacheMetrics {
241            total_hits: self.hits.values().sum(),
242            total_misses: self.misses.values().sum(),
243            total_entries: self.entries.len(),
244            stale_entries: self.stale_entries.len(),
245            max_entries: MAX_CACHE_ENTRIES,
246            provider_stats,
247        }
248    }
249}
250
251pub fn get_cached(key: &str) -> Option<String> {
252    PROVIDER_CACHE
253        .lock()
254        .ok()
255        .and_then(|mut c| c.get(key).map(std::string::ToString::to_string))
256}
257
258pub fn set_cached(key: &str, data: &str, ttl_secs: u64) {
259    set_cached_with_provider(
260        key,
261        data,
262        ttl_secs,
263        key.split(':').next().unwrap_or("unknown"),
264    );
265}
266
267pub fn set_cached_with_provider(key: &str, data: &str, ttl_secs: u64, provider_id: &str) {
268    if let Ok(mut cache) = PROVIDER_CACHE.lock() {
269        cache.set(
270            key.to_string(),
271            data.to_string(),
272            Duration::from_secs(ttl_secs),
273            provider_id,
274        );
275    }
276}
277
278pub fn invalidate_provider(provider_id: &str) -> usize {
279    PROVIDER_CACHE
280        .lock()
281        .ok()
282        .map_or(0, |mut c| c.invalidate_provider(provider_id))
283}
284
285pub fn invalidate_all() -> usize {
286    PROVIDER_CACHE
287        .lock()
288        .ok()
289        .map_or(0, |mut c| c.invalidate_all())
290}
291
292pub fn cache_metrics() -> CacheMetrics {
293    PROVIDER_CACHE
294        .lock()
295        .ok()
296        .map_or_else(CacheMetrics::default, |mut c| c.metrics())
297}
298
299pub fn cache_entry_count() -> usize {
300    PROVIDER_CACHE.lock().ok().map_or(0, |mut cache| {
301        cache.expire_entries();
302        cache.entries.len()
303    })
304}
305
306pub fn cache_stale_count() -> usize {
307    PROVIDER_CACHE
308        .lock()
309        .ok()
310        .map_or(0, |cache| cache.stale_entry_count())
311}
312
313pub fn cache_purge_stale() -> usize {
314    PROVIDER_CACHE.lock().ok().map_or(0, |mut cache| {
315        let before = cache.stale_entry_count();
316        cache.purge_stale();
317        before - cache.stale_entry_count()
318    })
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324
325    #[test]
326    fn cache_set_and_get() {
327        let mut cache = ProviderCache::new();
328        cache.set(
329            "test:key".into(),
330            "value".into(),
331            Duration::from_mins(1),
332            "test",
333        );
334        assert_eq!(cache.get("test:key"), Some("value"));
335    }
336
337    #[test]
338    fn test_stale_serve_on_expired_entry() {
339        let mut cache = ProviderCache::new();
340        cache.set(
341            "test:key".into(),
342            "value".into(),
343            Duration::from_millis(10),
344            "test",
345        );
346        std::thread::sleep(Duration::from_millis(20));
347        assert_eq!(cache.get("test:key"), Some("value"));
348    }
349
350    #[test]
351    fn cache_tracks_hits_and_misses() {
352        let mut cache = ProviderCache::new();
353        cache.set(
354            "github:key".into(),
355            "data".into(),
356            Duration::from_mins(1),
357            "github",
358        );
359        cache.get("github:key"); // hit
360        cache.get("github:key"); // hit
361        cache.get("github:missing"); // miss
362
363        let metrics = cache.metrics();
364        assert_eq!(metrics.total_hits, 2);
365        assert_eq!(metrics.total_misses, 1);
366        assert!((metrics.total_hit_rate() - 0.666).abs() < 0.01);
367    }
368
369    #[test]
370    fn cache_invalidate_provider() {
371        let mut cache = ProviderCache::new();
372        cache.set(
373            "github:a".into(),
374            "1".into(),
375            Duration::from_mins(1),
376            "github",
377        );
378        cache.set(
379            "github:b".into(),
380            "2".into(),
381            Duration::from_mins(1),
382            "github",
383        );
384        cache.set(
385            "gitlab:c".into(),
386            "3".into(),
387            Duration::from_mins(1),
388            "gitlab",
389        );
390
391        let removed = cache.invalidate_provider("github");
392        assert_eq!(removed, 2);
393        assert!(cache.get("github:a").is_none());
394        assert_eq!(cache.get("gitlab:c"), Some("3"));
395    }
396
397    #[test]
398    fn cache_invalidate_all() {
399        let mut cache = ProviderCache::new();
400        cache.set("a".into(), "1".into(), Duration::from_mins(1), "x");
401        cache.set("b".into(), "2".into(), Duration::from_mins(1), "y");
402
403        let removed = cache.invalidate_all();
404        assert_eq!(removed, 2);
405        assert!(cache.get("a").is_none());
406    }
407
408    #[test]
409    fn cache_metrics_per_provider() {
410        let mut cache = ProviderCache::new();
411        cache.set(
412            "github:x".into(),
413            "a".into(),
414            Duration::from_mins(1),
415            "github",
416        );
417        cache.set(
418            "gitlab:y".into(),
419            "b".into(),
420            Duration::from_mins(1),
421            "gitlab",
422        );
423        cache.get("github:x");
424        cache.get("gitlab:miss");
425
426        let metrics = cache.metrics();
427        assert_eq!(metrics.provider_stats.len(), 2);
428
429        let gh = metrics
430            .provider_stats
431            .iter()
432            .find(|s| s.provider_id == "github")
433            .unwrap();
434        assert_eq!(gh.entry_count, 1);
435        assert_eq!(gh.hits, 1);
436
437        let gl = metrics
438            .provider_stats
439            .iter()
440            .find(|s| s.provider_id == "gitlab")
441            .unwrap();
442        assert_eq!(gl.entry_count, 1);
443        assert!(gl.last_fetch.is_some());
444    }
445
446    #[test]
447    fn test_lru_eviction_at_capacity() {
448        let mut cache = ProviderCache::new();
449        for index in 0..MAX_CACHE_ENTRIES + 10 {
450            let key = format!("test:{index}");
451            cache.set(key.clone(), key, Duration::from_mins(1), "test");
452        }
453        assert_eq!(cache.entries.len(), MAX_CACHE_ENTRIES);
454    }
455
456    #[test]
457    fn test_stale_serve_expired_grace() {
458        let mut cache = ProviderCache::new();
459        cache.stale_entries.insert(
460            "test:key".into(),
461            StaleEntry {
462                data: "value".into(),
463                evicted_at: Instant::now()
464                    .checked_sub(STALE_SERVE_GRACE + Duration::from_millis(1))
465                    .unwrap(),
466                provider_id: "test".into(),
467            },
468        );
469        assert!(cache.get("test:key").is_none());
470    }
471
472    #[test]
473    fn test_access_order_update_on_get() {
474        let mut cache = ProviderCache::new();
475        cache.set("a".into(), "1".into(), Duration::from_mins(1), "test");
476        cache.set("b".into(), "2".into(), Duration::from_mins(1), "test");
477        cache.get("a");
478        assert_eq!(cache.access_order.last().map(String::as_str), Some("a"));
479    }
480
481    #[test]
482    fn test_metrics_include_stale_count() {
483        let mut cache = ProviderCache::new();
484        cache.set("a".into(), "1".into(), Duration::from_millis(10), "test");
485        std::thread::sleep(Duration::from_millis(20));
486        assert_eq!(cache.metrics().stale_entries, 1);
487    }
488
489    #[test]
490    fn test_purge_stale_removes_old() {
491        let mut cache = ProviderCache::new();
492        cache.stale_entries.insert(
493            "old".into(),
494            StaleEntry {
495                data: "value".into(),
496                evicted_at: Instant::now()
497                    .checked_sub(STALE_SERVE_GRACE + Duration::from_millis(1))
498                    .unwrap(),
499                provider_id: "test".into(),
500            },
501        );
502        cache.purge_stale();
503        assert_eq!(cache.stale_entry_count(), 0);
504    }
505
506    #[test]
507    #[serial_test::serial(provider_request_cache)]
508    fn test_cache_entry_count_accuracy() {
509        invalidate_all();
510        set_cached_with_provider("test:count", "value", 60, "test");
511        assert_eq!(cache_entry_count(), 1);
512        invalidate_all();
513    }
514
515    #[test]
516    fn provider_cache_stats_hit_rate() {
517        let stats = ProviderCacheStats {
518            provider_id: "test".into(),
519            hits: 3,
520            misses: 1,
521            entry_count: 2,
522            last_fetch: None,
523        };
524        assert!((stats.hit_rate() - 0.75).abs() < f64::EPSILON);
525    }
526
527    #[test]
528    fn request_cache_key_is_deterministic_and_principal_request_bound() {
529        let request = "https://gitlab.example/api/v4/projects/group%2Fproject/issues?per_page=20&state=opened";
530        let key = request_cache_key("gitlab", request, Some("principal-token"));
531
532        assert_eq!(
533            key,
534            request_cache_key("gitlab", request, Some("principal-token"))
535        );
536        assert_ne!(
537            key,
538            request_cache_key("gitlab", request, Some("other-principal-token"))
539        );
540        assert_ne!(
541            key,
542            request_cache_key(
543                "gitlab",
544                "https://gitlab.other/api/v4/projects/group%2Fproject/issues?per_page=20&state=opened",
545                Some("principal-token")
546            )
547        );
548        assert_ne!(
549            key,
550            request_cache_key(
551                "gitlab",
552                "https://gitlab.example/api/v4/projects/group%2Fproject/issues?per_page=20&state=closed",
553                Some("principal-token")
554            )
555        );
556        assert_ne!(
557            key,
558            request_cache_key("github", request, Some("principal-token"))
559        );
560        assert_ne!(key, request_cache_key("gitlab", request, None));
561        assert_ne!(key, request_cache_key("gitlab", request, Some("")));
562        assert_ne!(
563            request_cache_key("gitlab", request, None),
564            request_cache_key("gitlab", request, Some(""))
565        );
566        assert!(!key.contains("principal-token"));
567        assert!(!key.contains("gitlab.example"));
568        assert!(!key.contains("group%2Fproject"));
569    }
570
571    #[test]
572    fn request_cache_key_does_not_reuse_legacy_raw_key() {
573        let key = request_cache_key(
574            "gitlab",
575            "https://gitlab.example/api/v4/projects/group%2Fproject/issues?per_page=20&state=opened",
576            Some("principal-token"),
577        );
578        let legacy_key = "gitlab:issues:group/project:Some(\"opened\"):None:20";
579
580        assert_ne!(key, legacy_key);
581        assert!(key.starts_with("gitlab:request:v2:"));
582    }
583
584    #[test]
585    fn request_cache_key_isolates_fresh_and_stale_responses() {
586        let request = "https://gitlab.example/api/v4/projects/42/issues?state=opened";
587        let principal_key = request_cache_key("gitlab", request, Some("principal-token"));
588        let foreign_keys = [
589            request_cache_key("gitlab", request, Some("other-principal-token")),
590            request_cache_key("gitlab", request, None),
591            request_cache_key("gitlab", request, Some("")),
592            request_cache_key("github", request, Some("principal-token")),
593            request_cache_key(
594                "gitlab",
595                "https://gitlab.other/api/v4/projects/42/issues?state=opened",
596                Some("principal-token"),
597            ),
598            request_cache_key(
599                "gitlab",
600                "https://gitlab.example/api/v4/projects/42/issues?state=closed",
601                Some("principal-token"),
602            ),
603        ];
604        let mut cache = ProviderCache::new();
605        cache.set(
606            principal_key.clone(),
607            "principal response".into(),
608            Duration::from_mins(1),
609            "gitlab",
610        );
611        assert_eq!(cache.get(&principal_key), Some("principal response"));
612        for key in &foreign_keys {
613            assert_eq!(cache.get(key), None);
614        }
615        cache.move_to_stale(&principal_key, Instant::now());
616        assert_eq!(cache.get(&principal_key), Some("principal response"));
617        for key in &foreign_keys {
618            assert_eq!(cache.get(key), None);
619        }
620        cache.set(
621            "gitlab:issues:42:Some(\"opened\"):None:20".into(),
622            "legacy response".into(),
623            Duration::from_mins(1),
624            "gitlab",
625        );
626        assert_eq!(cache.get(&foreign_keys[0]), None);
627    }
628}