diff --git a/apps/origin-src/src/frames.rs b/apps/origin-src/src/frames.rs new file mode 100644 index 00000000..92e4e90b --- /dev/null +++ b/apps/origin-src/src/frames.rs @@ -0,0 +1,282 @@ +//! Append-only files of checked frames, which the [record index](crate::index) +//! is made of. +//! +//! A file is a header naming its format and version, then frames. A frame is +//! its payload's `u32` length, the payload, the first 8 bytes of the +//! payload's BLAKE3 hash, and the length again, so the last frame can be +//! checked from the end without reading the rest. +//! +//! Appenders hold an exclusive lock and write whole frames at the end. A +//! crash in the middle of an append leaves part of a frame at the end, a +//! partial tail: readers skip it, and the next append cuts it off first, so +//! a partial frame is only ever last. Anything else that fails its check is +//! damage, which each format handles its own way, including a length that +//! runs past the end of the file when a frame written in full ends it: an +//! append cut short never leaves one. + +use std::fs::File; +use std::io::{self, Read, Seek, SeekFrom, Write}; + +use origin_platform::Durability; +use origin_shared::Digest; +use origin_shared::object::DecodeError; + +/// The format of a file of frames: its header. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Frames { + header: &'static [u8], +} + +/// How a file ends after its last intact frame. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Tail { + /// It ends there. + Clean, + /// With part of a frame, at this offset: an append in progress, or one a + /// crash cut short. + Partial(u64), + /// With damage, or a header from another format or version. + Damaged, +} + +/// Why a frame cannot be read. +enum Broken { + /// The bytes end before it does. + Partial, + /// It is not what was appended: it fails its check, or its payload + /// doesn't decode. Each format handles damage the same way whatever + /// the reason. + Damaged, +} + +impl Frames { + /// The length of a frame's check. + const CHECK: usize = 8; + + /// The bytes a frame adds to its payload: two lengths and a check. + pub(crate) const FRAMING: usize = 4 + Self::CHECK + 4; + + /// The format whose files start with `header`. + pub(crate) const fn new(header: &'static [u8]) -> Self { + Self { header } + } + + /// The header every file of the format starts with. + pub(crate) fn header(self) -> &'static [u8] { + self.header + } + + /// Encodes the frame of the payload `write` writes. + pub(crate) fn frame(write: impl FnOnce(&mut Writer)) -> Vec { + let mut out = Writer(vec![0; 4]); + write(&mut out); + let mut out = out.0; + let len = u32::try_from(out.len() - 4) + .expect("frames are under 4 GiB") + .to_le_bytes(); + out[..4].copy_from_slice(&len); + let check = Self::check(&out[4..]); + out.extend_from_slice(&check); + out.extend_from_slice(&len); + out + } + + fn check(payload: &[u8]) -> [u8; Self::CHECK] { + Digest::of(payload).as_bytes()[..Self::CHECK] + .try_into() + .expect("a digest is longer than a check") + } + + /// The frames of a file, decoded by `decode`, and their offsets, up to + /// the first broken one, and how the file ends after them. A frame that + /// doesn't decode is damage. + pub(crate) fn parse( + self, + bytes: &[u8], + mut decode: impl FnMut(&[u8]) -> Result, + ) -> (Vec<(u64, T)>, Tail) { + let mut frames = Vec::new(); + let Some(mut rest) = bytes.strip_prefix(self.header) else { + return (frames, Tail::Damaged); + }; + while !rest.is_empty() { + let offset = (bytes.len() - rest.len()) as u64; + let frame = Self::payload(rest).and_then(|(payload, len)| { + let frame = decode(payload).map_err(|_| Broken::Damaged)?; + Ok((frame, len)) + }); + match frame { + Ok((frame, len)) => { + frames.push((offset, frame)); + rest = &rest[len..]; + } + Err(Broken::Partial) if !self.ends_with_frame(bytes, offset) => { + return (frames, Tail::Partial(offset)); + } + Err(_) => return (frames, Tail::Damaged), + } + } + (frames, Tail::Clean) + } + + /// Whether `bytes` end with a frame written in full that starts at or + /// after `offset`, whose trailing length and check are intact. An + /// append cut short never leaves one after it, so a frame at `offset` + /// that seems to run past the end has a damaged length instead. Its + /// leading length isn't checked: it may be the damaged one. + fn ends_with_frame(self, bytes: &[u8], offset: u64) -> bool { + let Some((rest, len)) = bytes.split_last_chunk::<4>() else { + return false; + }; + let len = u32::from_le_bytes(*len) as usize; + let Some(start) = bytes.len().checked_sub(len + Self::FRAMING) else { + return false; + }; + if (start as u64) < offset || start < self.header.len() { + return false; + } + let (payload, check) = rest[start + 4..].split_at(len); + *check == Self::check(payload) + } + + /// Checks the frame `bytes` start with, returning its payload and its + /// length. + fn payload(bytes: &[u8]) -> Result<(&[u8], usize), Broken> { + let (len, rest) = bytes.split_first_chunk::<4>().ok_or(Broken::Partial)?; + let (payload, rest) = rest + .split_at_checked(u32::from_le_bytes(*len) as usize) + .ok_or(Broken::Partial)?; + let (check, rest) = rest + .split_first_chunk::<{ Self::CHECK }>() + .ok_or(Broken::Partial)?; + let (end, _) = rest.split_first_chunk::<4>().ok_or(Broken::Partial)?; + if end != len || *check != Self::check(payload) { + return Err(Broken::Damaged); + } + Ok((payload, payload.len() + Self::FRAMING)) + } + + /// The payload of the last frame of `file`, or `None` if it holds only + /// the header, after cutting off a partial frame a crash left, durably. + /// Reads only the last frame, backwards from its trailing length, unless + /// it's broken. + /// + /// # Errors + /// + /// Fails with [`io::ErrorKind::InvalidData`] if the file is damaged, or + /// if it cannot be read or cut. + pub(crate) fn last( + self, + platform: &impl Durability, + file: &File, + ) -> io::Result>> { + if let Some(last) = self.peek_last(file)? { + return Ok(last); + } + let mut bytes = Vec::new(); + let mut reader = file; + reader.seek(SeekFrom::Start(0))?; + reader.read_to_end(&mut bytes)?; + let (frames, tail) = self.parse(&bytes, |payload| Ok(payload.to_vec())); + match tail { + Tail::Clean => {} + Tail::Partial(offset) => { + file.set_len(offset)?; + platform.sync_file(file)?; + } + Tail::Damaged => return Err(io::ErrorKind::InvalidData.into()), + } + Ok(frames.into_iter().last().map(|(_, payload)| payload)) + } + + /// The last frame's payload, `Some(None)` for a file holding only the + /// header, or `None` if the file doesn't end with an intact frame. Reads + /// only the last frame, and never writes. + #[expect( + clippy::option_option, + reason = "a file with no frame, and one that doesn't end with one, differ" + )] + pub(crate) fn peek_last(self, mut file: &File) -> io::Result>>> { + let len = file.metadata()?.len(); + let header = self.header.len() as u64; + if len <= header { + return Ok((len == header).then_some(None)); + } + let mut end = [0; 4]; + file.seek(SeekFrom::Start(len - 4))?; + file.read_exact(&mut end)?; + let frame = u64::from(u32::from_le_bytes(end)) + Self::FRAMING as u64; + if frame > len - header { + return Ok(None); + } + let mut bytes = vec![0; usize::try_from(frame).map_err(io::Error::other)?]; + file.seek(SeekFrom::Start(len - frame))?; + file.read_exact(&mut bytes)?; + Ok(Self::payload(&bytes) + .ok() + .map(|(payload, _)| Some(payload.to_vec()))) + } + + /// Appends `frame` to the locked `file`, opened for appending, without + /// syncing it, returning its offset. A partial frame a crash left is cut + /// off first; damage is left for readers to find. + /// + /// # Errors + /// + /// Fails if the file cannot be read, cut or written. + pub(crate) fn append( + self, + platform: &impl Durability, + file: &File, + frame: &[u8], + ) -> io::Result { + match self.last(platform, file) { + Err(error) if error.kind() == io::ErrorKind::InvalidData => {} + result => { + result?; + } + } + let offset = file.metadata()?.len(); + if let Err(error) = (&*file).write_all(frame) { + // Best effort: the next append cuts it off otherwise. + let _ = file.set_len(offset); + return Err(error); + } + Ok(offset) + } +} + +/// Builds a frame's payload, which a +/// [`Reader`](origin_shared::object::Reader) reads. +#[derive(Debug)] +pub(crate) struct Writer(Vec); + +impl Writer { + pub(crate) fn bytes(&mut self, bytes: &[u8]) { + self.0.extend_from_slice(bytes); + } + + pub(crate) fn u8(&mut self, value: u8) { + self.0.push(value); + } + + pub(crate) fn u64(&mut self, value: u64) { + self.bytes(&value.to_le_bytes()); + } + + /// A `u32` count, of items or bytes. + pub(crate) fn len(&mut self, len: usize) { + self.bytes(&u32::try_from(len).expect("fewer than 2^32").to_le_bytes()); + } + + /// A 0 byte for `None`, or a 1 byte and the id. + pub(crate) fn option(&mut self, id: Option<&[u8; 32]>) { + match id { + None => self.u8(0), + Some(id) => { + self.u8(1); + self.bytes(id); + } + } + } +} diff --git a/apps/origin-src/src/index.rs b/apps/origin-src/src/index.rs index 716008dc..c147d653 100644 --- a/apps/origin-src/src/index.rs +++ b/apps/origin-src/src/index.rs @@ -12,12 +12,10 @@ //! corrupt or don't decode, which readers can't use either, and reports //! them ([`Skipped`]). //! -//! On disk it is one append-only file, `index/log`: a header, then frames. -//! A frame is its payload's `u32` length, the payload, the first 8 bytes of -//! the payload's BLAKE3 hash, and the length again, so the last frame can be -//! checked from the end. A payload is what the index keeps of each record -//! of a batch, the mark that the batch at some offset was published, or -//! input digests computed since. +//! On disk it is one append-only file of [frames](crate::frames), +//! `index/log`. A frame holds what the index keeps of each record of a +//! batch, the mark that the batch at some offset was published, or input +//! digests computed since. //! //! [`Batch::commit`](crate::store::Batch::commit) appends a batch's entries //! before publishing its records, and the batch sync makes them durable @@ -42,8 +40,8 @@ use std::borrow::Cow; use std::collections::{HashMap, HashSet}; use std::fmt; -use std::fs::{self, File, OpenOptions}; -use std::io::{self, Read, Seek, SeekFrom, Write}; +use std::fs::{self, OpenOptions}; +use std::io; use std::path::PathBuf; use origin_platform::{DurableWrite, LockMode, LockedFile, Platform}; @@ -53,6 +51,7 @@ use origin_shared::{ RevisionId, Statement, StatementId, TreeId, }; +use crate::frames::{Frames, Tail, Writer}; use crate::store::{Store, StoreError}; /// The records of a store, by the fields they're looked up by. @@ -533,14 +532,14 @@ impl Entry { } fn id(&self) -> ObjectId { - Log::split(self.record()).1 + ObjectId::from(self.record()) } /// Appends the entry: its record's kind and id, then for a revision its /// change and a `u32` count of predecessors and their ids, and for a /// statement its subject's kind and id, and the statement it supersedes /// and its promotion group, each a 0 byte, or a 1 byte and the id. - fn write(&self, out: &mut Vec) { + fn write(&self, out: &mut Writer) { Log::write_record(self.record(), out); match self { Self::Revision { @@ -548,11 +547,10 @@ impl Entry { predecessors, .. } => { - out.extend_from_slice(change.as_bytes()); - let count = u32::try_from(predecessors.len()).expect("fewer than 2^32"); - out.extend_from_slice(&count.to_le_bytes()); + out.bytes(change.as_bytes()); + out.len(predecessors.len()); for predecessor in predecessors { - out.extend_from_slice(predecessor.as_bytes()); + out.bytes(predecessor.as_bytes()); } } Self::Statement { @@ -562,8 +560,8 @@ impl Entry { .. } => { Log::write_record(*subject, out); - Log::write_option(supersedes.as_ref().map(StatementId::as_bytes), out); - Log::write_option(group.as_ref().map(Digest::as_bytes), out); + out.option(supersedes.as_ref().map(StatementId::as_bytes)); + out.option(group.as_ref().map(Digest::as_bytes)); } Self::Acceptance(_) => {} } @@ -618,41 +616,30 @@ impl Frame<'_> { const PUBLISHED: u8 = 2; const DIGESTS: u8 = 3; - /// Encodes the frame: its payload's length, the payload (a tag and the - /// contents), a check, and the length again, so the last frame of a log - /// can be read backwards. + /// Encodes the frame: a tag, then its contents. fn encode(&self) -> Vec { - let mut out = vec![0; 4]; - match self { + Frames::frame(|out| match self { Self::Records(entries) => { - out.push(Self::RECORDS); + out.u8(Self::RECORDS); for entry in entries.iter() { - entry.write(&mut out); + entry.write(out); } } Self::Published(offset) => { - out.push(Self::PUBLISHED); - out.extend_from_slice(&offset.to_le_bytes()); + out.u8(Self::PUBLISHED); + out.u64(*offset); } Self::Digests(digests) => { - out.push(Self::DIGESTS); + out.u8(Self::DIGESTS); for (statement, digest) in digests.iter() { - out.extend_from_slice(statement.as_bytes()); - out.extend_from_slice(digest.as_bytes()); + out.bytes(statement.as_bytes()); + out.bytes(digest.as_bytes()); } } - } - let len = u32::try_from(out.len() - 4) - .expect("index frames are under 4 GiB") - .to_le_bytes(); - out[..4].copy_from_slice(&len); - let check = Log::check(&out[4..]); - out.extend_from_slice(&check); - out.extend_from_slice(&len); - out + }) } - fn decode(payload: &[u8]) -> Result { + fn decode(payload: &[u8]) -> Result, DecodeError> { let mut reader = Reader::new(payload); let frame = match reader.u8()? { Self::RECORDS => { @@ -660,16 +647,16 @@ impl Frame<'_> { while reader.remaining() > 0 { entries.push(Entry::read(&mut reader)?); } - Self::Records(Cow::Owned(entries)) + Frame::Records(Cow::Owned(entries)) } - Self::PUBLISHED => Self::Published(reader.u64()?), + Self::PUBLISHED => Frame::Published(reader.u64()?), Self::DIGESTS => { let mut digests = Vec::new(); while reader.remaining() > 0 { let statement = ObjectId::from_bytes(reader.array()?).into(); digests.push((statement, Digest::from_bytes(reader.array()?))); } - Self::Digests(Cow::Owned(digests)) + Frame::Digests(Cow::Owned(digests)) } tag => { return Err(DecodeError::UnknownTag { @@ -687,24 +674,12 @@ impl Frame<'_> { struct Log; impl Log { - /// The start of every log, with the format's version. - const HEADER: &[u8] = b"origin index 2\n"; - - /// The length of a frame's check. - const CHECK: usize = 8; - - /// The bytes a frame adds to its payload: two lengths and a check. - const FRAMING: usize = 4 + Self::CHECK + 4; - - fn check(payload: &[u8]) -> [u8; Self::CHECK] { - Digest::of(payload).as_bytes()[..Self::CHECK] - .try_into() - .expect("a digest is longer than a check") - } + /// The format, and its version. + const FRAMES: Frames = Frames::new(b"origin index 2\n"); /// Encodes a log holding `entries`, all published, and `digests`. fn encode(entries: &[Entry], digests: &[(StatementId, Digest)]) -> Vec { - let mut log = Self::HEADER.to_vec(); + let mut log = Self::FRAMES.header().to_vec(); let offset = log.len() as u64; log.extend(Frame::Records(Cow::Borrowed(entries)).encode()); log.extend(Frame::Published(offset).encode()); @@ -717,84 +692,16 @@ impl Log { /// The frames of a log and their offsets, up to the first broken one, /// and how it ends after them. fn parse(bytes: &[u8]) -> (Vec<(u64, Frame<'static>)>, Tail) { - let mut frames = Vec::new(); - let Some(mut rest) = bytes.strip_prefix(Self::HEADER) else { - return (frames, Tail::Damaged); - }; - while !rest.is_empty() { - let offset = (bytes.len() - rest.len()) as u64; - let frame = Self::payload(rest).and_then(|(payload, len)| { - let frame = Frame::decode(payload).map_err(|_| Broken::Damaged)?; - Ok((frame, len)) - }); - match frame { - Ok((frame, len)) => { - frames.push((offset, frame)); - rest = &rest[len..]; - } - Err(Broken::Partial) => return (frames, Tail::Partial(offset)), - Err(Broken::Damaged) => return (frames, Tail::Damaged), - } - } - (frames, Tail::Clean) - } - - /// Checks the frame `bytes` start with, returning its payload and its - /// length. - fn payload(bytes: &[u8]) -> Result<(&[u8], usize), Broken> { - let (len, rest) = bytes.split_first_chunk::<4>().ok_or(Broken::Partial)?; - let (payload, rest) = rest - .split_at_checked(u32::from_le_bytes(*len) as usize) - .ok_or(Broken::Partial)?; - let (check, rest) = rest - .split_first_chunk::<{ Self::CHECK }>() - .ok_or(Broken::Partial)?; - let (end, _) = rest.split_first_chunk::<4>().ok_or(Broken::Partial)?; - if end != len || *check != Self::check(payload) { - return Err(Broken::Damaged); - } - Ok((payload, payload.len() + Self::FRAMING)) - } - - /// Whether the locked `log` ends with an intact frame, or the header. - /// Reads only the last frame, backwards from its trailing length. - fn ends_cleanly(mut log: &File) -> io::Result { - let len = log.metadata()?.len(); - let header = Self::HEADER.len() as u64; - if len <= header { - return Ok(len == header); - } - let mut end = [0; 4]; - log.seek(SeekFrom::Start(len.saturating_sub(4)))?; - log.read_exact(&mut end)?; - let frame = u64::from(u32::from_le_bytes(end)) + Self::FRAMING as u64; - if frame > len - header { - return Ok(false); - } - let mut bytes = vec![0; usize::try_from(frame).map_err(io::Error::other)?]; - log.seek(SeekFrom::Start(len - frame))?; - log.read_exact(&mut bytes)?; - Ok(Self::payload(&bytes).is_ok()) - } - - /// Appends a 0 byte for `None`, or a 1 byte and the id. - fn write_option(id: Option<&[u8; 32]>, out: &mut Vec) { - match id { - None => out.push(0), - Some(id) => { - out.push(1); - out.extend_from_slice(id); - } - } + Self::FRAMES.parse(bytes, Frame::decode) } /// Appends a record's kind and id. - fn write_record(record: RecordId, out: &mut Vec) { - let (kind, id) = Self::split(record); - out.push(kind as u8); - out.extend_from_slice(id.as_bytes()); + fn write_record(record: RecordId, out: &mut Writer) { + out.u8(record.kind() as u8); + out.bytes(ObjectId::from(record).as_bytes()); } + /// Reads what [`Log::write_record`] wrote. fn read_record(reader: &mut Reader<'_>) -> Result { let kind = reader.u8()?; let id = ObjectId::from_bytes(reader.array()?); @@ -811,40 +718,6 @@ impl Log { } }) } - - /// A record's kind and id. - fn split(record: RecordId) -> (ObjectKind, ObjectId) { - match record { - RecordId::Snapshot(id) => (ObjectKind::Tree, id.into()), - RecordId::Revision(id) => (ObjectKind::Revision, id.into()), - RecordId::Statement(id) => (ObjectKind::Statement, id.into()), - RecordId::Acceptance(id) => (ObjectKind::Acceptance, id.into()), - } - } -} - -/// How a log ends after its last intact frame. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Tail { - /// It ends there. - Clean, - /// With part of a frame, at this offset: an append in progress, or one a - /// crash cut short. Appenders cut such a leftover off before appending, - /// so it is always last. - Partial(u64), - /// With damage, or a header from another version: the index must be - /// rebuilt. - Damaged, -} - -/// Why a frame cannot be decoded. -enum Broken { - /// The bytes end before it does. - Partial, - /// It is not what was appended: it fails its check, or its payload - /// doesn't decode. Either way the index is rebuilt, so why doesn't - /// matter. - Damaged, } impl Store

{ @@ -928,32 +801,12 @@ impl Store

{ self.platform .lock(&log, LockMode::Exclusive) .map_err(io_error)?; - if !Log::ends_cleanly(&log).map_err(io_error)? { - self.cut_partial_frame(&log).map_err(io_error)?; - } - let offset = log.metadata().map_err(io_error)?.len(); - if let Err(source) = (&log).write_all(&frame.encode()) { - // Best effort: the next append cuts it off otherwise. - let _ = log.set_len(offset); - return Err(io_error(source)); - } + let offset = Log::FRAMES + .append(&self.platform, &log, &frame.encode()) + .map_err(io_error)?; Ok(Some(offset)) } - /// Cuts off the partial frame a crash left at the end of the locked - /// `log`, durably, so appends never follow one. Damage is left for - /// readers to find, so they rebuild the index. - fn cut_partial_frame(&self, mut log: &File) -> io::Result<()> { - let mut bytes = Vec::new(); - log.seek(SeekFrom::Start(0))?; - log.read_to_end(&mut bytes)?; - if let (_, Tail::Partial(offset)) = Log::parse(&bytes) { - log.set_len(offset)?; - self.platform.sync_file(log)?; - } - Ok(()) - } - /// The entry of every record in the store, read from every core, and /// the objects skipped because they are corrupt or don't decode. fn entries(&self) -> Result<(Vec, Vec), StoreError> { @@ -984,6 +837,7 @@ impl Store

{ #[cfg(test)] mod tests { + use std::io::Write; use std::slice; use std::sync::atomic::{AtomicBool, Ordering}; use std::thread; @@ -1198,9 +1052,9 @@ mod tests { ); let mut early = bytes.clone(); - early[Log::HEADER.len() + 10] ^= 1; + early[Log::FRAMES.header().len() + 10] ^= 1; let mut versioned = bytes; - versioned[Log::HEADER.len() - 2] = b'9'; + versioned[Log::FRAMES.header().len() - 2] = b'9'; for damaged in [early, versioned, Vec::new()] { fs::write(&log, damaged).unwrap(); assert_eq!(sorted(Index::open(&store).unwrap()), sorted(index.clone())); diff --git a/apps/origin-src/src/lib.rs b/apps/origin-src/src/lib.rs index f00f28fc..5b41feda 100644 --- a/apps/origin-src/src/lib.rs +++ b/apps/origin-src/src/lib.rs @@ -8,6 +8,7 @@ pub mod config; pub mod conflict; #[cfg(feature = "fixture")] pub mod fixture; +mod frames; pub mod index; pub mod output; pub mod policy; diff --git a/crates/origin-shared/src/object/statement.rs b/crates/origin-shared/src/object/statement.rs index aa171e9c..de1afbcf 100644 --- a/crates/origin-shared/src/object/statement.rs +++ b/crates/origin-shared/src/object/statement.rs @@ -6,8 +6,8 @@ use std::str::FromStr; use super::{DecodeError, Field, ObjectKind, Reader, Record, fields, tagged}; use crate::name::names; use crate::{ - AcceptanceId, BlobId, Digest, InvalidName, Principal, RepoPath, RevisionId, StatementId, - TreeEntry, TreeId, + AcceptanceId, BlobId, Digest, InvalidName, ObjectId, Principal, RepoPath, RevisionId, + StatementId, TreeEntry, TreeId, }; /// An attributable claim about another record: a check result, a review, a @@ -149,6 +149,28 @@ impl RecordId { }; format!("{kind} {id}") } + + /// The kind of the record's object: a snapshot is a tree. + #[must_use] + pub fn kind(self) -> ObjectKind { + match self { + Self::Snapshot(_) => ObjectKind::Tree, + Self::Revision(_) => ObjectKind::Revision, + Self::Statement(_) => ObjectKind::Statement, + Self::Acceptance(_) => ObjectKind::Acceptance, + } + } +} + +impl From for ObjectId { + fn from(record: RecordId) -> Self { + match record { + RecordId::Snapshot(id) => id.into(), + RecordId::Revision(id) => id.into(), + RecordId::Statement(id) => id.into(), + RecordId::Acceptance(id) => id.into(), + } + } } // The tags are the records' object kinds.