larastvel-core 0.2.2

Larastvel framework core - inspired by Laravel
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
pub mod array;
pub mod database;
pub mod file;
pub mod lock;
pub mod redis;

pub use lock::{ArrayLockStore, Lock, LockStore};
pub use redis::RedisStore;

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// Default TTL of 60 minutes (3600 seconds).
pub const DEFAULT_TTL_SECONDS: u64 = 3600;

/// One year in seconds — used for "forever" cached items.
pub const FOREVER_TTL: u64 = 31536000;

/// Prefix helper — joins a cache key prefix with a key.
pub fn prefixed_key(prefix: &str, key: &str) -> String {
    if prefix.is_empty() {
        key.to_string()
    } else {
        format!("{}{}", prefix, key)
    }
}

#[derive(Debug, thiserror::Error)]
pub enum CacheError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    #[error("Serialization error: {0}")]
    Serialization(String),
    #[error("Deserialization error: {0}")]
    Deserialization(String),
    #[error("Key not found: {0}")]
    KeyNotFound(String),
    #[error("Store error: {0}")]
    Store(String),
    #[error("Store [{0}] not configured")]
    NotConfigured(String),
}

/// A single cache entry with its expiry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheItem {
    pub value: String,
    pub expires_at: Option<DateTime<Utc>>,
}

impl CacheItem {
    pub fn new(value: String, ttl_seconds: Option<u64>) -> Self {
        let expires_at =
            ttl_seconds.map(|secs| Utc::now() + chrono::Duration::seconds(secs as i64));
        Self { value, expires_at }
    }

    pub fn is_expired(&self) -> bool {
        match self.expires_at {
            Some(expiry) => Utc::now() > expiry,
            None => false,
        }
    }
}

/// Trait for cache store implementations.
#[async_trait]
pub trait CacheStore: Send + Sync + std::fmt::Debug {
    /// Retrieve a value by key. Returns `None` if missing or expired.
    async fn get(&self, key: &str) -> Result<Option<String>, CacheError>;

    /// Store a value with an optional TTL in seconds.
    async fn set(&self, key: &str, value: &str, ttl_seconds: Option<u64>)
        -> Result<(), CacheError>;

    /// Store a value permanently (or for a very long time).
    async fn forever(&self, key: &str, value: &str) -> Result<(), CacheError> {
        self.set(key, value, Some(FOREVER_TTL)).await
    }

    /// Delete a key. Returns `true` if the key existed.
    async fn delete(&self, key: &str) -> Result<bool, CacheError>;

    /// Check if a key exists and is not expired.
    async fn has(&self, key: &str) -> Result<bool, CacheError> {
        Ok(self.get(key).await?.is_some())
    }

    /// Remove all items from the store.
    async fn clear(&self) -> Result<(), CacheError>;

    /// Get and delete a key atomically.
    async fn pull(&self, key: &str) -> Result<Option<String>, CacheError> {
        let value = self.get(key).await?;
        if value.is_some() {
            self.delete(key).await?;
        }
        Ok(value)
    }

    /// Increment a numeric value. Returns the new value.
    async fn increment(&self, key: &str, by: i64) -> Result<i64, CacheError>;

    /// Decrement a numeric value. Returns the new value.
    async fn decrement(&self, key: &str, by: i64) -> Result<i64, CacheError> {
        self.increment(key, -by).await
    }

    /// Extend the TTL of an existing key without re-fetching its value.
    /// Returns `false` if the key does not exist or is expired.
    async fn touch(&self, key: &str, ttl_seconds: u64) -> Result<bool, CacheError> {
        if let Some(value) = self.get(key).await? {
            self.set(key, &value, Some(ttl_seconds)).await?;
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Retrieve multiple keys at once.
    async fn many(&self, keys: &[&str]) -> Result<HashMap<String, Option<String>>, CacheError> {
        let mut result = HashMap::new();
        for key in keys {
            let value = self.get(key).await?;
            result.insert(key.to_string(), value);
        }
        Ok(result)
    }

    /// Store multiple items at once with the same TTL.
    async fn set_many(
        &self,
        items: &[(&str, &str)],
        ttl_seconds: Option<u64>,
    ) -> Result<(), CacheError> {
        for (key, value) in items {
            self.set(key, value, ttl_seconds).await?;
        }
        Ok(())
    }

    /// Get or store a value using a boxed callback.
    async fn remember(
        &self,
        key: &str,
        ttl_seconds: u64,
        callback: Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = String> + Send>> + Send>,
    ) -> Result<String, CacheError> {
        if let Some(value) = self.get(key).await? {
            return Ok(value);
        }
        let value = callback().await;
        self.set(key, &value, Some(ttl_seconds)).await?;
        Ok(value)
    }

    /// Get or store forever using a boxed callback.
    async fn remember_forever(
        &self,
        key: &str,
        callback: Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = String> + Send>> + Send>,
    ) -> Result<String, CacheError> {
        self.remember(key, FOREVER_TTL, callback).await
    }

    fn name(&self) -> &str;

    /// Return a [`LockStore`] view of this store when it supports atomic
    /// locks (array, redis). Stores without lock support return `None`.
    fn as_lock_store(&self) -> Option<Arc<dyn LockStore>> {
        None
    }
}

/// Manager for multiple cache stores.
#[derive(Debug, Clone)]
pub struct CacheManager {
    stores: HashMap<String, Arc<dyn CacheStore>>,
    default: String,
}

impl CacheManager {
    pub fn new(default: &str) -> Self {
        Self {
            stores: HashMap::new(),
            default: default.to_string(),
        }
    }

    pub fn register<S: CacheStore + 'static>(&mut self, name: &str, store: S) {
        self.stores.insert(name.to_string(), Arc::new(store));
    }

    pub fn store(&self, name: &str) -> Result<Arc<dyn CacheStore>, CacheError> {
        self.stores
            .get(name)
            .cloned()
            .ok_or_else(|| CacheError::NotConfigured(name.to_string()))
    }

    pub fn default_store(&self) -> Result<Arc<dyn CacheStore>, CacheError> {
        self.store(&self.default)
    }

    pub fn set_default(&mut self, name: &str) {
        self.default = name.to_string();
    }

    pub fn default_name(&self) -> &str {
        &self.default
    }

    pub fn store_names(&self) -> Vec<String> {
        self.stores.keys().cloned().collect()
    }

    /// Create a [`Lock`] on the default store. The store must support locks
    /// (array or redis); returns [`CacheError::Store`] otherwise.
    ///
    /// Mirrors Laravel's `Cache::lock('key', $seconds)`.
    pub fn lock(&self, key: &str, ttl: Duration) -> Result<Lock, CacheError> {
        self.store_lock(&self.default, key, ttl)
    }

    /// Create a [`Lock`] on a named store.
    pub fn store_lock(&self, name: &str, key: &str, ttl: Duration) -> Result<Lock, CacheError> {
        let store = self.store(name)?;
        let lock_store = store
            .as_lock_store()
            .ok_or_else(|| CacheError::Store(format!("store '{name}' does not support locks")))?;
        Ok(Lock::new(lock_store, key, ttl))
    }

    /// Acquire a lock (blocking up to `wait`), run `callback` while holding
    /// it, then release. Mirrors Laravel's `Cache::withLock($key, $callback,
    /// $seconds)`.
    pub async fn with_lock<F, Fut, T>(
        &self,
        key: &str,
        ttl: Duration,
        wait: Duration,
        callback: F,
    ) -> Result<T, CacheError>
    where
        F: FnOnce() -> Fut,
        Fut: Future<Output = T>,
    {
        let lock = self.lock(key, ttl)?;
        if !lock.block(wait).await? {
            return Err(CacheError::Store(format!(
                "timed out waiting for lock '{key}'"
            )));
        }
        let result = callback().await;
        let _ = lock.release().await;
        Ok(result)
    }

    /// When the lock is free, run `callback` while holding it; when another
    /// process holds the lock, return the previously cached value instead.
    /// The callback is responsible for storing its own result via the cache
    /// (Laravel's `Cache::getLocked($key, $callback, $seconds)`).
    pub async fn get_locked<F, Fut>(
        &self,
        key: &str,
        ttl: Duration,
        callback: F,
    ) -> Result<String, CacheError>
    where
        F: FnOnce() -> Fut,
        Fut: Future<Output = String>,
    {
        let lock = self.lock(key, ttl)?;
        if lock.get().await? {
            let result = callback().await;
            let _ = lock.release().await;
            Ok(result)
        } else {
            self.get(key)
                .await?
                .ok_or_else(|| CacheError::KeyNotFound(key.to_string()))
        }
    }

    /// Convenience: get from the default store.
    pub async fn get(&self, key: &str) -> Result<Option<String>, CacheError> {
        self.default_store()?.get(key).await
    }

    /// Convenience: set on the default store.
    pub async fn set(
        &self,
        key: &str,
        value: &str,
        ttl_seconds: Option<u64>,
    ) -> Result<(), CacheError> {
        self.default_store()?.set(key, value, ttl_seconds).await
    }

    /// Convenience: forever on the default store.
    pub async fn forever(&self, key: &str, value: &str) -> Result<(), CacheError> {
        self.default_store()?.forever(key, value).await
    }

    /// Convenience: delete from the default store.
    pub async fn delete(&self, key: &str) -> Result<bool, CacheError> {
        self.default_store()?.delete(key).await
    }

    /// Convenience: has on the default store.
    pub async fn has(&self, key: &str) -> Result<bool, CacheError> {
        self.default_store()?.has(key).await
    }

    /// Convenience: clear the default store.
    pub async fn clear(&self) -> Result<(), CacheError> {
        self.default_store()?.clear().await
    }

    /// Convenience: pull from the default store.
    pub async fn pull(&self, key: &str) -> Result<Option<String>, CacheError> {
        self.default_store()?.pull(key).await
    }

    /// Convenience: increment on the default store.
    pub async fn increment(&self, key: &str, by: i64) -> Result<i64, CacheError> {
        self.default_store()?.increment(key, by).await
    }

    /// Convenience: decrement on the default store.
    pub async fn decrement(&self, key: &str, by: i64) -> Result<i64, CacheError> {
        self.default_store()?.decrement(key, by).await
    }

    /// Convenience: extend the TTL of a key on the default store.
    pub async fn touch(&self, key: &str, ttl_seconds: u64) -> Result<bool, CacheError> {
        self.default_store()?.touch(key, ttl_seconds).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cache::array::ArrayStore;

    fn setup_manager() -> CacheManager {
        let mut manager = CacheManager::new("array");
        manager.register("array", ArrayStore::new("array"));
        manager
    }

    #[tokio::test]
    async fn test_cache_item_not_expired() {
        let item = CacheItem::new("hello".to_string(), Some(3600));
        assert!(!item.is_expired());
    }

    #[tokio::test]
    async fn test_cache_item_expired() {
        let item = CacheItem {
            value: "hello".to_string(),
            expires_at: Some(Utc::now() - chrono::Duration::seconds(1)),
        };
        assert!(item.is_expired());
    }

    #[tokio::test]
    async fn test_cache_item_no_expiry() {
        let item = CacheItem::new("forever".to_string(), None);
        assert!(!item.is_expired());
    }

    #[tokio::test]
    async fn test_prefixed_key() {
        assert_eq!(prefixed_key("", "key"), "key");
        assert_eq!(prefixed_key("prefix:", "key"), "prefix:key");
    }

    #[tokio::test]
    async fn test_manager_get_set() {
        let manager = setup_manager();
        assert!(manager.get("name").await.unwrap().is_none());

        manager.set("name", "Larastvel", Some(60)).await.unwrap();
        assert_eq!(
            manager.get("name").await.unwrap(),
            Some("Larastvel".to_string())
        );
    }

    #[tokio::test]
    async fn test_manager_has() {
        let manager = setup_manager();
        assert!(!manager.has("key").await.unwrap());
        manager.set("key", "val", Some(60)).await.unwrap();
        assert!(manager.has("key").await.unwrap());
    }

    #[tokio::test]
    async fn test_manager_delete() {
        let manager = setup_manager();
        manager.set("del", "me", Some(60)).await.unwrap();
        assert!(manager.has("del").await.unwrap());
        assert!(manager.delete("del").await.unwrap());
        assert!(!manager.has("del").await.unwrap());
    }

    #[tokio::test]
    async fn test_manager_delete_missing() {
        let manager = setup_manager();
        assert!(!manager.delete("nonexistent").await.unwrap());
    }

    #[tokio::test]
    async fn test_manager_forever() {
        let manager = setup_manager();
        manager.forever("forever", "always").await.unwrap();
        assert_eq!(
            manager.get("forever").await.unwrap(),
            Some("always".to_string())
        );
    }

    #[tokio::test]
    async fn test_manager_pull() {
        let manager = setup_manager();
        manager.set("pull", "me", Some(60)).await.unwrap();
        assert_eq!(manager.pull("pull").await.unwrap(), Some("me".to_string()));
        assert!(!manager.has("pull").await.unwrap());
    }

    #[tokio::test]
    async fn test_manager_clear() {
        let manager = setup_manager();
        manager.set("a", "1", Some(60)).await.unwrap();
        manager.set("b", "2", Some(60)).await.unwrap();
        manager.clear().await.unwrap();
        assert!(!manager.has("a").await.unwrap());
        assert!(!manager.has("b").await.unwrap());
    }

    #[tokio::test]
    async fn test_manager_increment() {
        let manager = setup_manager();
        assert_eq!(manager.increment("counter", 1).await.unwrap(), 1);
        assert_eq!(manager.increment("counter", 5).await.unwrap(), 6);
    }

    #[tokio::test]
    async fn test_manager_decrement() {
        let manager = setup_manager();
        manager.set("count", "10", None).await.unwrap();
        assert_eq!(manager.decrement("count", 3).await.unwrap(), 7);
    }

    #[tokio::test]
    async fn test_manager_store_not_configured() {
        let manager = CacheManager::new("default");
        let result = manager.store("nonexistent");
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_manager_store_names() {
        let mut manager = CacheManager::new("array");
        manager.register("array", ArrayStore::new("array"));
        manager.register("file", ArrayStore::new("file"));
        let mut names = manager.store_names();
        names.sort();
        assert_eq!(names, vec!["array", "file"]);
    }

    #[tokio::test]
    async fn test_manager_set_default() {
        let mut manager = CacheManager::new("first");
        manager.register("first", ArrayStore::new("first"));
        manager.register("second", ArrayStore::new("second"));
        manager.set_default("second");
        assert_eq!(manager.default_name(), "second");
    }

    #[tokio::test]
    async fn test_manager_lock_mutual_exclusion() {
        let manager = setup_manager();
        let a = manager.lock("job-lock", Duration::from_secs(30)).unwrap();
        assert!(a.get().await.unwrap());
        assert!(!manager
            .lock("job-lock", Duration::from_secs(30))
            .unwrap()
            .get()
            .await
            .unwrap());
        assert!(a.release().await.unwrap());
        assert!(manager
            .lock("job-lock", Duration::from_secs(30))
            .unwrap()
            .get()
            .await
            .unwrap());
    }

    #[tokio::test]
    async fn test_manager_lock_unlock_returns_none() {
        let manager = setup_manager();
        assert!(manager.lock("no-key", Duration::from_secs(1)).is_ok());
    }

    #[tokio::test]
    async fn test_manager_lock_times_out() {
        let manager = setup_manager();
        let a = manager.lock("busy", Duration::from_secs(30)).unwrap();
        a.get().await.unwrap();
        assert!(!manager
            .lock("busy", Duration::from_secs(1))
            .unwrap()
            .block(Duration::from_millis(300))
            .await
            .unwrap());
    }

    #[tokio::test]
    async fn test_manager_with_lock_runs_callback_once() {
        let manager = setup_manager();
        let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));

        let result = manager
            .with_lock(
                "with-lock",
                Duration::from_secs(30),
                Duration::from_secs(2),
                || async {
                    calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    "done".to_string()
                },
            )
            .await
            .unwrap();
        assert_eq!(result, "done");

        let result = manager
            .with_lock(
                "with-lock",
                Duration::from_secs(30),
                Duration::from_secs(2),
                || async { "again".to_string() },
            )
            .await
            .unwrap();
        assert_eq!(result, "again");
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn test_manager_with_lock_times_out() {
        let manager = setup_manager();
        let a = manager.lock("busy-lock", Duration::from_secs(30)).unwrap();
        a.get().await.unwrap();
        assert!(manager
            .with_lock(
                "busy-lock",
                Duration::from_secs(30),
                Duration::from_millis(200),
                || async { "nope".to_string() },
            )
            .await
            .is_err());
    }

    #[tokio::test]
    async fn test_manager_get_locked() {
        let manager = setup_manager();
        let cache = manager.clone();

        // Free lock: the callback runs, caches its own result, and holds the
        // lock while it works.
        let first = manager.get_locked("expensive", Duration::from_secs(5), || async {
            cache.set("expensive", "value", Some(30)).await.unwrap();
            tokio::time::sleep(Duration::from_millis(100)).await;
            "value".to_string()
        });

        // Held lock: the concurrent call returns the cached value instead of
        // running the callback.
        let second = manager.get_locked("expensive", Duration::from_secs(5), || async {
            "recomputed".to_string()
        });

        let (first, second) = tokio::join!(first, second);
        assert_eq!(first.unwrap(), "value");
        assert_eq!(second.unwrap(), "value");
    }

    #[tokio::test]
    async fn test_cache_error_messages() {
        let err = CacheError::Store("disk full".to_string());
        assert_eq!(err.to_string(), "Store error: disk full");

        let err = CacheError::NotConfigured("redis".to_string());
        assert_eq!(err.to_string(), "Store [redis] not configured");
    }

    #[tokio::test]
    async fn test_remember() {
        let manager = setup_manager();
        let called = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let c = called.clone();

        let result = manager
            .default_store()
            .unwrap()
            .remember(
                "remembered",
                60,
                Box::new(move || {
                    let c = c.clone();
                    Box::pin(async move {
                        c.store(true, std::sync::atomic::Ordering::SeqCst);
                        "computed".to_string()
                    })
                }),
            )
            .await
            .unwrap();

        assert_eq!(result, "computed");
        assert!(called.load(std::sync::atomic::Ordering::SeqCst));

        // Second call should use cache
        let called2 = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let c2 = called2.clone();
        let result2 = manager
            .default_store()
            .unwrap()
            .remember(
                "remembered",
                60,
                Box::new(move || {
                    let c2 = c2.clone();
                    Box::pin(async move {
                        c2.store(true, std::sync::atomic::Ordering::SeqCst);
                        "recomputed".to_string()
                    })
                }),
            )
            .await
            .unwrap();

        assert_eq!(result2, "computed");
        assert!(!called2.load(std::sync::atomic::Ordering::SeqCst));
    }

    #[tokio::test]
    async fn test_many() {
        let manager = setup_manager();
        manager.set("k1", "v1", Some(60)).await.unwrap();
        manager.set("k2", "v2", Some(60)).await.unwrap();

        let results = manager
            .default_store()
            .unwrap()
            .many(&["k1", "k2", "k3"])
            .await
            .unwrap();

        assert_eq!(results.get("k1").unwrap(), &Some("v1".to_string()));
        assert_eq!(results.get("k2").unwrap(), &Some("v2".to_string()));
        assert_eq!(results.get("k3").unwrap(), &None);
    }

    #[tokio::test]
    async fn test_set_many() {
        let manager = setup_manager();
        manager
            .default_store()
            .unwrap()
            .set_many(&[("a", "1"), ("b", "2")], Some(60))
            .await
            .unwrap();

        assert_eq!(manager.get("a").await.unwrap(), Some("1".to_string()));
        assert_eq!(manager.get("b").await.unwrap(), Some("2".to_string()));
    }

    #[tokio::test]
    async fn test_touch_existing_key() {
        let manager = setup_manager();
        manager.set("touched", "value", Some(60)).await.unwrap();

        assert!(manager.touch("touched", 3600).await.unwrap());
        assert_eq!(
            manager.get("touched").await.unwrap(),
            Some("value".to_string())
        );
    }

    #[tokio::test]
    async fn test_touch_missing_key() {
        let manager = setup_manager();
        assert!(!manager.touch("missing", 3600).await.unwrap());
    }

    #[tokio::test]
    async fn test_touch_expired_key_returns_false() {
        let manager = setup_manager();
        manager.set("expired", "value", Some(0)).await.unwrap();
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        assert!(!manager.touch("expired", 3600).await.unwrap());
    }

    #[tokio::test]
    async fn test_touch_preserves_value() {
        let manager = setup_manager();
        manager.set("k", "v", Some(1)).await.unwrap();
        assert!(manager.touch("k", 3600).await.unwrap());
        assert_eq!(manager.get("k").await.unwrap(), Some("v".to_string()));
    }
}