crisol-core 1.2.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
//! Atomic file writes and versioned persistence helpers.
//!
//! A write goes to a hidden temporary sibling, is flushed with `sync_all`, and is then
//! renamed over the target. A crash leaves the old file or the new one, never a partial
//! write; a failed write leaves the old file untouched (CORE-DET-04).
//!
//! ```
//! use crisol_core::storage;
//! ```

#[cfg(feature = "threads")]
use std::io::Write;
use std::path::{Path, PathBuf};
#[cfg(feature = "threads")]
use std::sync::atomic::{AtomicU64, Ordering};

/// Why a file could not be written.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::storage::StorageError;
/// ```
pub enum StorageError {
    /// The path has no file name, so no sibling temporary can be made.
    #[error("the path has no file name")]
    NoFileName,
    /// The temporary file could not be created.
    #[error("could not create the temporary file: {0}")]
    Create(String),
    /// The bytes could not be written.
    #[error("could not write the temporary file: {0}")]
    Write(String),
    /// The bytes could not be flushed to disk.
    #[error("could not flush the temporary file: {0}")]
    Sync(String),
    /// The temporary file could not be renamed over the target.
    #[error("could not replace the target file: {0}")]
    Rename(String),
    /// The target could not be read.
    #[error("could not read the file: {0}")]
    Read(String),
}

/// Write `bytes` to `path` atomically.
///
/// The temporary file is a hidden sibling named after the target, the process id, and a
/// counter, so two writers never share it. It is opened with `create_new`, flushed with
/// `sync_all`, and renamed over the target. On Windows, where a rename cannot replace an
/// existing file, the old file is removed only after the complete temporary exists.
///
/// # Errors
/// When the temporary cannot be created, written, or flushed, or the rename fails. The
/// target is left as it was.
#[cfg(feature = "threads")]
/// # Example
///
/// ```
/// use crisol_core::storage::atomic_write;
/// ```
pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), StorageError> {
    atomic_write_with(path, bytes, |file| file.sync_all())
}

/// The write path with an injectable flush, so tests can fail after the bytes are on
/// disk but before the rename.
#[cfg(feature = "threads")]
fn atomic_write_with(
    path: &Path,
    bytes: &[u8],
    sync: impl FnOnce(&std::fs::File) -> std::io::Result<()>,
) -> Result<(), StorageError> {
    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let name = path
        .file_name()
        .and_then(|name| name.to_str())
        .ok_or(StorageError::NoFileName)?;
    // A hidden sibling named after the whole file name: `with_extension` made `a.json`
    // and `a.txt` share a temporary, and two writers in one process shared it too.
    // `process::id` is not implemented on wasm; one wasm instance is one process.
    let process: u32 = if cfg!(target_family = "wasm") {
        0
    } else {
        std::process::id()
    };
    let temp = path.with_file_name(format!(
        ".{name}.tmp-{process}-{}",
        COUNTER.fetch_add(1, Ordering::Relaxed)
    ));
    let written = (|| {
        // `create_new` refuses an existing file or symlink at the temporary path.
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&temp)
            .map_err(|error| StorageError::Create(error.to_string()))?;
        file.write_all(bytes)
            .map_err(|error| StorageError::Write(error.to_string()))?;
        sync(&file).map_err(|error| StorageError::Sync(error.to_string()))
    })();
    if let Err(error) = written {
        let _ = std::fs::remove_file(&temp);
        return Err(error);
    }
    // POSIX `rename` replaces the target atomically. Removing the old file first opened a
    // window in which a crash left no file at all.
    if let Err(error) = std::fs::rename(&temp, path) {
        // Windows refuses to rename over an existing file; fall back to remove + rename,
        // and keep the complete temporary file if that also fails.
        if path.exists() && std::fs::remove_file(path).is_ok() && std::fs::rename(&temp, path).is_ok() {
            return Ok(());
        }
        return Err(StorageError::Rename(error.to_string()));
    }
    Ok(())
}

/// Read a UTF-8 file, mapping the error to [`StorageError`].
///
/// # Errors
/// When the file cannot be read.
#[cfg(feature = "threads")]
/// # Example
///
/// ```
/// use crisol_core::storage::read_to_string;
/// ```
pub fn read_to_string(path: impl AsRef<Path>) -> Result<String, StorageError> {
    std::fs::read_to_string(path).map_err(|error| StorageError::Read(error.to_string()))
}

/// A version envelope around a serializable payload.
///
/// Versioned files store `{"version": N, "data": …}`. A reader rejects a version newer
/// than the latest it knows; older versions are migrated by the caller (CORE-DET-03).
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// # Example
///
/// ```
/// use crisol_core::storage::Versioned;
/// ```
pub struct Versioned<T> {
    /// The file format version.
    pub version: u32,
    /// The payload.
    pub data: T,
}

impl<T> Versioned<T> {
    /// A payload at the current version.
    pub fn new(version: u32, data: T) -> Self {
        Self { version, data }
    }
}

/// Check a stored version against the newest one the code writes.
///
/// # Errors
/// When `found` is newer than `latest`.
/// # Example
///
/// ```
/// use crisol_core::storage::check_version;
/// ```
pub fn check_version(found: u32, latest: u32) -> Result<(), StorageError> {
    if found > latest {
        Err(StorageError::Read(format!(
            "version {found} is newer than the supported version {latest}"
        )))
    } else {
        Ok(())
    }
}

/// A directory and the files a session keeps in it.
#[derive(Clone, Debug, PartialEq, Eq)]
/// # Example
///
/// ```
/// use crisol_core::storage::SessionPaths;
/// ```
pub struct SessionPaths {
    /// The session directory.
    pub directory: PathBuf,
}

impl SessionPaths {
    /// Paths under `directory`.
    pub fn new(directory: impl Into<PathBuf>) -> Self {
        Self {
            directory: directory.into(),
        }
    }

    /// The directory.
    pub fn directory(&self) -> &Path {
        &self.directory
    }

    /// `workspace.json`.
    pub fn workspace(&self) -> PathBuf {
        self.directory.join("workspace.json")
    }

    /// `stash.json`.
    pub fn stash(&self) -> PathBuf {
        self.directory.join("stash.json")
    }

    /// `journal.json`.
    pub fn journal(&self) -> PathBuf {
        self.directory.join("journal.json")
    }

    /// `keybindings.json`.
    pub fn keybindings(&self) -> PathBuf {
        self.directory.join("keybindings.json")
    }

    /// Create the directory, including parents.
    ///
    /// # Errors
    /// When the directory cannot be created.
    #[cfg(feature = "threads")]
    pub fn create(&self) -> Result<(), StorageError> {
        std::fs::create_dir_all(&self.directory).map_err(|error| StorageError::Write(error.to_string()))
    }
}

// spec: CORE-DET-04
#[cfg(all(test, feature = "threads"))]
mod tests {
    use super::*;

    fn directory(prefix: &str) -> PathBuf {
        let thread: String = std::thread::current()
            .name()
            .unwrap_or("test")
            .chars()
            .map(|character| {
                if character.is_ascii_alphanumeric() {
                    character
                } else {
                    '_'
                }
            })
            .collect();
        std::path::PathBuf::from("/tmp").join(format!("{prefix}-{thread}"))
    }

    #[test]
    fn a_write_replaces_the_file_and_leaves_no_temporary() {
        let directory = directory("crisol-storage");
        let _ = std::fs::remove_dir_all(&directory);
        std::fs::create_dir_all(&directory).expect("create");
        let path = directory.join("data.json");
        atomic_write(&path, b"one").expect("first");
        atomic_write(&path, b"two").expect("second");
        assert_eq!(std::fs::read(&path).expect("read"), b"two");
        assert_eq!(std::fs::read_dir(&directory).expect("dir").count(), 1);
        let _ = std::fs::remove_dir_all(directory);
    }

    #[test]
    fn a_failed_flush_keeps_the_previous_file_intact() {
        let directory = directory("crisol-storage-fail");
        let _ = std::fs::remove_dir_all(&directory);
        std::fs::create_dir_all(&directory).expect("create");
        let path = directory.join("data.json");
        atomic_write(&path, b"original").expect("original");
        let error = atomic_write_with(&path, b"replacement", |_| {
            Err(std::io::Error::other("simulated disk failure"))
        })
        .expect_err("flush fails");
        assert!(matches!(error, StorageError::Sync(_)));
        assert_eq!(std::fs::read(&path).expect("read"), b"original");
        assert_eq!(
            std::fs::read_dir(&directory).expect("dir").count(),
            1,
            "no temporary stays"
        );
        let _ = std::fs::remove_dir_all(directory);
    }

    #[test]
    fn a_path_without_a_file_name_is_rejected() {
        let error = atomic_write(Path::new("/"), b"x").expect_err("no name");
        assert_eq!(error, StorageError::NoFileName);
    }

    #[test]
    fn version_checks_accept_equal_and_older_and_reject_newer() {
        assert!(check_version(1, 1).is_ok());
        assert!(check_version(0, 1).is_ok());
        assert!(check_version(2, 1).is_err());
    }

    #[test]
    fn session_paths_have_stable_names() {
        let paths = SessionPaths::new("/tmp/session");
        assert_eq!(paths.workspace(), Path::new("/tmp/session/workspace.json"));
        assert_eq!(paths.stash(), Path::new("/tmp/session/stash.json"));
        assert_eq!(paths.journal(), Path::new("/tmp/session/journal.json"));
        assert_eq!(paths.keybindings(), Path::new("/tmp/session/keybindings.json"));
    }
}