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::{Path, PathBuf};
5use std::time::Duration;
6
7/// One lock name & primitive for every built-in ledger writer.
8pub(crate) fn ledger_file_lock(path: &Path) -> Result<rightkit_fs::lock::FileLock, String> {
9    if let Some(dir) = path.parent() {
10        std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
11    }
12    let mut name = path.as_os_str().to_os_string();
13    name.push(".lock");
14    rightkit_fs::lock::FileLock::acquire(
15        &PathBuf::from(name),
16        &rightkit_fs::lock::LockOptions::wait(Duration::from_secs(10)),
17    )
18    .map_err(|_| "cloud sync ledger is locked by another writer".to_string())
19}
20
21pub trait LedgerStorage: Send + Sync {
22    fn load(&self) -> Result<Option<Vec<u8>>, String>;
23    fn save(&self, bytes: &[u8]) -> Result<(), String>;
24}
25
26/// Atomic, durable, owner-only write (temp file, fsync, rename, fsync directory) to one file,
27/// through `rightkit_fs::atomic_write_private`.
28pub struct FileStorage {
29    path: PathBuf,
30}
31
32impl FileStorage {
33    pub fn new(path: impl Into<PathBuf>) -> Self {
34        Self { path: path.into() }
35    }
36
37    /// Caller must hold `ledger_file_lock` for this path across validation & replacement.
38    pub(crate) fn save_locked(&self, bytes: &[u8]) -> Result<(), String> {
39        if let Some(dir) = self.path.parent() {
40            std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
41        }
42        rightkit_fs::atomic_write_private(&self.path, bytes).map_err(|e| e.to_string())
43    }
44}
45
46impl LedgerStorage for FileStorage {
47    fn load(&self) -> Result<Option<Vec<u8>>, String> {
48        match std::fs::read(&self.path) {
49            Ok(b) => Ok(Some(b)),
50            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
51            Err(e) => Err(e.to_string()),
52        }
53    }
54    fn save(&self, bytes: &[u8]) -> Result<(), String> {
55        let _lock = ledger_file_lock(&self.path)?;
56        self.save_locked(bytes)
57    }
58}