Writing a tape¶
An application that records data hands it to a writer, which turns it into the blocks of a tape. What does the application hand over, and what does the writer add on its own? Four calls carry the data, and the writer adds the blocks that let a reader find and understand it. The examples count the calls of the drive's recorder over an hour.
The writer serves one thread at a time. A recorder with several sources writes through a mux instead, which owns the writer on a thread of its own. Writing from many threads explains it, and the drive's recorder writes so. Each handle of the mux sends units, and the mux turns each into one call of the writer.
The writer and its sink¶
A TapeWriter turns the application's calls into blocks of a piece. The application keeps its definitions
and hands over the data. The writer adds the blocks that the piece needs around that data. These are puts of
definitions and state, checkpoints, and at the end the final index, close and tail.
The writer puts its bytes into a sink: any type that implements TapeSink. A sink appends bytes, syncs them,
reports its size and completes the piece at the close. To resume a piece, it also reads bytes back and truncates them.
Two sinks come with the crates. A MemSink keeps the bytes in memory, where a TapeReader reads them while they
are written. A FileSink, in the crate ww_tape_fs, writes a file.
A chain needs one sink per piece, so it takes a store instead: any type that implements PieceStore. A store
makes the sink of each piece under a key. MemPieces keeps every piece in memory, and FilePieces keeps them in a
directory or in one file. A raw medium or a network store needs a sink and a store of its own.
Errors of sinks and stores¶
Each sink and store has its own error type: MemError for memory and FsError for files. A WriteError carries
that error in WriteError::Sink, together with the step that failed. A store refuses to make a tape that exists
already or that another writer holds, and names the tape by its key.
The writer's settings¶
The writer's settings are its WriterOptions. Each field has a default that suits a file on a disk:
| Field | What it sets | Explained in |
|---|---|---|
sync |
when the writer syncs | Files and syncing |
index |
when the writer places checkpoints | Anatomy of a piece |
layout |
how blocks are placed, such as payloads on 4 KiB | Aligned files |
producer |
the producer's name | Definitions and state |
near |
how the writer remembers puts and spaces state copies | Near, puts and copies |
clock |
the clock that decides when an interval is up | Files and syncing |
Four calls for data¶
The drive's recorder hands the hour to the mux through four handles. Each second it puts the mode and sends one records block of log lines and temperatures. It also sends a chunk of CAN frames and pushes a second of phase current. The mux turns each into one call of the writer, and adds the summary blocks of the phase current.
cargo run -p example_drive counts the calls:
| Handle call | Writer call | Count |
|---|---|---|
StateHandle::put, the mode |
TapeWriter::put |
3600 (9 wrote) |
RecordsHandle::send, log lines and temperatures |
TapeWriter::write_block |
3600 |
ChunkSender::send, can0 |
TapeWriter::write_chunk |
3600 |
GridHandle::push, phase_a |
TapeWriter::write_chunk_hashed |
3600 |
none: the mux's summaries of phase_a |
TapeWriter::defer_block |
2948 |
Only 9 of the 3600 puts wrote a record. A put writes its state item only when no record of the same item lies near behind, as Definitions and state explains. The recorder therefore puts the mode before every block and never keeps track of what it put.
Records blocks¶
The application builds a records block with a BlockWriter, as A first tape
shows. It hands the finished bytes to TapeWriter::write_block, which returns where the block landed as a
ww_tape::Placed: its offset from the start of the piece and its length. A block of puts lands as no single block,
and for such a block the call returns None. Through a mux, a RecordsHandle sends the bytes, and the mux's
ProgressWatch tells the piece and the bytes written.
Chunks¶
The application hands a chunk head and its encoded columns to TapeWriter::write_chunk. The writer builds the
chunk block around them and returns its ww_tape::Placed. For a chunk, Placed::unit is the chunk's unit hash.
The writer states that hash and does not verify it, so a writer in the same process folds range hashes without
reading the piece back. Event times and their codecs shows how the recorder encodes its frames, and
Samples and their codecs its samples.
A typed handle of a mux encodes the chunk on its producer's thread and hashes its payload there. The mux then calls
TapeWriter::write_chunk_hashed, which takes the payload's hash as given instead of computing it. The bytes are
those of TapeWriter::write_chunk.
A PieceChain writes a chunk with PieceChain::write_chunk, which returns a ChunkPlaced. It holds the same
fields and the sequence number of the piece that the chunk landed in. The call may cut to a new piece first, so the
caller learns where the chunk went.
What each kind of track takes¶
Each kind of track takes only its own form of data. A state track takes its items only through puts. The writer therefore refuses a caller's record or events chunk on a state track. A series has no records: its samples go into series chunks, each with its grid and scale in the head. The writer refuses a record, a put or an events chunk on a series track.
Definitions with every call¶
The writer keeps no table of definitions. Whoever drives it holds them in a Definitions container and passes it
by reference with every write of data and every put. A mux holds the container itself, so its handles never name a
definition. A program that drives the writer directly passes it. Before each block, the writer puts the definitions that the
block's tracks need: the clocks, maps and bundles a track names, then the track itself.
let mut defs = Definitions::new();
defs.define_clock(clock)?;
defs.define_track(temperature_track)?; // track 1, the one the readings name
let mode = defs.define_track(mode_track)?;
writer.put(&defs, mode, ticks, &mode_bytes)?; // a state item, at its use
writer.write_block(&defs, &readings)?; // the definitions it needs go first
A put writes a definition only where the same one does not lie near behind, so most blocks cost no definitions. The
writer refuses data on a track that the container does not hold. It also refuses a chunk whose head gives the track's
number with another id than the definition (DescribeError::TrackId).
How many definitions to hold¶
How many definitions to hold is the application's choice. A recorder of 10 000 sensors may hold 10 000 track definitions and pass them all with each block. A block of 3 sensors' readings gets only those 3 definitions and their clock written before it. The writer writes each of them once per 32 MiB, plus one state copy.
A track added an hour into the recording costs one record at its first block. An item that belongs to no track, such as
a description of the run, goes in with TapeWriter::put_item. The writer refuses a block of definitions that the caller wrote, so
every definition in a file lies near the data that needs it.
What the writer adds¶
The writer's own blocks hold what a reader needs to find and understand the data. For the drive's hour they are the piece heads, the puts, the checkpoints and the end of each piece:
| Blocks | Made by | Count | Bytes |
|---|---|---|---|
| piece head | the writer | 4 | 2064 |
| records blocks of puts and copies | the writer | 32 | 5652 |
| records blocks | the recorder | 3600 | 811071 |
| events chunks | the recorder | 3600 | 8400924 |
| series chunks | the recorder | 3600 | 99617283 |
| summary blocks | the mux | 2948 | 3301304 |
| checkpoints | the writer | 24 | 1584128 |
| final index | the writer | 4 | 1772160 |
| close | the writer | 4 | 11958 |
| tail | the writer | 4 | 656 |
The writer's own blocks take 3.4 MB of the hour's 116 MB, 2.9 %. Most of that is index: the checkpoints while the pieces grow, and each piece's final index. The 32 blocks of puts hold every definition and mode change of four pieces in 5.5 kB.
What the writer checks¶
The writer checks what it is handed in proportion to the cost. For a chunk that it builds from columns, it checks the head and the column table. It checks the chunk's track against the definitions, and a series chunk's ticks against its grid. It copies the caller's columns as they are and does not read them back.
A caller's whole block, handed to TapeWriter::write_block, TapeWriter::adopt_block or
TapeWriter::defer_block, is read once. The writer checks every CRC in it, a CRC-32C. Beyond that, each byte
placed costs one more pass: the content hash. Samples and their codecs
measures what these passes cost per chunk.
The writer does not compare a series chunk's grid with the chunk before it. A reader's SeriesTimeline does
(Series). The writer computes each CRC with the processor's CRC
instructions where it has them, and with a table elsewhere, with the same result.
Nothing is filled in later¶
A writer never goes back to change bytes it already wrote. Every block is final once placed, and the file only grows. This rule gives the format its shape:
- The piece's length and the place of its index are in the tail at the end, not in a header at the start.
- Checkpoints point back at the checkpoint before them, never forward at one not yet written.
- A tail cannot name the next piece's hash, which does not exist yet. It names the next piece's id instead.
- A new definition is a new record. The old one stays, and only readers after the new one see it replaced.
- A state copy is written at a use, never scheduled ahead, so nothing is left pending when the writer stops.
- A crash costs only the bytes not yet synced. No header exists that would be wrong after it.
Append-only writing suits every medium a tape targets. A NAND flash page takes one program, and a SD card is fastest in long sequential writes. A tool can also read a file whole while the file grows, since it is only appended.
Deferred blocks¶
Some blocks may wait. A summary block of a series is the usual case: a SeriesSummaries or an EventTree from
ww_tape_summary fills one as data comes. The mux, or an application that drives the writer itself, hands such a
block to TapeWriter::defer_block, and the writer chooses where it lands. That makes it a deferred block. The writer puts the block's definitions at once, and
where it places the block depends on the file's layout.
Aligned files¶
Disks, the page cache and direct input and output all work in blocks of 4 KiB, or in sectors that divide that size. A 4 KiB boundary is an offset in the file that 4096 divides. An aligned file starts every chunk's payload, the column bytes after its head, on such a boundary. Its samples then begin at the start of a page of the page cache and of a sector on the disk.
A reader gains three things from that:
- Memory maps. A reader maps the file and uses a chunk's samples in place, as a slice that starts on a page. A vector kernel or a copy engine takes it without moving a byte.
- Direct input and output. Reads that bypass the page cache, such as
O_DIRECTon Linux, need offsets and lengths in whole blocks. A payload on a boundary reads that way with no bytes before it. - Raw media. On a card or a disk without a file system, a payload on a boundary covers whole sectors. Reading one chunk's samples then reads no sector of the block before it.
Choose it with the layout Layout::ALIGNED, or call TapeWriter::set_alignment before the first block. In a file
that is not aligned, blocks follow each other with nothing between them, and a deferred block lands at once.
In an aligned file, the space before a payload holds zeros in the chunk's own head. The writer fills that gap with deferred blocks while they fit. A deferred block waits at most 1 MiB of writes for a gap that fits it.
phase_a alone, the waiting summary fills part of that gap. In the
drive's file, the next second's put of the mode places the summary first, so the gap holds zeros only. Drawn by
ww_tape_figures from the drive's first minute at full rate.Alignment costs the drive more than a series alone. The hour takes 129 MB aligned against 116 MB, 12 % more. In the aligned drive file, 0 of the 2948 summary blocks lie in a gap. Each second starts with a put of the mode and a records block, before the next series chunk. Every put and every block handed over places the waiting deferred blocks first, even a put that writes nothing.
A file of phase_a alone takes 112 MB aligned against 105 MB, 7.3 % more. There 2724 of the 2933 summary blocks fill
gaps. Alignment therefore suits a file that holds mostly series and is read by memory maps or direct input and
output. Alignment is optional: where space matters more than such reads, leave the file unaligned. The drive's
recorder keeps its mixed file unaligned.
Closing¶
TapeWriter::close places the deferred blocks still waiting and writes the final index, the close and the tail.
Files and syncing follows the syncs that make a file's close durable. The call
returns a writer::Closed, which holds the piece's content hash, its length and each track's next item number.
A close ends a write session, not the piece. A writer that opens a closed piece again writes on after its close. The next close names the one before it (Closing more than once). A piece closed again with nothing appended stays as it was, to the byte.
TapeWriter::close_with_summary closes with a summary block of the application's own, up to 1 MiB of any bytes. A
reader fetches it from the tail without a scan (The close summary).
TapeWriter.TapeReader.pub struct TapeWriter<S: TapeSink>
Appends blocks to a TapeSink, a file by default, see the module docs.
pub trait TapeSink
Where a TapeWriter appends its bytes.
TapeSink.pub struct MemSink<K = u64> {
tape: MemPiece<K>,
/// Where the piece being written starts in the bytes
base: u64,
/// The tape holds pieces back to back ([PieceStore::create_whole], [PieceStore::open_whole])
whole: bool,
}
pub struct TapeReader<S> {
src: S,
len: u64,
/// [ByteSource::start]: no piece is looked for before it
front: u64,
/// [OpenOptions::check_payloads] as it applies to the source
check_payloads: bool,
pieces: Vec<PieceInfo>,
/// [OpenOptions::state_read_max]
state_read_max: u64,
/// The pieces' state entries sorted, shared by the reader's lookups
states: state::StateCache,
}
A tape read by positional reads, see the module docs.
pub struct FileSink {
file: Locked,
path: PathBuf,
/// Where the piece being written starts in the file
base: u64,
/// The file holds pieces back to back ([TapeSink::holds_pieces])
pieces: bool,
/// Set when the file is on a network or user-space file system
warning: Option<FsWarning>,
}
A file of one piece or of pieces back to back, written under its own name from the start and appended to.
Whether the piece is open, closed or torn is read from its bytes (its close and tail), never from its name.
pub trait PieceStore
A store of pieces by key: makes the sink of each piece of a PieceChain, reopens one to write on and reads a closed one; under one key it may also keep every piece of a chain back to back.
A store keeps one writer per key: a second sink of bytes a sink holds is refused.
pub struct MemPieces<K = u64>(Arc<Mutex<BTreeMap<K, MemPiece<K>>>>);
Pieces in memory by key, shared by every clone: a PieceStore (keyed by a piece's seq with K = u64), and
where its readers find each piece (Self::get).
pub struct FilePieces(Names);
Piece files: a PieceStore of FileSinks keyed by a piece's seq, each piece a file of a directory, or every key the one file that holds all pieces of a chain.
PieceStore; the book never uses store as a verb.pub enum MemError<K = u64>
Why a MemSink, MemPiece or MemPieces failed or refused; a refusal of MemPieces names the tape by its key
K.
pub enum FsError
Why a FileSink, FilePieces or FileSource failed or refused.
pub enum WriteError<E>
Why a TapeWriter stopped; E is the error of its sink (TapeSink::Error).
Sink { what: &'static str, error: E },
The sink or its store failed or refused (another writer holds the bytes, a new piece is there already), with what was being done.
pub struct WriterOptions
How a TapeWriter places what it adds: what TapeWriter::resume_on needs to rebuild one, and what a crate::PieceChain gives each of its pieces.
pub struct BlockWriter<'b> {
buf: &'b mut [u8],
state: BlockState,
}
Writes one block into a buffer: BlockWriter::push records, then BlockWriter::finish.
pub fn write_block(
&mut self,
defs: &Definitions,
block: &[u8],
) -> Result<Option<Placed>, WriteError<S::Error>> {
self.check()?;
let b = crate::Block::read(block).map_err(WriteError::Block)?;
if b.is_repeat() {
return self.put_block(defs, block).map(|()| None);
}
self.write_read(defs, &b)
}
Append one whole block (its bytes as crate::Block::bytes gives them, its session and seq as made, see Self::next_id), then sync if the policy says so.
pub struct Placed {
/// Where the block starts, from the start of the piece.
pub offset: u64,
/// The whole block's length.
pub len: u32,
/// The chunk's unit hash ([TrackHash::chunk_unit]) as this writer states it in the chunk's index entry and folds
/// it into its track's hash; [UnitHash::NONE] for a block that is no chunk. Stated, not verified: the same value
/// a reader takes from the index entry, so a writer in the same process can fold range hashes without reading
/// the piece back.
pub unit: UnitHash,
}
Where TapeWriter::write_chunk, TapeWriter::write_block or TapeWriter::adopt_block placed the block it was asked to write.
pub struct RecordsHandle<T: PieceStore> {
s: Sender<T>,
}
Sends records blocks built with [ww_tape::BlockWriter]: log lines, records of several tracks.
The mux numbers each block as the writer's next, whatever id it was built with. Any number of these handles may write the same tracks.
pub struct ProgressWatch {
watch: Arc<Watch>,
}
Wakes a reader in the writer's process when the writing thread placed more (crate::TapeMux::watch).
pub fn write_chunk(
&mut self,
defs: &Definitions,
head: &crate::ChunkHead,
columns: &[(crate::ColumnSpec, &[u8])],
) -> Result<Placed, WriteError<S::Error>> {
self.write_chunk_as(defs, head, columns, None, false)
}
Encode and append a chunk block numbered Self::next_seq, its track checked against defs.
pub unit: UnitHash,
The chunk's unit hash (TrackHash::chunk_unit) as this writer states it in the chunk's index entry and folds it into its track's hash; UnitHash::NONE for a block that is no chunk.
pub fn write_chunk_hashed(
&mut self,
defs: &Definitions,
head: &crate::ChunkHead,
columns: &[(crate::ColumnSpec, &[u8])],
payload: [u8; 32],
) -> Result<Placed, WriteError<S::Error>> {
self.write_chunk_as(defs, head, columns, Some(payload), false)
}
Self::write_chunk with the hash of the chunk's payload given: payload is
columns_payload_hash of columns, computed by the producer on its own
thread, so the writer hashes no payload.
pub struct PieceChain<T: PieceStore> {
store: T,
pieces: PieceTapes,
/// None after a failed cut: the chain takes no more blocks
writer: Option<TapeWriter<T::Sink>>,
cut: CutPolicy,
/// When the current piece was started or resumed, by its writer's clock
started: Option<u64>,
seq: u64,
closed: Vec<ChainPiece<T::Key>>,
}
Writes one recording as pieces on the tapes of a PieceStore (files by default), each piece a tape of its own or all in one (PieceTapes), cutting by a CutPolicy before a chunk.
pub fn write_chunk(
&mut self,
defs: &Definitions,
head: &ChunkHead,
columns: &[(ColumnSpec, &[u8])],
) -> Result<ChunkPlaced, WriteError<T::Error>> {
self.write_chunk_as(defs, head, columns, None)
}
A chunk (TapeWriter::write_chunk), in a new piece when [Self::cut_due]: a cut happens before a chunk, never after the last one, so no piece is left empty.
pub struct ChunkPlaced {
pub seq: u64,
pub offset: u64,
pub len: u32,
/// The chunk's unit hash as the writer states it ([Placed::unit]).
pub unit: UnitHash,
}
Where PieceChain::write_chunk placed the chunk: the seq of the piece it landed in (PieceChain::seq by the time the call returns, past a cut when one happened) and where in that piece.
mode; the writer keeps its items near their uses.pub struct Definitions
The definitions an application works with, see the module docs.
TrackId {
track: TrackNum,
id: TrackId,
defined: TrackId,
},
A chunk or summary whose head names track track with id id, not the id defined its held definition
gives (TrackDef::id).
pub fn put_item(
&mut self,
defs: &Definitions,
item: &TypedItem<'_>,
) -> Result<bool, WriteError<S::Error>>
Put the typed item item on track 0, after its bundle where defs holds it and it doesn't lie close behind:
written unless the same item lies within track 0's near (crate::Layout::definitions) and no copy is due.
Whether it was written.
pub fn adopt_block(
&mut self,
defs: &Definitions,
block: &[u8],
) -> Result<Option<Placed>, WriteError<S::Error>>
Append a block of any session as the writer's own: renumbered into the writer's session and next seq (crate::set_id), then as Self::write_block.
pub fn defer_block(
&mut self,
defs: &Definitions,
block: Vec<u8>,
) -> Result<(), WriteError<S::Error>>
A small summary or data block that may wait for the gap in front of the next aligned chunk payload: checked
against defs and the definitions it needs put now, as for a block written now; when it is placed, nothing
is put.
pub struct SeriesTimeline {
period: Ratio64,
stretches: Vec<SeriesStretch>,
}
The grids of one series track, from its chunk heads in any order, checked as they come.
pub struct SeriesSummaries<T: Scalar> {
leaves: SeriesLeaves<T>,
tree: SeriesTree,
}
Builds the summary tree of one series track as samples come, and encodes its summary blocks.
pub struct EventTree {
track_id: TrackId,
track_number: TrackNum,
fields: EventFields,
origin: u64,
next_item: u64,
/// The open level-0 node
acc: Option<EventNode>,
levels: Levels<EventNode>,
blocks: Vec<Vec<u8>>,
/// Last start of the last closed level-0 node
last_tick: Option<i64>,
}
Builds the item tree of one event track as items are completed, and encodes its summary blocks.
pub const ALIGNED: Self = Self {
alignment: Bytes::new(ALIGNMENT),
..Self::UNALIGNED
};
Chunk payloads on 4 KiB boundaries, a file: no gaps.
pub fn set_alignment(&mut self, alignment: u32) -> Result<(), WriteError<S::Error>> {
let layout = Layout {
alignment: exact_units::Bytes::new(alignment),
..self.layout
};
self.set_layout(layout)
}
Place chunk payloads on multiples of alignment (0 or crate::ALIGNMENT), counted from the start of the file:
the writer's layout with that alignment (Self::set_layout).
pub fn close(self) -> Result<Closed, WriteError<S::Error>> {
self.close_as(CloseReason::Closed)
}
Close the piece (CloseReason::Closed) and sync it.
pub struct Closed
What a closed piece is.
pub fn close_with_summary(
self,
reason: CloseReason,
body: &[u8],
) -> Result<Closed, WriteError<S::Error>> {
self.end(End::Close(reason), Some(body)).map(|e| e.closed)
}
Self::close_as with a summary of the caller's own: body, at most
CLOSE_SUMMARY_MAX bytes, goes into a summary block right before the final
index, which the close names (Close::summary) and its content hash covers.
pub fn put(&self, ticks: i64, item: &[u8]) -> Result<Sent, MuxError<T::Error>> {
let (work, bytes) = self.unit(ticks, item);
self.s.send(work, bytes)
}
Put item at ticks of the track's clock.
pub fn put(
&mut self,
defs: &Definitions,
track: TrackNum,
ticks: i64,
item: &[u8],
) -> Result<bool, WriteError<S::Error>>
Put item on state track track of defs at ticks of its clock: the producer uses it now, and puts it at
each use. It is written, after the track's definition and what it names where those don't lie close behind,
unless the newest record of the track is the same item at most the track's near behind in the piece and no
copy is due (near). Deferred blocks are placed first.
pub fn send(&self, block: Vec<u8>) -> Result<Sent, MuxError<T::Error>> {
let (work, bytes) = self.unit(block)?;
self.s.send(work, bytes)
}
Send a records block. One that doesn't read, or of another kind, is refused before it is sent.
pub fn send(
&self,
head: ChunkHead,
columns: Vec<(ColumnSpec, Vec<u8>)>,
) -> Result<Sent, MuxError<T::Error>> {
let (work, bytes) = self.unit(head, columns)?;
self.s.send(work, bytes)
}
Send a chunk: its head and its columns, each spec's length that of its bytes. A chunk of another track or kind, or a column whose length is off, is refused before it is sent (CallError).
pub fn push(&mut self, steps: &[S]) -> Result<Option<Sent>, MuxError<T::Error>> {
self.push_flagged(steps, 0)
}
Add whole time steps of the handle's box (Self::step_len scalars each) on the current grid. Each chunk they fill is sent: what became of the last.