A first tape¶
A recorder writes a tape through a few calls of a writer, and a reader opens what it wrote. The shortest useful program writes items into a file, closes the file and reads the items back. It shows each call a recorder makes and what the file holds afterwards. The program here writes the drive's first minute.
Running the program¶
The program of this chapter lives in the crate example_drive, beside the drive's recording. Run it from a
checkout of ww_tape:
It writes the drive's first minute into a file drive.wwt in a directory of the system's temporary directory, and
names the file. Then it opens the file and prints one line for each track:
1634304 bytes in one piece
track 1 log records 180 items
track 2 mode state in force: "idle"
track 3 can0 events chunks 60000 items
track 4 phase_a series chunks 1500000 items
track 5 temp records 60 items
The counts follow from the drive's rates, which What a tape holds lists. A second holds three log lines, one temperature, 1 000 frames and 25 000 samples. The mode is idle, because the drive starts to run only after its first minute. A test checks that the program prints these lines, so they change with the code that makes them.
The definitions come first¶
A writer refuses an item of a track it does not know. Every write therefore takes the definitions of
the recording along: what each track holds and the clock its times count on. The program gets them from
Drive::definitions as a Definitions container, which holds eight of them:
- the board's clock, in microseconds since its boot;
- the host's clock, in nanoseconds since 1970;
- a clock map that turns board time into host time;
- the five tracks
log,mode,can0,phase_aandtemp.
Defining a clock or a track gives it a small number, which every record and chunk in the file names it by. The
container picks the number, and Drive::definitions keeps them in a DriveNumbers for the program to write with.
The application never writes a definition itself. The writer puts each one into the file just before the first block that needs it. It puts it again wherever the last one lies too far behind. Tracks and items shows how to define a track of your own.
Writing the minute¶
writer::create makes a new file at a path and returns a TapeWriter on it. The program then hands the
writer the minute, one act at a time. Drive::acts makes the acts from the drive's signals, in the order the
host receives them, and four calls of the writer take them. A fifth call closes the file:
// the clocks, the clock map and the five tracks, and the numbers they were given
let (defs, numbers) = drive.definitions()?;
let mut writer = ww_tape_fs::writer::create(path, SyncPolicy::default())?;
for act in drive.acts()? {
match act? {
// the mode in force from `ticks` on, put at each use
Act::Put { ticks, mode } => {
writer.put(&defs, numbers.mode, ticks, mode.item())?;
}
// log lines and temperatures, one records block a second
Act::Records(records) => {
let block = records_block(writer.next_id(), numbers.board_clock, &records)?;
writer.write_block(&defs, &block)?;
}
// a second of CAN frames or of phase current, as the columns of a chunk
Act::Chunk { head, columns } => {
let columns: Vec<(ColumnSpec, &[u8])> = columns
.iter()
.map(|(spec, bytes)| (*spec, &bytes[..]))
.collect();
writer.write_chunk(&defs, &head, &columns)?;
}
// the summaries of phase current, placed where they fit
Act::Summary(block) => writer.defer_block(&defs, block)?,
}
}
let closed = writer.close()?; // the final index, the close record and the tail
What the example uses here: Drive, Drive::acts, Drive::definitions, Act, records_block, DriveNumbers, Mode
/// How much of the drive's recording to make, and the writer's policies for it.
///
/// [Drive::full] is the story's hour; [Drive::scaled] divides the data rates and the byte policies alike and keeps
/// the pieces: each holds the same minutes of the run at every scale.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Drive {
/// Length of the run, minutes from the board's boot.
pub minutes: u32,
/// Samples of `phase_a` per second; it divides 1 000 000, so a sample period is a whole number of µs.
pub phase_hz: u32,
/// CAN frames on `can0` per second.
pub can_hz: u32,
/// Log lines per hour.
pub log_per_hour: u32,
/// Temperature readings per hour.
pub temp_per_hour: u32,
/// Milliseconds of the run each block covers: a records block, a chunk of `can0` and one of `phase_a`. It divides
/// a minute.
pub block_ms: u32,
/// Minutes of the run in a piece: the chain cuts to a new piece once a piece holds the chunks of this many minutes
/// ([ww_tape::CutPolicy::chunks]), so the pieces fall at the same minutes at every scale.
pub piece_minutes: u32,
/// The writer places a checkpoint every this many bytes ([ww_tape::IndexPolicy::bytes]).
pub checkpoint_bytes: Bytes<u64>,
/// The definitions and the mode lie at most this far behind each use ([ww_tape::StatePolicy::near]).
pub near_bytes: Bytes<u32>,
/// The writer copies a state item first written in a piece this far on
/// ([ww_tape::NearPolicy::copy_spacing]).
pub copy_spacing: Bytes<u64>,
/// `phase_a` carries summaries.
pub summaries: bool,
/// The number of the chain of [OWNER] the run records into: another number gives other piece ids and session
/// tags, as another day's run on the same bench does.
pub chain: u64,
/// How the writer places blocks: [ww_tape::Layout::UNALIGNED] for a file, [ww_tape::Layout::on_sd_card] for a
/// raw card.
pub layout: ww_tape::Layout,
}
/// The acts of the run in order: for each block of [Drive::block_ms] the puts of the mode, a records block, a
/// chunk of frames, a chunk of samples and the summary blocks those samples finish; the last summaries at the end.
pub fn acts(&self) -> Result<impl Iterator<Item = Result<Act, Error>> + use<>, Error> {
Acts::new(*self)
}
/// The definitions the run records with: the two clocks, the map between them and the five tracks; and the
/// numbers they give the clocks and tracks.
pub fn definitions(&self) -> Result<(Definitions, DriveNumbers), Error> {
drive_definitions(self)
}
/// The numbers the run's definitions give its clocks and tracks.
pub fn numbers(&self) -> Result<DriveNumbers, Error> {
Ok(drive_definitions(self)?.1)
}
/// One thing the recorder hands the chain.
#[derive(Clone, Debug, PartialEq)]
pub enum Act {
/// A put of the mode in force from `ticks` on.
Put { ticks: i64, mode: Mode },
/// A records block: log lines and temperatures, (track, ticks, item) in time order.
Records(Vec<(TrackNum, i64, Vec<u8>)>),
/// A chunk of `can0` or `phase_a`: its head and columns.
Chunk {
head: Box<ChunkHead>,
columns: Vec<(ColumnSpec, Vec<u8>)>,
},
/// A summary block of `phase_a`.
Summary(Vec<u8>),
}
/// A records block numbered `id` of `records` on the board's clock `board`, (track, ticks, item) in time order.
pub fn records_block(
id: BlockId,
board: ClockNum,
records: &[(TrackNum, i64, Vec<u8>)],
) -> Result<Vec<u8>, Error> {
let len = records
.iter()
.map(|(_, _, item)| item.len() + RECORD_OVERHEAD_MAX)
.sum::<usize>()
+ 256;
let mut buf = vec![0u8; len];
let mut block = BlockWriter::new(&mut buf, BlockKind::Records, id, &[board])?;
for (track, ticks, item) in records {
block.push(*track, ClockTime::new(board, *ticks), &[item])?;
}
let len = block.finish(); // the block's header, records and CRC: its bytes in buf
buf.truncate(len);
Ok(buf)
}
/// The numbers the drive's definitions were given ([Definitions::define_clock], [Definitions::define_track]): what its
/// records, chunks and maps name each clock and track by.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DriveNumbers {
/// The board's microsecond timer since boot: the clock of every track.
pub board_clock: ClockNum,
/// The host's wall clock in ns since the Unix epoch, which the board's clock maps to.
pub host_clock: ClockNum,
/// The firmware's log lines.
pub log: TrackNum,
/// The controller's mode, a state track.
pub mode: TrackNum,
/// CAN frames on the vehicle bus.
pub can0: TrackNum,
/// Phase current, 16-bit fixed point in mA.
pub phase_a: TrackNum,
/// Board temperature.
pub temp: TrackNum,
}
/// The drive's mode, the state track `mode`.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Mode {
Idle,
Run,
Fault,
}
impl Mode {
/// The mode in force at `us` since boot.
pub fn at(us: i64) -> Self {
let ms = us.div_euclid(US_PER_MS);
if ms >= FAULT_MS {
Self::Fault
} else if ms >= RUN_MS {
Self::Run
} else {
Self::Idle
}
}
/// The item a put of the mode carries.
pub fn item(self) -> &'static [u8] {
match self {
Self::Idle => b"idle",
Self::Run => b"run, 31 A limit",
Self::Fault => b"fault: overcurrent",
}
}
/// Microseconds since boot at which the mode after `self` starts, if any.
pub(crate) fn next_change_us(self) -> Option<i64> {
match self {
Self::Idle => Some(RUN_MS * US_PER_MS),
Self::Run => Some(FAULT_MS * US_PER_MS),
Self::Fault => None,
}
}
}
The program drives the writer from one thread, which then waits for every write. A recorder with several sources, or
a thread that must not wait for the disk, hands the acts to a mux instead. A TapeMux owns the writer and its
definitions on a thread of its own, the writing thread.
A handle of the mux takes each kind of act: the mode's puts, the records blocks, the chunks of frames and the samples. The drive's own recorder works so. It defines the clocks and tracks on the mux, then makes the handles:
let mux = TapeMux::create(
tapes.clone(),
OWNER,
drive.chain,
&[],
options,
mux_options(),
)?;
let numbers = define_on_mux(
&mux,
drive.phase_hz,
drive.summaries,
drive.near_bytes.get(),
)?;
let mode = mux.state(numbers.mode)?;
let records = mux.records();
let can0 = mux.chunks(numbers.can0)?;
The recorder gives each act to its handle, in the order the host receives them, and waits until the mux has placed it:
match act {
Act::Put { ticks, mode } => {
self.mode.put(*ticks, mode.item())?;
made.first_tick = *ticks;
made.put = Some(false);
}
Act::Records(records) => {
// the mux numbers the block as the writer's next
let id = BlockId::new(SessionTag::NONE, 0);
let block = records_block(id, self.numbers.board_clock, records)?;
self.records.send(block)?;
}
Act::Chunk { head, columns } if head.track_number == self.numbers.can0 => {
// frames are encoded as the page "Columns" says: the sender takes the chunk as it is
self.can0.send(**head, columns.clone())?;
}
Act::Chunk { head, columns } => {
let values = chunk_values(&self.drive, head, columns)?;
let phase_a = self.phase_handle(head)?;
phase_a.push(&values)?;
phase_a.complete()?; // a chunk a block of the run
}
// the mux builds the summaries of `phase_a` itself
Act::Summary(_) => return Ok(made),
}
The recorder never passes a definition. The summaries of phase_a come from the mux: the handle of samples builds
them as it takes the samples in. The mux cuts to a new piece by the chain's policy. Driven by one thread, it writes the
same bytes every run, and a crash at any byte resumes to the same bytes.
Writing from many threads drives the same handles from a thread per source. The file the program writes needs none of this and uses the writer's own calls.
What the example uses here: Recorder
/// A chain written through a mux, one handle for each kind of act.
pub(crate) struct Recorder<T: PieceStore = MemPieces> {
mux: TapeMux<T>,
drive: Drive,
/// The numbers the mux gave the drive's clocks and tracks.
pub(crate) numbers: DriveNumbers,
mode: StateHandle<T>,
records: RecordsHandle<T>,
can0: ChunkSender<T>,
/// Made at the first chunk of `phase_a` it is given, which says where the track goes on from.
phase_a: Option<GridHandle<T, i16>>,
watch: ProgressWatch,
/// The piece and its bytes after the last act.
seen: (u64, u64),
/// Whether each act waits until it is placed, to say where it lies: only a crash and its resume need that.
placed: bool,
}
let options = GridOptions {
chunk_steps: u32::MAX,
chunk_bytes: exact_units::Bytes::new(u32::MAX),
latency: None, // a chunk is completed after each block of the run, not by time
codec: PHASE_CODEC,
summaries: self.drive.summaries,
first_item: head.first_item,
first_tick: head.first_tick,
};
let mut phase_a = self.mux.grid::<i16>(self.numbers.phase_a, options)?;
if head.first_item.get() > 0 {
// a resumed track goes on on the grid the run started with, from sample 0
let def = crate::defs::phase_def(self.drive.phase_hz, self.drive.summaries)
.ok_or(Error::Settings("phase_hz is not 0"))?;
phase_a.regrid(def.first_grid(0))?;
}
self.phase_a = Some(phase_a);
Each call of the writer does one job:
| Call | What it writes |
|---|---|
TapeWriter::put |
a state item, here the mode, given at each use; the writer writes it only when no record of it lies close behind |
TapeWriter::write_block |
a records block the application made, here a second of log lines and temperatures |
TapeWriter::write_chunk |
a chunk from columns the application encoded, here a second of frames or of samples |
TapeWriter::defer_block |
a summary block, placed where it fits |
TapeWriter::close |
the final index, the close record and the tail, then a sync to the disk |
The application makes a records block itself with a BlockWriter. It pushes each record with its
track and time, and the BlockWriter adds the block header and the checksum:
let mut block = BlockWriter::new(&mut buf, BlockKind::Records, id, &[board])?;
for (track, ticks, item) in records {
block.push(*track, ClockTime::new(board, *ticks), &[item])?;
}
let len = block.finish(); // the block's header, records and CRC: its bytes in buf
What the example uses here: DriveNumbers
/// The numbers the drive's definitions were given ([Definitions::define_clock], [Definitions::define_track]): what its
/// records, chunks and maps name each clock and track by.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DriveNumbers {
/// The board's microsecond timer since boot: the clock of every track.
pub board_clock: ClockNum,
/// The host's wall clock in ns since the Unix epoch, which the board's clock maps to.
pub host_clock: ClockNum,
/// The firmware's log lines.
pub log: TrackNum,
/// The controller's mode, a state track.
pub mode: TrackNum,
/// CAN frames on the vehicle bus.
pub can0: TrackNum,
/// Phase current, 16-bit fixed point in mA.
pub phase_a: TrackNum,
/// Board temperature.
pub temp: TrackNum,
}
A chunk takes more work, since its times and values go into encoded columns. Drive::acts does that work
here. Event times and their codecs and Samples and their codecs explain it.
What the file holds¶
After TapeWriter::close, the file holds one piece: a complete recording that a reader opens alone. Most
of its bytes are chunks, and the end holds the index that lets a reader find any of them.
ww_tape_figures from the file the program writes, at full rate.The file starts with puts, each placed right before the first block that needs it. The layout and the
producer come first, then both clocks, the map, the mode's track and the mode itself. The
definitions of log and temp precede the first records block. Those of can0 and phase_a precede their
first chunks.
The minute ends with the summary blocks still due, then the final index. That index lists every block of the piece by track, so a reader finds the chunks of one track without reading the others. The close record follows with the piece's content hash, padded with zeros so that the tail ends on a 4 KiB boundary.
Reading it back¶
A reader starts at the end of the piece. It finds the tail there, and from it the close record and the
final index. The program reads the whole file into memory and opens it with TapeReader::open:
let reader = TapeReader::open(bytes)?;
let piece = reader.pieces().first().ok_or(FirstTapeError::NoPiece)?;
let (_close, ranges) = piece.close.as_ref().ok_or(FirstTapeError::NotClosed)?;
let defs = reader.definitions_at(0, piece.end)?; // every definition in force at the end
let mut tracks = Vec::new();
for (slot, state) in &defs.items {
let Slot::Track { number } = *slot else {
continue;
}; // a clock or the clock map
let Ok(Describe::Track(def)) = Describe::from_ww_bytes(&state.item) else {
return Err(FirstTapeError::Definition(number));
};
let range = ranges.iter().find(|r| r.track_number == number);
let kind = match (&def.repeat, &def.kind, range.map_or(0, |r| r.chunks)) {
(TrackRepeat::State(_), _, _) => "state",
(_, TrackKind::Series(_), _) => "series chunks",
(_, TrackKind::Events(_), 0) => "records",
(_, TrackKind::Events(_), _) => "events chunks",
(_, TrackKind::Unknown(_), _) => "unknown", // a kind newer than this build
};
let items = match def.repeat {
// the record of the state in force where the piece ends
TrackRepeat::State(_) => Items::InForce(
reader
.state_at(0, Slot::State { track: number }, piece.end)?
.item
.map(|s| s.item),
),
_ => Items::Count(range.map_or(0, |r| if r.chunks == 0 { r.records } else { r.items })),
};
tracks.push(Track {
number,
label: def.label.to_owned(),
kind,
items,
});
}
What the example uses here: Track, Items
/// What a track of a tape is, as [tracks] lists it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Track {
/// The track's number in the file.
pub number: TrackNum,
/// The label of its definition.
pub label: String,
/// How its items are kept: `records`, `state`, `events chunks` or `series chunks`.
pub kind: &'static str,
/// Its items in the piece: records, or the items of its chunks; for a state track, its item in force at the end.
pub items: Items,
}
/// What [Track::items] holds.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Items {
/// The items a track of a stream holds in the piece.
Count(u64),
/// The item of a state track in force at the end of the piece, none when no record reads.
InForce(Option<Vec<u8>>),
}
The close record holds a range for each track: its items, its chunks and its times in the piece. The
definitions come from TapeReader::definitions_at, which looks up every definition in force at a place in the
piece. Each is a shrink_wrap value of the type describe::Describe, which the program decodes. It asks at the end
of the piece, so it sees all of them. The mode lies on a state track, so the program asks
TapeReader::state_at for the mode in force there.
The program never needed the writer's options or the drive's code to read the file. Everything it printed came from the file: the names, the kinds and the counts. Tracks and items explains what a track is and how a tape names it.
TapeWriter.TapeReader.pub fn definitions(&self) -> Result<(Definitions, DriveNumbers), Error> {
drive_definitions(self)
}
The definitions the run records with: the two clocks, the map between them and the five tracks; and the numbers they give the clocks and tracks.
pub struct Definitions
The definitions an application works with, see the module docs.
pub struct DriveNumbers
The numbers the drive's definitions were given (Definitions::define_clock, Definitions::define_track): what its records, chunks and maps name each clock and track by.
pub fn create(
path: &Path,
policy: SyncPolicy,
) -> Result<TapeWriter<FileSink>, WriteError<FsError>> {
let sink = FileSink::create(path).map_err(sink_err("creating a writer"))?;
Ok(TapeWriter::create_on(sink, policy))
}
A new file at path, created exclusively under its final name; fails if path is there (FileSink::create).
pub struct TapeWriter<S: TapeSink>
Appends blocks to a TapeSink, a file by default, see the module docs.
pub fn acts(&self) -> Result<impl Iterator<Item = Result<Act, Error>> + use<>, Error> {
Acts::new(*self)
}
The acts of the run in order: for each block of Drive::block_ms the puts of the mode, a records block, a chunk of frames, a chunk of samples and the summary blocks those samples finish; the last summaries at the end.
pub struct TapeMux<T: PieceStore> {
shared: Arc<Shared<T>>,
thread: Option<JoinHandle<()>>,
}
Writes one chain from a thread of its own, for producers on any thread; see the crate docs.
pub struct BlockWriter<'b> {
buf: &'b mut [u8],
state: BlockState,
}
Writes one block into a buffer: BlockWriter::push records, then BlockWriter::finish.
pub fn close(self) -> Result<Closed, WriteError<S::Error>> {
self.close_as(CloseReason::Closed)
}
Close the piece (CloseReason::Closed) and sync it.
pub fn open(src: S) -> R<Self, S> {
Self::open_with(src, OpenOptions::default())
}
Find the pieces of src with the default OpenOptions.
pub fn definitions_at(&self, i: usize, offset: u64) -> R<DefinitionsAt, S> {
self.definitions_of(i, offset, Slot::is_definition)
}
Every definition in force at offset in piece i (u64::MAX: at its end): each definition slot's newest
record whose block starts before offset, an older one where that block doesn't read.
pub enum Describe<'i>
A definition: one per record on track 0, its item's whole bytes.
pub fn state_at(&self, i: usize, slot: Slot, offset: u64) -> R<Lookup, S> {
let ix = self.state_index(i)?;
let candidates: Vec<&(IndexEntry, StateEntry)> = ix.of_slot(slot, offset).rev().collect();
let mut found = self.first_good(i, &candidates)?;
let from = found.item.as_ref().map_or(0, |s| s.offset);
found.uncovered = uncovered(self.piece(i)?, from..offset);
Ok(found)
}
The record of slot in force at offset in piece i: the newest one whose block starts before offset.
mode; the writer keeps its items near their uses.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 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 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 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.