mappy_core/storage/
mod.rs1use async_trait::async_trait;
6use crate::MapletResult;
7use serde::{Serialize, Deserialize};
8
9pub mod memory;
10pub mod disk;
11pub mod aof;
12pub mod hybrid;
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct StorageStats {
17 pub total_keys: u64,
19 pub memory_usage: u64,
21 pub disk_usage: u64,
23 pub operations_count: u64,
25 pub avg_latency_us: u64,
27}
28
29impl Default for StorageStats {
30 fn default() -> Self {
31 Self {
32 total_keys: 0,
33 memory_usage: 0,
34 disk_usage: 0,
35 operations_count: 0,
36 avg_latency_us: 0,
37 }
38 }
39}
40
41#[async_trait]
43pub trait Storage: Send + Sync {
44 async fn get(&self, key: &str) -> MapletResult<Option<Vec<u8>>>;
46
47 async fn set(&self, key: String, value: Vec<u8>) -> MapletResult<()>;
49
50 async fn delete(&self, key: &str) -> MapletResult<bool>;
52
53 async fn exists(&self, key: &str) -> MapletResult<bool>;
55
56 async fn keys(&self) -> MapletResult<Vec<String>>;
58
59 async fn clear_database(&self) -> MapletResult<()>;
61
62 async fn flush(&self) -> MapletResult<()>;
64
65 async fn close(&self) -> MapletResult<()>;
67
68 async fn stats(&self) -> MapletResult<StorageStats>;
70}
71
72pub struct StorageFactory;
74
75impl StorageFactory {
76 pub async fn create_storage(
78 mode: PersistenceMode,
79 config: StorageConfig,
80 ) -> MapletResult<Box<dyn Storage>> {
81 match mode {
82 PersistenceMode::Memory => {
83 Ok(Box::new(memory::MemoryStorage::new(config).await?))
84 }
85 PersistenceMode::Disk => {
86 Ok(Box::new(disk::DiskStorage::new(config).await?))
87 }
88 PersistenceMode::AOF => {
89 Ok(Box::new(aof::AOFStorage::new(config).await?))
90 }
91 PersistenceMode::Hybrid => {
92 Ok(Box::new(hybrid::HybridStorage::new(config).await?))
93 }
94 }
95 }
96}
97
98#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
100pub enum PersistenceMode {
101 Memory,
103 AOF,
105 Disk,
107 Hybrid,
109}
110
111#[derive(Debug, Clone, Serialize, Deserialize)]
113pub struct StorageConfig {
114 pub data_dir: String,
116 pub max_memory: Option<u64>,
118 pub enable_compression: bool,
120 pub sync_interval: u64,
122 pub write_buffer_size: usize,
124}
125
126impl Default for StorageConfig {
127 fn default() -> Self {
128 Self {
129 data_dir: "./data".to_string(),
130 max_memory: None,
131 enable_compression: true,
132 sync_interval: 1,
133 write_buffer_size: 1024 * 1024, }
135 }
136}