diff --git a/apps/origin-src/benches/land.rs b/apps/origin-src/benches/land.rs index 33af14c9..1b1c51e9 100644 --- a/apps/origin-src/benches/land.rs +++ b/apps/origin-src/benches/land.rs @@ -93,7 +93,7 @@ impl Repo { author: "user:bench".parse().unwrap(), } .encode(); - let description = EncodedObject::blob(b""); + let description = EncodedObject::attachment(b""); self.store.write_all(&[content, tree, description]).unwrap(); self.store.write_all(&[revision]).unwrap(); change diff --git a/apps/origin-src/benches/server.rs b/apps/origin-src/benches/server.rs index 80568719..910b4e8c 100644 --- a/apps/origin-src/benches/server.rs +++ b/apps/origin-src/benches/server.rs @@ -15,8 +15,8 @@ use origin_shared::api::{EventsQuery, FetchRecords, LandRequest, List}; use origin_shared::landing::{Landing, Proposal}; use origin_shared::pack::Pack; use origin_shared::{ - Base, BlobId, ChangeId, EncodedObject, EntryKind, EntryName, Kind, NodeKey, Period, Record, - RecordId, Revision, RevisionId, Statement, TargetName, Tree, TreeEntry, Verdict, + AttachmentId, Base, ChangeId, EncodedObject, EntryKind, EntryName, Kind, NodeKey, Period, + Record, RecordId, Revision, RevisionId, Statement, TargetName, Tree, TreeEntry, Verdict, }; use origin_src::http::Api; use origin_src::policy::Policy; @@ -72,7 +72,7 @@ impl Hosted { }, ); let tree = tree.encode(); - let description = EncodedObject::blob(b""); + let description = EncodedObject::attachment(b""); let mut change = [0; 16]; change[..8].copy_from_slice(&n.to_le_bytes()); let revision = Revision { @@ -81,7 +81,7 @@ impl Hosted { base: Base::Acceptance(tip), deps: Vec::new(), snapshot: tree.id().into(), - description: BlobId::from(description.id()), + description: AttachmentId::from(description.id()), author: "user:bench".parse().unwrap(), } .encode(); diff --git a/apps/origin-src/benches/sync.rs b/apps/origin-src/benches/sync.rs index f3a33fd8..7438d0e7 100644 --- a/apps/origin-src/benches/sync.rs +++ b/apps/origin-src/benches/sync.rs @@ -151,7 +151,7 @@ fn land(service: &OriginService, snapshot: TreeId) -> Base { /// A revision of a new change with `snapshot`, on `base`, and its /// description. fn revision(base: Base, snapshot: TreeId) -> (EncodedObject, EncodedObject) { - let description = EncodedObject::blob(b"bench"); + let description = EncodedObject::attachment(b"bench"); let revision = Revision { change: ChangeId::random().unwrap(), predecessors: Vec::new(), @@ -250,7 +250,7 @@ static HISTORY_SETUP: LazyLock = LazyLock::new(|| { let service = OriginService::create(server.path().join("demo"), node.clone(), &policy).unwrap(); let tip = service.store().head(&TargetName::MAIN).unwrap().unwrap(); let state = service.store().get(tip.acceptance).unwrap().body().state; - let description = EncodedObject::blob(b"bench"); + let description = EncodedObject::attachment(b"bench"); let mut objects = vec![description.clone()]; let mut changes = Vec::new(); for change in 0..HISTORY { diff --git a/apps/origin-src/src/annotations/mod.rs b/apps/origin-src/src/annotations/mod.rs index 73cbe22b..4031c1ca 100644 --- a/apps/origin-src/src/annotations/mod.rs +++ b/apps/origin-src/src/annotations/mod.rs @@ -267,7 +267,7 @@ impl<'a, P: Platform> Annotations<'a, P> { .iter() .map(|head| head.to_hex() + "\n") .collect::(); - let payload = EncodedObject::blob(list.as_bytes()); + let payload = EncodedObject::attachment(list.as_bytes()); let statement = Statement { subject: RecordId::Revision(heads[0]), kind: Kind::DIVERGENT, @@ -388,7 +388,7 @@ mod tests { use std::thread; use origin_shared::{ - Base, BlobId, Digest, Inputs, ObjectId, RepoPath, Revision, RevisionId, Verdict, + AttachmentId, Base, Digest, Inputs, ObjectId, RepoPath, Revision, RevisionId, Verdict, }; use super::*; @@ -419,7 +419,7 @@ mod tests { base: Base::Acceptance(ObjectId::from_bytes([0; 32]).into()), deps: Vec::new(), snapshot: build(store, files), - description: BlobId::from(EncodedObject::blob(b"").id()), + description: AttachmentId::from(EncodedObject::attachment(b"").id()), author: principal("user:alice"), } .encode(); @@ -596,7 +596,7 @@ mod tests { assert_eq!(about.len(), 1); assert_eq!(about[0].statement.kind, Kind::DIVERGENT); let heads = store - .try_blob(about[0].statement.payload.unwrap().into()) + .try_attachment(about[0].statement.payload.unwrap()) .unwrap() .unwrap(); let mut expected = [left, right]; diff --git a/apps/origin-src/src/annotations/retention.rs b/apps/origin-src/src/annotations/retention.rs index cccfd31c..e19c3762 100644 --- a/apps/origin-src/src/annotations/retention.rs +++ b/apps/origin-src/src/annotations/retention.rs @@ -23,12 +23,14 @@ pub struct Dropped { impl Annotations<'_, P> { /// Deletes the payloads whose retention ended by `now`, counted from /// when this node stored their statement. A payload stays while any - /// statement still keeps it, or a revision or a tree refers to the same - /// blob, such as an empty file and an empty payload. Statements stay. - /// It waits for the writers [holding objects](crate::store::Store::hold_objects), - /// which landings on `policy` are too, then reads the rules from - /// `retention` and the index again, so a writer never refers to a - /// payload deleted under it, and a policy landed meanwhile applies. + /// statement still keeps it, or a revision's description is the same + /// attachment, such as an empty description and an empty payload. + /// Attachments never share an id with a file, so no snapshot is read. + /// Statements stay. It waits for the writers [holding + /// objects](crate::store::Store::hold_objects), which landings on + /// `policy` are too, then reads the rules from `retention` and the + /// index again, so a writer never refers to a payload deleted under it, + /// and a policy landed meanwhile applies. /// Without rules, it neither waits nor reads anything: a policy landed /// meanwhile could only have dropped payloads that this run keeps. /// @@ -52,20 +54,13 @@ impl Annotations<'_, P> { self.index = Index::open(self.store)?; let mut expired = HashSet::new(); let mut live: HashSet = HashSet::new(); - let mut roots = Vec::new(); for &record in self.index.arrivals() { match record { RecordId::Revision(id) => { - let revision = self.store.get(id)?; - roots.push(revision.snapshot); - live.insert(revision.description.into()); + live.insert(self.store.get(id)?.description.into()); } - RecordId::Acceptance(id) => roots.push(self.store.get(id)?.body().state), RecordId::Statement(id) => { let statement = self.store.get(id)?; - if let RecordId::Snapshot(tree) = statement.subject { - roots.push(tree); - } let Some(payload) = statement.payload else { continue; }; @@ -82,13 +77,9 @@ impl Annotations<'_, P> { live.insert(payload.into()); } } - RecordId::Snapshot(_) => {} + RecordId::Acceptance(_) | RecordId::Snapshot(_) => {} } } - if expired.is_empty() { - return Ok(Dropped::default()); - } - self.store.reach(roots, &mut live)?; let mut doomed = Vec::new(); for &id in expired.difference(&live) { if self.store.contains(id)? { @@ -108,7 +99,7 @@ mod tests { use std::time::Duration; use origin_platform::Native; - use origin_shared::{EncodedObject, Verdict}; + use origin_shared::{EncodedObject, Record, Revision, Verdict}; use super::*; use crate::annotations::tests::{FILES, check, issue, revision, store}; @@ -119,7 +110,7 @@ mod tests { let (_dir, store) = store(); let first = revision(&store, 1, &[], &[("empty", "")]); let with_payload = |kind: &str, payload: &[u8]| { - let payload = EncodedObject::blob(payload); + let payload = EncodedObject::attachment(payload); let mut statement = check(first, kind, Verdict::Pass, "node:ci", None); statement.payload = Some(payload.id().into()); let annotations = Annotations::open(&store).unwrap(); @@ -129,7 +120,7 @@ mod tests { (id, payload.id()) }; let (log_statement, log) = with_payload("ci.test", b"a long log"); - // The same blob as the empty file, which must stay. + // The same attachment as the empty description, which must stay. let (_, empty) = with_payload("ci.lint", b""); let (_, review) = with_payload("review", b"looks good"); let (_, shared) = with_payload("ci.bench", b"shared"); @@ -188,7 +179,7 @@ mod tests { fn collection_waits_for_writers_holding_objects() { let (_dir, store) = store(); let first = revision(&store, 1, &[], FILES); - let payload = EncodedObject::blob(b"a log, and a file"); + let payload = EncodedObject::attachment(b"a log, and a description"); let mut statement = check(first, "ci.test", Verdict::Pass, "node:ci", None); statement.payload = Some(payload.id().into()); Annotations::open(&store) @@ -199,8 +190,9 @@ mod tests { .unwrap() .retention; - // A writer finds the expired payload stored as a file it snapshots, - // so it doesn't write it, then writes the revision referring to it. + // A writer finds the expired payload stored as the description it + // writes, so it doesn't write it, then writes the revision referring + // to it. let held = store.hold_objects().unwrap(); assert_eq!(store.write_all(std::slice::from_ref(&payload)).unwrap(), 0); let (done, collected) = std::sync::mpsc::channel(); @@ -215,7 +207,11 @@ mod tests { }); thread::sleep(Duration::from_millis(100)); assert!(collected.try_recv().is_err(), "collection waits"); - revision(&store, 2, &[], &[("log", "a log, and a file")]); + let reusing = Revision { + description: payload.id().into(), + ..store.get(first).unwrap() + }; + store.write_all(&[reusing.encode()]).unwrap(); drop(held); assert_eq!(collected.recv().unwrap(), Dropped::default()); }); @@ -226,7 +222,7 @@ mod tests { fn promotions_and_collection_exclude_each_other() { let (_dir, store) = store(); let first = revision(&store, 1, &[], FILES); - let payload = EncodedObject::blob(b"a log to promote"); + let payload = EncodedObject::attachment(b"a log to promote"); let inputs = Some((&["src"][..], false)); let mut result = check(first, "ci.test", Verdict::Pass, "node:ci", inputs); result.payload = Some(payload.id().into()); diff --git a/apps/origin-src/src/conflict.rs b/apps/origin-src/src/conflict.rs index f07fbc14..817a6f2b 100644 --- a/apps/origin-src/src/conflict.rs +++ b/apps/origin-src/src/conflict.rs @@ -163,7 +163,7 @@ impl Conflicts { list.push_str(conflicted.path.as_str()); list.push('\0'); } - let payload = EncodedObject::blob(list.as_bytes()); + let payload = EncodedObject::attachment(list.as_bytes()); let statement = Statement { subject, kind: Kind::CONFLICT, @@ -192,7 +192,7 @@ impl Conflicts { return Ok(Self::default()); }; let content = store - .try_blob(payload.into())? + .try_attachment(payload)? .ok_or(StoreError::NotFound(payload.into()))?; let conflicted = String::from_utf8_lossy(&content) .split_terminator('\0') diff --git a/apps/origin-src/src/events.rs b/apps/origin-src/src/events.rs index f5d51c9f..beabb9f4 100644 --- a/apps/origin-src/src/events.rs +++ b/apps/origin-src/src/events.rs @@ -263,7 +263,10 @@ impl<'a, P: Platform> Events<'a, P> { author: revision.author, }), // Its event comes once a target advances to it. - Object::Acceptance(_) | Object::Blob(_) | Object::Tree(_) => None, + Object::Acceptance(_) + | Object::Blob(_) + | Object::Tree(_) + | Object::Attachment(_) => None, }); } Ok(events) diff --git a/apps/origin-src/src/http.rs b/apps/origin-src/src/http.rs index 01579d67..6300c739 100644 --- a/apps/origin-src/src/http.rs +++ b/apps/origin-src/src/http.rs @@ -187,7 +187,7 @@ impl IntoResponse for PackResponse { } } -/// Fetches records by id, each with the blob it carries, as a pack. +/// Fetches records by id, each with the attachment it carries, as a pack. #[utoipa::path( post, path = "/api/v1/repos/{repo}/records/fetch", @@ -196,7 +196,7 @@ impl IntoResponse for PackResponse { request_body = FetchRecords, responses( (status = 200, description = "The records, in the order asked, each followed by its description or payload if the repository has it, as a pack: each object a 32-byte id, a little-endian u64 length and the object's encoding. At most 64 MiB, but for a record alone", content_type = "application/octet-stream", body = Binary, headers(("origin-more" = bool, description = "Present if the pack stopped short: ask again for the records after the last it holds"))), - (status = 400, description = "An object is a blob or a tree, which only leave by walking a snapshot", body = ApiError), + (status = 400, description = "An object is a blob, a tree or an attachment, which only leave by walking a snapshot or with the record carrying them", body = ApiError), (status = 404, description = "The repository or a record does not exist", body = ApiError) ) )] diff --git a/apps/origin-src/src/index.rs b/apps/origin-src/src/index.rs index b35ce7d8..c2deccbe 100644 --- a/apps/origin-src/src/index.rs +++ b/apps/origin-src/src/index.rs @@ -607,7 +607,7 @@ impl Entry { pub(crate) fn of(object: &EncodedObject) -> Result, DecodeError> { let id = object.id(); Ok(match object.kind()? { - ObjectKind::Blob | ObjectKind::Tree => None, + ObjectKind::Blob | ObjectKind::Tree | ObjectKind::Attachment => None, ObjectKind::Revision => { let revision: Revision = object.decode_as()?; Some(Self::Revision { @@ -934,7 +934,7 @@ mod tests { use std::thread; use origin_platform::Native; - use origin_shared::{Base, BlobId, Inputs, Kind, Record, Tree, Verdict}; + use origin_shared::{AttachmentId, Base, Inputs, Kind, Record, Tree, Verdict}; use super::*; use crate::oplog::FramePart; @@ -958,7 +958,7 @@ mod tests { base: Base::Acceptance(ObjectId::from_bytes([0; 32]).into()), deps: Vec::new(), snapshot: Tree::default().encode().id().into(), - description: BlobId::from(EncodedObject::blob(seed.as_bytes()).id()), + description: AttachmentId::from(EncodedObject::attachment(seed.as_bytes()).id()), author: "user:alice".parse().unwrap(), } .encode() diff --git a/apps/origin-src/src/queue/tests/mod.rs b/apps/origin-src/src/queue/tests/mod.rs index 8290244c..801f5fdf 100644 --- a/apps/origin-src/src/queue/tests/mod.rs +++ b/apps/origin-src/src/queue/tests/mod.rs @@ -10,8 +10,8 @@ use origin_platform::Native; use origin_shared::landing::{Blocked, Landing, Pending, Proposal}; use origin_shared::policy::Requirement; use origin_shared::{ - AcceptanceBody, Base, BlobId, ChangeId, Digest, EncodedObject, Head, Inputs, Kind, NodeKey, - PrincipalName, Record, RecordId, RepoPath, Revision, RevisionId, Source, Statement, + AcceptanceBody, AttachmentId, Base, ChangeId, Digest, EncodedObject, Head, Inputs, Kind, + NodeKey, PrincipalName, Record, RecordId, RepoPath, Revision, RevisionId, Source, Statement, StatementId, TargetName, Tree, TreeId, Verdict, }; @@ -94,7 +94,7 @@ impl Repo { base, deps: Vec::new(), snapshot: self.files(files), - description: BlobId::from(EncodedObject::blob(b"").id()), + description: AttachmentId::from(EncodedObject::attachment(b"").id()), author: "user:ada".parse().unwrap(), } .encode(); diff --git a/apps/origin-src/src/queue/tests/policy.rs b/apps/origin-src/src/queue/tests/policy.rs index 2caa4518..c402dcc3 100644 --- a/apps/origin-src/src/queue/tests/policy.rs +++ b/apps/origin-src/src/queue/tests/policy.rs @@ -2,7 +2,7 @@ use std::thread; -use origin_shared::{BlobId, Statement}; +use origin_shared::{AttachmentId, Statement}; use super::*; @@ -109,7 +109,7 @@ fn policy_landings_keep_a_valid_policy() { base: tip, deps: Vec::new(), snapshot: repo.files(&[("policy.toml", &requiring)]), - description: BlobId::from(EncodedObject::blob(b"").id()), + description: AttachmentId::from(EncodedObject::attachment(b"").id()), author: "user:ada".parse().unwrap(), } .encode(); diff --git a/apps/origin-src/src/remote.rs b/apps/origin-src/src/remote.rs index e9abffb9..014f8067 100644 --- a/apps/origin-src/src/remote.rs +++ b/apps/origin-src/src/remote.rs @@ -68,8 +68,8 @@ calls! { fn targets() -> Vec = targets(), targets(); /// The acceptances of a target, oldest first. fn log(query: &LogQuery) -> Vec = log(query), log(query); - /// Records by id, each followed by the blob it carries: those up to the - /// last record of the part, if it stops short. + /// Records by id, each followed by the attachment it carries: those up + /// to the last record of the part, if it stops short. fn records(request: &FetchRecords) -> Part = fetch_records(request), records(&request.ids); /// The trees and blobs of a snapshot that the request's snapshots lack, /// in parts. diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index a8801d9a..c34fe589 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -35,7 +35,7 @@ use origin_shared::landing::{Pending, Proposal}; use origin_shared::object::DecodeError; use origin_shared::pack::{Pack, Packer, Part}; use origin_shared::{ - Base, ChangeId, Head, NodeKey, Object, ObjectId, ObjectKind, Principal, PrincipalName, + Base, ChangeId, Head, Kind, NodeKey, Object, ObjectId, ObjectKind, Principal, PrincipalName, RecordId, Statement, StatementId, TargetName, TreeId, }; @@ -194,17 +194,17 @@ impl OriginService { } /// The records `ids` name, in their order, as a pack: revisions, - /// statements and acceptances, each followed by the blob it carries, if - /// the repository has it: a revision's description, a statement's - /// payload. Snapshots only leave through [`OriginService::snapshot`]. - /// The pack stops short at [`Pack::LIMIT`], before a record that - /// doesn't fit with its blob: the rest comes from asking for the ids - /// after the last record it has. + /// statements and acceptances, each followed by the attachment it + /// carries, if the repository has it: a revision's description, a + /// statement's payload. Snapshots only leave through + /// [`OriginService::snapshot`]. The pack stops short at [`Pack::LIMIT`], + /// before a record that doesn't fit with its attachment: the rest comes + /// from asking for the ids after the last record it has. /// /// # Errors /// - /// Fails if the repository doesn't have one, one is a blob or a tree, or - /// it cannot read one. + /// Fails if the repository doesn't have one, one is a blob, a tree or + /// an attachment, or it cannot read one. pub fn records(&self, _caller: &Caller, ids: &[ObjectId]) -> Result { let mut packer = Packer::new(self.pack_limit); for &id in ids { @@ -213,15 +213,20 @@ impl OriginService { .decode() .map_err(|source| StoreError::Decode { id, source })? { - Object::Blob(_) | Object::Tree(_) => return Err(ServiceError::NotARecord(id)), - Object::Revision(revision) => Some(revision.description.into()), - Object::Statement(statement) => statement.payload.map(Into::into), + Object::Blob(_) | Object::Tree(_) | Object::Attachment(_) => { + return Err(ServiceError::NotARecord(id)); + } + Object::Revision(revision) => Some(revision.description), + Object::Statement(statement) => statement.payload, Object::Acceptance(_) => None, }; + // Only an attachment goes with a record: never a blob, a file's + // content, whose id a record names instead. let carried = carried - .map(|id| self.store.try_read(id)) + .map(|id| self.store.try_read(id.into())) .transpose()? - .flatten(); + .flatten() + .filter(|object| object.kind().ok() == Some(ObjectKind::Attachment)); let group: Vec<_> = iter::once(object).chain(carried).collect(); if !packer.fits(&group) { return Ok(Part { @@ -327,13 +332,15 @@ impl OriginService { }) } - /// Writes the objects of `pack`: snapshots, revisions and statements. - /// Each must be well formed, and the repository must have, or the - /// pack hold, everything it needs, of the kind it names: a tree's - /// entries, trees or blobs as each says, a revision's snapshot, a tree, - /// its description, base and dependencies, a statement's subject and - /// the statements it supersedes or promotes. So the repository never - /// holds a record it cannot use. Acceptances are + /// Writes the objects of `pack`: snapshots, attachments, revisions and + /// statements. Each must be well formed, and the repository must have, + /// or the pack hold, everything it needs, of the kind it names: a + /// tree's entries, trees or blobs as each says, a revision's snapshot, + /// a tree, its description, an attachment, its base and dependencies, a + /// statement's subject and the statements it supersedes or promotes. + /// So the repository never holds a record it cannot use. A payload must + /// be an attachment too, if the repository has it, and a + /// `core.conflict`'s, its list, must be there. Acceptances are /// refused: only a target's authority writes them, by landing. The /// blobs and trees are durable before the records that refer to them, /// statements before the revisions they're about, and promotions come @@ -411,9 +418,16 @@ impl OriginService { None => return Err(ServiceError::Missing { id, needed }), } } + Self::check_payload(id, &decoded, |id| match held.get(&id) { + Some(&kind) => Ok(kind), + None => Ok(self + .store + .try_read(id)? + .and_then(|object| object.kind().ok())), + })?; match decoded { Object::Acceptance(_) => return Err(ServiceError::Acceptance(id.into())), - Object::Blob(_) | Object::Tree(_) => snapshots.push(object), + Object::Blob(_) | Object::Tree(_) | Object::Attachment(_) => snapshots.push(object), Object::Revision(revision) => { if !revision.predecessors.is_empty() { changes.insert(revision.change); @@ -513,6 +527,34 @@ impl OriginService { checked.into_iter().collect() } + /// Checks that the payload `record`, `id`, carries, if any, is an + /// attachment, as far as `kind` knows the object: the repository may + /// lack it, as a payload is a detail, but for a `core.conflict`'s, the + /// list of conflicts that reading it needs (see + /// [`Conflicts::listed`](crate::conflict::Conflicts::listed)). + fn check_payload( + id: ObjectId, + record: &Object, + kind: impl Fn(ObjectId) -> Result, StoreError>, + ) -> Result<(), ServiceError> { + let Object::Statement(statement) = record else { + return Ok(()); + }; + let Some(payload) = statement.payload else { + return Ok(()); + }; + let needed = payload.into(); + match kind(needed)? { + None if statement.kind == Kind::CONFLICT => Err(ServiceError::Missing { id, needed }), + Some(kind) if kind != ObjectKind::Attachment => Err(ServiceError::WrongKind { + id, + needed, + kind: ObjectKind::Attachment, + }), + _ => Ok(()), + } + } + /// The statements about `subject`, in the order the repository received /// them. /// @@ -734,14 +776,14 @@ impl OriginService { pub(crate) struct Dependencies { /// Revisions, statements and acceptances. pub records: Vec<(ObjectId, ObjectKind)>, - /// Trees and blobs. + /// Trees, blobs and attachments. pub content: Vec<(ObjectId, ObjectKind)>, } impl Dependencies { pub(crate) fn of(object: &Object) -> Self { match object { - Object::Blob(_) | Object::Acceptance(_) => Self::default(), + Object::Blob(_) | Object::Attachment(_) | Object::Acceptance(_) => Self::default(), Object::Tree(tree) => Self { records: Vec::new(), content: tree @@ -765,7 +807,7 @@ impl Dependencies { records, content: vec![ (revision.snapshot.into(), ObjectKind::Tree), - (revision.description.into(), ObjectKind::Blob), + (revision.description.into(), ObjectKind::Attachment), ], } } @@ -818,7 +860,7 @@ pub enum ServiceError { /// The repository has no such snapshot. #[error("snapshot {0} not found")] UnknownSnapshot(TreeId), - /// A blob or a tree was fetched as a record. + /// A blob, a tree or an attachment was fetched as a record. #[error("{0} is not a record: fetch snapshots by walking them")] NotARecord(ObjectId), /// A target was proposed for landing without a target to land on. @@ -846,7 +888,8 @@ pub enum ServiceError { needed: ObjectId, }, /// An object put refers to one as an object of another kind: a - /// snapshot that isn't a tree, a file that is one. + /// snapshot that isn't a tree, a file that is one, a description that + /// isn't an attachment. #[error("object {id} refers to {needed} as a {kind}, which it is not")] WrongKind { /// The object put. @@ -949,15 +992,16 @@ mod tests { use super::*; - #[test] - fn pushes_publish_statements_before_the_revisions_they_are_about() { - let repo = crate::queue::tests::Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); + /// A service of `repo`, and the objects that put a revision with a + /// conflict: its description, the conflict's payload, the revision and + /// the conflict. + fn conflicted(repo: &crate::queue::tests::Repo) -> (OriginService, [EncodedObject; 4]) { let node = Node { name: "queue".parse().unwrap(), key: Arc::new(NodeKey::from_bytes(&[7; 32])), }; let service = OriginService::new(repo.store.clone(), node); - let description = EncodedObject::blob(b""); + let description = EncodedObject::attachment(b""); let revision = origin_shared::Revision { change: origin_shared::ChangeId::from_bytes([1; 16]), predecessors: Vec::new(), @@ -974,10 +1018,18 @@ mod tests { }]); let subject = RecordId::Revision(revision.id().into()); let (payload, conflict) = conflicts.statement(subject, "user:ada".parse().unwrap(), None); - let conflict = conflict.encode(); + (service, [description, payload, revision, conflict.encode()]) + } + + #[test] + fn pushes_publish_statements_before_the_revisions_they_are_about() { + let repo = crate::queue::tests::Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); + let (service, objects) = conflicted(&repo); + let [_, _, revision, conflict] = objects.clone(); + let subject = RecordId::Revision(revision.id().into()); let oplog = repo.store.oplog(); let before = oplog.last_seq().unwrap(); - let objects = vec![description, payload, revision, conflict.clone()]; + let objects = objects.to_vec(); service .put_records(&Caller::Owner, Pack { objects }) .unwrap(); @@ -997,6 +1049,31 @@ mod tests { assert!(written(conflict) < written(subject)); } + #[test] + fn conflicts_come_with_the_list_they_carry() { + let repo = crate::queue::tests::Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); + let (service, [description, payload, revision, conflict]) = conflicted(&repo); + let without = vec![description, revision, conflict.clone()]; + let refused = service.put_records( + &Caller::Owner, + Pack { + objects: without.clone(), + }, + ); + assert!( + matches!(refused, Err(ServiceError::Missing { id, needed }) + if id == conflict.id() && needed == payload.id()), + "{refused:?}" + ); + assert!(!repo.store.contains(conflict.id()).unwrap()); + // Stored already, the list needn't come again. + repo.store.write_all(&[payload]).unwrap(); + service + .put_records(&Caller::Owner, Pack { objects: without }) + .unwrap(); + assert!(repo.store.contains(conflict.id()).unwrap()); + } + #[test] fn calls_using_the_index_do_not_wait_for_each_other() { let dir = tempfile::tempdir().unwrap(); diff --git a/apps/origin-src/src/store/mod.rs b/apps/origin-src/src/store/mod.rs index b72b7276..b375f418 100644 --- a/apps/origin-src/src/store/mod.rs +++ b/apps/origin-src/src/store/mod.rs @@ -36,7 +36,7 @@ use std::time::{Duration, SystemTime}; use origin_platform::{DurableWrite, LockMode, LockedFile, Native, Platform, WritableError}; use origin_shared::object::{DecodeError, IdMismatch}; -use origin_shared::{EncodedObject, Head, ObjectId, TargetName, TypedId}; +use origin_shared::{AttachmentId, EncodedObject, Head, ObjectId, TargetName, TypedId}; use crate::index::Entry; use crate::oplog::{Actor, Effect}; @@ -510,6 +510,25 @@ impl Store

{ Ok(Some(content.to_vec())) } + /// Reads an attachment's content, or `None` if the store does not have + /// it. + /// + /// # Errors + /// + /// Fails if the object cannot be read, is corrupt, or isn't an + /// attachment, such as a blob whose id a record names as its + /// attachment. + pub fn try_attachment(&self, id: AttachmentId) -> Result>, StoreError> { + let id = id.into(); + let Some(object) = self.try_read(id)? else { + return Ok(None); + }; + let content = object + .attachment_content() + .map_err(|source| StoreError::Decode { id, source })?; + Ok(Some(content.to_vec())) + } + /// Reads an object the store must have. /// /// # Errors diff --git a/apps/origin-src/src/sync.rs b/apps/origin-src/src/sync.rs index 52ea1c11..9fefb4d6 100644 --- a/apps/origin-src/src/sync.rs +++ b/apps/origin-src/src/sync.rs @@ -815,7 +815,7 @@ impl<'a> Sync<'a> { /// those of `skip`, with the records they refer to, recursively: a /// revision's base and dependencies, a statement's subject and the /// statements it supersedes or promotes, but not their snapshots. Each - /// comes with the blob it carries. Those this node has are made durable + /// comes with the attachment it carries. Those this node has are made durable /// by `held`, which must commit before anything refers to them. fn closure( &self, @@ -1474,7 +1474,7 @@ mod tests { .iter() .map(|(_, content)| EncodedObject::blob(content.as_bytes())) .collect(); - let description = EncodedObject::blob(b"work"); + let description = EncodedObject::attachment(b"work"); let revision = Revision { change: ChangeId::from_bytes([change; 16]), predecessors: predecessors.to_vec(), @@ -2161,7 +2161,7 @@ mod tests { base: main_tip(&client.store), deps: Vec::new(), snapshot: build(&client.store, &[("a", "gone")]), - description: EncodedObject::blob(b"").id().into(), + description: EncodedObject::attachment(b"").id().into(), author: "user:ada".parse().unwrap(), }; client @@ -2178,8 +2178,8 @@ mod tests { .collect(); let room = Pack::LIMIT - wire(content) - - wire(vec![revision.encode(), EncodedObject::blob(b"")]); - let description = EncodedObject::blob(&vec![b'x'; room]); + - wire(vec![revision.encode(), EncodedObject::attachment(b"")]); + let description = EncodedObject::attachment(&vec![b'x'; room]); revision.description = description.id().into(); let revision = revision.encode(); client diff --git a/apps/origin-src/src/tree.rs b/apps/origin-src/src/tree.rs index 7ea9d1f4..0605c76b 100644 --- a/apps/origin-src/src/tree.rs +++ b/apps/origin-src/src/tree.rs @@ -400,42 +400,6 @@ impl<'a, P: Platform> Snapshots<'a, P> { } } -impl Store

{ - /// Adds every object the trees `roots` reach to `reached`: the trees - /// themselves, their subtrees and their files. Trees already in - /// `reached` are not read again, and those the store doesn't have, as - /// after a lazy clone, are skipped. - /// - /// # Errors - /// - /// Fails if a tree cannot be read. - pub fn reach( - &self, - roots: impl IntoIterator, - reached: &mut HashSet, - ) -> Result<(), StoreError> { - let mut pending: Vec = roots.into_iter().collect(); - while let Some(id) = pending.pop() { - if !reached.insert(id.into()) { - continue; - } - let tree: Tree = match self.get(id) { - Err(StoreError::NotFound(_)) => continue, - tree => tree?, - }; - for (_, entry) in &tree { - match entry.subtree() { - Some(subtree) => pending.push(subtree), - None => { - reached.insert(entry.id); - } - } - } - } - Ok(()) - } -} - /// A snapshot being fetched, marked durably in the store's `fetching/`, so /// an interrupted fetch, which published trees before what they hold, is /// never taken for a whole snapshot: see [`Store::holds`]. Dropping it @@ -942,10 +906,5 @@ pub(crate) mod tests { for missing in ["nope", "src/nope", "README/inside"] { assert_eq!(at(missing), None, "{missing}"); } - - let mut reached = HashSet::new(); - store.reach([root], &mut reached).unwrap(); - assert_eq!(reached.len(), 4, "two trees and two files"); - assert!(reached.contains(&file("lib").id)); } } diff --git a/apps/origin-src/src/workspace/annotate.rs b/apps/origin-src/src/workspace/annotate.rs index 9d95bae5..89d8abdb 100644 --- a/apps/origin-src/src/workspace/annotate.rs +++ b/apps/origin-src/src/workspace/annotate.rs @@ -8,8 +8,8 @@ use std::path::{Path, PathBuf}; use std::time::SystemTime; use origin_shared::{ - BlobId, EncodedObject, Inputs, Kind, Principal, RecordId, Revision, RevisionId, Statement, - StatementId, Verdict, + AttachmentId, EncodedObject, Inputs, Kind, Principal, RecordId, Revision, RevisionId, + Statement, StatementId, Verdict, }; use super::{WorkingCopy, Workspace, WorkspaceError}; @@ -73,18 +73,18 @@ pub enum Payload { } impl Payload { - /// The blob holding the details. - fn blob(&self) -> Result { + /// The attachment holding the details. + fn attachment(&self) -> Result { match self { - Self::Text(text) => Ok(EncodedObject::blob(text.as_bytes())), + Self::Text(text) => Ok(EncodedObject::attachment(text.as_bytes())), Self::File(path) if path == Path::new("-") => { - EncodedObject::read_blob(io::stdin().lock(), 0) + EncodedObject::read_attachment(io::stdin().lock(), 0) .map_err(|source| WorkspaceError::io(path, source)) } Self::File(path) => File::open(path) .and_then(|file| { let len = file.metadata()?.len(); - EncodedObject::read_blob(file, usize::try_from(len).unwrap_or(0)) + EncodedObject::read_attachment(file, usize::try_from(len).unwrap_or(0)) }) .map_err(|source| WorkspaceError::io(path, source)), } @@ -140,7 +140,7 @@ impl Workspace { let working_copy = self.refresh()?; let subject = working_copy.find_record(annotated)?; let mut annotations = Annotations::new(&self.store, working_copy.index); - let payload = payload.map(Payload::blob).transpose()?; + let payload = payload.map(Payload::attachment).transpose()?; let statement = Statement { subject, supersedes: None, @@ -310,8 +310,8 @@ impl Workspace { /// A payload's first line if it's text, its size otherwise, or that this /// repository doesn't have it: retention may have dropped it, or it /// never came here. - fn payload_summary(&self, payload: BlobId) -> Result { - let Some(content) = self.store.try_blob(payload.into())? else { + fn payload_summary(&self, payload: AttachmentId) -> Result { + let Some(content) = self.store.try_attachment(payload)? else { return Ok("unavailable here".to_owned()); }; Ok( diff --git a/apps/origin-src/src/workspace/land.rs b/apps/origin-src/src/workspace/land.rs index 3e932dc7..62a1753b 100644 --- a/apps/origin-src/src/workspace/land.rs +++ b/apps/origin-src/src/workspace/land.rs @@ -301,7 +301,7 @@ impl Workspace { state, [Self::OURS, &tip_label], )?; - let description = EncodedObject::blob(description.as_bytes()); + let description = EncodedObject::attachment(description.as_bytes()); let revision = Revision { change: ChangeId::random().map_err(WorkspaceError::Random)?, predecessors: Vec::new(), diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index ef0f72d9..69d3b85b 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -84,7 +84,7 @@ use std::sync::{Arc, OnceLock}; use origin_platform::{LockMode, LockedFile, Native}; use origin_shared::api::{LogQuery, RevisionEntry, Revisions}; use origin_shared::{ - AcceptanceId, Base, BlobId, ChangeId, EncodedObject, Kind, Principal, Record, RecordId, + AcceptanceId, AttachmentId, Base, ChangeId, EncodedObject, Kind, Principal, Record, RecordId, RepoPath, Revision, RevisionId, Source, Statement, StatementId, TargetId, TargetName, Tree, TreeId, }; @@ -269,7 +269,7 @@ impl Workspace { let policy = Policy::initial(config.node(), &key.public()); let main = Queue::new(&store, &key, config.node().clone()).init(&policy)?; let empty_tree = Tree::default().encode(); - let empty_description = EncodedObject::blob(b""); + let empty_description = EncodedObject::attachment(b""); let revision = Revision { change: ChangeId::random().map_err(WorkspaceError::Random)?, @@ -1015,7 +1015,7 @@ impl Workspace { let working_copy = self.record()?; let mut working_copy = self.following(working_copy)?; self.log_draft(&working_copy); - let description = EncodedObject::blob(description.as_bytes()); + let description = EncodedObject::attachment(description.as_bytes()); let revision = Revision { change: ChangeId::random().map_err(WorkspaceError::Random)?, predecessors: Vec::new(), @@ -1053,7 +1053,7 @@ impl Workspace { let working_copy = self.record()?; let mut working_copy = self.following(working_copy)?; self.log_draft(&working_copy); - let description = EncodedObject::blob(description.as_bytes()); + let description = EncodedObject::attachment(description.as_bytes()); let revision = Revision { predecessors: vec![working_copy.id], description: description.id().into(), @@ -1139,7 +1139,7 @@ impl Workspace { None => working_copy.revision.change, }; let head = Self::single_head(index, change)?; - let reason = EncodedObject::blob(reason.as_bytes()); + let reason = EncodedObject::attachment(reason.as_bytes()); let statement = Statement { subject: RecordId::Revision(head), kind: Kind::ABANDON, @@ -1165,7 +1165,7 @@ impl Workspace { } let abandoned: Revision = self.store.get(head)?; - let empty = EncodedObject::blob(b""); + let empty = EncodedObject::attachment(b""); let revision = Revision { change: ChangeId::random().map_err(WorkspaceError::Random)?, predecessors: Vec::new(), @@ -1432,14 +1432,13 @@ impl Workspace { self.text(revision.description) } - /// A blob's content, as text. - fn text(&self, blob: BlobId) -> Result { - let id = blob.into(); - let blob = self.store.read(id)?; - let content = blob - .blob_content() - .map_err(|source| StoreError::Decode { id, source })?; - Ok(String::from_utf8_lossy(content).into_owned()) + /// An attachment's content, as text. + fn text(&self, attachment: AttachmentId) -> Result { + let content = self + .store + .try_attachment(attachment)? + .ok_or(StoreError::NotFound(attachment.into()))?; + Ok(String::from_utf8_lossy(&content).into_owned()) } /// The first line of a revision's description. diff --git a/apps/origin-src/src/workspace/registry.rs b/apps/origin-src/src/workspace/registry.rs index 980c2812..9c53beab 100644 --- a/apps/origin-src/src/workspace/registry.rs +++ b/apps/origin-src/src/workspace/registry.rs @@ -49,7 +49,7 @@ impl Workspace { let head = Self::single_head(&working_copy.index, change)?; (head, self.store.get(head)?, Vec::new()) } else { - let description = EncodedObject::blob(b""); + let description = EncodedObject::attachment(b""); let base = working_copy.revision.base; let revision = Revision { change: ChangeId::random().map_err(WorkspaceError::Random)?, diff --git a/apps/origin-src/src/workspace/remote.rs b/apps/origin-src/src/workspace/remote.rs index d012c787..f4346846 100644 --- a/apps/origin-src/src/workspace/remote.rs +++ b/apps/origin-src/src/workspace/remote.rs @@ -122,7 +122,7 @@ impl Workspace { sync.need(state, &[])?; let empty_tree = Tree::default().encode(); - let empty_description = EncodedObject::blob(b""); + let empty_description = EncodedObject::attachment(b""); let revision = Revision { change: ChangeId::random().map_err(WorkspaceError::Random)?, predecessors: Vec::new(), diff --git a/apps/origin-src/tests/cli.rs b/apps/origin-src/tests/cli.rs index 589699f1..2f961ad4 100644 --- a/apps/origin-src/tests/cli.rs +++ b/apps/origin-src/tests/cli.rs @@ -312,7 +312,7 @@ fn a_revision_is_published_only_after_its_conflicts() { let issuer = revision.author.clone(); let described = Revision { predecessors: vec![converged], - description: EncodedObject::blob(b"Described").id().into(), + description: EncodedObject::attachment(b"Described").id().into(), ..revision } .encode(); @@ -724,7 +724,7 @@ fn statements_about_statements_show_under_them() { fn a_payload_the_repository_lacks_is_unavailable() { let repo = Repo::new(); repo.ok(&["annotate", "@", "review", "--pass", "-m", "Looks good"]); - let hex = EncodedObject::blob(b"Looks good").id().to_hex(); + let hex = EncodedObject::attachment(b"Looks good").id().to_hex(); fs::remove_file(repo.path(&format!( ".origin/objects/loose/{}/{}", &hex[..2], diff --git a/apps/origin-src/tests/http.rs b/apps/origin-src/tests/http.rs index 7c38d1c6..cb58b601 100644 --- a/apps/origin-src/tests/http.rs +++ b/apps/origin-src/tests/http.rs @@ -1,6 +1,7 @@ //! The HTTP API, driven through the SDK against a real server: every SDK //! method, over the server's own repositories. +use std::collections::BTreeMap; use std::slice; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -14,9 +15,9 @@ use origin_shared::event::EventKind; use origin_shared::landing::{Blocked, Landing, Proposal}; use origin_shared::pack::Pack; use origin_shared::{ - Base, BlobId, ChangeId, Digest, EncodedObject, EntryKind, EntryName, Inputs, Kind, NodeKey, - Period, Record, RecordId, RepoPath, Revision, RevisionId, Source, Statement, TargetName, Tree, - TreeEntry, TreeId, Verdict, + AttachmentId, Base, ChangeId, Digest, EncodedObject, EntryKind, EntryName, Inputs, Kind, + NodeKey, Period, Record, RecordId, RepoPath, Revision, RevisionId, Source, Statement, + TargetName, Tree, TreeEntry, TreeId, Verdict, }; use origin_src::http::Api; use origin_src::policy::Policy; @@ -97,14 +98,14 @@ impl Made { }) .collect(); let tree = tree.encode(); - let description = EncodedObject::blob(b"A change"); + let description = EncodedObject::attachment(b"A change"); let revision = Revision { change, predecessors, base, deps: Vec::new(), snapshot: tree.id().into(), - description: BlobId::from(description.id()), + description: AttachmentId::from(description.id()), author: "user:ada".parse().unwrap(), } .encode(); @@ -113,6 +114,57 @@ impl Made { Self { id, objects } } + /// A revision whose files may be in directories, such as + /// `src/lib.rs`. + fn nested(change: ChangeId, base: Base, files: &[(&str, &str)]) -> Self { + let mut objects = Vec::new(); + let tree = Self::tree(files, &mut objects); + let description = EncodedObject::attachment(b"A change"); + let revision = Revision { + change, + predecessors: Vec::new(), + base, + deps: Vec::new(), + snapshot: tree, + description: description.id().into(), + author: "user:ada".parse().unwrap(), + } + .encode(); + let id = revision.id().into(); + objects.extend([description, revision]); + Self { id, objects } + } + + /// The tree of `files`, pushing its objects, children first. + fn tree(files: &[(&str, &str)], objects: &mut Vec) -> TreeId { + let mut dirs: BTreeMap<&str, Vec<(&str, &str)>> = BTreeMap::new(); + let mut tree = Tree::default(); + for &(path, content) in files { + if let Some((dir, rest)) = path.split_once('/') { + dirs.entry(dir).or_default().push((rest, content)); + continue; + } + let blob = EncodedObject::blob(content.as_bytes()); + let entry = TreeEntry { + kind: EntryKind::File, + id: blob.id(), + }; + tree.insert(EntryName::new(path).unwrap(), entry); + objects.push(blob); + } + for (dir, files) in dirs { + let entry = TreeEntry { + kind: EntryKind::Tree, + id: Self::tree(&files, objects).into(), + }; + tree.insert(EntryName::new(dir).unwrap(), entry); + } + let encoded = tree.encode(); + let id = encoded.id().into(); + objects.push(encoded); + id + } + fn pack(&self) -> Pack { Pack { objects: self.objects.clone(), @@ -265,26 +317,29 @@ async fn puts_refuse_objects_named_as_another_kind() { // A revision whose snapshot is a blob, in the batch. let blob = EncodedObject::blob(b"not a tree"); - let description = EncodedObject::blob(b"A change"); + let description = EncodedObject::attachment(b"A change"); let revision = Revision { change: change(1), predecessors: Vec::new(), base, deps: Vec::new(), snapshot: blob.id().into(), - description: BlobId::from(description.id()), + description: description.id().into(), author: "user:ada".parse().unwrap(), } .encode(); - let objects = vec![blob, description, revision]; + let objects = vec![blob.clone(), description, revision]; assert_eq!(refused(objects).await, ErrorCode::BadRequest); // Trees naming a stored blob as a directory, and a stored tree as a // file. - let made = Made::revision(change(2), base, Vec::new(), &[("lib.rs", "fn a() {}")]); + let made = Made::nested(change(2), base, &[("src/lib.rs", "fn a() {}")]); repo.put_records(&made.pack()).await.unwrap(); - let (file, tree) = (made.objects[0].id(), made.objects[1].id()); - for (kind, id) in [(EntryKind::Tree, file), (EntryKind::File, tree)] { + let src = made.objects[1].id(); + for (kind, id) in [ + (EntryKind::Tree, made.objects[0].id()), + (EntryKind::File, src), + ] { let tree: Tree = [(EntryName::new("x").unwrap(), TreeEntry { kind, id })] .into_iter() .collect(); @@ -294,9 +349,10 @@ async fn puts_refuse_objects_named_as_another_kind() { // One stored object needed as two kinds, the right one last: a // revision's snapshot and description, and a tree's directory and // file. - let stored = EncodedObject::blob(b"stored"); + let attachment = EncodedObject::attachment(b"stored"); + let blob = made.objects[0].clone(); repo.put_records(&Pack { - objects: vec![stored.clone()], + objects: vec![attachment.clone()], }) .await .unwrap(); @@ -305,14 +361,14 @@ async fn puts_refuse_objects_named_as_another_kind() { predecessors: Vec::new(), base, deps: Vec::new(), - snapshot: stored.id().into(), - description: BlobId::from(stored.id()), + snapshot: attachment.id().into(), + description: attachment.id().into(), author: "user:ada".parse().unwrap(), }; assert_eq!(refused(vec![both.encode()]).await, ErrorCode::BadRequest); let entry = |kind| TreeEntry { kind, - id: stored.id(), + id: blob.id(), }; let tree: Tree = [ (EntryName::new("a").unwrap(), entry(EntryKind::Tree)), diff --git a/crates/origin-client/src/lib.rs b/crates/origin-client/src/lib.rs index 68523f5f..a1698697 100644 --- a/crates/origin-client/src/lib.rs +++ b/crates/origin-client/src/lib.rs @@ -67,9 +67,9 @@ endpoints! { impl Repo { /// Fetches records by id, in the order asked, each followed by the - /// blob it carries if the server has it: a revision's description, - /// a statement's payload. A part that stops short holds those up to - /// the last record it has. + /// attachment it carries if the server has it: a revision's + /// description, a statement's payload. A part that stops short + /// holds those up to the last record it has. fn fetch_records(request: &FetchRecords) -> Part = POST "records/fetch", json(request) => part; /// Fetches the trees and blobs of a snapshot that none of the diff --git a/crates/origin-shared/src/api.rs b/crates/origin-shared/src/api.rs index 85cb2e11..70df4920 100644 --- a/crates/origin-shared/src/api.rs +++ b/crates/origin-shared/src/api.rs @@ -101,14 +101,15 @@ pub struct RepoSummary { pub const MORE: &str = "origin-more"; /// Asks for records by id: revisions, statements and acceptances. Each -/// comes with the blob it carries, if the repository has it: a revision's -/// description, a statement's payload. Snapshots are fetched with -/// [`FetchSnapshot`] instead. +/// comes with the attachment it carries, if the repository has it: a +/// revision's description, a statement's payload. Snapshots are fetched +/// with [`FetchSnapshot`] instead. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] pub struct FetchRecords { - /// The records, returned in this order, each followed by its blob. A - /// response that stops short, with the [`MORE`] header, holds those up - /// to the last record it has: ask again for those after it. + /// The records, returned in this order, each followed by its + /// attachment. A response that stops short, with the [`MORE`] header, + /// holds those up to the last record it has: ask again for those after + /// it. pub ids: Vec, } diff --git a/crates/origin-shared/src/id.rs b/crates/origin-shared/src/id.rs index 6cd50313..0e38d38c 100644 --- a/crates/origin-shared/src/id.rs +++ b/crates/origin-shared/src/id.rs @@ -123,8 +123,11 @@ ids! { } object_ids! { - /// Identifies a blob: file contents, a description or a payload. + /// Identifies a blob: a file's content. BlobId; + /// Identifies an attachment: a revision's description or a statement's + /// payload. + AttachmentId; /// Identifies a tree, the root of which is a snapshot. TreeId => Tree; /// Identifies a revision. diff --git a/crates/origin-shared/src/lib.rs b/crates/origin-shared/src/lib.rs index 23a5239f..ca5e3f44 100644 --- a/crates/origin-shared/src/lib.rs +++ b/crates/origin-shared/src/lib.rs @@ -15,8 +15,8 @@ mod target; mod text; pub use id::{ - AcceptanceId, BlobId, ChangeId, Digest, ObjectId, ParseIdError, RevisionId, StatementId, - TargetId, TreeId, TypedId, + AcceptanceId, AttachmentId, BlobId, ChangeId, Digest, ObjectId, ParseIdError, RevisionId, + StatementId, TargetId, TreeId, TypedId, }; pub use name::InvalidName; pub use object::{ diff --git a/crates/origin-shared/src/object/mod.rs b/crates/origin-shared/src/object/mod.rs index 4567e347..10310c42 100644 --- a/crates/origin-shared/src/object/mod.rs +++ b/crates/origin-shared/src/object/mod.rs @@ -6,7 +6,10 @@ //! its own hash domain: objects of different kinds never share an id, and a //! record of one kind can never be mistaken for another. //! -//! - Blob: the content, as is. +//! - Blob: a file's content, as is. +//! - Attachment: a revision's description or a statement's payload, as is. +//! It is a kind of its own, so no record can carry a file's content as +//! its attachment: whoever may read a record may not read every file. //! - Tree: its entries, see [`Tree`]. //! - Revision, statement and acceptance: their fields in declaration order. //! Integers are little endian, ids their raw bytes, names and paths a @@ -40,7 +43,7 @@ mod tree; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[repr(u8)] pub enum ObjectKind { - /// File contents, a description or a payload. + /// A file's content. Blob = 1, /// A directory listing. Tree = 2, @@ -50,6 +53,8 @@ pub enum ObjectKind { Statement = 4, /// One landing on a target. Acceptance = 5, + /// A revision's description or a statement's payload. + Attachment = 6, } impl ObjectKind { @@ -60,6 +65,7 @@ impl ObjectKind { 3 => Ok(Self::Revision), 4 => Ok(Self::Statement), 5 => Ok(Self::Acceptance), + 6 => Ok(Self::Attachment), _ => Err(DecodeError::UnknownObjectKind(byte)), } } @@ -73,11 +79,12 @@ impl fmt::Display for ObjectKind { Self::Revision => "revision", Self::Statement => "statement", Self::Acceptance => "acceptance", + Self::Attachment => "attachment", }) } } -/// An object with structure: every kind but blobs. +/// An object with structure: every kind but blobs and attachments. pub trait Record: Field { /// The kind every encoding of this record starts with. const KIND: ObjectKind; @@ -96,8 +103,10 @@ macro_rules! object { /// A decoded object. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Object { - /// File contents, a description or a payload. + /// A file's content. Blob(Vec), + /// A revision's description or a statement's payload. + Attachment(Vec), $(#[doc = concat!("A ", stringify!($record), ".")] $record($record),)* } @@ -107,6 +116,7 @@ macro_rules! object { pub fn kind(&self) -> ObjectKind { match self { Self::Blob(_) => ObjectKind::Blob, + Self::Attachment(_) => ObjectKind::Attachment, $(Self::$record(_) => $record::KIND,)* } } @@ -116,6 +126,7 @@ macro_rules! object { pub fn encode(&self) -> EncodedObject { match self { Self::Blob(content) => EncodedObject::blob(content), + Self::Attachment(content) => EncodedObject::attachment(content), $(Self::$record(record) => record.encode(),)* } } @@ -130,6 +141,7 @@ macro_rules! object { pub fn decode(&self) -> Result { match self.kind()? { ObjectKind::Blob => Ok(Object::Blob(self.bytes[1..].to_vec())), + ObjectKind::Attachment => Ok(Object::Attachment(self.bytes[1..].to_vec())), $(ObjectKind::$record => self.decode_as().map(Object::$record),)* } } @@ -169,9 +181,24 @@ impl EncodedObject { /// # Errors /// /// Fails if reading fails. - pub fn read_blob(mut reader: impl Read, len_hint: usize) -> io::Result { + pub fn read_blob(reader: impl Read, len_hint: usize) -> io::Result { + Self::read_raw(ObjectKind::Blob, reader, len_hint) + } + + /// Encodes an attachment, reading its content to the end, like + /// [`EncodedObject::read_blob`]. + /// + /// # Errors + /// + /// Fails if reading fails. + pub fn read_attachment(reader: impl Read, len_hint: usize) -> io::Result { + Self::read_raw(ObjectKind::Attachment, reader, len_hint) + } + + /// Encodes content read to the end as is, as an object of `kind`. + fn read_raw(kind: ObjectKind, mut reader: impl Read, len_hint: usize) -> io::Result { let mut bytes = Vec::with_capacity(len_hint + 1); - bytes.push(ObjectKind::Blob as u8); + bytes.push(kind as u8); reader.read_to_end(&mut bytes)?; Ok(Self::hash(bytes)) } @@ -179,8 +206,19 @@ impl EncodedObject { /// Encodes a blob from its content. #[must_use] pub fn blob(content: &[u8]) -> Self { + Self::raw(ObjectKind::Blob, content) + } + + /// Encodes an attachment from its content. + #[must_use] + pub fn attachment(content: &[u8]) -> Self { + Self::raw(ObjectKind::Attachment, content) + } + + /// Encodes content as is, as an object of `kind`. + fn raw(kind: ObjectKind, content: &[u8]) -> Self { let mut bytes = Vec::with_capacity(content.len() + 1); - bytes.push(ObjectKind::Blob as u8); + bytes.push(kind as u8); bytes.extend_from_slice(content); Self::hash(bytes) } @@ -230,7 +268,22 @@ impl EncodedObject { /// /// Fails if the object is not a blob. pub fn blob_content(&self) -> Result<&[u8], DecodeError> { - self.expect_kind(ObjectKind::Blob)?; + self.content(ObjectKind::Blob) + } + + /// An attachment's content, without copying it. + /// + /// # Errors + /// + /// Fails if the object is not an attachment: a blob, a file's content, + /// is never read as one. + pub fn attachment_content(&self) -> Result<&[u8], DecodeError> { + self.content(ObjectKind::Attachment) + } + + /// The content of an object of `kind` stored as is. + fn content(&self, kind: ObjectKind) -> Result<&[u8], DecodeError> { + self.expect_kind(kind)?; Ok(&self.bytes[1..]) } diff --git a/crates/origin-shared/src/object/revision.rs b/crates/origin-shared/src/object/revision.rs index 05e2ebf7..83e5148c 100644 --- a/crates/origin-shared/src/object/revision.rs +++ b/crates/origin-shared/src/object/revision.rs @@ -1,5 +1,5 @@ use super::{ObjectKind, Record, fields, tagged}; -use crate::{AcceptanceId, BlobId, ChangeId, Principal, RevisionId, TreeId}; +use crate::{AcceptanceId, AttachmentId, ChangeId, Principal, RevisionId, TreeId}; /// One immutable version of a change. /// @@ -21,7 +21,7 @@ pub struct Revision { /// The root tree of the files. pub snapshot: TreeId, /// The intent, written for humans and agents. - pub description: BlobId, + pub description: AttachmentId, /// 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 86eb0cd2..8b2b352f 100644 --- a/crates/origin-shared/src/object/statement.rs +++ b/crates/origin-shared/src/object/statement.rs @@ -6,7 +6,7 @@ use std::str::FromStr; use super::{DecodeError, Field, ObjectKind, Reader, Record, fields, tagged}; use crate::name::names; use crate::{ - AcceptanceId, BlobId, Digest, InvalidName, ObjectId, ParseIdError, Principal, RepoPath, + AcceptanceId, AttachmentId, Digest, InvalidName, ObjectId, ParseIdError, Principal, RepoPath, RevisionId, StatementId, TreeEntry, TreeId, }; @@ -30,7 +30,7 @@ pub struct Statement { /// with the same inputs. pub inputs: Option, /// Free-form details, defined by whoever owns the kind. - pub payload: Option, + 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 diff --git a/crates/origin-shared/src/text.rs b/crates/origin-shared/src/text.rs index bb8f7ddb..38a4c902 100644 --- a/crates/origin-shared/src/text.rs +++ b/crates/origin-shared/src/text.rs @@ -11,9 +11,9 @@ use utoipa::openapi::schema::{ObjectBuilder, Schema, Type}; use crate::policy::{KindPattern, Principals}; use crate::{ - AcceptanceId, BlobId, ChangeId, Digest, EntryName, Kind, NodePublicKey, ObjectId, Principal, - PrincipalName, RecordId, RepoPath, RevisionId, StatementId, TargetId, TargetName, TreeId, - Verdict, + AcceptanceId, AttachmentId, BlobId, ChangeId, Digest, EntryName, Kind, NodePublicKey, ObjectId, + Principal, PrincipalName, RecordId, RepoPath, RevisionId, StatementId, TargetId, TargetName, + TreeId, Verdict, }; /// Serializes each type as the string it displays as, deserializes it by @@ -53,6 +53,7 @@ const ID: &str = "48fc721fbbc172e0925fa27af1671de225ba927134802998b10a1568a18865 as_text! { ObjectId => ID; BlobId => ID; + AttachmentId => ID; TreeId => ID; RevisionId => ID; StatementId => ID; diff --git a/docs/openapi.json b/docs/openapi.json index 1e9db4e8..ea949dd1 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -520,7 +520,7 @@ }, "/api/v1/repos/{repo}/records/fetch": { "post": { - "summary": "Fetches records by id, each with the blob it carries, as a pack.", + "summary": "Fetches records by id, each with the attachment it carries, as a pack.", "operationId": "fetch_records", "parameters": [ { @@ -563,7 +563,7 @@ } }, "400": { - "description": "An object is a blob or a tree, which only leave by walking a snapshot", + "description": "An object is a blob, a tree or an attachment, which only leave by walking a snapshot or with the record carrying them", "content": { "application/json": { "schema": { @@ -935,6 +935,12 @@ } } }, + "AttachmentId": { + "type": "string", + "examples": [ + "48fc721fbbc172e0925fa27af1671de225ba927134802998b10a1568a188652b" + ] + }, "Base": { "oneOf": [ { @@ -970,12 +976,6 @@ "type": "string", "contentMediaType": "application/octet-stream" }, - "BlobId": { - "type": "string", - "examples": [ - "48fc721fbbc172e0925fa27af1671de225ba927134802998b10a1568a188652b" - ] - }, "Blocked": { "oneOf": [ { @@ -1218,7 +1218,7 @@ }, "FetchRecords": { "type": "object", - "description": "Asks for records by id: revisions, statements and acceptances. Each\ncomes with the blob it carries, if the repository has it: a revision's\ndescription, a statement's payload. Snapshots are fetched with\n[`FetchSnapshot`] instead.", + "description": "Asks for records by id: revisions, statements and acceptances. Each\ncomes with the attachment it carries, if the repository has it: a\nrevision's description, a statement's payload. Snapshots are fetched\nwith [`FetchSnapshot`] instead.", "required": [ "ids" ], @@ -1228,7 +1228,7 @@ "items": { "$ref": "#/components/schemas/ObjectId" }, - "description": "The records, returned in this order, each followed by its blob. A\nresponse that stops short, with the [`MORE`] header, holds those up\nto the last record it has: ask again for those after it." + "description": "The records, returned in this order, each followed by its\nattachment. A response that stops short, with the [`MORE`] header,\nholds those up to the last record it has: ask again for those after\nit." } } }, @@ -1715,7 +1715,7 @@ "description": "The exact revisions this one requires: the changes below it in a\nstack." }, "description": { - "$ref": "#/components/schemas/BlobId", + "$ref": "#/components/schemas/AttachmentId", "description": "The intent, written for humans and agents." }, "predecessors": { @@ -1841,7 +1841,7 @@ "payload": { "oneOf": [ { - "$ref": "#/components/schemas/BlobId", + "$ref": "#/components/schemas/AttachmentId", "description": "Free-form details, defined by whoever owns the kind." }, {