Skip to main content

esh_cache/
redis_cache.rs

1//! Redis cache backend (feature `redis-cache`).
2
3use async_trait::async_trait;
4use esh_core::{Cache, CacheKey, ConfigValue, Error, Result};
5use redis::aio::ConnectionManager;
6use redis::AsyncCommands;
7use std::time::Duration;
8
9/// Redis-backed cache.
10pub struct RedisCache {
11    conn: ConnectionManager,
12    key_prefix: String,
13}
14
15impl RedisCache {
16    /// Connect using a redis URL (`redis://...`).
17    pub async fn connect(url: &str) -> Result<Self> {
18        let client = redis::Client::open(url).map_err(|e| Error::Cache(e.to_string()))?;
19        let conn = ConnectionManager::new(client)
20            .await
21            .map_err(|e| Error::Cache(e.to_string()))?;
22        Ok(Self {
23            conn,
24            key_prefix: "esh:".into(),
25        })
26    }
27
28    /// Set key prefix.
29    #[must_use]
30    pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
31        self.key_prefix = prefix.into();
32        self
33    }
34
35    fn redis_key(&self, key: &CacheKey) -> String {
36        match &key.namespace {
37            Some(ns) => format!("{}{ns}:{}", self.key_prefix, key.key),
38            None => format!("{}{}", self.key_prefix, key.key),
39        }
40    }
41}
42
43#[async_trait]
44impl Cache for RedisCache {
45    async fn get(&self, key: &CacheKey) -> Result<Option<ConfigValue>> {
46        let mut conn = self.conn.clone();
47        let rk = self.redis_key(key);
48        let raw: Option<String> = conn
49            .get(rk)
50            .await
51            .map_err(|e| Error::Cache(e.to_string()))?;
52        match raw {
53            Some(s) => {
54                let v: ConfigValue =
55                    serde_json::from_str(&s).map_err(|e| Error::Cache(e.to_string()))?;
56                Ok(Some(v))
57            }
58            None => Ok(None),
59        }
60    }
61
62    async fn put(&self, key: &CacheKey, value: ConfigValue, ttl: Duration) -> Result<()> {
63        let mut conn = self.conn.clone();
64        let rk = self.redis_key(key);
65        let raw = serde_json::to_string(&value).map_err(|e| Error::Cache(e.to_string()))?;
66        let secs = ttl.as_secs().max(1);
67        conn.set_ex::<_, _, ()>(rk, raw, secs)
68            .await
69            .map_err(|e| Error::Cache(e.to_string()))?;
70        Ok(())
71    }
72
73    async fn invalidate(&self, key: &CacheKey) -> Result<()> {
74        let mut conn = self.conn.clone();
75        let rk = self.redis_key(key);
76        let _: () = conn.del(rk).await.map_err(|e| Error::Cache(e.to_string()))?;
77        Ok(())
78    }
79
80    async fn clear(&self) -> Result<()> {
81        Err(Error::Cache(
82            "RedisCache::clear is intentionally unsupported; delete by prefix externally".into(),
83        ))
84    }
85}