diff --git a/apps/origin-src/src/conflict.rs b/apps/origin-src/src/conflict.rs index be1af632..51df17ca 100644 --- a/apps/origin-src/src/conflict.rs +++ b/apps/origin-src/src/conflict.rs @@ -24,6 +24,10 @@ //! `describe`, a new change on top, or a merge) gets its own //! `core.conflict` listing the paths still unresolved. It is published //! before the revision, so the revision is never seen without it. +//! +//! The landing queue also issues a `core.conflict`, as a node, when a +//! revision does not rebase onto its target. That statement only blocks +//! landing on that target; each retry merges again. use origin_platform::Platform; use origin_shared::{ diff --git a/apps/origin-src/src/queue/mod.rs b/apps/origin-src/src/queue/mod.rs index 92298a53..01b93433 100644 --- a/apps/origin-src/src/queue/mod.rs +++ b/apps/origin-src/src/queue/mod.rs @@ -1,15 +1,46 @@ //! The landing queue: how a target's authority lands changes on the target, -//! one acceptance at a time. [`Queue::init`] starts a repository's history -//! and checks the policy it begins with. +//! one acceptance at a time. +//! +//! Landing a change lands its stack: the head of each change below it that +//! the target does not have yet, from the bottom up, each with its own +//! acceptance. A divergent change is refused. Landing stops at the first +//! change that waits. For each revision: +//! +//! 1. **Rebase.** The changes the revision made to its base are merged onto +//! the target's tip, file by file ([`Store::merge`]). A revision made on +//! the tip lands as it is; this node rebases any other into a new +//! revision of its change, on the tip. If the merge would leave the +//! target unchanged, nothing lands: the target already has the change. +//! 2. **Conflicts.** If both sides changed a path, a `core.conflict` +//! statement about the revision lists the paths, and the change waits +//! until a new revision of it merges. +//! 3. **Policy.** The policy in force must name this node as the target's +//! authority. +//! 4. **Otherwise** this node signs an acceptance naming what landed and +//! the policy, and appends it to the target's chain. +//! +//! Each target's queue lives in `queue//`. It holds a `lock`, +//! taken while landing so landings on one target never race. -use origin_platform::{Native, Platform}; +mod session; + +use std::fmt; +use std::fs; +use std::path::PathBuf; + +use origin_platform::{LockMode, LockedFile, Native, Platform}; use origin_shared::{ - AcceptanceBody, AcceptanceId, EncodedObject, NodeKey, PrincipalName, Record, TargetName, Tree, + AcceptanceBody, AcceptanceId, ChangeId, EncodedObject, NodeKey, Principal, PrincipalName, + Record, RecordId, RepoPath, RevisionId, Source, StatementId, TargetId, TargetName, Tree, TreeId, }; +use crate::annotations::{AnnotateError, Annotations}; use crate::policy::{Policy, PolicyError}; use crate::store::{Store, StoreError}; +use crate::targets::Head; + +use session::Session; /// The landing queues of a store's targets, run by one node. #[derive(Debug)] @@ -19,6 +50,57 @@ pub struct Queue<'a, P = Native> { node: PrincipalName, } +/// What a landing lands. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Proposal { + /// A change, as of its head. + Change(ChangeId), +} + +/// The outcome of a landing. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Landing { + /// It landed. + Landed { + /// What landed. + proposal: Proposal, + /// The revision the acceptance names. + source: Source, + /// The acceptance. + acceptance: Head, + }, + /// The target already has it, so nothing landed. + Unchanged(Proposal), + /// It waits. + Pending(Pending), +} + +/// A landing that waits. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Pending { + /// The target it lands on. + pub onto: TargetName, + /// What lands. + pub proposal: Proposal, + /// The revision that didn't merge. + pub subject: RecordId, + /// Why it waits. + pub blocked: Blocked, +} + +/// Why a landing waits. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Blocked { + /// Both sides changed these paths. The `core.conflict` statement lists + /// them too. + Conflict { + /// The statement. + statement: StatementId, + /// The paths, sorted. + paths: Vec, + }, +} + impl<'a, P: Platform> Queue<'a, P> { /// Returns the queues of `store`, run by the node `node`, which signs with /// `key`. @@ -26,6 +108,12 @@ impl<'a, P: Platform> Queue<'a, P> { Self { store, key, node } } + /// Returns this node as a principal: the issuer of the statements and the + /// author of the revisions the queue makes. + fn principal(&self) -> Principal { + Principal::Node(self.node.clone()) + } + /// Starts a repository's history: creates the `policy` target, holding /// `policy` as its `policy.toml`, and an empty `main`. The policy must make /// this node the authority of both. Returns `main`'s first acceptance. @@ -65,6 +153,37 @@ impl<'a, P: Platform> Queue<'a, P> { )?) } + /// Lands `change` and the changes below it that `onto` does not have yet, + /// from the bottom of the stack up, and returns the outcome of each. Stops + /// at the first one that waits. + /// + /// # Errors + /// + /// Fails if this node is not the target's authority, a change in the stack + /// is divergent, or the records cannot be read or written. + pub fn land_change( + &self, + change: ChangeId, + onto: &TargetName, + ) -> Result, LandError> { + let mut session = self.session(onto)?; + let stack = session.stack(change)?; + if stack.is_empty() { + return Ok(vec![Landing::Unchanged(Proposal::Change(change))]); + } + let proposal = Proposal::Change(change); + let mut landings = Vec::new(); + for (id, revision) in stack { + let landing = session.land_revision(&proposal, id, revision)?; + let waits = matches!(landing, Landing::Pending(_)); + landings.push(landing); + if waits { + break; + } + } + Ok(landings) + } + /// Returns the policy in `state`, which is about to come into force, if it /// is valid and names an authority for `policy`. Without one, no one could /// ever land on `policy` again. @@ -78,6 +197,34 @@ impl<'a, P: Platform> Queue<'a, P> { Ok(policy) } + /// The name of the lock file in each target's queue. + const LOCK: &str = "lock"; + + /// Returns the directory of `target`'s queue, durably creating it if it is + /// missing. + fn queue_dir(&self, target: TargetId) -> Result { + let root = self.store.queue_dir(); + let dir = root.join(target.to_hex()); + if !dir.is_dir() { + fs::create_dir_all(&dir).map_err(|source| StoreError::io(&dir, source))?; + for parent in [&root, root.parent().unwrap_or(&root)] { + self.store.sync_dir(parent)?; + } + } + Ok(dir) + } + + /// Locks the queue of `target`, waiting for any landing in progress to + /// finish. + fn lock(&self, target: &TargetName) -> Result { + let path = self.queue_dir(target.id())?.join(Self::LOCK); + Ok(LockedFile::open( + &self.store.platform, + &path, + LockMode::Exclusive, + )?) + } + /// Checks that `policy` makes this node the authority of `target`, with /// this node's key. fn authorize(&self, policy: &Policy, target: &TargetName) -> Result<(), LandError> { @@ -96,11 +243,43 @@ impl<'a, P: Platform> Queue<'a, P> { } Ok(()) } + + /// Starts landing on `onto`: locks its queue, then reads the policy in + /// force and the target's tip. + fn session(&self, onto: &TargetName) -> Result, LandError> { + let lock = self.lock(onto)?; + let tip = self + .store + .head(onto)? + .ok_or_else(|| LandError::UnknownTarget(onto.clone()))?; + let (policy_head, policy) = Policy::in_force(self.store)?; + self.authorize(&policy, onto)?; + Ok(Session { + queue: self, + onto: onto.clone(), + policy_head, + state: self.store.get(tip.acceptance)?.body().state, + tip, + annotations: Annotations::open(self.store)?, + _lock: lock, + }) + } +} + +impl fmt::Display for Proposal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Change(change) => write!(f, "change {}", change.short()), + } + } } /// A failure to land. #[derive(Debug, thiserror::Error)] pub enum LandError { + /// No target has this name. + #[error("no target is named `{0}`")] + UnknownTarget(TargetName), /// The policy names no authority for the target. #[error("policy.toml names no authority for `{0}`: give it, or `policy`, a [targets] table")] NoAuthority(TargetName), @@ -120,10 +299,36 @@ pub enum LandError { /// The policy lists a different key for this node. #[error("policy.toml lists another key for node:{0} than this node's")] WrongKey(PrincipalName), + /// No revision of the change is known. + #[error("change {} has no revisions", .0.short())] + UnknownChange(ChangeId), + /// The change has several heads. + #[error( + "change {} is divergent, so it cannot land: its heads are {}. Run `origin converge {}` \ + first", + change.short(), + heads.iter().map(RevisionId::short).collect::>().join(", "), + change.short() + )] + Divergent { + /// The change. + change: ChangeId, + /// Its heads. + heads: Vec, + }, /// Landing on `policy` would leave it without a valid policy. #[error("landing would leave `policy` without a valid policy.toml")] InvalidPolicy(#[source] PolicyError), + /// The policy in force cannot be read. + #[error(transparent)] + Policy(#[from] PolicyError), + /// A conflict cannot be recorded. + #[error(transparent)] + Annotate(#[from] AnnotateError), /// Records cannot be read or written. #[error(transparent)] Store(#[from] StoreError), } + +#[cfg(test)] +mod tests; diff --git a/apps/origin-src/src/queue/session.rs b/apps/origin-src/src/queue/session.rs new file mode 100644 index 00000000..423195b0 --- /dev/null +++ b/apps/origin-src/src/queue/session.rs @@ -0,0 +1,226 @@ +//! Landing one candidate: rebasing it onto the target's tip, then appending +//! its acceptance, or keeping it waiting on a conflict. + +use std::collections::HashSet; + +use origin_platform::{LockedFile, Platform}; +use origin_shared::{ + AcceptanceBody, AcceptanceId, Base, ChangeId, EncodedObject, Kind, Record, RecordId, Revision, + RevisionId, Source, TargetName, TreeId, +}; + +use crate::annotations::Annotations; +use crate::conflict::Conflicts; +use crate::store::{Store, StoreError}; +use crate::targets::Head; + +use super::{Blocked, LandError, Landing, Pending, Proposal, Queue}; + +/// Landings onto one target, made while holding its queue's lock. +pub(super) struct Session<'q, 'a, P> { + pub(super) queue: &'q Queue<'a, P>, + pub(super) onto: TargetName, + /// The acceptance of `policy` holding the policy in force. + pub(super) policy_head: AcceptanceId, + /// The target's latest acceptance, and its snapshot. + pub(super) tip: Head, + pub(super) state: TreeId, + pub(super) annotations: Annotations<'a, P>, + pub(super) _lock: LockedFile, +} + +/// What a session is about to land. +pub(super) struct Candidate { + /// What lands. + pub(super) proposal: Proposal, + pub(super) source: Source, + /// The target's snapshot once it lands. + pub(super) state: TreeId, + /// The trees the merge made, to write first. + pub(super) trees: Vec, + /// The rebased revision, if there is one, to write after the trees. + pub(super) revision: Option, +} + +impl Session<'_, '_, P> { + fn store(&self) -> &Store

{ + self.queue.store + } + + /// Returns the heads to land for `change`, bottom first: the change's head + /// and, following each one's base downward, the heads of the changes the + /// target does not have yet. + pub(super) fn stack(&self, change: ChangeId) -> Result, LandError> { + let index = self.annotations.index(); + let mut stack = Vec::new(); + let mut seen = HashSet::new(); + let mut next = Some(change); + while let Some(change) = next.take() { + if !seen.insert(change) { + break; + } + let head = match index.heads(change)[..] { + [head] => head, + [] => return Err(LandError::UnknownChange(change)), + ref heads => { + return Err(LandError::Divergent { + change, + heads: heads.to_vec(), + }); + } + }; + let revision: Revision = self.store().get(head)?; + if self.has_landed(head, &revision)? { + break; + } + if let Base::Revision(below) = revision.base { + next = Some(self.store().get(below)?.change); + } + stack.push((head, revision)); + } + stack.reverse(); + Ok(stack) + } + + /// Whether the revision `id` landed on the target. A revision only lands on + /// the tip it is based on, so this checks the acceptance after that tip. + fn has_landed(&self, id: RevisionId, revision: &Revision) -> Result { + let Base::Acceptance(base) = revision.base else { + return Ok(false); + }; + let base = self.store().get(base)?; + if base.body().target != self.onto.id() { + return Ok(false); + } + let Some(next) = self + .store() + .acceptance_at(&self.onto, base.body().seq + 1)? + else { + return Ok(false); + }; + Ok(self + .store() + .get(next)? + .body() + .landed + .contains(&Source::Revision(id))) + } + + /// Rebases the revision `id` onto the tip and lands it, as part of the + /// landing of `stack`. If it has to wait, the queue keeps `stack` waiting. + pub(super) fn land_revision( + &mut self, + stack: &Proposal, + id: RevisionId, + revision: Revision, + ) -> Result { + let proposal = Proposal::Change(revision.change); + let base = match revision.base { + Base::Acceptance(id) => self.store().get(id)?.body().state, + Base::Revision(id) => self.store().get(id)?.snapshot, + }; + let merge = self + .store() + .merge(Some(base), revision.snapshot, self.state)?; + if !merge.conflicts.is_empty() { + return self.block(stack.clone(), RecordId::Revision(id), &merge.conflicts); + } + if merge.tree == self.state { + return Ok(Landing::Unchanged(proposal)); + } + let tip = Base::Acceptance(self.tip.acceptance); + if revision.base == tip { + return self.submit(Candidate { + proposal, + source: Source::Revision(id), + state: merge.tree, + trees: merge.trees, + revision: None, + }); + } + let rebased = Revision { + predecessors: vec![id], + base: tip, + snapshot: merge.tree, + author: self.queue.principal(), + ..revision + } + .encode(); + let rebased_id = RevisionId::from(rebased.id()); + self.submit(Candidate { + proposal, + source: Source::Revision(rebased_id), + state: merge.tree, + trees: merge.trees, + revision: Some(rebased), + }) + } + + /// Lands `candidate`. Writes the records in layers, each durable before the + /// next refers to it: first the trees, then the rebased revision and the + /// acceptance. + pub(super) fn submit(&mut self, candidate: Candidate) -> Result { + let store = self.queue.store; + if !candidate.trees.is_empty() { + store.write_all(&candidate.trees)?; + } + let mut records: Vec = candidate.revision.into_iter().collect(); + let acceptance = AcceptanceBody { + target: self.onto.id(), + seq: self.tip.seq + 1, + prev: Some(self.tip.acceptance), + state: candidate.state, + landed: vec![candidate.source], + evidence: Vec::new(), + policy: Some(self.policy_head), + } + .sign(self.queue.key); + records.push(acceptance.encode()); + store.write_all(&records)?; + let id = store.append(&self.onto, &acceptance)?; + self.tip = Head { + seq: acceptance.body().seq, + acceptance: id, + }; + self.state = candidate.state; + Ok(Landing::Landed { + proposal: candidate.proposal, + source: candidate.source, + acceptance: self.tip, + }) + } + + /// Blocks a landing on `conflicts` and keeps it waiting. Issues a + /// `core.conflict` statement about `subject` listing them, unless this + /// node's latest one already lists the same. + pub(super) fn block( + &mut self, + proposal: Proposal, + subject: RecordId, + conflicts: &Conflicts, + ) -> Result { + let issuer = self.queue.principal(); + let current = self + .annotations + .current(subject, &Kind::CONFLICT, &issuer)?; + let (payload, conflict) = conflicts.statement(subject, issuer, current); + let unchanged = match current { + Some(id) => self.store().get(id)?.payload == conflict.payload, + None => false, + }; + let statement = match current { + Some(id) if unchanged => id, + _ => self.annotations.issue(&conflict, Some(payload))?, + }; + let pending = Pending { + onto: self.onto.clone(), + proposal, + subject, + blocked: Blocked::Conflict { + statement, + paths: conflicts.paths(), + }, + }; + Ok(Landing::Pending(pending)) + } +} diff --git a/apps/origin-src/src/queue/tests/changes.rs b/apps/origin-src/src/queue/tests/changes.rs new file mode 100644 index 00000000..5952d66e --- /dev/null +++ b/apps/origin-src/src/queue/tests/changes.rs @@ -0,0 +1,127 @@ +//! Tests for landing changes: rebasing, stacks, and who may land. + +use std::sync::Mutex; +use std::thread; + +use super::*; + +#[test] +fn lands_rebases_and_skips_what_the_target_has() { + let repo = Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); + let a = repo.change_on_main(1, &[("a", "a")]); + let b = repo.change_on_main(2, &[("b", "b")]); + + let [landing] = &repo.land(1)[..] else { + panic!() + }; + assert_eq!(landed(landing), a, "made on the tip, it lands as it is"); + let acceptance = repo + .store + .get(repo.tip(&TargetName::MAIN).acceptance) + .unwrap(); + acceptance.verify(&repo.key.public()).unwrap(); + assert_eq!( + acceptance.body().policy, + Some(repo.tip(&TargetName::POLICY).acceptance) + ); + + let [landing] = &repo.land(2)[..] else { + panic!() + }; + let rebased = landed(landing); + assert_ne!(rebased, b, "made on an older tip, it is rebased"); + let revision = repo.store.get(rebased).unwrap(); + assert_eq!(revision.predecessors, [b]); + assert_eq!(revision.author, "node:queue".parse().unwrap()); + let log = repo.store.log(&TargetName::MAIN).unwrap(); + assert_eq!( + revision.base, + Base::Acceptance(log[1]), + "on the tip it landed after" + ); + assert_eq!( + repo.state(&TargetName::MAIN), + repo.files(&[("a", "a"), ("b", "b")]) + ); + + // Both changes are on `main` now: neither lands again, though `b`'s + // head is the rebased revision and `a`'s the original. + assert_eq!(repo.land(1), [Landing::Unchanged(change(1))]); + assert_eq!(repo.land(2), [Landing::Unchanged(change(2))]); + assert_eq!(repo.tip(&TargetName::MAIN).seq, 2); +} + +#[test] +fn stacks_land_from_the_bottom() { + let repo = Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); + let below = repo.change_on_main(1, &[("a", "a")]); + let above = repo.revision(2, &[], Base::Revision(below), &[("a", "a"), ("b", "b")]); + let landings = repo.land(2); + assert_eq!(landings.len(), 2, "{landings:?}"); + assert_eq!(landed(&landings[0]), below); + assert_ne!(landed(&landings[1]), above, "rebased onto the first"); + assert_eq!( + repo.state(&TargetName::MAIN), + repo.files(&[("a", "a"), ("b", "b")]) + ); +} + +#[test] +fn refuses_divergent_changes() { + let repo = Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); + let first = repo.change_on_main(1, &[("a", "a")]); + let base = Base::Acceptance(repo.tip(&TargetName::MAIN).acceptance); + repo.revision(1, &[first], base, &[("a", "left")]); + repo.revision(1, &[first], base, &[("a", "right")]); + let main = TargetName::MAIN; + let error = repo + .queue() + .land_change(ChangeId::from_bytes([1; 16]), &main) + .unwrap_err(); + assert!(matches!(error, LandError::Divergent { .. }), "{error}"); +} + +#[test] +fn only_the_authority_lands() { + let repo = Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); + repo.change_on_main(1, &[("a", "a")]); + let change = ChangeId::from_bytes([1; 16]); + let other = Queue::new(&repo.store, &repo.key, PrincipalName::new("other").unwrap()); + let error = other.land_change(change, &TargetName::MAIN).unwrap_err(); + assert!(matches!(error, LandError::NotAuthority { .. }), "{error}"); + + let impostor = NodeKey::from_bytes(&[8; 32]); + let queue = Queue::new(&repo.store, &impostor, PrincipalName::new("queue").unwrap()); + let error = queue.land_change(change, &TargetName::MAIN).unwrap_err(); + assert!(matches!(error, LandError::WrongKey(_)), "{error}"); + assert_eq!(repo.tip(&TargetName::MAIN).seq, 0); +} + +#[test] +fn concurrent_landings_serialize() { + let repo = Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); + let (proposers, each) = (6_u8, 3_u8); + let changes: Vec = (0..proposers * each).map(|change| change + 1).collect(); + for &change in &changes { + repo.change_on_main(change, &[(&format!("file-{change}"), "x")]); + } + let landed = Mutex::new(0); + thread::scope(|scope| { + for chunk in changes.chunks(usize::from(each)) { + let (repo, landed) = (&repo, &landed); + scope.spawn(move || { + for &change in chunk { + assert!(matches!(repo.land(change)[..], [Landing::Landed { .. }])); + *landed.lock().unwrap() += 1; + } + }); + } + }); + assert_eq!(*landed.lock().unwrap(), changes.len()); + let log = repo.store.log(&TargetName::MAIN).unwrap(); + assert_eq!(log.len(), changes.len() + 1); + for pair in log.windows(2) { + assert_eq!(repo.store.get(pair[1]).unwrap().body().prev, Some(pair[0])); + } + assert_eq!(repo.main_files().len(), changes.len(), "every file landed"); +} diff --git a/apps/origin-src/src/queue/tests/conflicts.rs b/apps/origin-src/src/queue/tests/conflicts.rs new file mode 100644 index 00000000..c944b97e --- /dev/null +++ b/apps/origin-src/src/queue/tests/conflicts.rs @@ -0,0 +1,28 @@ +//! Tests for landings that conflict, and for what lets them through. + +use super::*; + +#[test] +fn conflicts_block_until_a_revision_merges() { + let repo = Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); + repo.change_on_main(1, &[("shared", "one")]); + let two = repo.change_on_main(2, &[("shared", "two")]); + repo.land(1); + + let blocked = repo.land(2); + let [Landing::Pending(pending)] = &blocked[..] else { + panic!("{blocked:?}") + }; + assert_eq!(pending.subject, RecordId::Revision(two)); + let Blocked::Conflict { statement, paths } = &pending.blocked; + assert_eq!(paths, &[RepoPath::new("shared").unwrap()]); + let conflict = repo.store.get(*statement).unwrap(); + assert_eq!(conflict.kind, Kind::CONFLICT); + assert_eq!(conflict.subject, RecordId::Revision(two)); + assert_eq!(repo.land(2), blocked, "retrying issues the same statement"); + + // A new revision that takes `main`'s version merges. + let tip = Base::Acceptance(repo.tip(&TargetName::MAIN).acceptance); + repo.revision(2, &[two], tip, &[("shared", "one"), ("more", "m")]); + assert!(matches!(repo.land(2)[..], [Landing::Landed { .. }])); +} diff --git a/apps/origin-src/src/queue/tests/mod.rs b/apps/origin-src/src/queue/tests/mod.rs new file mode 100644 index 00000000..12a8336b --- /dev/null +++ b/apps/origin-src/src/queue/tests/mod.rs @@ -0,0 +1,155 @@ +//! The queue's tests, grouped by topic, and the test repository they share. + +mod changes; +mod conflicts; + +use origin_platform::Native; +use origin_shared::BlobId; +use origin_shared::{ + Base, ChangeId, EncodedObject, Kind, NodeKey, PrincipalName, Record, RecordId, RepoPath, + Revision, RevisionId, Source, TargetName, TreeId, +}; + +use super::*; +use crate::store::Store; +use crate::targets::Head; +use crate::tree::tests::build; + +/// A test repository whose `policy` and `main` targets the node `queue` +/// orders. `Repo::new` adds `extra` to its `policy.toml`. +struct Repo { + _dir: tempfile::TempDir, + store: Store, + key: NodeKey, +} + +impl Repo { + fn new(extra: &str) -> Self { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path().join(".origin"), Native::default()); + store.init().unwrap(); + let key = NodeKey::from_bytes(&[7; 32]); + let repo = Self { + _dir: dir, + store, + key, + }; + repo.queue().init(&repo.policy_toml(extra)).unwrap(); + repo + } + + /// Returns a `policy.toml` that makes this node the authority of `policy`, + /// followed by `extra`. + fn policy_toml(&self, extra: &str) -> String { + format!( + "[nodes]\nqueue = \"{}\"\n[targets.policy]\nauthority = \"node:queue\"\n{extra}", + self.key.public() + ) + } + + /// Writes a snapshot of `files`, with their contents, and returns its tree. + fn files(&self, files: &[(&str, &str)]) -> TreeId { + let blobs: Vec<_> = files + .iter() + .map(|(_, content)| EncodedObject::blob(content.as_bytes())) + .collect(); + self.store.write_all(&blobs).unwrap(); + build(&self.store, files) + } + + fn queue(&self) -> Queue<'_> { + Queue::new(&self.store, &self.key, PrincipalName::new("queue").unwrap()) + } + + fn tip(&self, target: &TargetName) -> Head { + self.store.head(target).unwrap().unwrap() + } + + fn state(&self, target: &TargetName) -> TreeId { + self.store + .get(self.tip(target).acceptance) + .unwrap() + .body() + .state + } + + /// Writes a revision of `change` with `files`, made on `base`. + fn revision( + &self, + change: u8, + predecessors: &[RevisionId], + base: Base, + files: &[(&str, &str)], + ) -> RevisionId { + let encoded = Revision { + change: ChangeId::from_bytes([change; 16]), + predecessors: predecessors.to_vec(), + base, + deps: Vec::new(), + snapshot: self.files(files), + description: BlobId::from(EncodedObject::blob(b"").id()), + author: "user:ada".parse().unwrap(), + } + .encode(); + self.store + .write_all(std::slice::from_ref(&encoded)) + .unwrap(); + encoded.id().into() + } + + /// Writes a revision of the new change `change` on the tip of `main`, + /// adding `files` to `main`'s files. + fn change_on_main(&self, change: u8, files: &[(&str, &str)]) -> RevisionId { + let base = Base::Acceptance(self.tip(&TargetName::MAIN).acceptance); + let mut all = self.main_files(); + all.extend( + files + .iter() + .map(|&(path, content)| (path.to_owned(), content.to_owned())), + ); + let all: Vec<_> = all.iter().map(|(p, c)| (p.as_str(), c.as_str())).collect(); + self.revision(change, &[], base, &all) + } + + /// Returns the files of `main`'s tip, with their contents. + fn main_files(&self) -> Vec<(String, String)> { + let empty = build(&self.store, &[]); + self.store + .diff(empty, self.state(&TargetName::MAIN)) + .unwrap() + .into_iter() + .map(|change| { + let content = self + .store + .try_blob(change.new.unwrap().id) + .unwrap() + .unwrap(); + ( + change.path.as_str().to_owned(), + String::from_utf8(content).unwrap(), + ) + }) + .collect() + } + + fn land(&self, change: u8) -> Vec { + self.queue() + .land_change(ChangeId::from_bytes([change; 16]), &TargetName::MAIN) + .unwrap() + } +} + +fn change(id: u8) -> Proposal { + Proposal::Change(ChangeId::from_bytes([id; 16])) +} + +/// Returns the revision a landing landed. Panics if it landed no revision. +fn landed(landing: &Landing) -> RevisionId { + match landing { + Landing::Landed { + source: Source::Revision(revision), + .. + } => *revision, + other => panic!("expected a landed revision, got {other:?}"), + } +} diff --git a/apps/origin-src/src/store/mod.rs b/apps/origin-src/src/store/mod.rs index ed782a13..1318e04e 100644 --- a/apps/origin-src/src/store/mod.rs +++ b/apps/origin-src/src/store/mod.rs @@ -1,27 +1,23 @@ -//! A repository's storage on disk, under its `.origin` directory: -//! content-addressed objects here, and target chains in -//! [`targets`](crate::targets). +//! A repository's storage on disk, under its `.origin` directory. This +//! module stores content-addressed objects; [`targets`](crate::targets) +//! stores target chains, and [`queue`](crate::queue) pending landings. //! -//! Each object lives in its own zstd-compressed file at +//! Each object is a zstd-compressed file at //! `objects/loose//`. Objects are -//! written in batches through a [`DurableWrite`]: every file of a batch is -//! staged beside its destination, then the batch is synced at once, renamed -//! into place and its directories synced, so a batch costs one batch sync -//! and one sync per directory. Once [`Batch::commit`] returns, the objects -//! survive a crash, so anything that refers to them can be published. +//! written in batches through a [`DurableWrite`]: each file is staged next +//! to its destination, then the whole batch is synced, renamed into place, +//! and its directories are synced. Once [`Batch::commit`] returns, the +//! objects survive a crash, so records that refer to them can be published. //! Readers never see a partial object, and concurrent writers of the same -//! object are harmless. A batch that finds an object already there syncs -//! its directory too, since the writer that put it there may not have yet. -//! Writers that crash leave temporary files behind, which -//! [`Store::remove_stale_temps`] removes. Garbage collection -//! ([`Store::gc`]) calls it, so opening a store never pays for a walk over -//! every object. +//! object do no harm. Writers that crash leave temporary files behind; +//! [`Store::remove_stale_temps`] removes them, and garbage collection +//! ([`Store::gc`]) calls it. //! -//! [`Store::compact`] moves small loose objects into [`packs`], and reads -//! look in the loose objects first, then in the packs. +//! [`Store::compact`] moves small loose objects into [`packs`]. Reads look in +//! the loose objects first, then in the packs. //! -//! Committing a batch also indexes its new records, see -//! [`index`](crate::index). +//! Committing a batch also indexes its new records (see +//! [`index`](crate::index)). use std::fs; use std::io; @@ -185,6 +181,10 @@ impl Store

{ self.root.join("index") } + pub(crate) fn queue_dir(&self) -> PathBuf { + self.root.join("queue") + } + pub(crate) fn path(&self, id: ObjectId) -> PathBuf { let hex = id.to_hex(); let mut path = self.loose(); diff --git a/apps/origin-src/src/targets.rs b/apps/origin-src/src/targets.rs index 05209177..3b912d8b 100644 --- a/apps/origin-src/src/targets.rs +++ b/apps/origin-src/src/targets.rs @@ -20,6 +20,7 @@ use std::fmt; use std::fs::{self, File}; use std::io::{self, Read, Seek, SeekFrom, Write}; +use std::os::unix::fs::FileExt; use std::path::{Path, PathBuf}; use std::slice; @@ -177,6 +178,32 @@ impl Store

{ Ok(log) } + /// Returns the acceptance at position `seq` of `target`'s log, or `None` if + /// none is published there yet. Reads one line of the log. + /// + /// # Errors + /// + /// Fails if the target's files cannot be read or are malformed. + pub fn acceptance_at( + &self, + target: &TargetName, + seq: u64, + ) -> Result, StoreError> { + let files = self.target_files(target.id()); + let Some(head) = files.read_head()? else { + return Ok(None); + }; + if seq >= head.seq { + return Ok((seq == head.seq).then_some(head.acceptance)); + } + let path = files.log(); + let mut line = [0; TargetFiles::LINE]; + File::open(&path) + .and_then(|log| log.read_exact_at(&mut line, seq * TargetFiles::LINE as u64)) + .map_err(|source| StoreError::io(&path, source))?; + Ok(files.parse_log(&line)?.first().copied()) + } + /// The names of every target, in no particular order. /// /// # Errors @@ -363,6 +390,10 @@ mod tests { }) ); assert_eq!(store.log(&main).unwrap(), ids); + for (seq, &id) in (0..).zip(&ids) { + assert_eq!(store.acceptance_at(&main, seq).unwrap(), Some(id)); + } + assert_eq!(store.acceptance_at(&main, 3).unwrap(), None); let last = store.get(ids[2]).unwrap(); assert_eq!(last.body().prev, Some(ids[1])); last.verify(&key().public()).unwrap();