do-memory-storage-redb 0.1.31

redb embedded storage backend for do-memory-core episodic learning system (cache layer)
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
//! # Redb Cache Persistence Module
//!
//! This module provides persistence for the redb cache layer, enabling:
//! - Cache state save/load functionality
//! - Graceful shutdown with cache flush
//! - Recovery on startup
//! - Incremental cache persistence
//!
//! ## Features
//!
//! - **Full Cache Persistence**: Save and load complete cache state
//! - **Incremental Updates**: Persist only changed entries
//! - **Graceful Shutdown**: Automatic cache flush on shutdown
//! - **Recovery**: Restore cache state on startup
//! - **Compression**: Optional compression for persisted data
//!
//! ## Usage
//!
//! ```rust
//! use do_memory_storage_redb::{CachePersistence, PersistenceConfig};
//!
//! let config = PersistenceConfig::default();
//! let persistence = CachePersistence::new(config);
//! ```

use std::path::{Path, PathBuf};
use std::sync::Arc;
#[allow(unused_imports)]
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use parking_lot::RwLock;
use tracing::{debug, info};

#[allow(unused_imports)] // False positive - imports are used in conditional code
mod config;
mod manager;
mod types;

pub use config::{PersistenceConfig, PersistenceMode, PersistenceStrategy};
pub use manager::PersistenceManager;
pub use types::{CacheSnapshot, IncrementalUpdate, PersistedCacheEntry, PersistenceStats};

/// Cache persistence handler
///
/// Manages saving and loading cache state to/from disk.
/// Supports full snapshots and incremental updates.
#[derive(Debug)]
pub struct CachePersistence {
    config: PersistenceConfig,
    stats: Arc<RwLock<PersistenceStats>>,
    last_save: Arc<RwLock<Option<Instant>>>,
}

impl CachePersistence {
    /// Create a new cache persistence handler
    pub fn new(config: PersistenceConfig) -> Self {
        info!(
            "Creating cache persistence with mode={:?}, strategy={:?}",
            config.mode, config.strategy
        );

        Self {
            config,
            stats: Arc::new(RwLock::new(PersistenceStats::default())),
            last_save: Arc::new(RwLock::new(None)),
        }
    }

    /// Create with default configuration
    pub fn with_default_config() -> Self {
        Self::new(PersistenceConfig::default())
    }

    /// Get persistence configuration
    pub fn config(&self) -> &PersistenceConfig {
        &self.config
    }

    /// Get persistence statistics
    pub fn stats(&self) -> PersistenceStats {
        self.stats.read().clone()
    }

    /// Check if persistence is enabled
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Save cache snapshot to disk
    ///
    /// # Arguments
    ///
    /// * `snapshot` - The cache snapshot to save
    /// * `path` - Optional path override (uses config path if None)
    ///
    /// # Returns
    ///
    /// Number of entries saved, or error if save failed
    pub fn save_snapshot(
        &self,
        snapshot: &CacheSnapshot,
        path: Option<&Path>,
    ) -> crate::Result<usize> {
        if !self.config.enabled {
            debug!("Cache persistence disabled, skipping save");
            return Ok(0);
        }

        let save_path = path
            .map(PathBuf::from)
            .unwrap_or_else(|| self.config.persistence_path.clone());

        info!(
            "Saving cache snapshot with {} entries to {:?}",
            snapshot.entries.len(),
            save_path
        );

        let start = Instant::now();

        // Serialize snapshot
        let serialized = postcard::to_allocvec(snapshot).map_err(|e| {
            crate::Error::Storage(format!("Failed to serialize cache snapshot: {}", e))
        })?;

        // Compress if enabled
        let data = if self.config.compression_enabled {
            debug!("Compressing cache snapshot ({} bytes)", serialized.len());
            compress_data(&serialized).map_err(|e| {
                crate::Error::Storage(format!("Failed to compress cache snapshot: {}", e))
            })?
        } else {
            serialized
        };

        // Write to file
        std::fs::write(&save_path, &data)
            .map_err(|e| crate::Error::Storage(format!("Failed to write cache snapshot: {}", e)))?;

        let elapsed = start.elapsed();
        let bytes_written = data.len();

        // Update statistics
        {
            let mut stats = self.stats.write();
            stats.snapshots_saved += 1;
            stats.total_entries_saved += snapshot.entries.len();
            stats.total_bytes_written += bytes_written as u64;
            stats.last_save_duration = elapsed;
        }

        // Update last save time
        {
            let mut last = self.last_save.write();
            *last = Some(Instant::now());
        }

        info!(
            "Cache snapshot saved: {} entries, {} bytes in {:?}",
            snapshot.entries.len(),
            bytes_written,
            elapsed
        );

        Ok(snapshot.entries.len())
    }

    /// Load cache snapshot from disk
    ///
    /// # Arguments
    ///
    /// * `path` - Optional path override (uses config path if None)
    ///
    /// # Returns
    ///
    /// Loaded cache snapshot, or error if load failed
    pub fn load_snapshot(&self, path: Option<&Path>) -> crate::Result<Option<CacheSnapshot>> {
        if !self.config.enabled {
            debug!("Cache persistence disabled, skipping load");
            return Ok(None);
        }

        let load_path = path
            .map(PathBuf::from)
            .unwrap_or_else(|| self.config.persistence_path.clone());

        if !load_path.exists() {
            debug!("No cache snapshot found at {:?}", load_path);
            return Ok(None);
        }

        info!("Loading cache snapshot from {:?}", load_path);

        let start = Instant::now();

        // Read from file
        let data = std::fs::read(&load_path)
            .map_err(|e| crate::Error::Storage(format!("Failed to read cache snapshot: {}", e)))?;

        // Decompress if needed
        let serialized = if self.config.compression_enabled {
            debug!("Decompressing cache snapshot ({} bytes)", data.len());
            decompress_data(&data).map_err(|e| {
                crate::Error::Storage(format!("Failed to decompress cache snapshot: {}", e))
            })?
        } else {
            data
        };

        // Deserialize snapshot
        let snapshot: CacheSnapshot = postcard::from_bytes(&serialized).map_err(|e| {
            crate::Error::Storage(format!("Failed to deserialize cache snapshot: {}", e))
        })?;

        let elapsed = start.elapsed();

        // Update statistics
        {
            let mut stats = self.stats.write();
            stats.snapshots_loaded += 1;
            stats.total_entries_loaded += snapshot.entries.len();
            stats.total_bytes_read += serialized.len() as u64;
            stats.last_load_duration = elapsed;
        }

        info!(
            "Cache snapshot loaded: {} entries, {} bytes in {:?}",
            snapshot.entries.len(),
            serialized.len(),
            elapsed
        );

        Ok(Some(snapshot))
    }

    /// Check if a save is needed based on configuration
    pub fn should_save(&self, entries_count: usize) -> bool {
        if !self.config.enabled {
            return false;
        }

        // Check minimum entries threshold
        if entries_count < self.config.min_entries_threshold {
            return false;
        }

        // Check save interval
        if let Some(last) = *self.last_save.read() {
            if last.elapsed() < self.config.save_interval {
                return false;
            }
        }

        true
    }

    /// Delete persisted cache snapshot
    pub fn delete_snapshot(&self, path: Option<&Path>) -> crate::Result<bool> {
        let delete_path = path
            .map(PathBuf::from)
            .unwrap_or_else(|| self.config.persistence_path.clone());

        if delete_path.exists() {
            std::fs::remove_file(&delete_path).map_err(|e| {
                crate::Error::Storage(format!("Failed to delete cache snapshot: {}", e))
            })?;

            info!("Cache snapshot deleted: {:?}", delete_path);
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Get the age of the last save
    pub fn last_save_age(&self) -> Option<Duration> {
        self.last_save.read().map(|instant| instant.elapsed())
    }

    /// Reset persistence statistics
    pub fn reset_stats(&self) {
        let mut stats = self.stats.write();
        *stats = PersistenceStats::default();
        info!("Cache persistence statistics reset");
    }
}

impl Default for CachePersistence {
    fn default() -> Self {
        Self::new(PersistenceConfig::default())
    }
}

/// Compress data using LZ4
fn compress_data(data: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    // Simple compression: store length prefix + compressed data
    let compressed = lz4_flex::compress_prepend_size(data);
    Ok(compressed)
}

/// Decompress data using LZ4
fn decompress_data(data: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let decompressed = lz4_flex::decompress_size_prepended(data)?;
    Ok(decompressed)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use tempfile::TempDir;

    fn create_test_snapshot() -> CacheSnapshot {
        let entries = vec![
            PersistedCacheEntry {
                key: "entry1".to_string(),
                value: vec![1, 2, 3],
                created_at: SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs(),
                access_count: 5,
                last_accessed: SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs(),
                ttl_secs: None,
            },
            PersistedCacheEntry {
                key: "entry2".to_string(),
                value: vec![4, 5, 6],
                created_at: SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs(),
                access_count: 3,
                last_accessed: SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs(),
                ttl_secs: None,
            },
        ];

        CacheSnapshot {
            version: 1,
            created_at: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs(),
            entries,
            metadata: HashMap::new(),
        }
    }

    #[test]
    fn test_persistence_creation() {
        let config = PersistenceConfig::default();
        let persistence = CachePersistence::new(config);

        assert!(persistence.is_enabled());
        assert_eq!(persistence.stats().snapshots_saved, 0);
    }

    #[test]
    fn test_save_and_load_snapshot() {
        let temp_dir = TempDir::new().unwrap();
        let snapshot_path = temp_dir.path().join("cache.snapshot");

        let config = PersistenceConfig {
            enabled: true,
            persistence_path: snapshot_path.clone(),
            compression_enabled: false,
            ..Default::default()
        };

        let persistence = CachePersistence::new(config);
        let snapshot = create_test_snapshot();

        // Save snapshot
        let saved = persistence.save_snapshot(&snapshot, None).unwrap();
        assert_eq!(saved, 2);
        assert_eq!(persistence.stats().snapshots_saved, 1);

        // Load snapshot
        let loaded = persistence.load_snapshot(None).unwrap();
        assert!(loaded.is_some());

        let loaded_snapshot = loaded.unwrap();
        assert_eq!(loaded_snapshot.entries.len(), 2);
        assert_eq!(loaded_snapshot.entries[0].key, "entry1");
        assert_eq!(loaded_snapshot.entries[1].key, "entry2");
    }

    #[test]
    fn test_save_with_compression() {
        let temp_dir = TempDir::new().unwrap();
        let snapshot_path = temp_dir.path().join("cache.snapshot");

        let config = PersistenceConfig {
            enabled: true,
            persistence_path: snapshot_path.clone(),
            compression_enabled: true,
            ..Default::default()
        };

        let persistence = CachePersistence::new(config);
        let snapshot = create_test_snapshot();

        // Save with compression
        let saved = persistence.save_snapshot(&snapshot, None).unwrap();
        assert_eq!(saved, 2);

        // Load and verify
        let loaded = persistence.load_snapshot(None).unwrap();
        assert!(loaded.is_some());
        assert_eq!(loaded.unwrap().entries.len(), 2);
    }

    #[test]
    fn test_disabled_persistence() {
        let config = PersistenceConfig {
            enabled: false,
            ..Default::default()
        };

        let persistence = CachePersistence::new(config);
        let snapshot = create_test_snapshot();

        assert!(!persistence.is_enabled());
        assert_eq!(persistence.save_snapshot(&snapshot, None).unwrap(), 0);
        assert!(persistence.load_snapshot(None).unwrap().is_none());
    }

    #[test]
    fn test_should_save() {
        let config = PersistenceConfig {
            enabled: true,
            min_entries_threshold: 10,
            save_interval: Duration::from_secs(60),
            ..Default::default()
        };

        let persistence = CachePersistence::new(config);

        // Below threshold
        assert!(!persistence.should_save(5));

        // Above threshold
        assert!(persistence.should_save(15));
    }

    #[test]
    fn test_delete_snapshot() {
        let temp_dir = TempDir::new().unwrap();
        let snapshot_path = temp_dir.path().join("cache.snapshot");

        let config = PersistenceConfig {
            enabled: true,
            persistence_path: snapshot_path.clone(),
            ..Default::default()
        };

        let persistence = CachePersistence::new(config);
        let snapshot = create_test_snapshot();

        // Save and verify exists
        persistence.save_snapshot(&snapshot, None).unwrap();
        assert!(snapshot_path.exists());

        // Delete and verify gone
        let deleted = persistence.delete_snapshot(None).unwrap();
        assert!(deleted);
        assert!(!snapshot_path.exists());

        // Delete non-existent
        let deleted = persistence.delete_snapshot(None).unwrap();
        assert!(!deleted);
    }
}