use std::io::Read;
use std::path::Path;
pub const MISSING_STORE_ERROR_CODE: &str = "RED_DATA_MISSING";
pub const MISSING_STORE_EXIT_CODE: i32 = 66;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissingStoreReason {
PathMissing,
PathIsDirectory,
NotRegularFile,
EmptyFile,
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";
const PROBE_BYTES: usize = 2 * 4096;
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 => {
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();
reddb_file::native_store_magic_matches(head)
|| at(0).starts_with(EMBEDDED_SUPERBLOCK_MAGIC)
|| at(slot).starts_with(EMBEDDED_SUPERBLOCK_MAGIC)
|| reddb_file::database_header_magic_matches(at(0))
|| reddb_file::database_header_magic_matches(at(slot))
}
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()
)
}
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");
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}");
}
}