logicaffeine_system/storage/
mod.rs1use crate::fs::{Vfs, VfsError, VfsResult};
52use async_lock::Mutex;
53use logicaffeine_data::crdt::Merge;
54use serde::{de::DeserializeOwned, Serialize};
55use std::marker::PhantomData;
56use std::sync::Arc;
57
58#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
60enum JournalOp<T> {
61 Snapshot(T),
63 Delta(T),
65}
66
67struct JournalHeader;
70
71impl JournalHeader {
72 const SIZE: usize = 8;
73
74 fn encode(payload: &[u8]) -> [u8; Self::SIZE] {
75 let length = payload.len() as u32;
76 let checksum = crc32fast::hash(payload);
77 let mut buf = [0u8; Self::SIZE];
78 buf[0..4].copy_from_slice(&length.to_le_bytes());
79 buf[4..8].copy_from_slice(&checksum.to_le_bytes());
80 buf
81 }
82
83 fn decode(buf: &[u8; Self::SIZE]) -> (u32, u32) {
84 let length = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]);
85 let checksum = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]);
86 (length, checksum)
87 }
88}
89
90#[cfg(not(target_arch = "wasm32"))]
98pub struct Persistent<T>
99where
100 T: Merge + Serialize + DeserializeOwned + Clone + Default + Send + 'static,
101{
102 inner: Arc<Mutex<T>>,
103 vfs: Arc<dyn Vfs + Send + Sync>,
104 journal_path: String,
105 entry_count: Arc<Mutex<u64>>,
106 _marker: PhantomData<T>,
107}
108
109#[cfg(target_arch = "wasm32")]
111pub struct Persistent<T>
112where
113 T: Merge + Serialize + DeserializeOwned + Clone + Default + 'static,
114{
115 inner: Arc<Mutex<T>>,
116 vfs: Arc<dyn Vfs>,
117 journal_path: String,
118 entry_count: Arc<Mutex<u64>>,
119 _marker: PhantomData<T>,
120}
121
122fn replay_journal<T>(data: &[u8]) -> Result<(T, u64), VfsError>
124where
125 T: Merge + Serialize + DeserializeOwned + Clone + Default,
126{
127 let mut state = T::default();
128 let mut entry_count = 0u64;
129 let mut pos = 0;
130
131 while pos + JournalHeader::SIZE <= data.len() {
132 let header_bytes: [u8; 8] = data[pos..pos + 8].try_into().unwrap();
133 let (length, expected_checksum) = JournalHeader::decode(&header_bytes);
134 pos += JournalHeader::SIZE;
135
136 let payload_end = pos + length as usize;
137 if payload_end > data.len() {
138 break;
140 }
141
142 let payload = &data[pos..payload_end];
143 let actual_checksum = crc32fast::hash(payload);
144
145 if actual_checksum != expected_checksum {
146 return Err(VfsError::JournalCorrupted(format!(
147 "Entry {} checksum mismatch",
148 entry_count
149 )));
150 }
151
152 let op: JournalOp<T> = bincode::deserialize(payload)
153 .map_err(|e| VfsError::SerializationError(e.to_string()))?;
154
155 match op {
156 JournalOp::Snapshot(s) => state = s,
157 JournalOp::Delta(d) => state.merge(&d),
158 }
159
160 pos = payload_end;
161 entry_count += 1;
162 }
163
164 Ok((state, entry_count))
165}
166
167#[cfg(not(target_arch = "wasm32"))]
169impl<T> Persistent<T>
170where
171 T: Merge + Serialize + DeserializeOwned + Clone + Default + Send + 'static,
172{
173 pub async fn mount(vfs: Arc<dyn Vfs + Send + Sync>, path: &str) -> VfsResult<Self> {
179 let (state, entry_count) = if vfs.exists(path).await.unwrap_or(false) {
180 let data = vfs.read(path).await?;
181 replay_journal(&data)?
182 } else {
183 (T::default(), 0)
184 };
185
186 Ok(Self {
187 inner: Arc::new(Mutex::new(state)),
188 vfs,
189 journal_path: path.to_string(),
190 entry_count: Arc::new(Mutex::new(entry_count)),
191 _marker: PhantomData,
192 })
193 }
194
195 pub async fn get(&self) -> T {
197 self.inner.lock().await.clone()
198 }
199
200 pub async fn mutate<F, R>(&self, f: F) -> VfsResult<R>
202 where
203 F: FnOnce(&mut T) -> R + Send,
204 {
205 let mut guard = self.inner.lock().await;
206 let result = f(&mut *guard);
207
208 let op = JournalOp::Delta(guard.clone());
209 let payload =
210 bincode::serialize(&op).map_err(|e| VfsError::SerializationError(e.to_string()))?;
211
212 let header = JournalHeader::encode(&payload);
213 let mut entry = Vec::with_capacity(JournalHeader::SIZE + payload.len());
214 entry.extend_from_slice(&header);
215 entry.extend_from_slice(&payload);
216
217 self.vfs.append(&self.journal_path, &entry).await?;
218 *self.entry_count.lock().await += 1;
219
220 Ok(result)
221 }
222
223 pub async fn compact(&self) -> VfsResult<()> {
225 let state = self.inner.lock().await.clone();
226
227 let op = JournalOp::<T>::Snapshot(state);
228 let payload =
229 bincode::serialize(&op).map_err(|e| VfsError::SerializationError(e.to_string()))?;
230
231 let header = JournalHeader::encode(&payload);
232 let mut entry = Vec::with_capacity(JournalHeader::SIZE + payload.len());
233 entry.extend_from_slice(&header);
234 entry.extend_from_slice(&payload);
235
236 self.vfs.write(&self.journal_path, &entry).await?;
237 *self.entry_count.lock().await = 1;
238
239 Ok(())
240 }
241
242 pub async fn entry_count(&self) -> u64 {
244 *self.entry_count.lock().await
245 }
246
247 pub async fn maybe_compact(&self, threshold: u64) -> VfsResult<bool> {
249 if self.entry_count().await > threshold {
250 self.compact().await?;
251 Ok(true)
252 } else {
253 Ok(false)
254 }
255 }
256}
257
258#[cfg(target_arch = "wasm32")]
260impl<T> Persistent<T>
261where
262 T: Merge + Serialize + DeserializeOwned + Clone + Default + 'static,
263{
264 pub async fn mount(vfs: Arc<dyn Vfs>, path: &str) -> VfsResult<Self> {
266 let (state, entry_count) = if vfs.exists(path).await.unwrap_or(false) {
267 let data = vfs.read(path).await?;
268 replay_journal(&data)?
269 } else {
270 (T::default(), 0)
271 };
272
273 Ok(Self {
274 inner: Arc::new(Mutex::new(state)),
275 vfs,
276 journal_path: path.to_string(),
277 entry_count: Arc::new(Mutex::new(entry_count)),
278 _marker: PhantomData,
279 })
280 }
281
282 pub async fn get(&self) -> T {
284 self.inner.lock().await.clone()
285 }
286
287 pub async fn mutate<F, R>(&self, f: F) -> VfsResult<R>
289 where
290 F: FnOnce(&mut T) -> R,
291 {
292 let mut guard = self.inner.lock().await;
293 let result = f(&mut *guard);
294
295 let op = JournalOp::Delta(guard.clone());
296 let payload =
297 bincode::serialize(&op).map_err(|e| VfsError::SerializationError(e.to_string()))?;
298
299 let header = JournalHeader::encode(&payload);
300 let mut entry = Vec::with_capacity(JournalHeader::SIZE + payload.len());
301 entry.extend_from_slice(&header);
302 entry.extend_from_slice(&payload);
303
304 self.vfs.append(&self.journal_path, &entry).await?;
305 *self.entry_count.lock().await += 1;
306
307 Ok(result)
308 }
309
310 pub async fn compact(&self) -> VfsResult<()> {
312 let state = self.inner.lock().await.clone();
313
314 let op = JournalOp::<T>::Snapshot(state);
315 let payload =
316 bincode::serialize(&op).map_err(|e| VfsError::SerializationError(e.to_string()))?;
317
318 let header = JournalHeader::encode(&payload);
319 let mut entry = Vec::with_capacity(JournalHeader::SIZE + payload.len());
320 entry.extend_from_slice(&header);
321 entry.extend_from_slice(&payload);
322
323 self.vfs.write(&self.journal_path, &entry).await?;
324 *self.entry_count.lock().await = 1;
325
326 Ok(())
327 }
328
329 pub async fn entry_count(&self) -> u64 {
331 *self.entry_count.lock().await
332 }
333
334 pub async fn maybe_compact(&self, threshold: u64) -> VfsResult<bool> {
336 if self.entry_count().await > threshold {
337 self.compact().await?;
338 Ok(true)
339 } else {
340 Ok(false)
341 }
342 }
343}
344
345#[cfg(test)]
348#[path = "../../../logicaffeine_tests/unit/logicaffeine_system/storage/tests.rs"]
349mod tests;