diff --git a/apps/origin-src/src/queue/mod.rs b/apps/origin-src/src/queue/mod.rs index 92d8318a..6453a2f7 100644 --- a/apps/origin-src/src/queue/mod.rs +++ b/apps/origin-src/src/queue/mod.rs @@ -5,8 +5,8 @@ //! the target does not have yet, from the bottom up, each with its own //! acceptance. A change that is divergent, abandoned by its creator, or //! whose head has unresolved conflicts (see [`conflict`](crate::conflict)) -//! is refused. Landing stops at the first change that waits. For each -//! revision: +//! is refused. If a change waits, the queue keeps the whole stack waiting, +//! so a retry lands the rest once that change can land. 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 @@ -38,15 +38,19 @@ //! start from it. //! //! Each target's queue lives in `queue//`. It holds a `lock`, -//! taken while landing so landings on one target never race. +//! taken while landing so landings on one target never race, and a file for +//! each waiting landing, `change-` or `target-`, so waiting +//! landings can be listed and retried. +mod pending; mod session; use std::fmt; use std::fs; +use std::io; use std::path::PathBuf; -use origin_platform::{LockMode, LockedFile, Native, Platform}; +use origin_platform::{DurableWrite, LockMode, LockedFile, Native, Platform}; use origin_shared::{ AcceptanceBody, AcceptanceId, ChangeId, EncodedObject, NodeKey, Principal, PrincipalName, Record, RecordId, RepoPath, RevisionId, Source, StatementId, TargetId, TargetName, Tree, @@ -54,6 +58,7 @@ use origin_shared::{ }; use crate::annotations::{AnnotateError, Annotations}; +use crate::conflict::Conflicts; use crate::policy::{Policy, PolicyError, Requirement}; use crate::store::{Store, StoreError}; use crate::targets::Head; @@ -91,11 +96,11 @@ pub enum Landing { }, /// The target already has it, so nothing landed. Unchanged(Proposal), - /// It waits. + /// It waits, and the queue keeps it. Pending(Pending), } -/// A landing that waits. +/// A landing that waits, kept in the queue to be listed and retried. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Pending { /// The target it lands on. @@ -179,7 +184,8 @@ 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. + /// at the first one that waits, which the queue keeps as a landing of + /// `change`, so retrying it lands the rest of the stack once that one can. /// /// # Errors /// @@ -194,6 +200,7 @@ impl<'a, P: Platform> Queue<'a, P> { let mut session = self.session(onto)?; let stack = session.stack(change)?; if stack.is_empty() { + session.forget(&Proposal::Change(change))?; return Ok(vec![Landing::Unchanged(Proposal::Change(change))]); } let proposal = Proposal::Change(change); @@ -245,6 +252,7 @@ impl<'a, P: Platform> Queue<'a, P> { let [ours, theirs] = tips; let either = history.descends(ours, theirs) || history.descends(theirs, ours); if merge.tree == session.state && either { + session.forget(&proposal)?; return Ok(Landing::Unchanged(proposal)); } // Even a merge that changes nothing lands, so that the tip is in @@ -292,6 +300,47 @@ impl<'a, P: Platform> Queue<'a, P> { Ok(Head { seq: 0, acceptance }) } + /// Returns every waiting landing, on every target, sorted by target. + /// + /// # Errors + /// + /// Fails if the queues cannot be listed, or if a landing cannot be read or + /// is malformed. + pub fn pending(store: &Store

) -> Result, StoreError> { + let root = store.queue_dir(); + let list = |dir: &PathBuf| match fs::read_dir(dir) { + Ok(entries) => entries + .map(|entry| entry.map(|entry| entry.path())) + .collect::>>() + .map_err(|source| StoreError::io(dir, source)), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Vec::new()), + Err(source) => Err(StoreError::io(dir, source)), + }; + let mut pending = Vec::new(); + for dir in list(&root)? { + for path in list(&dir)? { + let name = path.file_name().unwrap_or_default(); + if name == Self::LOCK || DurableWrite::

::is_temporary(name) { + continue; + } + // Read without the lock: a landing that just ended forgot it. + let text = match fs::read_to_string(&path) { + Ok(text) => text, + Err(error) if error.kind() == io::ErrorKind::NotFound => continue, + Err(source) => return Err(StoreError::io(&path, source)), + }; + let mut landing = + Pending::decode(&text).ok_or_else(|| StoreError::Malformed(path.clone()))?; + if let Blocked::Conflict { statement, paths } = &mut landing.blocked { + *paths = Conflicts::listed(store, &store.get(*statement)?)?.paths(); + } + pending.push(landing); + } + } + pending.sort_by(|a, b| a.onto.cmp(&b.onto)); + Ok(pending) + } + /// 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. diff --git a/apps/origin-src/src/queue/pending.rs b/apps/origin-src/src/queue/pending.rs new file mode 100644 index 00000000..95495fb8 --- /dev/null +++ b/apps/origin-src/src/queue/pending.rs @@ -0,0 +1,95 @@ +//! The file that keeps a waiting landing, in the queue's directory, until +//! the landing can continue. + +use origin_shared::RecordId; + +use crate::policy::Requirement; + +use super::{Blocked, Pending, Proposal}; + +impl Pending { + /// The first line of every file keeping a waiting landing. + const HEADER: &str = "origin pending 1"; + + /// Encodes the landing as lines: the header, `onto `, `change ` + /// or `target `, and `subject `. Then either a + /// `missing ` line for each requirement the + /// landing lacks, or a `conflict ` line naming the statement + /// whose payload lists the conflicting paths. + pub(super) fn encode(&self) -> String { + let mut lines = vec![Self::HEADER.to_owned(), format!("onto {}", self.onto)]; + lines.push(match &self.proposal { + Proposal::Change(change) => format!("change {change}"), + Proposal::Target(target) => format!("target {target}"), + }); + let (kind, id) = match self.subject { + RecordId::Snapshot(id) => ("snapshot", id.to_hex()), + RecordId::Revision(id) => ("revision", id.to_hex()), + RecordId::Statement(id) => ("statement", id.to_hex()), + RecordId::Acceptance(id) => ("acceptance", id.to_hex()), + }; + lines.push(format!("subject {kind} {id}")); + match &self.blocked { + Blocked::Evidence(missing) => lines.extend(missing.iter().map(|requirement| { + format!( + "missing {} {} {}", + requirement.kind, requirement.verdict, requirement.issuer + ) + })), + Blocked::Conflict { statement, .. } => lines.push(format!("conflict {statement}")), + } + lines.join("\n") + "\n" + } + + /// Decodes what [`Pending::encode`] wrote, or returns `None` if it is + /// malformed. A conflict comes back with no paths, since the file holds + /// only the statement listing them. + pub(super) fn decode(text: &str) -> Option { + let mut lines = text.lines(); + if lines.next()? != Self::HEADER { + return None; + } + let onto = lines.next()?.strip_prefix("onto ")?.parse().ok()?; + let proposal = match lines.next()?.split_once(' ')? { + ("change", id) => Proposal::Change(id.parse().ok()?), + ("target", name) => Proposal::Target(name.parse().ok()?), + _ => return None, + }; + let subject = match lines.next()?.strip_prefix("subject ")?.split_once(' ')? { + ("snapshot", id) => RecordId::Snapshot(id.parse().ok()?), + ("revision", id) => RecordId::Revision(id.parse().ok()?), + ("statement", id) => RecordId::Statement(id.parse().ok()?), + ("acceptance", id) => RecordId::Acceptance(id.parse().ok()?), + _ => return None, + }; + let mut missing = Vec::new(); + let mut conflict = None; + for line in lines { + match line.split_once(' ')? { + ("missing", requirement) => { + let mut fields = requirement.split(' '); + missing.push(Requirement { + kind: fields.next()?.parse().ok()?, + verdict: fields.next()?.parse().ok()?, + issuer: fields.next()?.parse().ok()?, + }); + } + ("conflict", id) => conflict = Some(id.parse().ok()?), + _ => return None, + } + } + let blocked = match conflict { + Some(statement) => Blocked::Conflict { + statement, + paths: Vec::new(), + }, + None => Blocked::Evidence(missing), + }; + Some(Self { + onto, + proposal, + subject, + blocked, + }) + } +} diff --git a/apps/origin-src/src/queue/session.rs b/apps/origin-src/src/queue/session.rs index c44b8bb5..72894294 100644 --- a/apps/origin-src/src/queue/session.rs +++ b/apps/origin-src/src/queue/session.rs @@ -3,6 +3,9 @@ //! it waiting. use std::collections::HashSet; +use std::fs; +use std::io; +use std::path::PathBuf; use origin_platform::{LockedFile, Platform}; use origin_shared::{ @@ -149,6 +152,7 @@ impl Session<'_, '_, P> { return self.block(stack.clone(), RecordId::Revision(id), &merge.conflicts); } if merge.tree == self.state { + self.forget(&proposal)?; return Ok(Landing::Unchanged(proposal)); } let tip = Base::Acceptance(self.tip.acceptance); @@ -240,6 +244,7 @@ impl Session<'_, '_, P> { subject: candidate.subject, blocked: Blocked::Evidence(missing), }; + self.keep(&pending)?; return Ok(Landing::Pending(pending)); } @@ -269,6 +274,7 @@ impl Session<'_, '_, P> { self.policy = policy; self.policy_head = id; } + self.forget(&candidate.proposal)?; Ok(Landing::Landed { proposal: candidate.proposal, source: candidate.source, @@ -322,9 +328,40 @@ impl Session<'_, '_, P> { paths: conflicts.paths(), }, }; + self.keep(&pending)?; Ok(Landing::Pending(pending)) } + /// Returns the path of the file that keeps a waiting landing of `proposal`. + fn pending_path(&self, proposal: &Proposal) -> Result { + let name = match proposal { + Proposal::Change(change) => format!("change-{change}"), + Proposal::Target(target) => format!("target-{}", target.id()), + }; + Ok(self.queue.queue_dir(self.onto.id())?.join(name)) + } + + /// Durably writes a waiting landing to its file, replacing the last + /// attempt's. + fn keep(&self, pending: &Pending) -> Result<(), StoreError> { + let write = self.store().durable_write(); + write.stage( + self.pending_path(&pending.proposal)?, + pending.encode().as_bytes(), + )?; + Ok(write.commit()?) + } + + /// Durably deletes the file of a landing that waited, if there is one. + pub(super) fn forget(&self, proposal: &Proposal) -> Result<(), StoreError> { + let path = self.pending_path(proposal)?; + match fs::remove_file(&path) { + Ok(()) => self.store().sync_dir(path.parent().unwrap_or(&path)), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), + Err(source) => Err(StoreError::io(&path, source)), + } + } + /// Reads the history of `tips`, the target's tip and another target's, for /// [merging](Ancestry::merge_base) the other target from the newest /// acceptance both histories share. An acceptance's parents are the diff --git a/apps/origin-src/src/queue/tests/changes.rs b/apps/origin-src/src/queue/tests/changes.rs index fac45acd..3950d700 100644 --- a/apps/origin-src/src/queue/tests/changes.rs +++ b/apps/origin-src/src/queue/tests/changes.rs @@ -1,9 +1,10 @@ -//! Tests for landing changes: rebasing, stacks, and who may land. +//! Tests for landing changes: rebasing, stacks, who may land, and keeping a +//! landing that waits. use std::sync::Mutex; use std::thread; -use origin_shared::Statement; +use origin_shared::{Statement, Verdict}; use super::*; @@ -146,6 +147,31 @@ fn concurrent_landings_serialize() { assert_eq!(repo.main_files().len(), changes.len(), "every file landed"); } +#[test] +fn pending_landings_round_trip() { + let pending = Pending { + onto: TargetName::new("release/v3").unwrap(), + proposal: Proposal::Target(TargetName::MAIN), + subject: RecordId::Snapshot(Tree::default().encode().id().into()), + blocked: Blocked::Evidence(vec![Requirement { + kind: Kind::new("ci.test").unwrap(), + verdict: Verdict::Pass, + issuer: "group:runners".parse().unwrap(), + }]), + }; + assert_eq!(Pending::decode(&pending.encode()), Some(pending.clone())); + let conflict = Pending { + proposal: change(9), + blocked: Blocked::Conflict { + statement: EncodedObject::blob(b"conflict").id().into(), + paths: Vec::new(), + }, + ..pending + }; + assert_eq!(Pending::decode(&conflict.encode()), Some(conflict)); + assert_eq!(Pending::decode("origin pending 2\n"), None); +} + #[test] fn only_the_creator_of_a_change_abandons_it() { let repo = Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); @@ -165,3 +191,34 @@ fn only_the_creator_of_a_change_abandons_it() { .unwrap(); assert!(matches!(repo.land(1)[..], [Landing::Landed { .. }])); } + +#[test] +fn a_waiting_stack_lands_whole_once_it_can() { + let repo = requiring_ci(); + let lower = repo.change_on_main(1, &[("a", "a")]); + repo.revision(2, &[], Base::Revision(lower), &[("a", "a"), ("b", "b")]); + let [Landing::Pending(pending)] = &repo.land(2)[..] else { + panic!("the lower change waits") + }; + assert_eq!(pending.subject, RecordId::Revision(lower)); + assert_eq!( + Queue::pending(&repo.store).unwrap(), + [Pending { + proposal: change(2), + ..pending.clone() + }], + "kept as the landing of the whole stack" + ); + + // Retrying it, as once the evidence arrives, lands both: the result + // is promoted to the upper change, which doesn't change `src`. + let annotations = Annotations::open(&repo.store).unwrap(); + annotations.issue(&ci_test(lower, "user:ci"), None).unwrap(); + let landings = repo.land(2); + assert_eq!(landed(&landings[0]), lower); + assert!( + matches!(landings[1], Landing::Landed { proposal: ref p, .. } if *p == change(2)), + "{landings:?}" + ); + assert_eq!(Queue::pending(&repo.store).unwrap(), []); +} diff --git a/apps/origin-src/src/queue/tests/conflicts.rs b/apps/origin-src/src/queue/tests/conflicts.rs index 585eba56..84005566 100644 --- a/apps/origin-src/src/queue/tests/conflicts.rs +++ b/apps/origin-src/src/queue/tests/conflicts.rs @@ -23,11 +23,16 @@ fn conflicts_block_until_a_revision_merges() { assert_eq!(conflict.kind, Kind::CONFLICT); assert_eq!(conflict.subject, RecordId::Revision(two)); assert_eq!(repo.land(2), blocked, "retrying issues the same statement"); + assert_eq!( + Queue::pending(&repo.store).unwrap(), + std::slice::from_ref(pending) + ); // 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 { .. }])); + assert_eq!(Queue::pending(&repo.store).unwrap(), []); } #[test] diff --git a/apps/origin-src/src/queue/tests/evidence.rs b/apps/origin-src/src/queue/tests/evidence.rs index 57a2aa53..fe57ab04 100644 --- a/apps/origin-src/src/queue/tests/evidence.rs +++ b/apps/origin-src/src/queue/tests/evidence.rs @@ -17,6 +17,10 @@ fn missing_evidence_waits_and_promoted_results_count() { panic!("{waiting:?}") }; assert!(matches!(&pending.blocked, Blocked::Evidence(missing) if missing.len() == 1)); + assert_eq!( + Queue::pending(&repo.store).unwrap(), + std::slice::from_ref(pending) + ); // A user outside the group doesn't count; the runner does. let annotations = Annotations::open(&repo.store).unwrap(); @@ -34,6 +38,7 @@ fn missing_evidence_waits_and_promoted_results_count() { .unwrap(); assert_eq!(landed(landing), code); assert_eq!(acceptance.body().evidence, [result]); + assert_eq!(Queue::pending(&repo.store).unwrap(), []); // The docs change is rebased onto `src` as tested, so the result is // promoted to it, and counts as the runner's. diff --git a/apps/origin-src/src/queue/tests/mod.rs b/apps/origin-src/src/queue/tests/mod.rs index 3381f9b0..46e80349 100644 --- a/apps/origin-src/src/queue/tests/mod.rs +++ b/apps/origin-src/src/queue/tests/mod.rs @@ -10,13 +10,13 @@ use origin_platform::Native; use origin_shared::{ AcceptanceBody, Base, BlobId, ChangeId, Digest, EncodedObject, Inputs, Kind, NodeKey, PrincipalName, Record, RecordId, RepoPath, Revision, RevisionId, Source, Statement, - StatementId, TargetName, TreeId, Verdict, + StatementId, TargetName, Tree, TreeId, Verdict, }; use super::*; use crate::annotations::Annotations; use crate::conflict::Conflicts; -use crate::policy::{Policy, PolicyError}; +use crate::policy::{Policy, PolicyError, Requirement}; use crate::store::Store; use crate::targets::Head; use crate::tree::tests::build;