use std::collections::{BTreeMap, BTreeSet, 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::write_blobs;
use crate::rows::{
fill, fits_v1, own_bytes_end, rows_batch, rows_schema, sync_dir_of, Blob, BlobRef, Group, SectionRows,
Lookup, RowEntry, RowIndex, SegmentCursor, Was, STREAM_PIECE,
};
use crate::stack::{LayerInfo, StackSection};
const JOURNAL_INFIX: &str = ".hot.";
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
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)]
#[non_exhaustive]
pub struct HotCommitReport {
pub rows_added: u64,
pub rows_replaced: u64,
pub journal_bytes_added: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
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],
written: u64,
hashed: u64,
}
impl Staged {
pub fn size(&self) -> u64 {
self.size
}
pub fn written(&self) -> u64 {
self.written
}
pub fn hashed(&self) -> u64 {
self.hashed
}
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,
index_copies: AtomicU64,
policy: crate::SkipPolicy,
layer: Option<LayerInfo>,
token: Arc<()>,
others: Mutex<Others>,
#[cfg(test)]
at_position: Mutex<Option<Box<dyn FnOnce() + Send>>>,
}
#[derive(Default)]
struct Others {
cursors: BTreeMap<u32, SegmentCursor>,
mine: BTreeSet<u32>,
at_open: u64,
}
struct HotWriter {
blob_end: u64,
journal: Journal,
ctx: CompressCtx,
}
struct Laying {
raw: bool,
whole: blake3::Hasher,
size: u64,
chunks: Vec<ChunkLoc>,
run: blake3::Hasher,
frame: Vec<u8>,
written: u64,
hashed: u64,
}
impl Laying {
fn new(raw: bool) -> Self {
Self {
raw,
whole: blake3::Hasher::new(),
size: 0,
chunks: Vec::new(),
run: blake3::Hasher::new(),
frame: Vec::new(),
written: 0,
hashed: 0,
}
}
fn lay(&mut self, w: &mut HotWriter, blobs: &File, bytes: &[u8]) -> Result<()> {
let at = w.blob_end;
let n = bytes.len() as u64;
if self.raw {
blobs.write_all_at(bytes, at)?;
match self.chunks.last_mut() {
Some(c) if c.blob_offset + c.blob_size == at => {
c.blob_size += n;
c.uncompressed_size += n;
}
_ => {
self.close_last();
self.chunks.push(ChunkLoc {
chunk_seq: u32::try_from(self.chunks.len())?,
fdata_offset: self.size,
blob_offset: at,
blob_size: n,
uncompressed_size: n,
compressed: false,
checksum: [0; 32],
});
}
}
if self.chunks.len() > 1 {
self.run.update(bytes);
self.hashed += n;
}
self.written += n;
w.blob_end = at + n;
} else {
self.close_last();
w.ctx.compress_into(bytes, &mut self.frame)?;
let (on_disk, compressed): (&[u8], bool) = if self.frame.len() < bytes.len() {
(&self.frame, true)
} else {
(bytes, false)
};
blobs.write_all_at(on_disk, at)?;
let checksum = if self.chunks.is_empty() {
[0; 32]
} else {
self.hashed += n;
*blake3::hash(bytes).as_bytes()
};
let written = on_disk.len() as u64;
self.chunks.push(ChunkLoc {
chunk_seq: u32::try_from(self.chunks.len())?,
fdata_offset: self.size,
blob_offset: at,
blob_size: written,
uncompressed_size: n,
compressed,
checksum,
});
self.written += written;
w.blob_end = at + on_disk.len() as u64;
}
self.whole.update(bytes);
self.hashed += n;
self.size += n;
Ok(())
}
fn close_last(&mut self) {
if let [first] = self.chunks.as_mut_slice() {
first.checksum = *self.whole.clone().finalize().as_bytes();
} else if self.raw
&& let Some(c) = self.chunks.last_mut()
{
let run = std::mem::replace(&mut self.run, blake3::Hasher::new());
c.checksum = *run.finalize().as_bytes();
}
}
fn check(&self, expect: &Expect) -> Result<()> {
if let Some(want) = expect.size {
let size = self.size;
ensure!(
want == size,
"the body is {size} bytes, {want} were expected"
);
}
if let Some(want) = expect.blake3 {
let digest = *self.whole.clone().finalize().as_bytes();
ensure!(want == digest, "the body's BLAKE3 is not the one expected");
}
Ok(())
}
fn one_run(&self) -> Option<(u64, u64)> {
let first = self.chunks.first()?;
let mut end = first.blob_offset;
for c in &self.chunks {
if c.blob_offset != end {
return None;
}
end += c.blob_size;
}
Some((first.blob_offset, end))
}
fn end(mut self, empty_at: u64, owner: Arc<()>) -> Staged {
let digest = *self.whole.finalize().as_bytes();
if let [one] = self.chunks.as_mut_slice() {
one.checksum = digest;
} else {
self.close_last();
}
if self.chunks.is_empty() {
self.chunks.push(ChunkLoc {
chunk_seq: 0,
fdata_offset: 0,
blob_offset: empty_at,
blob_size: 0,
uncompressed_size: 0,
compressed: false,
checksum: digest,
});
}
Staged {
owner,
at: BlobRef::new(None, self.chunks, Some(digest)),
size: self.size,
blake3: digest,
written: self.written,
hashed: self.hashed,
}
}
}
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,
cursors: Vec<SegmentCursor>,
read: u64,
}
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 others = Others {
cursors: (loaded.cursors.into_iter())
.map(|c| (c.number, c))
.collect(),
mine: BTreeSet::from([journal.number]),
at_open: loaded.read,
};
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),
index_copies: AtomicU64::new(0),
layer,
token: Arc::new(()),
others: Mutex::new(others),
#[cfg(test)]
at_position: Mutex::new(None),
})
}
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;
let mut cursors = Vec::new();
let mut read = 0u64;
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);
read += entries.len() as u64;
for e in entries {
own_end = own_end.max(own_bytes_end(&e));
index.apply(e);
}
cursors.push(c);
}
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,
cursors,
read,
});
}
let Some((entries, _)) = sealed_manifest() else {
return Ok(Loaded {
index,
own_end,
seed: None,
next_segment: 0,
needs_v2,
cursors,
read,
});
};
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, bodies) = crate::meta_sink_append::recover_rows(archive, &entries)?;
entries_by_name(Group::default(), paths, locs, bodies)
} 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,
cursors,
read,
})
}
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_copies.fetch_add(1, Ordering::Relaxed);
self.index_read().clone()
}
pub(crate) fn with_index<R>(&self, f: impl FnOnce(&RowIndex) -> R) -> R {
f(&self.index_read())
}
#[cfg(test)]
pub(crate) fn index_copies(&self) -> u64 {
self.index_copies.load(Ordering::Relaxed)
}
#[cfg(test)]
pub(crate) fn at_position(&self, at: impl FnOnce() + Send + 'static) {
*self.at_position.lock().unwrap_or_else(|e| e.into_inner()) = Some(Box::new(at));
}
#[cfg(test)]
fn positioned(&self) {
let at = self
.at_position
.lock()
.unwrap_or_else(|e| e.into_inner())
.take();
if let Some(at) = at {
at();
}
}
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;
#[cfg(test)]
self.positioned();
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::new(None, vec![loc], None)),
})
.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 piece = vec![0u8; STREAM_PIECE];
let mut n = fill(body, &mut piece)?;
let mut laying = Laying::new(self.raw(name, &piece[..n]));
let laid = loop {
if n == 0 {
break laying.check(expect);
}
if let Err(e) = self.lay_piece(&mut laying, &piece[..n]) {
break Err(e);
}
n = match fill(body, &mut piece) {
Ok(n) => n,
Err(e) => break Err(e),
};
};
if let Err(e) = laid {
self.give_back(&laying);
return Err(e);
}
self.blobs.sync_all()?;
self.fsyncs.fetch_add(1, Ordering::Relaxed);
Ok(laying.end(self.blob_end(), Arc::clone(&self.token)))
}
fn lay_piece(&self, laying: &mut Laying, bytes: &[u8]) -> Result<()> {
let mut guard = self.writer.lock().unwrap_or_else(|e| e.into_inner());
laying.lay(&mut guard, &self.blobs, bytes)?;
self.blob_end.store(guard.blob_end, Ordering::Release);
Ok(())
}
fn give_back(&self, laying: &Laying) {
let Some((start, end)) = laying.one_run() else {
return;
};
let mut guard = self.writer.lock().unwrap_or_else(|e| e.into_inner());
if guard.blob_end == end {
guard.blob_end = start;
self.blob_end.store(start, Ordering::Release);
}
}
fn raw(&self, name: &str, first: &[u8]) -> bool {
self.policy.skip_by_path(Path::new(name))
|| (self.policy).skip_by_bytes(&first[..first.len().min(crate::SNIFF_PREFIX_LEN)])
}
pub fn staged_here(&self, staged: &Staged) -> bool {
Arc::ptr_eq(&staged.owner, &self.token)
}
pub fn staged_body(&self, staged: &Staged) -> Result<Blob> {
ensure!(
self.staged_here(staged),
"the body was staged by another archive"
);
Ok(Blob::new(Arc::clone(&self.blobs), staged.at.clone()))
}
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 start = w.blob_end;
let mut out = Vec::with_capacity(bodies.len());
for (name, bytes) in bodies {
let mut laying = Laying::new(self.raw(name, bytes));
for piece in bytes.chunks(STREAM_PIECE) {
if let Err(e) = laying.lay(w, &self.blobs, piece) {
w.blob_end = start;
return Err(e);
}
}
out.push(laying.end(w.blob_end, Arc::clone(&self.token)));
}
if let Err(e) = self.blobs.sync_all() {
w.blob_end = start;
return Err(e.into());
}
self.fsyncs.fetch_add(1, Ordering::Relaxed);
self.blob_end.store(w.blob_end, Ordering::Release);
Ok(out)
}
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) {
self.new_segment(w, true)?;
}
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) => {
let v2 = w.journal.v2;
let _ = self.new_segment(w, v2);
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 new_segment(&self, w: &mut HotWriter, v2: bool) -> Result<()> {
let top = journal_segments(&self.archive)?.last().map(|(n, _)| *n);
let number = top.map_or(0, |n| n + 1).max(w.journal.number + 1);
w.journal = Journal::create(&self.archive, number, v2, self.layer.as_ref())?;
self.others().mine.insert(number);
Ok(())
}
fn others(&self) -> std::sync::MutexGuard<'_, Others> {
self.others.lock().unwrap_or_else(|e| e.into_inner())
}
pub(crate) fn rows_at_open(&self) -> u64 {
self.others().at_open
}
pub(crate) fn catch_up(&self) -> Result<(u64, bool)> {
let mut w = self.writer.lock().unwrap_or_else(|e| e.into_inner());
let segments = journal_segments(&self.archive)?;
let mut fresh = Vec::new();
let mut above = false;
{
let mut others = self.others();
let Others { cursors, mine, .. } = &mut *others;
for (n, path) in &segments {
if mine.contains(n) {
continue;
}
let cursor =
(cursors.entry(*n)).or_insert_with(|| SegmentCursor::new(*n, path.clone()));
let (entries, _) = cursor.read_more(true)?;
above |= !entries.is_empty() && *n > w.journal.number;
fresh.extend(entries);
}
}
let rows = fresh.len() as u64;
let end = fresh.iter().map(own_bytes_end).max().unwrap_or(0);
if end > w.blob_end {
w.blob_end = end;
self.blob_end.store(end, Ordering::Release);
}
if !fresh.is_empty() {
let mut idx = self.index.write().unwrap_or_else(|e| e.into_inner());
for e in fresh {
idx.apply(e);
}
}
if above {
let v2 = w.journal.v2;
self.new_segment(&mut w, v2)?;
}
Ok((rows, above))
}
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<SectionRows> = Vec::new();
for g in index.groups() {
let mut rows = SectionRows::new(g.clone());
for (name, slot) in index.slots(g) {
match slot {
Some(b) if b.pack.is_none() => {
rows_sealed += 1;
rows.push(name, b);
}
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 !rows.is_empty() {
groups.push(rows);
}
}
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 rows in &groups {
rows.push_to(&mut sink)?;
}
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>,
bodies: Vec<Option<[u8; 32]>>,
) -> Vec<RowEntry> {
let mut at: HashMap<String, usize> = HashMap::with_capacity(paths.len());
let mut out: Vec<RowEntry> = Vec::new();
for ((name, loc), body) in paths.into_iter().zip(locs).zip(bodies) {
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);
b.body_checksum = body.or(b.body_checksum);
}
None => {
at.insert(name.clone(), out.len());
out.push(RowEntry {
group: group.clone(),
name,
slot: Some(BlobRef {
pack: None,
chunks: vec![loc],
body_checksum: body,
}),
});
}
}
}
for e in &mut out {
if let Some(b) = &mut e.slot {
b.chunks.sort_by_key(|c| c.fdata_offset);
b.keep_body_checksum_only_when_needed();
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::mpsc::channel;
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 (positioned, at_position) = channel::<()>();
let (read, has_read) = channel::<()>();
h.at_position(move || {
positioned.send(()).unwrap();
has_read
.recv()
.expect("the reader reads the untouched row while the append holds");
});
let reader = {
let (h, probe) = (Arc::clone(&h), probe.clone());
std::thread::spawn(move || {
at_position
.recv()
.expect("the append takes its write position");
let body = h.extract_file(&probe);
read.send(()).unwrap();
body
})
};
let mut body = vec![0u8; 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 report = h.append(&[("hot/big.bin".to_string(), body)]).unwrap();
let during = reader.join().unwrap();
assert_eq!(
during.unwrap(),
probe_body,
"the reader read the untouched row, whole, while the append held its position"
);
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"
);
assert_eq!(h.extract_file(&probe).unwrap(), probe_body);
assert_eq!(h.extract_file("hot/big.bin").unwrap().len(), 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
}
pub(crate) 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(),
Some(staged.blake3()),
"a body in pieces carries the digest of the whole beside its pieces'"
);
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_body_laid_as_one_chunk_is_hashed_once() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
let bodies = [
("raw.gz", noise(8, 3 << 20)),
("one.txt", text(1 << 20)),
("pieces.txt", text(2 * STREAM_PIECE as u64 + 1000)),
];
let staged: Vec<Staged> = (bodies.iter())
.map(|(name, body)| {
(h.stage_from(name, &mut Cursor::new(body), &Expect::default())).unwrap()
})
.collect();
let (raw, one, pieces) = (&staged[0], &staged[1], &staged[2]);
assert_eq!(raw.location().chunks.len(), 1);
assert!(!raw.location().chunks[0].compressed);
assert_eq!(raw.written(), raw.size());
assert_eq!(raw.hashed(), raw.size(), "a raw body in one chunk");
assert_eq!(one.location().chunks.len(), 1);
assert!(one.location().chunks[0].compressed);
assert_eq!(one.written(), one.location().stored_bytes());
assert_eq!(one.hashed(), one.size(), "a body compressed whole");
let chunks = &pieces.location().chunks;
assert_eq!(chunks.len(), 3);
assert_eq!(pieces.written(), pieces.location().stored_bytes());
assert_eq!(
pieces.hashed(),
2 * pieces.size() - chunks[0].uncompressed_size,
"a body in pieces: whole once, and every chunk after the first"
);
for (s, (name, body)) in staged.iter().zip(&bodies) {
assert_eq!(s.blake3(), *blake3::hash(body).as_bytes(), "{name}");
assert_eq!(s.location().checksum(), Some(s.blake3()), "{name}");
let blob = h.staged_body(s).unwrap();
let mut p = blob.pieces(STREAM_PIECE, true).unwrap();
let mut got = Vec::new();
for piece in &mut p {
got.extend(piece.unwrap());
}
assert_eq!(&got, body, "{name}");
assert_eq!(p.read(), s.location().stored_bytes(), "{name}: read once");
assert_eq!(p.hashed(), s.size(), "{name}: checked once");
}
}
#[test]
fn a_body_laid_in_pieces_has_its_whole_blake3_in_its_row() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let g = Group::default();
let size = 2 * STREAM_PIECE as u64 + 1000;
let want = *blake3::hash(&text(size)).as_bytes();
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
let staged = h
.append_from(&g, "data.txt", &mut Text { at: 0, left: size }, &Expect::default())
.unwrap();
let at = staged.location().clone();
assert_eq!(at.chunks.len(), 3, "laid in pieces: {at:?}");
assert_eq!(staged.blake3(), want);
assert_eq!(at.checksum(), Some(want), "the staged body's place");
let c = &at.chunks[0];
let f = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
f.write_all_at(&vec![0u8; c.blob_size as usize], c.blob_offset).unwrap();
drop(f);
let Lookup::Live(row) = h.lookup(&g, "data.txt") else {
panic!("no row for data.txt")
};
assert_eq!(row.checksum(), Some(want), "its row");
assert_eq!(h.get(&g, "data.txt").unwrap().checksum(), Some(want), "its blob");
assert_eq!(ZnippyReader::checksum(&h, "data.txt"), Some(want), "the archive");
let v = HotView::open(&path).unwrap();
assert_eq!(v.checksum("data.txt"), Some(want), "another process's view");
drop(h);
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
assert_eq!(ZnippyReader::checksum(&h, "data.txt"), Some(want), "reopened");
h.seal(None).unwrap();
let ar = ZnippyArchive::open(&path).unwrap();
assert_eq!(ar.checksum("data.txt"), Some(want), "sealed");
let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
assert_eq!(ZnippyReader::checksum(&h, "data.txt"), Some(want), "sealed, hot again");
assert!(
ar.extract_file_verified("data.txt").is_err(),
"the first chunk was overwritten: only the row can have given the digest"
);
}
#[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");
}
struct Waits {
first: Vec<u8>,
rest: Vec<u8>,
told: Option<std::sync::mpsc::Sender<()>>,
go: std::sync::mpsc::Receiver<()>,
}
impl Read for Waits {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if !self.first.is_empty() {
let n = buf.len().min(self.first.len());
buf[..n].copy_from_slice(&self.first[..n]);
self.first.drain(..n);
return Ok(n);
}
if let Some(told) = self.told.take() {
let _ = told.send(());
self.go
.recv()
.map_err(|_| std::io::Error::other("the test ended"))?;
}
let n = buf.len().min(self.rest.len());
buf[..n].copy_from_slice(&self.rest[..n]);
self.rest.drain(..n);
Ok(n)
}
}
fn waits(
first: Vec<u8>,
rest: Vec<u8>,
) -> (
Waits,
std::sync::mpsc::Receiver<()>,
std::sync::mpsc::Sender<()>,
) {
let (told, heard) = std::sync::mpsc::channel();
let (go, wait) = std::sync::mpsc::channel();
let body = Waits {
first,
rest,
told: Some(told),
go: wait,
};
(body, heard, go)
}
#[test]
fn a_body_whose_reader_waits_holds_no_other_writer() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let h = HotArchive::open(&path, 3, raw()).unwrap();
let (first, rest) = (noise(11, STREAM_PIECE as u64), noise(12, 1000));
let whole = [first.clone(), rest.clone()].concat();
let (mut body, heard, go) = waits(first, rest);
let g = Group::new(1, "crates");
std::thread::scope(|s| {
let slow = s.spawn(|| h.stage_from("slow.crate", &mut body, &Expect::default()));
heard.recv().unwrap();
let other = noise(13, 100);
let staged = h
.stage_from("other.crate", &mut Cursor::new(&other), &Expect::default())
.unwrap();
h.commit(vec![HotOp::Put {
group: g.clone(),
name: "other.crate".into(),
staged,
}])
.unwrap();
h.append(&[("appended".into(), b"appended".to_vec())])
.unwrap();
assert_eq!(h.get(&g, "other.crate").unwrap().read().unwrap(), other);
go.send(()).unwrap();
let slow = slow.join().unwrap().unwrap();
assert_eq!(slow.size(), whole.len() as u64);
assert_eq!(&slow.blake3(), blake3::hash(&whole).as_bytes());
let chunks = &slow.location().chunks;
assert_eq!(chunks.len(), 2, "two runs, the others' bytes between");
assert!(chunks[1].blob_offset > chunks[0].blob_offset + chunks[0].blob_size);
assert_eq!(
slow.location().checksum(),
Some(*blake3::hash(&whole).as_bytes()),
"two runs carry the digest of the whole beside theirs"
);
h.commit(vec![HotOp::Put {
group: g.clone(),
name: "slow.crate".into(),
staged: slow,
}])
.unwrap();
});
let read = h.get(&g, "slow.crate").unwrap();
assert_eq!(read.read_verified().unwrap(), whole);
let alone = noise(14, STREAM_PIECE as u64 + 10);
let staged = h
.stage_from("alone.crate", &mut Cursor::new(&alone), &Expect::default())
.unwrap();
assert_eq!(staged.location().chunks.len(), 1, "one run, one chunk");
assert_eq!(
staged.location().checksum(),
Some(*blake3::hash(&alone).as_bytes())
);
assert_eq!(
h.staged_body(&staged).unwrap().read_verified().unwrap(),
alone
);
drop(h);
let h = HotArchive::open(&path, 3, raw()).unwrap();
assert_eq!(h.get(&g, "slow.crate").unwrap().read().unwrap(), whole);
assert!(
h.extract_file("alone.crate").is_err(),
"staged, never named"
);
}
#[test]
fn a_body_refused_after_another_writer_came_after_it_is_named_by_no_row() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let h = HotArchive::open(&path, 3, raw()).unwrap();
let (mut body, heard, go) = waits(noise(21, STREAM_PIECE as u64), noise(22, 10));
let wrong = Expect {
size: Some(1),
blake3: None,
};
std::thread::scope(|s| {
let slow = s.spawn(|| h.stage_from("slow.crate", &mut body, &wrong));
heard.recv().unwrap();
h.append(&[("after".into(), b"after".to_vec())]).unwrap();
let end = h.blob_end();
go.send(()).unwrap();
assert!(slow.join().unwrap().is_err());
assert_eq!(
h.blob_end(),
end + 10,
"the cursor does not go back over the other's bytes: the refused body's last \
piece lies after them, dead"
);
});
assert_eq!(h.rows(), 1);
assert_eq!(h.extract_file("after").unwrap(), b"after");
}
#[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 want_pieces = Some(*blake3::hash(&text(9 << 20)).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"),
want_pieces,
"a body in pieces stores the whole's beside its pieces'"
);
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"), want_pieces);
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), 9);
h.append_in(&Group::new(2, "pypi"), &[("b".into(), b"B".to_vec())])
.unwrap();
assert_eq!(schema_of(1), 13);
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));
}
}
}