use std::collections::HashSet;
use std::fmt::Display;
use std::fs::{self, File, Metadata};
use std::io::{BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::error::{Error, Result};
use crate::records::Records;
use crate::value::Value;
pub const FORMAT: &str = "legit-hamming-snapshot";
pub const VERSION: u32 = 1;
pub const MANIFEST: &str = "MANIFEST.json";
pub const MANIFEST_MAX_BYTES: u64 = 16 << 20;
pub const MAX_PARTS: usize = 65_536;
pub const PART_NAME_MAX: usize = 128;
const CHUNK: usize = 4096;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Manifest {
pub format: String,
pub version: u32,
pub width: u32,
pub ids: bool,
pub record_bytes: u32,
pub records: u64,
pub first_id: Option<u64>,
pub last_id: Option<u64>,
pub parts: Vec<Part>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub covers_seq: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Part {
pub file: String,
pub records: u64,
pub bytes: u64,
pub sha256: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Fault {
Parse,
TooLarge,
Format,
Width,
RecordBytes,
PartCount,
PartName,
PartTwice,
PartSize,
RecordCount,
IdsWithout,
IdRange,
Link,
NotFile,
DirLink,
NotDir,
FileSize,
Changed,
BigEndian,
}
impl Fault {
const ALL: [Self; 19] = [
Self::Parse,
Self::TooLarge,
Self::Format,
Self::Width,
Self::RecordBytes,
Self::PartCount,
Self::PartName,
Self::PartTwice,
Self::PartSize,
Self::RecordCount,
Self::IdsWithout,
Self::IdRange,
Self::Link,
Self::NotFile,
Self::DirLink,
Self::NotDir,
Self::FileSize,
Self::Changed,
Self::BigEndian,
];
pub(crate) const fn text(self) -> &'static str {
match self {
Self::Parse => "isn't a manifest: ",
Self::TooLarge => "is larger than a manifest may be: ",
Self::Format => "isn't a manifest of the format and version this crate reads: ",
Self::Width => "is of another width: ",
Self::RecordBytes => "gives a record size that isn't the format's: ",
Self::PartCount => "lists more parts than a snapshot may have: ",
Self::PartName => {
"names a part that isn't 1 to 128 of `A-Z`, `a-z`, `0-9`, `.`, `_` and `-`, not starting with `.`: "
}
Self::PartTwice => "lists one file as two parts: ",
Self::PartSize => "gives a part a size that isn't its records': ",
Self::RecordCount => "gives a record count that isn't its parts': ",
Self::IdsWithout => "gives a first or last id for records without ids",
Self::IdRange => "gives ids that aren't the ones its parts begin and end with: ",
Self::Link => "is a symbolic link; a snapshot holds files",
Self::NotFile => "isn't a file",
Self::DirLink => "is a symbolic link; a snapshot is a directory",
Self::NotDir => "isn't a directory",
Self::FileSize => "isn't the size the manifest says: ",
Self::Changed => "changed while it was opened; a snapshot's files never change",
Self::BigEndian => "can't be mapped on a big-endian CPU; load it",
}
}
pub(crate) fn of(reason: &str) -> Option<Self> {
Self::ALL.into_iter().find(|fault| reason.starts_with(fault.text()))
}
pub(crate) fn words(self) -> &'static str {
self.text().trim_end_matches(": ")
}
pub(crate) fn at(self, path: &Path, detail: impl Display) -> Error {
Error::snapshot(path, format!("{}{detail}", self.text()))
}
}
impl Manifest {
pub fn read<V: Value>(dir: &Path) -> Result<Self> {
let (path, manifest) = read_manifest(dir)?;
manifest.check::<V>(&path)?;
Ok(manifest)
}
pub(crate) fn check<V: Value>(&self, path: &Path) -> Result<()> {
if self.format != FORMAT || self.version != VERSION {
return Err(Fault::Format.at(
path,
format_args!(
"it is format `{}` version {}; this crate reads `{FORMAT}` version {VERSION}",
self.format, self.version
),
));
}
if self.width != V::BITS {
return Err(Fault::Width.at(
path,
format_args!("holds {}-bit values, not {}-bit", self.width, V::BITS),
));
}
if self.record_bytes != record_bytes::<V>(self.ids) {
return Err(Fault::RecordBytes.at(
path,
format_args!(
"says records are {} bytes; they're {}",
self.record_bytes,
record_bytes::<V>(self.ids)
),
));
}
if self.parts.len() > MAX_PARTS {
return Err(Fault::PartCount.at(path, format_args!("{} parts; at most {MAX_PARTS}", self.parts.len())));
}
let mut names = HashSet::with_capacity(self.parts.len());
let mut total = 0u64;
for (index, part) in self.parts.iter().enumerate() {
if !is_part_name(&part.file) {
return Err(Fault::PartName.at(path, format_args!("part {index} (from 0) is `{}`", part.file)));
}
if !names.insert(part.file.as_str()) {
return Err(Fault::PartTwice.at(path, format_args!("part {index} (from 0) is `{}` again", part.file)));
}
if part.records.checked_mul(u64::from(self.record_bytes)) != Some(part.bytes) {
return Err(Fault::PartSize.at(
path,
format_args!(
"says part `{}` has {} records in {} bytes",
part.file, part.records, part.bytes
),
));
}
total = total.saturating_add(part.records);
}
if total != self.records {
return Err(Fault::RecordCount.at(
path,
format_args!("says {} records, but its parts hold {total}", self.records),
));
}
if total > u64::from(u32::MAX) {
return Err(Error::TooManyRecords);
}
if !self.ids && (self.first_id.is_some() || self.last_id.is_some()) {
return Err(Fault::IdsWithout.at(path, ""));
}
Ok(())
}
#[must_use]
pub fn part_bytes(&self) -> u64 {
self.parts
.iter()
.fold(0u64, |total, part| total.saturating_add(part.bytes))
}
pub(crate) fn check_ids(&self, path: &Path, first: Option<u64>, last: Option<u64>) -> Result<()> {
if !self.ids || (first == self.first_id && last == self.last_id) {
return Ok(());
}
let show = |id: Option<u64>| id.map_or_else(|| "none".to_owned(), |id| format!("`{id}`"));
Err(Fault::IdRange.at(
path,
format_args!(
"{} to {}, but the parts hold {} to {}",
show(self.first_id),
show(self.last_id),
show(first),
show(last)
),
))
}
}
fn is_part_name(name: &str) -> bool {
(1..=PART_NAME_MAX).contains(&name.len())
&& !name.starts_with('.')
&& name
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
}
pub(crate) fn open_file(path: &Path) -> Result<(File, Metadata)> {
let named = fs::symlink_metadata(path).map_err(|error| Error::io(path, error))?;
if named.file_type().is_symlink() {
return Err(Fault::Link.at(path, ""));
}
if !named.is_file() {
return Err(Fault::NotFile.at(path, ""));
}
let file = File::open(path).map_err(|error| Error::io(path, error))?;
let opened = file.metadata().map_err(|error| Error::io(path, error))?;
if !opened.is_file() || identity(&opened) != identity(&named) {
return Err(Fault::Changed.at(path, ""));
}
Ok((file, opened))
}
#[cfg(unix)]
#[expect(
clippy::unnecessary_wraps,
reason = "the same signature as where the platform gives none"
)]
pub(crate) fn identity(metadata: &Metadata) -> Option<(u64, u64)> {
use std::os::unix::fs::MetadataExt;
Some((metadata.dev(), metadata.ino()))
}
#[cfg(not(unix))]
pub(crate) const fn identity(_: &Metadata) -> Option<(u64, u64)> {
None
}
pub(crate) fn read_manifest(dir: &Path) -> Result<(PathBuf, Manifest)> {
if let Ok(named) = fs::symlink_metadata(dir) {
if named.file_type().is_symlink() {
return Err(Fault::DirLink.at(dir, ""));
}
if !named.is_dir() {
return Err(Fault::NotDir.at(dir, ""));
}
}
let path = dir.join(MANIFEST);
let (file, metadata) = open_file(&path)?;
let too_large = || Fault::TooLarge.at(&path, format_args!("more than {MANIFEST_MAX_BYTES} bytes"));
if metadata.len() > MANIFEST_MAX_BYTES {
return Err(too_large());
}
let mut bytes = Vec::new();
file.take(MANIFEST_MAX_BYTES + 1)
.read_to_end(&mut bytes)
.map_err(|error| Error::io(&path, error))?;
if bytes.len() as u64 > MANIFEST_MAX_BYTES {
return Err(too_large());
}
let manifest = serde_json::from_slice(&bytes).map_err(|error| Fault::Parse.at(&path, error))?;
Ok((path, manifest))
}
#[must_use]
pub const fn record_bytes<V: Value>(ids: bool) -> u32 {
(V::WORDS as u32 + if ids { 1 } else { 0 }) * 8
}
pub fn write<V: Value>(dir: &Path, records: &Records<V>, records_per_part: usize) -> Result<Manifest> {
write_covering(dir, records, records_per_part, None)
}
pub fn write_covering<V: Value>(
dir: &Path,
records: &Records<V>,
records_per_part: usize,
covers_seq: Option<u64>,
) -> Result<Manifest> {
let manifest_path = dir.join(MANIFEST);
if manifest_path.exists() {
return Err(Error::snapshot(
manifest_path,
"already exists; a snapshot is never overwritten",
));
}
let per_part = records_per_part.max(1);
if records.len().div_ceil(per_part) > MAX_PARTS {
return Err(Error::snapshot(
manifest_path,
format!("would list more than {MAX_PARTS} parts; write more records a part"),
));
}
fs::create_dir_all(dir).map_err(|error| Error::io(dir, error))?;
let ids = records.has_ids();
let mut parts = Vec::new();
let mut start = 0;
while start < records.len() || (start == 0 && parts.is_empty()) {
let end = (start + per_part).min(records.len());
let file = format!("part-{:05}.bin", parts.len());
let path = dir.join(&file);
let mut writer = BufWriter::new(File::create(&path).map_err(|error| Error::io(&path, error))?);
let mut hasher = Sha256::new();
let mut buffer = Vec::with_capacity(record_bytes::<V>(ids) as usize);
for position in start..end {
buffer.clear();
if let Some(id) = records.id(position) {
buffer.extend_from_slice(&id.to_le_bytes());
}
records.value(position).write_le(&mut buffer);
hasher.update(&buffer);
writer.write_all(&buffer).map_err(|error| Error::io(&path, error))?;
}
writer
.into_inner()
.map_err(|error| Error::io(&path, error.into_error()))?
.sync_all()
.map_err(|error| Error::io(&path, error))?;
let count = (end - start) as u64;
parts.push(Part {
file,
records: count,
bytes: count * u64::from(record_bytes::<V>(ids)),
sha256: hex(&hasher.finalize()),
});
if end == records.len() {
break;
}
start = end;
}
let (first_id, last_id) = match records.ids() {
Some(ids) => (ids.first().copied(), ids.last().copied()),
None => (None, None),
};
let manifest = Manifest {
format: FORMAT.to_owned(),
version: VERSION,
width: V::BITS,
ids,
record_bytes: record_bytes::<V>(ids),
records: records.len() as u64,
first_id,
last_id,
parts,
covers_seq,
};
let text =
serde_json::to_string_pretty(&manifest).map_err(|error| Error::snapshot(&manifest_path, error.to_string()))?;
fs::write(&manifest_path, text + "\n").map_err(|error| Error::io(&manifest_path, error))?;
Ok(manifest)
}
pub(crate) fn check_parts(dir: &Path, manifest: &Manifest) -> Result<()> {
let mut files = HashSet::with_capacity(manifest.parts.len());
for (index, part) in manifest.parts.iter().enumerate() {
let path = dir.join(&part.file);
let metadata = fs::symlink_metadata(&path).map_err(|error| Error::io(&path, error))?;
if metadata.file_type().is_symlink() {
return Err(Fault::Link.at(&path, ""));
}
if !metadata.is_file() {
return Err(Fault::NotFile.at(&path, ""));
}
check_size(&path, &metadata, part)?;
if let Some(identity) = identity(&metadata)
&& !files.insert(identity)
{
return Err(Fault::PartTwice.at(
&dir.join(MANIFEST),
format_args!(
"part {index} (from 0), `{}`, is a part before it under another name",
part.file
),
));
}
}
Ok(())
}
fn check_size(path: &Path, metadata: &Metadata, part: &Part) -> Result<()> {
if metadata.len() == part.bytes {
Ok(())
} else {
Err(Fault::FileSize.at(
path,
format_args!("is {} bytes; the manifest says {}", metadata.len(), part.bytes),
))
}
}
pub(crate) fn open_part(dir: &Path, part: &Part) -> Result<(PathBuf, File)> {
let path = dir.join(&part.file);
let (file, metadata) = open_file(&path)?;
check_size(&path, &metadata, part)?;
Ok((path, file))
}
fn read_parts(
dir: &Path,
manifest: &Manifest,
read: &AtomicU64,
mut each: impl FnMut(&[u8]) -> Result<()>,
) -> Result<()> {
let record_bytes = manifest.record_bytes as usize;
let mut buffer = vec![0u8; record_bytes * CHUNK];
for part in &manifest.parts {
let (path, mut file) = open_part(dir, part)?;
let mut hasher = Sha256::new();
let mut left = part.records;
while left > 0 {
let count = usize::try_from(left).map_or(CHUNK, |left| left.min(CHUNK));
let bytes = &mut buffer[..count * record_bytes];
file.read_exact(bytes).map_err(|error| Error::io(&path, error))?;
read.fetch_add(bytes.len() as u64, Ordering::Relaxed);
hasher.update(&*bytes);
each(bytes)?;
left -= count as u64;
}
check_sum(&path, &part.sha256, &hasher.finalize())?;
}
Ok(())
}
pub fn load<V: Value>(dir: &Path) -> Result<Records<V>> {
load_counting(dir, &AtomicU64::new(0)).map(|(_, records)| records)
}
pub fn load_counting<V: Value>(dir: &Path, read: &AtomicU64) -> Result<(Manifest, Records<V>)> {
let (path, manifest) = read_manifest(dir)?;
manifest.check::<V>(&path)?;
let records = load_listed(dir, &manifest, read)?;
Ok((manifest, records))
}
pub(crate) fn load_listed<V: Value>(dir: &Path, manifest: &Manifest, read: &AtomicU64) -> Result<Records<V>> {
check_parts(dir, manifest)?;
let mut records = if manifest.ids {
Records::with_ids()
} else {
Records::values_only()
};
records.try_reserve(usize::try_from(manifest.records).unwrap_or(usize::MAX))?;
let record_bytes = manifest.record_bytes as usize;
read_parts(dir, manifest, read, |bytes| {
for record in bytes.chunks_exact(record_bytes) {
if manifest.ids {
let (id, value) = record.split_at(8);
records.push(
u64::from_le_bytes(id.try_into().expect("eight bytes")),
V::read_le(value),
)?;
} else {
records.push_value(V::read_le(record))?;
}
}
Ok(())
})?;
let ids = records.ids().unwrap_or_default();
manifest.check_ids(&dir.join(MANIFEST), ids.first().copied(), ids.last().copied())?;
Ok(records)
}
pub fn verify<V: Value>(dir: &Path) -> Result<Manifest> {
let (path, manifest) = read_manifest(dir)?;
verify_listed::<V>(dir, &path, manifest)
}
pub(crate) fn verify_listed<V: Value>(dir: &Path, path: &Path, manifest: Manifest) -> Result<Manifest> {
manifest.check::<V>(path)?;
check_parts(dir, &manifest)?;
let (mut first, mut previous): (Option<u64>, Option<u64>) = (None, None);
let record_bytes = manifest.record_bytes as usize;
read_parts(dir, &manifest, &AtomicU64::new(0), |bytes| {
if !manifest.ids {
return Ok(());
}
for record in bytes.chunks_exact(record_bytes) {
let id = u64::from_le_bytes(record[..8].try_into().expect("eight bytes"));
if let Some(previous) = previous
&& id <= previous
{
return Err(Error::IdOrder { previous, id });
}
first.get_or_insert(id);
previous = Some(id);
}
Ok(())
})?;
manifest.check_ids(path, first, previous)?;
Ok(manifest)
}
pub(crate) fn check_sum(path: &Path, expected: &str, actual: &[u8]) -> Result<()> {
let actual = hex(actual);
if actual == expected.to_ascii_lowercase() {
Ok(())
} else {
Err(Error::Checksum {
path: PathBuf::from(path),
expected: expected.to_owned(),
actual,
})
}
}
#[must_use]
pub fn sha256_hex(bytes: &[u8]) -> String {
hex(&Sha256::digest(bytes))
}
fn hex(bytes: &[u8]) -> String {
use std::fmt::Write;
bytes
.iter()
.fold(String::with_capacity(bytes.len() * 2), |mut out, byte| {
let _ = write!(out, "{byte:02x}");
out
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn no_fault_s_words_begin_another_s() {
for fault in Fault::ALL {
for other in Fault::ALL.into_iter().filter(|other| *other != fault) {
assert!(!other.text().starts_with(fault.text()), "{fault:?} begins {other:?}");
}
assert_eq!(Fault::of(&format!("{}detail", fault.text())), Some(fault));
}
}
}