Skip to main content

larastvel_core/cache/
array.rs

1use std::collections::HashMap;
2use std::sync::{Arc, Mutex};
3
4use async_trait::async_trait;
5
6use super::lock::ArrayLockStore;
7use super::{CacheError, CacheItem, CacheStore, LockStore, FOREVER_TTL};
8
9/// In-memory cache store using a `HashMap`. Useful for testing and single-server
10/// use where persistence is not required.
11///
12/// This is the equivalent of Laravel's `array` cache driver.
13#[derive(Debug, Clone)]
14pub struct ArrayStore {
15    name: String,
16    data: Arc<Mutex<HashMap<String, CacheItem>>>,
17    locks: Arc<ArrayLockStore>,
18}
19
20impl ArrayStore {
21    pub fn new(name: &str) -> Self {
22        Self {
23            name: name.to_string(),
24            data: Arc::new(Mutex::new(HashMap::new())),
25            locks: Arc::new(ArrayLockStore::new()),
26        }
27    }
28
29    /// Remove all expired entries.
30    pub fn gc(&self) {
31        let mut data = self.data.lock().unwrap();
32        data.retain(|_, item| !item.is_expired());
33    }
34
35    /// Return the number of items in the store (including expired).
36    pub fn len(&self) -> usize {
37        self.data.lock().unwrap().len()
38    }
39
40    /// Return true if the store is empty.
41    pub fn is_empty(&self) -> bool {
42        self.data.lock().unwrap().is_empty()
43    }
44}
45
46#[async_trait]
47impl CacheStore for ArrayStore {
48    async fn get(&self, key: &str) -> Result<Option<String>, CacheError> {
49        let data = self.data.lock().unwrap();
50        match data.get(key) {
51            Some(item) if !item.is_expired() => Ok(Some(item.value.clone())),
52            _ => Ok(None),
53        }
54    }
55
56    async fn set(
57        &self,
58        key: &str,
59        value: &str,
60        ttl_seconds: Option<u64>,
61    ) -> Result<(), CacheError> {
62        let mut data = self.data.lock().unwrap();
63        data.insert(
64            key.to_string(),
65            CacheItem::new(value.to_string(), ttl_seconds),
66        );
67        Ok(())
68    }
69
70    async fn delete(&self, key: &str) -> Result<bool, CacheError> {
71        let mut data = self.data.lock().unwrap();
72        Ok(data.remove(key).is_some())
73    }
74
75    async fn clear(&self) -> Result<(), CacheError> {
76        let mut data = self.data.lock().unwrap();
77        data.clear();
78        Ok(())
79    }
80
81    async fn increment(&self, key: &str, by: i64) -> Result<i64, CacheError> {
82        let mut data = self.data.lock().unwrap();
83        let current = data
84            .get(key)
85            .filter(|item| !item.is_expired())
86            .and_then(|item| item.value.parse::<i64>().ok())
87            .unwrap_or(0);
88        let new = current + by;
89        data.insert(
90            key.to_string(),
91            CacheItem::new(new.to_string(), Some(FOREVER_TTL)),
92        );
93        Ok(new)
94    }
95
96    fn name(&self) -> &str {
97        &self.name
98    }
99
100    fn as_lock_store(&self) -> Option<Arc<dyn LockStore>> {
101        Some(self.locks.clone())
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    #[tokio::test]
110    async fn test_array_store_get_set() {
111        let store = ArrayStore::new("array");
112        assert!(store.get("key").await.unwrap().is_none());
113
114        store.set("key", "value", Some(60)).await.unwrap();
115        assert_eq!(store.get("key").await.unwrap(), Some("value".to_string()));
116    }
117
118    #[tokio::test]
119    async fn test_array_store_overwrite() {
120        let store = ArrayStore::new("array");
121        store.set("key", "old", Some(60)).await.unwrap();
122        store.set("key", "new", Some(60)).await.unwrap();
123        assert_eq!(store.get("key").await.unwrap(), Some("new".to_string()));
124    }
125
126    #[tokio::test]
127    async fn test_array_store_delete() {
128        let store = ArrayStore::new("array");
129        store.set("key", "val", Some(60)).await.unwrap();
130        assert!(store.delete("key").await.unwrap());
131        assert!(!store.delete("key").await.unwrap());
132    }
133
134    #[tokio::test]
135    async fn test_array_store_has() {
136        let store = ArrayStore::new("array");
137        assert!(!store.has("key").await.unwrap());
138        store.set("key", "val", Some(60)).await.unwrap();
139        assert!(store.has("key").await.unwrap());
140    }
141
142    #[tokio::test]
143    async fn test_array_store_clear() {
144        let store = ArrayStore::new("array");
145        store.set("a", "1", Some(60)).await.unwrap();
146        store.set("b", "2", Some(60)).await.unwrap();
147        store.clear().await.unwrap();
148        assert!(!store.has("a").await.unwrap());
149        assert!(!store.has("b").await.unwrap());
150    }
151
152    #[tokio::test]
153    async fn test_array_store_pull() {
154        let store = ArrayStore::new("array");
155        store.set("key", "val", Some(60)).await.unwrap();
156        assert_eq!(store.pull("key").await.unwrap(), Some("val".to_string()));
157        assert!(!store.has("key").await.unwrap());
158    }
159
160    #[tokio::test]
161    async fn test_array_store_increment() {
162        let store = ArrayStore::new("array");
163        assert_eq!(store.increment("counter", 1).await.unwrap(), 1);
164        assert_eq!(store.increment("counter", 5).await.unwrap(), 6);
165        assert_eq!(store.increment("counter", -2).await.unwrap(), 4);
166    }
167
168    #[tokio::test]
169    async fn test_array_store_decrement() {
170        let store = ArrayStore::new("array");
171        store.set("count", "10", None).await.unwrap();
172        assert_eq!(store.decrement("count", 3).await.unwrap(), 7);
173    }
174
175    #[tokio::test]
176    async fn test_array_store_forever() {
177        let store = ArrayStore::new("array");
178        store.forever("key", "always").await.unwrap();
179        assert_eq!(store.get("key").await.unwrap(), Some("always".to_string()));
180    }
181
182    #[tokio::test]
183    async fn test_array_store_many() {
184        let store = ArrayStore::new("array");
185        store.set("a", "1", Some(60)).await.unwrap();
186        store.set("b", "2", Some(60)).await.unwrap();
187
188        let results = store.many(&["a", "b", "c"]).await.unwrap();
189        assert_eq!(results.get("a").unwrap(), &Some("1".to_string()));
190        assert_eq!(results.get("b").unwrap(), &Some("2".to_string()));
191        assert_eq!(results.get("c").unwrap(), &None);
192    }
193
194    #[tokio::test]
195    async fn test_array_store_set_many() {
196        let store = ArrayStore::new("array");
197        store
198            .set_many(&[("x", "10"), ("y", "20")], Some(60))
199            .await
200            .unwrap();
201        assert_eq!(store.get("x").await.unwrap(), Some("10".to_string()));
202        assert_eq!(store.get("y").await.unwrap(), Some("20".to_string()));
203    }
204
205    #[tokio::test]
206    async fn test_array_store_remember() {
207        let store = ArrayStore::new("array");
208        let result = store
209            .remember(
210                "computed",
211                60,
212                Box::new(|| Box::pin(async { "expensive".to_string() })),
213            )
214            .await
215            .unwrap();
216        assert_eq!(result, "expensive");
217        assert_eq!(
218            store.get("computed").await.unwrap(),
219            Some("expensive".to_string())
220        );
221    }
222
223    #[tokio::test]
224    async fn test_array_store_name() {
225        let store = ArrayStore::new("my-cache");
226        assert_eq!(store.name(), "my-cache");
227    }
228
229    #[tokio::test]
230    async fn test_array_store_gc() {
231        let store = ArrayStore::new("array");
232        store.set("fresh", "ok", Some(60)).await.unwrap();
233        store.set("stale", "gone", Some(0)).await.unwrap();
234        // Wait a tiny bit for the 0-second TTL to expire
235        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
236        store.gc();
237        assert!(store.has("fresh").await.unwrap());
238        assert!(!store.has("stale").await.unwrap());
239    }
240
241    #[tokio::test]
242    async fn test_array_store_len() {
243        let store = ArrayStore::new("array");
244        assert_eq!(store.len(), 0);
245        store.set("a", "1", Some(60)).await.unwrap();
246        assert_eq!(store.len(), 1);
247    }
248}