feat(rustdb): add restore and periodic persistence support for in-memory storage
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
pub mod management;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use dashmap::DashMap;
|
||||
@@ -33,7 +35,16 @@ impl RustDb {
|
||||
// Create storage adapter
|
||||
let storage: Arc<dyn StorageAdapter> = match options.storage {
|
||||
StorageType::Memory => {
|
||||
let adapter = MemoryStorageAdapter::new();
|
||||
let adapter = if let Some(ref pp) = options.persist_path {
|
||||
tracing::info!("MemoryStorageAdapter with periodic persistence to {}", pp);
|
||||
MemoryStorageAdapter::with_persist_path(PathBuf::from(pp))
|
||||
} else {
|
||||
tracing::warn!(
|
||||
"SmartDB is using in-memory storage — data will NOT survive a restart. \
|
||||
Set storage to 'file' for durable persistence."
|
||||
);
|
||||
MemoryStorageAdapter::new()
|
||||
};
|
||||
Arc::new(adapter)
|
||||
}
|
||||
StorageType::File => {
|
||||
@@ -49,6 +60,26 @@ impl RustDb {
|
||||
// Initialize storage
|
||||
storage.initialize().await?;
|
||||
|
||||
// Restore any previously persisted state (no-op for file storage and
|
||||
// memory storage without a persist_path).
|
||||
storage.restore().await?;
|
||||
|
||||
// Spawn periodic persistence task for memory storage with persist_path.
|
||||
if options.storage == StorageType::Memory && options.persist_path.is_some() {
|
||||
let persist_storage = storage.clone();
|
||||
let interval_ms = options.persist_interval_ms;
|
||||
tokio::spawn(async move {
|
||||
let mut interval = tokio::time::interval(Duration::from_millis(interval_ms));
|
||||
interval.tick().await; // skip the immediate first tick
|
||||
loop {
|
||||
interval.tick().await;
|
||||
if let Err(e) = persist_storage.persist().await {
|
||||
tracing::error!("Periodic persist failed: {}", e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let ctx = Arc::new(CommandContext {
|
||||
storage,
|
||||
indexes: Arc::new(DashMap::new()),
|
||||
|
||||
Reference in New Issue
Block a user