mx-cache 0.1.0

Shared cache utilities (local + Redis) for MultiversX Rust services.
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
//! Mock implementations for testing cache operations without external dependencies.
//!
//! This module provides mock implementations that can be used in tests to simulate
//! Redis behavior without requiring a live Redis server.

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use crate::Cache;

/// Helper macro to check error mode and return an error if enabled.
/// Reduces boilerplate in mock implementations.
macro_rules! check_error_mode {
    ($error_mode:expr) => {{
        let guard = $error_mode.lock().unwrap();
        if let Some(ref msg) = *guard {
            return Err(anyhow::anyhow!("{}", msg));
        }
    }};
}

/// Entry in the mock cache with value and expiration time.
#[derive(Clone, Debug)]
struct MockEntry {
    value: Vec<u8>,
    expires_at: Option<Instant>,
}

impl MockEntry {
    fn is_expired(&self) -> bool {
        self.expires_at
            .map(|t| Instant::now() >= t)
            .unwrap_or(false)
    }
}

/// Mock cache implementation for testing purposes.
///
/// Provides an in-memory cache that mimics Redis behavior including:
/// - TTL expiration
/// - NX (not exists) semantics
/// - Error injection for testing error handling
///
/// # Example
///
/// ```
/// use mx_cache::mock::MockCache;
/// use mx_cache::Cache;
/// use std::time::Duration;
///
/// # tokio_test::block_on(async {
/// let cache = MockCache::new();
///
/// cache.set(b"key", b"value", Duration::from_secs(60)).await.unwrap();
/// let result = cache.get(b"key").await.unwrap();
/// assert_eq!(result, Some(b"value".to_vec()));
/// # });
/// ```
#[derive(Clone, Debug)]
pub struct MockCache {
    data: Arc<Mutex<HashMap<Vec<u8>, MockEntry>>>,
    /// When set, all operations will return this error message
    error_mode: Arc<Mutex<Option<String>>>,
    /// Count of operations performed (for verification in tests)
    operation_count: Arc<Mutex<OperationCounts>>,
}

/// Tracks operation counts for test verification.
#[derive(Clone, Debug, Default)]
pub struct OperationCounts {
    pub gets: usize,
    pub sets: usize,
    pub set_nx_px: usize,
    pub deletes: usize,
}

impl MockCache {
    /// Creates a new empty mock cache.
    pub fn new() -> Self {
        Self {
            data: Arc::new(Mutex::new(HashMap::new())),
            error_mode: Arc::new(Mutex::new(None)),
            operation_count: Arc::new(Mutex::new(OperationCounts::default())),
        }
    }

    /// Creates a mock cache with pre-populated data.
    ///
    /// # Arguments
    ///
    /// * `entries` - Iterator of (key, value) pairs to pre-populate
    pub fn with_data<I, K, V>(entries: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<[u8]>,
        V: AsRef<[u8]>,
    {
        let cache = Self::new();
        {
            let mut data = cache.data.lock().unwrap();
            for (key, value) in entries {
                data.insert(
                    key.as_ref().to_vec(),
                    MockEntry {
                        value: value.as_ref().to_vec(),
                        expires_at: None,
                    },
                );
            }
        }
        cache
    }

    /// Enables error mode - all subsequent operations will fail with the given message.
    ///
    /// This is useful for testing error handling paths.
    pub fn enable_error_mode(&self, message: &str) {
        let mut error_mode = self.error_mode.lock().unwrap();
        *error_mode = Some(message.to_owned());
    }

    /// Disables error mode - operations will proceed normally.
    pub fn disable_error_mode(&self) {
        let mut error_mode = self.error_mode.lock().unwrap();
        *error_mode = None;
    }

    /// Returns the current operation counts.
    pub fn operation_counts(&self) -> OperationCounts {
        self.operation_count.lock().unwrap().clone()
    }

    /// Resets operation counts to zero.
    pub fn reset_counts(&self) {
        let mut counts = self.operation_count.lock().unwrap();
        *counts = OperationCounts::default();
    }

    /// Returns the number of non-expired entries in the cache.
    pub fn len(&self) -> usize {
        let data = self.data.lock().unwrap();
        data.values().filter(|e| !e.is_expired()).count()
    }

    /// Returns true if the cache has no non-expired entries.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Clears all entries from the cache.
    pub fn clear(&self) {
        let mut data = self.data.lock().unwrap();
        data.clear();
    }

    /// Manually expires an entry (for testing TTL behavior).
    pub fn force_expire(&self, key: &[u8]) {
        let mut data = self.data.lock().unwrap();
        if let Some(entry) = data.get_mut(&key.to_vec()) {
            entry.expires_at = Some(Instant::now() - Duration::from_secs(1));
        }
    }
}

impl Default for MockCache {
    fn default() -> Self {
        Self::new()
    }
}

impl Cache for MockCache {
    fn set_nx_px(
        &self,
        key: &[u8],
        value: &[u8],
        ttl: Duration,
    ) -> impl Future<Output = anyhow::Result<bool>> + Send {
        let key_vec = key.to_vec();
        let value_vec = value.to_vec();
        let data = Arc::clone(&self.data);
        let error_mode = Arc::clone(&self.error_mode);
        let operation_count = Arc::clone(&self.operation_count);

        async move {
            check_error_mode!(error_mode);
            operation_count.lock().unwrap().set_nx_px += 1;

            let mut data = data.lock().unwrap();

            // Check if key exists and is not expired
            if let Some(entry) = data.get(&key_vec)
                && !entry.is_expired()
            {
                return Ok(false);
            }

            // Insert new entry
            let expires_at = if ttl.is_zero() {
                Some(Instant::now())
            } else {
                Some(Instant::now() + ttl)
            };

            data.insert(
                key_vec,
                MockEntry {
                    value: value_vec,
                    expires_at,
                },
            );

            Ok(true)
        }
    }

    fn set(
        &self,
        key: &[u8],
        value: &[u8],
        ttl: Duration,
    ) -> impl Future<Output = anyhow::Result<()>> + Send {
        let key_vec = key.to_vec();
        let value_vec = value.to_vec();
        let data = Arc::clone(&self.data);
        let error_mode = Arc::clone(&self.error_mode);
        let operation_count = Arc::clone(&self.operation_count);

        async move {
            check_error_mode!(error_mode);
            operation_count.lock().unwrap().sets += 1;

            let expires_at = if ttl.is_zero() {
                Some(Instant::now())
            } else {
                Some(Instant::now() + ttl)
            };

            let mut data = data.lock().unwrap();
            data.insert(
                key_vec,
                MockEntry {
                    value: value_vec,
                    expires_at,
                },
            );

            Ok(())
        }
    }

    fn get(&self, key: &[u8]) -> impl Future<Output = anyhow::Result<Option<Vec<u8>>>> + Send {
        let key_vec = key.to_vec();
        let data = Arc::clone(&self.data);
        let error_mode = Arc::clone(&self.error_mode);
        let operation_count = Arc::clone(&self.operation_count);

        async move {
            check_error_mode!(error_mode);
            operation_count.lock().unwrap().gets += 1;

            let data = data.lock().unwrap();

            match data.get(&key_vec) {
                Some(entry) if !entry.is_expired() => Ok(Some(entry.value.clone())),
                _ => Ok(None),
            }
        }
    }

    fn del(&self, key: &[u8]) -> impl Future<Output = anyhow::Result<()>> + Send {
        let key_vec = key.to_vec();
        let data = Arc::clone(&self.data);
        let error_mode = Arc::clone(&self.error_mode);
        let operation_count = Arc::clone(&self.operation_count);

        async move {
            check_error_mode!(error_mode);
            operation_count.lock().unwrap().deletes += 1;

            let mut data = data.lock().unwrap();
            data.remove(&key_vec);

            Ok(())
        }
    }
}

/// Mock set implementation for testing `RedisSet` operations.
#[derive(Clone, Debug)]
pub struct MockSet {
    data: Arc<Mutex<std::collections::HashSet<String>>>,
    error_mode: Arc<Mutex<Option<String>>>,
}

impl MockSet {
    /// Creates a new empty mock set.
    pub fn new() -> Self {
        Self {
            data: Arc::new(Mutex::new(std::collections::HashSet::new())),
            error_mode: Arc::new(Mutex::new(None)),
        }
    }

    /// Enables error mode for testing error handling.
    pub fn enable_error_mode(&self, message: &str) {
        let mut error_mode = self.error_mode.lock().unwrap();
        *error_mode = Some(message.to_owned());
    }

    /// Disables error mode.
    pub fn disable_error_mode(&self) {
        let mut error_mode = self.error_mode.lock().unwrap();
        *error_mode = None;
    }

    /// Adds items to the set.
    pub async fn add_items(&self, items: &[String]) -> anyhow::Result<()> {
        check_error_mode!(self.error_mode);

        if items.is_empty() {
            return Ok(());
        }

        let mut data = self.data.lock().unwrap();
        for item in items {
            data.insert(item.clone());
        }
        Ok(())
    }

    /// Removes items from the set.
    pub async fn remove_items(&self, items: &[String]) -> anyhow::Result<()> {
        check_error_mode!(self.error_mode);

        if items.is_empty() {
            return Ok(());
        }

        let mut data = self.data.lock().unwrap();
        for item in items {
            data.remove(item);
        }
        Ok(())
    }

    /// Adds a single item to the set.
    pub async fn add_item(&self, item: &str) -> anyhow::Result<()> {
        self.add_items(&[item.to_owned()]).await
    }

    /// Removes a single item from the set.
    pub async fn remove_item(&self, item: &str) -> anyhow::Result<()> {
        self.remove_items(&[item.to_owned()]).await
    }

    /// Returns all items in the set.
    pub async fn load_items(&self) -> anyhow::Result<Vec<String>> {
        check_error_mode!(self.error_mode);

        let data = self.data.lock().unwrap();
        Ok(data.iter().cloned().collect())
    }

    /// Trims the set to `max_entries` by removing arbitrary entries.
    pub async fn trim_to(&self, max_entries: usize) -> anyhow::Result<()> {
        check_error_mode!(self.error_mode);

        if max_entries == 0 {
            return Ok(());
        }

        let mut data = self.data.lock().unwrap();
        while data.len() > max_entries {
            // Remove an arbitrary element
            if let Some(item) = data.iter().next().cloned() {
                data.remove(&item);
            }
        }
        Ok(())
    }

    /// Returns the number of items in the set.
    pub fn len(&self) -> usize {
        self.data.lock().unwrap().len()
    }

    /// Returns true if the set is empty.
    pub fn is_empty(&self) -> bool {
        self.data.lock().unwrap().is_empty()
    }

    /// Clears all items from the set.
    pub fn clear(&self) {
        self.data.lock().unwrap().clear();
    }

    /// Checks if the set contains an item.
    pub fn contains(&self, item: &str) -> bool {
        self.data.lock().unwrap().contains(item)
    }
}

impl Default for MockSet {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_mock_cache_basic_operations() {
        let cache = MockCache::new();

        // Test set and get
        cache
            .set(b"key1", b"value1", Duration::from_secs(60))
            .await
            .unwrap();
        let result = cache.get(b"key1").await.unwrap();
        assert_eq!(result, Some(b"value1".to_vec()));

        // Test get non-existent
        let result = cache.get(b"nonexistent").await.unwrap();
        assert_eq!(result, None);

        // Test delete
        cache.del(b"key1").await.unwrap();
        let result = cache.get(b"key1").await.unwrap();
        assert_eq!(result, None);
    }

    #[tokio::test]
    async fn test_mock_cache_set_nx_px() {
        let cache = MockCache::new();

        // First set should succeed
        let was_set = cache
            .set_nx_px(b"key1", b"value1", Duration::from_secs(60))
            .await
            .unwrap();
        assert!(was_set);

        // Second set should fail
        let was_set = cache
            .set_nx_px(b"key1", b"value2", Duration::from_secs(60))
            .await
            .unwrap();
        assert!(!was_set);

        // Value should be original
        let result = cache.get(b"key1").await.unwrap();
        assert_eq!(result, Some(b"value1".to_vec()));
    }

    #[tokio::test]
    async fn test_mock_cache_error_mode() {
        let cache = MockCache::new();

        // Normal operation should succeed
        cache
            .set(b"key1", b"value1", Duration::from_secs(60))
            .await
            .unwrap();

        // Enable error mode
        cache.enable_error_mode("Redis connection failed");

        // All operations should fail
        let result = cache.get(b"key1").await;
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("connection failed")
        );

        let result = cache.set(b"key2", b"value2", Duration::from_secs(60)).await;
        assert!(result.is_err());

        let result = cache
            .set_nx_px(b"key3", b"value3", Duration::from_secs(60))
            .await;
        assert!(result.is_err());

        let result = cache.del(b"key1").await;
        assert!(result.is_err());

        // Disable error mode
        cache.disable_error_mode();

        // Operations should succeed again
        let result = cache.get(b"key1").await.unwrap();
        assert_eq!(result, Some(b"value1".to_vec()));
    }

    #[tokio::test]
    async fn test_mock_cache_operation_counts() {
        let cache = MockCache::new();

        cache
            .set(b"k1", b"v1", Duration::from_secs(60))
            .await
            .unwrap();
        cache
            .set(b"k2", b"v2", Duration::from_secs(60))
            .await
            .unwrap();
        cache.get(b"k1").await.unwrap();
        cache.get(b"k2").await.unwrap();
        cache.get(b"k3").await.unwrap();
        cache
            .set_nx_px(b"k4", b"v4", Duration::from_secs(60))
            .await
            .unwrap();
        cache.del(b"k1").await.unwrap();

        let counts = cache.operation_counts();
        assert_eq!(counts.sets, 2);
        assert_eq!(counts.gets, 3);
        assert_eq!(counts.set_nx_px, 1);
        assert_eq!(counts.deletes, 1);

        cache.reset_counts();
        let counts = cache.operation_counts();
        assert_eq!(counts.sets, 0);
        assert_eq!(counts.gets, 0);
    }

    #[tokio::test]
    async fn test_mock_cache_ttl_expiration() {
        let cache = MockCache::new();

        cache
            .set(b"key1", b"value1", Duration::from_millis(50))
            .await
            .unwrap();

        // Should exist immediately
        let result = cache.get(b"key1").await.unwrap();
        assert_eq!(result, Some(b"value1".to_vec()));

        // Wait for expiration
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Should be expired
        let result = cache.get(b"key1").await.unwrap();
        assert_eq!(result, None);
    }

    #[tokio::test]
    async fn test_mock_cache_force_expire() {
        let cache = MockCache::new();

        cache
            .set(b"key1", b"value1", Duration::from_secs(60))
            .await
            .unwrap();

        // Force expire
        cache.force_expire(b"key1");

        // Should be expired
        let result = cache.get(b"key1").await.unwrap();
        assert_eq!(result, None);
    }

    #[tokio::test]
    async fn test_mock_cache_with_data() {
        let cache = MockCache::with_data([
            (b"key1".as_slice(), b"value1".as_slice()),
            (b"key2", b"value2"),
        ]);

        let result1 = cache.get(b"key1").await.unwrap();
        assert_eq!(result1, Some(b"value1".to_vec()));

        let result2 = cache.get(b"key2").await.unwrap();
        assert_eq!(result2, Some(b"value2".to_vec()));
    }

    #[tokio::test]
    async fn test_mock_cache_len_and_clear() {
        let cache = MockCache::new();

        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);

        cache
            .set(b"k1", b"v1", Duration::from_secs(60))
            .await
            .unwrap();
        cache
            .set(b"k2", b"v2", Duration::from_secs(60))
            .await
            .unwrap();

        assert!(!cache.is_empty());
        assert_eq!(cache.len(), 2);

        cache.clear();

        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
    }

    #[tokio::test]
    async fn test_mock_set_basic_operations() {
        let set = MockSet::new();

        assert!(set.is_empty());

        // Add items
        set.add_item("item1").await.unwrap();
        set.add_item("item2").await.unwrap();

        assert_eq!(set.len(), 2);
        assert!(set.contains("item1"));
        assert!(set.contains("item2"));
        assert!(!set.contains("item3"));

        // Load items
        let items = set.load_items().await.unwrap();
        assert_eq!(items.len(), 2);

        // Remove item
        set.remove_item("item1").await.unwrap();
        assert!(!set.contains("item1"));
        assert_eq!(set.len(), 1);

        // Clear
        set.clear();
        assert!(set.is_empty());
    }

    #[tokio::test]
    async fn test_mock_set_batch_operations() {
        let set = MockSet::new();

        // Add multiple items
        set.add_items(&["a".to_owned(), "b".to_owned(), "c".to_owned()])
            .await
            .unwrap();
        assert_eq!(set.len(), 3);

        // Remove multiple items
        set.remove_items(&["a".to_owned(), "c".to_owned()])
            .await
            .unwrap();
        assert_eq!(set.len(), 1);
        assert!(set.contains("b"));
    }

    #[tokio::test]
    async fn test_mock_set_trim_to() {
        let set = MockSet::new();

        for i in 0..10 {
            set.add_item(&format!("item{i}")).await.unwrap();
        }
        assert_eq!(set.len(), 10);

        set.trim_to(5).await.unwrap();
        assert_eq!(set.len(), 5);

        // trim_to(0) should do nothing (matches RedisSet behavior)
        set.trim_to(0).await.unwrap();
        assert_eq!(set.len(), 5);
    }

    #[tokio::test]
    async fn test_mock_set_error_mode() {
        let set = MockSet::new();

        set.add_item("item1").await.unwrap();

        set.enable_error_mode("Redis error");

        assert!(set.add_item("item2").await.is_err());
        assert!(set.remove_item("item1").await.is_err());
        assert!(set.load_items().await.is_err());
        assert!(set.trim_to(1).await.is_err());

        set.disable_error_mode();

        assert!(set.load_items().await.is_ok());
    }

    #[tokio::test]
    async fn test_mock_set_empty_operations() {
        let set = MockSet::new();

        // Empty operations should succeed
        set.add_items(&[]).await.unwrap();
        set.remove_items(&[]).await.unwrap();

        assert!(set.is_empty());
    }
}