pub struct Reader { /* private fields */ }Expand description
An independent cursor over a journal, in this or another process.
Readers never take locks, never write, and never slow the writer down. Any number can run at once. Each record is validated (length, CRC32C, sequence number) before it is returned.
There are two ways to open one (ADR 0006):
Reader::open(safe): reads the files withpreadinto a buffer the reader owns, and validates each record there. Memory-safe whatever other processes do to the files, and never receivesSIGBUS.Reader::open_mapped(unsafe, zero-copy): payloads point straight into a read-only mapping.
Reader doesn’t implement Iterator, because returned records borrow from the reader. Loop with while let
(zero allocations), or use Reader::records for an iterator of owned copies:
let mut reader = Reader::open("/tmp/journal", ReaderConfig::default())?;
while let Some(record) = reader.try_next()? {
println!("{} {} bytes", record.seq, record.payload.len());
}Implementations§
Source§impl Reader
impl Reader
Sourcepub fn open(dir: impl AsRef<Path>, config: ReaderConfig) -> Result<Reader>
pub fn open(dir: impl AsRef<Path>, config: ReaderConfig) -> Result<Reader>
Opens the journal in dir, positioned at the first record of the oldest segment.
If retention removes the oldest segment while the reader opens it, the reader opens the oldest segment that
remains; it doesn’t report the removed file. A directory listing that comes back empty while retention runs
(on btrfs a listing omits segments created after it started, so it can miss every segment) is listed again
rather than reported as Error::NotFound.
§Errors
Error::NotFound if dir has no segments (for example, the writer hasn’t started),
Error::Corrupt, Error::UnsupportedVersion if
the oldest segment’s header is invalid, Error::Io.
Sourcepub unsafe fn open_mapped(
dir: impl AsRef<Path>,
config: ReaderConfig,
) -> Result<Reader>
pub unsafe fn open_mapped( dir: impl AsRef<Path>, config: ReaderConfig, ) -> Result<Reader>
Like Reader::open, but returned records borrow their payload directly from the memory-mapped segment,
without copying.
Each record is validated (length, CRC32C, sequence number, flags) from atomic loads of the mapping before any
slice into it is created. The checks, their order and the errors are those of Reader::open (ADR 0027).
Segments are mapped only on x86-64 and aarch64. On other targets this opens the same reader as
Reader::open (same API and results; payloads borrow from a buffer the reader owns and nothing is mapped),
because the atomic loads used for validation are not documented as working on read-only memory there.
§Safety
While the returned reader exists, no process other than a tickertape Writer may modify
the journal’s segment files (writing into them, truncating them, or replacing their contents through other
tools). If a mapped file is truncated, the process receives SIGBUS.
What follows holds for an intact publication chain, where every commit word the reader follows is one a
writer published. A tickertape writer then never modifies committed bytes, including during crash recovery,
which in place only zeroes bytes after an empty slot (never committed, on an intact chain) and writes a seal
there, and otherwise replaces or moves whole files (docs/format.md → Recovery). A returned
payload is the bytes that were validated only because nothing modifies them afterwards.
Known limitation: a commit word damaged on storage breaks the chain, and then a mapped load can touch bytes a writer is storing to without synchronisation. If the writer runs in the same process, that is a data race, undefined behaviour in Rust’s terms, before any CRC runs; for a writer in another process the language says nothing. Two cases (ADR 0027 → “Which loads can race”):
- The length in an earlier record’s commit word is enlarged while no writer runs, and a writer then appends after that record: validating it loads bytes the writer is storing.
- The commit word of a published record not yet covered by a checkpoint is zeroed, and the next writer’s
recovery cannot tell that from a torn append (damage after which nothing validates, such as the newest
record’s commit word zeroed;
docs/crash-contract.md, C11 (3), has the cases). It then takes the slot for the end of the journal and zeroes that record and the published records after it in place, under a live zero-copy reader. A payload the caller still holds then changes, and the reader’s later loads meet the new writer’s stores. (When recovery finds evidence of the records, it usually replaces the segment by a new file instead, and mappings of the old file do not change. ADR 0035.)
That such loads return some mixture of old and new bytes, which the CRC then rejects, is an assumption about the implementation on the supported targets, not a guarantee. Earlier releases had the same exposure.
§Errors
As for Reader::open.
Sourcepub fn seek(&mut self, seq: u64) -> Result<()>
pub fn seek(&mut self, seq: u64) -> Result<()>
Positions the reader so that the next record returned is seq.
If seq hasn’t been written yet, the reader waits for it: Reader::try_next returns None until the
writer gets there, and records before seq are skipped. Every record on the way is validated, so the reader
only lands on positions along the journal’s current chain.
Retention may remove the segment holding seq while seek runs (between listing the segments and opening
the chosen one). seek then lists the segments again, so it returns Error::SeqUnavailable with the new
oldest sequence number, never an I/O error for the removed file. A segment removed just after seek
returns is still read, and the reader returns Error::Discarded at its end, as for any removed segment; a
durable-only reader may get it earlier, when the checkpoint moves past its position (ADR 0034).
§Errors
Error::SeqUnavailable if seq is older than the oldest segment, including when retention removes it
during the call;
Error::Corrupt or Error::Io while locating it. An I/O “not found” error for a segment that seek
listed is returned only if the chosen segment disappeared on each of 8 listings in a row.
Sourcepub fn try_next(&mut self) -> Result<Option<Record<'_>>>
pub fn try_next(&mut self) -> Result<Option<Record<'_>>>
Returns the next record if one is committed, without waiting for one.
Ok(None) means there is no new record yet. Follows seals into the next segment transparently.
One case does wait: a committed slot that fails validation is read again for at least 50 ms before it is
reported, because a reader’s view of a record just committed can lag (docs/crash-contract.md → Known risks
and limits). A call that ends in Error::Corrupt, or in Error::Discarded after a repair, can therefore
take that long, and Reader::next_timeout can pass its timeout by the same amount.
With ReaderConfig::durable_only enabled, records wait at the cursor until covered by a checkpoint;
a missing or invalid checkpoint marker covers no records. A marker describes the journal’s current files, so a
durable-only reader applies a marker that moves past its cursor only after confirming that its segment is still
in place; if recovery replaced it or retention removed it, the reader returns Error::Discarded then, instead
of reading on in the file it has open (ADR 0034). If it is in place, the reader reads the records the marker
newly covers from the file’s current bytes, so records that recovery removed in place are never returned
(crash contract C13 states the exception: damage that also destroys the checkpoint marker).
A visible reader can’t notice such an in-place repair (storage damage that emptied a commit word; crash
contract C11): it may return records it had already read, then continue in the new history, wait, or report
corruption at a position that no longer starts a record; Reader::seek to its position puts it back on the
current chain.
§Errors
Error::Corrupt if the bytes at the cursor fail validation. The cursor doesn’t move,
so calling again retries the same position (which may succeed after a writer recovery).
Error::Discarded if writer recovery or retention replaced or removed the segment at the cursor
(including when retention removed both it and the next segment while the reader was moving between them);
call Reader::seek to continue on the current chain. A removal is never reported as corruption or as an
I/O “not found” error.
Error::Corrupt with CorruptReason::BrokenChain if the segment at the cursor is sealed and still in
place but the next segment is missing. When the next segment is not found, the reader first reads the seal
again from the file: if the seal is gone (a repair in place can remove one the reader had read or buffered,
crash contract C11), it reads the slot as it is now; if it is still there, it tries the next segment once
more and reports the broken chain only if that misses too. A later call tries again.
Error::Io if the next segment can’t be opened, if checking whether the segment is still in place fails
other than with “not found” (only that counts as a removal), or (with kind
OutOfMemory) if the read buffer for the frame at the cursor can’t be
allocated.
Sourcepub fn next_timeout(
&mut self,
timeout: Option<Duration>,
) -> Result<Option<Record<'_>>>
pub fn next_timeout( &mut self, timeout: Option<Duration>, ) -> Result<Option<Record<'_>>>
Returns the next record, polling with the configured Backoff until one is committed or
timeout passes (None, or a timeout too large to represent: wait forever). Ok(None) means the timeout
passed. With ReaderConfig::durable_only enabled, also waits for checkpoint coverage, refreshing the marker
at most once per poll.
§Errors
As for Reader::try_next.
Sourcepub fn next_owned(&mut self) -> Result<Option<OwnedRecord>>
pub fn next_owned(&mut self) -> Result<Option<OwnedRecord>>
Sourcepub fn records(&mut self) -> Records<'_> ⓘ
pub fn records(&mut self) -> Records<'_> ⓘ
An iterator over the records committed so far, copied out of the reader, starting at the current position.
It ends at the first slot with no committed record (it doesn’t wait for more; call records() again later
or use Reader::next_timeout to follow live). After an error it yields that error once and ends; the
reader’s position is where Reader::try_next left it, so you can handle the error and continue.
let mut reader = Reader::open("/tmp/journal", ReaderConfig::default())?;
let trades: Vec<_> = reader
.records()
.filter(|r| r.as_ref().map_or(true, |r| r.schema_id == 1))
.collect::<tickertape::Result<_>>()?;Source§impl Reader
impl Reader
Sourcepub fn cursor(&self) -> Cursor
pub fn cursor(&self) -> Cursor
This reader’s cursor: the sequence number of the next record it returns (Reader::position), the slot it
reads next, whether a seek is still pending, whether it is durable-only, and its segment file. Pass it to
Status::lag.
Cost: no system calls.