Definitions and state¶
A reader that opens a recording in the middle needs facts that were first written long before. It needs to know what each track is, and which values were in force at that point. A tape therefore keeps such facts close to every place that needs them, so that a reader anywhere finds them within 32 MiB.
The drive's fault at minute 52, for example, lies in the last of its four pieces. A viewer that has only that piece needs the definitions of the drive's tracks and the mode the controller was in, a state item.
What a definition says¶
A reader needs some facts before the data means anything. A definition states one of them:
- the producer, the program that writes the tape;
- the layout, how the writer places blocks;
- an API bundle, the WireWeaver description of the producer's API, which gives each item's type;
- a clock or a clock map;
- a track: its number, key, clock, kind and what its items are;
- a schema of a foreign item format, such as a
.protofile; - a typed item, such as a description of the run.
Each definition is a record on track 0, the track that holds only definitions. The drive's definitions are its two clocks, the map between them and its five tracks.
Slots¶
Each definition fills a slot that follows from the definition itself:
- a track's slot is its track number;
- a clock's slot is its clock number;
- a map's slot is the two clocks it links;
- a bundle's slot is its hash, and so is a schema's;
- the producer and the layout have one slot each.
A newer record in a slot replaces the older one for every reader after it. A reader at a place therefore takes the newest record of each slot behind that place, and has every definition in force there. Adding a track an hour into a recording costs one record, however many tracks the file already has.
The definitions an application holds¶
The definitions belong to the application, not to the file. The application keeps the definitions of what it works
on in a Definitions container and passes the container with every write. Defining writes nothing to the tape:
the writer places each definition just before the first data that needs it.
Definitions::define_clock and Definitions::define_track hold a clock or a track. Each returns the
number it gives, the lowest not yet taken, so the application never picks a number. Defining the same clock key again
gives the same number back. So does the same track key with the same dimensions, in any order.
A resume gives the numbers the tape already holds, in Resumed::numbers. Definitions::with_numbers starts
a container with them, so every clock and track defined again keeps its number and a new one takes a number not yet
taken. A chain's resume reads them from every piece still there, the last one up to its close,
also when it starts a new piece. A track or clock defined only in a piece removed since loses its number:
no piece left names it. Resumed::numbers_unread counts the definitions the resume could not read, damaged or
past its budget: a track or clock among them may get a new number.
Each definition is checked against those already held. A track or a map must name clocks that the container holds.
An epoch clock must come with its link, which Definitions::define_clock_with_maps defines with it.
Definitions::define_all holds several maps, bundles or schemas at once.
Definitions::close drops a track, and the clocks, maps and bundles that no held track names go with it. The
container reports how many definitions it holds and their size in bytes, and the application decides how many to keep.
The drive holds 8 definitions in 469 bytes. The test below takes them from the example, puts the mode three times and closes a track:
use ww_tape::{MemSink, SyncPolicy, TapeWriter};
use example_drive::{Mode, definitions};
// The definitions, and the numbers they gave the drive's clocks and tracks.
let (mut defs, numbers) = definitions(25_000, true, 32 << 20).expect("the drive's definitions");
let (can0, mode) = (numbers.can0, numbers.mode);
assert_eq!((defs.len(), defs.bytes()), (8, 469));
let mut w = TapeWriter::create_on(MemSink::new(), SyncPolicy::None);
// The first put writes the mode, with the definitions it needs.
assert!(w.put(&defs, mode, 0, Mode::Run.item()).expect("put"));
// The same mode 1 ms later lies close behind: the put writes nothing.
assert!(!w.put(&defs, mode, 1_000, Mode::Run.item()).expect("put"));
// A new mode is written.
assert!(w.put(&defs, mode, 2_000, Mode::Fault.item()).expect("put"));
// Closing can0 drops its definition; the clocks stay, since other tracks name them.
assert!(defs.close(can0));
assert_eq!(defs.len(), 7);
The producer and the layout belong to the writer, which takes them from WriterOptions. The writer puts them
after every piece head, before the first block of a file, and when a block starts another session. It refuses a
block of definitions that the caller wrote. A relay that passes on another producer's blocks uses
TapeWriter::relay_block, which holds the definitions those blocks carry and puts them by the writer's own rule.
Every call that puts a definition or an item uses the producer and the layout too. They so get copies and are put again as the tracks' definitions are, and a piece whose first blocks are lost still names them.
State¶
Most tracks are streams of events: a frame received at one tick says nothing about the next tick. Some
tracks hold state instead: an item that stays in force until the next one replaces it. The drive's mode is
such a state track: idle from boot, run from minute 1, fault from minute 52. Definitions are state too, on track 0.
A reader at a place needs the item in force there to understand the data after it. A reader that reads a file from its start always knows the state, because it has seen every record. A reader that starts in the middle looks backwards for the newest record of the slot. That works only when the record lies in bytes the reader has.
Why a reader needs state close behind¶
A record written once at the start of a week-long file lies a week of bytes away. Three readers then fail, even with unlimited time:
- A reader of a file whose start is damaged: the only record may lie in the damaged bytes.
- A reader of one piece of a long recording: the record lies in a piece it does not have.
- A reader that joins a live feed late: the record went out before it joined.
The format therefore keeps every state item close behind each place that uses it, in the same piece. The first reader finds a copy past the damage, and the second finds one inside its piece. The third has every item once it has received that much of the feed.
Near, puts and copies¶
A state track's policy, a StatePolicy in TrackRepeat::State, holds two numbers:
- Near is how far behind a use the item must lie in the same piece, 32 MiB by default.
copiesis how many extra records an item gets after it is first written in a piece, as a guard against damage around one place. The default is one state copy, at least 1 MiB after the first record.
Each time the producer uses a state item, it puts the item: it calls TapeWriter::put at that place. The
writer compares the item, by its hash, with the newest record of its slot. When the same item lies less than
near behind, the put writes nothing. Otherwise the put writes the item again, and a reader at this place finds it
close behind.
A put is idempotent, so the producer keeps no memory of what it put before. The drive's recorder puts the mode before
each one-second block, 901 times while it writes the first piece. Only four of those puts write, as cargo run -p
example_drive prints. They are idle at the start, its copy at 40 seconds, run at minute 1 and its copy at 96 seconds.
The piece ends at about 28 MiB, before the record of run lies 32 MiB behind, so no other put writes.
The writer puts definitions the same way before every block of data, by the layout's own policy. The drawing shows the rule shrunk, so that a whole cycle fits on one line.
near behind. Drawn by
ww_tape_figures from the blocks TapeWriter wrote, with near shrunk to 8 KiB and the copy
spacing to 2 KiB.A record that a put or a copy writes goes into a block with the flag FLAG_REPEAT in its header. A reader that
already holds the same item in that slot takes the record as nothing new. The writer never writes a state item ahead of
a use, so a track whose data has stopped costs nothing until its data continues.
A series holds no state. Each series chunk carries its own grid, which gives the tick of one sample and the scale of the stored numbers. The chunk places its samples alone, so nothing needs to stay near it. Anatomy of a piece shows where the definitions, the puts and the data sit in a whole piece.
TapeReader.pub struct Definitions
The definitions an application works with, see the module docs.
TapeWriter.pub fn define_clock(&mut self, c: ClockSpec<'_>) -> Result<ClockNum, DescribeError> {
self.define_clock_with_maps(c, &[])
}
Define clock c and give its number: the one its key has (Numbers), else the lowest not taken.
pub fn define_track(&mut self, t: TrackSpec<'_>) -> Result<TrackNum, DescribeError> {
let number = self.numbers.track_for(t.id(), t.owner)?;
self.hold(&[Describe::Track(t.numbered(number))])?;
Ok(number)
}
Define track t and give its number: the one its identity has (Numbers), else the lowest not taken. It is
held as Self::define holds a definition, replacing the one of the same identity; its clock is held. A refused
track takes no number; the error names the one it would have had.
pub numbers: crate::Numbers,
Which number stands for which track and clock in the definitions the resume read: the walked blocks, and the puts after the head of a piece written on after its close.
pub fn with_numbers(numbers: Numbers) -> Self {
Self {
numbers,
..Self::default()
}
}
No definitions, numbering tracks and clocks as numbers does: those a resumed piece holds
(crate::Resumed::numbers), so a track or clock defined again gets its number there.
pub numbers_unread: usize,
Track and clock definitions a chain's resume could not read in the pieces before the resumed piece's own writes: blocks that don't read, items that don't decode, and one per piece whose lookup budget (OpenOptions::state_read_max) ran out.
pub fn define_clock_with_maps(
&mut self,
c: ClockSpec<'_>,
maps: &[(ClockNum, &[MapSegment])],
) -> Result<ClockNum, DescribeError>
Define clock c as Self::define_clock does, with a map from it to each held clock to of maps over its
segments, checked as one batch: an Epoch clock with its epoch link.
pub fn define_all(&mut self, defs: &[Describe<'_>]) -> Result<(), DescribeError> {
if defs
.iter()
.any(|d| matches!(d, Describe::Track(_) | Describe::Clock(_)))
{
return Err(DescribeError::Numbered);
}
self.hold(defs)
}
Hold each of defs as Self::define does, checked as one batch in any order; none is held when one is
refused.
pub fn close(&mut self, number: TrackNum) -> bool
Drop track number: its definition goes, and with it the clocks, maps and bundles no held track names any
more. Nothing is written. False when it wasn't held.
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 fn relay_block(
&mut self,
defs: &mut Definitions,
block: &[u8],
) -> Result<(), WriteError<S::Error>> {
let b = crate::Block::read(block).map_err(WriteError::Block)?;
if !b.is_repeat() {
self.check()?;
return self.write_read(defs, &b).map(|_| ());
}
let mut buf = Vec::new();
defs.take_block(&b.decode(&mut buf).map_err(WriteError::Block)?)?;
self.put_block(defs, block)
}
Pass on a live producer's block, as a relay does: a block of puts (FLAG_REPEAT) has its
definitions held in defs (Definitions::take_block) and its records put (Self::put_block); any other
block is written under defs (Self::write_block).
mode; the writer keeps its items near their uses.pub struct StatePolicy {
/// An item used at a place has a copy at most this many bytes behind it, in the same piece: how far a reader
/// looks back for it.
pub near: Bytes<u32>,
/// Copies an item gets after it is first written in a piece, spaced apart (a writer's
/// [NearPolicy::copy_spacing](crate::writer::NearPolicy)), against damage around one place; 0 for none.
pub copies: Count<Item, u8>,
}
How a writer repeats the items of a state track, or of track 0 (Layout::definitions).
State(StatePolicy),
Each record is the track's state from then on: a writer puts it (TapeWriter::put)
so that a copy lies at most near behind wherever it is used, and a reader takes the nearest record behind a
place.
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 const FLAG_REPEAT: u16 = 1 << 1;
Header flag: the block holds state records a writer put or copied (state), not new items of the producer's: it carries the seq of the block before it and takes no part in the seq order.
A reader holding an item of the same hash in the same slot takes such a record as nothing new.