Skip to main content

larastvel_core/cache/
mod.rs

1pub mod array;
2pub mod database;
3pub mod file;
4pub mod lock;
5pub mod redis;
6
7pub use lock::{ArrayLockStore, Lock, LockStore};
8pub use redis::RedisStore;
9
10use std::collections::HashMap;
11use std::future::Future;
12use std::pin::Pin;
13use std::sync::Arc;
14use std::time::Duration;
15
16use async_trait::async_trait;
17use chrono::{DateTime, Utc};
18use serde::{Deserialize, Serialize};
19
20/// Default TTL of 60 minutes (3600 seconds).
21pub const DEFAULT_TTL_SECONDS: u64 = 3600;
22
23/// One year in seconds — used for "forever" cached items.
24pub const FOREVER_TTL: u64 = 31536000;
25
26/// Prefix helper — joins a cache key prefix with a key.
27pub fn prefixed_key(prefix: &str, key: &str) -> String {
28    if prefix.is_empty() {
29        key.to_string()
30    } else {
31        format!("{}{}", prefix, key)
32    }
33}
34
35#[derive(Debug, thiserror::Error)]
36pub enum CacheError {
37    #[error("IO error: {0}")]
38    Io(#[from] std::io::Error),
39    #[error("Serialization error: {0}")]
40    Serialization(String),
41    #[error("Deserialization error: {0}")]
42    Deserialization(String),
43    #[error("Key not found: {0}")]
44    KeyNotFound(String),
45    #[error("Store error: {0}")]
46    Store(String),
47    #[error("Store [{0}] not configured")]
48    NotConfigured(String),
49}
50
51/// A single cache entry with its expiry.
52#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct CacheItem {
54    pub value: String,
55    pub expires_at: Option<DateTime<Utc>>,
56}
57
58impl CacheItem {
59    pub fn new(value: String, ttl_seconds: Option<u64>) -> Self {
60        let expires_at =
61            ttl_seconds.map(|secs| Utc::now() + chrono::Duration::seconds(secs as i64));
62        Self { value, expires_at }
63    }
64
65    pub fn is_expired(&self) -> bool {
66        match self.expires_at {
67            Some(expiry) => Utc::now() > expiry,
68            None => false,
69        }
70    }
71}
72
73/// Trait for cache store implementations.
74#[async_trait]
75pub trait CacheStore: Send + Sync + std::fmt::Debug {
76    /// Retrieve a value by key. Returns `None` if missing or expired.
77    async fn get(&self, key: &str) -> Result<Option<String>, CacheError>;
78
79    /// Store a value with an optional TTL in seconds.
80    async fn set(&self, key: &str, value: &str, ttl_seconds: Option<u64>)
81        -> Result<(), CacheError>;
82
83    /// Store a value permanently (or for a very long time).
84    async fn forever(&self, key: &str, value: &str) -> Result<(), CacheError> {
85        self.set(key, value, Some(FOREVER_TTL)).await
86    }
87
88    /// Delete a key. Returns `true` if the key existed.
89    async fn delete(&self, key: &str) -> Result<bool, CacheError>;
90
91    /// Check if a key exists and is not expired.
92    async fn has(&self, key: &str) -> Result<bool, CacheError> {
93        Ok(self.get(key).await?.is_some())
94    }
95
96    /// Remove all items from the store.
97    async fn clear(&self) -> Result<(), CacheError>;
98
99    /// Get and delete a key atomically.
100    async fn pull(&self, key: &str) -> Result<Option<String>, CacheError> {
101        let value = self.get(key).await?;
102        if value.is_some() {
103            self.delete(key).await?;
104        }
105        Ok(value)
106    }
107
108    /// Increment a numeric value. Returns the new value.
109    async fn increment(&self, key: &str, by: i64) -> Result<i64, CacheError>;
110
111    /// Decrement a numeric value. Returns the new value.
112    async fn decrement(&self, key: &str, by: i64) -> Result<i64, CacheError> {
113        self.increment(key, -by).await
114    }
115
116    /// Extend the TTL of an existing key without re-fetching its value.
117    /// Returns `false` if the key does not exist or is expired.
118    async fn touch(&self, key: &str, ttl_seconds: u64) -> Result<bool, CacheError> {
119        if let Some(value) = self.get(key).await? {
120            self.set(key, &value, Some(ttl_seconds)).await?;
121            Ok(true)
122        } else {
123            Ok(false)
124        }
125    }
126
127    /// Retrieve multiple keys at once.
128    async fn many(&self, keys: &[&str]) -> Result<HashMap<String, Option<String>>, CacheError> {
129        let mut result = HashMap::new();
130        for key in keys {
131            let value = self.get(key).await?;
132            result.insert(key.to_string(), value);
133        }
134        Ok(result)
135    }
136
137    /// Store multiple items at once with the same TTL.
138    async fn set_many(
139        &self,
140        items: &[(&str, &str)],
141        ttl_seconds: Option<u64>,
142    ) -> Result<(), CacheError> {
143        for (key, value) in items {
144            self.set(key, value, ttl_seconds).await?;
145        }
146        Ok(())
147    }
148
149    /// Get or store a value using a boxed callback.
150    async fn remember(
151        &self,
152        key: &str,
153        ttl_seconds: u64,
154        callback: Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = String> + Send>> + Send>,
155    ) -> Result<String, CacheError> {
156        if let Some(value) = self.get(key).await? {
157            return Ok(value);
158        }
159        let value = callback().await;
160        self.set(key, &value, Some(ttl_seconds)).await?;
161        Ok(value)
162    }
163
164    /// Get or store forever using a boxed callback.
165    async fn remember_forever(
166        &self,
167        key: &str,
168        callback: Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = String> + Send>> + Send>,
169    ) -> Result<String, CacheError> {
170        self.remember(key, FOREVER_TTL, callback).await
171    }
172
173    fn name(&self) -> &str;
174
175    /// Return a [`LockStore`] view of this store when it supports atomic
176    /// locks (array, redis). Stores without lock support return `None`.
177    fn as_lock_store(&self) -> Option<Arc<dyn LockStore>> {
178        None
179    }
180}
181
182/// Manager for multiple cache stores.
183#[derive(Debug, Clone)]
184pub struct CacheManager {
185    stores: HashMap<String, Arc<dyn CacheStore>>,
186    default: String,
187}
188
189impl CacheManager {
190    pub fn new(default: &str) -> Self {
191        Self {
192            stores: HashMap::new(),
193            default: default.to_string(),
194        }
195    }
196
197    pub fn register<S: CacheStore + 'static>(&mut self, name: &str, store: S) {
198        self.stores.insert(name.to_string(), Arc::new(store));
199    }
200
201    pub fn store(&self, name: &str) -> Result<Arc<dyn CacheStore>, CacheError> {
202        self.stores
203            .get(name)
204            .cloned()
205            .ok_or_else(|| CacheError::NotConfigured(name.to_string()))
206    }
207
208    pub fn default_store(&self) -> Result<Arc<dyn CacheStore>, CacheError> {
209        self.store(&self.default)
210    }
211
212    pub fn set_default(&mut self, name: &str) {
213        self.default = name.to_string();
214    }
215
216    pub fn default_name(&self) -> &str {
217        &self.default
218    }
219
220    pub fn store_names(&self) -> Vec<String> {
221        self.stores.keys().cloned().collect()
222    }
223
224    /// Create a [`Lock`] on the default store. The store must support locks
225    /// (array or redis); returns [`CacheError::Store`] otherwise.
226    ///
227    /// Mirrors Laravel's `Cache::lock('key', $seconds)`.
228    pub fn lock(&self, key: &str, ttl: Duration) -> Result<Lock, CacheError> {
229        self.store_lock(&self.default, key, ttl)
230    }
231
232    /// Create a [`Lock`] on a named store.
233    pub fn store_lock(&self, name: &str, key: &str, ttl: Duration) -> Result<Lock, CacheError> {
234        let store = self.store(name)?;
235        let lock_store = store
236            .as_lock_store()
237            .ok_or_else(|| CacheError::Store(format!("store '{name}' does not support locks")))?;
238        Ok(Lock::new(lock_store, key, ttl))
239    }
240
241    /// Acquire a lock (blocking up to `wait`), run `callback` while holding
242    /// it, then release. Mirrors Laravel's `Cache::withLock($key, $callback,
243    /// $seconds)`.
244    pub async fn with_lock<F, Fut, T>(
245        &self,
246        key: &str,
247        ttl: Duration,
248        wait: Duration,
249        callback: F,
250    ) -> Result<T, CacheError>
251    where
252        F: FnOnce() -> Fut,
253        Fut: Future<Output = T>,
254    {
255        let lock = self.lock(key, ttl)?;
256        if !lock.block(wait).await? {
257            return Err(CacheError::Store(format!(
258                "timed out waiting for lock '{key}'"
259            )));
260        }
261        let result = callback().await;
262        let _ = lock.release().await;
263        Ok(result)
264    }
265
266    /// When the lock is free, run `callback` while holding it; when another
267    /// process holds the lock, return the previously cached value instead.
268    /// The callback is responsible for storing its own result via the cache
269    /// (Laravel's `Cache::getLocked($key, $callback, $seconds)`).
270    pub async fn get_locked<F, Fut>(
271        &self,
272        key: &str,
273        ttl: Duration,
274        callback: F,
275    ) -> Result<String, CacheError>
276    where
277        F: FnOnce() -> Fut,
278        Fut: Future<Output = String>,
279    {
280        let lock = self.lock(key, ttl)?;
281        if lock.get().await? {
282            let result = callback().await;
283            let _ = lock.release().await;
284            Ok(result)
285        } else {
286            self.get(key)
287                .await?
288                .ok_or_else(|| CacheError::KeyNotFound(key.to_string()))
289        }
290    }
291
292    /// Convenience: get from the default store.
293    pub async fn get(&self, key: &str) -> Result<Option<String>, CacheError> {
294        self.default_store()?.get(key).await
295    }
296
297    /// Convenience: set on the default store.
298    pub async fn set(
299        &self,
300        key: &str,
301        value: &str,
302        ttl_seconds: Option<u64>,
303    ) -> Result<(), CacheError> {
304        self.default_store()?.set(key, value, ttl_seconds).await
305    }
306
307    /// Convenience: forever on the default store.
308    pub async fn forever(&self, key: &str, value: &str) -> Result<(), CacheError> {
309        self.default_store()?.forever(key, value).await
310    }
311
312    /// Convenience: delete from the default store.
313    pub async fn delete(&self, key: &str) -> Result<bool, CacheError> {
314        self.default_store()?.delete(key).await
315    }
316
317    /// Convenience: has on the default store.
318    pub async fn has(&self, key: &str) -> Result<bool, CacheError> {
319        self.default_store()?.has(key).await
320    }
321
322    /// Convenience: clear the default store.
323    pub async fn clear(&self) -> Result<(), CacheError> {
324        self.default_store()?.clear().await
325    }
326
327    /// Convenience: pull from the default store.
328    pub async fn pull(&self, key: &str) -> Result<Option<String>, CacheError> {
329        self.default_store()?.pull(key).await
330    }
331
332    /// Convenience: increment on the default store.
333    pub async fn increment(&self, key: &str, by: i64) -> Result<i64, CacheError> {
334        self.default_store()?.increment(key, by).await
335    }
336
337    /// Convenience: decrement on the default store.
338    pub async fn decrement(&self, key: &str, by: i64) -> Result<i64, CacheError> {
339        self.default_store()?.decrement(key, by).await
340    }
341
342    /// Convenience: extend the TTL of a key on the default store.
343    pub async fn touch(&self, key: &str, ttl_seconds: u64) -> Result<bool, CacheError> {
344        self.default_store()?.touch(key, ttl_seconds).await
345    }
346}
347
348#[cfg(test)]
349mod tests {
350    use super::*;
351    use crate::cache::array::ArrayStore;
352
353    fn setup_manager() -> CacheManager {
354        let mut manager = CacheManager::new("array");
355        manager.register("array", ArrayStore::new("array"));
356        manager
357    }
358
359    #[tokio::test]
360    async fn test_cache_item_not_expired() {
361        let item = CacheItem::new("hello".to_string(), Some(3600));
362        assert!(!item.is_expired());
363    }
364
365    #[tokio::test]
366    async fn test_cache_item_expired() {
367        let item = CacheItem {
368            value: "hello".to_string(),
369            expires_at: Some(Utc::now() - chrono::Duration::seconds(1)),
370        };
371        assert!(item.is_expired());
372    }
373
374    #[tokio::test]
375    async fn test_cache_item_no_expiry() {
376        let item = CacheItem::new("forever".to_string(), None);
377        assert!(!item.is_expired());
378    }
379
380    #[tokio::test]
381    async fn test_prefixed_key() {
382        assert_eq!(prefixed_key("", "key"), "key");
383        assert_eq!(prefixed_key("prefix:", "key"), "prefix:key");
384    }
385
386    #[tokio::test]
387    async fn test_manager_get_set() {
388        let manager = setup_manager();
389        assert!(manager.get("name").await.unwrap().is_none());
390
391        manager.set("name", "Larastvel", Some(60)).await.unwrap();
392        assert_eq!(
393            manager.get("name").await.unwrap(),
394            Some("Larastvel".to_string())
395        );
396    }
397
398    #[tokio::test]
399    async fn test_manager_has() {
400        let manager = setup_manager();
401        assert!(!manager.has("key").await.unwrap());
402        manager.set("key", "val", Some(60)).await.unwrap();
403        assert!(manager.has("key").await.unwrap());
404    }
405
406    #[tokio::test]
407    async fn test_manager_delete() {
408        let manager = setup_manager();
409        manager.set("del", "me", Some(60)).await.unwrap();
410        assert!(manager.has("del").await.unwrap());
411        assert!(manager.delete("del").await.unwrap());
412        assert!(!manager.has("del").await.unwrap());
413    }
414
415    #[tokio::test]
416    async fn test_manager_delete_missing() {
417        let manager = setup_manager();
418        assert!(!manager.delete("nonexistent").await.unwrap());
419    }
420
421    #[tokio::test]
422    async fn test_manager_forever() {
423        let manager = setup_manager();
424        manager.forever("forever", "always").await.unwrap();
425        assert_eq!(
426            manager.get("forever").await.unwrap(),
427            Some("always".to_string())
428        );
429    }
430
431    #[tokio::test]
432    async fn test_manager_pull() {
433        let manager = setup_manager();
434        manager.set("pull", "me", Some(60)).await.unwrap();
435        assert_eq!(manager.pull("pull").await.unwrap(), Some("me".to_string()));
436        assert!(!manager.has("pull").await.unwrap());
437    }
438
439    #[tokio::test]
440    async fn test_manager_clear() {
441        let manager = setup_manager();
442        manager.set("a", "1", Some(60)).await.unwrap();
443        manager.set("b", "2", Some(60)).await.unwrap();
444        manager.clear().await.unwrap();
445        assert!(!manager.has("a").await.unwrap());
446        assert!(!manager.has("b").await.unwrap());
447    }
448
449    #[tokio::test]
450    async fn test_manager_increment() {
451        let manager = setup_manager();
452        assert_eq!(manager.increment("counter", 1).await.unwrap(), 1);
453        assert_eq!(manager.increment("counter", 5).await.unwrap(), 6);
454    }
455
456    #[tokio::test]
457    async fn test_manager_decrement() {
458        let manager = setup_manager();
459        manager.set("count", "10", None).await.unwrap();
460        assert_eq!(manager.decrement("count", 3).await.unwrap(), 7);
461    }
462
463    #[tokio::test]
464    async fn test_manager_store_not_configured() {
465        let manager = CacheManager::new("default");
466        let result = manager.store("nonexistent");
467        assert!(result.is_err());
468    }
469
470    #[tokio::test]
471    async fn test_manager_store_names() {
472        let mut manager = CacheManager::new("array");
473        manager.register("array", ArrayStore::new("array"));
474        manager.register("file", ArrayStore::new("file"));
475        let mut names = manager.store_names();
476        names.sort();
477        assert_eq!(names, vec!["array", "file"]);
478    }
479
480    #[tokio::test]
481    async fn test_manager_set_default() {
482        let mut manager = CacheManager::new("first");
483        manager.register("first", ArrayStore::new("first"));
484        manager.register("second", ArrayStore::new("second"));
485        manager.set_default("second");
486        assert_eq!(manager.default_name(), "second");
487    }
488
489    #[tokio::test]
490    async fn test_manager_lock_mutual_exclusion() {
491        let manager = setup_manager();
492        let a = manager.lock("job-lock", Duration::from_secs(30)).unwrap();
493        assert!(a.get().await.unwrap());
494        assert!(!manager
495            .lock("job-lock", Duration::from_secs(30))
496            .unwrap()
497            .get()
498            .await
499            .unwrap());
500        assert!(a.release().await.unwrap());
501        assert!(manager
502            .lock("job-lock", Duration::from_secs(30))
503            .unwrap()
504            .get()
505            .await
506            .unwrap());
507    }
508
509    #[tokio::test]
510    async fn test_manager_lock_unlock_returns_none() {
511        let manager = setup_manager();
512        assert!(manager.lock("no-key", Duration::from_secs(1)).is_ok());
513    }
514
515    #[tokio::test]
516    async fn test_manager_lock_times_out() {
517        let manager = setup_manager();
518        let a = manager.lock("busy", Duration::from_secs(30)).unwrap();
519        a.get().await.unwrap();
520        assert!(!manager
521            .lock("busy", Duration::from_secs(1))
522            .unwrap()
523            .block(Duration::from_millis(300))
524            .await
525            .unwrap());
526    }
527
528    #[tokio::test]
529    async fn test_manager_with_lock_runs_callback_once() {
530        let manager = setup_manager();
531        let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
532
533        let result = manager
534            .with_lock(
535                "with-lock",
536                Duration::from_secs(30),
537                Duration::from_secs(2),
538                || async {
539                    calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
540                    "done".to_string()
541                },
542            )
543            .await
544            .unwrap();
545        assert_eq!(result, "done");
546
547        let result = manager
548            .with_lock(
549                "with-lock",
550                Duration::from_secs(30),
551                Duration::from_secs(2),
552                || async { "again".to_string() },
553            )
554            .await
555            .unwrap();
556        assert_eq!(result, "again");
557        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
558    }
559
560    #[tokio::test]
561    async fn test_manager_with_lock_times_out() {
562        let manager = setup_manager();
563        let a = manager.lock("busy-lock", Duration::from_secs(30)).unwrap();
564        a.get().await.unwrap();
565        assert!(manager
566            .with_lock(
567                "busy-lock",
568                Duration::from_secs(30),
569                Duration::from_millis(200),
570                || async { "nope".to_string() },
571            )
572            .await
573            .is_err());
574    }
575
576    #[tokio::test]
577    async fn test_manager_get_locked() {
578        let manager = setup_manager();
579        let cache = manager.clone();
580
581        // Free lock: the callback runs, caches its own result, and holds the
582        // lock while it works.
583        let first = manager.get_locked("expensive", Duration::from_secs(5), || async {
584            cache.set("expensive", "value", Some(30)).await.unwrap();
585            tokio::time::sleep(Duration::from_millis(100)).await;
586            "value".to_string()
587        });
588
589        // Held lock: the concurrent call returns the cached value instead of
590        // running the callback.
591        let second = manager.get_locked("expensive", Duration::from_secs(5), || async {
592            "recomputed".to_string()
593        });
594
595        let (first, second) = tokio::join!(first, second);
596        assert_eq!(first.unwrap(), "value");
597        assert_eq!(second.unwrap(), "value");
598    }
599
600    #[tokio::test]
601    async fn test_cache_error_messages() {
602        let err = CacheError::Store("disk full".to_string());
603        assert_eq!(err.to_string(), "Store error: disk full");
604
605        let err = CacheError::NotConfigured("redis".to_string());
606        assert_eq!(err.to_string(), "Store [redis] not configured");
607    }
608
609    #[tokio::test]
610    async fn test_remember() {
611        let manager = setup_manager();
612        let called = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
613        let c = called.clone();
614
615        let result = manager
616            .default_store()
617            .unwrap()
618            .remember(
619                "remembered",
620                60,
621                Box::new(move || {
622                    let c = c.clone();
623                    Box::pin(async move {
624                        c.store(true, std::sync::atomic::Ordering::SeqCst);
625                        "computed".to_string()
626                    })
627                }),
628            )
629            .await
630            .unwrap();
631
632        assert_eq!(result, "computed");
633        assert!(called.load(std::sync::atomic::Ordering::SeqCst));
634
635        // Second call should use cache
636        let called2 = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
637        let c2 = called2.clone();
638        let result2 = manager
639            .default_store()
640            .unwrap()
641            .remember(
642                "remembered",
643                60,
644                Box::new(move || {
645                    let c2 = c2.clone();
646                    Box::pin(async move {
647                        c2.store(true, std::sync::atomic::Ordering::SeqCst);
648                        "recomputed".to_string()
649                    })
650                }),
651            )
652            .await
653            .unwrap();
654
655        assert_eq!(result2, "computed");
656        assert!(!called2.load(std::sync::atomic::Ordering::SeqCst));
657    }
658
659    #[tokio::test]
660    async fn test_many() {
661        let manager = setup_manager();
662        manager.set("k1", "v1", Some(60)).await.unwrap();
663        manager.set("k2", "v2", Some(60)).await.unwrap();
664
665        let results = manager
666            .default_store()
667            .unwrap()
668            .many(&["k1", "k2", "k3"])
669            .await
670            .unwrap();
671
672        assert_eq!(results.get("k1").unwrap(), &Some("v1".to_string()));
673        assert_eq!(results.get("k2").unwrap(), &Some("v2".to_string()));
674        assert_eq!(results.get("k3").unwrap(), &None);
675    }
676
677    #[tokio::test]
678    async fn test_set_many() {
679        let manager = setup_manager();
680        manager
681            .default_store()
682            .unwrap()
683            .set_many(&[("a", "1"), ("b", "2")], Some(60))
684            .await
685            .unwrap();
686
687        assert_eq!(manager.get("a").await.unwrap(), Some("1".to_string()));
688        assert_eq!(manager.get("b").await.unwrap(), Some("2".to_string()));
689    }
690
691    #[tokio::test]
692    async fn test_touch_existing_key() {
693        let manager = setup_manager();
694        manager.set("touched", "value", Some(60)).await.unwrap();
695
696        assert!(manager.touch("touched", 3600).await.unwrap());
697        assert_eq!(
698            manager.get("touched").await.unwrap(),
699            Some("value".to_string())
700        );
701    }
702
703    #[tokio::test]
704    async fn test_touch_missing_key() {
705        let manager = setup_manager();
706        assert!(!manager.touch("missing", 3600).await.unwrap());
707    }
708
709    #[tokio::test]
710    async fn test_touch_expired_key_returns_false() {
711        let manager = setup_manager();
712        manager.set("expired", "value", Some(0)).await.unwrap();
713        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
714        assert!(!manager.touch("expired", 3600).await.unwrap());
715    }
716
717    #[tokio::test]
718    async fn test_touch_preserves_value() {
719        let manager = setup_manager();
720        manager.set("k", "v", Some(1)).await.unwrap();
721        assert!(manager.touch("k", 3600).await.unwrap());
722        assert_eq!(manager.get("k").await.unwrap(), Some("v".to_string()));
723    }
724}