use std::fs::File;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard};
use anyhow::{anyhow, ensure, Result};
use crate::archive::ZnippyReader;
use crate::hot::journal_segments;
use crate::rows::{
changed_keys, own_bytes_end, Blob, Group, Lookup, RowEntry, RowIndex, SegmentCursor,
};
use crate::stack::LayerInfo;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct HotViewStats {
pub refreshes: u64,
pub rebuilds: u64,
pub journal_bytes_read: u64,
pub untrusted_rows: u64,
}
pub struct HotView {
archive: PathBuf,
state: RwLock<ViewState>,
read: Mutex<ReadState>,
}
#[derive(Default)]
struct ViewState {
index: RowIndex,
blobs: Option<Arc<File>>,
layer: Option<LayerInfo>,
sealed: bool,
}
#[derive(Default)]
struct ReadState {
id: Option<(u64, u64)>,
cursors: Vec<SegmentCursor>,
sealed_len: Option<u64>,
stats: HotViewStats,
}
impl HotView {
pub fn open(archive: &Path) -> Result<Self> {
let v = Self {
archive: archive.to_path_buf(),
state: RwLock::new(ViewState::default()),
read: Mutex::new(ReadState::default()),
};
v.refresh()?;
Ok(v)
}
pub fn archive(&self) -> &Path {
&self.archive
}
fn state(&self) -> RwLockReadGuard<'_, ViewState> {
self.state.read().unwrap_or_else(|e| e.into_inner())
}
pub fn refresh(&self) -> Result<Vec<(Group, String)>> {
let mut rs = self.read.lock().unwrap_or_else(|e| e.into_inner());
rs.stats.refreshes += 1;
let segs = journal_segments(&self.archive)?;
let meta = match std::fs::metadata(&self.archive) {
Ok(m) => Some(m),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => return Err(anyhow!("hot view: {}: {e}", self.archive.display())),
};
if meta.is_none() && segs.is_empty() {
return Ok(Vec::new());
}
let id = meta.as_ref().map(|m| (m.dev(), m.ino()));
if segs.is_empty()
&& rs.sealed_len.is_some()
&& id == rs.id
&& meta.as_ref().map(|m| m.len()) == rs.sealed_len
{
return Ok(Vec::new());
}
let grows = !segs.is_empty()
&& id.is_some()
&& id == rs.id
&& rs.sealed_len.is_none()
&& segs[0].0 == 0
&& segs.len() >= rs.cursors.len()
&& rs
.cursors
.iter()
.zip(&segs)
.all(|(c, (n, _))| c.number == *n);
if grows && let Ok(changed) = self.read_more(&mut rs, &segs) {
return Ok(changed);
}
self.rebuild(&mut rs, &segs)
}
fn read_more(
&self,
rs: &mut ReadState,
segs: &[(u32, PathBuf)],
) -> Result<Vec<(Group, String)>> {
let mut cursors = rs.cursors.clone();
let mut fresh: Vec<RowEntry> = Vec::new();
let mut bytes = 0u64;
for c in cursors.iter_mut() {
let (e, n) = c.read_more(true)?;
bytes += n;
fresh.extend(e);
}
for (n, p) in &segs[rs.cursors.len()..] {
let mut c = SegmentCursor::new(*n, p.clone());
let (e, b) = c.read_more(true)?;
bytes += b;
fresh.extend(e);
cursors.push(c);
}
let layer = layer_of(&cursors)?;
let file_len = std::fs::metadata(&self.archive)?.len();
rs.cursors = cursors;
rs.stats.journal_bytes_read += bytes;
let mut st = self.state.write().unwrap_or_else(|e| e.into_inner());
st.layer = layer;
let mut changed = Vec::with_capacity(fresh.len());
for e in fresh {
if own_bytes_end(&e) > file_len {
rs.stats.untrusted_rows += 1;
continue;
}
changed.push((e.group.clone(), e.name.clone()));
st.index.apply(e);
}
Ok(changed)
}
fn rebuild(&self, rs: &mut ReadState, segs: &[(u32, PathBuf)]) -> Result<Vec<(Group, String)>> {
rs.stats.rebuilds += 1;
let file = match File::open(&self.archive) {
Ok(f) => Some(f),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => return Err(anyhow!("hot view: {}: {e}", self.archive.display())),
};
let id = match &file {
Some(f) => {
let m = f.metadata()?;
Some((m.dev(), m.ino()))
}
None => None,
};
let sealed = if segs.first().is_none_or(|(n, _)| *n != 0) {
file.as_ref()
.and_then(|f| crate::stack::load_sealed(f).ok())
} else {
None
};
let mut index = RowIndex::default();
let mut layer = None;
let mut cursors = Vec::new();
let mut sealed_len = None;
let journal = !segs.is_empty() && (segs[0].0 == 0 || sealed.is_none());
if journal {
let mut entries = Vec::new();
for (n, p) in segs {
let mut c = SegmentCursor::new(*n, p.clone());
let (e, b) = c.read_more(true)?;
rs.stats.journal_bytes_read += b;
entries.extend(e);
cursors.push(c);
}
layer = layer_of(&cursors)?;
let file_len = match &file {
Some(f) => f.metadata()?.len(),
None => 0,
};
for e in entries {
if own_bytes_end(&e) > file_len {
rs.stats.untrusted_rows += 1;
continue;
}
index.apply(e);
}
} else if let Some(s) = sealed {
index = s.index;
layer = s.section.and_then(|s| s.layer_info());
sealed_len = Some(s.len);
}
let mut st = self.state.write().unwrap_or_else(|e| e.into_inner());
let changed = changed_keys(&st.index, &index);
*st = ViewState {
index,
blobs: file.map(Arc::new),
layer,
sealed: sealed_len.is_some(),
};
rs.id = id;
rs.cursors = cursors;
rs.sealed_len = sealed_len;
Ok(changed)
}
pub fn lookup(&self, group: &Group, name: &str) -> Lookup {
self.state().index.lookup(group, name)
}
pub fn get(&self, group: &Group, name: &str) -> Option<Blob> {
let st = self.state();
match st.index.lookup(group, name) {
Lookup::Live(b) if b.pack.is_none() => {
st.blobs.as_ref().map(|f| Blob::new(Arc::clone(f), b))
}
_ => None,
}
}
pub fn names(&self, group: &Group) -> Vec<String> {
self.state().index.names(group)
}
pub fn groups(&self) -> Vec<Group> {
self.state().index.groups().to_vec()
}
pub fn rows(&self) -> u64 {
self.state().index.live()
}
pub fn layer(&self) -> Option<LayerInfo> {
self.state().layer
}
pub fn is_sealed(&self) -> bool {
self.state().sealed
}
pub fn stats(&self) -> HotViewStats {
self.read.lock().unwrap_or_else(|e| e.into_inner()).stats
}
pub(crate) fn file(&self) -> Option<Arc<File>> {
self.state().blobs.clone()
}
pub(crate) fn with_index<R>(&self, f: impl FnOnce(&RowIndex) -> R) -> R {
f(&self.state().index)
}
}
fn layer_of(cursors: &[SegmentCursor]) -> Result<Option<LayerInfo>> {
let mut found: Option<LayerInfo> = None;
for c in cursors {
if let Some(m) = &c.metadata
&& let Some(l) = LayerInfo::from_metadata(m)?
{
ensure!(
found.is_none_or(|f| f == l),
"hot view: the segments name two places in a stack"
);
found = Some(l);
}
}
Ok(found)
}
impl ZnippyReader for HotView {
fn list_files(&self) -> Result<Vec<String>> {
Ok(self.names(&Group::default()))
}
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 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 checksum(&self, relative_path: &str) -> Option<[u8; 32]> {
match self.lookup(&Group::default(), relative_path) {
Lookup::Live(b) => b.checksum(),
_ => None,
}
}
}
#[cfg(all(test, feature = "openzl"))]
mod tests {
use super::*;
use crate::hot::segment_path;
use crate::hot::stream_tests::noise;
use crate::HotArchive;
fn raw() -> crate::SkipPolicy {
crate::SkipPolicy::already_compressed()
}
fn files(tag: &str, n: usize, seed: u64) -> Vec<(String, Vec<u8>)> {
(0..n)
.map(|i| (format!("{tag}/{i}"), noise(seed + i as u64, 200 + i as u64)))
.collect()
}
#[test]
fn a_view_reads_what_the_writer_appended() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let h = HotArchive::open(&path, 3, raw()).unwrap();
let first = files("one", 10, 1);
h.append(&first).unwrap();
let v = HotView::open(&path).unwrap();
assert_eq!(v.rows(), 10);
let second = files("two", 5, 100);
h.append(&second).unwrap();
h.end(&Group::default(), "one/0").unwrap();
let changed = v.refresh().unwrap();
assert_eq!(changed.len(), 6, "{changed:?}");
assert!(!v.contains("one/0"));
for (p, b) in first.iter().skip(1).chain(&second) {
assert_eq!(&v.extract_file(p).unwrap(), b, "{p}");
}
assert_eq!(v.stats().rebuilds, 1, "growth is read as growth");
}
#[test]
fn a_refresh_that_fails_part_way_drops_no_row() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let h = HotArchive::open(&path, 3, raw()).unwrap();
let first = files("one", 10, 1);
h.append(&first).unwrap();
let v = HotView::open(&path).unwrap();
let second = files("two", 5, 100);
h.append(&second).unwrap();
let last = journal_segments(&path).unwrap().last().map(|(n, _)| *n);
let gone = segment_path(&path, last.expect("a segment") + 1);
std::os::unix::fs::symlink(dir.path().join("nowhere"), &gone).unwrap();
let failed = v.refresh().expect_err("a segment listed and gone");
assert!(failed.to_string().contains("No such file"), "{failed:#}");
std::fs::remove_file(&gone).unwrap();
v.refresh().unwrap();
for (p, b) in first.iter().chain(&second) {
assert_eq!(v.extract_file(p).ok().as_ref(), Some(b), "{p}");
}
assert_eq!(v.rows(), 15);
}
#[test]
fn refresh_reads_only_what_was_added() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let h = HotArchive::open(&path, 3, raw()).unwrap();
h.append(&files("seed", 100, 1)).unwrap();
let v = HotView::open(&path).unwrap();
let read0 = v.stats().journal_bytes_read;
let mut added = 0u64;
for round in 0..20u64 {
added += h
.append(&files(&format!("r{round}"), 3, round * 7))
.unwrap()
.journal_bytes_added;
}
v.refresh().unwrap();
assert_eq!(
v.stats().journal_bytes_read - read0,
added,
"exactly the bytes appended"
);
let read1 = v.stats().journal_bytes_read;
assert!(v.refresh().unwrap().is_empty());
assert_eq!(
v.stats().journal_bytes_read,
read1,
"nothing new, nothing read"
);
assert_eq!(v.stats().rebuilds, 1);
assert_eq!(v.rows(), 160);
}
#[test]
fn a_message_being_written_is_left_for_the_next_refresh() {
let src = tempfile::tempdir().unwrap();
let sp = src.path().join("a.znippy");
let h = HotArchive::open(&sp, 3, raw()).unwrap();
h.append(&files("a", 4, 1)).unwrap();
let cut_at = std::fs::metadata(segment_path(&sp, 0)).unwrap().len();
h.append(&files("b", 4, 50)).unwrap();
let seg = std::fs::read(segment_path(&sp, 0)).unwrap();
let blobs = std::fs::read(&sp).unwrap();
let dst = tempfile::tempdir().unwrap();
let dp = dst.path().join("a.znippy");
std::fs::write(&dp, &blobs).unwrap();
let half = cut_at as usize + (seg.len() - cut_at as usize) / 2;
std::fs::write(segment_path(&dp, 0), &seg[..half]).unwrap();
let v = HotView::open(&dp).unwrap();
assert_eq!(v.rows(), 4, "only the whole message");
std::fs::write(segment_path(&dp, 0), &seg).unwrap();
v.refresh().unwrap();
assert_eq!(v.rows(), 8);
assert_eq!(v.stats().rebuilds, 1);
assert_eq!(v.extract_file("b/3").unwrap(), files("b", 4, 50)[3].1);
}
#[test]
fn a_row_past_the_file_end_is_not_trusted() {
let src = tempfile::tempdir().unwrap();
let sp = src.path().join("a.znippy");
let h = HotArchive::open(&sp, 3, raw()).unwrap();
h.append(&files("a", 4, 1)).unwrap();
let dst = tempfile::tempdir().unwrap();
let dp = dst.path().join("a.znippy");
let blobs = std::fs::read(&sp).unwrap();
std::fs::write(&dp, &blobs[..blobs.len() - 10]).unwrap();
std::fs::copy(segment_path(&sp, 0), segment_path(&dp, 0)).unwrap();
let v = HotView::open(&dp).unwrap();
assert_eq!(v.rows(), 3);
assert_eq!(v.stats().untrusted_rows, 1);
assert!(!v.contains("a/3"));
}
#[test]
fn the_view_follows_a_seal_and_a_reheat() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let h = HotArchive::open(&path, 3, raw()).unwrap();
h.append(&files("a", 6, 1)).unwrap();
let v = HotView::open(&path).unwrap();
h.seal(None).unwrap();
v.refresh().unwrap();
assert!(v.is_sealed());
assert_eq!(v.rows(), 6);
assert!(
v.refresh().unwrap().is_empty(),
"an unchanged seal is not read again"
);
assert_eq!(v.stats().rebuilds, 2);
let h = HotArchive::open(&path, 3, raw()).unwrap();
h.append(&files("b", 2, 9)).unwrap();
let changed = v.refresh().unwrap();
assert!(!v.is_sealed());
assert_eq!(changed.len(), 2, "{changed:?}");
assert_eq!(v.rows(), 8);
assert_eq!(v.extract_file("a/5").unwrap(), files("a", 6, 1)[5].1);
}
#[test]
fn the_view_never_writes() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
{
let h = HotArchive::open(&path, 3, raw()).unwrap();
h.append(&files("a", 3, 1)).unwrap();
let _ = h.append_from(
&Group::default(),
"cut",
&mut crate::hot::stream_tests::Noise { s: 1, left: 0 },
&crate::Expect {
size: Some(5),
blake3: None,
},
);
}
let mut f = std::fs::OpenOptions::new()
.append(true)
.open(&path)
.unwrap();
std::io::Write::write_all(&mut f, b"orphan bytes").unwrap();
let mut j = std::fs::OpenOptions::new()
.append(true)
.open(segment_path(&path, 0))
.unwrap();
std::io::Write::write_all(&mut j, &[0xff, 0xff, 0xff, 0xff, 0x40, 0, 0, 0, 1, 2]).unwrap();
let snapshot = || {
let mut v: Vec<(String, u64)> = std::fs::read_dir(dir.path())
.unwrap()
.map(|e| {
let e = e.unwrap();
(
e.file_name().into_string().unwrap(),
e.metadata().unwrap().len(),
)
})
.collect();
v.sort();
v
};
let before = snapshot();
let v = HotView::open(&path).unwrap();
v.refresh().unwrap();
assert_eq!(v.rows(), 3);
assert_eq!(snapshot(), before, "the view changed the directory");
}
#[test]
fn pieces_are_checked_per_chunk() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("a.znippy");
let h = HotArchive::open(&path, 3, raw()).unwrap();
let body = noise(3, 3 * crate::STREAM_PIECE as u64);
h.append(&[("x".into(), body.clone())]).unwrap();
drop(h);
{
use std::os::unix::fs::FileExt;
let f = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
f.write_all_at(&[body[100] ^ 1], 100).unwrap();
}
let v = HotView::open(&path).unwrap();
let blob = v.get(&Group::default(), "x").unwrap();
assert!(blob.read_verified().is_err());
assert_eq!(blob.read().unwrap().len(), body.len());
let pieces: Vec<_> = blob.pieces(crate::STREAM_PIECE, true).unwrap().collect();
assert_eq!(
pieces.len(),
3,
"the bad digest shows at the end of the one chunk"
);
assert!(pieces[..2].iter().all(|p| p.is_ok()));
assert!(pieces[2].is_err());
}
}