diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index aba0066e..e8ba31b7 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -16,18 +16,25 @@ //! Every method takes the [`Caller`]. Nothing is checked yet: every caller //! may read and write everything. +use std::collections::hash_map::Entry; +use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use origin_platform::Native; use origin_shared::api::{ Annotation, ErrorCode, LandRequest, Landings, LogEntry, NewTarget, RevisionEntry, Revisions, - TargetInfo, + Stored, TargetInfo, }; use origin_shared::landing::{Pending, Proposal}; -use origin_shared::{Base, ChangeId, Head, NodeKey, PrincipalName, RecordId, TargetName}; +use origin_shared::object::DecodeError; +use origin_shared::pack::Pack; +use origin_shared::{ + Base, ChangeId, Head, NodeKey, Object, ObjectId, ObjectKind, Principal, PrincipalName, + RecordId, Statement, StatementId, TargetName, +}; -use crate::annotations::Annotations; +use crate::annotations::{AnnotateError, Annotations}; use crate::index::Index; use crate::policy::{Policy, PolicyError}; use crate::queue::{LandError, Queue}; @@ -53,6 +60,13 @@ pub struct Node { pub key: Arc, } +impl Node { + /// The node as a principal, which issues the statements it makes. + fn principal(&self) -> Principal { + Principal::Node(self.name.clone()) + } +} + /// One repository, served by its node. #[derive(Debug)] pub struct OriginService { @@ -153,6 +167,156 @@ impl OriginService { self.indexes.lock().unwrap_or_else(PoisonError::into_inner) } + /// The objects `ids` name, in their order, as a pack. + /// + /// # Errors + /// + /// Fails if the repository doesn't have one, or cannot read it. + pub fn records(&self, _caller: &Caller, ids: &[ObjectId]) -> Result { + let objects = ids + .iter() + .map(|&id| self.store.read(id)) + .collect::>()?; + Ok(Pack { objects }) + } + + /// 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 + /// 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 + /// last, each checked against its original by + /// [`Store::claim`], once the original and both subjects are stored. + /// Issues `core.divergent` for the changes the revisions made diverge. + /// + /// # Errors + /// + /// Fails if an object is malformed, an acceptance, or needs an object + /// neither the pack nor the repository has, or one of another kind, if + /// a promotion doesn't + /// match its original, which leaves the other records stored, or if + /// the objects cannot be written. + pub fn put_records(&self, _caller: &Caller, pack: Pack) -> Result { + // Objects this finds stored stay until what refers to them is. + let _held = self.store.hold_objects()?; + let held: HashMap> = pack + .objects + .iter() + .map(|object| (object.id(), object.kind().ok())) + .collect(); + // Makes what the repository has of the dependencies durable before + // anything refers to them: their writers may not have yet. + let dependencies = self.store.batch(); + // The dependencies the repository has, whose kinds are read once + // every object is checked otherwise. + let mut stored: HashMap = HashMap::new(); + let mut snapshots = Vec::new(); + let mut statements = Vec::new(); + let mut revisions = Vec::new(); + let mut promotions = Vec::new(); + let mut changes = HashSet::new(); + for object in pack.objects { + let id = object.id(); + let decoded = object + .decode() + .map_err(|source| ServiceError::Malformed { id, source })?; + for (needed, kind) in Dependencies::of(&decoded) { + match held.get(&needed) { + Some(&held) if held != Some(kind) => { + return Err(ServiceError::WrongKind { id, needed, kind }); + } + Some(_) => {} + // Two objects needing it as different kinds can't both + // be right. + None if dependencies.depend(needed)? => match stored.entry(needed) { + Entry::Occupied(entry) if entry.get().1 != kind => { + return Err(ServiceError::WrongKind { id, needed, kind }); + } + Entry::Occupied(_) => {} + Entry::Vacant(entry) => { + entry.insert((id, kind)); + } + }, + None => return Err(ServiceError::Missing { id, needed }), + } + } + match decoded { + Object::Acceptance(_) => return Err(ServiceError::Acceptance(id.into())), + Object::Blob(_) | Object::Tree(_) => snapshots.push(object), + Object::Revision(revision) => { + if !revision.predecessors.is_empty() { + changes.insert(revision.change); + } + revisions.push(object); + } + Object::Statement(statement) if statement.promoted_from.is_some() => { + promotions.push((object, statement)); + } + Object::Statement(_) => statements.push(object), + } + } + self.check_kinds(&stored)?; + dependencies.commit()?; + let mut new = 0; + // Each layer durable before the next, as a workspace writes them: + // statements before the revisions they're about, so a crash never + // publishes a revision without its `core.conflict`. + for layer in [snapshots, statements, revisions] { + if !layer.is_empty() { + new += self.store.write_all(&layer)?; + } + } + // An original is never a promotion, so it's stored by now. + let mut checked = Vec::new(); + for (object, statement) in promotions { + let id = object.id().into(); + self.store + .claim(id, statement)? + .map_err(|invalid| ServiceError::Statement { + id, + source: Box::new(invalid.into()), + })?; + checked.push(object); + } + if !checked.is_empty() { + new += self.store.write_all(&checked)?; + } + if !changes.is_empty() { + self.annotations(|annotations| { + for &change in &changes { + annotations.flag_divergence(change, self.node.principal())?; + } + Ok(()) + })?; + } + Ok(Stored { new: new as u64 }) + } + + /// Checks that each object of `stored`, which the repository has, is of + /// the kind the object of the pack needing it names, reading them from + /// every core. + fn check_kinds( + &self, + stored: &HashMap, + ) -> Result<(), ServiceError> { + let stored: Vec<_> = stored.iter().collect(); + let checked = Store::::on_every_core(&stored, |chunk| { + for &(&needed, &(id, kind)) in chunk { + let object = self.store.read(needed)?; + if object.kind().ok() != Some(kind) { + return Err(ServiceError::WrongKind { id, needed, kind }); + } + } + Ok(()) + }); + checked.into_iter().collect() + } + /// The statements about `subject`, in the order the repository received /// them. /// @@ -336,6 +500,58 @@ impl OriginService { } } +/// What an object needs the repository to have for it to be usable, as +/// [`OriginService::put_records`] lists, and the kind each must be. A +/// revision's predecessors and a statement's payload are history and +/// details: the repository may lack them, and retention may have dropped a +/// payload. +struct Dependencies; + +impl Dependencies { + fn of(object: &Object) -> Vec<(ObjectId, ObjectKind)> { + match object { + Object::Blob(_) | Object::Acceptance(_) => Vec::new(), + Object::Tree(tree) => tree + .iter() + .map(|(_, entry)| (entry.id, entry.kind.object_kind())) + .collect(), + Object::Revision(revision) => { + let base = match revision.base { + Base::Acceptance(id) => (id.into(), ObjectKind::Acceptance), + Base::Revision(id) => (id.into(), ObjectKind::Revision), + }; + let mut needed = vec![ + (revision.snapshot.into(), ObjectKind::Tree), + (revision.description.into(), ObjectKind::Blob), + base, + ]; + needed.extend( + revision + .deps + .iter() + .map(|&id| (id.into(), ObjectKind::Revision)), + ); + needed + } + Object::Statement(statement) => Self::of_statement(statement), + } + } + + /// What a statement needs: its subject, and the statements it + /// supersedes or promotes. + fn of_statement(statement: &Statement) -> Vec<(ObjectId, ObjectKind)> { + let subject = (statement.subject.into(), statement.subject.kind()); + [Some(subject)] + .into_iter() + .chain( + [statement.supersedes, statement.promoted_from] + .map(|id| id.map(|id| (id.into(), ObjectKind::Statement))), + ) + .flatten() + .collect() + } +} + /// A failed service call. #[derive(Debug, thiserror::Error)] pub enum ServiceError { @@ -354,6 +570,47 @@ pub enum ServiceError { /// A target was proposed for landing without a target to land on. #[error("landing a target needs a target to land on")] NoTarget, + /// An object put isn't a well-formed object. + #[error("object {id} is malformed")] + Malformed { + /// The object. + id: ObjectId, + /// What is wrong. + source: DecodeError, + }, + /// An acceptance was put. + #[error( + "acceptance {0} cannot be put: only a target's authority writes acceptances, by landing" + )] + Acceptance(origin_shared::AcceptanceId), + /// An object put needs one neither the batch nor the repository has. + #[error("object {id} needs object {needed}, which neither the batch nor the repository has")] + Missing { + /// The object put. + id: ObjectId, + /// What it needs. + 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. + #[error("object {id} refers to {needed} as a {kind}, which it is not")] + WrongKind { + /// The object put. + id: ObjectId, + /// What it refers to. + needed: ObjectId, + /// The kind it must be. + kind: ObjectKind, + }, + /// A statement put isn't one the repository accepts: a promotion that + /// doesn't match its original. + #[error("statement {} cannot be put", .id.short())] + Statement { + /// The statement. + id: StatementId, + /// Why, boxed: it's large, and rare. + source: Box, + }, /// A landing failed. #[error(transparent)] Land(#[from] LandError), @@ -371,7 +628,15 @@ impl ServiceError { pub fn code(&self) -> ErrorCode { match self { Self::UnknownChange(_) | Self::UnknownTarget(_) => ErrorCode::NotFound, - Self::NoTarget => ErrorCode::BadRequest, + Self::NoTarget + | Self::Malformed { .. } + | Self::Acceptance(_) + | Self::Missing { .. } + | Self::WrongKind { .. } => ErrorCode::BadRequest, + Self::Statement { source, .. } => match &**source { + AnnotateError::Store(error) => Self::store_code(error), + _ => ErrorCode::BadRequest, + }, Self::Land(error) => match error { LandError::UnknownTarget(_) | LandError::UnknownChange(_) => ErrorCode::NotFound, LandError::TargetExists(_) @@ -403,8 +668,58 @@ impl ServiceError { #[cfg(test)] mod tests { + use origin_shared::{EncodedObject, Record, RepoPath}; + 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"); + 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 revision = origin_shared::Revision { + change: origin_shared::ChangeId::from_bytes([1; 16]), + predecessors: Vec::new(), + base: origin_shared::Base::Acceptance(repo.tip(&TargetName::MAIN).acceptance), + deps: Vec::new(), + snapshot: repo.files(&[("a", "<<<<<<<")]), + description: description.id().into(), + author: "user:ada".parse().unwrap(), + } + .encode(); + let conflicts = crate::conflict::Conflicts::new(vec![crate::conflict::Conflicted { + path: RepoPath::new("a").unwrap(), + written: None, + }]); + let subject = RecordId::Revision(revision.id().into()); + let (payload, conflict) = conflicts.statement(subject, "user:ada".parse().unwrap(), None); + let conflict = conflict.encode(); + let oplog = repo.store.oplog(); + let before = oplog.last_seq().unwrap(); + let objects = vec![description, payload, revision, conflict.clone()]; + service + .put_records(&Caller::Owner, Pack { objects }) + .unwrap(); + // A crash between the two finds the conflict alone, never the + // revision without it. + let entries = oplog.after(before).unwrap().entries; + let written = |record: RecordId| { + let written = |entry: &&crate::oplog::Entry| match &entry.effect { + crate::oplog::Effect::Wrote(written) => { + written.iter().any(|entry| entry.record() == record) + } + _ => false, + }; + entries.iter().find(written).unwrap().seq + }; + let conflict = RecordId::Statement(conflict.id().into()); + assert!(written(conflict) < written(subject)); + } + #[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 2c8c34d1..523e349f 100644 --- a/apps/origin-src/src/store/mod.rs +++ b/apps/origin-src/src/store/mod.rs @@ -507,14 +507,14 @@ pub struct Batch<'a, P> { /// What the index keeps of each new record staged, for the op log. entries: Mutex>, /// Whether the batch read the pack manifest, which it does before it - /// first trusts a pack to hold an object: see [`Batch::packed`]. + /// first looks an object up in the packs: see [`Batch::packed`]. manifest_read: Mutex, } impl Batch<'_, P> { /// Stages an object, unless the store already has it, returning whether /// it was new. Either way, it is durable once the batch commits. An - /// object packed since the packs were last loaded is staged again, and + /// object packed since the batch read the manifest is staged again, and /// the next compaction removes the copy. /// /// # Errors @@ -524,17 +524,7 @@ impl Batch<'_, P> { pub fn write(&self, object: &EncodedObject) -> Result { let id = object.id(); let path = self.store.path(id); - if path.exists() { - // Its writer may not have synced its directory yet, and the - // batch's objects may refer to it. - let mut shard = path; - shard.pop(); - self.write.sync_dir_with(shard); - return Ok(false); - } - if self.packed(id)? { - // The manifest naming its pack may not be durable yet. - self.write.sync_dir_with(self.store.packs_dir()); + if self.hold(&path, || self.packed(id))? { return Ok(false); } let entry = Entry::of(object).map_err(|source| StoreError::Decode { id, source })?; @@ -550,17 +540,50 @@ impl Batch<'_, P> { Ok(true) } + /// Whether the store has `id`, which an object of the batch refers to. + /// If it does, it is durable once the batch commits, like the batch's + /// own objects. + /// + /// # Errors + /// + /// Fails like [`Store::contains`]. + pub fn depend(&self, id: ObjectId) -> Result { + self.hold(&self.store.path(id), || { + Ok(self.packed(id)? || self.store.find_packed(id)?.is_some()) + }) + } + + /// Whether the store has the object whose loose file is `path`, or + /// that `packed` finds, making it durable with the batch if so: its + /// writer may not have synced its directory yet, nor the compactor the + /// manifest naming its pack. + fn hold( + &self, + path: &Path, + packed: impl FnOnce() -> Result, + ) -> Result { + if path.exists() { + let mut shard = path.to_owned(); + shard.pop(); + self.write.sync_dir_with(shard); + return Ok(true); + } + let packed = packed()?; + if packed { + self.write.sync_dir_with(self.store.packs_dir()); + } + Ok(packed) + } + /// Whether a pack holds `id`, as of a manifest read since the batch /// started. Packs loaded before may include one that garbage /// collection rewrote without the object since, and nothing may skip - /// writing an object that's gone. Once the batch read the manifest, - /// holding [`Store::hold_objects`] as writers that skip objects do, - /// only compactions replace it, and they keep every object. + /// writing an object that's gone; a process may also have loaded no + /// packs yet, and must not stage every packed object again. Once the + /// batch read the manifest, holding [`Store::hold_objects`] as writers + /// that skip objects do, only compactions replace it, and they keep + /// every object. fn packed(&self, id: ObjectId) -> Result { - // A miss only stages the object again, so it needs no fresh read. - if self.store.packs.find(id).is_none() { - return Ok(false); - } let mut read = self .manifest_read .lock() @@ -569,6 +592,8 @@ impl Batch<'_, P> { self.store.reload_packs()?; *read = true; } + // Lookups from every core needn't wait on each other. + drop(read); Ok(self.store.packs.find(id).is_some()) } @@ -772,6 +797,26 @@ pub(crate) mod tests { ); } + #[test] + fn dependencies_are_durable_with_the_batch() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path().join(".origin"), Recorder::default()); + store.init().unwrap(); + let blob = EncodedObject::blob(b"hello"); + store.write_all(slice::from_ref(&blob)).unwrap(); + store.platform.0.lock().unwrap().clear(); + + let batch = store.batch(); + assert!(batch.depend(blob.id()).unwrap()); + assert!(!batch.depend(EncodedObject::blob(b"absent").id()).unwrap()); + batch.commit().unwrap(); + let shard = store.path(blob.id()).parent().unwrap().to_owned(); + assert_eq!( + store.platform.0.into_inner().unwrap(), + [Synced::Batch(0), Synced::Dir(shard)] + ); + } + #[test] fn writes_and_reads_objects() { let (_dir, store) = store(); diff --git a/apps/origin-src/src/store/packs.rs b/apps/origin-src/src/store/packs.rs index eef13119..4df8ce59 100644 --- a/apps/origin-src/src/store/packs.rs +++ b/apps/origin-src/src/store/packs.rs @@ -843,16 +843,28 @@ mod tests { let (_dir, store) = store(); let objects = objects(0, 10); store.write_all(&objects).unwrap(); - store.compact().unwrap(); - // A writer that hasn't loaded the packs writes them again. + // A batch that read the manifest before a compaction packed them + // writes them again. let unaware = Store::new(&store.root, Native::default()); - assert_eq!(unaware.write_all(&objects[..3]).unwrap(), 3); + let batch = unaware.batch(); + assert!(batch.write(&EncodedObject::blob(b"first")).unwrap()); + store.compact().unwrap(); + for object in &objects[..3] { + assert!(batch.write(object).unwrap()); + } + batch.commit().unwrap(); let compaction = store.compact().unwrap().unwrap(); assert_eq!(compaction.duplicates, 3); - assert_eq!(compaction.packed, 0); + assert_eq!(compaction.packed, 1); assert!(!store.path(objects[0].id()).exists()); assert_readable(&store, &objects); + + // A later batch reads the manifest, even in a process that never + // loaded the packs. + let fresh = Store::new(&store.root, Native::default()); + assert_eq!(fresh.write_all(&objects).unwrap(), 0); + assert!(!store.path(objects[0].id()).exists()); } #[test] diff --git a/crates/origin-shared/src/lib.rs b/crates/origin-shared/src/lib.rs index 25b563b9..23a5239f 100644 --- a/crates/origin-shared/src/lib.rs +++ b/crates/origin-shared/src/lib.rs @@ -7,6 +7,7 @@ mod id; pub mod landing; mod name; pub mod object; +pub mod pack; mod path; pub mod policy; mod principal; diff --git a/crates/origin-shared/src/object/tree.rs b/crates/origin-shared/src/object/tree.rs index 5a1ea5f6..c33226fd 100644 --- a/crates/origin-shared/src/object/tree.rs +++ b/crates/origin-shared/src/object/tree.rs @@ -73,6 +73,16 @@ impl EntryKind { pub fn is_tree(self) -> bool { self == Self::Tree } + + /// The kind of object the entry points to: a tree, or a blob. + #[must_use] + pub fn object_kind(self) -> ObjectKind { + if self.is_tree() { + ObjectKind::Tree + } else { + ObjectKind::Blob + } + } } impl fmt::Display for EntryKind { diff --git a/crates/origin-shared/src/pack.rs b/crates/origin-shared/src/pack.rs new file mode 100644 index 00000000..d9b76202 --- /dev/null +++ b/crates/origin-shared/src/pack.rs @@ -0,0 +1,110 @@ +//! The binary format objects travel in. +//! +//! A pack is a sequence of entries, each +//! `id:[u8; 32] len:u64 bytes:[u8; len]` with `bytes` the object's encoding. +//! Decoding verifies every object against its id, so a pack can come from an +//! untrusted peer. + +use std::collections::HashSet; + +use crate::object::{DecodeError, IdMismatch, Reader}; +use crate::{EncodedObject, ObjectId}; + +/// A batch of objects. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Pack { + /// The objects, in the order they were added. + pub objects: Vec, +} + +impl Pack { + const HEADER_LEN: usize = ObjectId::LEN + 8; + + /// Encodes the pack. + #[must_use] + pub fn encode(&self) -> Vec { + let len = self + .objects + .iter() + .map(|object| Self::HEADER_LEN + object.bytes().len()) + .sum(); + let mut out = Vec::with_capacity(len); + for object in &self.objects { + out.extend_from_slice(object.id().as_bytes()); + out.extend_from_slice(&(object.bytes().len() as u64).to_le_bytes()); + out.extend_from_slice(object.bytes()); + } + out + } + + /// Decodes and verifies a pack, keeping each object once: one sent + /// twice is stored and counted once. + /// + /// # Errors + /// + /// Fails if the pack is truncated or an object does not match its id. + pub fn decode(bytes: &[u8]) -> Result { + let mut reader = Reader::new(bytes); + let mut objects = Vec::new(); + let mut seen = HashSet::new(); + while reader.remaining() > 0 { + let id = ObjectId::from_bytes(reader.array()?); + // A length past the address space is past the end of the pack. + let len = usize::try_from(reader.u64()?).unwrap_or(usize::MAX); + let object = EncodedObject::verify(id, reader.take(len)?.to_vec())?; + if seen.insert(id) { + objects.push(object); + } + } + Ok(Self { objects }) + } +} + +/// Bytes that are not a valid pack. +#[derive(Debug, thiserror::Error)] +pub enum PackError { + /// The pack is not a sequence of whole entries: it ended in the middle + /// of one. + #[error("cannot decode pack")] + Malformed(#[from] DecodeError), + /// An object does not match its id. + #[error(transparent)] + Corrupt(#[from] IdMismatch), +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trips() { + let pack = Pack { + objects: vec![EncodedObject::blob(b"a"), EncodedObject::blob(b"")], + }; + assert_eq!(Pack::decode(&pack.encode()).unwrap(), pack); + assert_eq!(Pack::decode(&[]).unwrap(), Pack::default()); + } + + #[test] + fn keeps_each_object_once() { + let blob = EncodedObject::blob(b"a"); + let pack = Pack { + objects: vec![blob.clone(), blob.clone()], + }; + assert_eq!(Pack::decode(&pack.encode()).unwrap().objects, vec![blob]); + } + + #[test] + fn rejects_truncated_and_corrupt_packs() { + let mut bytes = Pack { + objects: vec![EncodedObject::blob(b"content")], + } + .encode(); + assert!(matches!( + Pack::decode(&bytes[..bytes.len() - 1]), + Err(PackError::Malformed(DecodeError::Truncated)) + )); + *bytes.last_mut().unwrap() ^= 1; + assert!(matches!(Pack::decode(&bytes), Err(PackError::Corrupt(_)))); + } +}