Live feeds and relays¶
A tape need not be finished to be read. Its blocks can go to a viewer while they are written, over a link to a host, or onto a raw card. How does a reader follow a growing tape? How does a program record another producer's tape into a file of its own? The examples relay a tape that the drive's board writes itself into the host's chain.
Reading while the writer writes¶
A live feed is a tape passed on block by block while it is written. Every block checks itself and the writer never changes a byte it placed, so a reader may take each block as it comes. A reader that joins late finds the definitions and state it needs near behind, as Definitions and state shows.
In one process, a MemSink holds the tape, and a TapeReader reads it while the writer appends. A recorder
that writes through a mux gives its readers a ProgressWatch, which wakes them each time the writing thread
places more. Writing from many threads shows it. A MemSink of a
chain reserves the room of a whole piece when the piece starts: the chain's cut size plus 1 MiB. A reader's read
therefore never waits while the bytes move into a bigger buffer.
A piece that was closed and opened again grows after its close. Reading a growing piece explains what a reader sees then, and how it notices the growth.
Relays¶
A relay is a program that takes a live producer's blocks and writes them into a tape of its own. A host that receives a device's tape over a link and records it to disk is one. A capture tool that keeps a file of a live feed is another.
The producer's stream carries its own puts, placed by its own near rule in its own stream. They do not fit the
relay's file, which may start later, be cut elsewhere, or have lost blocks. TapeWriter::relay_block therefore
takes the definitions of a block of puts into the relay's own Definitions. It puts the block's state records by the
relay's own rule (TapeWriter::put_block). Every other block passes as data, byte for byte.
The relay needs no knowledge of the producer's tracks. Its file has every definition near its use, like any other file.
The drive's host relays the board's tape into a chain cut every 15 minutes. It writes through a mux, whose
RelayHandle sends each block to the writing thread. That thread calls TapeWriter::relay_block and cuts by
the chain's policy:
let tapes = MemPieces::new();
let mux = TapeMux::create(
tapes.clone(),
OWNER,
CHAIN,
&[],
options(&drive),
MuxOptions::default(),
)?;
let relay = mux.relay(RelayMode::Relay); // the board's own defs, filled from its puts
let mut walk = FileBlocks::with_recovery(&board[..], Recovery::Prefix);
while let Some(b) = walk.next_block() {
let b = b?;
if ww_tape::index::is_structural(b.kind) {
continue; // the board's index, close and tail: the relay writes its own
}
relay.send(b.bytes().to_vec())?; // a new piece every 15 minutes, as the host's own recording: the mux cuts
}
let closed = mux.close()?;
What the example uses here: board_tape, options
/// The board's own tape of the hour: one piece in memory, closed, its definitions near 1 MiB.
fn board_tape(drive: &Drive, acts: &[Act]) -> Result<Vec<u8>, Error> {
let board = Drive {
near_bytes: exact_units::Bytes::new(1 << 20),
..*drive
};
one_tape(&board, acts, "drive firmware", |_| true)
}
/// The chain's options for `drive`.
pub(crate) fn options(drive: &Drive) -> ChainOptions {
let definitions = StatePolicy {
near: drive.near_bytes,
copies: exact_units::Count::new(1),
};
ChainOptions {
writer: WriterOptions {
sync: SyncPolicy::default(),
index: IndexPolicy {
bytes: drive.checkpoint_bytes,
interval: None,
..IndexPolicy::default()
},
layout: drive.layout.with_definitions(definitions),
producer: PRODUCER.to_owned(),
near: NearPolicy {
copy_spacing: drive.copy_spacing,
..NearPolicy::default()
},
// no clock: no sync, checkpoint or cut is due by time, so the bytes follow from the acts alone
clock: ClockRef::NONE,
// every CRC and hash: the drive's log is kept and handed on
integrity: ww_tape::Integrity::Full,
},
cut: CutPolicy {
bytes: exact_units::Bytes::new(0),
chunks: exact_units::Count::new(drive.piece_chunks()),
interval: None,
},
tapes: PieceTapes::Each,
}
}
The board writes its hour as one tape of 116 MB, with about 13700 data blocks. It keeps near at 1 MiB, since a viewer may join its feed at any time, and so writes 702 blocks of puts, 85 kB. The relayed chain has 4 pieces, 116 MB, with 121 blocks of puts, 11 kB. Its data blocks are the board's, byte for byte.
Adopting blocks on raw media¶
On a raw medium, a piece must be one session, as Where the data ends on a raw
card explains. A block from another session reads there as stale data. A
writer for raw media therefore passes a producer's blocks with TapeWriter::adopt_block. Through a mux, a
RelayHandle made with RelayMode::Adopt does the same.
The call renumbers each block into the writer's own session and returns where it landed, or None for a block of puts.
A jump in the producer's sequence numbers stays a jump in the writer's. A reader therefore still sees that blocks
were lost on the way. A block passed with TapeWriter::write_block keeps its session, which suits a file but not a
card.
Without the standard library¶
The writer, the chain and the resume need only an allocator. Firmware or a browser therefore writes tapes on a sink of its own. Without the standard library, a new writer starts without a session and without a clock.
A new writer has no session, because it has no random source, and it refuses to write until it gets one.
TapeWriter::set_session gives it one, such as SessionTag::from_seed over a device id and a boot counter. A
piece head gives it one too: TapeWriter::begin_piece, and every piece of a chain.
A new writer also has no clock, so no sync, checkpoint or cut falls due by time. WriterOptions::clock gives it
one (Files and syncing).
TapeReader.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 ProgressWatch {
watch: Arc<Watch>,
}
Wakes a reader in the writer's process when the writing thread placed more (crate::TapeMux::watch).
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).
pub struct Definitions
The definitions an application works with, see the module docs.
pub fn put_block(
&mut self,
defs: &Definitions,
block: &[u8],
) -> Result<(), WriteError<S::Error>>
Put the records of a producer's block of puts or copies (FLAG_REPEAT) on this tape, as
a relay of a live producer passes them on, each with what it needs as Self::put does, all decided at once
and written in as few blocks as they fit: a definition of a kind defs holds must be the one held (a relay
holds the block's definitions first, Self::relay_block) and is put after what it names; a typed item or a
kind this crate doesn't know is put as it is, a typed item after its bundle; a producer's producer and layout
are passed over (this tape's are the writer's own); every other record is put on its state track after the
track's definitions.
pub struct RelayHandle<T: PieceStore> {
s: Sender<T>,
mode: RelayMode,
}
Passes on another producer's blocks: a link tap's, or those that came over a socket from another process.
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.
Adopt,
As PieceChain::adopt_block: renumbered into the writer's session, a jump in the producer's seq kept as a jump.
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.
TapeSink.pub fn set_session(&mut self, session: SessionTag) -> Result<(), WriteError<S::Error>> {
if !session.is_session() {
return Err(WriteError::Input(InputError::Session(session)));
}
self.session = session;
self.next_seq = 0;
Ok(())
}
Make the blocks from here on part of session session (a deterministic producer's own tag), its seqs from 0. A tag
a writer may not use (SessionTag::is_session) is refused.
pub fn from_seed(seed: &[u8]) -> Self {
let mut h = blake3::Hasher::new_derive_key("ww_tape run tag");
h.update(seed);
let mut out = [0u8; 4];
h.finalize_xof().fill(&mut out);
Self::writable(u32::from_le_bytes(out))
}
A tag from seed (a device's unique id, a free-running timer at boot, an ADC noise read; or anything that
names the session, for a deterministic writer): the first 4 bytes of BLAKE3 in key derivation mode
("ww_tape run tag") over it, made writable. The same seed gives the same tag.
pub fn begin_piece(
&mut self,
head: &PieceHead,
tracks: &[TrackStart],
) -> Result<(), WriteError<S::Error>> {
if head.prev.is_none() {
self.session = SessionTag::of_piece(&head.ident.id);
}
self.write_piece_head(head, tracks)
}
Start the file as a piece of a chain: the piece head block, first in the file. The session of a chain's first piece is SessionTag::of_piece its id, so the same input gives the same bytes.
pub clock: ClockRef,
[TapeWriter::set_clock]: when intervals are up (the system clock with std).