1use async_trait::async_trait;
2use std::sync::Arc;
3use std::time::Duration;
4
5use super::{prefixed_key, CacheError, CacheStore, LockStore};
6
7const RELEASE_LUA: &str = r#"
9if redis.call('get', KEYS[1]) == ARGV[1] then
10 return redis.call('del', KEYS[1])
11end
12return 0
13"#;
14
15const REFRESH_LUA: &str = r#"
17if redis.call('get', KEYS[1]) == ARGV[1] then
18 return redis.call('pexpire', KEYS[1], ARGV[2])
19end
20return 0
21"#;
22
23#[derive(Debug, Clone)]
28pub struct RedisStore {
29 name: String,
30 client: redis::Client,
31 prefix: String,
32}
33
34impl RedisStore {
35 pub fn new(name: &str, url: &str, prefix: &str) -> Result<Self, CacheError> {
41 let client = redis::Client::open(url)
42 .map_err(|e| CacheError::Store(format!("Invalid Redis URL: {}", e)))?;
43 Ok(Self {
44 name: name.to_string(),
45 client,
46 prefix: prefix.to_string(),
47 })
48 }
49
50 fn key(&self, key: &str) -> String {
51 prefixed_key(&self.prefix, key)
52 }
53
54 async fn connection(&self) -> Result<redis::aio::MultiplexedConnection, CacheError> {
55 self.client
56 .get_multiplexed_async_connection()
57 .await
58 .map_err(|e| CacheError::Store(format!("Redis connection error: {}", e)))
59 }
60}
61
62#[async_trait]
63impl CacheStore for RedisStore {
64 async fn get(&self, key: &str) -> Result<Option<String>, CacheError> {
65 let mut conn = self.connection().await?;
66 let value: Option<String> = redis::cmd("GET")
67 .arg(self.key(key))
68 .query_async(&mut conn)
69 .await
70 .map_err(|e| CacheError::Store(format!("Redis GET failed: {}", e)))?;
71 Ok(value)
72 }
73
74 async fn set(
75 &self,
76 key: &str,
77 value: &str,
78 ttl_seconds: Option<u64>,
79 ) -> Result<(), CacheError> {
80 let mut conn = self.connection().await?;
81 let mut cmd = redis::cmd("SET");
82 cmd.arg(self.key(key)).arg(value);
83 if let Some(ttl) = ttl_seconds {
84 cmd.arg("EX").arg(ttl);
85 }
86 cmd.query_async::<()>(&mut conn)
87 .await
88 .map_err(|e| CacheError::Store(format!("Redis SET failed: {}", e)))?;
89 Ok(())
90 }
91
92 async fn delete(&self, key: &str) -> Result<bool, CacheError> {
93 let mut conn = self.connection().await?;
94 let removed: i64 = redis::cmd("DEL")
95 .arg(self.key(key))
96 .query_async(&mut conn)
97 .await
98 .map_err(|e| CacheError::Store(format!("Redis DEL failed: {}", e)))?;
99 Ok(removed > 0)
100 }
101
102 async fn clear(&self) -> Result<(), CacheError> {
103 let mut conn = self.connection().await?;
104 let pattern = format!("{}*", self.prefix);
106 let mut cursor = 0u64;
107 loop {
108 let (next, keys): (u64, Vec<String>) = redis::cmd("SCAN")
109 .arg(cursor)
110 .arg("MATCH")
111 .arg(&pattern)
112 .arg("COUNT")
113 .arg(100)
114 .query_async(&mut conn)
115 .await
116 .map_err(|e| CacheError::Store(format!("Redis SCAN failed: {}", e)))?;
117 if !keys.is_empty() {
118 let mut del = redis::cmd("DEL");
119 for k in &keys {
120 del.arg(k);
121 }
122 let _: i64 = del
123 .query_async(&mut conn)
124 .await
125 .map_err(|e| CacheError::Store(format!("Redis DEL failed: {}", e)))?;
126 }
127 if next == 0 {
128 break;
129 }
130 cursor = next;
131 }
132 Ok(())
133 }
134
135 async fn increment(&self, key: &str, by: i64) -> Result<i64, CacheError> {
136 let mut conn = self.connection().await?;
137 let value: i64 = redis::cmd("INCRBY")
138 .arg(self.key(key))
139 .arg(by)
140 .query_async(&mut conn)
141 .await
142 .map_err(|e| CacheError::Store(format!("Redis INCRBY failed: {}", e)))?;
143 Ok(value)
144 }
145
146 async fn touch(&self, key: &str, ttl_seconds: u64) -> Result<bool, CacheError> {
147 let mut conn = self.connection().await?;
148 let touched: i64 = redis::cmd("EXPIRE")
149 .arg(self.key(key))
150 .arg(ttl_seconds)
151 .query_async(&mut conn)
152 .await
153 .map_err(|e| CacheError::Store(format!("Redis EXPIRE failed: {}", e)))?;
154 Ok(touched > 0)
155 }
156
157 fn name(&self) -> &str {
158 &self.name
159 }
160
161 fn as_lock_store(&self) -> Option<Arc<dyn LockStore>> {
162 Some(Arc::new(self.clone()))
163 }
164}
165
166#[async_trait]
167impl LockStore for RedisStore {
168 async fn acquire(&self, key: &str, owner: &str, ttl: Duration) -> Result<bool, CacheError> {
169 let mut conn = self.connection().await?;
170 let acquired: bool = redis::cmd("SET")
171 .arg(self.key(key))
172 .arg(owner)
173 .arg("NX")
174 .arg("PX")
175 .arg(ttl.as_millis() as u64)
176 .query_async(&mut conn)
177 .await
178 .map_err(|e| CacheError::Store(format!("Redis SET NX failed: {}", e)))?;
179 Ok(acquired)
180 }
181
182 async fn release(&self, key: &str, owner: &str) -> Result<bool, CacheError> {
183 let mut conn = self.connection().await?;
184 let released: i64 = redis::cmd("EVAL")
185 .arg(RELEASE_LUA)
186 .arg(1)
187 .arg(self.key(key))
188 .arg(owner)
189 .query_async(&mut conn)
190 .await
191 .map_err(|e| CacheError::Store(format!("Redis lock release failed: {}", e)))?;
192 Ok(released > 0)
193 }
194
195 async fn force_release(&self, key: &str) -> Result<bool, CacheError> {
196 let mut conn = self.connection().await?;
197 let removed: i64 = redis::cmd("DEL")
198 .arg(self.key(key))
199 .query_async(&mut conn)
200 .await
201 .map_err(|e| CacheError::Store(format!("Redis DEL failed: {}", e)))?;
202 Ok(removed > 0)
203 }
204
205 async fn refresh(&self, key: &str, owner: &str, ttl: Duration) -> Result<bool, CacheError> {
206 let mut conn = self.connection().await?;
207 let refreshed: i64 = redis::cmd("EVAL")
208 .arg(REFRESH_LUA)
209 .arg(1)
210 .arg(self.key(key))
211 .arg(owner)
212 .arg(ttl.as_millis() as u64)
213 .query_async(&mut conn)
214 .await
215 .map_err(|e| CacheError::Store(format!("Redis lock refresh failed: {}", e)))?;
216 Ok(refreshed > 0)
217 }
218}
219
220#[cfg(test)]
225mod tests {
226 use super::*;
227 use once_cell::sync::Lazy;
228
229 static REDIS_URL: Lazy<String> = Lazy::new(|| {
230 std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string())
231 });
232
233 fn redis_url() -> &'static str {
234 &REDIS_URL
235 }
236
237 async fn maybe_store() -> Option<RedisStore> {
241 let store = match RedisStore::new("redis", redis_url(), "larastvel_test:") {
242 Ok(s) => s,
243 Err(_) => return None,
244 };
245 let connected =
246 tokio::time::timeout(std::time::Duration::from_millis(300), store.connection()).await;
247 match connected {
248 Ok(Ok(_)) => Some(store),
249 _ => {
250 eprintln!("skipping Redis tests: no server at {}", redis_url());
251 None
252 }
253 }
254 }
255
256 #[tokio::test]
257 async fn test_redis_store_get_set_delete() {
258 let Some(store) = maybe_store().await else {
259 return;
260 };
261 assert!(store.get("key").await.unwrap().is_none());
262 store.set("key", "value", Some(60)).await.unwrap();
263 assert_eq!(store.get("key").await.unwrap(), Some("value".to_string()));
264 assert!(store.delete("key").await.unwrap());
265 assert!(!store.delete("key").await.unwrap());
266 }
267
268 #[tokio::test]
269 async fn test_redis_store_overwrite() {
270 let Some(store) = maybe_store().await else {
271 return;
272 };
273 store.set("key", "old", Some(60)).await.unwrap();
274 store.set("key", "new", Some(60)).await.unwrap();
275 assert_eq!(store.get("key").await.unwrap(), Some("new".to_string()));
276 let _ = store.delete("key").await;
277 }
278
279 #[tokio::test]
280 async fn test_redis_store_ttl_expiry() {
281 let Some(store) = maybe_store().await else {
282 return;
283 };
284 store.set("temp", "gone", Some(1)).await.unwrap();
285 assert!(store.has("temp").await.unwrap());
286 tokio::time::sleep(std::time::Duration::from_millis(1100)).await;
287 assert!(!store.has("temp").await.unwrap());
288 }
289
290 #[tokio::test]
291 async fn test_redis_store_forever_has_no_ttl() {
292 let Some(store) = maybe_store().await else {
293 return;
294 };
295 store.forever("perm", "always").await.unwrap();
296 assert_eq!(store.get("perm").await.unwrap(), Some("always".to_string()));
297 let _ = store.delete("perm").await;
298 }
299
300 #[tokio::test]
301 async fn test_redis_store_clear_only_prefixed() {
302 let Some(store) = maybe_store().await else {
303 return;
304 };
305 let other = RedisStore::new("redis", redis_url(), "other:").unwrap();
307 other.set("keep", "safe", Some(60)).await.unwrap();
308 store.set("a", "1", Some(60)).await.unwrap();
309 store.set("b", "2", Some(60)).await.unwrap();
310 store.clear().await.unwrap();
311 assert!(!store.has("a").await.unwrap());
312 assert!(!store.has("b").await.unwrap());
313 assert!(other.has("keep").await.unwrap());
314 let _ = other.delete("keep").await;
315 }
316
317 #[tokio::test]
318 async fn test_redis_store_increment_decrement() {
319 let Some(store) = maybe_store().await else {
320 return;
321 };
322 assert_eq!(store.increment("counter", 1).await.unwrap(), 1);
323 assert_eq!(store.increment("counter", 5).await.unwrap(), 6);
324 assert_eq!(store.decrement("counter", 2).await.unwrap(), 4);
325 let _ = store.delete("counter").await;
326 }
327
328 #[tokio::test]
329 async fn test_redis_store_pull_and_many() {
330 let Some(store) = maybe_store().await else {
331 return;
332 };
333 store.set("p", "val", Some(60)).await.unwrap();
334 assert_eq!(store.pull("p").await.unwrap(), Some("val".to_string()));
335 assert!(!store.has("p").await.unwrap());
336
337 store.set("a", "1", Some(60)).await.unwrap();
338 store.set("b", "2", Some(60)).await.unwrap();
339 let results = store.many(&["a", "b", "c"]).await.unwrap();
340 assert_eq!(results.get("a").unwrap(), &Some("1".to_string()));
341 assert_eq!(results.get("c").unwrap(), &None);
342 let _ = store.delete("a").await;
343 let _ = store.delete("b").await;
344 }
345
346 #[tokio::test]
347 async fn test_redis_store_remember() {
348 let Some(store) = maybe_store().await else {
349 return;
350 };
351 let result = store
352 .remember(
353 "computed",
354 60,
355 Box::new(|| Box::pin(async { "expensive".to_string() })),
356 )
357 .await
358 .unwrap();
359 assert_eq!(result, "expensive");
360 assert_eq!(
361 store.get("computed").await.unwrap(),
362 Some("expensive".to_string())
363 );
364 let _ = store.delete("computed").await;
365 }
366
367 #[tokio::test]
368 async fn test_redis_store_touch() {
369 let Some(store) = maybe_store().await else {
370 return;
371 };
372 assert!(!store.touch("missing", 60).await.unwrap());
373 store.set("t", "v", Some(60)).await.unwrap();
374 assert!(store.touch("t", 120).await.unwrap());
375 assert_eq!(store.get("t").await.unwrap(), Some("v".to_string()));
376 let _ = store.delete("t").await;
377 }
378
379 #[tokio::test]
380 async fn test_redis_store_name_and_bad_url() {
381 let Some(store) = maybe_store().await else {
382 return;
383 };
384 assert_eq!(store.name(), "redis");
385 assert!(RedisStore::new("redis", "not-a-url", "").is_err());
386 }
387
388 #[tokio::test]
389 async fn test_redis_locks() {
390 let Some(store) = maybe_store().await else {
391 return;
392 };
393 let lock_store = store.as_lock_store().unwrap();
394 let owner_a = "owner-a";
395 let owner_b = "owner-b";
396
397 assert!(lock_store
398 .acquire("lock1", owner_a, Duration::from_secs(60))
399 .await
400 .unwrap());
401 assert!(!lock_store
403 .acquire("lock1", owner_b, Duration::from_secs(60))
404 .await
405 .unwrap());
406 assert!(!lock_store.release("lock1", owner_b).await.unwrap());
407 assert!(lock_store.release("lock1", owner_a).await.unwrap());
408 assert!(lock_store
409 .acquire("lock1", owner_b, Duration::from_secs(60))
410 .await
411 .unwrap());
412
413 assert!(lock_store
415 .refresh("lock1", owner_b, Duration::from_secs(120))
416 .await
417 .unwrap());
418 assert!(!lock_store
419 .refresh("lock1", owner_a, Duration::from_secs(120))
420 .await
421 .unwrap());
422
423 assert!(lock_store.force_release("lock1").await.unwrap());
425 assert!(!lock_store.force_release("lock1").await.unwrap());
426
427 assert!(lock_store
429 .acquire("short", owner_a, Duration::from_millis(100))
430 .await
431 .unwrap());
432 tokio::time::sleep(Duration::from_millis(300)).await;
433 assert!(lock_store
434 .acquire("short", owner_b, Duration::from_secs(60))
435 .await
436 .unwrap());
437 let _ = lock_store.force_release("short").await;
438 }
439}