diff --git a/crates/origin-shared/benches/object.rs b/crates/origin-shared/benches/object.rs index c2a15e8d..0d8b278c 100644 --- a/crates/origin-shared/benches/object.rs +++ b/crates/origin-shared/benches/object.rs @@ -1,4 +1,4 @@ -//! Encoding, hashing and signing throughput of the object model. +//! Benchmarks encoding, hashing and signing objects. use divan::counter::BytesCount; use divan::{Bencher, black_box}; @@ -12,7 +12,8 @@ fn main() { divan::main(); } -/// Hashing a blob: the cost of snapshotting a changed file. +/// Benchmarks hashing a blob of `len` bytes, as snapshotting a changed +/// file does. #[divan::bench(args = [4 * 1024, 1024 * 1024, 64 * 1024 * 1024])] fn hash_blob(bencher: Bencher<'_, '_>, len: usize) { let content = vec![0xa5_u8; len]; @@ -35,26 +36,26 @@ fn tree(len: usize) -> Tree { .collect() } -/// Encoding and hashing a directory listing. +/// Benchmarks encoding and hashing a tree of `len` entries. #[divan::bench(args = [16, 1024])] fn encode_tree(bencher: Bencher<'_, '_>, len: usize) { let tree = Object::Tree(tree(len)); bencher.bench(|| black_box(&tree).encode()); } -/// Decoding a directory listing: the cost of every tree read. +/// Benchmarks decoding a tree of `len` entries, as every tree read does. #[divan::bench(args = [16, 1024])] fn decode_tree(bencher: Bencher<'_, '_>, len: usize) { let encoded = Object::Tree(tree(len)).encode(); bencher.bench(|| black_box(&encoded).decode_as::().unwrap()); } -/// An id of any type, from a seed. +/// Builds an id of any type by hashing `seed` as a blob. fn id>(seed: &str) -> T { EncodedObject::blob(seed.as_bytes()).id().into() } -/// A CI result with declared inputs: the most common record. +/// Builds a CI result with declared inputs, the most common statement. fn statement() -> Statement { Statement { subject: RecordId::Revision(id("revision")), @@ -75,21 +76,21 @@ fn statement() -> Statement { } } -/// Encoding and hashing a statement. +/// Benchmarks encoding and hashing a statement. #[divan::bench] fn encode_statement(bencher: Bencher<'_, '_>) { let statement = statement(); bencher.bench(|| black_box(&statement).encode()); } -/// Decoding a statement: the cost of every statement read. +/// Benchmarks decoding a statement, as every statement read does. #[divan::bench] fn decode_statement(bencher: Bencher<'_, '_>) { let encoded = statement().encode(); bencher.bench(|| black_box(&encoded).decode_as::().unwrap()); } -/// Encoding and hashing a revision. +/// Benchmarks encoding and hashing a revision. #[divan::bench] fn encode_revision(bencher: Bencher<'_, '_>) { let revision = Revision { @@ -116,7 +117,8 @@ fn acceptance() -> AcceptanceBody { } } -/// Signing an acceptance: once per landing, by the target's authority. +/// Benchmarks signing an acceptance. A target's authority signs one per +/// landing. #[divan::bench] fn sign_acceptance(bencher: Bencher<'_, '_>) { let key = NodeKey::from_bytes(&[42; 32]); @@ -126,7 +128,8 @@ fn sign_acceptance(bencher: Bencher<'_, '_>) { .bench_values(|body| body.sign(&key)); } -/// Verifying an acceptance: once per acceptance of every chain fetched. +/// Benchmarks verifying an acceptance. A fetch verifies each acceptance +/// of every chain it brings. #[divan::bench] fn verify_acceptance(bencher: Bencher<'_, '_>) { let key = NodeKey::from_bytes(&[42; 32]); diff --git a/crates/origin-shared/src/id.rs b/crates/origin-shared/src/id.rs index 6cd50313..3f6a0533 100644 --- a/crates/origin-shared/src/id.rs +++ b/crates/origin-shared/src/id.rs @@ -32,7 +32,7 @@ macro_rules! ids { hex::string(&self.0) } - /// An abbreviated id for display to humans. + /// The first 12 hex digits of the id, for display to humans. #[must_use] pub fn short(&self) -> String { let mut hex = self.to_hex(); @@ -76,9 +76,9 @@ macro_rules! ids { )*}; } -/// Defines ids of objects of one kind. They convert to and from -/// [`ObjectId`]: converting from one vouches for the kind, which reading the -/// object checks. +/// Defines ids of objects of one kind, which convert to and from +/// [`ObjectId`]. Converting from an [`ObjectId`] doesn't check the kind; +/// reading the object does. macro_rules! object_ids { ($($(#[$meta:meta])* $name:ident $(=> $record:ty)?;)*) => { ids! { $($(#[$meta])* $name(32);)* } @@ -105,16 +105,16 @@ macro_rules! object_ids { ids! { /// Identifies an object by the BLAKE3 hash of its encoding. /// - /// The typed ids ([`TreeId`], [`RevisionId`], ...) name objects of one - /// kind, and convert to and from this one. + /// The typed ids ([`TreeId`], [`RevisionId`], ...) identify objects of one + /// kind and convert to and from this one. ObjectId(32); - /// Identifies a change across all its revisions: random, so two changes - /// never share one, whoever creates them and wherever. + /// Identifies a change across all its revisions. It is random, so two + /// changes never share one. ChangeId(16); - /// Identifies a target: the hash of its name, so user-chosen names never - /// become file names. + /// Identifies a target by the hash of its name. Targets are stored under + /// their id, so user-chosen names never become file names. TargetId(32); /// A BLAKE3 hash of something that isn't an object, such as a check's @@ -125,7 +125,8 @@ ids! { object_ids! { /// Identifies a blob: file contents, a description or a payload. BlobId; - /// Identifies a tree, the root of which is a snapshot. + /// Identifies a tree. A snapshot is identified by the id of its root + /// tree. TreeId => Tree; /// Identifies a revision. RevisionId => Revision; @@ -135,14 +136,15 @@ object_ids! { AcceptanceId => Acceptance; } -/// The id of a record of one type, which reading the record returns. +/// An id of a record of one known type: reading it returns a +/// [`TypedId::Record`]. pub trait TypedId: Copy + Into { /// The record the id names. type Record: Record; } impl ObjectId { - /// Hashes an object encoding. + /// Hashes an object's encoding into its id. pub(crate) fn hash(encoded: &[u8]) -> Self { Self(*blake3::hash(encoded).as_bytes()) } @@ -170,8 +172,8 @@ impl Digest { } impl TargetId { - /// The BLAKE3 key derivation context, which keeps target ids apart from - /// every other hash. + /// The BLAKE3 key derivation context for target ids, which keeps them + /// apart from every other hash. const CONTEXT: &str = "origin 2026-10 target name"; /// The id of the target named `name`. @@ -190,22 +192,22 @@ pub struct ParseIdError { pub input: String, } -/// Lowercase hex. +/// Lowercase hex encoding and decoding. pub(crate) mod hex { const DIGITS: &[u8; 16] = b"0123456789abcdef"; /// Number of hex digits a short id has. pub const SHORT_LEN: usize = 12; - /// `bytes` as a string of lowercase hex. + /// Encodes `bytes` as a string of lowercase hex. pub fn string(bytes: &[u8]) -> String { let mut hex = vec![0; 2 * bytes.len()]; encode(bytes, &mut hex); String::from_utf8(hex).expect("hex digits are ASCII") } - /// Writes the two digits of each byte of `bytes` to `out`, which is - /// twice as long. + /// Writes each byte of `bytes` to `out` as two lowercase hex digits. + /// `out` must be twice as long as `bytes`. pub fn encode(bytes: &[u8], out: &mut [u8]) { for (byte, pair) in bytes.iter().zip(out.as_chunks_mut::<2>().0) { *pair = [ @@ -215,7 +217,8 @@ pub(crate) mod hex { } } - /// Parses exactly `2 * N` hex digits, in either case. + /// Parses exactly `2 * N` hex digits, in either case. Returns `None` for + /// anything else. pub fn decode(input: &str) -> Option<[u8; N]> { let input = input.as_bytes(); if input.len() != 2 * N { diff --git a/crates/origin-shared/src/name.rs b/crates/origin-shared/src/name.rs index b6bc05a3..0e9bcb06 100644 --- a/crates/origin-shared/src/name.rs +++ b/crates/origin-shared/src/name.rs @@ -1,11 +1,11 @@ //! Strings restricted to valid names: file names, target names, statement //! kinds and principals. -/// Defines string types holding only valid names. Each type defines -/// `fn is_valid(name: &str) -> bool` in its own `impl` block, where -/// constants can also borrow a static name: `Self(Cow::Borrowed("main"))`. +/// Defines string types that hold only valid names. Each type defines +/// `fn is_valid(name: &str) -> bool` in its own `impl` block. Its constants +/// can borrow a static name: `Self(Cow::Borrowed("main"))`. /// -/// Names are encoded as a `u32` length and their UTF-8 bytes. +/// A name is encoded as a `u32` length and its UTF-8 bytes. macro_rules! names { ($($(#[$meta:meta])* $name:ident($what:literal);)*) => {$( $(#[$meta])* @@ -13,11 +13,11 @@ macro_rules! names { pub struct $name(std::borrow::Cow<'static, str>); impl $name { - /// Validates a name. + /// Creates a name, checking that it is valid. /// /// # Errors /// - /// Fails if the name breaks the rules above. + /// Fails if the name breaks the type's rules. pub fn new(name: impl Into) -> Result { let name = name.into(); if Self::is_valid(&name) { diff --git a/crates/origin-shared/src/object/acceptance.rs b/crates/origin-shared/src/object/acceptance.rs index ecc82997..2db1d5cd 100644 --- a/crates/origin-shared/src/object/acceptance.rs +++ b/crates/origin-shared/src/object/acceptance.rs @@ -11,7 +11,7 @@ pub use ed25519_dalek::Signature; /// One landing on a target, signed by the target's authority. /// -/// Acceptances form a hash chain per target: each names the one before it, +/// A target's acceptances form a hash chain: each names the one before it, /// and its sequence number is its position in the target's log. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Acceptance { @@ -26,7 +26,7 @@ impl Record for Acceptance { } impl Acceptance { - /// What landed, and where. + /// The body: what landed, and where. #[must_use] pub fn body(&self) -> &AcceptanceBody { &self.body @@ -64,11 +64,10 @@ pub struct AcceptanceBody { pub state: TreeId, /// What landed. pub landed: Vec, - /// The statements the policy relied on. + /// The statements the policy relied on to accept the landing. pub evidence: Vec, /// The acceptance of the `policy` target in force when this one landed. - /// Absent only for the first acceptance of `policy`, which nothing - /// precedes. + /// Absent only for the first acceptance of `policy` itself. pub policy: Option, } @@ -83,7 +82,7 @@ fields!(AcceptanceBody { }); impl AcceptanceBody { - /// Signs the body as `authority`. + /// Signs the body as `authority`, returning the acceptance. #[must_use] pub fn sign(self, authority: &NodeKey) -> Acceptance { let signature = authority.0.sign(&self.signed_bytes()); @@ -93,9 +92,9 @@ impl AcceptanceBody { } } - /// The bytes signed: the acceptance's encoding without its signature, - /// which starts with the object kind, so the signature can't be passed - /// off as one of anything else. + /// The bytes the authority signs: the acceptance's encoding without the + /// signature. They start with the object kind, so the signature can't be + /// reused for an object of another kind. fn signed_bytes(&self) -> Vec { let mut bytes = vec![ObjectKind::Acceptance as u8]; self.write(&mut bytes); @@ -127,8 +126,8 @@ impl Field for Signature { } } -/// A node's ed25519 key pair. As a target's authority, the node signs the -/// acceptances it writes. +/// A node's ed25519 key pair. A node signs the acceptances of the targets +/// it is the authority of. pub struct NodeKey(SigningKey); impl NodeKey { @@ -149,20 +148,20 @@ impl NodeKey { Self(SigningKey::from_bytes(secret)) } - /// The secret key, to keep the key pair somewhere safe. + /// The secret key, for storing the key pair. #[must_use] pub fn to_bytes(&self) -> [u8; ed25519_dalek::SECRET_KEY_LENGTH] { self.0.to_bytes() } - /// The public half, which verifies the node's signatures. + /// The public key, which verifies the node's signatures. #[must_use] pub fn public(&self) -> NodePublicKey { NodePublicKey(self.0.verifying_key()) } } -/// Never prints the secret key. +/// Prints only the public key, never the secret key. impl fmt::Debug for NodeKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("NodeKey").field(&self.public()).finish() @@ -194,7 +193,7 @@ impl FromStr for NodePublicKey { } } -/// A signature that the claimed signer did not make. +/// A signature the claimed signer did not make. #[derive(Debug, thiserror::Error)] #[error("the signature does not match the signer's key")] pub struct BadSignature(#[source] ed25519_dalek::SignatureError); diff --git a/crates/origin-shared/src/object/encoding.rs b/crates/origin-shared/src/object/encoding.rs index 5020157d..fd25f597 100644 --- a/crates/origin-shared/src/object/encoding.rs +++ b/crates/origin-shared/src/object/encoding.rs @@ -1,17 +1,17 @@ -//! The building blocks of record encodings. Every field has exactly one -//! encoding, so a record has exactly one too. +//! The building blocks of record encodings. Each field type has exactly +//! one encoding, so each record has exactly one too. use super::DecodeError; /// A value with a canonical, self-delimiting binary encoding. /// -/// Public only so the crate's public traits can require it: it isn't -/// reachable from outside the crate, which keeps encodings internal. +/// The trait is public only so the crate's public traits can require it. +/// Code outside the crate can't reach it, so encodings stay internal. pub trait Field: Sized { /// Appends the encoding to `out`. fn write(&self, out: &mut Vec); - /// Decodes a value, rejecting any encoding [`Field::write`] wouldn't + /// Decodes a value. Rejects any encoding that [`Field::write`] would not /// produce. /// /// # Errors @@ -70,7 +70,7 @@ macro_rules! tagged { pub(crate) use {fields, tagged}; -/// Little endian. +/// Encoded as 8 bytes, little endian. impl Field for u64 { fn write(&self, out: &mut Vec) { out.extend_from_slice(&self.to_le_bytes()); @@ -81,7 +81,7 @@ impl Field for u64 { } } -/// One byte, 0 or 1. +/// Encoded as one byte, 0 or 1. impl Field for bool { fn write(&self, out: &mut Vec) { out.push(u8::from(*self)); @@ -96,7 +96,7 @@ impl Field for bool { } } -/// A `u32` count, then the items. +/// Encoded as a `u32` count, then the items. impl Field for Vec { fn write(&self, out: &mut Vec) { Reader::write_len(self.len(), out); @@ -117,7 +117,7 @@ impl Field for Vec { } } -/// A 0 byte for `None`, or a 1 byte and the value. +/// Encoded as a 0 byte for `None`, or a 1 byte and the value. impl Field for Option { fn write(&self, out: &mut Vec) { match self { @@ -134,11 +134,11 @@ impl Field for Option { } } -/// A cursor over an encoding that fails with [`DecodeError::Truncated`] -/// instead of panicking. +/// A cursor over an encoding. Reading past the end fails with +/// [`DecodeError::Truncated`] instead of panicking. /// -/// Records are read with it, and other crates read their own binary formats -/// with it too, in the same conventions: integers are little endian, and +/// Records are read with it. Other crates read their own binary formats +/// with it too, with the same conventions: integers are little endian and /// lengths are `u32`s. #[derive(Debug)] pub struct Reader<'a>(&'a [u8]); @@ -150,20 +150,20 @@ impl<'a> Reader<'a> { Self(bytes) } - /// Writes a length as a `u32`. Nothing in a record comes close to - /// 4 GiB. + /// Writes a length as a little-endian `u32`. Panics past 4 GiB, which + /// nothing in a record comes close to. pub(crate) fn write_len(len: usize, out: &mut Vec) { let len = u32::try_from(len).expect("record field longer than 4 GiB"); out.extend_from_slice(&len.to_le_bytes()); } - /// Writes a string as its [`Reader::write_len`] length and its bytes. + /// Writes a string as a `u32` length and its bytes. pub(crate) fn write_str(string: &str, out: &mut Vec) { Self::write_len(string.len(), out); out.extend_from_slice(string.as_bytes()); } - /// Reads a length: a `u32`. + /// Reads a length, encoded as a `u32`. /// /// # Errors /// @@ -211,7 +211,7 @@ impl<'a> Reader<'a> { self.array().map(u64::from_le_bytes) } - /// Reads bytes preceded by their [`Reader::read_len`] length. + /// Reads bytes preceded by their `u32` length. /// /// # Errors /// @@ -221,11 +221,12 @@ impl<'a> Reader<'a> { self.take(len) } - /// Reads a 0 byte for `None`, or a 1 byte and the value `read` reads. + /// Reads an option: a 0 byte for `None`, or a 1 byte and the value that + /// `read` reads. /// /// # Errors /// - /// Fails if the tag is neither, or `read` fails. + /// Fails if the tag byte is neither 0 nor 1, or if `read` fails. pub fn option( &mut self, read: impl FnOnce(&mut Self) -> Result, @@ -251,8 +252,7 @@ impl<'a> Reader<'a> { Ok(name) } - /// Reads a string: UTF-8 bytes preceded by their [`Reader::read_len`] - /// length. + /// Reads a string: UTF-8 bytes preceded by their `u32` length. /// /// # Errors /// @@ -272,7 +272,7 @@ impl<'a> Reader<'a> { self.0.len() } - /// Ends reading, checking nothing is left. + /// Ends reading and checks that no bytes are left. /// /// # Errors /// diff --git a/crates/origin-shared/src/object/errors.rs b/crates/origin-shared/src/object/errors.rs index 94fbf3b8..857cb988 100644 --- a/crates/origin-shared/src/object/errors.rs +++ b/crates/origin-shared/src/object/errors.rs @@ -11,7 +11,7 @@ pub struct IdMismatch { pub actual: ObjectId, } -/// Bytes that are not a canonical encoding: of an object, or of anything +/// Bytes that are not a canonical encoding of an object, or of anything /// else read with a [`Reader`](super::Reader). #[derive(Debug, PartialEq, Eq, thiserror::Error)] pub enum DecodeError { @@ -32,7 +32,8 @@ pub enum DecodeError { /// The kind of the object. actual: ObjectKind, }, - /// A tag byte (an enum variant, an option or a boolean) has no meaning. + /// A tag byte (of an enum variant, an option or a boolean) has no + /// meaning. #[error("unknown {field} tag {tag}")] UnknownTag { /// What the tag encodes. @@ -43,7 +44,8 @@ pub enum DecodeError { /// A name is invalid. #[error(transparent)] InvalidName(#[from] InvalidName), - /// A value is valid but not in the one form its type encodes it in. + /// A value is valid but not in its canonical form. Holds what the value + /// is, such as "path". #[error("{0} is not in canonical form")] NonCanonical(&'static str), /// Tree entries are not strictly sorted by name. diff --git a/crates/origin-shared/src/object/mod.rs b/crates/origin-shared/src/object/mod.rs index 4567e347..f4ee7843 100644 --- a/crates/origin-shared/src/object/mod.rs +++ b/crates/origin-shared/src/object/mod.rs @@ -2,9 +2,9 @@ //! canonical encoding. //! //! Every object has exactly one encoding, and its id is the BLAKE3 hash of -//! that encoding. The first byte is the [`ObjectKind`], which gives each kind -//! its own hash domain: objects of different kinds never share an id, and a -//! record of one kind can never be mistaken for another. +//! that encoding. The first byte is the [`ObjectKind`], so objects of +//! different kinds never share an id, and a record of one kind is never +//! read as another. After that byte: //! //! - Blob: the content, as is. //! - Tree: its entries, see [`Tree`]. @@ -77,9 +77,9 @@ impl fmt::Display for ObjectKind { } } -/// An object with structure: every kind but blobs. +/// An object with structured fields: every kind but blobs. pub trait Record: Field { - /// The kind every encoding of this record starts with. + /// The kind byte every encoding of this record starts with. const KIND: ObjectKind; /// Encodes and hashes the record. @@ -147,8 +147,9 @@ object!(Tree, Revision, Statement, Acceptance); /// An object's encoding together with its id. /// -/// The id is always the hash of the bytes: constructors either hash the bytes -/// or verify a claimed id, so holding an `EncodedObject` proves integrity. +/// The id is always the hash of the bytes: every constructor either hashes +/// the bytes or checks a claimed id. Holding an `EncodedObject` proves the +/// bytes are intact. #[derive(Clone, PartialEq, Eq)] pub struct EncodedObject { id: ObjectId, @@ -163,8 +164,8 @@ impl EncodedObject { } } - /// Encodes a blob, reading its content to the end. `len_hint` sizes the - /// buffer up front, so passing the file size avoids reallocating. + /// Encodes a blob by reading its content to the end. `len_hint` sizes the + /// buffer up front: pass the file size to avoid reallocating. /// /// # Errors /// @@ -185,8 +186,8 @@ impl EncodedObject { Self::hash(bytes) } - /// Accepts bytes claimed to encode the object `id`, such as bytes read - /// from disk or the network. + /// Wraps bytes that should encode the object `id`, such as bytes read + /// from disk or the network, after checking that they hash to `id`. /// /// # Errors /// @@ -234,7 +235,7 @@ impl EncodedObject { Ok(&self.bytes[1..]) } - /// Decodes the object as a `R`. + /// Decodes the object as an `R`. /// /// # Errors /// @@ -327,7 +328,7 @@ pub(crate) mod tests { } } - /// A key that signs the same way in every run. + /// A fixed key, so its signatures are the same in every run. pub(crate) fn sample_key() -> NodeKey { NodeKey::from_bytes(&[42; 32]) } @@ -371,8 +372,9 @@ pub(crate) mod tests { } } - /// Ids are the storage and wire format: changing the encoding changes - /// every id, so it must never happen by accident. + /// Checks that the encoding hasn't changed. Ids are the storage and wire + /// format, so changing the encoding changes every id: it must never happen + /// by accident. #[test] fn encoding_is_stable() { let ids = samples().map(|object| object.encode().id().short()); diff --git a/crates/origin-shared/src/object/revision.rs b/crates/origin-shared/src/object/revision.rs index bd97abe0..a38210c1 100644 --- a/crates/origin-shared/src/object/revision.rs +++ b/crates/origin-shared/src/object/revision.rs @@ -3,24 +3,24 @@ use crate::{AcceptanceId, BlobId, ChangeId, Principal, RevisionId, TreeId}; /// One immutable version of a change. /// -/// Editing, rebasing or handing a change to someone else creates a new -/// revision of the same change, whose predecessors are the revisions it -/// evolves from. +/// Editing, rebasing or handing over a change creates a new revision of the +/// same change. Its predecessors are the revisions it evolves from. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Revision { /// The change this is a version of. pub change: ChangeId, - /// The revisions this one evolves from. Two make it a convergence of - /// divergent heads. + /// The revisions this one evolves from. A revision with two of them + /// converges divergent heads. pub predecessors: Vec, /// What the revision was made on top of. pub base: Base, - /// The exact revisions this one requires: the changes below it in a - /// stack. + /// The exact revisions this one requires, such as the changes below it + /// in a stack. pub deps: Vec, - /// The root tree of the files. + /// The root tree of the revision's files. pub snapshot: TreeId, - /// The intent, written for humans and agents. + /// The blob holding the change's description, written for humans and + /// agents. pub description: BlobId, /// Who wrote the revision. pub author: Principal, diff --git a/crates/origin-shared/src/object/statement.rs b/crates/origin-shared/src/object/statement.rs index aa171e9c..ccce673f 100644 --- a/crates/origin-shared/src/object/statement.rs +++ b/crates/origin-shared/src/object/statement.rs @@ -10,32 +10,33 @@ use crate::{ TreeEntry, TreeId, }; -/// An attributable claim about another record: a check result, a review, a -/// conflict, an abandonment. +/// A claim about another record, made by its issuer: a check result, a +/// review, a conflict, an abandonment. /// -/// Statements are permanent. An issuer revises one by issuing another that -/// supersedes it. A promoted statement carries another one over to a record -/// with the same input digest, pointing at it instead of copying its issuer. +/// Statements never change. An issuer revises one by issuing a new one that +/// supersedes it. A promotion copies a statement's claim to another record +/// with the same input digest, and points at the original through +/// `promoted_from`. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Statement { /// The record the claim is about. pub subject: RecordId, /// What kind of claim it is. pub kind: Kind, - /// The outcome, the only field core interprets. + /// The outcome. It is the only field origin itself interprets. pub verdict: Option, /// Who makes the claim. pub issuer: Principal, - /// What the claim depended on, which lets it be promoted to revisions - /// with the same inputs. + /// What the claim depended on. Statements with inputs can be promoted to + /// revisions with the same input digest. pub inputs: Option, /// Free-form details, defined by whoever owns the kind. pub payload: Option, /// A statement from the same issuer that this one replaces. pub supersedes: Option, - /// The statement this one promotes: its kind, verdict, inputs and - /// payload hold here too, because the input digests are equal. The - /// issuer is whoever promoted it, the original's stays on the original. + /// The statement this one promotes. Its kind, verdict, inputs and + /// payload also hold here, because the input digests are equal. The issuer + /// is whoever promoted it; the original keeps its own issuer. pub promoted_from: Option, } @@ -55,13 +56,15 @@ impl Record for Statement { } impl Statement { - /// Given the claims about one record that nothing superseded, drops - /// each promotion whose original's kind and issuer the record also has - /// a statement of that isn't a promotion, a result or a withdrawal, - /// whichever came first: a result that ran there wins. `pair` gives a - /// claim's statement, and the one whose claim it makes: itself, or a - /// promotion's original. A superseded statement must not be among - /// `claims`, or it would drop a promotion that still holds. + /// Removes the promotions that a direct statement replaces. `claims` are + /// the unsuperseded statements about one record. Each promotion is removed + /// if `claims` also holds a statement that isn't a promotion (a result or a + /// withdrawal) with the kind and issuer of the promotion's original: a + /// result that ran on the record wins over one promoted to it. + /// + /// `pair` returns a claim's statement and the statement whose claim it + /// makes: itself, or a promotion's original. `claims` must not hold a + /// superseded statement, or a promotion that still holds could be removed. pub fn drop_replaced_promotions( claims: &mut Vec, pair: impl Fn(&T) -> (&Statement, &Statement), @@ -79,24 +82,27 @@ impl Statement { }); } - /// The BLAKE3 key derivation context of promotion groups. + /// The BLAKE3 key derivation context for promotion groups. const GROUP_CONTEXT: &str = "origin 2026-10 promotion group"; - /// Whether the statement takes back the one it supersedes, claiming - /// nothing instead: it has no verdict, and its kind isn't a reserved - /// one, whose statements have none. + /// Whether the statement withdraws the one it supersedes, claiming + /// nothing instead: it supersedes a statement and has no verdict. A + /// statement of a reserved kind is never a withdrawal, since those have no + /// verdict anyway. #[must_use] pub fn withdraws(&self) -> bool { self.verdict.is_none() && self.supersedes.is_some() && !self.kind.is_reserved() } - /// Whether the statement can be promoted to other records: it declares - /// inputs and depends on nothing outside them, its subject has a - /// snapshot to take the input digest of (it isn't a statement), it - /// isn't itself a promotion, whose original is promoted instead, nor a - /// withdrawal, which claims nothing, and its kind isn't reserved: - /// abandonments, conflicts and divergence are about one revision, - /// whatever its inputs. + /// Whether the statement can be promoted to other records. It must: + /// + /// - declare inputs that aren't `external`; + /// - not be about a statement, which has no snapshot to take the input + /// digest of; + /// - not be a promotion (its original is promoted instead) or a withdrawal + /// (it claims nothing); + /// - not have a reserved kind: abandonments, conflicts and divergence are + /// about one revision, whatever its inputs. #[must_use] pub fn is_promotable(&self) -> bool { self.promoted_from.is_none() @@ -106,11 +112,12 @@ impl Statement { && self.inputs.as_ref().is_some_and(|inputs| !inputs.external) } - /// Identifies the statements this one is interchangeable with when - /// promoting, if it's promotable: those of its kind, from its issuer, - /// declaring the same inputs. A record needs only one result of a - /// group. It hashes the [`Inputs::spec`], then the kind and the issuer - /// as they're encoded. + /// The digest of the group of statements this one is interchangeable + /// with when promoting: those of its kind, from its issuer, declaring the + /// same inputs. A record needs only one result per group. Returns `None` if + /// the statement isn't promotable. + /// + /// It hashes the [`Inputs::spec`], then the encoded kind and issuer. #[must_use] pub fn promotion_group(&self) -> Option { let inputs = self.inputs.as_ref().filter(|_| self.is_promotable())?; @@ -138,7 +145,8 @@ pub enum RecordId { } impl RecordId { - /// The record, by kind and short id, for humans: `revision 3f1c9a2e07b4`. + /// Describes the record for humans by kind and short id, such as + /// `revision 3f1c9a2e07b4`. #[must_use] pub fn describe(&self) -> String { let (kind, id) = match self { @@ -160,21 +168,23 @@ tagged!(RecordId { }); names! { - /// The kind of a statement, namespaced by its owner: `ci.test`, - /// `review`, `core.conflict`. Dot-separated segments of lowercase ASCII + /// The kind of a statement, namespaced by its owner, such as `ci.test`, + /// `review` or `core.conflict`: dot-separated segments of lowercase ASCII /// letters, digits, `_` and `-`. Kind("statement kind"); } impl Kind { - /// The author gave the change up. The payload says why. + /// The author gave up the change. The payload says why. pub const ABANDON: Self = Self(Cow::Borrowed("core.abandon")); - /// A landing could not rebase. The payload lists the conflicting paths. + /// A landing could not rebase the change. The payload lists the + /// conflicting paths. pub const CONFLICT: Self = Self(Cow::Borrowed("core.conflict")); /// The change has more than one head. pub const DIVERGENT: Self = Self(Cow::Borrowed("core.divergent")); - /// Whether the kind is reserved for origin itself: `core.` and below. + /// Whether the kind is reserved for origin itself: it starts with + /// `core.`. #[must_use] pub fn is_reserved(&self) -> bool { self.0.starts_with("core.") @@ -249,19 +259,21 @@ impl Field for Verdict { /// What a statement depended on. /// -/// The input digest of a snapshot hashes the ids it stores at `paths`, with -/// `definition` and `toolchain`. A statement that declares inputs and isn't -/// `external` is promoted to every revision with the same input digest. +/// The input digest of a snapshot hashes what the snapshot stores at +/// `paths`, along with `definition` and `toolchain`. A statement that +/// declares inputs and isn't `external` is promoted to every revision with +/// the same input digest. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Inputs { - /// The files and directories read, each covering everything under it. + /// The files and directories read. Each covers everything under it. pub paths: Vec, - /// The check's command and configuration. + /// The hash of the check's command and configuration. pub definition: Digest, - /// The tools that ran it, such as the hash of `rustc -V`. + /// The hash of the tools that ran the check, such as the output of + /// `rustc -V`. pub toolchain: Digest, - /// Whether the claim also depended on things outside the snapshot, such - /// as the network, which makes it never promotable. + /// Whether the claim also depended on something outside the snapshot, + /// such as the network. Such a statement is never promoted. pub external: bool, } @@ -273,13 +285,13 @@ fields!(Inputs { }); impl Inputs { - /// The BLAKE3 key derivation contexts, which keep these hashes apart - /// from every other. + /// The BLAKE3 key derivation contexts of the spec and the digest, which + /// keep these hashes apart from every other. const SPEC_CONTEXT: &str = "origin 2026-10 input spec"; const DIGEST_CONTEXT: &str = "origin 2026-10 input digest"; - /// The paths, sorted and without duplicates: the order they're declared - /// in doesn't matter. + /// The paths, sorted and without duplicates, so the order they are + /// declared in doesn't matter. fn sorted_paths(&self) -> Vec<&RepoPath> { let mut paths: Vec<_> = self.paths.iter().collect(); paths.sort_unstable(); @@ -287,10 +299,10 @@ impl Inputs { paths } - /// Identifies what the inputs declare: equal for statements reading the - /// same paths with the same definition and toolchain, whatever their - /// order. It hashes the definition, the toolchain, and each path's - /// `u32` length and bytes. + /// Hashes what the inputs declare. Statements reading the same paths, in + /// any order, with the same definition and toolchain have the same spec. + /// It hashes the definition, the toolchain, and each path as a `u32` length + /// and its bytes. #[must_use] pub fn spec(&self) -> Digest { let mut hasher = blake3::Hasher::new_derive_key(Self::SPEC_CONTEXT); @@ -305,16 +317,16 @@ impl Inputs { } /// The input digest of a snapshot: the [`Inputs::spec`], then for each - /// path, in its order, a 0 byte if the snapshot has nothing there, or a - /// 1 byte, the entry's kind and its id. `entry_at` looks up what the - /// snapshot stores at a path; at the root, that's the snapshot's tree. + /// path, sorted, a 0 byte if the snapshot has nothing there, or a 1 byte, + /// the entry's kind and its id. `entry_at` returns what the snapshot holds + /// at a path; at the root, that is the snapshot's tree. /// - /// Records with equal digests agree on everything the inputs cover, so - /// a promotable statement about one holds for the other. + /// Records with equal digests agree on everything the inputs cover, so a + /// promotable statement about one holds for the other. /// /// # Errors /// - /// Fails if `entry_at` does. + /// Fails if `entry_at` fails. pub fn digest( &self, mut entry_at: impl FnMut(&RepoPath) -> Result, E>, diff --git a/crates/origin-shared/src/object/tree.rs b/crates/origin-shared/src/object/tree.rs index 5a1ea5f6..1ce1a825 100644 --- a/crates/origin-shared/src/object/tree.rs +++ b/crates/origin-shared/src/object/tree.rs @@ -8,9 +8,9 @@ use crate::{ObjectId, TreeId}; names! { /// The name of an entry in a tree: one path component. It isn't empty, - /// `.` or `..`, and contains no `/` or NUL byte. The names of repository + /// `.` or `..`, and contains no `/` or NUL byte. Names of repository /// metadata directories are reserved, compared case-insensitively so they - /// cannot be smuggled in on case-insensitive file systems. + /// can't slip in on case-insensitive file systems. EntryName("file name"); } @@ -25,8 +25,8 @@ impl EntryName { && !Self::is_reserved(name) } - /// Whether a name belongs to repository metadata, which working copies - /// skip and trees cannot contain. + /// Whether a name is reserved for repository metadata. Working copies + /// skip such names, and trees cannot contain them. #[must_use] pub fn is_reserved(name: &str) -> bool { Self::RESERVED @@ -50,7 +50,7 @@ pub enum EntryKind { } impl EntryKind { - /// The kind a tag byte encodes, as in tree encodings. + /// Returns the kind a tag byte encodes in a tree. /// /// # Errors /// @@ -112,7 +112,7 @@ impl TreeEntry { /// A directory listing, sorted by name. /// /// Encoded as its entries in order, each `kind:u8 name 0x00 id:[u8; 32]`, -/// up to the end of the object: a tree is never a field of another record. +/// up to the end of the object. A tree is never a field of another record. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Tree { entries: BTreeMap, diff --git a/crates/origin-shared/src/path.rs b/crates/origin-shared/src/path.rs index 454b0b2a..3ccc29ae 100644 --- a/crates/origin-shared/src/path.rs +++ b/crates/origin-shared/src/path.rs @@ -20,7 +20,7 @@ impl RepoPath { Self(String::new()) } - /// Validates a `/`-separated path. Leading and trailing slashes are + /// Parses a `/`-separated path. Leading and trailing slashes are /// ignored, so `/src/` is `src`. /// /// # Errors @@ -85,8 +85,8 @@ impl FromStr for RepoPath { } } -/// Encoded as a name. Only the normalized form decodes, so each path has one -/// encoding. +/// Encoded as a name. Only the normalized form decodes, so each path has +/// one encoding. impl Field for RepoPath { fn write(&self, out: &mut Vec) { Reader::write_str(&self.0, out); diff --git a/crates/origin-shared/src/principal.rs b/crates/origin-shared/src/principal.rs index 7643ab39..7706b785 100644 --- a/crates/origin-shared/src/principal.rs +++ b/crates/origin-shared/src/principal.rs @@ -1,4 +1,4 @@ -//! Who wrote a record. +//! Principals: who wrote a record. use std::fmt; use std::str::FromStr; @@ -36,7 +36,7 @@ pub enum Principal { tagged!(Principal { User = 1, Node = 2 }); impl Principal { - /// The prefix written before the name. + /// The prefix written before the name: `user` or `node`. fn prefix(&self) -> &'static str { match self { Self::User(_) => "user", diff --git a/crates/origin-shared/src/target.rs b/crates/origin-shared/src/target.rs index 3b444e97..b8e0c1ca 100644 --- a/crates/origin-shared/src/target.rs +++ b/crates/origin-shared/src/target.rs @@ -7,12 +7,12 @@ use crate::name::names; names! { /// The name of a target, such as `main` or `release/v3`: `/`-separated - /// segments of ASCII letters, digits, `.`, `_` and `-`. No segment is - /// empty or starts with `.`, which keeps names unambiguous in URLs and - /// on the command line. + /// segments of ASCII letters, digits, `.`, `_` and `-`. No segment is empty + /// or starts with `.`, so names stay unambiguous in URLs and on the command + /// line. /// - /// Names never become file names: a target is stored under its - /// [`TargetId`]. + /// A target is stored under its [`TargetId`], so names never become file + /// names. TargetName("target name"); }