Pieces and chains¶
A recording that runs for days does not fit one file well. A crash costs only the bytes it touched, in a file of any size. A file of hundreds of gigabytes, though, is slow to copy, and its old data cannot go without rewriting the rest. How does a writer cut a long recording into pieces, how do the pieces find each other, and how do old ones go? The examples cut the drive's hour every 15 minutes into four pieces.
Why pieces¶
A piece is a complete tape: it has its own definitions, index, content hash and tail, and it reads without any other piece. A chain is the pieces of one recording in order, each piece head naming the piece before it. Cutting a recording into a chain gives three things:
- Files of a handy size. A piece of 256 MiB copies, uploads or moves to an archive on its own. A tool that needs one stretch of the recording takes only the pieces that hold it.
- Simple retention. Deleting the oldest piece frees space without rewriting anything.
- Closed history. The pieces before the one being written are closed and hashed. A later crash or a bug in the writer cannot touch them.
A crash inside a piece costs only the bytes it touched there, as When the power fails shows. A chain is therefore not what bounds the loss. A reader also opens a piece of any size with a few small reads at its end.
A piece reads alone because the writer measures near inside the piece. A new piece carries the definition of every track the chain has used, even when the piece before held it a few bytes earlier. It also carries each state track's newest state item. A reader of piece 7 alone therefore decodes everything piece 7 holds.
Pieces know each other¶
Each piece says by itself where it belongs. Its piece head holds its id, the owner id and its piece number, which counts from 0 in each chain. The head also names the piece before it by that piece's content hash and id. The close names the next piece's id. The ids follow from the owner id and the chain number, so a reader tells two chains apart.
A program therefore never trusts a file's name. Files renamed by hand, copied into one directory from several disks or
listed in any order still form their chain. A scan opens each file from its end, a few small reads, and learns which
piece it is and which items it holds. check_chain then orders the pieces and checks every link both ways:
// Copied by hand under names that sort in the wrong order: piece 0 becomes d.wwt, piece 3 a.wwt.
let mixed = scratch("chains_mixed");
for seq in 0..pieces {
let name = ["d.wwt", "c.wwt", "b.wwt", "a.wwt"][seq as usize];
std::fs::copy(
dir.join(ww_tape_fs::chain::piece_name(seq)),
mixed.join(name),
)?;
}
// A scan opens each file from its end and asks the piece where it belongs and what it holds.
let mut found = Vec::new(); // (file, piece number, the items of the track)
let mut summaries = Vec::new();
for file in std::fs::read_dir(&mixed)? {
let path = file?.path();
let reader = TapeReader::open(ww_tape_fs::FileSource::open(&path)?)?;
let piece = &reader.pieces()[0];
let summary = piece.summary().ok_or("a closed piece")?;
let (_, ranges) = piece.close.as_ref().ok_or("a close")?;
let items = ranges[0].first_item.get()..ranges[0].end_item().get();
found.push((
path.file_name().ok_or("a name")?.to_owned(),
summary.ident.seq,
items,
));
summaries.push(summary);
}
// The heads put the pieces in order, whatever their names, and every link holds.
let report = check_chain(&summaries);
assert!(report.is_whole());
found.sort_by_key(|(_, seq, _)| *seq);
assert_eq!(
found,
[
("d.wwt".into(), 0, 0..1600),
("c.wwt".into(), 1, 1600..3150),
("b.wwt".into(), 2, 3150..4700),
("a.wwt".into(), 3, 4700..6000),
]
);
The scan needs no index of the directory and no database beside the files. The close of each piece lists every track it holds with its first and last item number and tick. A viewer thus knows which file to open for a given second before it reads any data.
A chain in a directory¶
A PieceChain writes a chain and cuts it by itself. On files, ww_tape_fs::chain::create makes one file
per piece in a directory, named 00000000.wwt, 00000001.wwt and so on, so that the names sort in chain order. The
test below cuts a piece once it holds 16 KiB:
let options = ChainOptions {
cut: CutPolicy {
bytes: exact_units::Bytes::new(16 << 10), // a new piece once one holds 16 KiB
..CutPolicy::default()
},
tapes: PieceTapes::Each, // a file per piece: 00000000.wwt, 00000001.wwt, ...
writer: WriterOptions {
index: IndexPolicy {
bytes: exact_units::Bytes::new(4 << 10),
..IndexPolicy::default()
},
..WriterOptions::default()
},
};
let mut chain = ww_tape_fs::chain::create(&dir, owner, 0, &[], options)?;
for k in 0..120 {
let (head, starts) = chunk(0, k);
chain.write_chunk(defs, &head, &column(&starts))?; // cuts first when the piece is full
}
let pieces = chain.close()?;
The chain takes an owner id and a chain number. The owner id is a 32-byte id that the application chooses and
ww_tape does not interpret, such as a project's id. One owner may have several chains, such as one for events and one
for a high-rate stream. Each chain then gets its own piece ids and session tag. Tracks of several owners can share
one chain (Track owners and hashes).
When to cut¶
A CutPolicy has three limits, and the first one reached cuts:
| Limit | Cuts when the piece holds |
|---|---|
bytes |
that many bytes, such as 256 MiB |
chunks |
that many chunks |
interval |
data for that long, counted from its start or its resume |
A limit of 0 or None is off. The chain checks the policy before each chunk, so a cut never comes after the last chunk
and never leaves a piece without data. The chain also cuts before a write that the piece's index has no room left for.
PieceChain::cut_now cuts at once.
A cut by age makes the file's bytes depend on the clock. The drive's recorder counts chunks instead, as many as 15 minutes of the run make:
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,
}
What the example uses here: Drive
/// 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,
}
A recorder that writes a PieceChain itself and must know in which piece a chunk lands asks PieceChain::cut_due
and cuts first with PieceChain::cut_now. A TapeMux does so on its writing thread before it places each
chunk. A chunk thus lies whole in one piece, and its handle never notices the cut. TapeMux::cut cuts at once.
The drive's recorder only starts the mux with these options, and hands it the acts through its handles:
What the example uses here: Act, Recorder
/// 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 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,
}
Nothing waits for a cut¶
Durability comes from the sync policy and the checkpoints, which work inside a piece. A cut only bounds how large one file grows. A slow input of one log line a minute goes into a records block as it comes. The writer syncs it within the sync interval, and a reader of the unclosed piece reads it at once.
What a cut writes¶
A cut ends the current piece and starts the next one. TapeWriter::cut_with does it in five steps:
- It places every deferred block still waiting.
- It writes the final index, the close and the tail.
- It closes the sink; a file takes its final name.
- It starts the next piece in a new sink, which the store makes under the next key.
- It puts the definitions of every track that the new head carries, from its caller's
Definitions.
ww_tape_figures from the drive's chain at 1/1000 of its data; each row has its own scale.At full rate, piece 0 of the drive ends with a final index of 443 kB. The close takes 2556 bytes, 1680 of them padding, and the tail 164 bytes. Piece 1 starts with a head of 636 bytes, then 2 blocks of puts of 624 bytes in all.
The head lists every track the chain has used so far, a state track included. The puts after it carry their definitions, and the mode's newest item. The definitions a new piece carries says which definitions a piece carries and what they cost.
The four pieces of the hour end on 4 KiB:
| Piece | Bytes | Close padding |
|---|---|---|
| 0 | 29396992 | 1680 |
| 1 | 29614080 | 1820 |
| 2 | 29605888 | 1687 |
| 3 | 26890240 | 3259 |
A TapeWriter without a chain cuts the same way. TapeWriter::cut_on takes a sink the caller made, and
writer::cut the path of the next file. Only a piece of a chain can be cut: such a piece starts with a piece head,
which TapeWriter::begin_piece writes. A piece takes data of a bounded number of tracks, and a head carries a bounded
number of rows (Tape pieces).
Deleting old pieces¶
Retention by file deletes the oldest piece. Every piece left reads alone, and the chain reads as head cut: its start was deleted, not damaged.
std::fs::remove_file(dir.join(ww_tape_fs::chain::piece_name(0)))?; // retention: the oldest piece goes
let mut summaries = Vec::new();
for seq in 1..pieces.len() as u64 {
let bytes = std::fs::read(dir.join(ww_tape_fs::chain::piece_name(seq)))?;
let reader = TapeReader::open(&bytes[..])?; // each piece reads alone
summaries.extend(reader.pieces().iter().filter_map(|p| p.summary()));
}
let report = check_chain(&summaries);
assert!(report.head_cut); // the start was deleted, not damaged
assert!(report.links.iter().all(|l| *l == ChainLink::Linked));
The drive's chain without piece 0 shows it. check_chain finds 3 pieces from piece 1, and both links between them
hold. The report says head cut, and so not whole. Piece 1 defines every track at its start, the carried ones.
A resume (PieceChain::resume_on, or chain::resume for files) starts at the lowest piece there, as a reader
does. Retention and a writer that goes on after a restart thus work together.
A chain in memory keeps a bounded window the same way. MemPieces::remove takes a closed piece out of the store. A
reader that already holds the piece reads on unchanged. The piece still being written is not removed
(MemError::Unclosed).
A chain in one memory tape keeps its window with MemPieces::drop_front. The call frees the oldest pieces whole, in
blocks of memory of up to 64 MiB. Offsets don't move: the tape now starts at its first kept piece
(ByteSource::start). A reader opened on it finds the pieces from there, as a head cut. The piece being written
stays, and a read of a dropped piece fails with MemError::Dropped.
Pieces removed on purpose¶
An application may delete pieces from the middle of a chain on purpose, such as a stretch a user cut out. Without a
note, the hole reads as pieces lost. The note is a list of the removed pieces in a close: each row gives one removed piece's
piece number, id and content hash (RemovedPiece).
The writer appends the note to the chain's last piece, after its close:
- Resume the closed last piece (
TapeWriter::resume_on, orwriter::resumefor a file). An append would start a new piece, which cannot name removed pieces. - Name the removed pieces with
TapeWriter::record_removed. - Close it. The new close names the pieces, and every later close of the piece names them again.
check_chain then links over the hole as ChainLink::Removed, and checks both ends of the hole by the rows. A row
that disagrees with either end reads as broken. A chain whose first pieces were named this way reads as removed, not as
head cut. The chain report gives the rules the writer enforces on the rows.
A resume walks over such a hole the same way. Any other hole stops it with ResumeError::Gap, which names the
missing piece numbers. The writer never goes on after pieces that may have been lost.
Removing pieces while the chain is written¶
PieceChain::remove removes closed pieces of a chain that is being written, in one call. Order matters, since a
crash can come between any two steps:
- Name each removed piece that comes after a piece that stays in the piece being written. The rows a removed piece held for a hole removed before are named again.
- Close that piece and sync it, then write on after the close (
TapeWriter::close_and_go_on). - Take the pieces out of the store, oldest first (
PieceStore::remove): a file is deleted and its directory synced.
// pieces 1 and 2 named in piece 4, which is closed and synced, then taken out of the store
c.remove(&[1, 2]).unwrap();
assert_eq!(mem.keys().unwrap(), [0, 3, 4]);
A crash before the third step leaves pieces at hand that the rows name. A row for a piece still there plays no part in a link. A crash part way through it leaves a hole the rows cover. Either way the chain reads whole and resumes:
// a crash, then a resume over the hole: pieces 0 and 3 closed, piece 4 written on
let (mut c, _) =
PieceChain::resume_on(mem.clone(), OWNER, 0, options(PieceTapes::Each)).unwrap();
assert_eq!((c.seq(), c.closed().len()), (4, 2));
The pieces before every piece that stays get no row: they go as retention does, and the chain reads as head cut. Rows
for them would only pile up, while a head cut already says the start was deleted. In a chain in one memory tape only
those pieces go, as the tape's front (MemPieces::drop_front). A piece from the middle of a tape is refused, as is
the piece being written.
Writing a chain into one file¶
A chain of many files suits retention, since old pieces go file by file. One file per recording suits an application
that keeps a recording as one document, such as a project file. ChainOptions::tapes makes the choice:
PieceTapes::Each, the default, writes a file per piece.PieceTapes::Onewrites every piece into the one file the chain was created with. A cut then starts the next piece right behind the closed one (TapeWriter::cut_in_place).
The bytes are the same as those of a chain of many files placed back to back. A reader walks such a file from its end. The last tail gives the last piece's start, and the tail just before that start gives the piece before.
let options = ChainOptions {
tapes: PieceTapes::One,
..ChainOptions::default()
};
let mut chain = ww_tape_fs::chain::create(path, owner, 0, &[], options.clone())?;
chain.write_chunk(defs, head, columns)?;
let first = chain.close()?;
// opened again: written on after the close
let (mut chain, _) = ww_tape_fs::chain::resume(path, owner, 0, options)?;
chain.write_chunk(defs, head, columns)?;
let second = chain.close()?;
The first session leaves one closed piece in the file. The second finds it by the tails, writes on after its close and closes it again. The file still holds one piece, closed twice, and gains a piece only where the chain cuts. An unclosed last piece, cut off by a crash, resumes as When the power fails describes.
The 4 KiB end and cloning¶
A closed piece is a multiple of 4 KiB long: the writer pads the close with zeros up to the boundary. The boundary makes cloning free on file systems that share data between files. The Linux file systems Btrfs and XFS can clone a range of one file into another. The new file then points at the same disk blocks.
The kernel clones only ranges that start on a block boundary in both files, 4 KiB on common setups. cp --reflink, the
FICLONERANGE call and copy_file_range clone, and std::io::copy uses copy_file_range between files on Linux.
Every closed piece ends on a boundary, so pieces clone back to back with nothing between them. In an aligned
file, the payloads keep their alignment too.
Clones and subsets of a file¶
A clone of a file has the same bytes as the original: every block, index entry and content hash.
TapeReader::verify checks it against the hash its close states. A subset keeps only some tracks, so it is a new
file:
| Part | Clone | Subset |
|---|---|---|
| chunk and summary bodies: columns, item numbers, ticks | same | same |
| block headers: session tag, sequence number, CRC | same | the subset's own |
| definitions and state records | same | the kept tracks' only, put by the subset's writer |
| index, close, tail, content hash | same | new |
| piece ids | same | new |
The items of a subset keep their item numbers and ticks, so a reference to an item stays valid. To write one, an
application holds the kept tracks' definitions, puts their state and writes the chosen blocks through its own writer. It
renumbers each block into the subset's session with ww_tape::set_id.
TapeWriter.TapeReader.mode; the writer keeps its items near their uses.pub fn check_chain(pieces: &[PieceSummary]) -> ChainReport
Order pieces of one recording by sequence number and check each link both ways.
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 create(
dir: &Path,
owner: OwnerId,
chain: u64,
tracks: &[TrackStart],
options: ChainOptions,
) -> Result<PieceChain<FilePieces>, WriteError<FsError>> {
PieceChain::create_on(files_at(dir, &options), owner, chain, tracks, options)
}
Start chain chain of owner in dir (which must exist; with PieceTapes::One the file to create) with its
first piece, see PieceChain::create_on.
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_now(&mut self, defs: &Definitions) -> Result<(), WriteError<T::Error>>
Cut to a new piece now, its head followed by the definitions defs holds of the tracks it carries
(TapeWriter::cut_on). A cut refused before the piece ends keeps the piece being written.
pub fn cut_due(&self) -> bool {
let Some(w) = self.writer.as_ref() else {
return false;
};
// never inside a unit ([TapeWriter::write_chunk_unit])
if w.unit_open() {
return false;
}
let c = self.cut;
(c.bytes.get() > 0 && w.bytes() >= c.bytes.get())
|| (c.chunks.get() > 0 && w.chunks() >= c.chunks.get())
|| c.interval
.is_some_and(|t| w.clock().passed(self.started, t))
}
Whether the policy says the current piece is full: checked before a chunk, by its bytes, its chunk blocks (TapeWriter::chunks, whoever wrote them) and its age. False after a failed cut.
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 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 cut_with<T: PieceStore<Sink = S, Error = S::Error>>(
self,
defs: &Definitions,
tapes: &mut T,
next: &T::Key,
) -> Result<(Closed, Self), CutError<S>> {
self.cut_into(defs, || {
tapes
.create(next)
.map_err(sink_err("creating the next piece"))
})
}
End this piece as a cut (a Close naming the next piece) and start the next piece of the chain on the tape tapes makes
under next, see Self::cut_on.
pub struct TapeWriter<S: TapeSink>
Appends blocks to a TapeSink, a file by default, see the module docs.
pub fn cut_on(self, defs: &Definitions, next: S) -> Result<(Closed, Self), CutError<S>> {
self.cut_into(defs, || Ok(next))
}
End this piece as a cut (a Close naming the next piece) and start the next piece of the chain on next: its id
PieceId::after this one's id and final content hash (the close's), its head naming this piece, the track
starts moved on by this piece's chunks, then the layout and the producer put, then the definitions of every
track the head carries that defs holds (Definitions::needs), in blocks of at most CARRIED_BLOCK_LEN that
each hold their tracks' clocks and maps: a piece holds the definitions of its quiet tracks too, so it reads
alone when the pieces before it are gone.
pub fn cut(
writer: TapeWriter<FileSink>,
defs: &Definitions,
next_path: &Path,
) -> Result<(Closed, TapeWriter<FileSink>), CutError<FileSink>> {
writer.cut_with(defs, &mut FilePieces::file(next_path), &0)
}
End the piece writer writes by a cut and start the next piece of the chain in a new file at next_path.
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 fn resume_on(
store: T,
owner: OwnerId,
chain: u64,
options: ChainOptions,
) -> Result<(Self, Resumed), WriteError<T::Error>> {
match options.tapes {
PieceTapes::Each => Self::resume_each(store, owner, chain, options),
PieceTapes::One => Self::resume_one(store, owner, chain, options),
}
}
Reopen chain chain of owner in store to write on, after a crash or after its close, from the lowest piece
there (PieceStore::first_from): the pieces before it were deleted (a head cut).
pub fn resume(
dir: &Path,
owner: OwnerId,
chain: u64,
options: ChainOptions,
) -> Result<(PieceChain<FilePieces>, Resumed), WriteError<FsError>>
Reopen chain chain of owner in dir (with PieceTapes::One the file) after a crash, see
[PieceChain::resume_on]: from the lowest piece file there, past pieces removed on purpose.
pub fn remove(&self, key: &K) -> Result<bool, MemError<K>> {
let mut map = self.lock()?;
match map.get(key) {
None => Ok(false),
Some(t) if !t.is_closed() => Err(MemError::Unclosed(key.clone())),
Some(_) => Ok(map.remove(key).is_some()),
}
}
Take the closed piece under key out of the map: true when it was there, false when it was not.
Unclosed(K),
MemPieces::remove of a tape still being written.
pub fn drop_front(&self, key: &K, to: u64) -> Result<Option<u64>, MemError<K>> {
let Some(tape) = self.get(key)? else {
return Ok(None);
};
Ok(Some(tape.write()?.drop_front(to)))
}
Free the oldest pieces of the tape under key that end at or before to, an offset in the tape: the first
byte it keeps (ByteSource::start), None when there is no tape under key.
fn start(&self) -> Result<u64, Self::Error> {
Ok(0)
}
Offset of the first byte there is: 0, or where bytes before it were freed (a memory tape whose oldest pieces were dropped). A reader finds no piece before it.
Dropped { front: u64 },
A read or truncate before front, the first byte kept: MemPieces::drop_front freed the bytes before it.
pub struct RemovedPiece {
pub seq: u64,
pub id: PieceId,
/// The content hash of the piece's close in force: what the next piece's head names.
pub hash: ContentHash,
}
A piece of the chain removed on purpose, as a close record names it (Close, check_chain).
Removed { pieces: u64 },
The pieces between them were removed on purpose: a close at hand names each of them (RemovedPiece), the
earlier piece's last close, a cut, names the first one's id, and the later head names the last one's hash and
id.
Gap { from: u64, to: u64 },
The pieces of sequence numbers from..to are missing from the middle of the chain, and the closes at hand don't
name them as removed on purpose (TapeWriter::record_removed) or name them
with ends that don't link to the pieces on either side.
pub fn remove(&mut self, seqs: &[u64]) -> Result<(), WriteError<T::Error>>
Remove the closed pieces of sequence numbers seqs from the store, on purpose, so that the chain still reads
and resumes, also after a crash part way.
pub tapes: PieceTapes,
A tape per piece, or all pieces in one.
pub fn verify(&self, i: usize) -> R<Verification, S>
Whether closed piece i holds up as a whole: its bytes before its close record hash to the close's content
hash (each block that reads whole as it is, a chunk's payload by its hash, other bytes as they are,
piece docs); its final index and the blocks walked are the same set: each block walked that
its writer lists has exactly the entries its writer made of it, field for field (offset, length, kind, track,
items, ticks, a chunk's unit hash of its bytes and its range relation's range from its column), but a
byte-identical copy of the listed block before it; each entry names a block walked, or a block that doesn't
read whole in bytes no block explains, ending before the close and before the next block walked; and each
close row states the hash its track's blocks fold to from the head row's, or says it incomplete exactly where
a damaged block kept or the head leaves units out.
pub fn set_id(block: &mut [u8], id: BlockId) -> Result<(), BlockError> {
restamp(block, id, 0, Reread::Whole)
}
Give the whole, good block block the session and seq of id and rewrite its CRCs.
A chunk or index block's head CRC is rewritten too. A writer that places blocks later than it made them (a summary block filling the gap before an aligned chunk) so keeps seqs ascending in the file and every block in its session.
PieceStore; the book never uses store as a verb.pub struct Definitions
The definitions an application works with, see the module docs.
pub fn resume_on(
mut sink: S,
options: WriterOptions,
) -> Result<(Self, Resumed), WriteError<S::Error>>
Reopen the unclosed piece in sink (cut off by a crash, or cut in its end) to go on writing it, see the
module docs; a closed piece is written on after its last close. options are the ones it was written
with.
pub fn resume(
path: &Path,
options: WriterOptions,
) -> Result<(TapeWriter<FileSink>, Resumed), WriteError<FsError>>
Reopen the piece path to write on, see TapeWriter::resume_on.
pub fn record_removed(
&mut self,
pieces: &[crate::piece::RemovedPiece],
) -> Result<(), WriteError<S::Error>>
Name pieces of the chain as removed on purpose in the close of this piece and in every later close of it, with
those named before (crate::piece::RemovedPiece).
pub fn close_and_go_on(self) -> Result<(Self, Closed), WriteError<S::Error>>
Close the piece now (CloseReason::Closed), synced, and go on writing after that close: the writer a resume of the closed piece gives (Self::resume_on), so the calls after it write what they would after a close and a resume.
fn remove(&mut self, key: &Self::Key) -> Result<bool, Self::Error>;
Take the tape key of a closed piece out of the store, durably: a file is deleted and its directory synced.
False when there was none.
Each,
Each piece a tape of its own, piece seq under PieceStore::key_of (seq): a file per piece in a directory.
One,
All pieces back to back in one tape, under PieceStore::key_of (0): one file.
pub fn cut_in_place(self, defs: &Definitions) -> Result<(Closed, Self), CutError<S>>
End this piece as a cut (a Close naming the next piece) and start the next piece of the chain right behind it in the same sink, as Self::cut_on does on a new one: the sink's window (TapeSink::rebase) moves to the end of this piece, a multiple of PIECE_ALIGN when this one started on one.