1use std::collections::HashMap;
7use std::hash::Hash;
8use std::sync::Arc;
9use std::time::{Duration, Instant};
10use tokio::sync::RwLock;
11
12#[derive(Debug, Clone)]
14struct CacheEntry<V> {
15 value: V,
16 expires_at: Option<Instant>,
17 access_count: u64,
18 last_accessed: Instant,
19}
20
21impl<V> CacheEntry<V> {
22 fn new(value: V, ttl: Option<Duration>) -> Self {
23 let now = Instant::now();
24 Self {
25 value,
26 expires_at: ttl.map(|duration| now + duration),
27 access_count: 0,
28 last_accessed: now,
29 }
30 }
31
32 fn is_expired(&self) -> bool {
33 self.expires_at.is_some_and(|expires_at| Instant::now() > expires_at)
34 }
35
36 fn access(&mut self) -> &V {
37 self.access_count += 1;
38 self.last_accessed = Instant::now();
39 &self.value
40 }
41}
42
43#[derive(Debug)]
45pub struct Cache<K, V> {
46 storage: Arc<RwLock<HashMap<K, CacheEntry<V>>>>,
47 max_size: usize,
48 default_ttl: Option<Duration>,
49 stats: Arc<RwLock<CacheStats>>,
50}
51
52#[derive(Debug, Default, Clone)]
54pub struct CacheStats {
55 pub hits: u64,
57 pub misses: u64,
59 pub evictions: u64,
61 pub expirations: u64,
63 pub insertions: u64,
65}
66
67impl<K: Hash + Eq + Clone, V: Clone> Cache<K, V> {
68 pub fn new(max_size: usize) -> Self {
70 Self {
71 storage: Arc::new(RwLock::new(HashMap::new())),
72 max_size,
73 default_ttl: None,
74 stats: Arc::new(RwLock::new(CacheStats::default())),
75 }
76 }
77
78 pub fn with_ttl(max_size: usize, default_ttl: Duration) -> Self {
80 Self {
81 storage: Arc::new(RwLock::new(HashMap::new())),
82 max_size,
83 default_ttl: Some(default_ttl),
84 stats: Arc::new(RwLock::new(CacheStats::default())),
85 }
86 }
87
88 pub async fn insert(&self, key: K, value: V, ttl: Option<Duration>) {
90 let mut storage = self.storage.write().await;
91 let mut stats = self.stats.write().await;
92
93 let effective_ttl = ttl.or(self.default_ttl);
95
96 self.cleanup_expired(&mut storage, &mut stats).await;
98
99 if storage.len() >= self.max_size && !storage.contains_key(&key) {
101 self.evict_lru(&mut storage, &mut stats).await;
102 }
103
104 storage.insert(key, CacheEntry::new(value, effective_ttl));
105 stats.insertions += 1;
106 }
107
108 pub async fn get(&self, key: &K) -> Option<V> {
110 let mut storage = self.storage.write().await;
111 let mut stats = self.stats.write().await;
112
113 if let Some(entry) = storage.get_mut(key) {
114 if entry.is_expired() {
115 storage.remove(key);
116 stats.expirations += 1;
117 stats.misses += 1;
118 return None;
119 }
120
121 stats.hits += 1;
122 Some(entry.access().clone())
123 } else {
124 stats.misses += 1;
125 None
126 }
127 }
128
129 pub async fn contains_key(&self, key: &K) -> bool {
131 let storage = self.storage.read().await;
132 if let Some(entry) = storage.get(key) {
133 !entry.is_expired()
134 } else {
135 false
136 }
137 }
138
139 pub async fn remove(&self, key: &K) -> Option<V> {
141 let mut storage = self.storage.write().await;
142 storage.remove(key).map(|entry| entry.value)
143 }
144
145 pub async fn clear(&self) {
147 let mut storage = self.storage.write().await;
148 storage.clear();
149 }
150
151 pub async fn len(&self) -> usize {
153 let storage = self.storage.read().await;
154 storage.len()
155 }
156
157 pub async fn is_empty(&self) -> bool {
159 let storage = self.storage.read().await;
160 storage.is_empty()
161 }
162
163 pub async fn stats(&self) -> CacheStats {
165 let stats = self.stats.read().await;
166 stats.clone()
167 }
168
169 pub async fn reset_stats(&self) {
171 let mut stats = self.stats.write().await;
172 *stats = CacheStats::default();
173 }
174
175 pub async fn get_or_insert<F, Fut>(&self, key: K, f: F) -> V
177 where
178 F: FnOnce() -> Fut,
179 Fut: std::future::Future<Output = V>,
180 {
181 if let Some(value) = self.get(&key).await {
182 return value;
183 }
184
185 let value = f().await;
186 self.insert(key, value.clone(), None).await;
187 value
188 }
189
190 pub async fn get_or_insert_with_ttl<F, Fut>(&self, key: K, f: F, ttl: Duration) -> V
192 where
193 F: FnOnce() -> Fut,
194 Fut: std::future::Future<Output = V>,
195 {
196 if let Some(value) = self.get(&key).await {
197 return value;
198 }
199
200 let value = f().await;
201 self.insert(key, value.clone(), Some(ttl)).await;
202 value
203 }
204
205 async fn cleanup_expired(
207 &self,
208 storage: &mut HashMap<K, CacheEntry<V>>,
209 stats: &mut CacheStats,
210 ) {
211 let expired_keys: Vec<K> = storage
212 .iter()
213 .filter_map(|(k, v)| {
214 if v.is_expired() {
215 Some(k.clone())
216 } else {
217 None
218 }
219 })
220 .collect();
221
222 for key in expired_keys {
223 storage.remove(&key);
224 stats.expirations += 1;
225 }
226 }
227
228 async fn evict_lru(&self, storage: &mut HashMap<K, CacheEntry<V>>, stats: &mut CacheStats) {
230 if let Some((lru_key, _)) = storage
231 .iter()
232 .min_by_key(|(_, entry)| entry.last_accessed)
233 .map(|(k, v)| (k.clone(), v.clone()))
234 {
235 storage.remove(&lru_key);
236 stats.evictions += 1;
237 }
238 }
239}
240
241#[derive(Debug)]
243pub struct ResponseCache {
244 cache: Cache<String, CachedResponse>,
245}
246
247#[derive(Debug, Clone)]
249pub struct CachedResponse {
250 pub status_code: u16,
252 pub headers: HashMap<String, String>,
254 pub body: String,
256 pub content_type: Option<String>,
258}
259
260impl ResponseCache {
261 pub fn new(max_size: usize, ttl: Duration) -> Self {
263 Self {
264 cache: Cache::with_ttl(max_size, ttl),
265 }
266 }
267
268 pub fn generate_key(
270 method: &str,
271 path: &str,
272 query: &str,
273 headers: &HashMap<String, String>,
274 ) -> String {
275 use std::collections::hash_map::DefaultHasher;
276 use std::hash::Hasher;
277
278 let mut hasher = DefaultHasher::new();
279 hasher.write(method.as_bytes());
280 hasher.write(path.as_bytes());
281 hasher.write(query.as_bytes());
282
283 let mut sorted_headers: Vec<_> = headers.iter().collect();
285 sorted_headers.sort_by_key(|(k, _)| *k);
286 for (key, value) in sorted_headers {
287 if key.to_lowercase() != "authorization" && !key.to_lowercase().starts_with("x-") {
288 hasher.write(key.as_bytes());
289 hasher.write(value.as_bytes());
290 }
291 }
292
293 format!("resp_{}_{}", hasher.finish(), path.len())
294 }
295
296 pub async fn cache_response(&self, key: String, response: CachedResponse) {
298 self.cache.insert(key, response, None).await;
299 }
300
301 pub async fn get_response(&self, key: &str) -> Option<CachedResponse> {
303 self.cache.get(&key.to_string()).await
304 }
305
306 pub async fn stats(&self) -> CacheStats {
308 self.cache.stats().await
309 }
310}
311
312#[derive(Debug)]
314pub struct TemplateCache {
315 cache: Cache<String, CompiledTemplate>,
316}
317
318#[derive(Debug, Clone)]
320pub struct CompiledTemplate {
321 pub template: String,
323 pub variables: Vec<String>,
325 pub compiled_at: Instant,
327}
328
329impl TemplateCache {
330 pub fn new(max_size: usize) -> Self {
332 Self {
333 cache: Cache::new(max_size),
334 }
335 }
336
337 pub async fn cache_template(&self, key: String, template: String, variables: Vec<String>) {
339 let compiled = CompiledTemplate {
340 template,
341 variables,
342 compiled_at: Instant::now(),
343 };
344 self.cache.insert(key, compiled, None).await;
345 }
346
347 pub async fn get_template(&self, key: &str) -> Option<CompiledTemplate> {
349 self.cache.get(&key.to_string()).await
350 }
351
352 pub async fn stats(&self) -> CacheStats {
354 self.cache.stats().await
355 }
356}
357
358#[cfg(test)]
359mod tests {
360 use super::*;
361 use tokio::time::sleep;
362
363 #[tokio::test]
366 async fn test_basic_cache_operations() {
367 let cache = Cache::new(3);
368
369 cache.insert("key1".to_string(), "value1".to_string(), None).await;
370 cache.insert("key2".to_string(), "value2".to_string(), None).await;
371
372 assert_eq!(cache.get(&"key1".to_string()).await, Some("value1".to_string()));
373 assert_eq!(cache.get(&"key2".to_string()).await, Some("value2".to_string()));
374 assert_eq!(cache.get(&"key3".to_string()).await, None);
375
376 assert_eq!(cache.len().await, 2);
377 assert!(!cache.is_empty().await);
378 }
379
380 #[tokio::test]
381 async fn test_cache_new() {
382 let cache: Cache<String, String> = Cache::new(100);
383 assert!(cache.is_empty().await);
384 assert_eq!(cache.len().await, 0);
385 }
386
387 #[tokio::test]
388 async fn test_cache_with_ttl() {
389 let cache: Cache<String, String> = Cache::with_ttl(100, Duration::from_secs(60));
390 assert!(cache.is_empty().await);
391 }
392
393 #[tokio::test]
394 async fn test_cache_contains_key() {
395 let cache = Cache::new(10);
396 cache.insert("key1".to_string(), "value1".to_string(), None).await;
397
398 assert!(cache.contains_key(&"key1".to_string()).await);
399 assert!(!cache.contains_key(&"key2".to_string()).await);
400 }
401
402 #[tokio::test]
403 async fn test_cache_remove() {
404 let cache = Cache::new(10);
405 cache.insert("key1".to_string(), "value1".to_string(), None).await;
406
407 let removed = cache.remove(&"key1".to_string()).await;
408 assert_eq!(removed, Some("value1".to_string()));
409 assert!(!cache.contains_key(&"key1".to_string()).await);
410
411 let removed2 = cache.remove(&"key2".to_string()).await;
413 assert_eq!(removed2, None);
414 }
415
416 #[tokio::test]
417 async fn test_cache_clear() {
418 let cache = Cache::new(10);
419 cache.insert("key1".to_string(), "value1".to_string(), None).await;
420 cache.insert("key2".to_string(), "value2".to_string(), None).await;
421
422 assert_eq!(cache.len().await, 2);
423 cache.clear().await;
424 assert_eq!(cache.len().await, 0);
425 assert!(cache.is_empty().await);
426 }
427
428 #[tokio::test]
429 async fn test_cache_overwrite() {
430 let cache = Cache::new(10);
431 cache.insert("key1".to_string(), "value1".to_string(), None).await;
432 cache.insert("key1".to_string(), "value2".to_string(), None).await;
433
434 assert_eq!(cache.get(&"key1".to_string()).await, Some("value2".to_string()));
435 assert_eq!(cache.len().await, 1);
436 }
437
438 #[tokio::test]
441 async fn test_ttl_expiration() {
442 let cache = Cache::with_ttl(10, Duration::from_millis(50));
443
444 cache.insert("key1".to_string(), "value1".to_string(), None).await;
445 assert_eq!(cache.get(&"key1".to_string()).await, Some("value1".to_string()));
446
447 sleep(Duration::from_millis(60)).await;
448 assert_eq!(cache.get(&"key1".to_string()).await, None);
449 }
450
451 #[tokio::test]
452 async fn test_custom_ttl_per_entry() {
453 let cache = Cache::new(10);
454
455 cache
457 .insert("short".to_string(), "short_lived".to_string(), Some(Duration::from_millis(30)))
458 .await;
459 cache
460 .insert("long".to_string(), "long_lived".to_string(), Some(Duration::from_secs(60)))
461 .await;
462
463 assert_eq!(cache.get(&"short".to_string()).await, Some("short_lived".to_string()));
464 assert_eq!(cache.get(&"long".to_string()).await, Some("long_lived".to_string()));
465
466 sleep(Duration::from_millis(50)).await;
468
469 assert_eq!(cache.get(&"short".to_string()).await, None);
470 assert_eq!(cache.get(&"long".to_string()).await, Some("long_lived".to_string()));
471 }
472
473 #[tokio::test]
474 async fn test_contains_key_respects_ttl() {
475 let cache = Cache::with_ttl(10, Duration::from_millis(30));
476 cache.insert("key".to_string(), "value".to_string(), None).await;
477
478 assert!(cache.contains_key(&"key".to_string()).await);
479
480 sleep(Duration::from_millis(50)).await;
481
482 assert!(!cache.contains_key(&"key".to_string()).await);
483 }
484
485 #[tokio::test]
488 async fn test_lru_eviction() {
489 let cache = Cache::new(2);
490
491 cache.insert("key1".to_string(), "value1".to_string(), None).await;
492 cache.insert("key2".to_string(), "value2".to_string(), None).await;
493
494 cache.get(&"key1".to_string()).await;
496
497 cache.insert("key3".to_string(), "value3".to_string(), None).await;
499
500 assert_eq!(cache.get(&"key1".to_string()).await, Some("value1".to_string()));
501 assert_eq!(cache.get(&"key2".to_string()).await, None);
502 assert_eq!(cache.get(&"key3".to_string()).await, Some("value3".to_string()));
503 }
504
505 #[tokio::test]
506 async fn test_eviction_stats() {
507 let cache = Cache::new(2);
508
509 cache.insert("key1".to_string(), "value1".to_string(), None).await;
510 cache.insert("key2".to_string(), "value2".to_string(), None).await;
511 cache.insert("key3".to_string(), "value3".to_string(), None).await;
512
513 let stats = cache.stats().await;
514 assert_eq!(stats.evictions, 1);
515 }
516
517 #[tokio::test]
518 async fn test_no_eviction_when_replacing() {
519 let cache = Cache::new(2);
520
521 cache.insert("key1".to_string(), "value1".to_string(), None).await;
522 cache.insert("key2".to_string(), "value2".to_string(), None).await;
523 cache.insert("key1".to_string(), "updated".to_string(), None).await;
525
526 let stats = cache.stats().await;
527 assert_eq!(stats.evictions, 0);
528 assert_eq!(cache.len().await, 2);
529 }
530
531 #[tokio::test]
534 async fn test_cache_stats() {
535 let cache = Cache::new(10);
536
537 cache.insert("key1".to_string(), "value1".to_string(), None).await;
538 cache.get(&"key1".to_string()).await; cache.get(&"key2".to_string()).await; let stats = cache.stats().await;
542 assert_eq!(stats.hits, 1);
543 assert_eq!(stats.misses, 1);
544 assert_eq!(stats.insertions, 1);
545 }
546
547 #[tokio::test]
548 async fn test_reset_stats() {
549 let cache = Cache::new(10);
550
551 cache.insert("key1".to_string(), "value1".to_string(), None).await;
552 cache.get(&"key1".to_string()).await;
553 cache.get(&"key2".to_string()).await;
554
555 let stats = cache.stats().await;
556 assert_eq!(stats.hits, 1);
557 assert_eq!(stats.misses, 1);
558
559 cache.reset_stats().await;
560
561 let stats_after = cache.stats().await;
562 assert_eq!(stats_after.hits, 0);
563 assert_eq!(stats_after.misses, 0);
564 assert_eq!(stats_after.insertions, 0);
565 }
566
567 #[tokio::test]
568 async fn test_expiration_stats() {
569 let cache = Cache::with_ttl(10, Duration::from_millis(20));
570
571 cache.insert("key".to_string(), "value".to_string(), None).await;
572 sleep(Duration::from_millis(30)).await;
573 cache.get(&"key".to_string()).await; let stats = cache.stats().await;
576 assert_eq!(stats.expirations, 1);
577 }
578
579 #[tokio::test]
582 async fn test_get_or_insert_miss() {
583 let cache = Cache::new(10);
584
585 let value = cache
586 .get_or_insert("key".to_string(), || async { "computed_value".to_string() })
587 .await;
588
589 assert_eq!(value, "computed_value".to_string());
590 assert_eq!(cache.get(&"key".to_string()).await, Some("computed_value".to_string()));
591 }
592
593 #[tokio::test]
594 async fn test_get_or_insert_hit() {
595 let cache = Cache::new(10);
596 cache.insert("key".to_string(), "existing_value".to_string(), None).await;
597
598 let value = cache
599 .get_or_insert("key".to_string(), || async { "should_not_be_used".to_string() })
600 .await;
601
602 assert_eq!(value, "existing_value".to_string());
603 }
604
605 #[tokio::test]
606 async fn test_get_or_insert_with_ttl() {
607 let cache = Cache::new(10);
608
609 let value = cache
610 .get_or_insert_with_ttl(
611 "key".to_string(),
612 || async { "computed".to_string() },
613 Duration::from_millis(30),
614 )
615 .await;
616
617 assert_eq!(value, "computed".to_string());
618
619 assert!(cache.contains_key(&"key".to_string()).await);
621
622 sleep(Duration::from_millis(50)).await;
624
625 assert!(!cache.contains_key(&"key".to_string()).await);
626 }
627
628 #[tokio::test]
631 async fn test_response_cache() {
632 let response_cache = ResponseCache::new(100, Duration::from_secs(300));
633
634 let headers = HashMap::new();
635 let key = ResponseCache::generate_key("GET", "/api/users", "", &headers);
636
637 let response = CachedResponse {
638 status_code: 200,
639 headers: HashMap::new(),
640 body: "test response".to_string(),
641 content_type: Some("application/json".to_string()),
642 };
643
644 response_cache.cache_response(key.clone(), response.clone()).await;
645 let cached = response_cache.get_response(&key).await;
646
647 assert!(cached.is_some());
648 assert_eq!(cached.unwrap().body, "test response");
649 }
650
651 #[tokio::test]
652 async fn test_response_cache_key_generation() {
653 let headers1 = HashMap::new();
654 let headers2 = HashMap::new();
655
656 let key1 = ResponseCache::generate_key("GET", "/api/users", "page=1", &headers1);
658 let key2 = ResponseCache::generate_key("GET", "/api/users", "page=1", &headers2);
659 assert_eq!(key1, key2);
660
661 let key3 = ResponseCache::generate_key("POST", "/api/users", "page=1", &headers1);
663 assert_ne!(key1, key3);
664
665 let key4 = ResponseCache::generate_key("GET", "/api/items", "page=1", &headers1);
667 assert_ne!(key1, key4);
668
669 let key5 = ResponseCache::generate_key("GET", "/api/users", "page=2", &headers1);
671 assert_ne!(key1, key5);
672 }
673
674 #[tokio::test]
675 async fn test_response_cache_key_excludes_auth_headers() {
676 let mut headers_without_auth = HashMap::new();
677 headers_without_auth.insert("accept".to_string(), "application/json".to_string());
678
679 let mut headers_with_auth = headers_without_auth.clone();
680 headers_with_auth.insert("authorization".to_string(), "Bearer token123".to_string());
681
682 let key1 = ResponseCache::generate_key("GET", "/api/users", "", &headers_without_auth);
684 let key2 = ResponseCache::generate_key("GET", "/api/users", "", &headers_with_auth);
685
686 assert_eq!(key1, key2);
687 }
688
689 #[tokio::test]
690 async fn test_response_cache_key_excludes_x_headers() {
691 let mut headers1 = HashMap::new();
692 headers1.insert("accept".to_string(), "application/json".to_string());
693
694 let mut headers2 = headers1.clone();
695 headers2.insert("x-request-id".to_string(), "unique-id-123".to_string());
696 headers2.insert("x-correlation-id".to_string(), "corr-456".to_string());
697
698 let key1 = ResponseCache::generate_key("GET", "/api/users", "", &headers1);
699 let key2 = ResponseCache::generate_key("GET", "/api/users", "", &headers2);
700
701 assert_eq!(key1, key2);
702 }
703
704 #[tokio::test]
705 async fn test_response_cache_stats() {
706 let response_cache = ResponseCache::new(10, Duration::from_secs(60));
707
708 let response = CachedResponse {
709 status_code: 200,
710 headers: HashMap::new(),
711 body: "test".to_string(),
712 content_type: None,
713 };
714
715 response_cache.cache_response("key1".to_string(), response).await;
716 response_cache.get_response("key1").await; response_cache.get_response("key2").await; let stats = response_cache.stats().await;
720 assert_eq!(stats.hits, 1);
721 assert_eq!(stats.misses, 1);
722 }
723
724 #[tokio::test]
727 async fn test_template_cache_new() {
728 let template_cache = TemplateCache::new(100);
729 assert_eq!(template_cache.stats().await.insertions, 0);
730 }
731
732 #[tokio::test]
733 async fn test_template_cache_operations() {
734 let template_cache = TemplateCache::new(100);
735
736 template_cache
737 .cache_template(
738 "greeting".to_string(),
739 "Hello, {{name}}!".to_string(),
740 vec!["name".to_string()],
741 )
742 .await;
743
744 let cached = template_cache.get_template("greeting").await;
745 assert!(cached.is_some());
746
747 let template = cached.unwrap();
748 assert_eq!(template.template, "Hello, {{name}}!");
749 assert_eq!(template.variables, vec!["name".to_string()]);
750 }
751
752 #[tokio::test]
753 async fn test_template_cache_miss() {
754 let template_cache = TemplateCache::new(100);
755
756 let cached = template_cache.get_template("nonexistent").await;
757 assert!(cached.is_none());
758 }
759
760 #[tokio::test]
761 async fn test_template_cache_stats() {
762 let template_cache = TemplateCache::new(10);
763
764 template_cache
765 .cache_template("key".to_string(), "template".to_string(), vec![])
766 .await;
767
768 template_cache.get_template("key").await; template_cache.get_template("missing").await; let stats = template_cache.stats().await;
772 assert_eq!(stats.hits, 1);
773 assert_eq!(stats.misses, 1);
774 assert_eq!(stats.insertions, 1);
775 }
776
777 #[test]
780 fn test_cache_stats_default() {
781 let stats = CacheStats::default();
782 assert_eq!(stats.hits, 0);
783 assert_eq!(stats.misses, 0);
784 assert_eq!(stats.evictions, 0);
785 assert_eq!(stats.expirations, 0);
786 assert_eq!(stats.insertions, 0);
787 }
788
789 #[test]
790 fn test_cache_stats_clone() {
791 let mut stats = CacheStats::default();
792 stats.hits = 10;
793 stats.misses = 5;
794
795 let cloned = stats.clone();
796 assert_eq!(cloned.hits, 10);
797 assert_eq!(cloned.misses, 5);
798 }
799
800 #[test]
801 fn test_cache_stats_debug() {
802 let stats = CacheStats::default();
803 let debug_str = format!("{:?}", stats);
804 assert!(debug_str.contains("CacheStats"));
805 assert!(debug_str.contains("hits"));
806 }
807
808 #[test]
811 fn test_cached_response_clone() {
812 let response = CachedResponse {
813 status_code: 200,
814 headers: HashMap::new(),
815 body: "test".to_string(),
816 content_type: Some("application/json".to_string()),
817 };
818
819 let cloned = response.clone();
820 assert_eq!(cloned.status_code, 200);
821 assert_eq!(cloned.body, "test");
822 assert_eq!(cloned.content_type, Some("application/json".to_string()));
823 }
824
825 #[test]
826 fn test_cached_response_debug() {
827 let response = CachedResponse {
828 status_code: 404,
829 headers: HashMap::new(),
830 body: "not found".to_string(),
831 content_type: None,
832 };
833
834 let debug_str = format!("{:?}", response);
835 assert!(debug_str.contains("CachedResponse"));
836 assert!(debug_str.contains("404"));
837 }
838
839 #[test]
842 fn test_compiled_template_clone() {
843 let template = CompiledTemplate {
844 template: "Hello, {{name}}!".to_string(),
845 variables: vec!["name".to_string()],
846 compiled_at: Instant::now(),
847 };
848
849 let cloned = template.clone();
850 assert_eq!(cloned.template, "Hello, {{name}}!");
851 assert_eq!(cloned.variables, vec!["name".to_string()]);
852 }
853
854 #[test]
855 fn test_compiled_template_debug() {
856 let template = CompiledTemplate {
857 template: "test".to_string(),
858 variables: vec![],
859 compiled_at: Instant::now(),
860 };
861
862 let debug_str = format!("{:?}", template);
863 assert!(debug_str.contains("CompiledTemplate"));
864 assert!(debug_str.contains("test"));
865 }
866
867 #[tokio::test]
870 async fn test_cache_with_zero_size() {
871 let cache = Cache::new(0);
873 cache.insert("key".to_string(), "value".to_string(), None).await;
874 }
876
877 #[tokio::test]
878 async fn test_cache_with_numeric_keys() {
879 let cache = Cache::new(10);
880 cache.insert(1, "one".to_string(), None).await;
881 cache.insert(2, "two".to_string(), None).await;
882
883 assert_eq!(cache.get(&1).await, Some("one".to_string()));
884 assert_eq!(cache.get(&2).await, Some("two".to_string()));
885 }
886
887 #[tokio::test]
888 async fn test_cache_with_complex_values() {
889 let cache: Cache<String, Vec<u8>> = Cache::new(10);
890 cache.insert("bytes".to_string(), vec![1, 2, 3, 4, 5], None).await;
891
892 let retrieved = cache.get(&"bytes".to_string()).await;
893 assert_eq!(retrieved, Some(vec![1, 2, 3, 4, 5]));
894 }
895
896 #[tokio::test]
897 async fn test_multiple_expirations_cleanup() {
898 let cache = Cache::with_ttl(10, Duration::from_millis(20));
899
900 cache.insert("key1".to_string(), "v1".to_string(), None).await;
901 cache.insert("key2".to_string(), "v2".to_string(), None).await;
902 cache.insert("key3".to_string(), "v3".to_string(), None).await;
903
904 sleep(Duration::from_millis(30)).await;
905
906 cache.insert("new".to_string(), "new_val".to_string(), None).await;
908
909 let stats = cache.stats().await;
910 assert!(stats.expirations >= 3);
911 }
912}