Skip to main content

logicaffeine_system/storage/
mod.rs

1//! Persistent Storage with Journaling
2//!
3//! Provides crash-resilient persistence for CRDTs using an append-only journal
4//! with automatic replay on mount and compaction support.
5//!
6//! # Architecture
7//!
8//! The journal uses a simple binary format:
9//!
10//! ```text
11//! ┌─────────────┬─────────────┬─────────────────┐
12//! │ Length (4B) │ CRC32 (4B)  │ Payload (N B)   │
13//! └─────────────┴─────────────┴─────────────────┘
14//! ```
15//!
16//! Entries are either:
17//! - **Snapshot**: Full state replacement (written during compaction)
18//! - **Delta**: Incremental update (written on each mutation)
19//!
20//! # Recovery
21//!
22//! On mount, the journal is replayed entry-by-entry:
23//! - Snapshots replace the current state
24//! - Deltas are merged via the CRDT's `Merge` trait
25//! - Truncated entries are ignored (WAL semantics)
26//! - Checksum failures return an error
27//!
28//! # Features
29//!
30//! Requires the `persistence` feature.
31//!
32//! # Example
33//!
34//! ```no_run
35//! use logicaffeine_system::storage::Persistent;
36//! use logicaffeine_data::crdt::GCounter;
37//! # use logicaffeine_system::fs::NativeVfs;
38//! # use std::sync::Arc;
39//!
40//! # fn main() {}
41//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
42//! let vfs: Arc<dyn logicaffeine_system::fs::Vfs + Send + Sync> = Arc::new(NativeVfs::new("/data"));
43//! let counter = Persistent::<GCounter>::mount(vfs, "counter.lsf").await?;
44//!
45//! counter.mutate(|c| c.increment(5)).await?;
46//! counter.compact().await?; // Reduce journal size
47//! # Ok(())
48//! # }
49//! ```
50
51use 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/// Operation recorded in the journal.
59#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
60enum JournalOp<T> {
61    /// Full state snapshot (for compaction)
62    Snapshot(T),
63    /// Delta operation (for incremental updates)
64    Delta(T),
65}
66
67/// Journal entry header format:
68/// [4 bytes: length][4 bytes: crc32][N bytes: payload]
69struct 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/// A persistent CRDT wrapper with journaling (native platform).
91///
92/// Wraps any type implementing `Merge + Serialize + DeserializeOwned`
93/// and provides durable storage with crash recovery.
94///
95/// This is the native version with `Send` bounds required for thread-safe access.
96/// The WASM version relaxes these bounds since JavaScript is single-threaded.
97#[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/// WASM version without Send bounds (JS is single-threaded).
110#[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
122/// Helper function to replay journal entries (shared between platforms).
123fn 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            // Truncated entry - stop replay (WAL semantics)
139            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/// Native implementation with Send bounds.
168#[cfg(not(target_arch = "wasm32"))]
169impl<T> Persistent<T>
170where
171    T: Merge + Serialize + DeserializeOwned + Clone + Default + Send + 'static,
172{
173    /// Mount a persistent value from a journal file.
174    ///
175    /// If the journal exists, replays all entries to reconstruct state.
176    /// If not, creates a new journal with default state.
177    ///
178    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    /// Get immutable access to the current state.
196    pub async fn get(&self) -> T {
197        self.inner.lock().await.clone()
198    }
199
200    /// Mutate the state and persist the delta.
201    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    /// Compact the journal by writing a snapshot.
224    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    /// Get the number of journal entries.
243    pub async fn entry_count(&self) -> u64 {
244        *self.entry_count.lock().await
245    }
246
247    /// Automatically compact when entry count exceeds threshold.
248    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/// WASM implementation without Send bounds (single-threaded).
259#[cfg(target_arch = "wasm32")]
260impl<T> Persistent<T>
261where
262    T: Merge + Serialize + DeserializeOwned + Clone + Default + 'static,
263{
264    /// Mount a persistent value from a journal file.
265    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    /// Get immutable access to the current state.
283    pub async fn get(&self) -> T {
284        self.inner.lock().await.clone()
285    }
286
287    /// Mutate the state and persist the delta.
288    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    /// Compact the journal by writing a snapshot.
311    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    /// Get the number of journal entries.
330    pub async fn entry_count(&self) -> u64 {
331        *self.entry_count.lock().await
332    }
333
334    /// Automatically compact when entry count exceeds threshold.
335    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// The storage module directly accepts Arc<dyn Vfs> for flexibility.
346
347#[cfg(test)]
348#[path = "../../../logicaffeine_tests/unit/logicaffeine_system/storage/tests.rs"]
349mod tests;