Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 56 additions & 7 deletions apps/origin-src/src/queue/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -38,22 +38,27 @@
//! start from it.
//!
//! Each target's queue lives in `queue/<target id>/`. 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-<id>` or `target-<target id>`, 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,
TreeId,
};

use crate::annotations::{AnnotateError, Annotations};
use crate::conflict::Conflicts;
use crate::policy::{Policy, PolicyError, Requirement};
use crate::store::{Store, StoreError};
use crate::targets::Head;
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
///
Expand All @@ -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);
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<P>) -> Result<Vec<Pending>, 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::<io::Result<Vec<_>>>()
.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::<P>::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.
Expand Down
95 changes: 95 additions & 0 deletions apps/origin-src/src/queue/pending.rs
Original file line number Diff line number Diff line change
@@ -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 <target>`, `change <id>`
/// or `target <name>`, and `subject <kind> <id>`. Then either a
/// `missing <kind> <verdict> <issuer>` line for each requirement the
/// landing lacks, or a `conflict <statement>` 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<Self> {
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,
})
}
}
37 changes: 37 additions & 0 deletions apps/origin-src/src/queue/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -149,6 +152,7 @@ impl<P: Platform> 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);
Expand Down Expand Up @@ -240,6 +244,7 @@ impl<P: Platform> Session<'_, '_, P> {
subject: candidate.subject,
blocked: Blocked::Evidence(missing),
};
self.keep(&pending)?;
return Ok(Landing::Pending(pending));
}

Expand Down Expand Up @@ -269,6 +274,7 @@ impl<P: Platform> Session<'_, '_, P> {
self.policy = policy;
self.policy_head = id;
}
self.forget(&candidate.proposal)?;
Ok(Landing::Landed {
proposal: candidate.proposal,
source: candidate.source,
Expand Down Expand Up @@ -322,9 +328,40 @@ impl<P: Platform> 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<PathBuf, StoreError> {
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
Expand Down
61 changes: 59 additions & 2 deletions apps/origin-src/src/queue/tests/changes.rs
Original file line number Diff line number Diff line change
@@ -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::*;

Expand Down Expand Up @@ -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");
Expand All @@ -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(), []);
}
5 changes: 5 additions & 0 deletions apps/origin-src/src/queue/tests/conflicts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Loading
Loading