reddb-io-server 1.46.3

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
Documentation
//! "Must exist" guard for `create_if_missing = false` opens.
//!
//! A database that is supposed to already exist (every start after the first
//! provisioning) must never be silently recreated empty. When the operator
//! passes `--no-create-if-missing` / `REDDB_NO_CREATE_IF_MISSING=true`, every
//! open path asks [`probe_existing_store`] before it initialises anything and
//! refuses with [`MISSING_STORE_ERROR_CODE`] when the data path does not hold
//! a store.
//!
//! "Holds a store" is decided from the data file alone (`--path`), never from
//! the files next to it: the data file must be a non-empty regular file whose
//! head carries one of the engine's store signatures. Leftovers such as a lone
//! certificate, a lock file, an empty WAL or an empty support directory do not
//! count, and neither does a directory passed as the data path.

use std::io::Read;
use std::path::Path;

/// Stable, greppable code carried at the start of the refusal message.
pub const MISSING_STORE_ERROR_CODE: &str = "RED_DATA_MISSING";

/// Process exit status `red server` uses for the refusal (sysexits
/// `EX_NOINPUT`: the input the process must open is not there).
pub const MISSING_STORE_EXIT_CODE: i32 = 66;

/// Why a data path does not hold a store.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissingStoreReason {
    /// Nothing exists at the data path.
    PathMissing,
    /// The data path is a directory, not a database file.
    PathIsDirectory,
    /// The data path is not a regular file (socket, device, dangling link...).
    NotRegularFile,
    /// The data file exists but holds no bytes.
    EmptyFile,
    /// The data file holds bytes but no store signature.
    NoStoreSignature,
}

impl MissingStoreReason {
    pub fn describe(self) -> &'static str {
        match self {
            Self::PathMissing => "the data file does not exist",
            Self::PathIsDirectory => "the data path is a directory, not a database file",
            Self::NotRegularFile => "the data path is not a regular file",
            Self::EmptyFile => "the data file is empty",
            Self::NoStoreSignature => "the data file holds no RedDB store signature",
        }
    }
}

const EMBEDDED_SUPERBLOCK_MAGIC: &[u8; 8] = b"RDBSBLK1";
/// Bytes read from the head of the data file: both superblock slots of the
/// embedded and paged layouts live inside the first 8 KiB.
const PROBE_BYTES: usize = 2 * 4096;

/// Decide whether `path` holds an existing store. Read-only: never creates,
/// truncates or locks anything.
pub fn probe_existing_store(path: &Path) -> Result<(), MissingStoreReason> {
    let metadata = match std::fs::metadata(path) {
        Ok(metadata) => metadata,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            // A dangling symlink is "something" the operator left there, but
            // it is still not a store.
            return Err(if std::fs::symlink_metadata(path).is_ok() {
                MissingStoreReason::NotRegularFile
            } else {
                MissingStoreReason::PathMissing
            });
        }
        Err(_) => return Err(MissingStoreReason::NotRegularFile),
    };
    if metadata.is_dir() {
        return Err(MissingStoreReason::PathIsDirectory);
    }
    if !metadata.is_file() {
        return Err(MissingStoreReason::NotRegularFile);
    }
    if metadata.len() == 0 {
        return Err(MissingStoreReason::EmptyFile);
    }
    let mut head = Vec::with_capacity(PROBE_BYTES);
    std::fs::File::open(path)
        .and_then(|file| file.take(PROBE_BYTES as u64).read_to_end(&mut head))
        .map_err(|_| MissingStoreReason::NotRegularFile)?;
    if has_store_signature(&head) {
        Ok(())
    } else {
        Err(MissingStoreReason::NoStoreSignature)
    }
}

fn has_store_signature(head: &[u8]) -> bool {
    let slot = reddb_file::EMBEDDED_RDB_SUPERBLOCK_SIZE as usize;
    let at = |offset: usize| head.get(offset..).unwrap_or_default();
    // Legacy whole-store binary dump.
    reddb_file::native_store_magic_matches(head)
        // Embedded single-file artifact: superblock copy 0 or 1.
        || at(0).starts_with(EMBEDDED_SUPERBLOCK_MAGIC)
        || at(slot).starts_with(EMBEDDED_SUPERBLOCK_MAGIC)
        // Native paged file: page 0 at the head (sidecar era) or the page-0
        // image held by either superblock slot.
        || reddb_file::database_header_magic_matches(at(0))
        || reddb_file::database_header_magic_matches(at(slot))
}

/// The one refusal message. Starts with [`MISSING_STORE_ERROR_CODE`] so the
/// control plane can match it whatever prefix the caller adds.
pub fn missing_store_error(path: &Path, reason: MissingStoreReason) -> String {
    format!(
        "{MISSING_STORE_ERROR_CODE}: refusing to create a new database at {}: {} and \
         --no-create-if-missing (REDDB_NO_CREATE_IF_MISSING) requires existing data",
        path.display(),
        reason.describe()
    )
}

/// `Err(message)` when `path` does not hold a store.
pub fn require_existing_store(path: &Path) -> Result<(), String> {
    probe_existing_store(path).map_err(|reason| missing_store_error(path, reason))
}

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

    #[test]
    fn missing_empty_directory_and_leftovers_are_refused() {
        let dir = tempfile::tempdir().unwrap();
        let data = dir.path().join("data.rdb");
        assert_eq!(
            probe_existing_store(&data),
            Err(MissingStoreReason::PathMissing)
        );
        assert_eq!(
            probe_existing_store(dir.path()),
            Err(MissingStoreReason::PathIsDirectory)
        );
        std::fs::write(&data, b"").unwrap();
        assert_eq!(
            probe_existing_store(&data),
            Err(MissingStoreReason::EmptyFile)
        );
        std::fs::write(&data, b"-----BEGIN CERTIFICATE-----\n").unwrap();
        assert_eq!(
            probe_existing_store(&data),
            Err(MissingStoreReason::NoStoreSignature)
        );
        std::fs::write(&data, vec![0u8; 8192]).unwrap();
        assert_eq!(
            probe_existing_store(&data),
            Err(MissingStoreReason::NoStoreSignature)
        );
    }

    #[test]
    fn store_signatures_are_accepted() {
        let dir = tempfile::tempdir().unwrap();
        let data = dir.path().join("data.rdb");
        // Paged page 0 in superblock slot 1 only.
        let mut paged = vec![0u8; 8192];
        reddb_file::init_database_header_page(&mut paged[4096..], 1).unwrap();
        std::fs::write(&data, &paged).unwrap();
        assert_eq!(probe_existing_store(&data), Ok(()));

        let mut embedded = vec![0u8; 8192];
        embedded[..8].copy_from_slice(EMBEDDED_SUPERBLOCK_MAGIC);
        std::fs::write(&data, &embedded).unwrap();
        assert_eq!(probe_existing_store(&data), Ok(()));

        std::fs::write(&data, reddb_file::STORE_MAGIC).unwrap();
        assert_eq!(probe_existing_store(&data), Ok(()));
    }

    #[test]
    fn refusal_message_carries_the_stable_code() {
        let message = require_existing_store(Path::new("/nonexistent/data.rdb")).unwrap_err();
        assert!(message.starts_with("RED_DATA_MISSING: "), "{message}");
        assert!(message.contains("--no-create-if-missing"), "{message}");
    }
}