hayson-engine 0.14.0

Storage engine for hayson document databases — the embeddable core behind hayson-server, hayson-cli and hayson-browser
Documentation
use std::path::Path;

use crate::atomic::write_atomic;
use crate::errors::HaysonSchemaError;

use super::parse::parse_catalog;
use super::serialize::{catalog_document, serialize_catalog};
use super::types::Catalog;

#[cfg(unix)]
const PERMISSION_BITS: u32 = 0o777;

/// Parses the catalog's own serialized form back before it is allowed near the disk — a catalog
/// this build could write but not read back would leave the next open() unable to see its tables.
pub fn assert_catalog_readable(path: &Path, catalog: &Catalog) -> Result<(), HaysonSchemaError> {
    parse_catalog(&catalog_document(catalog)).map(|_| ()).map_err(|error| {
        HaysonSchemaError(format!(
            "refusing to write \"{}\": the catalog it would hold is one this build of hayson cannot read back — {}; nothing on disk was changed, and the declaration in the way has to go before the change can",
            path.display(),
            error.0,
        ))
    })
}

#[cfg(unix)]
fn permissions_of(path: &Path) -> std::io::Result<Option<u32>> {
    use std::os::unix::fs::PermissionsExt;
    match std::fs::metadata(path) {
        Ok(metadata) => Ok(Some(metadata.permissions().mode() & PERMISSION_BITS)),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(error),
    }
}

// NOTE: wasi has no permission bits at all; the host sandbox bounds fs access instead.
#[cfg(not(unix))]
fn permissions_of(_path: &Path) -> std::io::Result<Option<u32>> {
    Ok(None)
}

/// Writes the catalog atomically (`.tmp` → `fsync` → `rename`, via [`write_atomic`]), inheriting
/// the permissions of the file it replaces so `.tmp` is never briefly world-readable
/// (see `docs/format.md`, "Zapis, kolejność kluczy, uprawnienia"). Refuses first, via
/// [`assert_catalog_readable`], leaving the file on disk untouched.
pub fn write_catalog(path: &Path, catalog: &Catalog) -> Result<(), Box<dyn std::error::Error>> {
    assert_catalog_readable(path, catalog)?;
    let mode = permissions_of(path)?;
    let contents = serialize_catalog(catalog);
    write_atomic(path, contents.as_bytes(), mode)?;
    Ok(())
}

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

    use super::*;
    use crate::catalog::build::empty_catalog;
    use crate::catalog::types::CatalogLayout;

    #[test]
    fn writes_the_catalog_atomically() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hayson.json");
        let catalog = empty_catalog(CatalogLayout::Flat, 1_000);

        write_catalog(&path, &catalog).unwrap();

        let on_disk = fs::read_to_string(&path).unwrap();
        assert!(on_disk.contains("\"catalogVersion\": 2"));
        assert!(!path.with_extension("json.tmp").exists());

        let reparsed = parse_catalog(&serde_json::from_str(&on_disk).unwrap()).unwrap();
        assert_eq!(reparsed.tables, BTreeMap::new());
    }

    #[test]
    fn refuses_before_touching_disk_when_the_catalog_cannot_be_read_back() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hayson.json");
        fs::write(&path, "original").unwrap();

        let mut catalog = empty_catalog(CatalogLayout::Flat, 1_000);
        catalog.catalog_version = 3;

        assert!(write_catalog(&path, &catalog).is_err());
        assert_eq!(fs::read_to_string(&path).unwrap(), "original");
    }
}