mod beacon;
pub use beacon::ReaderBeacon;
use std::fs::{File, OpenOptions};
use std::io;
use std::os::unix::fs::{FileExt, MetadataExt, OpenOptionsExt};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, UNIX_EPOCH};
use crate::error::{CorruptReason, Error, Result};
use crate::format::{self, CheckpointSlot, RecordHeader, SegmentHeader, Slot};
use crate::journal::{self, Identity, PreadView};
use crate::reader::Reader;
pub const READERS_DIR: &str = "readers";
pub const DEFAULT_BEACON_INTERVAL: Duration = Duration::from_secs(1);
const VALIDATION_RETRIES: u32 = 3;
const RECORD_WINDOW: usize = 4096;
const SAMPLE_ATTEMPTS: u32 = 3;
const ROLL_ATTEMPTS: u32 = 16;
const MARKER_ATTEMPTS: u32 = 3;
const MTIME_SLACK_NS: u64 = 2_000_000_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Position {
pub next_seq: u64,
pub segment_base_seq: u64,
pub offset: u64,
}
impl Position {
pub fn new(next_seq: u64, segment_base_seq: u64, offset: u64) -> Position {
Position {
next_seq,
segment_base_seq,
offset,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Cursor {
pub next_seq: u64,
pub position: Position,
pub seek_pending: bool,
pub durable_only: bool,
file: Identity,
}
pub(crate) struct CursorParts<'r> {
pub(crate) slot_seq: u64,
pub(crate) skip_until: u64,
pub(crate) path: &'r Path,
pub(crate) offset: u64,
pub(crate) file: &'r File,
pub(crate) identity: Identity,
pub(crate) durable_only: bool,
}
impl CursorParts<'_> {
fn cursor(&self) -> Cursor {
let base = self
.path
.file_name()
.and_then(|n| n.to_str())
.and_then(format::parse_segment_file_name)
.unwrap_or(self.slot_seq);
Cursor {
next_seq: self.slot_seq.max(self.skip_until),
position: Position::new(self.slot_seq, base, self.offset),
seek_pending: self.skip_until > self.slot_seq,
durable_only: self.durable_only,
file: self.identity,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum HeadEnd {
Open,
Sealed,
Invalid(CorruptReason),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Head {
pub position: Position,
pub segment_size: u64,
pub end: HeadEnd,
pub last_local_ts_ns: Option<u64>,
pub verified: bool,
pub chain_broken: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Segments {
pub count: u64,
pub first_seq: u64,
pub total_bytes: u64,
pub oldest_created_unix_ns: Option<u64>,
pub before_checkpoint: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CheckpointProblem {
MissingSegment,
InvalidSegmentHeader,
InvalidOffset,
}
impl CheckpointProblem {
pub fn code(self) -> &'static str {
match self {
CheckpointProblem::MissingSegment => "missing_segment",
CheckpointProblem::InvalidSegmentHeader => "invalid_segment_header",
CheckpointProblem::InvalidOffset => "invalid_offset",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AgeUnknown {
NoModificationTime,
InFuture,
BeforeSegment,
MarkerResized,
Changing,
OlderSlotLost,
}
impl AgeUnknown {
pub fn code(self) -> &'static str {
match self {
AgeUnknown::NoModificationTime => "no_modification_time",
AgeUnknown::InFuture => "modification_time_in_future",
AgeUnknown::BeforeSegment => "modification_time_before_segment",
AgeUnknown::MarkerResized => "marker_resized",
AgeUnknown::Changing => "marker_changing",
AgeUnknown::OlderSlotLost => "older_slot_lost",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct CheckpointStatus {
pub marker: CheckpointSlot,
pub problem: Option<CheckpointProblem>,
pub modified_unix_ns: Option<u64>,
pub estimated_age: Option<Duration>,
pub age_unknown: Option<AgeUnknown>,
}
impl CheckpointStatus {
pub fn position(&self) -> Position {
Position::new(
self.marker.next_seq,
self.marker.segment_base_seq,
self.marker.offset,
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Exposure {
pub records: Option<u64>,
pub bytes: Option<u64>,
pub estimated_age: Option<Duration>,
pub oldest_local_ts_ns: Option<u64>,
pub verified: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Storage {
pub available_bytes: u64,
pub total_bytes: u64,
pub next_segment_size: u64,
pub spare_segment: bool,
pub estimated_rolls_left: u64,
pub estimated_time_to_full: Option<Duration>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Rates {
pub interval: Duration,
pub records_per_sec: f64,
pub bytes_per_sec: Option<f64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct WriterProcess {
pub pid: Option<u32>,
pub alive: Option<bool>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BeaconState {
Live,
Stale,
Uncertain,
Invalid,
Unreadable,
Changing,
}
impl BeaconState {
pub fn code(self) -> &'static str {
match self {
BeaconState::Live => "live",
BeaconState::Stale => "stale",
BeaconState::Uncertain => "uncertain",
BeaconState::Invalid => "invalid",
BeaconState::Unreadable => "unreadable",
BeaconState::Changing => "changing",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BeaconDirState {
Listed,
Missing,
Unusable(io::ErrorKind),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Lag {
pub records: u64,
pub bytes: Option<u64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LagUnknown {
SegmentGone,
OtherHistory,
SegmentUnreadable,
CheckpointUnusable,
AheadOfSample,
}
impl LagUnknown {
pub fn code(self) -> &'static str {
match self {
LagUnknown::SegmentGone => "segment_gone",
LagUnknown::OtherHistory => "other_history",
LagUnknown::SegmentUnreadable => "segment_unreadable",
LagUnknown::CheckpointUnusable => "checkpoint_unusable",
LagUnknown::AheadOfSample => "ahead_of_sample",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct BeaconReport {
pub pid: u32,
pub next_seq: u64,
pub position: Position,
pub seek_pending: bool,
pub durable_only: bool,
pub updated_unix_ns: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ReaderStatus {
pub name: String,
pub path: PathBuf,
pub state: BeaconState,
pub report: Option<BeaconReport>,
pub update_age: Option<Duration>,
pub lag: Option<Lag>,
pub lag_unknown: Option<LagUnknown>,
pub oldest_unread_local_ts_ns: Option<u64>,
pub unread_age: Option<Duration>,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Status {
pub dir: PathBuf,
pub sampled_unix_ns: u64,
pub head: Head,
pub segments: Segments,
pub checkpoint: Option<CheckpointStatus>,
pub exposure: Exposure,
pub storage: Storage,
pub rates: Option<Rates>,
pub writer: WriterProcess,
pub readers_dir: PathBuf,
pub readers_dir_state: BeaconDirState,
pub readers: Vec<ReaderStatus>,
files: Vec<SegFile>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct WriterMetrics {
pub head: Position,
pub segment_size: u64,
pub checkpoint: Option<CheckpointSlot>,
pub since_checkpoint: Option<Duration>,
pub uncheckpointed_records: u64,
pub uncheckpointed_bytes: u64,
pub poisoned: bool,
pub retention_failures: u64,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Thresholds {
pub max_checkpoint_age: Option<Duration>,
pub min_headroom_bytes: Option<u64>,
pub min_headroom_segments: Option<u64>,
pub max_reader_lag: Option<u64>,
}
impl Thresholds {
pub fn max_checkpoint_age(mut self, age: Duration) -> Self {
self.max_checkpoint_age = Some(age);
self
}
pub fn min_headroom_bytes(mut self, bytes: u64) -> Self {
self.min_headroom_bytes = Some(bytes);
self
}
pub fn min_headroom_segments(mut self, segments: u64) -> Self {
self.min_headroom_segments = Some(segments);
self
}
pub fn max_reader_lag(mut self, records: u64) -> Self {
self.max_reader_lag = Some(records);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Breach {
HeadInvalid,
CheckpointInvalid,
ChainBroken,
CheckpointAge,
HeadroomBytes,
HeadroomSegments,
ReaderLag {
name: String,
},
}
impl Breach {
pub fn code(&self) -> &'static str {
match self {
Breach::HeadInvalid => "head_invalid",
Breach::CheckpointInvalid => "checkpoint_invalid",
Breach::ChainBroken => "chain_broken",
Breach::CheckpointAge => "checkpoint_age",
Breach::HeadroomBytes => "headroom_bytes",
Breach::HeadroomSegments => "headroom_segments",
Breach::ReaderLag { .. } => "reader_lag",
}
}
pub fn is_corruption(&self) -> bool {
matches!(
self,
Breach::HeadInvalid | Breach::CheckpointInvalid | Breach::ChainBroken
)
}
}
impl Status {
pub fn lag(&self, cursor: &Cursor) -> std::result::Result<Lag, LagUnknown> {
let file = self.listed(cursor.position.segment_base_seq)?;
if file.file != cursor.file {
return Err(LagUnknown::OtherHistory);
}
self.lag_from(
cursor.next_seq,
cursor.position,
cursor.seek_pending,
cursor.durable_only,
)
}
fn listed(&self, base: u64) -> std::result::Result<&SegFile, LagUnknown> {
self.files.iter().find(|f| f.base == base).ok_or_else(|| {
if self.files.last().is_some_and(|f| base > f.base) {
LagUnknown::AheadOfSample
} else {
LagUnknown::SegmentGone
}
})
}
fn lag_from(
&self,
next_seq: u64,
position: Position,
seek_pending: bool,
durable_only: bool,
) -> std::result::Result<Lag, LagUnknown> {
let target = if durable_only {
match &self.checkpoint {
None => {
return Ok(Lag {
records: 0,
bytes: Some(0),
});
}
Some(c) if c.problem.is_some() => return Err(LagUnknown::CheckpointUnusable),
Some(c) => c.position(),
}
} else {
self.head.position
};
let records = target.next_seq.saturating_sub(next_seq);
let bytes = if records == 0 {
Some(0)
} else if seek_pending {
None
} else {
footprint(&self.files, position, target)
};
Ok(Lag { records, bytes })
}
pub fn breaches(&self, thresholds: &Thresholds) -> Vec<Breach> {
let mut out = Vec::new();
if matches!(self.head.end, HeadEnd::Invalid(_)) {
out.push(Breach::HeadInvalid);
}
if self.checkpoint.is_some_and(|c| c.problem.is_some()) {
out.push(Breach::CheckpointInvalid);
}
if self.head.chain_broken {
out.push(Breach::ChainBroken);
}
if let Some(max) = thresholds.max_checkpoint_age {
let just_written = self.checkpoint.is_some_and(|c| {
c.problem.is_none() && c.age_unknown == Some(AgeUnknown::Changing)
});
if !just_written
&& self.exposure.records != Some(0)
&& self.exposure.estimated_age.is_none_or(|age| age > max)
{
out.push(Breach::CheckpointAge);
}
}
if thresholds
.min_headroom_bytes
.is_some_and(|min| self.storage.available_bytes < min)
{
out.push(Breach::HeadroomBytes);
}
if thresholds
.min_headroom_segments
.is_some_and(|min| self.storage.estimated_rolls_left < min)
{
out.push(Breach::HeadroomSegments);
}
if let Some(max) = thresholds.max_reader_lag {
for reader in &self.readers {
if matches!(reader.state, BeaconState::Live | BeaconState::Uncertain)
&& reader.lag.is_some_and(|l| l.records > max)
{
out.push(Breach::ReaderLag {
name: reader.name.clone(),
});
}
}
}
out
}
}
pub fn status(dir: impl AsRef<Path>) -> Result<Status> {
Sampler::new(dir).sample()
}
#[derive(Debug, Clone)]
pub struct Sampler {
dir: PathBuf,
readers_dir: PathBuf,
previous: Option<Previous>,
}
#[derive(Debug, Clone)]
struct Previous {
at: Instant,
head: Head,
head_seg: SegId,
_pinned: std::sync::Arc<File>,
origin: u64,
last_record: Option<(u64, RecordHeader)>,
marker: Option<CheckpointSlot>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct SegFile {
base: u64,
size: u64,
file: Identity,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct SegId {
base: u64,
file: Identity,
created_unix_ns: u64,
size: u64,
}
#[derive(Debug)]
struct Opened {
id: SegId,
file: File,
path: PathBuf,
}
#[derive(Debug, Default)]
struct OpenSegments {
opened: Vec<Opened>,
}
impl OpenSegments {
fn get(&mut self, dir: &Path, base: u64) -> Result<&Opened> {
if let Some(i) = self.opened.iter().position(|o| o.id.base == base) {
return Ok(&self.opened[i]);
}
let opened = open_segment(dir, base)?;
self.opened.push(opened);
Ok(self.opened.last().expect("just pushed"))
}
fn take(&mut self, base: u64) -> Option<File> {
let i = self.opened.iter().position(|o| o.id.base == base)?;
Some(self.opened.swap_remove(i).file)
}
}
impl Sampler {
pub fn new(dir: impl AsRef<Path>) -> Sampler {
let dir = dir.as_ref().to_path_buf();
Sampler {
readers_dir: dir.join(READERS_DIR),
dir,
previous: None,
}
}
pub fn readers_dir(mut self, readers_dir: impl AsRef<Path>) -> Sampler {
self.readers_dir = readers_dir.as_ref().to_path_buf();
self
}
pub fn sample(&mut self) -> Result<Status> {
let mut attempt = 1;
loop {
match self.sample_once() {
Err(Error::Io { source, .. })
if source.kind() == io::ErrorKind::NotFound && attempt < SAMPLE_ATTEMPTS =>
{
attempt += 1;
}
other => return other,
}
}
}
fn sample_once(&mut self) -> Result<Status> {
let at = Instant::now();
let (mut files, mut marker) = list_with_marker(&self.dir)?;
let mut open = OpenSegments::default();
let mut rolls = 0;
let (head, head_seg, origin, start, scan_first, last_record, proven) = loop {
let slot = marker.as_ref().and_then(|m| m.slot);
let newest = *files
.last()
.expect("list_with_marker never returns an empty listing");
let seg = open.get(&self.dir, newest.base)?;
let id = seg.id;
let size = id.size;
let marker_here = slot
.filter(|c| c.segment_base_seq == id.base && valid_offset(c.offset, size))
.map(|c| Position::new(c.next_seq, c.segment_base_seq, c.offset));
let fresh = match marker_here {
Some(m) => (m, m.offset),
None => (
Position::new(id.base, id.base, format::SEGMENT_HEADER_LEN as u64),
format::SEGMENT_HEADER_LEN as u64,
),
};
let proven = self
.previous
.as_ref()
.filter(|p| p.head_seg == id && valid_offset(p.head.position.offset, size))
.filter(|p| p.last_record.is_none_or(|(at, h)| record_is(seg, at, h)));
let resumed = proven.filter(|p| match marker_here {
Some(m) if m.offset > p.head.position.offset => false,
Some(m) if p.marker != slot && m.offset >= p.origin => {
if m.offset == p.head.position.offset {
m.next_seq == p.head.position.next_seq
} else {
matches!(slot_at(seg, m), Some(Ok(Slot::Record { .. })))
}
}
_ => true,
});
let (start, origin, carried) = match resumed {
Some(p) => (p.head.position, p.origin, Some(p)),
None => (fresh.0, fresh.1, None),
};
let scan = scan_from(&seg.file, &seg.path, size, start)?;
if scan.end == HeadEnd::Sealed {
let successor = journal::segment_path(&self.dir, scan.end_position.next_seq);
if std::fs::symlink_metadata(&successor).is_ok() {
rolls += 1;
if rolls >= ROLL_ATTEMPTS {
return Err(Error::io(
"sample journal head",
&self.dir,
io::Error::other(format!(
"the writer rolled {ROLL_ATTEMPTS} times during one sample"
)),
));
}
(files, marker) = list_with_marker(&self.dir)?;
continue;
}
}
let last_record = match (scan.last, scan.last_at) {
(Some(h), Some(at)) => Some((at, h)),
_ => proven.and_then(|p| p.last_record),
};
let head = Head {
position: scan.end_position,
segment_size: size,
end: scan.end,
last_local_ts_ns: match scan.last {
Some(h) => Some(h.local_ts_ns).filter(|&ts| ts != 0),
None => carried.and_then(|p| p.head.last_local_ts_ns),
},
verified: false,
chain_broken: false,
};
break (
head,
id,
origin,
start,
scan.first,
last_record,
proven.is_some(),
);
};
let mut head = head;
let first = files[0];
let slot = marker.as_ref().and_then(|m| m.slot);
let (readers_dir_state, observed) = beacon::observe_all(&self.readers_dir);
let now_ns = crate::clock::realtime_ns();
let checkpoint = match (slot, marker.as_ref()) {
(Some(c), Some(m)) => Some(checkpoint_status(
&self.dir, &files, &mut open, c, m, now_ns,
)?),
_ => None,
};
let usable = checkpoint.filter(|c| c.problem.is_none());
let covered_from = match (&checkpoint, usable) {
(_, Some(c)) => Some(c.position()),
(None, _) => Some(Position::new(
first.base,
first.base,
format::SEGMENT_HEADER_LEN as u64,
)),
(Some(_), None) => None,
};
head.chain_broken = covered_from.is_some_and(|c| missing_segment(&files, c, head_seg.base));
let head_invalid = matches!(head.end, HeadEnd::Invalid(_));
head.verified = !head.chain_broken
&& !head_invalid
&& covered_from.is_some_and(|c| {
c.segment_base_seq == head_seg.base
&& origin <= c.offset
&& c.next_seq <= head.position.next_seq
});
let oldest_created_unix_ns = open
.get(&self.dir, first.base)
.ok()
.map(|o| o.id.created_unix_ns);
let segments = Segments {
count: files.len() as u64,
first_seq: first.base,
total_bytes: files.iter().fold(0u64, |sum, f| sum.saturating_add(f.size)),
oldest_created_unix_ns,
before_checkpoint: checkpoint.map_or(0, |c| {
files
.iter()
.filter(|f| f.base < c.marker.segment_base_seq)
.count() as u64
}),
};
let records = covered_from
.filter(|_| !head.chain_broken && !head_invalid)
.and_then(|c| head.position.next_seq.checked_sub(c.next_seq));
let oldest_local_ts_ns = match (records, covered_from) {
(Some(n), Some(c)) if n > 0 => {
if start == c && scan_first.is_some() {
scan_first.map(|h| h.local_ts_ns).filter(|&ts| ts != 0)
} else {
open.get(&self.dir, c.segment_base_seq)
.ok()
.and_then(|seg| record_at(&self.dir, seg, c))
.map(|h| h.local_ts_ns)
.filter(|&ts| ts != 0)
}
}
_ => None,
};
let exposure = Exposure {
records,
bytes: match (records, covered_from) {
(Some(0), _) => Some(0),
(Some(_), Some(c)) => footprint(&files, c, head.position),
_ => None,
},
estimated_age: match records {
Some(0) => Some(Duration::ZERO),
Some(_) => usable.and_then(|c| c.estimated_age),
None => None,
},
oldest_local_ts_ns,
verified: head.verified,
};
let rates = self.previous.as_ref().and_then(|p| {
let interval = at.checked_duration_since(p.at)?;
let secs = interval.as_secs_f64();
if secs <= 0.0 || head.position.next_seq < p.head.position.next_seq {
return None;
}
let continued = if p.head_seg == head_seg {
proven
} else {
p.head_seg.base < head_seg.base
&& open
.get(&self.dir, p.head_seg.base)
.is_ok_and(|o| o.id == p.head_seg)
};
continued.then(|| Rates {
interval,
records_per_sec: (head.position.next_seq - p.head.position.next_seq) as f64 / secs,
bytes_per_sec: footprint(&files, p.head.position, head.position)
.map(|b| b as f64 / secs),
})
});
let storage = storage(&self.dir, &head, rates)?;
let writer = writer_process(&self.dir);
let mut status = Status {
dir: self.dir.clone(),
sampled_unix_ns: now_ns,
head,
segments,
checkpoint,
exposure,
storage,
rates,
writer,
readers_dir: self.readers_dir.clone(),
readers_dir_state,
readers: Vec::new(),
files,
};
let readers = observed
.into_iter()
.map(|o| reader_status(&status, &self.dir, &mut open, o, now_ns))
.collect();
status.readers = readers;
let pinned = open
.take(head_seg.base)
.map(std::sync::Arc::new)
.expect("the head's segment was opened by this sample");
self.previous = Some(Previous {
at,
head,
head_seg,
_pinned: pinned,
origin,
last_record,
marker: slot,
});
Ok(status)
}
}
impl Reader {
pub fn cursor(&self) -> Cursor {
self.cursor_parts().cursor()
}
}
fn list_with_marker(dir: &Path) -> Result<(Vec<SegFile>, Option<Marker>)> {
let mut files = list_files(dir)?;
let mut marker = read_marker(dir)?;
let named = |m: &Option<Marker>| m.as_ref().and_then(|m| m.slot);
let mut attempts = 0;
while let Some(c) =
named(&marker).filter(|c| files.iter().all(|f| f.base != c.segment_base_seq))
{
attempts += 1;
if attempts > MARKER_ATTEMPTS {
return Err(Error::io(
"sample journal",
dir,
io::Error::other(
"the checkpoint marker kept naming segments the listing didn't show yet",
),
));
}
files = list_files(dir)?;
let again = read_marker(dir)?;
let unchanged = named(&again) == Some(c);
marker = again;
if unchanged {
break;
}
}
if files.is_empty() {
return Err(match named(&marker) {
Some(c) => Error::corrupt(
dir.join(journal::CHECKPOINT_FILE),
0,
CorruptReason::DanglingCheckpoint(c.segment_base_seq),
),
None => Error::NotFound {
dir: dir.to_path_buf(),
},
});
}
Ok((files, marker))
}
fn list_files(dir: &Path) -> Result<Vec<SegFile>> {
let listed = journal::list_segments(dir)?;
let mut files = Vec::with_capacity(listed.len());
for (base, path) in &listed {
let meta = std::fs::metadata(path).map_err(|e| Error::io("stat segment", path, e))?;
files.push(SegFile {
base: *base,
size: meta.len(),
file: (meta.dev(), meta.ino()),
});
}
Ok(files)
}
fn open_plain(path: &Path, follow: bool) -> io::Result<File> {
let mut flags = libc::O_NONBLOCK | libc::O_CLOEXEC;
if !follow {
flags |= libc::O_NOFOLLOW;
}
let file = OpenOptions::new()
.read(true)
.custom_flags(flags)
.open(path)?;
if !file.metadata()?.is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"not a regular file",
));
}
Ok(file)
}
fn open_segment(dir: &Path, base: u64) -> Result<Opened> {
let path = journal::segment_path(dir, base);
let file = open_plain(&path, true).map_err(|e| Error::io("open segment", &path, e))?;
let header: SegmentHeader = journal::read_header(&file, &path, base)?;
let file_id = journal::file_identity(&file, &path)?;
Ok(Opened {
id: SegId {
base,
file: file_id,
created_unix_ns: header.created_unix_ns,
size: header.segment_size,
},
file,
path,
})
}
fn valid_offset(offset: u64, size: u64) -> bool {
offset % format::RECORD_ALIGN as u64 == 0
&& offset >= format::SEGMENT_HEADER_LEN as u64
&& offset <= size.saturating_sub(format::SEGMENT_TRAILER_LEN as u64)
}
fn footprint(files: &[SegFile], from: Position, to: Position) -> Option<u64> {
if from.segment_base_seq == to.segment_base_seq {
return to.offset.checked_sub(from.offset);
}
if from.segment_base_seq > to.segment_base_seq {
return None;
}
let i = files
.binary_search_by_key(&from.segment_base_seq, |f| f.base)
.ok()?;
let j = files
.binary_search_by_key(&to.segment_base_seq, |f| f.base)
.ok()?;
let rest = files[i].size.saturating_sub(from.offset);
let between = files[i + 1..j]
.iter()
.fold(0u64, |sum, f| sum.saturating_add(f.size));
Some(rest.saturating_add(between).saturating_add(to.offset))
}
fn missing_segment(files: &[SegFile], from: Position, head_base: u64) -> bool {
let min_frame = format::align8(format::RECORD_HEADER_LEN as u64);
let (Ok(i), Ok(j)) = (
files.binary_search_by_key(&from.segment_base_seq, |f| f.base),
files.binary_search_by_key(&head_base, |f| f.base),
) else {
return false;
};
let (mut seq, mut offset) = (from.next_seq, from.offset);
for k in i..j {
let end = files[k]
.size
.saturating_sub(format::SEGMENT_TRAILER_LEN as u64);
let most = seq.saturating_add(end.saturating_sub(offset) / min_frame);
if files[k + 1].base > most {
return true;
}
seq = files[k + 1].base;
offset = format::SEGMENT_HEADER_LEN as u64;
}
false
}
struct ScanOut {
end_position: Position,
end: HeadEnd,
first: Option<RecordHeader>,
last: Option<RecordHeader>,
last_at: Option<u64>,
}
fn read_slot_retrying(
view: &PreadView<'_>,
path: &Path,
offset: u64,
seq: u64,
) -> Result<std::result::Result<Slot, CorruptReason>> {
let mut attempt = 0;
loop {
let slot = format::read_slot(view, offset, seq);
if let Some(e) = view.take_error() {
return Err(Error::io("read segment", path, e));
}
match slot {
Err(_) if attempt < VALIDATION_RETRIES => {
attempt += 1;
view.invalidate();
}
other => return Ok(other),
}
}
}
fn scan_from(file: &File, path: &Path, size: u64, start: Position) -> Result<ScanOut> {
let view = PreadView::new(file, size, journal::SCAN_WINDOW);
let mut position = start;
let mut first = None;
let mut last = None;
let mut last_at = None;
let end = loop {
match read_slot_retrying(&view, path, position.offset, position.next_seq)? {
Ok(Slot::Empty) => break HeadEnd::Open,
Ok(Slot::Seal) => break HeadEnd::Sealed,
Err(reason) => break HeadEnd::Invalid(reason),
Ok(Slot::Record {
header,
next_offset,
..
}) => {
let Some(next_seq) = position.next_seq.checked_add(1) else {
break HeadEnd::Invalid(CorruptReason::SequenceExhausted);
};
first.get_or_insert(header);
last = Some(header);
last_at = Some(position.offset);
position.offset = next_offset;
position.next_seq = next_seq;
}
}
};
Ok(ScanOut {
end_position: position,
end,
first,
last,
last_at,
})
}
fn slot_at(seg: &Opened, position: Position) -> Option<std::result::Result<Slot, CorruptReason>> {
let view = PreadView::new(&seg.file, seg.id.size, RECORD_WINDOW);
read_slot_retrying(&view, &seg.path, position.offset, position.next_seq).ok()
}
fn record_is(seg: &Opened, offset: u64, header: RecordHeader) -> bool {
matches!(
slot_at(seg, Position::new(header.seq, seg.id.base, offset)),
Some(Ok(Slot::Record { header: h, .. })) if h == header
)
}
fn record_at(dir: &Path, seg: &Opened, position: Position) -> Option<RecordHeader> {
let view = PreadView::new(&seg.file, seg.id.size, RECORD_WINDOW);
match read_slot_retrying(&view, &seg.path, position.offset, position.next_seq).ok()? {
Ok(Slot::Record { header, .. }) => Some(header),
Ok(Slot::Seal) => {
let next = open_segment(dir, position.next_seq).ok()?;
let view = PreadView::new(&next.file, next.id.size, RECORD_WINDOW);
let at = format::SEGMENT_HEADER_LEN as u64;
match read_slot_retrying(&view, &next.path, at, position.next_seq).ok()? {
Ok(Slot::Record { header, .. }) => Some(header),
_ => None,
}
}
_ => None,
}
}
#[derive(Debug, Clone, Copy)]
struct Marker {
slot: Option<CheckpointSlot>,
len: u64,
modified_unix_ns: Option<u64>,
changing: bool,
older_slot_lost: bool,
}
fn marker_stamp(meta: &std::fs::Metadata) -> (u64, u64, i64, i64, i64, i64) {
(
meta.ino(),
meta.len(),
meta.mtime(),
meta.mtime_nsec(),
meta.ctime(),
meta.ctime_nsec(),
)
}
fn read_marker(dir: &Path) -> Result<Option<Marker>> {
let path = dir.join(journal::CHECKPOINT_FILE);
let file = match open_plain(&path, true) {
Ok(file) => file,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(Error::io("open checkpoint", &path, e)),
};
let stat = |file: &File| {
file.metadata()
.map_err(|e| Error::io("stat checkpoint", &path, e))
};
let mut last = None;
for _ in 0..MARKER_ATTEMPTS {
let before = stat(&file)?;
let len = before.len();
let mut slots = [None, None];
let mut short = false;
for (slot, at) in slots.iter_mut().zip(format::CHECKPOINT_SLOT_OFFSETS) {
let end = (at + format::CHECKPOINT_SLOT_LEN) as u64;
if end > len.min(format::CHECKPOINT_FILE_LEN as u64) {
continue;
}
let mut buf = [0u8; format::CHECKPOINT_SLOT_LEN];
match file.read_exact_at(&mut buf, at as u64) {
Ok(()) => *slot = format::decode_checkpoint_slot(&buf),
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => short = true,
Err(e) => return Err(Error::io("read checkpoint", &path, e)),
}
}
let after = stat(&file)?;
let slot = match slots {
[Some(a), Some(b)] => Some(if a.generation > b.generation { a } else { b }),
[a, b] => a.or(b),
};
let marker = Marker {
slot,
older_slot_lost: slot.is_some_and(|current| {
current.generation >= 2
&& !slots
.iter()
.flatten()
.any(|s| s.generation == current.generation - 1)
}),
len,
modified_unix_ns: before
.modified()
.ok()
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
.map(|d| u64::try_from(d.as_nanos()).unwrap_or(u64::MAX)),
changing: false,
};
if !short && marker_stamp(&before) == marker_stamp(&after) {
return Ok(Some(marker));
}
last = Some(marker);
}
Ok(last.map(|m| Marker {
changing: true,
..m
}))
}
fn checkpoint_status(
dir: &Path,
files: &[SegFile],
open: &mut OpenSegments,
c: CheckpointSlot,
marker: &Marker,
now_ns: u64,
) -> Result<CheckpointStatus> {
let mut created = None;
let problem = if files.iter().all(|f| f.base != c.segment_base_seq) {
Some(CheckpointProblem::MissingSegment)
} else {
match open.get(dir, c.segment_base_seq) {
Ok(seg) => {
created = Some(seg.id.created_unix_ns);
(!valid_offset(c.offset, seg.id.size)).then_some(CheckpointProblem::InvalidOffset)
}
Err(Error::Corrupt { .. } | Error::UnsupportedVersion { .. }) => {
Some(CheckpointProblem::InvalidSegmentHeader)
}
Err(e) => return Err(e),
}
};
let age_unknown = if marker.changing {
Some(AgeUnknown::Changing)
} else if marker.len != format::CHECKPOINT_FILE_LEN as u64 {
Some(AgeUnknown::MarkerResized)
} else if marker.older_slot_lost {
Some(AgeUnknown::OlderSlotLost)
} else {
match marker.modified_unix_ns {
None => Some(AgeUnknown::NoModificationTime),
Some(m) if m > now_ns => Some(AgeUnknown::InFuture),
Some(m) if created.is_some_and(|c| m.saturating_add(MTIME_SLACK_NS) < c) => {
Some(AgeUnknown::BeforeSegment)
}
Some(_) => None,
}
};
let estimated_age = match (age_unknown, marker.modified_unix_ns) {
(None, Some(m)) => Some(Duration::from_nanos(now_ns - m)),
_ => None,
};
Ok(CheckpointStatus {
marker: c,
problem,
modified_unix_ns: marker.modified_unix_ns,
estimated_age,
age_unknown,
})
}
fn storage(dir: &Path, head: &Head, rates: Option<Rates>) -> Result<Storage> {
let vfs = rustix::fs::statvfs(dir)
.map_err(|e| Error::io("statvfs journal directory", dir, e.into()))?;
let available_bytes = vfs.f_bavail.saturating_mul(vfs.f_frsize);
let total_bytes = vfs.f_blocks.saturating_mul(vfs.f_frsize);
let spare = std::fs::symlink_metadata(dir.join(journal::SPARE_FILE))
.ok()
.filter(|m| m.is_file() && format::validate_segment_size(m.len()).is_ok())
.map(|m| (m.len(), m.blocks().saturating_mul(512) >= m.len()));
Ok(estimate_storage(
available_bytes,
total_bytes,
spare,
head,
rates,
))
}
fn estimate_storage(
available_bytes: u64,
total_bytes: u64,
spare: Option<(u64, bool)>,
head: &Head,
rates: Option<Rates>,
) -> Storage {
let next_segment_size = spare.map_or(head.segment_size, |(len, _)| len).max(1);
let spare_segment = spare.is_some_and(|(_, allocated)| allocated);
let estimated_rolls_left = available_bytes / next_segment_size;
let estimated_time_to_full = rates
.and_then(|r| r.bytes_per_sec)
.filter(|&rate| rate > 0.0)
.and_then(|rate| {
let left_in_active = match head.end {
HeadEnd::Sealed => 0,
_ => head.segment_size.saturating_sub(head.position.offset),
};
let bytes = left_in_active
.saturating_add(estimated_rolls_left.saturating_mul(next_segment_size));
Duration::try_from_secs_f64(bytes as f64 / rate).ok()
});
Storage {
available_bytes,
total_bytes,
next_segment_size,
spare_segment,
estimated_rolls_left,
estimated_time_to_full,
}
}
fn writer_process(dir: &Path) -> WriterProcess {
use std::io::Read;
let pid = open_plain(&dir.join(journal::LOCK_FILE), false)
.ok()
.and_then(|f| {
let mut text = String::new();
f.take(32).read_to_string(&mut text).ok()?;
text.trim().parse::<u32>().ok()
});
let alive = pid
.and_then(|p| i32::try_from(p).ok())
.and_then(rustix::process::Pid::from_raw)
.and_then(|p| match rustix::process::test_kill_process(p) {
Ok(()) => Some(true),
Err(e) if e == rustix::io::Errno::PERM => Some(true),
Err(e) if e == rustix::io::Errno::SRCH => Some(false),
Err(_) => None,
});
WriterProcess { pid, alive }
}
fn reader_status(
status: &Status,
dir: &Path,
open: &mut OpenSegments,
observed: beacon::Observed,
now_ns: u64,
) -> ReaderStatus {
let mut out = ReaderStatus {
name: observed.name,
path: observed.path,
state: observed.state,
report: None,
update_age: None,
lag: None,
lag_unknown: None,
oldest_unread_local_ts_ns: None,
unread_age: None,
};
let Some(payload) = observed.payload else {
return out;
};
let report = payload.report;
out.report = Some(report);
out.update_age = now_ns
.checked_sub(report.updated_unix_ns)
.map(Duration::from_nanos);
let base = report.position.segment_base_seq;
let identity = match status.listed(base) {
Err(reason) => Err(reason),
Ok(f) if f.file != payload.segment_file || f.size != payload.segment_size => {
Err(LagUnknown::OtherHistory)
}
Ok(_) => match open.get(dir, base) {
Ok(seg)
if seg.id.file == payload.segment_file
&& seg.id.size == payload.segment_size
&& seg.id.created_unix_ns == payload.segment_created_unix_ns =>
{
Ok(())
}
Ok(_) => Err(LagUnknown::OtherHistory),
Err(Error::Io { source, .. }) if source.kind() == io::ErrorKind::NotFound => {
Err(LagUnknown::SegmentGone)
}
Err(_) => Err(LagUnknown::SegmentUnreadable),
},
};
let lag = identity.and_then(|()| {
status.lag_from(
report.next_seq,
report.position,
report.seek_pending,
report.durable_only,
)
});
match lag {
Err(reason) => out.lag_unknown = Some(reason),
Ok(lag) => {
out.lag = Some(lag);
if lag.records == 0 {
out.unread_age = Some(Duration::ZERO);
} else if !report.seek_pending {
out.oldest_unread_local_ts_ns = open
.get(dir, base)
.ok()
.and_then(|seg| record_at(dir, seg, report.position))
.map(|h| h.local_ts_ns)
.filter(|&ts| ts != 0);
out.unread_age = out
.oldest_unread_local_ts_ns
.and_then(|ts| now_ns.checked_sub(ts))
.map(Duration::from_nanos);
}
}
}
out
}
#[cfg(test)]
mod tests;