use std::fs::File;
use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::error::{CorruptReason, Error, Result};
use crate::format::{self, ScanEnd};
use crate::journal;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SegmentInfo {
pub path: PathBuf,
pub base_seq: u64,
pub segment_size: u64,
pub format_version: u16,
pub created_unix_ns: u64,
}
pub fn list_segments(dir: impl AsRef<Path>) -> Result<Vec<SegmentInfo>> {
let dir = dir.as_ref();
let mut attempt = 1;
loop {
if let Some(segments) = list_once(dir, attempt == LISTING_ATTEMPTS)? {
return Ok(segments);
}
attempt += 1;
}
}
const LISTING_ATTEMPTS: u32 = 8;
const TRANSIENT_FIRST_PAUSE: Duration = Duration::from_millis(10);
const TRANSIENT_LAST_PAUSE: Duration = Duration::from_millis(320);
fn open_listed(path: &Path, last: bool) -> Result<Option<File>> {
crate::fault::hook(crate::fault::Point::InspectOpen);
match File::open(path) {
Ok(file) => Ok(Some(file)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound && !last => Ok(None),
Err(e) => Err(Error::io("open segment", path, e)),
}
}
fn list_nonempty(dir: &Path, last: bool) -> Result<Option<Vec<(u64, PathBuf)>>> {
let segments = journal::list_segments(dir)?;
match (segments.is_empty(), last) {
(false, _) => Ok(Some(segments)),
(true, false) => Ok(None),
(true, true) => Err(Error::NotFound {
dir: dir.to_path_buf(),
}),
}
}
fn list_once(dir: &Path, last: bool) -> Result<Option<Vec<SegmentInfo>>> {
let Some(segments) = list_nonempty(dir, last)? else {
return Ok(None);
};
let mut out = Vec::with_capacity(segments.len());
for (base, path) in segments {
let Some(file) = open_listed(&path, last)? else {
return Ok(None);
};
let header = journal::read_header(&file, &path, base)?;
out.push(SegmentInfo {
path,
base_seq: base,
segment_size: header.segment_size,
format_version: format::FORMAT_VERSION,
created_unix_ns: header.created_unix_ns,
});
}
Ok(Some(out))
}
pub fn read_checkpoint(dir: impl AsRef<Path>) -> Result<Option<format::CheckpointSlot>> {
use std::io::Read;
let path = dir.as_ref().join(journal::CHECKPOINT_FILE);
let file = match File::open(&path) {
Ok(file) => file,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(Error::io("open checkpoint", &path, e)),
};
let mut bytes = Vec::new();
file.take(format::CHECKPOINT_FILE_LEN as u64)
.read_to_end(&mut bytes)
.map_err(|e| Error::io("read checkpoint", &path, e))?;
Ok(format::decode_checkpoint(&bytes))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SegmentEnd {
Sealed,
Open,
Damaged,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SegmentReport {
pub info: Option<SegmentInfo>,
pub path: PathBuf,
pub records: u64,
pub end_seq: u64,
pub used_bytes: u64,
pub end: SegmentEnd,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct VerifyReport {
pub segments: Vec<SegmentReport>,
pub records: u64,
pub first_seq: Option<u64>,
pub last_seq: Option<u64>,
pub problems: Vec<Problem>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Problem {
pub path: PathBuf,
pub offset: u64,
pub reason: CorruptReason,
}
pub fn verify(dir: impl AsRef<Path>) -> Result<VerifyReport> {
let dir = dir.as_ref();
let mut attempt = 1;
loop {
if let Some(report) = verify_once(dir, attempt == LISTING_ATTEMPTS)? {
return Ok(report);
}
attempt += 1;
}
}
fn verify_once(dir: &Path, last: bool) -> Result<Option<VerifyReport>> {
let Some(segments) = list_nonempty(dir, last)? else {
return Ok(None);
};
let mut report = VerifyReport {
segments: Vec::new(),
records: 0,
first_seq: None,
last_seq: None,
problems: Vec::new(),
};
let mut expected_base = Some(segments[0].0);
let count = segments.len();
for (i, (base, path)) in segments.into_iter().enumerate() {
let newest = i + 1 == count;
let Some(file) = open_listed(&path, last)? else {
let oldest = journal::list_segments(dir)?.first().map(|(b, _)| *b);
if newest || oldest.is_none_or(|oldest| base >= oldest) {
return Ok(None);
}
report.segments.clear();
report.problems.clear();
expected_base = None;
continue;
};
let mut seg = SegmentReport {
info: None,
path: path.clone(),
records: 0,
end_seq: base,
used_bytes: 0,
end: SegmentEnd::Damaged,
};
if let Some(expected) = expected_base.filter(|expected| *expected != base) {
report.problems.push(Problem {
path: path.clone(),
offset: 0,
reason: CorruptReason::BrokenChain(expected),
});
}
let header = match journal::read_header(&file, &path, base) {
Ok(h) => h,
Err(Error::Corrupt { reason, offset, .. }) => {
report.problems.push(Problem {
path: path.clone(),
offset,
reason,
});
report.segments.push(seg);
continue;
}
Err(Error::UnsupportedVersion { .. }) => {
report.problems.push(Problem {
path: path.clone(),
offset: 8,
reason: CorruptReason::BadSegmentHeader("unsupported format version"),
});
report.segments.push(seg);
continue;
}
Err(e) => return Err(e),
};
seg.info = Some(SegmentInfo {
path: path.clone(),
base_seq: base,
segment_size: header.segment_size,
format_version: format::FORMAT_VERSION,
created_unix_ns: header.created_unix_ns,
});
let mut scan = journal::scan_open(&file, &path, base)?;
let transient = |end: ScanEnd| match end {
ScanEnd::Invalid(_) => newest,
ScanEnd::Empty => !newest,
_ => false,
};
let mut rescans = Rescans::new();
while transient(scan.end) && rescans.pause() {
scan = journal::scan_open(&file, &path, base)?;
}
let mut later = later_history(&file, &path, &scan)?;
let (mut follows, mut waited) = (0, false);
while newest && later.is_some() {
let mut word = journal::commit_word_open(&file, &path, scan.end_offset)?;
if word == 0 && !waited {
waited = true;
pause(EMPTY_WORD_WAIT);
word = journal::commit_word_open(&file, &path, scan.end_offset)?;
}
if word == 0 {
break;
}
if follows == MAX_FOLLOWS {
later = None;
break;
}
follows += 1;
let mut more = journal::scan_open_from(&file, &path, scan.end_offset, scan.next_seq)?;
while matches!(more.end, ScanEnd::Invalid(_)) && rescans.pause() {
more = journal::scan_open_from(&file, &path, scan.end_offset, scan.next_seq)?;
}
scan = format::ScanResult {
records: scan.records + more.records,
..more
};
later = later_history(&file, &path, &scan)?;
}
seg.records = scan.records;
seg.end_seq = scan.next_seq;
seg.used_bytes = scan.end_offset;
match scan.end {
ScanEnd::Seal => {
seg.used_bytes += format::SEAL_LEN as u64;
seg.end = SegmentEnd::Sealed;
if newest {
crate::fault::hook(crate::fault::Point::InspectSeal);
let successor = journal::segment_path(dir, scan.next_seq);
if journal::path_identity(&successor)?.is_none()
&& journal::path_identity(&path)?
== Some(journal::file_identity(&file, &path)?)
{
report.problems.push(Problem {
path: path.clone(),
offset: scan.end_offset,
reason: CorruptReason::BrokenChain(scan.next_seq),
});
}
}
}
ScanEnd::Empty if later.is_some() => report.problems.push(Problem {
path: path.clone(),
offset: scan.end_offset,
reason: later.map_or(CorruptReason::EmptyCommitWord(0), |h| h.reason()),
}),
ScanEnd::Empty if newest => seg.end = SegmentEnd::Open,
ScanEnd::Empty => report.problems.push(Problem {
path: path.clone(),
offset: scan.end_offset,
reason: CorruptReason::BrokenChain(scan.next_seq),
}),
ScanEnd::Invalid(reason) => report.problems.push(Problem {
path: path.clone(),
offset: scan.end_offset,
reason,
}),
}
expected_base = Some(scan.next_seq);
report.segments.push(seg);
}
report.records = report.segments.iter().map(|s| s.records).sum();
let mut with_records = report.segments.iter().filter(|s| s.records > 0);
report.first_seq = with_records.next().map(|s| s.end_seq - s.records);
report.last_seq = report
.segments
.iter()
.rev()
.find(|s| s.records > 0)
.map(|s| s.end_seq - 1);
Ok(Some(report))
}
const EMPTY_WORD_WAIT: Duration = Duration::from_millis(50);
const MAX_FOLLOWS: u32 = 8;
struct Rescans {
next: Duration,
}
impl Rescans {
fn new() -> Self {
Rescans {
next: TRANSIENT_FIRST_PAUSE,
}
}
fn pause(&mut self) -> bool {
if self.next > TRANSIENT_LAST_PAUSE {
return false;
}
pause(self.next);
self.next *= 2;
true
}
}
fn pause(duration: Duration) {
#[cfg(test)]
tests::WAIT_HOOK.with(|hook| {
if let Some(hook) = hook.borrow_mut().as_mut() {
hook();
}
});
std::thread::sleep(duration);
crate::fault::hook(crate::fault::Point::InspectRescan);
}
fn later_history(
file: &File,
path: &Path,
scan: &format::ScanResult,
) -> Result<Option<format::LaterHistory>> {
if scan.end != ScanEnd::Empty {
return Ok(None);
}
journal::history_after_empty_open(file, path, scan.end_offset, scan.next_seq)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
use std::os::unix::fs::FileExt;
thread_local! {
pub(super) static WAIT_HOOK: RefCell<Option<Box<dyn FnMut()>>> = RefCell::new(None);
}
#[test]
fn follow_loop_retries_a_record_caught_mid_append() {
let dir = tempfile::tempdir().unwrap();
let mut w = crate::Writer::open(
dir.path(),
crate::WriterConfig::default().segment_size(format::SEGMENT_SIZE_UNIT),
)
.unwrap();
for i in 0..13_u8 {
w.append(&crate::NewRecord {
schema_id: 1,
venue_ts_ns: 0,
local_ts_ns: 0,
payload: &[i; 50],
})
.unwrap();
}
drop(w);
let (_, path) = journal::list_segments(dir.path()).unwrap().pop().unwrap();
let full = std::fs::read(&path).unwrap();
let mut offsets = vec![format::SEGMENT_HEADER_LEN as u64];
for seq in 0..13 {
let at = *offsets.last().unwrap();
let Ok(format::Slot::Record { next_offset, .. }) =
format::read_slot(&full[..], at, seq)
else {
panic!("record {seq}");
};
offsets.push(next_offset);
}
let (r10, r12, end) = (
offsets[10] as usize,
offsets[12] as usize,
offsets[13] as usize,
);
let file = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
file.write_all_at(&[0; 4], r10 as u64).unwrap();
file.write_all_at(&vec![0; end - r12], r12 as u64).unwrap();
let mut stage = 0;
let (full_hook, path_hook) = (full.clone(), path.clone());
WAIT_HOOK.with(|hook| {
*hook.borrow_mut() = Some(Box::new(move || {
let file = std::fs::OpenOptions::new()
.write(true)
.open(&path_hook)
.unwrap();
match stage {
0 => {
file.write_all_at(&full_hook[r10..r10 + 4], r10 as u64)
.unwrap();
file.write_all_at(&full_hook[r12..r12 + 4], r12 as u64)
.unwrap();
}
_ => file.write_all_at(&full_hook[r12..end], r12 as u64).unwrap(),
}
stage += 1;
}));
});
let report = verify(dir.path()).unwrap();
WAIT_HOOK.with(|hook| hook.borrow_mut().take());
assert!(report.problems.is_empty(), "{:?}", report.problems);
assert_eq!(report.records, 13);
assert_eq!(std::fs::read(&path).unwrap(), full);
}
#[test]
fn follow_loop_rescans_share_the_first_scans_budget() {
let dir = tempfile::tempdir().unwrap();
let mut w = crate::Writer::open(
dir.path(),
crate::WriterConfig::default().segment_size(format::SEGMENT_SIZE_UNIT),
)
.unwrap();
for i in 0..13_u8 {
w.append(&crate::NewRecord {
schema_id: 1,
venue_ts_ns: 0,
local_ts_ns: 0,
payload: &[i; 50],
})
.unwrap();
}
drop(w);
let (_, path) = journal::list_segments(dir.path()).unwrap().pop().unwrap();
let full = std::fs::read(&path).unwrap();
let mut offsets = vec![format::SEGMENT_HEADER_LEN as u64];
for seq in 0..13 {
let at = *offsets.last().unwrap();
let Ok(format::Slot::Record { next_offset, .. }) =
format::read_slot(&full[..], at, seq)
else {
panic!("record {seq}");
};
offsets.push(next_offset);
}
let [r5, r6, r10, r12, end] = [5, 6, 10, 12, 13].map(|i| offsets[i] as usize);
let file = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
file.write_all_at(&vec![0; r6 - r5 - 4], r5 as u64 + 4)
.unwrap();
file.write_all_at(&[0; 4], r10 as u64).unwrap();
file.write_all_at(&vec![0; end - r12 - 4], r12 as u64 + 4)
.unwrap();
let pauses = std::rc::Rc::new(std::cell::Cell::new(0));
let (full_hook, path_hook, pauses_hook) = (full.clone(), path.clone(), pauses.clone());
WAIT_HOOK.with(|hook| {
*hook.borrow_mut() = Some(Box::new(move || {
let file = std::fs::OpenOptions::new()
.write(true)
.open(&path_hook)
.unwrap();
pauses_hook.set(pauses_hook.get() + 1);
match pauses_hook.get() {
6 => file.write_all_at(&full_hook[r5..r6], r5 as u64).unwrap(),
7 => file
.write_all_at(&full_hook[r10..r10 + 4], r10 as u64)
.unwrap(),
_ => {}
}
}));
});
let report = verify(dir.path()).unwrap();
WAIT_HOOK.with(|hook| hook.borrow_mut().take());
assert_eq!(
pauses.get(),
7,
"six rescans, then the 50 ms wait, and no more"
);
assert_eq!(report.problems.len(), 1, "{:?}", report.problems);
assert_eq!(report.problems[0].offset, r12 as u64);
assert_eq!(report.problems[0].reason, CorruptReason::BadChecksum);
assert_eq!(report.records, 12);
}
#[test]
fn checkpoint_missing_invalid_valid_and_truncated() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(read_checkpoint(dir.path()).unwrap(), None);
let path = dir.path().join("checkpoint");
std::fs::write(&path, [0; 64]).unwrap();
assert_eq!(read_checkpoint(dir.path()).unwrap(), None);
let slot = format::CheckpointSlot {
generation: 2,
next_seq: 7,
segment_base_seq: 0,
offset: 512,
};
std::fs::write(&path, format::encode_checkpoint_slot(&slot)).unwrap();
assert_eq!(read_checkpoint(dir.path()).unwrap(), Some(slot));
std::fs::write(&path, [0; 63]).unwrap();
assert_eq!(read_checkpoint(dir.path()).unwrap(), None);
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
assert!(matches!(read_checkpoint(dir.path()), Err(Error::Io { .. })));
}
}