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;
5
6pub trait LedgerStorage: Send + Sync {
7    fn load(&self) -> Result<Option<Vec<u8>>, String>;
8    fn save(&self, bytes: &[u8]) -> Result<(), String>;
9}
10
11/// Atomic, durable, owner-only write (temp file, fsync, rename, fsync directory) to one file,
12/// through `rightkit_fs::atomic_write_private`.
13pub struct FileStorage {
14    path: PathBuf,
15}
16
17impl FileStorage {
18    pub fn new(path: impl Into<PathBuf>) -> Self {
19        Self { path: path.into() }
20    }
21}
22
23impl LedgerStorage for FileStorage {
24    fn load(&self) -> Result<Option<Vec<u8>>, String> {
25        match std::fs::read(&self.path) {
26            Ok(b) => Ok(Some(b)),
27            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
28            Err(e) => Err(e.to_string()),
29        }
30    }
31    fn save(&self, bytes: &[u8]) -> Result<(), String> {
32        if let Some(dir) = self.path.parent() {
33            std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
34        }
35        rightkit_fs::atomic_write_private(&self.path, bytes).map_err(|e| e.to_string())
36    }
37}