oxcache 0.1.4

A high-performance multi-level cache library for Rust with L1 (memory) and L2 (Redis) caching.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
//! Copyright (c) 2025-2026, Kirky.X
//!
//! MIT License
//!
//! Unified Cache interface for the modernized cache API

use crate::backend::{CacheBackend, MemoryBackend};
use crate::error::Result;
use crate::serialization::json::JsonSerializer;
use crate::serialization::Serializer;
use crate::traits::{CacheKey, Cacheable};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

// ============================================================================
// CacheOps Wrapper for Backend
// ============================================================================

use crate::serialization::SerializerEnum;
use async_trait::async_trait;
use std::any::Any;

/// Wrapper that implements CacheOps trait for any CacheBackend.
/// This is used to register caches in the global registry for #[cached] macro support.
pub(crate) struct BackendCacheOps {
    pub(crate) backend: Arc<dyn CacheBackend>,
    pub(crate) serializer: SerializerEnum,
}

#[async_trait]
impl crate::client::CacheOps for BackendCacheOps {
    async fn get_bytes(&self, key: &str) -> Result<Option<Vec<u8>>> {
        self.backend.get(key).await
    }

    async fn set_bytes(&self, key: &str, value: Vec<u8>, _ttl: Option<u64>) -> Result<()> {
        self.backend.set(key, value, None).await
    }

    async fn delete(&self, key: &str) -> Result<()> {
        self.backend.delete(key).await
    }

    async fn clear_l1(&self) -> Result<()> {
        self.backend.clear().await
    }

    async fn clear_l2(&self) -> Result<()> {
        self.backend.clear().await
    }

    async fn shutdown(&self) -> Result<()> {
        self.backend.close().await
    }

    fn serializer(&self) -> &SerializerEnum {
        &self.serializer
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn into_any_arc(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
        self
    }
}

/// Creates a CacheOps wrapper for a given backend.
/// This is used by the confers initialization to register caches.
pub fn create_cache_ops_wrapper(
    backend: Arc<dyn CacheBackend>,
    serializer: SerializerEnum,
) -> Arc<dyn crate::client::CacheOps + Send + Sync> {
    Arc::new(BackendCacheOps {
        backend,
        serializer,
    })
}

/// Unified cache interface with type-safe key and value types
///
/// This is the main cache type that users interact with. It provides a
/// type-safe interface over the pluggable backend architecture.
///
/// # Type Parameters
///
/// * `K` - Key type, must implement `CacheKey` trait
/// * `V` - Value type, must implement `Cacheable` trait (Serialize + Deserialize)
///
/// # Example
///
/// ```rust,ignore
/// use oxcache::Cache;
///
/// // Create a simple memory cache
/// let cache: Cache<String, User> = Cache::new().await?;
///
/// // Set a value
/// let user = User { id: 1, name: "Alice".to_string() };
/// cache.set("user:1", &user).await?;
///
/// // Get a value
/// let user: Option<User> = cache.get("user:1").await?;
///
/// // Get with fallback
/// let user: User = cache.get_or("user:1", || async {
///     fetch_user_from_db(1).await
/// }).await?;
/// ```
pub struct Cache<K, V> {
    backend: Arc<dyn CacheBackend>,
    _phantom: std::marker::PhantomData<(K, V)>,
}

impl<K, V> std::fmt::Debug for Cache<K, V>
where
    K: CacheKey,
    V: Cacheable,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Cache")
            .field("backend", &"<CacheBackend>")
            .finish()
    }
}

impl<K, V> Cache<K, V>
where
    K: CacheKey,
    V: Cacheable,
{
    /// Create a new cache with default memory backend
    ///
    /// # Returns
    ///
    /// Configured cache instance
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let cache: Cache<String, User> = Cache::new().await?;
    /// ```
    pub async fn new() -> Result<Self> {
        let backend = MemoryBackend::new();
        Ok(Self {
            backend: Arc::new(backend),
            _phantom: std::marker::PhantomData,
        })
    }

    /// Internal constructor for builder
    pub(crate) fn new_with_backend(backend: Arc<dyn CacheBackend>) -> Self {
        Self {
            backend,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Create a cache with a memory backend
    ///
    /// # Returns
    ///
    /// Configured cache instance
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let cache: Cache<String, User> = Cache::memory().await?;
    /// ```
    pub async fn memory() -> Result<Self> {
        Self::new().await
    }

    /// Create a cache with a Redis backend
    ///
    /// # Arguments
    ///
    /// * `connection_string` - Redis connection URL
    ///
    /// # Returns
    ///
    /// Configured cache instance
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let cache: Cache<String, User> = Cache::redis("redis://localhost:6379").await?;
    /// ```
    pub async fn redis(connection_string: &str) -> Result<Self> {
        let backend = crate::backend::RedisBackend::new(connection_string).await?;
        Ok(Self {
            backend: Arc::new(backend),
            _phantom: std::marker::PhantomData,
        })
    }

    /// Create a cache with a tiered backend (L1 memory + L2 Redis)
    ///
    /// # Arguments
    ///
    /// * `l1_capacity` - Maximum entries in L1 cache
    /// * `l2_connection_string` - Redis connection URL
    ///
    /// # Returns
    ///
    /// Configured cache instance
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let cache: Cache<String, User> = Cache::tiered(
    ///     10000,
    ///     "redis://localhost:6379"
    /// ).await?;
    /// ```
    pub async fn tiered(l1_capacity: u64, l2_connection_string: &str) -> Result<Self> {
        let l1 = MemoryBackend::builder().capacity(l1_capacity).build();
        let l2 = crate::backend::RedisBackend::new(l2_connection_string).await?;
        let backend = crate::backend::TieredBackend::new(l1, l2);
        Ok(Self {
            backend: Arc::new(backend),
            _phantom: std::marker::PhantomData,
        })
    }

    /// Create a cache builder for advanced configuration
    ///
    /// # Returns
    ///
    /// CacheBuilder instance
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let cache: Cache<String, User> = Cache::builder()
    ///     .ttl(Duration::from_secs(3600))
    ///     .capacity(10000)
    ///     .build()
    ///     .await?;
    /// ```
    pub fn builder() -> crate::builder::CacheBuilder<K, V> {
        crate::builder::CacheBuilder::default()
    }

    /// Get a value from the cache
    ///
    /// # Arguments
    ///
    /// * `key` - Cache key
    ///
    /// # Returns
    ///
    /// * `Ok(Some(value))` - Value found
    /// * `Ok(None)` - Key not found
    /// * `Err(CacheError)` - Operation failed
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let user: Option<User> = cache.get("user:1").await?;
    /// ```
    pub async fn get(&self, key: &K) -> Result<Option<V>> {
        let key_str = key.to_key_string();
        let bytes = self.backend.get(&key_str).await?;

        match bytes {
            Some(data) => {
                let serializer = JsonSerializer::new();
                let value: V = serializer.deserialize(&data)?;
                Ok(Some(value))
            }
            None => Ok(None),
        }
    }

    /// Set a value in the cache
    ///
    /// # Arguments
    ///
    /// * `key` - Cache key
    /// * `value` - Value to store
    ///
    /// # Returns
    ///
    /// * `Ok(())` - Value stored successfully
    /// * `Err(CacheError)` - Operation failed
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// cache.set("user:1", &user).await?;
    /// ```
    pub async fn set(&self, key: &K, value: &V) -> Result<()> {
        self.set_with_ttl(key, value, None).await
    }

    /// Set a value in the cache with TTL
    ///
    /// # Arguments
    ///
    /// * `key` - Cache key
    /// * `value` - Value to store
    /// * `ttl` - Time-to-live duration
    ///
    /// # Returns
    ///
    /// * `Ok(())` - Value stored successfully
    /// * `Err(CacheError)` - Operation failed
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::time::Duration;
    ///
    /// cache.set_with_ttl("user:1", &user, Some(Duration::from_secs(3600))).await?;
    /// ```
    pub async fn set_with_ttl(&self, key: &K, value: &V, ttl: Option<Duration>) -> Result<()> {
        let key_str = key.to_key_string();
        let serializer = JsonSerializer::new();
        let bytes = serializer.serialize(value)?;
        self.backend.set(&key_str, bytes, ttl).await
    }

    /// Delete a value from the cache
    ///
    /// # Arguments
    ///
    /// * `key` - Cache key to delete
    ///
    /// # Returns
    ///
    /// * `Ok(())` - Key deleted successfully
    /// * `Err(CacheError)` - Operation failed
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// cache.delete("user:1").await?;
    /// ```
    pub async fn delete(&self, key: &K) -> Result<()> {
        let key_str = key.to_key_string();
        self.backend.delete(&key_str).await
    }

    /// Check if a key exists in the cache
    ///
    /// # Arguments
    ///
    /// * `key` - Cache key to check
    ///
    /// # Returns
    ///
    /// * `Ok(true)` - Key exists
    /// * `Ok(false)` - Key does not exist
    /// * `Err(CacheError)` - Operation failed
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// if cache.exists("user:1").await? {
    ///     println!("User is cached");
    /// }
    /// ```
    pub async fn exists(&self, key: &K) -> Result<bool> {
        let key_str = key.to_key_string();
        self.backend.exists(&key_str).await
    }

    /// Get a value or compute it using a fallback function
    ///
    /// This method provides a convenient way to implement the cache-aside pattern.
    /// If the key exists in the cache, it returns the cached value. Otherwise,
    /// it calls the provided function to compute the value, stores it in the cache,
    /// and returns it.
    ///
    /// # Arguments
    ///
    /// * `key` - Cache key
    /// * `fallback` - Async function to compute the value if not in cache
    ///
    /// # Returns
    ///
    /// * `Ok(value)` - Value from cache or fallback
    /// * `Err(CacheError)` - Operation failed
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let user: User = cache.get_or("user:1", || async {
    ///     fetch_user_from_db(1).await
    /// }).await?;
    /// ```
    pub async fn get_or<F, Fut>(&self, key: &K, fallback: F) -> Result<V>
    where
        F: FnOnce() -> Fut,
        Fut: std::future::Future<Output = Result<V>>,
    {
        if let Some(value) = self.get(key).await? {
            return Ok(value);
        }

        let value = fallback().await?;
        self.set(key, &value).await?;
        Ok(value)
    }

    /// Set multiple values in the cache
    ///
    /// # Arguments
    ///
    /// * `items` - Iterator of (key, value) pairs
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All values stored successfully
    /// * `Err(CacheError)` - Operation failed
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let users = vec![
    ///     ("user:1", user1),
    ///     ("user:2", user2),
    /// ];
    /// cache.set_many(users.iter().map(|(k, v)| (*k, v))).await?;
    /// ```
    pub async fn set_many<'a, I>(&self, items: I) -> Result<()>
    where
        K: 'a,
        V: 'a,
        I: IntoIterator<Item = (&'a K, &'a V)>,
    {
        for (key, value) in items {
            self.set(key, value).await?;
        }
        Ok(())
    }

    /// Get multiple values from the cache
    ///
    /// # Arguments
    ///
    /// * `keys` - Iterator of keys to retrieve
    ///
    /// # Returns
    ///
    /// * `Ok(map)` - Map of keys to values (only found keys)
    /// * `Err(CacheError)` - Operation failed
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let keys = vec!["user:1", "user:2", "user:3"];
    /// let users: HashMap<String, User> = cache.get_many(keys.iter()).await?;
    /// ```
    pub async fn get_many<'a, I>(&self, keys: I) -> Result<HashMap<String, V>>
    where
        K: 'a,
        I: IntoIterator<Item = &'a K>,
    {
        let mut result = HashMap::new();
        for key in keys {
            if let Some(value) = self.get(key).await? {
                result.insert(key.to_key_string(), value);
            }
        }
        Ok(result)
    }

    /// Delete multiple keys from the cache
    ///
    /// # Arguments
    ///
    /// * `keys` - Iterator of keys to delete
    ///
    /// # Returns
    ///
    /// * `Ok(())` - All keys deleted successfully
    /// * `Err(CacheError)` - Operation failed
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let keys = vec!["user:1", "user:2"];
    /// cache.delete_many(keys.iter()).await?;
    /// ```
    pub async fn delete_many<'a, I>(&self, keys: I) -> Result<()>
    where
        K: 'a,
        I: IntoIterator<Item = &'a K>,
    {
        for key in keys {
            self.delete(key).await?;
        }
        Ok(())
    }

    /// Clear all values from the cache
    ///
    /// # Returns
    ///
    /// * `Ok(())` - Cache cleared successfully
    /// * `Err(CacheError)` - Operation failed
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// cache.clear().await?;
    /// ```
    pub async fn clear(&self) -> Result<()> {
        self.backend.clear().await
    }

    /// Get cache statistics
    ///
    /// # Returns
    ///
    /// * `Ok(stats)` - Map of statistics
    /// * `Err(CacheError)` - Failed to retrieve statistics
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let stats = cache.stats().await?;
    /// println!("Cache type: {}", stats.get("type").unwrap());
    /// ```
    pub async fn stats(&self) -> Result<HashMap<String, String>> {
        self.backend.stats().await
    }

    /// Check if the cache backend is healthy
    ///
    /// # Returns
    ///
    /// * `Ok(true)` - Backend is healthy
    /// * `Ok(false)` - Backend is unhealthy
    /// * `Err(CacheError)` - Health check failed
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// if cache.health_check().await? {
    ///     println!("Cache is healthy");
    /// Perform a health check on the cache backend.
    ///
    /// # Returns
    ///
    /// * `Ok(true)` - Cache is healthy
    /// * `Ok(false)` - Cache is unhealthy
    /// * `Err(CacheError)` - Health check failed
    pub async fn health_check(&self) -> Result<bool> {
        self.backend.health_check().await
    }

    /// Shutdown the cache and release all resources.
    ///
    /// This method should be called during application shutdown to properly
    /// close connections and release resources.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let cache: Cache<String, User> = Cache::new().await?;
    /// // ... use cache ...
    /// cache.shutdown().await?;
    /// ```
    pub async fn shutdown(&self) -> Result<()> {
        self.backend.close().await
    }

    /// Create a CacheOps wrapper for this cache instance.
    ///
    /// This allows the cache to be used with the global registry for
    /// #[cached] macro support and confers configuration.
    ///
    /// # Returns
    ///
    /// Arc<dyn CacheOps + Send + Sync> that can be registered in the global registry
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use oxcache::Cache;
    ///
    /// let cache: Cache<String, User> = Cache::new().await?;
    /// let cache_ops = cache.to_cache_ops();
    /// manager::register("my_service", cache_ops);
    /// ```
    pub fn to_cache_ops(&self) -> Arc<dyn crate::client::CacheOps + Send + Sync> {
        create_cache_ops_wrapper(
            self.backend.clone(),
            SerializerEnum::Json(crate::serialization::json::JsonSerializer::new()),
        )
    }

    /// Register this cache instance for use with the #[cached] macro.
    ///
    /// After calling this method, you can use `#[cached(service = "name")]`
    /// on async functions to cache their results using this cache instance.
    ///
    /// # Arguments
    ///
    /// * `service_name` - A unique name to identify this cache instance
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use oxcache::Cache;
    ///
    /// let cache: Cache<String, User> = Cache::new().await?;
    /// cache.register_for_macro("my_service").await;
    ///
    /// // Now you can use:
    /// // #[cached(service = "my_service", ttl = 300)]
    /// // async fn get_user(id: u64) -> User { ... }
    /// ```
    pub async fn register_for_macro(&self, service_name: &str) {
        use crate::internal::__internal_register_cache;

        let cache_ops = create_cache_ops_wrapper(
            self.backend.clone(),
            SerializerEnum::Json(crate::serialization::json::JsonSerializer::new()),
        );
        __internal_register_cache(service_name, cache_ops);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

    #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
    struct TestValue {
        id: u64,
        name: String,
    }

    #[tokio::test]
    async fn test_cache_basic() {
        let cache: Cache<String, TestValue> = Cache::new().await.unwrap();

        let value = TestValue {
            id: 1,
            name: "test".to_string(),
        };

        // Test set and get
        cache.set(&"key1".to_string(), &value).await.unwrap();
        let result = cache.get(&"key1".to_string()).await.unwrap();
        assert_eq!(result, Some(value));

        // Test exists
        assert!(cache.exists(&"key1".to_string()).await.unwrap());
        assert!(!cache.exists(&"key2".to_string()).await.unwrap());

        // Test delete
        cache.delete(&"key1".to_string()).await.unwrap();
        assert!(!cache.exists(&"key1".to_string()).await.unwrap());
    }

    #[tokio::test]
    async fn test_cache_get_or() {
        use crate::error::CacheError;
        let cache: Cache<String, TestValue> = Cache::new().await.unwrap();

        let value = TestValue {
            id: 1,
            name: "test".to_string(),
        };

        // First call should use fallback
        async fn fallback1() -> Result<TestValue> {
            Ok(TestValue {
                id: 1,
                name: "test".to_string(),
            })
        }
        let result1 = cache.get_or(&"key1".to_string(), fallback1).await.unwrap();
        assert_eq!(result1, value);

        // Second call should use cache
        async fn fallback2() -> Result<TestValue> {
            Err(CacheError::NotFound("should not be called".to_string()))
        }
        let result2 = cache.get_or(&"key1".to_string(), fallback2).await.unwrap();
        assert_eq!(result2, value);
    }

    #[tokio::test]
    async fn test_cache_batch_operations() {
        let cache: Cache<String, TestValue> = Cache::new().await.unwrap();

        let value1 = TestValue {
            id: 1,
            name: "test1".to_string(),
        };
        let value2 = TestValue {
            id: 2,
            name: "test2".to_string(),
        };

        // Test set_many
        cache
            .set_many(vec![
                (&"key1".to_string(), &value1),
                (&"key2".to_string(), &value2),
            ])
            .await
            .unwrap();

        // Test get_many
        let results = cache
            .get_many(vec![
                &"key1".to_string(),
                &"key2".to_string(),
                &"key3".to_string(),
            ])
            .await
            .unwrap();
        assert_eq!(results.len(), 2);
        assert_eq!(results.get("key1"), Some(&value1));
        assert_eq!(results.get("key2"), Some(&value2));

        // Test delete_many
        cache
            .delete_many(vec![&"key1".to_string(), &"key2".to_string()])
            .await
            .unwrap();
        assert!(!cache.exists(&"key1".to_string()).await.unwrap());
        assert!(!cache.exists(&"key2".to_string()).await.unwrap());
    }

    #[tokio::test]
    async fn test_cache_clear() {
        let cache: Cache<String, TestValue> = Cache::new().await.unwrap();

        cache
            .set(
                &"key1".to_string(),
                &TestValue {
                    id: 1,
                    name: "test".to_string(),
                },
            )
            .await
            .unwrap();

        cache.clear().await.unwrap();

        assert!(!cache.exists(&"key1".to_string()).await.unwrap());
    }

    #[tokio::test]
    async fn test_cache_stats() {
        let cache: Cache<String, TestValue> = Cache::new().await.unwrap();

        let stats = cache.stats().await.unwrap();
        assert_eq!(stats.get("type"), Some(&"memory".to_string()));
    }
}