mpl_registry_api/
cache.rs

1//! Schema caching with TTL
2
3use moka::sync::Cache;
4use serde_json::Value;
5use std::time::Duration;
6
7/// Cache for schemas with automatic expiration
8pub struct SchemaCache {
9    schemas: Cache<String, Value>,
10}
11
12impl SchemaCache {
13    /// Create a new schema cache
14    pub fn new() -> Self {
15        Self {
16            schemas: Cache::builder()
17                .max_capacity(1000)
18                .time_to_live(Duration::from_secs(300)) // 5 minute TTL
19                .time_to_idle(Duration::from_secs(60))   // 1 minute idle
20                .build(),
21        }
22    }
23
24    /// Get a schema from cache
25    pub fn get(&self, stype: &str) -> Option<Value> {
26        self.schemas.get(stype)
27    }
28
29    /// Insert a schema into cache
30    pub fn insert(&self, stype: String, schema: Value) {
31        self.schemas.insert(stype, schema);
32    }
33
34    /// Check if schema is cached
35    pub fn contains(&self, stype: &str) -> bool {
36        self.schemas.contains_key(stype)
37    }
38
39    /// Invalidate a schema
40    pub fn invalidate(&self, stype: &str) {
41        self.schemas.invalidate(stype);
42    }
43
44    /// Clear all cached schemas
45    pub fn clear(&self) {
46        self.schemas.invalidate_all();
47    }
48
49    /// Get cache statistics
50    pub fn stats(&self) -> CacheStats {
51        CacheStats {
52            entry_count: self.schemas.entry_count(),
53            weighted_size: self.schemas.weighted_size(),
54        }
55    }
56}
57
58impl Default for SchemaCache {
59    fn default() -> Self {
60        Self::new()
61    }
62}
63
64#[derive(Debug, Clone, serde::Serialize)]
65pub struct CacheStats {
66    pub entry_count: u64,
67    pub weighted_size: u64,
68}