Skip to main content

rightkit_sync/
storage.rs

1//! Durable ledger bytes. Failures are reported, never swallowed: a pass that
2//! cannot persist its progress must not advance the change token.
3
4use std::path::PathBuf;
5use std::sync::{Arc, Mutex};
6
7pub trait LedgerStorage: Send + Sync {
8    fn load(&self) -> Result<Option<Vec<u8>>, String>;
9    fn save(&self, bytes: &[u8]) -> Result<(), String>;
10}
11
12/// Atomic, durable, owner-only write (temp file, fsync, rename, fsync directory) to one file,
13/// through `rightkit_fs::atomic_write_private`.
14pub struct FileStorage {
15    path: PathBuf,
16}
17
18impl FileStorage {
19    pub fn new(path: impl Into<PathBuf>) -> Self {
20        Self { path: path.into() }
21    }
22}
23
24impl LedgerStorage for FileStorage {
25    fn load(&self) -> Result<Option<Vec<u8>>, String> {
26        match std::fs::read(&self.path) {
27            Ok(b) => Ok(Some(b)),
28            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
29            Err(e) => Err(e.to_string()),
30        }
31    }
32    fn save(&self, bytes: &[u8]) -> Result<(), String> {
33        if let Some(dir) = self.path.parent() {
34            std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
35        }
36        rightkit_fs::atomic_write_private(&self.path, bytes).map_err(|e| e.to_string())
37    }
38}
39
40/// Clonable in-memory storage; clones share bytes (simulates an app restart).
41#[derive(Clone, Default)]
42pub struct MemoryStorage(Arc<Mutex<Option<Vec<u8>>>>);
43
44impl LedgerStorage for MemoryStorage {
45    fn load(&self) -> Result<Option<Vec<u8>>, String> {
46        Ok(self.0.lock().unwrap().clone())
47    }
48    fn save(&self, bytes: &[u8]) -> Result<(), String> {
49        *self.0.lock().unwrap() = Some(bytes.to_vec());
50        Ok(())
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn file_storage_round_trips_replaces_and_leaves_no_temp_files() {
60        let dir = std::env::temp_dir().join(format!("rk-sync-storage-{}", std::process::id()));
61        let _ = std::fs::remove_dir_all(&dir);
62        let store = FileStorage::new(dir.join("nested").join("ledger.json"));
63        assert_eq!(store.load().unwrap(), None);
64        store.save(b"one").unwrap();
65        store.save(b"two").unwrap();
66        assert_eq!(store.load().unwrap().as_deref(), Some(&b"two"[..]));
67        let names: Vec<_> = std::fs::read_dir(dir.join("nested"))
68            .unwrap()
69            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
70            .collect();
71        assert_eq!(names, vec!["ledger.json".to_string()]);
72        let _ = std::fs::remove_dir_all(&dir);
73    }
74}