Skip to main content

elif_orm/relationships/
cache.rs

1//! Relationship Cache - Memory-efficient caching for loaded relationships
2
3use serde_json::Value;
4use std::collections::HashMap;
5use std::sync::Arc;
6use std::time::{Duration, Instant};
7use tokio::sync::RwLock;
8
9/// Configuration for relationship cache
10#[derive(Debug, Clone)]
11pub struct RelationshipCacheConfig {
12    /// Maximum number of cached relationships per model type
13    pub max_relationships_per_type: usize,
14    /// Maximum memory usage in bytes (0 = unlimited)
15    pub max_memory_bytes: usize,
16    /// Time to live for cached relationships
17    pub ttl: Option<Duration>,
18    /// Whether to enable cache metrics
19    pub enable_metrics: bool,
20}
21
22impl Default for RelationshipCacheConfig {
23    fn default() -> Self {
24        Self {
25            max_relationships_per_type: 1000,
26            max_memory_bytes: 50 * 1024 * 1024,  // 50MB
27            ttl: Some(Duration::from_secs(300)), // 5 minutes
28            enable_metrics: true,
29        }
30    }
31}
32
33/// Cached relationship entry
34#[derive(Debug, Clone)]
35struct CacheEntry {
36    /// The cached data
37    data: Value,
38    /// When the entry was created
39    created_at: Instant,
40    /// When the entry was last accessed
41    last_accessed: Instant,
42    /// Estimated size in bytes
43    size_bytes: usize,
44}
45
46impl CacheEntry {
47    fn new(data: Value) -> Self {
48        let now = Instant::now();
49        let size_bytes = estimate_json_size(&data);
50
51        Self {
52            data,
53            created_at: now,
54            last_accessed: now,
55            size_bytes,
56        }
57    }
58
59    fn is_expired(&self, ttl: Duration) -> bool {
60        self.created_at.elapsed() > ttl
61    }
62
63    fn touch(&mut self) {
64        self.last_accessed = Instant::now();
65    }
66}
67
68/// Cache key for relationships
69#[derive(Debug, Clone, Hash, PartialEq, Eq)]
70struct CacheKey {
71    model_type: String,
72    model_id: String,
73    relationship: String,
74}
75
76impl CacheKey {
77    fn new(model_type: &str, model_id: &str, relationship: &str) -> Self {
78        Self {
79            model_type: model_type.to_string(),
80            model_id: model_id.to_string(),
81            relationship: relationship.to_string(),
82        }
83    }
84}
85
86/// Optimized relationship cache with simple HashMap storage
87pub struct OptimizedRelationshipCache {
88    /// Cache storage
89    cache: Arc<RwLock<HashMap<CacheKey, CacheEntry>>>,
90    /// Cache configuration
91    config: RelationshipCacheConfig,
92    /// Cache metrics
93    metrics: Arc<RwLock<CacheMetrics>>,
94}
95
96impl OptimizedRelationshipCache {
97    /// Create a new optimized cache
98    pub fn new(config: RelationshipCacheConfig) -> Self {
99        Self {
100            cache: Arc::new(RwLock::new(HashMap::new())),
101            config,
102            metrics: Arc::new(RwLock::new(CacheMetrics::new())),
103        }
104    }
105
106    /// Store a relationship in the cache
107    pub async fn store(
108        &self,
109        model_type: &str,
110        model_id: &str,
111        relationship: &str,
112        data: Value,
113    ) -> bool {
114        let key = CacheKey::new(model_type, model_id, relationship);
115        let entry = CacheEntry::new(data);
116
117        // Check memory limits
118        if self.config.max_memory_bytes > 0 {
119            let current_memory = self.get_memory_usage().await;
120            if current_memory + entry.size_bytes > self.config.max_memory_bytes {
121                // Evict some entries to make room
122                self.evict_by_memory().await;
123
124                // Check again after eviction
125                let current_memory = self.get_memory_usage().await;
126                if current_memory + entry.size_bytes > self.config.max_memory_bytes {
127                    return false; // Could not make enough room
128                }
129            }
130        }
131
132        // Store the entry
133        {
134            let mut cache = self.cache.write().await;
135            cache.insert(key, entry);
136        }
137
138        // Update metrics
139        if self.config.enable_metrics {
140            let mut metrics = self.metrics.write().await;
141            metrics.stores += 1;
142        }
143
144        true
145    }
146
147    /// Retrieve a relationship from the cache
148    pub async fn get(&self, model_type: &str, model_id: &str, relationship: &str) -> Option<Value> {
149        let key = CacheKey::new(model_type, model_id, relationship);
150
151        let mut cache = self.cache.write().await;
152
153        if let Some(entry) = cache.get_mut(&key) {
154            // Check if expired
155            if let Some(ttl) = self.config.ttl {
156                if entry.is_expired(ttl) {
157                    cache.remove(&key);
158
159                    // Update metrics
160                    if self.config.enable_metrics {
161                        let mut metrics = self.metrics.write().await;
162                        metrics.misses += 1;
163                        metrics.expired += 1;
164                    }
165
166                    return None;
167                }
168            }
169
170            // Touch the entry and return data
171            entry.touch();
172            let data = entry.data.clone();
173
174            // Update metrics
175            if self.config.enable_metrics {
176                let mut metrics = self.metrics.write().await;
177                metrics.hits += 1;
178            }
179
180            Some(data)
181        } else {
182            // Update metrics
183            if self.config.enable_metrics {
184                let mut metrics = self.metrics.write().await;
185                metrics.misses += 1;
186            }
187
188            None
189        }
190    }
191
192    /// Check if a relationship is cached and not expired
193    pub async fn contains(&self, model_type: &str, model_id: &str, relationship: &str) -> bool {
194        self.get(model_type, model_id, relationship).await.is_some()
195    }
196
197    /// Remove a specific cached relationship
198    pub async fn remove(&self, model_type: &str, model_id: &str, relationship: &str) -> bool {
199        let key = CacheKey::new(model_type, model_id, relationship);
200
201        let mut cache = self.cache.write().await;
202        cache.remove(&key).is_some()
203    }
204
205    /// Clear all cached relationships for a model instance
206    pub async fn clear_model(&self, model_type: &str, model_id: &str) {
207        let mut cache = self.cache.write().await;
208
209        // Collect keys to remove
210        let keys_to_remove: Vec<CacheKey> = cache
211            .iter()
212            .filter_map(|(key, _)| {
213                if key.model_type == model_type && key.model_id == model_id {
214                    Some(key.clone())
215                } else {
216                    None
217                }
218            })
219            .collect();
220
221        // Remove the keys
222        for key in keys_to_remove {
223            cache.remove(&key);
224        }
225    }
226
227    /// Clear all cached relationships for a model type
228    pub async fn clear_model_type(&self, model_type: &str) {
229        let mut cache = self.cache.write().await;
230
231        // Collect keys to remove
232        let keys_to_remove: Vec<CacheKey> = cache
233            .iter()
234            .filter_map(|(key, _)| {
235                if key.model_type == model_type {
236                    Some(key.clone())
237                } else {
238                    None
239                }
240            })
241            .collect();
242
243        // Remove the keys
244        for key in keys_to_remove {
245            cache.remove(&key);
246        }
247    }
248
249    /// Clear all cached relationships
250    pub async fn clear_all(&self) {
251        let mut cache = self.cache.write().await;
252        cache.clear();
253
254        // Reset metrics
255        if self.config.enable_metrics {
256            let mut metrics = self.metrics.write().await;
257            *metrics = CacheMetrics::new();
258        }
259    }
260
261    /// Get current memory usage in bytes
262    pub async fn get_memory_usage(&self) -> usize {
263        let cache = self.cache.read().await;
264        cache.values().map(|entry| entry.size_bytes).sum()
265    }
266
267    /// Get cache statistics
268    pub async fn stats(&self) -> CacheStatistics {
269        let cache = self.cache.read().await;
270        let metrics = self.metrics.read().await;
271
272        let total_entries = cache.len();
273        let memory_usage = cache.values().map(|entry| entry.size_bytes).sum();
274
275        // Count by model type
276        let mut model_type_counts = HashMap::new();
277        for (key, _) in cache.iter() {
278            *model_type_counts.entry(key.model_type.clone()).or_insert(0) += 1;
279        }
280
281        CacheStatistics {
282            total_entries,
283            memory_usage_bytes: memory_usage,
284            model_type_counts,
285            hits: metrics.hits,
286            misses: metrics.misses,
287            stores: metrics.stores,
288            expired: metrics.expired,
289            hit_rate: if metrics.hits + metrics.misses > 0 {
290                metrics.hits as f64 / (metrics.hits + metrics.misses) as f64
291            } else {
292                0.0
293            },
294        }
295    }
296
297    /// Evict entries to free memory
298    async fn evict_by_memory(&self) {
299        let target_memory = (self.config.max_memory_bytes as f64 * 0.8) as usize; // Target 80% of max
300
301        let mut cache = self.cache.write().await;
302
303        // Simple eviction strategy: remove oldest entries
304        let mut entries: Vec<(CacheKey, CacheEntry)> = cache.drain().collect();
305        entries.sort_by_key(|(_, entry)| entry.created_at);
306
307        let mut current_memory = 0;
308        for (key, entry) in entries {
309            if current_memory + entry.size_bytes <= target_memory {
310                current_memory += entry.size_bytes;
311                cache.insert(key, entry);
312            } else {
313                break; // Skip remaining entries to stay under target
314            }
315        }
316    }
317
318    /// Clean up expired entries
319    pub async fn cleanup_expired(&self) {
320        if let Some(ttl) = self.config.ttl {
321            let mut cache = self.cache.write().await;
322
323            let keys_to_remove: Vec<CacheKey> = cache
324                .iter()
325                .filter_map(|(key, entry)| {
326                    if entry.is_expired(ttl) {
327                        Some(key.clone())
328                    } else {
329                        None
330                    }
331                })
332                .collect();
333
334            let expired_count = keys_to_remove.len();
335
336            for key in keys_to_remove {
337                cache.remove(&key);
338            }
339
340            // Update metrics
341            if self.config.enable_metrics && expired_count > 0 {
342                let mut metrics = self.metrics.write().await;
343                metrics.expired += expired_count;
344            }
345        }
346    }
347}
348
349impl Default for OptimizedRelationshipCache {
350    fn default() -> Self {
351        Self::new(RelationshipCacheConfig::default())
352    }
353}
354
355/// Cache metrics for monitoring and debugging
356#[derive(Debug, Clone)]
357struct CacheMetrics {
358    hits: usize,
359    misses: usize,
360    stores: usize,
361    expired: usize,
362}
363
364impl CacheMetrics {
365    fn new() -> Self {
366        Self {
367            hits: 0,
368            misses: 0,
369            stores: 0,
370            expired: 0,
371        }
372    }
373}
374
375/// Public cache statistics
376#[derive(Debug, Clone)]
377pub struct CacheStatistics {
378    pub total_entries: usize,
379    pub memory_usage_bytes: usize,
380    pub model_type_counts: HashMap<String, usize>,
381    pub hits: usize,
382    pub misses: usize,
383    pub stores: usize,
384    pub expired: usize,
385    pub hit_rate: f64,
386}
387
388/// Estimate the size of a JSON value in bytes
389fn estimate_json_size(value: &Value) -> usize {
390    match value {
391        Value::Null => 4,
392        Value::Bool(_) => 4,
393        Value::Number(n) => {
394            if n.is_i64() || n.is_u64() {
395                8
396            } else {
397                8 // f64
398            }
399        }
400        Value::String(s) => s.len() + 24, // String overhead
401        Value::Array(arr) => {
402            24 + arr.iter().map(estimate_json_size).sum::<usize>() // Vec overhead
403        }
404        Value::Object(obj) => {
405            48 + obj
406                .iter()
407                .map(|(k, v)| k.len() + estimate_json_size(v))
408                .sum::<usize>() // HashMap overhead
409        }
410    }
411}
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416    use serde_json::json;
417
418    #[tokio::test]
419    async fn test_cache_store_and_retrieve() {
420        let cache = OptimizedRelationshipCache::default();
421        let data = json!({"id": 1, "name": "Test"});
422
423        // Store data
424        let stored = cache.store("User", "1", "posts", data.clone()).await;
425        assert!(stored);
426
427        // Retrieve data
428        let retrieved = cache.get("User", "1", "posts").await;
429        assert_eq!(retrieved, Some(data));
430    }
431
432    #[tokio::test]
433    async fn test_cache_expiration() {
434        let mut config = RelationshipCacheConfig::default();
435        config.ttl = Some(Duration::from_millis(100));
436
437        let cache = OptimizedRelationshipCache::new(config);
438        let data = json!({"id": 1, "name": "Test"});
439
440        // Store data
441        cache.store("User", "1", "posts", data.clone()).await;
442
443        // Should be available immediately
444        assert_eq!(cache.get("User", "1", "posts").await, Some(data));
445
446        // Wait for expiration
447        tokio::time::sleep(Duration::from_millis(150)).await;
448
449        // Should be expired
450        assert_eq!(cache.get("User", "1", "posts").await, None);
451    }
452
453    #[tokio::test]
454    async fn test_memory_estimation() {
455        let data = json!({
456            "id": 1,
457            "name": "Test User",
458            "email": "test@example.com"
459        });
460
461        let size = estimate_json_size(&data);
462        assert!(size > 50); // Should have reasonable size estimation
463    }
464}