Skip to main content

strata_storage/
storage.rs

1//! Concurrent In-Memory Cache with Bitcask WAL Persistence.
2
3use crate::bitcask::StrataKV;
4use std::collections::HashMap;
5use std::path::PathBuf;
6use std::sync::{Arc, Mutex, RwLock};
7
8/// Persistent LocalStorage with instant in-memory reads and background WAL durability.
9#[derive(Clone)]
10pub struct LocalStorage {
11    cache: Arc<RwLock<HashMap<String, String>>>,
12    kv: Arc<Mutex<StrataKV>>,
13}
14
15impl LocalStorage {
16    /// Opens or initializes LocalStorage at the specified WAL file path.
17    pub fn open(wal_path: impl Into<PathBuf>) -> std::io::Result<Self> {
18        let mut kv = StrataKV::open(wal_path.into())?;
19        let mut cache = HashMap::new();
20
21        // Hydrate in-memory cache from WAL keys
22        for key in kv.keys() {
23            if let Ok(Some(bytes)) = kv.get(&key) {
24                if let Ok(s) = String::from_utf8(bytes) {
25                    cache.insert(key, s);
26                }
27            }
28        }
29
30        Ok(Self {
31            cache: Arc::new(RwLock::new(cache)),
32            kv: Arc::new(Mutex::new(kv)),
33        })
34    }
35
36    /// Default global LocalStorage instance anchored to `app_data/storage.wal`.
37    pub fn default_instance() -> Self {
38        let wal_path =
39            strata_vfs::driver::to_physical_path(&strata_vfs::app_data().join("storage.wal"))
40                .unwrap_or_else(|_| std::env::temp_dir().join("strata_default_storage.wal"));
41        Self::open(wal_path).unwrap_or_else(|_| {
42            let tmp_path = std::env::temp_dir().join("strata_default_storage.wal");
43            Self::open(tmp_path).expect("Failed to open fallback storage WAL")
44        })
45    }
46
47    /// Instant $O(1)$ zero-latency read from in-memory cache.
48    pub fn get(&self, key: &str) -> Option<String> {
49        if let Ok(lock) = self.cache.read() {
50            lock.get(key).cloned()
51        } else {
52            None
53        }
54    }
55
56    /// Stores a value, updating in-memory cache and appending to WAL.
57    pub fn set(&self, key: impl Into<String>, val: impl Into<String>) {
58        let k = key.into();
59        let v = val.into();
60
61        if let Ok(mut lock) = self.cache.write() {
62            lock.insert(k.clone(), v.clone());
63        }
64
65        if let Ok(mut kv_lock) = self.kv.lock() {
66            let _ = kv_lock.put(&k, v.as_bytes());
67        }
68    }
69
70    /// Removes a key from both in-memory cache and WAL.
71    pub fn remove(&self, key: &str) -> bool {
72        let removed = if let Ok(mut lock) = self.cache.write() {
73            lock.remove(key).is_some()
74        } else {
75            false
76        };
77
78        if removed {
79            if let Ok(mut kv_lock) = self.kv.lock() {
80                let _ = kv_lock.delete(key);
81            }
82        }
83
84        removed
85    }
86
87    /// Clears all stored key-value pairs.
88    pub fn clear(&self) {
89        let keys_to_delete: Vec<String> = if let Ok(mut lock) = self.cache.write() {
90            let keys = lock.keys().cloned().collect();
91            lock.clear();
92            keys
93        } else {
94            Vec::new()
95        };
96
97        if let Ok(mut kv_lock) = self.kv.lock() {
98            for key in keys_to_delete {
99                let _ = kv_lock.delete(&key);
100            }
101        }
102    }
103
104    /// Number of active items in storage.
105    pub fn len(&self) -> usize {
106        if let Ok(lock) = self.cache.read() {
107            lock.len()
108        } else {
109            0
110        }
111    }
112
113    pub fn is_empty(&self) -> bool {
114        self.len() == 0
115    }
116
117    /// Returns a list of all keys in storage.
118    pub fn keys(&self) -> Vec<String> {
119        if let Ok(lock) = self.cache.read() {
120            lock.keys().cloned().collect()
121        } else {
122            Vec::new()
123        }
124    }
125
126    /// Explicitly trigger WAL compaction.
127    pub fn compact(&self) -> std::io::Result<()> {
128        if let Ok(mut kv_lock) = self.kv.lock() {
129            kv_lock.compact()?;
130        }
131        Ok(())
132    }
133}
134
135/// Volatile in-memory SessionStorage (discarded on application exit).
136#[derive(Clone, Default)]
137pub struct SessionStorage {
138    cache: Arc<RwLock<HashMap<String, String>>>,
139}
140
141impl SessionStorage {
142    pub fn new() -> Self {
143        Self {
144            cache: Arc::new(RwLock::new(HashMap::new())),
145        }
146    }
147
148    pub fn get(&self, key: &str) -> Option<String> {
149        if let Ok(lock) = self.cache.read() {
150            lock.get(key).cloned()
151        } else {
152            None
153        }
154    }
155
156    pub fn set(&self, key: impl Into<String>, val: impl Into<String>) {
157        if let Ok(mut lock) = self.cache.write() {
158            lock.insert(key.into(), val.into());
159        }
160    }
161
162    pub fn remove(&self, key: &str) -> bool {
163        if let Ok(mut lock) = self.cache.write() {
164            lock.remove(key).is_some()
165        } else {
166            false
167        }
168    }
169
170    pub fn clear(&self) {
171        if let Ok(mut lock) = self.cache.write() {
172            lock.clear();
173        }
174    }
175
176    pub fn len(&self) -> usize {
177        if let Ok(lock) = self.cache.read() {
178            lock.len()
179        } else {
180            0
181        }
182    }
183
184    pub fn is_empty(&self) -> bool {
185        self.len() == 0
186    }
187
188    pub fn keys(&self) -> Vec<String> {
189        if let Ok(lock) = self.cache.read() {
190            lock.keys().cloned().collect()
191        } else {
192            Vec::new()
193        }
194    }
195}