Writing from many threads¶
A recorder rarely has one source. A protocol analyser reads several links, and a test bench samples a current while a board sends log lines. Each source has a thread or a task of its own, and none of them should wait for the disk. How do they write one tape together? They hand their data to a mux, which owns the writer on a thread of its own.
A writing thread and its handles¶
A TapeMux owns a PieceChain and its definitions on the writing thread, a thread that does nothing but
write. Producers never touch the writer. Each holds a handle, which takes its data, makes finished units of it and
sends them into one queue. The writing thread takes the units from the queue in the order they came and places them.
Each kind of data has its handle:
| Handle | Takes | Sends |
|---|---|---|
StateHandle |
a state item, on change | a put |
RecordsHandle |
a records block built with a BlockWriter |
the block |
EventsHandle |
items of one events track, one by one or in batches | an events chunk it encodes |
GridHandle |
time steps of one series track: its samples, or the cells of its tiles | a series chunk per tile, which it encodes |
ChunkSender |
a chunk the caller encoded | the chunk |
RelayHandle |
another producer's blocks | each block, as a relay passes it |
The writing thread does every chore the writer needs. It puts definitions and state where blocks need them,
cuts by the chain's policy and syncs by the sync policy. It places checkpoints and closes the chain.
Handles never pass definitions: the mux holds them, and TapeMux::define_track gives a track its number.
A shared lock around the writer would serialize the producers instead. A slow sync to the disk would then block every producer that waits for the lock. With a writing thread, a sync blocks only that thread. A producer waits only when the queue is full, and the thread wakes by itself when a sync or a checkpoint falls due.
A small mux¶
A mux this small still shows the shape. Two sensors push pings on their own events track, each in one call to
EventsHandle::push_all. A third pushes levels on a series track with GridHandle::push. Each thread holds
its own handle into one chain in memory, joins, and the mux closes:
/// Two sensors push pings on their own events track, and a third pushes levels on a series track.
///
/// Each thread holds its own handle into one chain in memory; [read_back] after the close shows every item arrived.
///
/// # Errors
///
/// A mux or handle call that failed.
pub fn threads() -> Result<Counts, Error> {
let tapes = MemPieces::new();
let mux = TapeMux::create(
tapes.clone(),
OWNER,
0,
&[],
ChainOptions::default(),
MuxOptions::default(),
)?;
let clock = mux.define_clock(clock())?;
let pings_a = mux.define_track(pings_track(clock, "pings_a"))?;
let pings_b = mux.define_track(pings_track(clock, "pings_b"))?;
let levels = mux.define_track(levels_track(clock))?;
thread::scope(|s| -> Result<(), Error> {
let a = s.spawn(|| -> Result<(), Error> {
let mut h = mux.events(pings_a, EventsOptions::default())?;
let events: Vec<Event<'_>> = (0..PINGS)
.map(|i| Event {
start: i64::from(i),
end: i64::from(i),
..Event::default()
})
.collect();
h.push_all(&events)?;
h.finish()?;
Ok(())
});
let b = s.spawn(|| -> Result<(), Error> {
let mut h = mux.events(pings_b, EventsOptions::default())?;
let events: Vec<Event<'_>> = (0..PINGS)
.map(|i| Event {
start: i64::from(i),
end: i64::from(i),
..Event::default()
})
.collect();
h.push_all(&events)?;
h.finish()?;
Ok(())
});
let c = s.spawn(|| -> Result<(), Error> {
let mut h = mux.grid::<i16>(levels, GridOptions::default())?;
h.push(&vec![0i16; LEVELS])?;
h.finish()?;
Ok(())
});
joined(a)?;
joined(b)?;
joined(c)
})?;
let pieces = pieces_of(&tapes, &mux.close()?)?;
read_back(&pieces, pings_a, pings_b, levels)
}
Reading the chain back after the close shows every item of every thread arrived.
Every blocking call has an async twin, named with _async. The same three sources, as tasks on tokio instead of
threads, push and close the same way:
/// [producers::threads], the same calls as `_async`, on tokio tasks: two push pings, a third pushes levels, each
/// its own task. `smol::spawn` schedules the same futures the same way.
async fn tasks() -> Result<Counts, Error> {
let tapes = MemPieces::new();
let mux = TapeMux::create(
tapes.clone(),
OWNER,
0,
&[],
ChainOptions::default(),
MuxOptions::default(),
)?;
let clock = mux.define_clock_async(producers::clock()).await?;
let pings_a = mux
.define_track_async(producers::pings_track(clock, "pings_a"))
.await?;
let pings_b = mux
.define_track_async(producers::pings_track(clock, "pings_b"))
.await?;
let levels = mux
.define_track_async(producers::levels_track(clock))
.await?;
let mut a = mux.events_async(pings_a, EventsOptions::default()).await?;
let mut b = mux.events_async(pings_b, EventsOptions::default()).await?;
let mut c = mux
.grid_async::<i16>(levels, GridOptions::default())
.await?;
let t_a = tokio::spawn(async move {
let events: Vec<Event<'_>> = (0..PINGS)
.map(|i| Event {
start: i64::from(i),
end: i64::from(i),
..Event::default()
})
.collect();
a.push_all_async(&events).await?;
a.finish_async().await
});
let t_b = tokio::spawn(async move {
let events: Vec<Event<'_>> = (0..PINGS)
.map(|i| Event {
start: i64::from(i),
end: i64::from(i),
..Event::default()
})
.collect();
b.push_all_async(&events).await?;
b.finish_async().await
});
let t_c = tokio::spawn(async move {
c.push_async(&vec![0i16; LEVELS]).await?;
c.finish_async().await
});
t_a.await
.map_err(|_join| Error::Settings("a task panicked"))??;
t_b.await
.map_err(|_join| Error::Settings("a task panicked"))??;
t_c.await
.map_err(|_join| Error::Settings("a task panicked"))??;
let pieces = producers::pieces_of(&tapes, &mux.close_async().await?)?;
producers::read_back(&pieces, pings_a, pings_b, levels)
}
smol::spawn schedules the same futures the same way; neither runtime is a dependency of ww_tape_mux.
The drive with one thread per source¶
The drive's hour (What a tape holds) shows the pattern with four threads. The program first starts a mux on a chain in memory and defines the clocks and tracks on it:
let mux_tapes = MemPieces::new();
let mux = TapeMux::create(
mux_tapes.clone(),
OWNER,
drive.chain,
&[],
options(drive),
MuxOptions::default(),
)?;
let numbers = define_on_mux(
&mux,
drive.phase_hz,
drive.summaries,
drive.near_bytes.get(),
)?;
let end_us = i64::from(drive.minutes) * 60_000 * US_PER_MS;
What the example uses here: define_on_mux
let host_clock = mux.define_clock(host)?;
let board_clock = mux.define_clock_with_maps(board, &[(host_clock, &segments)])?;
let on_board = |path, name, repeat, kind| track(board_clock, path, name, repeat, kind);
Ok(DriveNumbers {
board_clock,
host_clock,
log: mux.define_track(on_board(log, "log", TrackRepeat::Stream, events.clone()))?,
mode: mux.define_track(on_board(mode_path, "mode", mode, events.clone()))?,
can0: mux.define_track(on_board(can0, "can0", TrackRepeat::Stream, events.clone()))?,
phase_a: mux.define_track(on_board(
phase_a,
"phase_a",
TrackRepeat::Stream,
TrackKind::Series(phase),
))?,
temp: mux.define_track(on_board(temp, "temp", TrackRepeat::Stream, events))?,
})
One thread puts the mode each time it changes. The state track needs no put at each use. The writer carries the newest item into each new piece and writes copies by its own rule.
let mode_t = s.spawn(|| -> Result<u64, Error> {
let state = mux.state(numbers.mode)?;
let mut mode = Mode::at(0);
state.put(0, mode.item())?;
let mut n = 1u64;
while let Some(next) = mode.next_change_us().filter(|&c| c < end_us) {
mode = Mode::at(next);
state.put(next, mode.item())?;
n += 1;
}
Ok(n)
});
Another thread pushes the CAN frames of can0 in batches of 4096 into an EventsHandle. A third pushes a second of
phase current at a time into a GridHandle. Each handle ends with finish, which completes its open chunk and
sends it:
let can0_t = s.spawn(|| -> Result<u64, Error> {
let mut can0 = mux.events(numbers.can0, EventsOptions::default())?;
let period_us = 1_000_000 / u64::from(drive.can_hz);
let total = first_at(end_us, u64::from(drive.can_hz) * 3_600);
let mut k = 0u64;
while k < total {
let take = CAN0_BATCH.min(total - k);
let payloads: Vec<(i64, Vec<u8>)> =
(k..k + take).map(|i| frame(i, period_us)).collect();
let events: Vec<Event<'_>> = payloads
.iter()
.map(|(start, payload)| Event {
start: *start,
end: *start,
payload,
..Event::default()
})
.collect();
can0.push_all(&events)?;
k += take;
}
can0.finish()?;
Ok(total)
});
let phase_t = s.spawn(|| -> Result<u64, Error> {
let mut phase_a = mux.grid::<i16>(
numbers.phase_a,
GridOptions {
codec: PHASE_CODEC,
summaries: drive.summaries,
..GridOptions::default()
},
)?;
let total = first_at(end_us, u64::from(drive.phase_hz) * 3_600);
let step = u64::from(drive.phase_hz).max(1);
let mut n = 0u64;
while n < total {
let take = step.min(total - n);
phase_a.push(&phase_values(drive, n, take))?;
n += take;
}
phase_a.finish()?;
Ok(total)
});
A fourth thread sends the log lines and temperatures as records blocks through a RecordsHandle. When every thread
is done, the program closes the mux, which places what was sent and closes the chain:
Which unit reaches the queue first depends on the threads, so the bytes of the chain differ from run to run. What each track holds does not. A test decodes every track and compares it with the drive's recording through one thread. That recording drives the same handles from one thread in a fixed order, so it writes the same bytes every run.
Typed handles encode on their own thread¶
An EventsHandle or a GridHandle keeps an open chunk. A push adds items to it, and the handle completes the
chunk when it is full: 4096 items or 1 MiB of payload by default. Completing encodes the chunk's columns and hashes
its payload with BLAKE3, the costliest pass of a write. It also computes the leaves of the track's summary, such
as a series' statistics per group of samples.
A series track with fixed axes keeps a chunk per tile. Its GridHandle takes a time step of the whole grid,
or of a box of tiles (TapeMux::grid_box), and splits it into the open chunk of each tile. The tiles' chunks hold
the same time steps and are completed together. Several producers may each write a box of their own, and a tile that
no box holds is never written. A tile's time step must fit a chunk and a block: a handle refuses a larger one with
CallError::StepTooLarge and never splits it.
All of this runs on the producer's thread, so the work spreads over the producers. The writing thread places the chunk with its hash given, and builds the summary levels above the leaves. It keeps one summary tree per track and piece and ends it before each cut.
A producer may go quiet with a chunk half full. The writing thread then completes the chunk itself once its first item
has waited the handle's latency, 1 second by default (EventsOptions::latency). A quiet source's items thus reach the
tape within that time, behind every unit the handle sent before.
Pushing items one at a time costs a call per item. EventsHandle::push_all takes a batch, which the handle encodes
in one pass. The bytes are the same either way.
The other handles take units that are already whole. A ChunkSender takes a chunk that its caller encoded, as the
page Event times and their codecs shows. A RecordsHandle takes a records block, and the writing
thread numbers it as the writer's next block. A RelayHandle takes another producer's blocks, as Live feeds and
relays explains.
The queue and back-pressure¶
The queue between the handles and the writing thread is bounded by bytes, not by units. A put is small and a chunk
of samples may be large, so a count of units would bound nothing. A unit takes its bytes from the
budget when it is sent and gives them back when it is placed. The budget is MuxOptions::queue_bytes, 64 MiB by
default.
When the budget is spent, a handle meets back-pressure: it cannot send until the writing thread catches up. Each
handle chooses what to do then with its Pressure:
| Pressure | A full queue | Suits |
|---|---|---|
Wait, the default |
blocks the call until there is room; nothing is lost | a recorder that keeps every item |
Fail |
returns MuxError::Full with the unit |
a producer that decides itself, such as one that buffers elsewhere |
Drop |
drops the unit and counts it | a live monitor that must never block |
Handles that wait are served in the order they started to wait, so a fast producer cannot starve the others. A unit larger than the whole budget goes alone once the queue is empty.
A dropped chunk leaves a gap in its track's item numbers. The next chunk starts past the dropped items, so a
reader sees that items were lost and how many. MuxStats counts the drops of each track. The test below lets one
handle drop and another fail while the sink stalls:
let drop = mux
.chunks(TrackNum::new(1))
.unwrap()
.pressure(Pressure::Drop);
let fail = mux
.chunks(TrackNum::new(2))
.unwrap()
.pressure(Pressure::Fail);
let mut dropped = 0;
for k in 0..40 {
if send_chunk(&drop, 0, k).unwrap() == Sent::Dropped {
dropped += 1;
}
}
assert!(dropped > 20, "{dropped} dropped");
match send_chunk(&fail, 1, 0) {
Err(MuxError::Full(Unit::Chunk { head, .. })) => assert_eq!(head.first_item.get(), 0),
other => panic!("{other:?}"),
}
The order units land in¶
One handle's units land in the order it sent them: its chunks, its puts and its blocks. Units of different handles land in the order they reached the queue, which need not be the order of their times. A chunk of samples may land after a records block whose times are later.
The format does not need time order across tracks. Each track is indexed on its own, a state is looked up by its tick, and a reader merges tracks by time. One order is fixed: a definition lands before any data that names it, since a handle is made only once the mux holds its track.
Cuts and closes under live handles¶
The writing thread cuts between units, never inside one. A chunk therefore lies whole in one piece, and a handle never
notices a cut. The chain cuts by its CutPolicy before it places a chunk, and TapeMux::cut cuts once every unit
sent before is placed. Item numbers go on across the cut, as Pieces and chains shows.
TapeMux::close refuses everything sent after it: every handle's next call returns MuxError::Closed. The units
sent before are placed, the summary trees are ended, and the chain is closed. The close does not wait for the handles
to be dropped, so one forgotten handle cannot hold it up.
A mux dropped without a close places what was sent, syncs, and leaves the last piece unclosed, as a crash would.
TapeMux::resume goes on with the chain and rebuilds the summary tree of the piece from the chunks it kept. When the
power fails explains the resume.
Errors reach every handle¶
A producer learns of an error where it can act on it. Three kinds of error surface in three places:
| Kind | Example | Where it surfaces |
|---|---|---|
| refused at the call | an item too long, a chunk of another track | the call returns MuxError::Call, and nothing was sent |
| refused by the writer | a block on a track the definitions don't hold | the handle's next call, flush or sync returns MuxError::Refused |
| the mux failed | a write or a sync that failed | every call of every handle, and the close, return MuxError::Failed |
A failed write stops the chain, since the writer never retries. The test below lets the sink fail after one block:
rigged.rig.fail.store(true, Ordering::SeqCst);
// taken by the queue; the writing thread's write of it fails
assert_eq!(send_chunk(&chunks, 0, 1).unwrap(), Sent::Queued);
assert!(matches!(mux.flush(), Err(MuxError::Failed(_))));
let failed = |r: Result<Sent, MuxError<MemError<u64>>>| matches!(r, Err(MuxError::Failed(_)));
assert!(failed(send_chunk(&chunks, 0, 2)));
assert!(failed(log.send(records(crate::id(2), 2))));
assert!(failed(state.put(3, b"x")));
assert!(failed(relay.send(records(crate::id(3), 3))));
assert!(matches!(chunks.flush(), Err(MuxError::Failed(_))));
assert!(matches!(state.sync(), Err(MuxError::Failed(_))));
assert!(matches!(mux.cut(), Err(MuxError::Failed(_))));
assert!(mux.stats().failed);
assert!(matches!(mux.close(), Err(MuxError::Failed(_))));
A send returns once the queue holds the unit, not once the unit is placed. A producer that needs to know more asks
its handle. Its flush returns once every unit of the handle is placed, and its sync once they are durable on the
store.
Threads and tasks¶
Every call that may wait has an async twin, named with _async: EventsHandle::push_async,
ChunkSender::send_async, TapeMux::close_async and the rest. A task awaits room in the queue as a thread blocks
for it, and both wait in one line. The writing thread wakes them, so the crate needs no async runtime and depends on
none. The writing thread itself stays an operating system thread, since its writes and syncs block.
The futures are cancel-safe. A send dropped while it waits leaves the line and sends nothing. A typed handle's push dropped while it waits keeps the chunk it completed. The handle sends that chunk first on its next call, so no item is lost. The test below ends an events handle and the mux from a task:
for i in i..ITEMS {
h.push_async(i as i64 * 10, i as i64 * 10, 0, &i.to_le_bytes())
.await
.unwrap();
}
h.finish_async().await.unwrap();
mux.close_async().await.unwrap();
A typed handle's drop sends its open chunk and blocks while it does. Async code therefore ends a handle with
finish_async.
Readers while the mux writes¶
A reader in the writer's own process waits on a ProgressWatch from TapeMux::watch. The writing thread wakes it
each time it places more. The watch tells the piece, its bytes written and synced, and the newest chunk of each track.
A reader in another process follows the chain's files with a follower. A ChainFollower hands out each block
once it checks, and a TrackFollower gives one track's items as their chunks land. Reading a growing
piece explains both.
Several chains, one writer each¶
One mux writes one chain, and a process may run several. The radio capture of Series writes its
samples and its decoded bursts into two chains, each from a mux of its own. Neither writing thread waits for the
other's writes, and a TimeMerge gives a reader the items of both in time order.
Each chain has one writer. A file sink locks the file it writes, so a second writer of the same chain is refused. The lock holds against another process and against the same one.
Data from other processes therefore travels to the writing process over a channel of the program's own, such as a
socket or shared memory. A completed chunk or a block is plain bytes. The writing process hands each unit to a
RelayHandle or a ChunkSender.
How fast the mux writes¶
The bench handles writes the same data through a mux and through one thread writing a chain directly. It splits the
data across 1, 4 and 16 tracks, each track a producer thread on the mux. The events are instants with a 16-byte
payload and their summaries:
| Writer | Tracks | ms | M events/s | MB/s written | vs direct | Waits |
|---|---|---|---|---|---|---|
| direct | 1 | 128 | 62.3 | 262 | 1.00 | 0 |
| mux | 1 | 145 | 55.0 | 231 | 0.88 | 0 |
| mux, one by one | 1 | 553 | 14.5 | 61 | 0.23 | 0 |
| direct | 4 | 118 | 67.7 | 285 | 1.00 | 0 |
| mux | 4 | 47 | 170.4 | 717 | 2.52 | 0 |
| mux, one by one | 4 | 137 | 58.5 | 246 | 0.86 | 0 |
| direct | 16 | 115 | 69.7 | 294 | 1.00 | 0 |
| mux | 16 | 25 | 323.9 | 1365 | 4.65 | 0 |
| mux, one by one | 16 | 59 | 135.9 | 573 | 1.95 | 0 |
just bench-handles on gpd-omarchy, load average 9.21 before, 8.71 after.
With one track, the mux reaches 88 % of the direct writer's rate: the queue and the second thread cost a little. A producer that pushes events one by one reaches only 23 %, which is why a batch is worth making. With 16 tracks, the producers encode in parallel, and the mux writes 4.6 times as many events a second as the direct writer.
The second table writes a radio capture, 20 million IQ samples a second, packed to 12 bits with summaries:
| Writer | Tracks | ms | MS/s | MB/s written | vs direct | Waits |
|---|---|---|---|---|---|---|
| direct | 1 | 1248 | 256.4 | 783 | 1.00 | 0 |
| mux | 1 | 1169 | 273.7 | 836 | 1.07 | 0 |
| direct | 4 | 1190 | 269.0 | 822 | 1.00 | 0 |
| mux | 4 | 401 | 797.6 | 2437 | 2.97 | 0 |
| direct | 16 | 1231 | 260.0 | 795 | 1.00 | 0 |
| mux | 16 | 303 | 1055.3 | 3224 | 4.06 | 1400 |
just bench-handles on gpd-omarchy, load average 8.71 before, 8.25 after.
With 16 tracks, the mux writes 4.1 times as many samples as the direct writer, 3.2 GB/s. There the writing thread becomes the limit: 1 400 sends waited for room in the queue. A source faster than one writing thread gets a chain of its own, and the chains are merged when they are read.
The bench ran on gpd-omarchy, a machine with 24 logical CPUs (AMD Ryzen AI 9 HX 370 w/ Radeon 890M, x86_64). It was a release build at opt-level 3 of commit d7abba98a, built with 24 jobs. The load average ran from 8.25 to 9.21 across the tables.
just bench-handles --help lists the bench's settings, and Sizes and speeds says how to run the benches
on your own machine.
TapeWriter.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 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 define_track(&self, t: TrackSpec<'_>) -> Result<TrackNum, MuxError<T::Error>> {
block_on(self.define_track_async(t))
}
Define track t (Definitions::define_track) and give its number, once the writing thread holds it.
pub fn push_all(&mut self, items: &[Event<'_>]) -> Result<Option<Sent>, MuxError<T::Error>> {
let (open, refused) = self.add(items)?;
let sent = self.backlog.send(&self.s)?;
self.opened(open);
refused.map_or(Ok(sent), |r| Err(r.into()))
}
Add items in order, in one pass under one hold of the open chunk: the bytes are those of pushing them one by
one. Each chunk they fill is sent: what became of the last. A refused item refuses the rest: the items before
it are added and their chunks sent, and the refusal names its number.
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.
mode; the writer keeps its items near their uses.pub struct EventsHandle<T: PieceStore> {
s: Sender<T>,
open: Arc<Open<T, EventsChunk>>,
backlog: Backlog<T>,
track: TrackNum,
}
Writes the items of one events track from one producer: instants, spans, flags, relation values and payloads.
pub struct GridHandle<T: PieceStore, S: Scalar + Sample + Send + 'static> {
s: Sender<T>,
open: Arc<Open<T, GridChunks<S>>>,
backlog: Backlog<T>,
track: TrackNum,
}
Writes the time steps of one grid track from one producer: the whole grid, or one box of its tiles.
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 fn grid_box<S: Scalar + Sample + Send + 'static>(
&self,
track: TrackNum,
cells: &[Range<u32>],
options: GridOptions,
) -> Result<GridHandle<T, S>, MuxError<T::Error>> {
crate::wait::block_on(self.grid_box_async::<S>(track, cells, options))
}
A handle that writes the time steps of the box of cells cells of grid track track: one range of cells per
fixed axis, each starting and ending at a tile's edge (CallError::TileBox).
StepTooLarge { bytes: Bytes<u64>, max: Bytes<u64> },
One time step of a tile takes bytes bytes, more than a chunk holds: max, the smaller of the handle's
chunk bytes and what fits a block.
pub latency: Option<Duration>,
How long the first item of an open chunk waits at most before the writing thread completes the chunk; None: until the chunk is full or completed by the producer.
pub struct ChunkSender<T: PieceStore> {
s: Sender<T>,
track: TrackNum,
kind: BlockKind,
}
Sends chunks of one events or series track, encoded by the caller.
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 queue_bytes: Bytes<u64>,
The bytes of units sent and not yet placed, at most; a unit larger than this goes alone.
pub enum Pressure {
/// Block until the queue has room, behind the handles that waited first. Nothing is lost.
#[default]
Wait,
/// Return [MuxError::Full] with the unit, for a producer that decides itself.
Fail,
/// Drop the unit and count it ([crate::MuxStats::drops]). A chunk sender's next chunk then starts past the
/// dropped items, and a reader sees the gap in the item numbers as items lost.
Drop,
}
What a handle does when the queue has no room for a unit.
pub struct MuxStats
What a TapeMux did so far; read from any thread (TapeMux::stats).
TapeReader.pub struct CutPolicy {
/// Once a piece holds this many bytes.
pub bytes: Bytes<u64>,
/// Once a piece holds this many chunk blocks.
pub chunks: Count<Chunk, u64>,
/// Once a piece is this old (since it was started or resumed).
pub interval: Option<Duration>,
}
When a PieceChain cuts to a new piece; checked before each chunk. Zero or None turns a limit off.
pub fn cut(&self) -> Result<(), MuxError<T::Error>> {
block_on(self.cut_async())
}
Cut to a new piece once every unit sent before is placed (PieceChain::cut_now).
pub fn close(self) -> Result<Vec<ChainPiece<T::Key>>, MuxError<T::Error>> {
block_on(self.close_as_async(CloseReason::Closed))
}
Close the chain (CloseReason::Closed) once every unit sent before is placed; every piece.
Closed,
The mux is closed or dropped: it takes nothing more.
pub fn resume(
store: T,
owner: OwnerId,
chain: u64,
options: ChainOptions,
mux: MuxOptions,
) -> Result<(Self, Resumed), MuxError<T::Error>> {
let (chain, resumed) =
PieceChain::resume_on(store, owner, chain, options).map_err(MuxError::Start)?;
Ok((Self::start_resumed(chain, &resumed, mux)?, resumed))
}
Reopen chain chain of owner in store (PieceChain::resume_on) and write on from a new writing thread.
PieceStore; the book never uses store as a verb.pub async fn push_async(
&mut self,
start: i64,
end: i64,
flags: u32,
payload: &[u8],
) -> Result<Option<Sent>, MuxError<T::Error>> {
self.push_related_async(start, end, flags, payload, &[])
.await
}
Self::push as a future, waiting for room by waker.
Dropped while it waits, the item stays added and the chunk it completed stays with the handle: its next push, complete, finish or drop sends that chunk first.
pub async fn send_async(
&self,
head: ChunkHead,
columns: Vec<(ColumnSpec, Vec<u8>)>,
) -> Result<Sent, MuxError<T::Error>> {
let (work, bytes) = self.unit(head, columns)?;
self.s.send_async(work, bytes).await
}
Self::send as a future, waiting for room by waker. Dropped while it waits, the chunk is not sent.
pub async fn close_async(self) -> Result<Vec<ChainPiece<T::Key>>, MuxError<T::Error>> {
self.close_as_async(CloseReason::Closed).await
}
Self::close as a future.
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 watch(&self) -> ProgressWatch {
ProgressWatch::new(self.shared.watch.clone())
}
A watch of what the writing thread placed, for readers in this process (ProgressWatch).
pub struct ChainFollower
Follows a chain in a directory (or one file) while a writer in any process writes it; see the module docs.
pub struct TrackFollower {
chain: ChainFollower,
items: TrackItems,
pending: VecDeque<TrackItem>,
}
A ChainFollower that gives one track's items (ChainFollower::track).
pub struct TimeMerge<T> {
sources: Vec<Source<T>>,
quiet_max: Option<Duration>,
/// The time of the last item given.
given: Option<i128>,
}
Merges sources of timed items into one stream in time order, as far as the slowest source allows.
pub struct StateHandle<T: PieceStore> {
s: Sender<T>,
track: TrackNum,
}
Puts the items of one state track, on change: the writer puts them again where readers need them.
Any number of these handles may put on the same track.
pub struct BlockWriter<'b> {
buf: &'b mut [u8],
state: BlockState,
}
Writes one block into a buffer: BlockWriter::push records, then BlockWriter::finish.
Full(Unit),
No room in the queue, and the handle's pressure is Fail: the unit back.
Call(CallError),
The handle refused the call; nothing was sent.
Refused(WriteError<E>),
The writer refused something it was sent: a unit of this handle (returned by the handle's next call), or a control call's work (a cut refused). Nothing of it was written; the mux writes on.
Failed(Arc<WriteError<E>>),
A write or sync failed, or a cut could not start the next piece: the chain takes no more blocks. Every handle's next call, flush and the close return this. Shared, as every handle gets it.