use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard};
use anyhow::{anyhow, bail, ensure, Result};
use arrow::datatypes::Schema;
use arrow::ipc::writer::StreamWriter;
use crate::archive::ZnippyReader;
use crate::codec::CompressCtx;
use crate::index::{data_subindex_schema, ChunkLoc, ZNIPPY_LINKS_MODULE, ZNIPPY_STACK_MODULE};
use crate::meta_sink::{ArchiveMetaSink, ArrowIpcSink, ReservedSection, ReservedSectionBuilder};
use crate::meta_sink_append::{base_batch_from_rows, write_blobs};
use crate::rows::{
fill, fits_v1, own_bytes_end, rows_batch, rows_schema, sync_dir_of, Blob, BlobRef, Group,
Lookup, RowEntry, RowIndex, SegmentCursor, Was, STREAM_PIECE,
};
use crate::stack::{LayerInfo, StackSection};
const JOURNAL_INFIX: &str = ".hot.";
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct HotAppendReport {
pub rows_added: u64,
pub rows_replaced: u64,
pub blob_append_offset: u64,
pub blob_bytes_added: u64,
pub journal_bytes_added: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct HotCommitReport {
pub rows_added: u64,
pub rows_replaced: u64,
pub journal_bytes_added: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HotSealReport {
pub archive: PathBuf,
pub rows_sealed: u64,
pub segments_removed: usize,
pub journal_bytes_reclaimed: u64,
pub sealed_total_bytes: u64,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Expect {
pub size: Option<u64>,
pub blake3: Option<[u8; 32]>,
}
#[derive(Debug, Clone)]
pub struct Staged {
owner: Arc<()>,
at: BlobRef,
size: u64,
blake3: [u8; 32],
}
impl Staged {
pub fn size(&self) -> u64 {
self.size
}
pub fn blake3(&self) -> [u8; 32] {
self.blake3
}
pub fn location(&self) -> &BlobRef {
&self.at
}
}
#[derive(Debug, Clone)]
pub enum HotOp {
Put {
group: Group,
name: String,
staged: Staged,
},
Link {
group: Group,
name: String,
to: BlobRef,
},
End { group: Group, name: String },
}
pub struct HotArchive {
archive: PathBuf,
blobs: Arc<File>,
index: RwLock<RowIndex>,
blob_end: AtomicU64,
writer: Mutex<HotWriter>,
fsyncs: AtomicU64,
policy: crate::SkipPolicy,
layer: Option<LayerInfo>,
token: Arc<()>,
}
struct HotWriter {
blob_end: u64,
journal: Journal,
ctx: CompressCtx,
}
struct Journal {
w: StreamWriter<File>,
schema: Arc<Schema>,
v2: bool,
number: u32,
len: u64,
}
impl Journal {
fn schema_for(v2: bool, layer: Option<&LayerInfo>) -> Arc<Schema> {
if v2 {
rows_schema(&layer.map(|l| l.to_metadata()).unwrap_or_default())
} else {
data_subindex_schema()
}
}
fn create(archive: &Path, number: u32, v2: bool, layer: Option<&LayerInfo>) -> Result<Self> {
let path = segment_path(archive, number);
let f = File::create(&path)
.map_err(|e| anyhow!("hot: create journal segment {}: {e}", path.display()))?;
let j = Self::start(f, number, v2, layer)?;
sync_dir_of(&path);
Ok(j)
}
fn create_seeded(
archive: &Path,
number: u32,
v2: bool,
layer: Option<&LayerInfo>,
entries: &[RowEntry],
) -> Result<Self> {
let path = segment_path(archive, number);
let mut tmp = path.as_os_str().to_os_string();
tmp.push(".seed");
let tmp = PathBuf::from(tmp);
let f = File::create(&tmp)
.map_err(|e| anyhow!("hot: create journal seed {}: {e}", tmp.display()))?;
let mut j = Self::start(f, number, v2, layer)?;
if !entries.is_empty() {
let batch = rows_batch(&j.schema, entries)?;
j.w.write(&batch)
.map_err(|e| anyhow!("hot: seeding journal: {e}"))?;
j.w.flush()
.map_err(|e| anyhow!("hot: journal flush: {e}"))?;
}
j.w.get_ref()
.sync_all()
.map_err(|e| anyhow!("hot: journal fsync: {e}"))?;
j.len = j.w.get_ref().metadata()?.len();
std::fs::rename(&tmp, &path)
.map_err(|e| anyhow!("hot: placing journal segment {}: {e}", path.display()))?;
sync_dir_of(&path);
Ok(j)
}
fn start(f: File, number: u32, v2: bool, layer: Option<&LayerInfo>) -> Result<Self> {
let schema = Self::schema_for(v2, layer);
let opts = arrow::ipc::writer::IpcWriteOptions::try_new(
JOURNAL_ALIGNMENT,
false,
arrow::ipc::MetadataVersion::V5,
)
.map_err(|e| anyhow!("hot: journal write options: {e}"))?;
let w = StreamWriter::try_new_with_options(f, schema.as_ref(), opts)
.map_err(|e| anyhow!("hot: journal schema: {e}"))?;
let len = w.get_ref().metadata().map(|m| m.len()).unwrap_or(0);
Ok(Self {
w,
schema,
v2,
number,
len,
})
}
}
struct Loaded {
index: RowIndex,
own_end: u64,
seed: Option<Vec<RowEntry>>,
next_segment: u32,
needs_v2: bool,
}
impl HotArchive {
pub fn open(archive: &Path, level: i32, policy: crate::SkipPolicy) -> Result<Self> {
Self::open_inner(archive, level, policy, None)
}
pub(crate) fn open_layer(
path: &Path,
level: i32,
policy: crate::SkipPolicy,
layer: LayerInfo,
) -> Result<Self> {
Self::open_inner(path, level, policy, Some(layer))
}
fn open_inner(
archive: &Path,
level: i32,
policy: crate::SkipPolicy,
layer: Option<LayerInfo>,
) -> Result<Self> {
let archive = archive.to_path_buf();
let loaded = Self::load(&archive, layer.as_ref())?;
let v2 = layer.is_some() || loaded.needs_v2;
let journal = match &loaded.seed {
Some(entries) => {
Journal::create_seeded(&archive, loaded.next_segment, v2, layer.as_ref(), entries)?
}
None => Journal::create(&archive, loaded.next_segment, v2, layer.as_ref())?,
};
let blob_end = loaded.own_end;
let blobs = Arc::new(
std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&archive)
.map_err(|e| anyhow!("hot: open {} : {e}", archive.display()))?,
);
if blobs.metadata()?.len() > blob_end {
blobs.set_len(blob_end)?;
blobs.sync_all()?;
}
Ok(Self {
archive,
blobs,
blob_end: AtomicU64::new(blob_end),
index: RwLock::new(loaded.index),
writer: Mutex::new(HotWriter {
blob_end,
journal,
ctx: CompressCtx::new(level)?,
}),
policy,
fsyncs: AtomicU64::new(0),
layer,
token: Arc::new(()),
})
}
fn load(archive: &Path, layer: Option<&LayerInfo>) -> Result<Loaded> {
let mut segments = journal_segments(archive)?;
let sealed_manifest = || {
(archive.is_file())
.then(|| crate::index::read_znippy_full_manifest(archive).ok())
.flatten()
};
if segments.first().is_some_and(|(n, _)| *n != 0) && layer.is_none() {
ensure!(
sealed_manifest().is_some(),
"hot: {} has journal segments from {} on, segment 0 is gone and the file is \
not sealed: rows are lost; refusing to cut the file",
archive.display(),
segments[0].0
);
for (_, seg) in &segments {
std::fs::remove_file(seg)
.map_err(|e| anyhow!("hot: removing journal {}: {e}", seg.display()))?;
}
sync_dir_of(archive);
segments.clear();
}
let mut index = RowIndex::default();
let mut own_end = 0u64;
let mut needs_v2 = false;
if !segments.is_empty() {
let mut found: Option<LayerInfo> = None;
let mut plain = false;
for (n, p) in &segments {
let mut c = SegmentCursor::new(*n, p.clone());
let (entries, _) = c.read_more(true)?;
if let Some(m) = &c.metadata {
match LayerInfo::from_metadata(m)? {
Some(l) => {
ensure!(
found.is_none_or(|f| f == l),
"hot: the journal segments of {} name two places in a stack",
archive.display()
);
found = Some(l);
}
None => plain = true,
}
}
needs_v2 |= !fits_v1(&entries);
for e in entries {
own_end = own_end.max(own_bytes_end(&e));
index.apply(e);
}
}
match (layer, found) {
(None, Some(_)) => bail!(
"hot: {} is a stack layer; it is opened through its stack",
archive.display()
),
(Some(want), Some(got)) => ensure!(
*want == got,
"hot: {} is layer {:?}, not {:?}",
archive.display(),
got,
want
),
(Some(_), None) => ensure!(
!plain,
"hot: {} has a plain journal where a stack layer was asked for",
archive.display()
),
(None, None) => {}
}
let next_segment = segments.last().map(|(n, _)| n + 1).unwrap_or(0);
return Ok(Loaded {
index,
own_end,
seed: None,
next_segment,
needs_v2,
});
}
let Some((entries, _)) = sealed_manifest() else {
return Ok(Loaded {
index,
own_end,
seed: None,
next_segment: 0,
needs_v2,
});
};
ensure!(
layer.is_none(),
"hot: {} is sealed but has no journal; a sealed layer is never reopened hot",
archive.display()
);
ensure!(
!(entries.iter())
.any(|e| e.module_name == ZNIPPY_STACK_MODULE
|| e.module_name == ZNIPPY_LINKS_MODULE),
"hot: {} is a stack's file; a stack's seal is never consumed — write a layer through \
StackWriter",
archive.display()
);
let data: Vec<&crate::index::ManifestEntry> = entries
.iter()
.filter(|e| !crate::index::is_reserved_module(&e.module_name))
.collect();
let seed = if data.iter().all(|e| e.pkg_type == 0 && e.repo.is_empty()) {
let (paths, locs) = crate::meta_sink_append::recover_rows(archive, &entries)?;
entries_by_name(Group::default(), paths, locs)
} else {
let file = File::open(archive)?;
let sealed = crate::stack::load_sealed(&file)?;
let mut out = Vec::new();
for g in sealed.index.groups() {
for (name, slot) in sealed.index.slots(g) {
out.push(RowEntry {
group: g.clone(),
name: name.to_string(),
slot: slot.clone(),
});
}
}
out
};
needs_v2 = !fits_v1(&seed);
for e in &seed {
own_end = own_end.max(own_bytes_end(e));
index.apply(e.clone());
}
Ok(Loaded {
index,
own_end,
seed: Some(seed),
next_segment: 0,
needs_v2,
})
}
pub fn is_hot(archive: &Path) -> bool {
journal_segments(archive)
.map(|s| !s.is_empty())
.unwrap_or(false)
}
pub fn archive(&self) -> &Path {
&self.archive
}
pub fn rows(&self) -> u64 {
self.index_read().live()
}
pub fn has_rows(&self) -> bool {
self.index_read().has_rows()
}
pub fn blob_end(&self) -> u64 {
self.blob_end.load(Ordering::Acquire)
}
pub fn fsyncs(&self) -> u64 {
self.fsyncs.load(Ordering::Relaxed)
}
pub fn layer(&self) -> Option<LayerInfo> {
self.layer
}
fn index_read(&self) -> RwLockReadGuard<'_, RowIndex> {
self.index.read().unwrap_or_else(|e| e.into_inner())
}
pub(crate) fn index_snapshot(&self) -> RowIndex {
self.index_read().clone()
}
pub(crate) fn blob_file(&self) -> Arc<File> {
Arc::clone(&self.blobs)
}
pub fn lookup(&self, group: &Group, name: &str) -> Lookup {
self.index_read().lookup(group, name)
}
pub fn get(&self, group: &Group, name: &str) -> Option<Blob> {
match self.lookup(group, name) {
Lookup::Live(b) if b.pack.is_none() => Some(Blob::new(Arc::clone(&self.blobs), b)),
_ => None,
}
}
pub fn names(&self, group: &Group) -> Vec<String> {
self.index_read().names(group)
}
pub fn groups(&self) -> Vec<Group> {
self.index_read().groups().to_vec()
}
pub fn append(&self, files: &[(String, Vec<u8>)]) -> Result<HotAppendReport> {
self.append_in(&Group::default(), files)
}
pub fn append_in(&self, group: &Group, files: &[(String, Vec<u8>)]) -> Result<HotAppendReport> {
group.check()?;
if files.is_empty() {
return Ok(HotAppendReport {
blob_append_offset: self.blob_end(),
..Default::default()
});
}
let mut guard = self.writer.lock().unwrap_or_else(|e| e.into_inner());
let w = &mut *guard;
let blob_append_offset = w.blob_end;
let (paths, locs, cursor) =
write_blobs(&self.blobs, w.blob_end, files, &mut w.ctx, self.policy)?;
let blob_bytes_added = cursor - blob_append_offset;
self.blobs.sync_all()?;
self.fsyncs.fetch_add(1, Ordering::Relaxed);
w.blob_end = cursor;
self.blob_end.store(cursor, Ordering::Release);
let entries: Vec<RowEntry> = (paths.into_iter().zip(locs))
.map(|(name, loc)| RowEntry {
group: group.clone(),
name,
slot: Some(BlobRef {
pack: None,
chunks: vec![loc],
}),
})
.collect();
let (rows_added, journal_bytes_added) = self.write_journal(w, &entries)?;
let rows_replaced = self.publish(entries);
Ok(HotAppendReport {
rows_added,
rows_replaced,
blob_append_offset,
blob_bytes_added,
journal_bytes_added,
})
}
pub fn stage_from(&self, name: &str, body: &mut dyn Read, expect: &Expect) -> Result<Staged> {
let mut guard = self.writer.lock().unwrap_or_else(|e| e.into_inner());
let w = &mut *guard;
let (staged, end) = self.write_body(w, w.blob_end, name, body, expect)?;
self.blobs.sync_all()?;
self.fsyncs.fetch_add(1, Ordering::Relaxed);
w.blob_end = end;
self.blob_end.store(end, Ordering::Release);
Ok(staged)
}
pub fn stage_all(&self, bodies: &[(&str, &[u8])]) -> Result<Vec<Staged>> {
if bodies.is_empty() {
return Ok(Vec::new());
}
let mut guard = self.writer.lock().unwrap_or_else(|e| e.into_inner());
let w = &mut *guard;
let mut cursor = w.blob_end;
let mut out = Vec::with_capacity(bodies.len());
for (name, bytes) in bodies {
let (staged, end) = self.write_body(w, cursor, name, &mut &bytes[..], &Expect::default())?;
out.push(staged);
cursor = end;
}
self.blobs.sync_all()?;
self.fsyncs.fetch_add(1, Ordering::Relaxed);
w.blob_end = cursor;
self.blob_end.store(cursor, Ordering::Release);
Ok(out)
}
fn write_body(
&self,
w: &mut HotWriter,
start: u64,
name: &str,
body: &mut dyn Read,
expect: &Expect,
) -> Result<(Staged, u64)> {
let mut piece = vec![0u8; STREAM_PIECE];
let mut n = fill(body, &mut piece)?;
let raw = self.policy.skip_by_path(Path::new(name))
|| self
.policy
.skip_by_bytes(&piece[..n.min(crate::SNIFF_PREFIX_LEN)]);
let mut whole = blake3::Hasher::new();
let mut cursor = start;
let mut size = 0u64;
let mut chunks: Vec<ChunkLoc> = Vec::new();
let mut frame: Vec<u8> = Vec::new();
loop {
if n == 0 {
break;
}
let bytes = &piece[..n];
whole.update(bytes);
if raw {
self.blobs.write_all_at(bytes, cursor)?;
cursor += n as u64;
} else {
w.ctx.compress_into(bytes, &mut frame)?;
let (on_disk, compressed): (&[u8], bool) = if frame.len() < n {
(&frame, true)
} else {
(bytes, false)
};
self.blobs.write_all_at(on_disk, cursor)?;
chunks.push(ChunkLoc {
chunk_seq: u32::try_from(chunks.len())?,
fdata_offset: size,
blob_offset: cursor,
blob_size: on_disk.len() as u64,
uncompressed_size: n as u64,
compressed,
checksum: *blake3::hash(bytes).as_bytes(),
});
cursor += on_disk.len() as u64;
}
size += n as u64;
n = fill(body, &mut piece)?;
}
let digest = *whole.finalize().as_bytes();
if raw || chunks.is_empty() {
chunks = vec![ChunkLoc {
chunk_seq: 0,
fdata_offset: 0,
blob_offset: start,
blob_size: size,
uncompressed_size: size,
compressed: false,
checksum: digest,
}];
}
if let Some(want) = expect.size {
ensure!(
want == size,
"the body is {size} bytes, {want} were expected"
);
}
if let Some(want) = expect.blake3 {
ensure!(want == digest, "the body's BLAKE3 is not the one expected");
}
let staged = Staged {
owner: Arc::clone(&self.token),
at: BlobRef { pack: None, chunks },
size,
blake3: digest,
};
Ok((staged, cursor))
}
pub fn commit(&self, ops: Vec<HotOp>) -> Result<HotCommitReport> {
if ops.is_empty() {
return Ok(HotCommitReport::default());
}
let mut guard = self.writer.lock().unwrap_or_else(|e| e.into_inner());
let w = &mut *guard;
let mut entries = Vec::with_capacity(ops.len());
for op in ops {
let e = match op {
HotOp::Put {
group,
name,
staged,
} => {
ensure!(
Arc::ptr_eq(&staged.owner, &self.token),
"{name}: the body was staged by another archive"
);
RowEntry {
group,
name,
slot: Some(staged.at),
}
}
HotOp::Link { group, name, to } => {
self.check_ref(&to, w.blob_end)?;
RowEntry {
group,
name,
slot: Some(to),
}
}
HotOp::End { group, name } => RowEntry {
group,
name,
slot: None,
},
};
e.group.check()?;
entries.push(e);
}
let (rows_added, journal_bytes_added) = self.write_journal(w, &entries)?;
let rows_replaced = self.publish(entries);
Ok(HotCommitReport {
rows_added,
rows_replaced,
journal_bytes_added,
})
}
fn check_ref(&self, to: &BlobRef, blob_end: u64) -> Result<()> {
ensure!(!to.chunks.is_empty(), "a link names no bytes");
match to.pack {
None => ensure!(
to.end() <= blob_end,
"a link names bytes up to {} past the blob end {blob_end}",
to.end()
),
Some(p) => {
let Some(l) = self.layer else {
bail!("a plain archive names no other file's bytes");
};
ensure!(
p < l.generation,
"layer {} cannot name bytes of generation {p}",
l.generation
);
}
}
Ok(())
}
pub fn append_from(
&self,
group: &Group,
name: &str,
body: &mut dyn Read,
expect: &Expect,
) -> Result<Staged> {
let staged = self.stage_from(name, body, expect)?;
self.commit(vec![HotOp::Put {
group: group.clone(),
name: name.to_string(),
staged: staged.clone(),
}])?;
Ok(staged)
}
pub fn link(
&self,
group: &Group,
name: &str,
from_group: &Group,
from_name: &str,
) -> Result<()> {
let Lookup::Live(to) = self.lookup(from_group, from_name) else {
bail!("{from_name}: no live name to link to");
};
self.commit(vec![HotOp::Link {
group: group.clone(),
name: name.to_string(),
to,
}])?;
Ok(())
}
pub fn end(&self, group: &Group, name: &str) -> Result<()> {
self.commit(vec![HotOp::End {
group: group.clone(),
name: name.to_string(),
}])?;
Ok(())
}
fn write_journal(&self, w: &mut HotWriter, entries: &[RowEntry]) -> Result<(u64, u64)> {
if !w.journal.v2 && !fits_v1(entries) {
w.journal = Journal::create(
&self.archive,
w.journal.number + 1,
true,
self.layer.as_ref(),
)?;
}
let batch = rows_batch(&w.journal.schema, entries)?;
let wrote = (|| -> Result<u64> {
w.journal
.w
.write(&batch)
.map_err(|e| anyhow!("hot: journal write: {e}"))?;
w.journal
.w
.flush()
.map_err(|e| anyhow!("hot: journal flush: {e}"))?;
w.journal
.w
.get_ref()
.sync_all()
.map_err(|e| anyhow!("hot: journal fsync: {e}"))?;
Ok(w.journal.w.get_ref().metadata()?.len())
})();
let len = match wrote {
Ok(len) => len,
Err(e) => {
if let Ok(j) = Journal::create(
&self.archive,
w.journal.number + 1,
w.journal.v2,
self.layer.as_ref(),
) {
w.journal = j;
}
return Err(e);
}
};
self.fsyncs.fetch_add(1, Ordering::Relaxed);
let added = len - w.journal.len;
w.journal.len = len;
Ok((batch.num_rows() as u64, added))
}
fn publish(&self, entries: Vec<RowEntry>) -> u64 {
let mut idx = self.index.write().unwrap_or_else(|e| e.into_inner());
(entries.into_iter())
.filter(|e| idx.set(e.group.clone(), e.name.clone(), e.slot.clone()) == Was::Live)
.count() as u64
}
pub fn seal(self, reserved: Option<ReservedSectionBuilder>) -> Result<HotSealReport> {
self.seal_with(reserved, true)
}
pub(crate) fn seal_with(
self,
reserved: Option<ReservedSectionBuilder>,
remove_journal: bool,
) -> Result<HotSealReport> {
let Self {
archive,
blobs,
index,
writer,
layer,
..
} = self;
let index = index.into_inner().unwrap_or_else(|e| e.into_inner());
let HotWriter {
blob_end, journal, ..
} = writer.into_inner().unwrap_or_else(|e| e.into_inner());
drop(journal);
let mut sink = ArrowIpcSink::new(Arc::clone(&blobs), blob_end);
let mut rows_sealed = 0u64;
let mut links: Vec<RowEntry> = Vec::new();
let mut groups: Vec<(Group, Vec<String>, Vec<ChunkLoc>)> = Vec::new();
for g in index.groups() {
let (mut paths, mut locs) = (Vec::new(), Vec::new());
for (name, slot) in index.slots(g) {
match slot {
Some(b) if b.pack.is_none() => {
rows_sealed += 1;
for c in &b.chunks {
paths.push(name.to_string());
locs.push(c.clone());
}
}
Some(_) => links.push(RowEntry {
group: g.clone(),
name: name.to_string(),
slot: slot.clone(),
}),
None if layer.is_some() => links.push(RowEntry {
group: g.clone(),
name: name.to_string(),
slot: None,
}),
None => {}
}
}
if !paths.is_empty() {
groups.push((g.clone(), paths, locs));
}
}
let mut mine: Vec<ReservedSection> = Vec::new();
if let Some(l) = layer {
if !links.is_empty() {
let schema = rows_schema(&HashMap::new());
let batch = rows_batch(&schema, &links)?;
mine.push(ReservedSection::arrow(
ZNIPPY_LINKS_MODULE,
schema,
vec![batch],
));
}
mine.push(ReservedSection::raw(
ZNIPPY_STACK_MODULE,
StackSection::layer(l).encode(),
));
}
if let Some(b) = compose_reserved(reserved, mine) {
sink = sink.with_reserved_builder(b);
}
for (g, paths, locs) in &groups {
let batch = base_batch_from_rows(paths, locs)?;
sink.push_subindex(data_subindex_schema().as_ref(), &[batch], g.key())?;
}
let sealed_total_bytes = Box::new(sink).finish()?;
if blobs.metadata()?.len() > sealed_total_bytes {
blobs.set_len(sealed_total_bytes)?;
blobs.sync_all()?;
}
let mut segments_removed = 0usize;
let mut journal_bytes_reclaimed = 0u64;
if remove_journal {
let segments = journal_segments(&archive)?;
for (_, seg) in &segments {
journal_bytes_reclaimed += std::fs::metadata(seg).map(|m| m.len()).unwrap_or(0);
std::fs::remove_file(seg)
.map_err(|e| anyhow!("hot: removing journal {}: {e}", seg.display()))?;
}
segments_removed = segments.len();
sync_dir_of(&archive);
}
Ok(HotSealReport {
archive,
rows_sealed,
segments_removed,
journal_bytes_reclaimed,
sealed_total_bytes,
})
}
}
pub(crate) fn compose_reserved(
reserved: Option<ReservedSectionBuilder>,
mine: Vec<ReservedSection>,
) -> Option<ReservedSectionBuilder> {
if reserved.is_none() && mine.is_empty() {
return None;
}
Some(Box::new(move |view: &crate::meta_sink::LookupView<'_>| {
let mut out = match reserved {
Some(b) => b(view)?,
None => Vec::new(),
};
for s in &out {
ensure!(
s.module_name != ZNIPPY_STACK_MODULE && s.module_name != ZNIPPY_LINKS_MODULE,
"{} is written by the archive itself",
s.module_name
);
}
out.extend(mine);
Ok(out)
}))
}
fn entries_by_name(group: Group, paths: Vec<String>, locs: Vec<ChunkLoc>) -> Vec<RowEntry> {
let mut at: HashMap<String, usize> = HashMap::with_capacity(paths.len());
let mut out: Vec<RowEntry> = Vec::new();
for (name, loc) in paths.into_iter().zip(locs) {
match at.get(&name) {
Some(&i) => {
let b = out[i].slot.as_mut().expect("built live");
b.chunks.retain(|c| c.fdata_offset != loc.fdata_offset);
b.chunks.push(loc);
}
None => {
at.insert(name.clone(), out.len());
out.push(RowEntry {
group: group.clone(),
name,
slot: Some(BlobRef {
pack: None,
chunks: vec![loc],
}),
});
}
}
}
for e in &mut out {
if let Some(b) = &mut e.slot {
b.chunks.sort_by_key(|c| c.fdata_offset);
for (i, c) in b.chunks.iter_mut().enumerate() {
c.chunk_seq = u32::try_from(i).unwrap_or(u32::MAX);
}
}
}
out
}
impl ZnippyReader for HotArchive {
fn list_files(&self) -> Result<Vec<String>> {
Ok(self.names(&Group::default()))
}
fn contains(&self, relative_path: &str) -> bool {
matches!(
self.lookup(&Group::default(), relative_path),
Lookup::Live(_)
)
}
fn file_size(&self, relative_path: &str) -> Option<u64> {
match self.lookup(&Group::default(), relative_path) {
Lookup::Live(b) => Some(b.size()),
_ => None,
}
}
fn extract_file(&self, relative_path: &str) -> Result<Vec<u8>> {
(self.get(&Group::default(), relative_path))
.ok_or_else(|| anyhow!("file not found in archive: {relative_path}"))?
.read()
}
fn checksum(&self, relative_path: &str) -> Option<[u8; 32]> {
match self.lookup(&Group::default(), relative_path) {
Lookup::Live(b) => b.checksum(),
_ => None,
}
}
}
pub(crate) fn segment_path(archive: &Path, n: u32) -> PathBuf {
let mut s = archive.as_os_str().to_os_string();
s.push(format!("{JOURNAL_INFIX}{n:05}"));
PathBuf::from(s)
}
pub(crate) fn journal_segments(archive: &Path) -> Result<Vec<(u32, PathBuf)>> {
let dir = archive.parent().filter(|p| !p.as_os_str().is_empty());
let dir = dir
.map(|d| d.to_path_buf())
.unwrap_or_else(|| PathBuf::from("."));
let stem = archive
.file_name()
.and_then(|n| n.to_str())
.ok_or_else(|| anyhow!("hot: {} has no usable file name", archive.display()))?;
let prefix = format!("{stem}{JOURNAL_INFIX}");
let mut out = Vec::new();
let rd = match std::fs::read_dir(&dir) {
Ok(rd) => rd,
Err(_) => return Ok(out),
};
for e in rd.flatten() {
let name = e.file_name();
let Some(name) = name.to_str() else { continue };
let Some(tail) = name.strip_prefix(&prefix) else {
continue;
};
let Ok(n) = tail.parse::<u32>() else { continue };
out.push((n, e.path()));
}
out.sort_by_key(|(n, _)| *n);
Ok(out)
}
const JOURNAL_ALIGNMENT: usize = 8;
pub fn seal_hot(archive: &Path, level: i32, policy: crate::SkipPolicy) -> Result<HotSealReport> {
if !HotArchive::is_hot(archive) {
bail!("{} has no journal; it is not hot", archive.display());
}
HotArchive::open(archive, level, policy)?.seal(None)
}
#[cfg(all(test, feature = "openzl"))]
mod tests {
use super::*;
use crate::{create_archive, ZnippyArchive};
use std::time::{SystemTime, UNIX_EPOCH};
fn unique_dir(tag: &str) -> PathBuf {
let ns = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let d = std::env::temp_dir().join(format!(
"znippy_hot_{tag}_{ns}_{:?}",
std::thread::current().id()
));
std::fs::create_dir_all(&d).unwrap();
d
}
fn synth(n: usize, salt: u64) -> Vec<(String, Vec<u8>)> {
(0..n)
.map(|i| {
let g = (i.wrapping_mul(2_654_435_761) ^ salt as usize) % 997;
let p = format!("repo/grp{g:03}/file{i:08}_{salt}.bin");
let body = format!("payload {i} salt {salt} {}\n", "z".repeat(8 + (i % 40)));
(p, body.into_bytes())
})
.collect()
}
#[test]
fn seal_matches_create_archive_byte_for_byte() {
let dir = unique_dir("identity");
let files = synth(400, 11);
let reference = dir.join("ref.znippy");
create_archive(&reference, &files, 3).unwrap();
let hot = dir.join("hot.znippy");
{
let h = HotArchive::open(&hot, 3, crate::SkipPolicy::resolve()).unwrap();
for f in &files {
h.append(std::slice::from_ref(f)).unwrap();
}
let report = h.seal(None).unwrap();
assert_eq!(report.rows_sealed, files.len() as u64);
assert_eq!(report.segments_removed, 1, "one process, one segment");
}
let a = std::fs::read(&reference).unwrap();
let b = std::fs::read(&hot).unwrap();
assert_eq!(
a.len(),
b.len(),
"sealed length differs: create_archive {} vs hot-then-seal {}",
a.len(),
b.len()
);
let first_diff = a.iter().zip(&b).position(|(x, y)| x != y);
assert!(
first_diff.is_none(),
"hot-then-seal is NOT byte-identical to create_archive; first difference at byte {:?}",
first_diff
);
assert!(!HotArchive::is_hot(&hot), "seal must remove the journal");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_hot_archive_serves_reads_before_the_seal() {
let dir = unique_dir("read");
let path = dir.join("a.znippy");
let files = synth(120, 3);
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
for f in &files {
h.append(std::slice::from_ref(f)).unwrap();
}
for (p, bytes) in &files {
assert!(h.contains(p), "hot archive must contain {p}");
assert_eq!(h.file_size(p), Some(bytes.len() as u64));
assert_eq!(
&h.extract_file(p).unwrap(),
bytes,
"hot read mismatch for {p}"
);
}
assert_eq!(h.list_files().unwrap().len(), files.len());
h.seal(None).unwrap();
let ar = ZnippyArchive::open(&path).unwrap();
for (p, bytes) in &files {
assert_eq!(
&ar.extract_file(p).unwrap(),
bytes,
"sealed read mismatch for {p}"
);
}
assert!(!crate::locate_file(&path, &files[77].0).unwrap().is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn reopening_recovers_every_segment() {
let dir = unique_dir("reopen");
let path = dir.join("a.znippy");
let mut all: Vec<(String, Vec<u8>)> = Vec::new();
for round in 0..3u64 {
let files = synth(40, round + 1);
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
assert_eq!(h.rows(), all.len() as u64, "reopen must recover prior rows");
for f in &files {
h.append(std::slice::from_ref(f)).unwrap();
}
all.extend(files);
}
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
assert_eq!(h.rows(), all.len() as u64);
let report = h.seal(None).unwrap();
assert_eq!(
report.segments_removed, 4,
"three appending opens + the final one"
);
let ar = ZnippyArchive::open(&path).unwrap();
for (p, bytes) in &all {
assert_eq!(
&ar.extract_file(p).unwrap(),
bytes,
"byte mismatch after restarts for {p}"
);
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_sealed_archive_reheats_and_keeps_its_rows() {
let dir = unique_dir("reheat");
let path = dir.join("a.znippy");
let sealed = synth(60, 5);
create_archive(&path, &sealed, 3).unwrap();
let cold_len = std::fs::metadata(&path).unwrap().len();
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
assert_eq!(
h.rows(),
sealed.len() as u64,
"re-heat must recover the sealed rows"
);
assert!(
h.blob_end() < cold_len,
"the metadata tail must be dropped: blob_end {} vs sealed length {cold_len}",
h.blob_end()
);
let extra = synth(20, 6);
for f in &extra {
h.append(std::slice::from_ref(f)).unwrap();
}
h.seal(None).unwrap();
let ar = ZnippyArchive::open(&path).unwrap();
for (p, bytes) in sealed.iter().chain(extra.iter()) {
assert_eq!(
&ar.extract_file(p).unwrap(),
bytes,
"byte mismatch after re-heat for {p}"
);
}
let mut listed = ar.list_files().unwrap();
listed.sort();
let mut want: Vec<String> = sealed
.iter()
.chain(extra.iter())
.map(|(p, _)| p.clone())
.collect();
want.sort();
assert_eq!(listed, want);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn re_appending_a_path_replaces_it() {
let dir = unique_dir("replace");
let path = dir.join("a.znippy");
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
h.append(&[("x.bin".into(), b"first version".to_vec())])
.unwrap();
h.append(&[("y.bin".into(), b"other".to_vec())]).unwrap();
let r = h
.append(&[("x.bin".into(), b"SECOND version, longer".to_vec())])
.unwrap();
assert_eq!(
r.rows_replaced, 1,
"re-appending x.bin must replace, not duplicate"
);
assert_eq!(h.rows(), 2);
assert_eq!(h.extract_file("x.bin").unwrap(), b"SECOND version, longer");
h.seal(None).unwrap();
let ar = ZnippyArchive::open(&path).unwrap();
assert_eq!(
ar.list_files().unwrap().len(),
2,
"the seal must carry ONE row per path"
);
assert_eq!(ar.extract_file("x.bin").unwrap(), b"SECOND version, longer");
assert_eq!(ar.extract_file("y.bin").unwrap(), b"other");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_torn_journal_tail_is_dropped_not_fatal() {
let dir = unique_dir("torn");
let path = dir.join("a.znippy");
let files = synth(30, 2);
{
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
for f in &files {
h.append(std::slice::from_ref(f)).unwrap();
}
}
let seg = segment_path(&path, 0);
let len = std::fs::metadata(&seg).unwrap().len();
std::fs::OpenOptions::new()
.write(true)
.open(&seg)
.unwrap()
.set_len(len - 40)
.unwrap();
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
let rows = h.rows();
assert!(
rows > 0 && rows < files.len() as u64,
"a torn tail must cost SOME rows and not all of them; got {rows} of {}",
files.len()
);
for p in h.list_files().unwrap() {
let want = &files.iter().find(|(q, _)| *q == p).unwrap().1;
assert_eq!(
&h.extract_file(&p).unwrap(),
want,
"torn-journal read mismatch for {p}"
);
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_index_cost_of_an_append_does_not_grow_with_the_archive() {
let dir = unique_dir("flat");
let path = dir.join("a.znippy");
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
let mut early = 0u64;
let mut late = 0u64;
for i in 0..2_000usize {
let f = vec![(format!("pack-{i:040x}.pack"), vec![b'q'; 64])];
let r = h.append(&f).unwrap();
if i == 10 {
early = r.journal_bytes_added;
}
if i == 1_999 {
late = r.journal_bytes_added;
}
}
assert!(
early > 0,
"an append must cost SOME journal bytes; the probe read 0"
);
assert_eq!(
early, late,
"the index cost of an append grew from {early} B at row 10 to {late} B at row 2000 — \
the append is paying for the archive again"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn hot_archive_is_send_and_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<HotArchive>();
}
#[test]
fn a_reader_on_an_untouched_region_proceeds_during_an_append() {
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering as O};
let dir = unique_dir("reader_during_append");
let path = dir.join("a.znippy");
let cold: Vec<(String, Vec<u8>)> = synth(64, 7);
let probe = cold[0].0.clone();
let probe_body = cold[0].1.clone();
let h = Arc::new(HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap());
h.append(&cold).unwrap();
let stop = Arc::new(AtomicBool::new(false));
let reads = Arc::new(AtomicU64::new(0));
let bad = Arc::new(AtomicU64::new(0));
let reader = {
let (h, stop, reads, bad, probe, probe_body) = (
Arc::clone(&h),
Arc::clone(&stop),
Arc::clone(&reads),
Arc::clone(&bad),
probe.clone(),
probe_body.clone(),
);
std::thread::spawn(move || {
while !stop.load(O::Relaxed) {
match h.extract_file(&probe) {
Ok(b) if b == probe_body => {
reads.fetch_add(1, O::Relaxed);
}
_ => {
bad.fetch_add(1, O::Relaxed);
}
}
}
})
};
let warm_deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
while reads.load(O::Relaxed) < 1_000 {
assert!(
std::time::Instant::now() < warm_deadline,
"reader never warmed up: {} reads, {} failures",
reads.load(O::Relaxed),
bad.load(O::Relaxed)
);
std::thread::yield_now();
}
let mut body = vec![0u8; 16 * 1024 * 1024];
let mut s: u64 = 0x2545_F491_4F6C_DD1D;
for b in body.iter_mut() {
s = s
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
*b = (s >> 33) as u8;
}
let before = reads.load(O::Relaxed);
let t0 = std::time::Instant::now();
let report = h.append(&[("hot/big.bin".to_string(), body)]).unwrap();
let append_took = t0.elapsed();
let during = reads.load(O::Relaxed) - before;
stop.store(true, O::Relaxed);
reader.join().unwrap();
assert_eq!(
bad.load(O::Relaxed),
0,
"a concurrent reader saw a wrong or missing body"
);
assert_eq!(report.rows_added, 1);
assert!(
report.blob_append_offset >= 1,
"the append must start past the cold rows, not on top of them"
);
eprintln!(
"reader completed {during} reads on an untouched row during one {append_took:?} append"
);
assert!(
during >= 100,
"a reader on an untouched row completed only {during} reads during a \
{append_took:?} append — the append is excluding readers again"
);
assert_eq!(h.extract_file(&probe).unwrap(), probe_body);
assert_eq!(
h.extract_file("hot/big.bin").unwrap().len(),
16 * 1024 * 1024
);
assert_eq!(h.rows(), 65);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_append_pays_exactly_two_fsyncs_and_an_empty_one_pays_none() {
let dir = unique_dir("fsync_count");
let path = dir.join("a.znippy");
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
assert_eq!(
h.fsyncs(),
0,
"a freshly opened archive has appended nothing"
);
for f in synth(8, 11) {
h.append(std::slice::from_ref(&f)).unwrap();
}
assert_eq!(
h.fsyncs(),
16,
"8 one-at-a-time appends are 8 x (blob, journal)"
);
h.append(&[]).unwrap();
assert_eq!(h.fsyncs(), 16, "an empty append must not touch the disk");
h.append(&synth(8, 12)).unwrap();
assert_eq!(
h.fsyncs(),
18,
"8 files in one append are two fsyncs, not sixteen"
);
assert_eq!(h.rows(), 16);
let _ = std::fs::remove_dir_all(&dir);
}
}
#[cfg(all(test, feature = "openzl"))]
pub(crate) mod stream_tests {
use super::*;
use crate::index::{read_znippy_index_filtered, IndexFilter};
use crate::{create_archive, HotView, ZnippyArchive};
use std::io::Cursor;
pub(crate) struct Noise {
pub s: u64,
pub left: u64,
}
impl Read for Noise {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = usize::try_from(self.left).map_or(buf.len(), |l| l.min(buf.len()));
for b in &mut buf[..n] {
self.s = self
.s
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
*b = (self.s >> 33) as u8;
}
self.left -= n as u64;
Ok(n)
}
}
pub(crate) struct Text {
pub at: u64,
pub left: u64,
}
impl Read for Text {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = usize::try_from(self.left).map_or(buf.len(), |l| l.min(buf.len()));
for b in &mut buf[..n] {
let line = self.at / 64;
let col = self.at % 64;
*b = if col == 63 {
b'\n'
} else {
b"line of text number "[(col % 20) as usize] ^ ((line % 3) as u8)
};
self.at += 1;
}
self.left -= n as u64;
Ok(n)
}
}
pub(crate) fn noise(seed: u64, n: u64) -> Vec<u8> {
let mut v = Vec::new();
Noise { s: seed, left: n }.read_to_end(&mut v).unwrap();
v
}
fn text(n: u64) -> Vec<u8> {
let mut v = Vec::new();
Text { at: 0, left: n }.read_to_end(&mut v).unwrap();
v
}
fn raw() -> crate::SkipPolicy {
crate::SkipPolicy::already_compressed()
}
fn seg_batches(path: &Path) -> usize {
let bytes = std::fs::read(path).unwrap();
let whole = crate::ipc_guard::valid_prefix(&bytes);
arrow::ipc::reader::StreamReader::try_new(Cursor::new(whole), None)
.unwrap()
.count()
}
#[test]
fn append_from_a_reader_writes_one_row_after_the_last_byte() {
struct Probe<'a> {
h: &'a HotArchive,
seg: PathBuf,
body: Noise,
seen: Vec<(u64, u64)>,
}
impl Read for Probe<'_> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.seen
.push((self.h.rows(), std::fs::metadata(&self.seg).unwrap().len()));
self.body.read(buf)
}
}
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let h = HotArchive::open(&path, 3, raw()).unwrap();
let seg = segment_path(&path, 0);
let journal_before = std::fs::metadata(&seg).unwrap().len();
let size = 10 * (1 << 20) + 7;
let mut probe = Probe {
h: &h,
seg: seg.clone(),
body: Noise { s: 1, left: size },
seen: Vec::new(),
};
let staged = h
.append_from(&Group::default(), "big.bin", &mut probe, &Expect::default())
.unwrap();
assert!(probe.seen.len() >= 3, "a 10 MiB body is read in pieces");
assert!(
probe
.seen
.iter()
.all(|&(rows, j)| rows == 0 && j == journal_before),
"a row or a journal message appeared before the last byte: {:?}",
probe.seen
);
let want = noise(1, size);
assert_eq!(staged.size(), size);
assert_eq!(staged.blake3(), *blake3::hash(&want).as_bytes());
assert_eq!(staged.location().chunks.len(), 1, "a raw body is one chunk");
assert_eq!(h.rows(), 1);
assert_eq!(seg_batches(&seg), 1, "one journal message");
assert_eq!(h.fsyncs(), 2, "the body, then the row");
assert_eq!(h.extract_file("big.bin").unwrap(), want);
h.seal(None).unwrap();
let ar = ZnippyArchive::open(&path).unwrap();
assert_eq!(ar.extract_file_verified("big.bin").unwrap(), want);
}
#[test]
fn a_compressible_stream_is_stored_in_compressed_pieces() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
let size = 2 * STREAM_PIECE as u64 + 1000;
let staged = h
.append_from(
&Group::default(),
"data.txt",
&mut Text { at: 0, left: size },
&Expect::default(),
)
.unwrap();
let want = text(size);
let at = staged.location();
assert_eq!(at.chunks.len(), 3);
assert!(at.chunks[..2].iter().all(|c| c.compressed), "{at:?}");
assert!(
at.stored_bytes() < size / 4,
"stored {} of {size}",
at.stored_bytes()
);
assert_eq!(staged.blake3(), *blake3::hash(&want).as_bytes());
assert_eq!(
at.checksum(),
None,
"a body in pieces stores no digest of the whole"
);
assert_eq!(
h.get(&Group::default(), "data.txt")
.unwrap()
.read_verified()
.unwrap(),
want
);
let v = HotView::open(&path).unwrap();
assert_eq!(v.extract_file("data.txt").unwrap(), want);
h.seal(None).unwrap();
let ar = ZnippyArchive::open(&path).unwrap();
assert_eq!(ar.extract_file_verified("data.txt").unwrap(), want);
}
#[test]
fn a_read_error_mid_body_leaves_no_row_and_the_orphan_is_cut_at_reopen() {
struct Breaks(Noise);
impl Read for Breaks {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if self.0.left == 0 {
return Err(std::io::Error::other("the source broke"));
}
self.0.read(buf)
}
}
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
{
let h = HotArchive::open(&path, 3, raw()).unwrap();
h.append(&[("first".into(), b"one".to_vec())]).unwrap();
let end = h.blob_end();
let err = h
.append_from(
&Group::default(),
"cut.bin",
&mut Breaks(Noise {
s: 2,
left: 5 << 20,
}),
&Expect::default(),
)
.unwrap_err();
assert!(format!("{err:#}").contains("the source broke"), "{err:#}");
assert_eq!(h.rows(), 1);
assert_eq!(h.blob_end(), end, "the cursor does not move");
assert!(
std::fs::metadata(&path).unwrap().len() >= end + STREAM_PIECE as u64,
"the orphan is there"
);
assert!(!h.contains("cut.bin"));
}
let h = HotArchive::open(&path, 3, raw()).unwrap();
assert_eq!(
std::fs::metadata(&path).unwrap().len(),
3,
"the open cut the orphan"
);
assert_eq!(h.rows(), 1);
let r = h.append(&[("second".into(), b"two".to_vec())]).unwrap();
assert_eq!(r.blob_append_offset, 3);
assert_eq!(h.extract_file("second").unwrap(), b"two");
}
#[test]
fn a_short_body_against_an_expected_size_is_refused() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let h = HotArchive::open(&path, 3, raw()).unwrap();
let body = noise(3, 60);
let short = Expect {
size: Some(100),
blake3: None,
};
assert!(h
.append_from(&Group::default(), "x", &mut Cursor::new(&body), &short)
.is_err());
let wrong = Expect {
size: None,
blake3: Some([7u8; 32]),
};
assert!(h
.append_from(&Group::default(), "x", &mut Cursor::new(&body), &wrong)
.is_err());
assert_eq!(h.rows(), 0);
assert_eq!(h.blob_end(), 0);
let right = Expect {
size: Some(60),
blake3: Some(*blake3::hash(&body).as_bytes()),
};
h.append_from(&Group::default(), "x", &mut Cursor::new(&body), &right)
.unwrap();
assert_eq!(h.extract_file("x").unwrap(), body);
}
#[test]
fn stage_all_is_one_fsync_for_many_bodies() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
let fs0 = h.fsyncs();
assert!(h.stage_all(&[]).unwrap().is_empty());
assert_eq!(h.fsyncs(), fs0, "nothing staged, nothing synced");
let long = vec![b'z'; 10_000];
let bodies: Vec<(&str, &[u8])> =
vec![("a", b"AAAA"), ("empty", b""), ("long", &long), ("b", b"B")];
let staged = h.stage_all(&bodies).unwrap();
assert_eq!(h.fsyncs(), fs0 + 1, "one fsync for all");
assert_eq!(staged.len(), 4);
assert_eq!(staged[2].size(), 10_000);
let g = Group::new(1, "rows");
let ops = (bodies.iter().zip(staged))
.map(|((name, _), staged)| HotOp::Put {
group: g.clone(),
name: (*name).into(),
staged,
})
.collect();
h.commit(ops).unwrap();
assert_eq!(h.fsyncs(), fs0 + 2, "and one for the rows");
drop(h);
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
for (name, bytes) in &bodies {
assert_eq!(&h.get(&g, name).unwrap().read().unwrap(), bytes, "{name}");
}
}
#[test]
fn stage_then_commit_is_one_journal_message() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let h = HotArchive::open(&path, 3, raw()).unwrap();
h.append(&[("old".into(), b"old".to_vec())]).unwrap();
let seg = segment_path(&path, 0);
let before = seg_batches(&seg);
let fs0 = h.fsyncs();
let a = h
.stage_from("a", &mut Cursor::new(b"AAAA".to_vec()), &Expect::default())
.unwrap();
let b = h
.stage_from("b", &mut Cursor::new(b"BBBB".to_vec()), &Expect::default())
.unwrap();
assert_eq!(h.fsyncs(), fs0 + 2, "a stage is one fsync");
assert_eq!(h.rows(), 1, "a staged body has no row");
let g = Group::new(1, "crates");
let r = h
.commit(vec![
HotOp::Put {
group: Group::default(),
name: "a".into(),
staged: a.clone(),
},
HotOp::Put {
group: g.clone(),
name: "b".into(),
staged: b,
},
HotOp::Put {
group: g.clone(),
name: "a-too".into(),
staged: a,
},
HotOp::End {
group: Group::default(),
name: "old".into(),
},
])
.unwrap();
assert_eq!(h.fsyncs(), fs0 + 3, "a commit is one fsync");
assert_eq!(r.rows_replaced, 1, "old was ended");
assert_eq!(
seg_batches(&seg) + seg_batches(&segment_path(&path, 1)),
before + 1,
"the four ops are one message (in the V2 segment the group needs)"
);
assert_eq!(h.get(&g, "a-too").unwrap().read().unwrap(), b"AAAA");
assert_eq!(h.get(&g, "b").unwrap().read().unwrap(), b"BBBB");
assert!(!h.contains("old"));
let other = HotArchive::open(&dir.path().join("b.znippy"), 3, raw()).unwrap();
let foreign = other
.stage_from("f", &mut Cursor::new(b"F".to_vec()), &Expect::default())
.unwrap();
let err = h
.commit(vec![HotOp::Put {
group: g,
name: "f".into(),
staged: foreign,
}])
.unwrap_err();
assert!(format!("{err:#}").contains("another archive"), "{err:#}");
}
#[test]
fn a_second_name_on_one_blob_writes_no_bytes() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let body = noise(4, 100_000);
let h = HotArchive::open(&path, 3, raw()).unwrap();
h.append(&[("a".into(), body.clone())]).unwrap();
let end = h.blob_end();
let g = Group::new(3, "maven-central");
h.link(&Group::default(), "a2", &Group::default(), "a")
.unwrap();
h.link(&g, "a", &Group::default(), "a").unwrap();
assert_eq!(h.blob_end(), end, "a link writes no byte");
assert_eq!(h.extract_file("a2").unwrap(), body);
assert_eq!(h.get(&g, "a").unwrap().read().unwrap(), body);
h.seal(None).unwrap();
let ar = ZnippyArchive::open(&path).unwrap();
assert_eq!(ar.extract_file_verified("a2").unwrap(), body);
let v = HotView::open(&path).unwrap();
assert!(v.is_sealed());
let (Lookup::Live(x), Lookup::Live(y)) =
(v.lookup(&Group::default(), "a"), v.lookup(&g, "a"))
else {
panic!("both names live after the seal");
};
assert_eq!(x.chunks, y.chunks, "both rows name the one blob");
assert_eq!(v.get(&g, "a").unwrap().read_verified().unwrap(), body);
}
#[test]
fn compact_archive_keeps_a_shared_blob_once() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let body = noise(5, 1 << 20);
let h = HotArchive::open(&path, 3, raw()).unwrap();
h.append(&[("a".into(), body.clone())]).unwrap();
h.link(&Group::default(), "a2", &Group::default(), "a")
.unwrap();
h.append(&[("dead".into(), noise(6, 1 << 20))]).unwrap();
h.end(&Group::default(), "dead").unwrap();
h.seal(None).unwrap();
let report = crate::compact_archive(&path).unwrap();
assert!(
report.bytes_after < (1 << 20) + (1 << 18),
"the compacted archive holds {} bytes: the shared 1 MiB body was copied twice, or the \
ended one was kept",
report.bytes_after
);
let ar = ZnippyArchive::open(&path).unwrap();
assert_eq!(ar.extract_file_verified("a").unwrap(), body);
assert_eq!(ar.extract_file_verified("a2").unwrap(), body);
assert!(!ar.contains("dead"));
}
#[test]
fn ending_one_name_keeps_the_blob_for_the_other() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let body = noise(7, 50_000);
let h = HotArchive::open(&path, 3, raw()).unwrap();
h.append(&[("a".into(), body.clone())]).unwrap();
h.link(&Group::default(), "b", &Group::default(), "a")
.unwrap();
h.end(&Group::default(), "a").unwrap();
assert!(!h.contains("a"));
assert_eq!(h.extract_file("b").unwrap(), body);
h.seal(None).unwrap();
crate::compact_archive(&path).unwrap();
let ar = ZnippyArchive::open(&path).unwrap();
assert!(!ar.contains("a"));
assert_eq!(ar.extract_file_verified("b").unwrap(), body);
}
#[test]
fn checksum_is_the_stored_blake3_of_a_name() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let small = b"small body".to_vec();
let big = noise(8, 9 << 20);
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
h.append(&[("small".into(), small.clone())]).unwrap();
h.append_from(
&Group::default(),
"big.gz",
&mut Cursor::new(&big),
&Expect::default(),
)
.unwrap();
h.append_from(
&Group::default(),
"pieces.txt",
&mut Text {
at: 0,
left: 9 << 20,
},
&Expect::default(),
)
.unwrap();
let want_small = Some(*blake3::hash(&small).as_bytes());
let want_big = Some(*blake3::hash(&big).as_bytes());
let v = HotView::open(&path).unwrap();
let readers: [&dyn ZnippyReader; 2] = [&h, &v];
for r in readers {
assert_eq!(r.checksum("small"), want_small);
assert_eq!(
r.checksum("big.gz"),
want_big,
"a raw stream stores the body's digest"
);
assert_eq!(
r.checksum("pieces.txt"),
None,
"a body in pieces stores none for the whole"
);
assert_eq!(r.checksum("absent"), None);
}
h.seal(None).unwrap();
let ar = ZnippyArchive::open(&path).unwrap();
assert_eq!(ar.checksum("small"), want_small);
assert_eq!(ar.checksum("big.gz"), want_big);
assert_eq!(ar.checksum("pieces.txt"), None);
assert_eq!(ar.checksum("absent"), None);
}
#[test]
fn an_interrupted_seal_is_finished_at_reopen() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let mut all = Vec::new();
for round in 0..3u64 {
let h = HotArchive::open(&path, 3, raw()).unwrap();
let files: Vec<(String, Vec<u8>)> = (0..5)
.map(|i| (format!("r{round}/f{i}"), noise(round * 10 + i, 300)))
.collect();
h.append(&files).unwrap();
all.extend(files);
}
let h = HotArchive::open(&path, 3, raw()).unwrap();
h.seal_with(None, false).unwrap();
std::fs::remove_file(segment_path(&path, 0)).unwrap();
let h = HotArchive::open(&path, 3, raw()).unwrap();
assert_eq!(h.rows(), all.len() as u64, "every row of the seal");
for (p, b) in &all {
assert_eq!(&h.extract_file(p).unwrap(), b, "{p}");
}
assert_eq!(
journal_segments(&path).unwrap().len(),
1,
"only this open's own segment is left"
);
h.seal(None).unwrap();
let ar = ZnippyArchive::open(&path).unwrap();
assert_eq!(ar.list_files().unwrap().len(), all.len());
}
#[test]
fn a_cut_reheat_leaves_the_seal_readable() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let files: Vec<(String, Vec<u8>)> =
(0..20).map(|i| (format!("f{i}"), noise(i, 500))).collect();
create_archive(&path, &files, 3).unwrap();
let mut seed = segment_path(&path, 0).into_os_string();
seed.push(".seed");
std::fs::write(&seed, b"half a seed").unwrap();
assert!(!HotArchive::is_hot(&path), "a seed is not a segment");
let h = HotArchive::open(&path, 3, raw()).unwrap();
assert_eq!(h.rows(), 20);
for (p, b) in &files {
assert_eq!(&h.extract_file(p).unwrap(), b);
}
}
#[test]
fn a_plain_archive_keeps_the_v1_journal_until_a_row_needs_more() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let h = HotArchive::open(&path, 3, raw()).unwrap();
h.append(&[("a".into(), b"A".to_vec())]).unwrap();
let schema_of = |n: u32| {
let bytes = std::fs::read(segment_path(&path, n)).unwrap();
let r = arrow::ipc::reader::StreamReader::try_new(Cursor::new(bytes), None).unwrap();
r.schema().fields().len()
};
assert_eq!(schema_of(0), 8);
h.append_in(&Group::new(2, "pypi"), &[("b".into(), b"B".to_vec())])
.unwrap();
assert_eq!(schema_of(1), 12);
drop(h);
let h = HotArchive::open(&path, 3, raw()).unwrap();
assert_eq!(h.extract_file("a").unwrap(), b"A");
assert_eq!(
h.get(&Group::new(2, "pypi"), "b").unwrap().read().unwrap(),
b"B"
);
}
#[test]
fn many_repositories_of_many_types_in_one_archive() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("account.znippy");
let groups = [
Group::new(1, "crates-io"),
Group::new(1, "internal"),
Group::new(3, "central"),
Group::default(),
];
let body = |g: &Group, i: usize| format!("{g:?} body {i}").into_bytes();
let h = HotArchive::open(&path, 3, raw()).unwrap();
for g in &groups {
let files: Vec<(String, Vec<u8>)> =
(0..10).map(|i| (format!("pkg/{i}"), body(g, i))).collect();
h.append_in(g, &files).unwrap();
}
h.seal(None).unwrap();
for g in &groups {
let (_, batches) = read_znippy_index_filtered(
&path,
&IndexFilter {
pkg_type: Some(g.pkg_type),
repo: Some(g.repo.clone()),
},
)
.unwrap();
let rows: usize = batches.iter().map(|b| b.num_rows()).sum();
assert_eq!(rows, 10, "{g:?} is its own data sub-index");
}
let v = HotView::open(&path).unwrap();
assert_eq!(v.groups().len(), 4);
for g in &groups {
for i in 0..10 {
assert_eq!(
v.get(g, &format!("pkg/{i}"))
.unwrap()
.read_verified()
.unwrap(),
body(g, i)
);
}
}
let h = HotArchive::open(&path, 3, raw()).unwrap();
assert_eq!(h.rows(), 40);
h.append_in(&groups[0], &[("pkg/new".into(), b"new".to_vec())])
.unwrap();
h.seal(None).unwrap();
v.refresh().unwrap();
assert_eq!(
v.get(&groups[0], "pkg/new").unwrap().read().unwrap(),
b"new"
);
assert!(v.get(&groups[1], "pkg/new").is_none());
for g in &groups {
assert_eq!(v.get(g, "pkg/3").unwrap().read().unwrap(), body(g, 3));
}
}
}