1use std::collections::{HashMap, VecDeque};
25
26fn fnv1a_hash(data: &[u8]) -> u64 {
30 const FNV_OFFSET_BASIS: u64 = 14_695_981_039_346_656_037;
31 const FNV_PRIME: u64 = 1_099_511_628_211;
32
33 let mut hash = FNV_OFFSET_BASIS;
34 for byte in data {
35 hash ^= *byte as u64;
36 hash = hash.wrapping_mul(FNV_PRIME);
37 }
38 hash
39}
40
41fn query_hash(query: &str) -> u64 {
43 fnv1a_hash(query.as_bytes())
44}
45
46#[derive(Debug, Clone)]
50pub struct CacheEntry {
51 pub query_hash: u64,
53 pub response: String,
55 pub created_at: u64,
57 pub access_count: usize,
59 pub ttl_ms: u64,
61}
62
63impl CacheEntry {
64 pub fn is_valid(&self, now_ms: u64) -> bool {
66 now_ms < self.created_at.saturating_add(self.ttl_ms)
67 }
68}
69
70#[derive(Debug, Clone, Default)]
72pub struct CacheStats {
73 pub hits: u64,
75 pub misses: u64,
77 pub evictions: u64,
79 pub entries: usize,
81}
82
83pub struct ResponseCache {
91 capacity: usize,
92 default_ttl_ms: u64,
93 entries: HashMap<u64, CacheEntry>,
94 lru_order: VecDeque<u64>,
96 stats: CacheStats,
97}
98
99impl ResponseCache {
100 pub fn new(capacity: usize, default_ttl_ms: u64) -> Self {
103 Self {
104 capacity: capacity.max(1),
105 default_ttl_ms,
106 entries: HashMap::new(),
107 lru_order: VecDeque::new(),
108 stats: CacheStats::default(),
109 }
110 }
111
112 pub fn get(&mut self, query: &str, now_ms: u64) -> Option<String> {
120 let key = query_hash(query);
121
122 match self.entries.get_mut(&key) {
123 Some(entry) if entry.is_valid(now_ms) => {
124 entry.access_count += 1;
125 self.stats.hits += 1;
126 let response = entry.response.clone();
127 self.touch_lru(key);
129 Some(response)
130 }
131 _ => {
132 self.stats.misses += 1;
133 None
134 }
135 }
136 }
137
138 pub fn put(&mut self, query: &str, response: String, now_ms: u64) {
142 let key = query_hash(query);
143
144 if !self.entries.contains_key(&key) && self.entries.len() >= self.capacity {
146 self.evict_lru();
147 }
148
149 if self.entries.contains_key(&key) {
151 self.lru_order.retain(|&k| k != key);
152 }
153
154 let entry = CacheEntry {
155 query_hash: key,
156 response,
157 created_at: now_ms,
158 access_count: 0,
159 ttl_ms: self.default_ttl_ms,
160 };
161
162 self.entries.insert(key, entry);
163 self.lru_order.push_front(key);
164 self.stats.entries = self.entries.len();
165 }
166
167 pub fn invalidate(&mut self, query: &str) -> bool {
171 let key = query_hash(query);
172 if self.entries.remove(&key).is_some() {
173 self.lru_order.retain(|&k| k != key);
174 self.stats.entries = self.entries.len();
175 true
176 } else {
177 false
178 }
179 }
180
181 pub fn invalidate_expired(&mut self, now_ms: u64) -> usize {
185 let expired_keys: Vec<u64> = self
186 .entries
187 .iter()
188 .filter(|(_, e)| !e.is_valid(now_ms))
189 .map(|(k, _)| *k)
190 .collect();
191
192 let count = expired_keys.len();
193 for key in expired_keys {
194 self.entries.remove(&key);
195 self.lru_order.retain(|&k| k != key);
196 }
197
198 self.stats.entries = self.entries.len();
199 count
200 }
201
202 pub fn stats(&self) -> &CacheStats {
204 &self.stats
205 }
206
207 pub fn len(&self) -> usize {
209 self.entries.len()
210 }
211
212 pub fn is_empty(&self) -> bool {
214 self.entries.is_empty()
215 }
216
217 pub fn capacity(&self) -> usize {
219 self.capacity
220 }
221
222 pub fn default_ttl_ms(&self) -> u64 {
224 self.default_ttl_ms
225 }
226
227 pub fn clear(&mut self) {
229 self.entries.clear();
230 self.lru_order.clear();
231 self.stats = CacheStats::default();
232 }
233
234 fn touch_lru(&mut self, key: u64) {
238 self.lru_order.retain(|&k| k != key);
239 self.lru_order.push_front(key);
240 }
241
242 fn evict_lru(&mut self) {
244 if let Some(lru_key) = self.lru_order.pop_back() {
245 self.entries.remove(&lru_key);
246 self.stats.evictions += 1;
247 self.stats.entries = self.entries.len();
248 }
249 }
250}
251
252#[cfg(test)]
255mod tests {
256 use super::*;
257
258 #[test]
261 fn test_hash_deterministic() {
262 assert_eq!(query_hash("hello"), query_hash("hello"));
263 }
264
265 #[test]
266 fn test_hash_different_inputs() {
267 assert_ne!(query_hash("hello"), query_hash("world"));
268 }
269
270 #[test]
271 fn test_hash_empty_string() {
272 let h = query_hash("");
273 let _ = h;
275 }
276
277 #[test]
280 fn test_entry_is_valid_before_expiry() {
281 let entry = CacheEntry {
282 query_hash: 1,
283 response: "r".to_string(),
284 created_at: 1000,
285 access_count: 0,
286 ttl_ms: 5000,
287 };
288 assert!(entry.is_valid(5999));
289 }
290
291 #[test]
292 fn test_entry_is_invalid_after_expiry() {
293 let entry = CacheEntry {
294 query_hash: 1,
295 response: "r".to_string(),
296 created_at: 1000,
297 access_count: 0,
298 ttl_ms: 5000,
299 };
300 assert!(!entry.is_valid(6001));
301 }
302
303 #[test]
304 fn test_entry_exact_boundary_invalid() {
305 let entry = CacheEntry {
306 query_hash: 1,
307 response: "r".to_string(),
308 created_at: 1000,
309 access_count: 0,
310 ttl_ms: 5000,
311 };
312 assert!(!entry.is_valid(6000));
314 }
315
316 #[test]
319 fn test_new_cache_is_empty() {
320 let cache = ResponseCache::new(100, 60_000);
321 assert!(cache.is_empty());
322 assert_eq!(cache.len(), 0);
323 }
324
325 #[test]
326 fn test_new_cache_capacity_stored() {
327 let cache = ResponseCache::new(50, 10_000);
328 assert_eq!(cache.capacity(), 50);
329 }
330
331 #[test]
332 fn test_new_cache_ttl_stored() {
333 let cache = ResponseCache::new(50, 99_999);
334 assert_eq!(cache.default_ttl_ms(), 99_999);
335 }
336
337 #[test]
340 fn test_basic_put_and_get() {
341 let mut cache = ResponseCache::new(10, 60_000);
342 cache.put("q1", "response1".to_string(), 0);
343 assert_eq!(cache.get("q1", 1000), Some("response1".to_string()));
344 }
345
346 #[test]
347 fn test_get_missing_returns_none() {
348 let mut cache = ResponseCache::new(10, 60_000);
349 assert!(cache.get("nonexistent", 0).is_none());
350 }
351
352 #[test]
353 fn test_get_after_ttl_expiry_returns_none() {
354 let mut cache = ResponseCache::new(10, 5_000);
355 cache.put("q", "r".to_string(), 0);
356 assert!(cache.get("q", 5_001).is_none());
357 }
358
359 #[test]
360 fn test_get_within_ttl_succeeds() {
361 let mut cache = ResponseCache::new(10, 5_000);
362 cache.put("q", "r".to_string(), 1000);
363 assert!(cache.get("q", 5_999).is_some());
364 }
365
366 #[test]
367 fn test_put_updates_existing_entry() {
368 let mut cache = ResponseCache::new(10, 60_000);
369 cache.put("q", "v1".to_string(), 0);
370 cache.put("q", "v2".to_string(), 0);
371 assert_eq!(cache.get("q", 0), Some("v2".to_string()));
372 assert_eq!(cache.len(), 1); }
374
375 #[test]
376 fn test_put_multiple_entries() {
377 let mut cache = ResponseCache::new(10, 60_000);
378 cache.put("q1", "r1".to_string(), 0);
379 cache.put("q2", "r2".to_string(), 0);
380 cache.put("q3", "r3".to_string(), 0);
381 assert_eq!(cache.len(), 3);
382 }
383
384 #[test]
387 fn test_eviction_at_capacity() {
388 let mut cache = ResponseCache::new(3, 60_000);
389 cache.put("q1", "r1".to_string(), 0);
390 cache.put("q2", "r2".to_string(), 0);
391 cache.put("q3", "r3".to_string(), 0);
392 cache.get("q1", 0);
394 cache.put("q4", "r4".to_string(), 0);
396 assert_eq!(cache.len(), 3);
397 assert!(cache.get("q2", 0).is_none()); assert!(cache.get("q1", 0).is_some()); assert!(cache.get("q3", 0).is_some()); assert!(cache.get("q4", 0).is_some()); }
402
403 #[test]
404 fn test_eviction_counter_increments() {
405 let mut cache = ResponseCache::new(2, 60_000);
406 cache.put("q1", "r1".to_string(), 0);
407 cache.put("q2", "r2".to_string(), 0);
408 cache.put("q3", "r3".to_string(), 0); assert_eq!(cache.stats().evictions, 1);
410 }
411
412 #[test]
413 fn test_no_eviction_within_capacity() {
414 let mut cache = ResponseCache::new(5, 60_000);
415 cache.put("q1", "r1".to_string(), 0);
416 cache.put("q2", "r2".to_string(), 0);
417 assert_eq!(cache.stats().evictions, 0);
418 }
419
420 #[test]
423 fn test_invalidate_existing_returns_true() {
424 let mut cache = ResponseCache::new(10, 60_000);
425 cache.put("q", "r".to_string(), 0);
426 assert!(cache.invalidate("q"));
427 }
428
429 #[test]
430 fn test_invalidate_missing_returns_false() {
431 let mut cache = ResponseCache::new(10, 60_000);
432 assert!(!cache.invalidate("nonexistent"));
433 }
434
435 #[test]
436 fn test_invalidate_removes_entry() {
437 let mut cache = ResponseCache::new(10, 60_000);
438 cache.put("q", "r".to_string(), 0);
439 cache.invalidate("q");
440 assert!(cache.get("q", 0).is_none());
441 assert_eq!(cache.len(), 0);
442 }
443
444 #[test]
445 fn test_invalidate_allows_reinsertion() {
446 let mut cache = ResponseCache::new(10, 60_000);
447 cache.put("q", "r1".to_string(), 0);
448 cache.invalidate("q");
449 cache.put("q", "r2".to_string(), 0);
450 assert_eq!(cache.get("q", 0), Some("r2".to_string()));
451 }
452
453 #[test]
456 fn test_invalidate_expired_removes_stale() {
457 let mut cache = ResponseCache::new(10, 1_000);
458 cache.put("q1", "r1".to_string(), 0);
459 cache.put("q2", "r2".to_string(), 0);
460 let purged = cache.invalidate_expired(2_000); assert_eq!(purged, 2);
462 assert!(cache.is_empty());
463 }
464
465 #[test]
466 fn test_invalidate_expired_keeps_fresh() {
467 let mut cache = ResponseCache::new(10, 10_000);
468 cache.put("q1", "r1".to_string(), 0); cache.put("q2", "r2".to_string(), 5_000); let purged = cache.invalidate_expired(11_000); assert_eq!(purged, 1);
472 assert_eq!(cache.len(), 1);
473 assert!(cache.get("q2", 11_000).is_some());
474 }
475
476 #[test]
477 fn test_invalidate_expired_none_expired() {
478 let mut cache = ResponseCache::new(10, 60_000);
479 cache.put("q", "r".to_string(), 0);
480 let purged = cache.invalidate_expired(1_000);
481 assert_eq!(purged, 0);
482 assert_eq!(cache.len(), 1);
483 }
484
485 #[test]
486 fn test_invalidate_expired_empty_cache() {
487 let mut cache = ResponseCache::new(10, 60_000);
488 assert_eq!(cache.invalidate_expired(0), 0);
489 }
490
491 #[test]
494 fn test_stats_initial_zeros() {
495 let cache = ResponseCache::new(10, 60_000);
496 let s = cache.stats();
497 assert_eq!(s.hits, 0);
498 assert_eq!(s.misses, 0);
499 assert_eq!(s.evictions, 0);
500 assert_eq!(s.entries, 0);
501 }
502
503 #[test]
504 fn test_stats_hit_increments() {
505 let mut cache = ResponseCache::new(10, 60_000);
506 cache.put("q", "r".to_string(), 0);
507 cache.get("q", 0);
508 assert_eq!(cache.stats().hits, 1);
509 }
510
511 #[test]
512 fn test_stats_miss_increments() {
513 let mut cache = ResponseCache::new(10, 60_000);
514 cache.get("q", 0);
515 assert_eq!(cache.stats().misses, 1);
516 }
517
518 #[test]
519 fn test_stats_miss_on_expired() {
520 let mut cache = ResponseCache::new(10, 1_000);
521 cache.put("q", "r".to_string(), 0);
522 cache.get("q", 2_000); assert_eq!(cache.stats().misses, 1);
524 assert_eq!(cache.stats().hits, 0);
525 }
526
527 #[test]
528 fn test_stats_entries_tracks_len() {
529 let mut cache = ResponseCache::new(10, 60_000);
530 cache.put("q1", "r1".to_string(), 0);
531 cache.put("q2", "r2".to_string(), 0);
532 assert_eq!(cache.stats().entries, 2);
533 cache.invalidate("q1");
534 assert_eq!(cache.stats().entries, 1);
535 }
536
537 #[test]
540 fn test_access_count_increments_on_hit() {
541 let mut cache = ResponseCache::new(10, 60_000);
542 cache.put("q", "r".to_string(), 0);
543 cache.get("q", 0);
544 cache.get("q", 0);
545 let entry = cache.entries.get(&query_hash("q")).expect("entry exists");
546 assert_eq!(entry.access_count, 2);
547 }
548
549 #[test]
552 fn test_is_empty_after_clear() {
553 let mut cache = ResponseCache::new(10, 60_000);
554 cache.put("q", "r".to_string(), 0);
555 cache.clear();
556 assert!(cache.is_empty());
557 }
558
559 #[test]
560 fn test_len_after_clear() {
561 let mut cache = ResponseCache::new(10, 60_000);
562 cache.put("q1", "r1".to_string(), 0);
563 cache.put("q2", "r2".to_string(), 0);
564 cache.clear();
565 assert_eq!(cache.len(), 0);
566 }
567
568 #[test]
571 fn test_clear_resets_stats() {
572 let mut cache = ResponseCache::new(10, 60_000);
573 cache.put("q", "r".to_string(), 0);
574 cache.get("q", 0);
575 cache.clear();
576 assert_eq!(cache.stats().hits, 0);
577 assert_eq!(cache.stats().entries, 0);
578 }
579
580 #[test]
583 fn test_minimum_capacity_is_one() {
584 let cache = ResponseCache::new(0, 60_000);
585 assert_eq!(cache.capacity(), 1);
586 }
587
588 #[test]
589 fn test_large_capacity() {
590 let cache = ResponseCache::new(100_000, 3_600_000);
591 assert_eq!(cache.capacity(), 100_000);
592 }
593
594 #[test]
597 fn test_lru_order_after_access() {
598 let mut cache = ResponseCache::new(3, 60_000);
599 cache.put("q1", "r1".to_string(), 0);
600 cache.put("q2", "r2".to_string(), 0);
601 cache.put("q3", "r3".to_string(), 0);
602 cache.get("q1", 0);
604 cache.get("q3", 0);
605 cache.put("q4", "r4".to_string(), 0);
607 assert!(cache.get("q2", 0).is_none());
608 assert!(cache.get("q1", 0).is_some());
609 assert!(cache.get("q3", 0).is_some());
610 assert!(cache.get("q4", 0).is_some());
611 }
612
613 #[test]
616 fn test_zero_ttl_always_expired() {
617 let mut cache = ResponseCache::new(10, 0);
618 cache.put("q", "r".to_string(), 0);
619 assert!(cache.get("q", 0).is_none());
621 }
622
623 #[test]
624 fn test_very_large_ttl() {
625 let mut cache = ResponseCache::new(10, u64::MAX / 2);
626 cache.put("q", "r".to_string(), 0);
627 assert!(cache.get("q", u64::MAX / 4).is_some());
628 }
629}