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 segments = journal::list_segments(dir)?;
if segments.is_empty() {
return Err(Error::NotFound {
dir: dir.to_path_buf(),
});
}
segments
.into_iter()
.map(|(base, path)| {
let file = File::open(&path).map_err(|e| Error::io("open segment", &path, e))?;
let header = journal::read_header(&file, &path, base)?;
Ok(SegmentInfo {
path,
base_seq: base,
segment_size: header.segment_size,
format_version: format::FORMAT_VERSION,
created_unix_ns: header.created_unix_ns,
})
})
.collect()
}
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 segments = journal::list_segments(dir)?;
if segments.is_empty() {
return Err(Error::NotFound {
dir: dir.to_path_buf(),
});
}
let mut report = VerifyReport {
segments: Vec::new(),
records: 0,
first_seq: None,
last_seq: None,
problems: Vec::new(),
};
let mut expected_base = segments[0].0;
let count = segments.len();
for (i, (base, path)) in segments.into_iter().enumerate() {
let newest = i + 1 == count;
let mut seg = SegmentReport {
info: None,
path: path.clone(),
records: 0,
end_seq: base,
used_bytes: 0,
end: SegmentEnd::Damaged,
};
if base != expected_base {
report.problems.push(Problem {
path: path.clone(),
offset: 0,
reason: CorruptReason::BrokenChain(expected_base),
});
}
let file = File::open(&path).map_err(|e| Error::io("open segment", &path, e))?;
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 = scan_file(&path, base)?;
if newest && matches!(scan.end, ScanEnd::Invalid(_)) {
std::thread::sleep(Duration::from_millis(50));
scan = scan_file(&path, base)?;
}
seg.records = scan.records;
seg.end_seq = scan.next_seq;
seg.used_bytes = scan.end_offset;
report.records += scan.records;
if scan.records > 0 {
report.first_seq.get_or_insert(base);
report.last_seq = Some(scan.next_seq - 1);
}
match scan.end {
ScanEnd::Seal => {
seg.used_bytes += format::SEAL_LEN as u64;
seg.end = SegmentEnd::Sealed;
if newest {
report.problems.push(Problem {
path: path.clone(),
offset: scan.end_offset,
reason: CorruptReason::BrokenChain(scan.next_seq),
});
}
}
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 = scan.next_seq;
report.segments.push(seg);
}
Ok(report)
}
fn scan_file(path: &Path, base: u64) -> Result<format::ScanResult> {
journal::scan_file(path, base)
}
#[cfg(test)]
mod tests {
use super::*;
#[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 { .. })));
}
}