Skip to main content

hyperinfer_client/
cache.rs

1//! Redis-backed exact-match response cache.
2//!
3//! The cache key is a SHA-256 hash of the canonical JSON serialization of the
4//! [`ChatRequest`].  Because the request struct derives [`Serialize`], the
5//! hash is deterministic for identical requests regardless of field insertion
6//! order (serde always serialises struct fields in declaration order).
7//!
8//! Cache entries expire after [`DEFAULT_TTL_SECS`] seconds; callers can
9//! override this via [`ExactMatchCache::with_ttl`].
10//!
11//! The cache gracefully degrades: if Redis is unavailable all `get`/`set`
12//! calls return `None`/`Ok(())` without surfacing errors to the caller.
13
14use hyperinfer_core::{ChatRequest, ChatResponse};
15use redis::{aio::ConnectionManager, AsyncCommands};
16use sha2::{Digest, Sha256};
17use tracing::{debug, warn};
18
19/// Default TTL for cached responses (5 minutes).
20pub const DEFAULT_TTL_SECS: u64 = 300;
21
22/// Exact-match Redis cache for [`ChatResponse`] values.
23#[derive(Clone)]
24pub struct ExactMatchCache {
25    conn: Option<ConnectionManager>,
26    ttl_secs: u64,
27    /// Namespace for cache keys to avoid cross-client collisions.
28    namespace: String,
29}
30
31impl ExactMatchCache {
32    /// Construct a disabled cache that never connects to Redis.
33    pub fn disabled(namespace: &str) -> Self {
34        Self {
35            conn: None,
36            ttl_secs: DEFAULT_TTL_SECS,
37            namespace: namespace.to_string(),
38        }
39    }
40
41    /// Connect to Redis at `redis_url`.  On failure the cache is disabled and
42    /// all operations become no-ops.
43    pub async fn new(redis_url: &str, namespace: &str) -> Self {
44        match redis::Client::open(redis_url) {
45            Ok(client) => match ConnectionManager::new(client).await {
46                Ok(mgr) => {
47                    debug!("ExactMatchCache: connected to Redis");
48                    Self {
49                        conn: Some(mgr),
50                        ttl_secs: DEFAULT_TTL_SECS,
51                        namespace: namespace.to_string(),
52                    }
53                }
54                Err(e) => {
55                    warn!(
56                        "ExactMatchCache: Redis connection failed: {}; cache disabled",
57                        e
58                    );
59                    Self {
60                        conn: None,
61                        ttl_secs: DEFAULT_TTL_SECS,
62                        namespace: namespace.to_string(),
63                    }
64                }
65            },
66            Err(e) => {
67                warn!("ExactMatchCache: invalid Redis URL: {}; cache disabled", e);
68                Self {
69                    conn: None,
70                    ttl_secs: DEFAULT_TTL_SECS,
71                    namespace: namespace.to_string(),
72                }
73            }
74        }
75    }
76
77    /// Create an ExactMatchCache from an existing ConnectionManager.
78    /// This allows sharing a single Redis connection across subsystems.
79    pub fn from_connection_manager(manager: ConnectionManager, namespace: &str) -> Self {
80        debug!("ExactMatchCache: using shared Redis connection");
81        Self {
82            conn: Some(manager),
83            ttl_secs: DEFAULT_TTL_SECS,
84            namespace: namespace.to_string(),
85        }
86    }
87
88    /// Override the cache TTL.  Returns `self` for chaining.
89    pub fn with_ttl(mut self, secs: u64) -> Self {
90        self.ttl_secs = secs;
91        self
92    }
93
94    /// Compute the cache key for `request`.
95    pub fn cache_key(&self, request: &ChatRequest) -> Option<String> {
96        // Clone and normalize to ignore streaming preference
97        let mut normalized_request = request.clone();
98        normalized_request.stream = None;
99
100        match serde_json::to_string(&normalized_request) {
101            Ok(json) => {
102                let mut hasher = Sha256::new();
103                hasher.update(json.as_bytes());
104                let hash = hex::encode(hasher.finalize());
105                Some(format!("hyperinfer:cache:{}:{}", self.namespace, hash))
106            }
107            Err(e) => {
108                warn!("Cache key serialisation error: {}", e);
109                None
110            }
111        }
112    }
113
114    /// Attempt to retrieve a cached [`ChatResponse`] for `request`.
115    ///
116    /// Returns `None` on cache miss, Redis error, or deserialisation failure.
117    pub async fn get(&self, request: &ChatRequest) -> Option<ChatResponse> {
118        let conn = self.conn.as_ref()?;
119        let key = self.cache_key(request)?;
120
121        // Clone the ConnectionManager for this operation (it's cheap and lock-free).
122        let mut conn = conn.clone();
123        let raw: Option<String> = conn.get(&key).await.ok()?;
124
125        let raw = raw?;
126        match serde_json::from_str::<ChatResponse>(&raw) {
127            Ok(resp) => {
128                debug!("Cache HIT for key {}", key);
129                Some(resp)
130            }
131            Err(e) => {
132                warn!("Cache deserialisation error: {}", e);
133                None
134            }
135        }
136    }
137
138    /// Store `response` in the cache under the key derived from `request`.
139    ///
140    /// Silently ignores serialisation and Redis errors.
141    pub async fn set(&self, request: &ChatRequest, response: &ChatResponse) {
142        let conn = match self.conn.as_ref() {
143            Some(c) => c,
144            None => return,
145        };
146
147        let key = match self.cache_key(request) {
148            Some(k) => k,
149            None => return,
150        };
151        let raw = match serde_json::to_string(response) {
152            Ok(s) => s,
153            Err(e) => {
154                warn!("Cache serialisation error: {}", e);
155                return;
156            }
157        };
158
159        // Clone the ConnectionManager for this operation (it's cheap and lock-free).
160        let mut conn = conn.clone();
161        let result: redis::RedisResult<()> = conn.set_ex(&key, &raw, self.ttl_secs).await;
162
163        if let Err(e) = result {
164            warn!("Cache write error: {}", e);
165        } else {
166            debug!("Cache SET key {} ttl={}s", key, self.ttl_secs);
167        }
168    }
169}
170
171// ── Tests ─────────────────────────────────────────────────────────────────────
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use hyperinfer_core::{
177        types::{ChatMessage, Choice, Usage},
178        ChatRequest, ChatResponse,
179    };
180
181    fn sample_request(model: &str) -> ChatRequest {
182        ChatRequest {
183            model: model.to_string(),
184            messages: vec![ChatMessage::user("hello")],
185            max_tokens: Some(100),
186            temperature: None,
187            stream: None,
188            stop: None,
189            tools: None,
190            tool_choice: None,
191            response_format: None,
192        }
193    }
194
195    fn sample_response() -> ChatResponse {
196        ChatResponse {
197            id: "resp-test".to_string(),
198            model: model_unused(),
199            choices: vec![Choice {
200                message: ChatMessage::assistant("Hi there!"),
201                finish_reason: Some("stop".to_string()),
202                index: 0,
203            }],
204            usage: Usage {
205                input_tokens: 5,
206                output_tokens: 10,
207            },
208        }
209    }
210
211    fn model_unused() -> String {
212        "gpt-4".to_string()
213    }
214
215    #[test]
216    fn test_cache_key_deterministic() {
217        let req = sample_request("gpt-4");
218        let cache = ExactMatchCache {
219            conn: None,
220            ttl_secs: DEFAULT_TTL_SECS,
221            namespace: "test-ns".to_string(),
222        };
223        let k1 = cache.cache_key(&req);
224        let k2 = cache.cache_key(&req);
225        assert_eq!(k1, k2);
226        assert!(k1.unwrap().starts_with("hyperinfer:cache:test-ns:"));
227    }
228
229    #[test]
230    fn test_cache_key_different_models() {
231        let cache = ExactMatchCache {
232            conn: None,
233            ttl_secs: DEFAULT_TTL_SECS,
234            namespace: "test-ns".to_string(),
235        };
236        let k1 = cache.cache_key(&sample_request("gpt-4"));
237        let k2 = cache.cache_key(&sample_request("claude-3"));
238        assert_ne!(k1, k2);
239    }
240
241    #[test]
242    fn test_cache_key_different_messages() {
243        let cache = ExactMatchCache {
244            conn: None,
245            ttl_secs: DEFAULT_TTL_SECS,
246            namespace: "test-ns".to_string(),
247        };
248        let mut r1 = sample_request("gpt-4");
249        let mut r2 = sample_request("gpt-4");
250        r1.messages[0].content = "hello".to_string();
251        r2.messages[0].content = "goodbye".to_string();
252        assert_ne!(cache.cache_key(&r1), cache.cache_key(&r2));
253    }
254
255    #[test]
256    fn test_cache_key_ignores_stream() {
257        let cache = ExactMatchCache {
258            conn: None,
259            ttl_secs: DEFAULT_TTL_SECS,
260            namespace: "test-ns".to_string(),
261        };
262        let mut r1 = sample_request("gpt-4");
263        r1.stream = Some(true);
264
265        let mut r2 = sample_request("gpt-4");
266        r2.stream = Some(false);
267
268        let mut r3 = sample_request("gpt-4");
269        r3.stream = None;
270
271        let k1 = cache.cache_key(&r1);
272        let k2 = cache.cache_key(&r2);
273        let k3 = cache.cache_key(&r3);
274
275        assert_eq!(k1, k2);
276        assert_eq!(k2, k3);
277    }
278
279    #[tokio::test]
280    async fn test_cache_disabled_get_returns_none() {
281        // Build a cache with an invalid URL → disabled.
282        let cache = ExactMatchCache::new("redis://invalid-host:1", "test-ns").await;
283        let req = sample_request("gpt-4");
284        let result = cache.get(&req).await;
285        assert!(result.is_none());
286    }
287
288    #[tokio::test]
289    async fn test_cache_disabled_set_no_panic() {
290        let cache = ExactMatchCache::new("redis://invalid-host:1", "test-ns").await;
291        let req = sample_request("gpt-4");
292        let resp = sample_response();
293        // Should not panic.
294        cache.set(&req, &resp).await;
295    }
296
297    #[test]
298    fn test_with_ttl() {
299        // Verify the builder stores the custom TTL.
300        // We can't easily call async new in a sync test, so test the field
301        // directly by constructing a disabled cache inline.
302        let cache = ExactMatchCache {
303            conn: None,
304            ttl_secs: DEFAULT_TTL_SECS,
305            namespace: "test-ns".to_string(),
306        };
307        let cache = cache.with_ttl(60);
308        assert_eq!(cache.ttl_secs, 60);
309    }
310
311    #[tokio::test]
312    async fn test_cache_deserialisation_error() {
313        // We use testcontainers to reliably spin up a redis instance to test this properly,
314        // covering both ExactMatchCache struct's internal `get()` interaction with ConnectionManager
315        // and deserialization match arms seamlessly.
316        use testcontainers::{core::IntoContainerPort, runners::AsyncRunner, GenericImage};
317        use testcontainers_modules::redis::REDIS_PORT;
318
319        let container_result = GenericImage::new("redis", "7.2.4")
320            .with_exposed_port(REDIS_PORT.tcp())
321            .with_wait_for(testcontainers::core::WaitFor::message_on_stdout(
322                "Ready to accept connections",
323            ))
324            .start()
325            .await;
326
327        // In CI some docker socket configurations may fail - fail the test explicitly in CI, skip gracefully locally
328        let container = match container_result {
329            Ok(c) => c,
330            Err(e) => {
331                let is_ci = std::env::var("CI").map(|v| v == "true").unwrap_or(false);
332                if is_ci {
333                    panic!(
334                        "FATAL: testcontainers failed to start Redis in CI environment: {}. \
335                         This indicates a test infrastructure issue that must be resolved.",
336                        e
337                    );
338                } else {
339                    println!(
340                        "Skipping test: testcontainers failed to start Redis ({})",
341                        e
342                    );
343                    return;
344                }
345            }
346        };
347
348        let port = container
349            .get_host_port_ipv4(REDIS_PORT)
350            .await
351            .expect("Failed to get port");
352        let redis_url = format!("redis://127.0.0.1:{}", port);
353
354        let cache = ExactMatchCache::new(&redis_url, "test-ns-malformed").await;
355
356        let req = sample_request("gpt-4");
357        let key = cache.cache_key(&req).unwrap();
358
359        // Directly insert malformed JSON into Redis
360        let client = redis::Client::open(redis_url.as_str()).unwrap();
361        let mut conn = client.get_multiplexed_async_connection().await.unwrap();
362        let _: () = redis::cmd("SET")
363            .arg(&key)
364            .arg("not valid json")
365            .query_async(&mut conn)
366            .await
367            .unwrap();
368
369        // The get should return None and not panic
370        let result = cache.get(&req).await;
371        assert!(
372            result.is_none(),
373            "Deserialization error should result in a cache miss (None)"
374        );
375    }
376}