1use serde_json::Value;
4use std::collections::HashMap;
5use std::sync::Arc;
6use std::time::{Duration, Instant};
7use tokio::sync::RwLock;
8
9#[derive(Debug, Clone)]
11pub struct RelationshipCacheConfig {
12 pub max_relationships_per_type: usize,
14 pub max_memory_bytes: usize,
16 pub ttl: Option<Duration>,
18 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, ttl: Some(Duration::from_secs(300)), enable_metrics: true,
29 }
30 }
31}
32
33#[derive(Debug, Clone)]
35struct CacheEntry {
36 data: Value,
38 created_at: Instant,
40 last_accessed: Instant,
42 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#[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
86pub struct OptimizedRelationshipCache {
88 cache: Arc<RwLock<HashMap<CacheKey, CacheEntry>>>,
90 config: RelationshipCacheConfig,
92 metrics: Arc<RwLock<CacheMetrics>>,
94}
95
96impl OptimizedRelationshipCache {
97 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 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 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 self.evict_by_memory().await;
123
124 let current_memory = self.get_memory_usage().await;
126 if current_memory + entry.size_bytes > self.config.max_memory_bytes {
127 return false; }
129 }
130 }
131
132 {
134 let mut cache = self.cache.write().await;
135 cache.insert(key, entry);
136 }
137
138 if self.config.enable_metrics {
140 let mut metrics = self.metrics.write().await;
141 metrics.stores += 1;
142 }
143
144 true
145 }
146
147 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 if let Some(ttl) = self.config.ttl {
156 if entry.is_expired(ttl) {
157 cache.remove(&key);
158
159 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 entry.touch();
172 let data = entry.data.clone();
173
174 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 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 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 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 pub async fn clear_model(&self, model_type: &str, model_id: &str) {
207 let mut cache = self.cache.write().await;
208
209 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 for key in keys_to_remove {
223 cache.remove(&key);
224 }
225 }
226
227 pub async fn clear_model_type(&self, model_type: &str) {
229 let mut cache = self.cache.write().await;
230
231 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 for key in keys_to_remove {
245 cache.remove(&key);
246 }
247 }
248
249 pub async fn clear_all(&self) {
251 let mut cache = self.cache.write().await;
252 cache.clear();
253
254 if self.config.enable_metrics {
256 let mut metrics = self.metrics.write().await;
257 *metrics = CacheMetrics::new();
258 }
259 }
260
261 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 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 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 async fn evict_by_memory(&self) {
299 let target_memory = (self.config.max_memory_bytes as f64 * 0.8) as usize; let mut cache = self.cache.write().await;
302
303 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; }
315 }
316 }
317
318 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 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#[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#[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
388fn 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 }
399 }
400 Value::String(s) => s.len() + 24, Value::Array(arr) => {
402 24 + arr.iter().map(estimate_json_size).sum::<usize>() }
404 Value::Object(obj) => {
405 48 + obj
406 .iter()
407 .map(|(k, v)| k.len() + estimate_json_size(v))
408 .sum::<usize>() }
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 let stored = cache.store("User", "1", "posts", data.clone()).await;
425 assert!(stored);
426
427 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 cache.store("User", "1", "posts", data.clone()).await;
442
443 assert_eq!(cache.get("User", "1", "posts").await, Some(data));
445
446 tokio::time::sleep(Duration::from_millis(150)).await;
448
449 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); }
464}