dakera-storage 0.10.1

Storage backends for the Dakera AI memory platform
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! Redis L1.5 distributed cache layer
//!
//! Sits between the Moka L1 in-process cache and the VectorStorage backend.
//! Provides cross-node cache sharing and pub/sub invalidation for HA deployments.

use common::Vector;
use futures_util::StreamExt;
use redis::aio::ConnectionManager;
use redis::AsyncCommands;
use serde::{Deserialize, Serialize};

/// Error type for Redis cache operations
#[derive(Debug)]
pub struct RedisError(pub String);

impl std::fmt::Display for RedisError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Redis error: {}", self.0)
    }
}

impl From<redis::RedisError> for RedisError {
    fn from(e: redis::RedisError) -> Self {
        RedisError(e.to_string())
    }
}

/// Cache invalidation messages for pub/sub
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CacheInvalidation {
    /// Specific vectors in a namespace were changed
    Vectors { namespace: String, ids: Vec<String> },
    /// An entire namespace was invalidated
    Namespace(String),
    /// Full cache invalidation
    All,
}

/// Redis cache statistics
#[derive(Debug, Clone, Default)]
pub struct RedisCacheStats {
    pub connected: bool,
    pub used_memory_bytes: u64,
    pub total_keys: u64,
    pub hits: u64,
    pub misses: u64,
    pub hit_rate: f64,
}

const REDIS_KEY_PREFIX: &str = "buf";
const REDIS_PUBSUB_CHANNEL: &str = "buffer:cache:invalidate";
const DEFAULT_TTL_SECS: u64 = 3600; // 1 hour

/// Redis L1.5 distributed cache
#[derive(Clone)]
pub struct RedisCache {
    conn: ConnectionManager,
    url: String,
    default_ttl_secs: u64,
}

impl RedisCache {
    /// Connect to Redis and create a new cache instance
    pub async fn new(redis_url: &str) -> Result<Self, RedisError> {
        let client = redis::Client::open(redis_url)
            .map_err(|e| RedisError(format!("Failed to create Redis client: {}", e)))?;
        let conn = ConnectionManager::new(client)
            .await
            .map_err(|e| RedisError(format!("Failed to connect to Redis: {}", e)))?;
        Ok(Self {
            conn,
            url: redis_url.to_string(),
            default_ttl_secs: DEFAULT_TTL_SECS,
        })
    }

    /// Returns a clone of the underlying Redis connection manager.
    ///
    /// Cloning is cheap — `ConnectionManager` is backed by an `Arc`.
    /// Used by the rate-limit middleware to share the connection pool.
    pub fn connection(&self) -> ConnectionManager {
        self.conn.clone()
    }

    /// Build a Redis key from namespace and vector ID
    fn key(namespace: &str, id: &str) -> String {
        format!("{}:{}:{}", REDIS_KEY_PREFIX, namespace, id)
    }

    /// Build a namespace scan pattern
    fn namespace_pattern(namespace: &str) -> String {
        format!("{}:{}:*", REDIS_KEY_PREFIX, namespace)
    }

    /// Get a single vector from Redis
    pub async fn get(&self, namespace: &str, id: &str) -> Option<Vector> {
        let key = Self::key(namespace, id);
        let mut conn = self.conn.clone();
        match conn.get::<_, Option<String>>(&key).await {
            Ok(Some(json)) => {
                metrics::counter!("buffer_redis_hits_total").increment(1);
                match serde_json::from_str(&json) {
                    Ok(v) => Some(v),
                    Err(e) => {
                        tracing::warn!(key = %key, error = %e, "Failed to deserialize vector from Redis");
                        None
                    }
                }
            }
            Ok(None) => {
                metrics::counter!("buffer_redis_misses_total").increment(1);
                None
            }
            Err(e) => {
                tracing::debug!(key = %key, error = %e, "Redis GET failed");
                metrics::counter!("buffer_redis_misses_total").increment(1);
                None
            }
        }
    }

    /// Get multiple vectors from Redis
    pub async fn get_multi(&self, namespace: &str, ids: &[String]) -> Vec<Vector> {
        if ids.is_empty() {
            return Vec::new();
        }
        let keys: Vec<String> = ids.iter().map(|id| Self::key(namespace, id)).collect();
        let mut conn = self.conn.clone();

        // Use MGET for batch retrieval
        let results: Result<Vec<Option<String>>, _> =
            redis::cmd("MGET").arg(&keys).query_async(&mut conn).await;

        match results {
            Ok(values) => {
                let mut vectors = Vec::new();
                for (i, val) in values.into_iter().enumerate() {
                    match val {
                        Some(json) => {
                            metrics::counter!("buffer_redis_hits_total").increment(1);
                            match serde_json::from_str::<Vector>(&json) {
                                Ok(v) => vectors.push(v),
                                Err(e) => {
                                    tracing::warn!(key = %keys[i], error = %e, "Failed to deserialize vector from Redis");
                                }
                            }
                        }
                        None => {
                            metrics::counter!("buffer_redis_misses_total").increment(1);
                        }
                    }
                }
                vectors
            }
            Err(e) => {
                tracing::debug!(error = %e, "Redis MGET failed");
                metrics::counter!("buffer_redis_misses_total").increment(ids.len() as u64);
                Vec::new()
            }
        }
    }

    /// Store a single vector in Redis with TTL
    pub async fn set(&self, namespace: &str, vector: &Vector) {
        let key = Self::key(namespace, &vector.id);
        let json = match serde_json::to_string(vector) {
            Ok(j) => j,
            Err(e) => {
                tracing::warn!(key = %key, error = %e, "Failed to serialize vector for Redis");
                return;
            }
        };
        let mut conn = self.conn.clone();
        if let Err(e) = conn
            .set_ex::<_, _, ()>(&key, &json, self.default_ttl_secs)
            .await
        {
            tracing::debug!(key = %key, error = %e, "Redis SET failed");
        }
    }

    /// Store multiple vectors in Redis using pipeline
    pub async fn set_batch(&self, namespace: &str, vectors: &[Vector]) {
        if vectors.is_empty() {
            return;
        }
        let mut conn = self.conn.clone();
        let mut pipe = redis::pipe();
        for vector in vectors {
            let key = Self::key(namespace, &vector.id);
            let json = match serde_json::to_string(vector) {
                Ok(j) => j,
                Err(_) => continue,
            };
            pipe.cmd("SET")
                .arg(&key)
                .arg(&json)
                .arg("EX")
                .arg(self.default_ttl_secs)
                .ignore();
        }
        if let Err(e) = pipe.query_async::<()>(&mut conn).await {
            tracing::debug!(error = %e, count = vectors.len(), "Redis pipeline SET failed");
        }
    }

    /// Delete specific vectors from Redis
    pub async fn delete(&self, namespace: &str, ids: &[String]) {
        if ids.is_empty() {
            return;
        }
        let keys: Vec<String> = ids.iter().map(|id| Self::key(namespace, id)).collect();
        let mut conn = self.conn.clone();
        if let Err(e) = conn.del::<_, ()>(&keys).await {
            tracing::debug!(error = %e, count = ids.len(), "Redis DEL failed");
        }
    }

    /// Invalidate all entries for a namespace using SCAN + DEL
    pub async fn invalidate_namespace(&self, namespace: &str) {
        let pattern = Self::namespace_pattern(namespace);
        let mut conn = self.conn.clone();
        let mut cursor: u64 = 0;
        let mut total_deleted = 0u64;

        loop {
            let result: Result<(u64, Vec<String>), _> = redis::cmd("SCAN")
                .arg(cursor)
                .arg("MATCH")
                .arg(&pattern)
                .arg("COUNT")
                .arg(500)
                .query_async(&mut conn)
                .await;

            match result {
                Ok((next_cursor, keys)) => {
                    if !keys.is_empty() {
                        let _ = conn.del::<_, ()>(&keys).await;
                        total_deleted += keys.len() as u64;
                    }
                    cursor = next_cursor;
                    if cursor == 0 {
                        break;
                    }
                }
                Err(e) => {
                    tracing::warn!(namespace, error = %e, "Redis SCAN+DEL failed during namespace invalidation");
                    break;
                }
            }
        }

        if total_deleted > 0 {
            tracing::debug!(
                namespace,
                deleted = total_deleted,
                "Redis namespace invalidated"
            );
        }
    }

    /// Clear all buffer keys from Redis using SCAN + DEL
    pub async fn clear_all(&self) {
        let pattern = format!("{}:*", REDIS_KEY_PREFIX);
        let mut conn = self.conn.clone();
        let mut cursor: u64 = 0;

        loop {
            let result: Result<(u64, Vec<String>), _> = redis::cmd("SCAN")
                .arg(cursor)
                .arg("MATCH")
                .arg(&pattern)
                .arg("COUNT")
                .arg(500)
                .query_async(&mut conn)
                .await;

            match result {
                Ok((next_cursor, keys)) => {
                    if !keys.is_empty() {
                        let _ = conn.del::<_, ()>(&keys).await;
                    }
                    cursor = next_cursor;
                    if cursor == 0 {
                        break;
                    }
                }
                Err(e) => {
                    tracing::warn!(error = %e, "Redis SCAN+DEL failed during full cache clear");
                    break;
                }
            }
        }

        tracing::info!("Redis cache cleared");
    }

    /// Get Redis cache statistics from INFO command
    pub async fn stats(&self) -> RedisCacheStats {
        let mut conn = self.conn.clone();
        let info: Result<String, _> = redis::cmd("INFO").query_async(&mut conn).await;

        match info {
            Ok(info_str) => {
                let used_memory = Self::parse_info_field(&info_str, "used_memory")
                    .and_then(|s| s.parse::<u64>().ok())
                    .unwrap_or(0);
                let hits = Self::parse_info_field(&info_str, "keyspace_hits")
                    .and_then(|s| s.parse::<u64>().ok())
                    .unwrap_or(0);
                let misses = Self::parse_info_field(&info_str, "keyspace_misses")
                    .and_then(|s| s.parse::<u64>().ok())
                    .unwrap_or(0);

                // Get key count via DBSIZE
                let total_keys: u64 = redis::cmd("DBSIZE")
                    .query_async(&mut conn)
                    .await
                    .unwrap_or(0);

                let hit_rate = if hits + misses > 0 {
                    hits as f64 / (hits + misses) as f64 * 100.0
                } else {
                    0.0
                };

                RedisCacheStats {
                    connected: true,
                    used_memory_bytes: used_memory,
                    total_keys,
                    hits,
                    misses,
                    hit_rate,
                }
            }
            Err(e) => {
                tracing::debug!(error = %e, "Redis INFO command failed");
                RedisCacheStats {
                    connected: false,
                    ..Default::default()
                }
            }
        }
    }

    /// Parse a field from Redis INFO output
    fn parse_info_field<'a>(info: &'a str, field: &str) -> Option<&'a str> {
        for line in info.lines() {
            if let Some(value) = line.strip_prefix(&format!("{}:", field)) {
                return Some(value.trim());
            }
        }
        None
    }

    /// Publish a cache invalidation message via Redis pub/sub
    pub async fn publish_invalidation(&self, msg: &CacheInvalidation) {
        let json = match serde_json::to_string(msg) {
            Ok(j) => j,
            Err(e) => {
                tracing::warn!(error = %e, "Failed to serialize cache invalidation message");
                return;
            }
        };
        let mut conn = self.conn.clone();
        if let Err(e) = conn.publish::<_, _, ()>(REDIS_PUBSUB_CHANNEL, &json).await {
            tracing::debug!(error = %e, "Redis PUBLISH failed for cache invalidation");
        }
    }

    /// Publish a raw string message to any Redis channel.
    /// Used for backup cache invalidation and other cross-node signaling.
    pub async fn publish_raw(&self, channel: &str, message: &str) {
        let mut conn = self.conn.clone();
        if let Err(e) = conn.publish::<_, _, ()>(channel, message).await {
            tracing::debug!(channel = %channel, error = %e, "Redis PUBLISH failed");
        }
    }

    /// Subscribe to a Redis channel and return a receiver for raw string messages.
    /// Spawns a background task that listens for messages on the channel.
    pub async fn subscribe_raw(
        &self,
        channel: &str,
    ) -> Result<tokio::sync::mpsc::Receiver<String>, RedisError> {
        let client = redis::Client::open(self.url.as_str())
            .map_err(|e| RedisError(format!("Failed to create Redis client for pub/sub: {}", e)))?;
        let mut pubsub_conn = client
            .get_async_pubsub()
            .await
            .map_err(|e| RedisError(format!("Failed to get Redis pub/sub connection: {}", e)))?;
        pubsub_conn
            .subscribe(channel)
            .await
            .map_err(|e| RedisError(format!("Failed to subscribe to {}: {}", channel, e)))?;

        let (tx, rx) = tokio::sync::mpsc::channel(256);
        let channel_name = channel.to_string();

        tokio::spawn(async move {
            let mut msg_stream = pubsub_conn.on_message();
            while let Some(msg) = msg_stream.next().await {
                let payload: String = match msg.get_payload() {
                    Ok(p) => p,
                    Err(e) => {
                        tracing::debug!(error = %e, "Failed to get pub/sub message payload");
                        continue;
                    }
                };
                if tx.send(payload).await.is_err() {
                    tracing::debug!(channel = %channel_name, "Pub/sub receiver dropped, stopping");
                    break;
                }
            }
            tracing::warn!(channel = %channel_name, "Redis pub/sub raw stream ended");
        });

        tracing::info!(channel = %channel, "Redis raw pub/sub subscription started");
        Ok(rx)
    }

    /// Subscribe to cache invalidation messages.
    /// This is a long-running async function that calls the handler for each message.
    /// Should be spawned as a background task.
    pub async fn subscribe_invalidations<F>(&self, mut handler: F)
    where
        F: FnMut(CacheInvalidation) + Send + 'static,
    {
        // Create a separate connection for pub/sub (can't reuse ConnectionManager)
        let client = match redis::Client::open(self.url.as_str()) {
            Ok(c) => c,
            Err(e) => {
                tracing::error!(error = %e, "Failed to create Redis client for pub/sub");
                return;
            }
        };

        let mut pubsub_conn = match client.get_async_pubsub().await {
            Ok(c) => c,
            Err(e) => {
                tracing::error!(error = %e, "Failed to get Redis pub/sub connection");
                return;
            }
        };

        if let Err(e) = pubsub_conn.subscribe(REDIS_PUBSUB_CHANNEL).await {
            tracing::error!(error = %e, "Failed to subscribe to Redis invalidation channel");
            return;
        }

        tracing::info!("Redis pub/sub subscribed to {}", REDIS_PUBSUB_CHANNEL);

        let mut msg_stream = pubsub_conn.on_message();
        while let Some(msg) = msg_stream.next().await {
            let payload: String = match msg.get_payload() {
                Ok(p) => p,
                Err(e) => {
                    tracing::debug!(error = %e, "Failed to get pub/sub message payload");
                    continue;
                }
            };
            match serde_json::from_str::<CacheInvalidation>(&payload) {
                Ok(invalidation) => handler(invalidation),
                Err(e) => {
                    tracing::debug!(error = %e, "Failed to deserialize invalidation message");
                }
            }
        }

        tracing::warn!("Redis pub/sub stream ended");
    }

    /// Try to acquire a distributed lock via SET NX EX.
    ///
    /// Returns `true` if the lock was acquired (this replica is the leader),
    /// `false` if another replica already holds it.
    ///
    /// On Redis error (connection failure, timeout) returns `true` so callers
    /// gracefully degrade to in-process mode — the operation runs on every
    /// replica independently rather than not running at all.
    /// Callers MUST call `release_lock` after their critical section completes.
    pub async fn try_acquire_lock(&self, key: &str, owner: &str, ttl_secs: u64) -> bool {
        let mut conn = self.conn.clone();
        let result: Result<Option<String>, _> = redis::cmd("SET")
            .arg(key)
            .arg(owner)
            .arg("EX")
            .arg(ttl_secs)
            .arg("NX")
            .query_async(&mut conn)
            .await;
        match result {
            Ok(Some(_)) => {
                tracing::debug!(key = %key, owner = %owner, "Distributed lock acquired");
                true
            }
            Ok(None) => false, // Another replica holds the lock
            Err(e) => {
                tracing::warn!(
                    key = %key,
                    error = %e,
                    "Redis lock acquire failed — running as single-node fallback"
                );
                true // Graceful degradation: run anyway rather than skip the operation
            }
        }
    }

    /// Release a distributed lock, but only if this replica still owns it.
    ///
    /// Uses a Lua script for atomic check-and-delete.
    pub async fn release_lock(&self, key: &str, owner: &str) {
        let mut conn = self.conn.clone();
        let script = redis::Script::new(
            r#"if redis.call('get', KEYS[1]) == ARGV[1] then
                 return redis.call('del', KEYS[1])
               else
                 return 0
               end"#,
        );
        if let Err(e) = script
            .key(key)
            .arg(owner)
            .invoke_async::<i64>(&mut conn)
            .await
        {
            tracing::debug!(key = %key, error = %e, "Redis lock release failed (lock may have already expired)");
        }
    }
}

impl std::fmt::Debug for RedisCache {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RedisCache")
            .field("url", &self.url)
            .field("default_ttl_secs", &self.default_ttl_secs)
            .finish()
    }
}