garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /src/store.rs

raw

//! A JSON file that several threads and processes change: the hub answers
//! each connection on a thread of its own, and its warmer and root's setup
//! run beside it. A change is read, made and written back under one `flock`,
//! and written by renaming a complete copy into place, so a reader never sees
//! half a file and a crash leaves the previous one.
//!
//! ```ignore
//! let mut s: Store<Value> = Store::open(registry::root().join("collab.json"))?;
//! s.data["notes"] = json!({});
//! s.save()?;            // still locked; the lock goes when `s` does
//! ```
//!
//! The lock is a file of its own beside the data (`.collab.lock` for
//! `collab.json`), never the data file itself, which is replaced on every save.

use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::os::fd::AsRawFd;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

use anyhow::{bail, Context, Result};
use serde::de::DeserializeOwned;
use serde::Serialize;

/// Readable by others: the default.
pub const PUBLIC: u32 = 0o644;
/// Secrets and hashes: the owner only.
pub const PRIVATE: u32 = 0o600;

/// Wait for, and hold, an exclusive lock on `path` (created if missing). The
/// lock is released when the file is dropped.
pub fn lock(path: &Path) -> Result<File> {
    if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
        fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
    }
    let f = OpenOptions::new().create(true).append(true).read(true).open(path)
        .with_context(|| format!("opening {}", path.display()))?;
    // SAFETY: flock on a descriptor we own; released when `f` drops.
    if unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_EX) } != 0 {
        bail!("flock {}: {}", path.display(), std::io::Error::last_os_error());
    }
    Ok(f)
}

/// The lock beside a data file: `.<stem>.lock` in the same directory.
pub fn lock_path(path: &Path) -> PathBuf {
    let stem = path.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
    path.with_file_name(format!(".{stem}.lock"))
}

/// The file parsed, or `None` when it is missing or not what `T` reads.
pub fn read<T: DeserializeOwned>(path: &Path) -> Option<T> {
    fs::read_to_string(path).ok().and_then(|t| serde_json::from_str(&t).ok())
}

/// Replace `path` with `bytes`, whole or not at all: written to a temporary
/// file of this process and thread's own beside it, synced, then renamed over.
/// Two writers never share a temporary file, so neither can delete or
/// truncate the other's; the later rename wins.
pub fn write_atomic(path: &Path, bytes: &[u8], mode: u32) -> Result<()> {
    static SEQ: AtomicU64 = AtomicU64::new(0);
    let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
    let tmp = path.with_file_name(format!(".{name}.{}.{}.tmp", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed)));
    let written = (|| -> Result<()> {
        let mut f = OpenOptions::new().write(true).create_new(true).mode(mode).open(&tmp)
            .with_context(|| format!("creating {}", tmp.display()))?;
        f.write_all(bytes)?;
        f.sync_all()?;
        fs::rename(&tmp, path).with_context(|| format!("replacing {}", path.display()))
    })();
    if written.is_err() {
        let _ = fs::remove_file(&tmp);
    }
    written
}

/// `value` as pretty JSON, by [`write_atomic`].
pub fn write_json<T: Serialize + ?Sized>(path: &Path, value: &T, mode: u32) -> Result<()> {
    write_atomic(path, serde_json::to_string_pretty(value)?.as_bytes(), mode)
}

/// A JSON file, locked from `open` until dropped. `data` is what was read (or
/// `T::default()` if nothing readable was there); `save` writes it back.
pub struct Store<T> {
    _lock: File,
    path: PathBuf,
    mode: u32,
    /// The file as read: a save that would write it back the same is skipped.
    was: Option<String>,
    pub data: T,
}

impl<T: Serialize + DeserializeOwned + Default> Store<T> {
    /// Lock `path` (by its [`lock_path`]) and read it.
    pub fn open(path: impl Into<PathBuf>) -> Result<Self> {
        let path = path.into();
        let lock = lock_path(&path);
        Self::open_locked_by(path, &lock)
    }

    /// The same, locked by a file other than the usual one: a lock older than
    /// this module, which a running older binary still takes.
    pub fn open_locked_by(path: impl Into<PathBuf>, lock_file: &Path) -> Result<Self> {
        let path = path.into();
        let lock = lock(lock_file)?;
        // Only a missing file is an empty one. Any other failure to read (out of descriptors,
        // an I/O error) taken for empty had the next save write the default over what was there.
        let was = match fs::read_to_string(&path) {
            Ok(t) => Some(t),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
            Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
        };
        let data = match was.as_deref().map(serde_json::from_str::<T>) {
            Some(Ok(d)) => d,
            // Not what `T` reads: starts over, as it always did, but what was there is kept beside it.
            Some(Err(_)) if !was.as_deref().unwrap_or("").trim().is_empty() => {
                let aside = path.with_file_name(format!("{}.unreadable", path.file_name().unwrap_or_default().to_string_lossy()));
                let _ = fs::copy(&path, &aside);
                T::default()
            }
            _ => T::default(),
        };
        Ok(Self { _lock: lock, path, mode: PUBLIC, was, data })
    }

    /// Saved readable by its owner only.
    pub fn private(mut self) -> Self {
        self.mode = PRIVATE;
        self
    }

    /// Written only when it changed (or its mode must): most updates are a look that changes
    /// nothing — a runner's poll every few seconds asking for bots to start — and each wrote and
    /// synced the whole file.
    pub fn save(&self) -> Result<()> {
        use std::os::unix::fs::PermissionsExt;
        let text = serde_json::to_string_pretty(&self.data)?;
        let same_mode = || fs::metadata(&self.path).is_ok_and(|m| m.permissions().mode() & 0o777 == self.mode);
        if self.was.as_deref() == Some(text.as_str()) && same_mode() {
            return Ok(());
        }
        write_atomic(&self.path, text.as_bytes(), self.mode)
    }
}

/// Read, change and save `path` under its lock in one go; returns what `f` does.
pub fn update<T, R>(path: impl Into<PathBuf>, f: impl FnOnce(&mut T) -> Result<R>) -> Result<R>
where
    T: Serialize + DeserializeOwned + Default,
{
    let mut s = Store::<T>::open(path)?;
    let r = f(&mut s.data)?;
    s.save()?;
    Ok(r)
}

/// For a `Store<Value>` whose top level holds objects by name: make it an
/// object, and each of `keys` an object in it.
pub fn objects(v: &mut serde_json::Value, keys: &[&str]) {
    if !v.is_object() {
        *v = serde_json::json!({});
    }
    for k in keys {
        if !v[*k].is_object() {
            v[*k] = serde_json::json!({});
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeMap;

    fn dir(name: &str) -> PathBuf {
        let d = std::env::temp_dir().join(format!("midas-store-{name}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&d);
        fs::create_dir_all(&d).unwrap();
        d
    }

    #[test]
    fn concurrent_updates_lose_nothing_and_leave_no_temporary_files() {
        let d = dir("concurrent");
        let path = d.join("counts.json");
        let threads: Vec<_> = (0..8).map(|t| {
            let path = path.clone();
            std::thread::spawn(move || {
                for i in 0..25 {
                    update(&path, |m: &mut BTreeMap<String, u32>| {
                        m.insert(format!("{t}-{i}"), i);
                        Ok(())
                    }).unwrap();
                }
            })
        }).collect();
        threads.into_iter().for_each(|t| t.join().unwrap());
        let m: BTreeMap<String, u32> = read(&path).unwrap();
        assert_eq!(m.len(), 200, "every write kept");
        let left: Vec<_> = fs::read_dir(&d).unwrap().flatten()
            .map(|e| e.file_name().to_string_lossy().to_string()).filter(|n| n.ends_with(".tmp")).collect();
        assert!(left.is_empty(), "{left:?}");
    }

    #[test]
    fn a_save_that_changes_nothing_writes_nothing() {
        use std::os::unix::fs::MetadataExt;
        let d = dir("unchanged");
        let path = d.join("runs.json");
        update(&path, |m: &mut BTreeMap<String, u32>| { m.insert("a".into(), 1); Ok(()) }).unwrap();
        let ino = fs::metadata(&path).unwrap().ino();
        update(&path, |_: &mut BTreeMap<String, u32>| Ok(())).unwrap();
        assert_eq!(fs::metadata(&path).unwrap().ino(), ino, "an unchanged save renamed a new copy over");
        update(&path, |m: &mut BTreeMap<String, u32>| { m.insert("b".into(), 2); Ok(()) }).unwrap();
        assert_ne!(fs::metadata(&path).unwrap().ino(), ino);
        assert_eq!(read::<BTreeMap<String, u32>>(&path).unwrap().len(), 2);
        // The same data saved private still makes it private.
        Store::<BTreeMap<String, u32>>::open(&path).unwrap().private().save().unwrap();
        assert_eq!(fs::metadata(&path).unwrap().mode() & 0o777, PRIVATE);
    }

    #[test]
    fn a_private_store_is_its_owners_and_unreadable_data_starts_over() {
        let d = dir("private");
        let path = d.join("secrets.json");
        fs::write(&path, "not json").unwrap();
        let mut s = Store::<serde_json::Value>::open(&path).unwrap().private();
        assert!(s.data.is_null());
        objects(&mut s.data, &["a", "b"]);
        s.save().unwrap();
        drop(s);
        let mode = fs::metadata(&path).unwrap().permissions();
        assert_eq!(std::os::unix::fs::PermissionsExt::mode(&mode) & 0o777, 0o600);
        assert_eq!(read::<serde_json::Value>(&path).unwrap(), serde_json::json!({"a": {}, "b": {}}));
        assert_eq!(lock_path(&path), d.join(".secrets.lock"));
    }
}