From dfa0c9bbd42243ecdba178dbc23e386a71a30049 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 16:03:52 +0100 Subject: [PATCH] feat(queue): retry waiting landings when their evidence arrives A landing that waited for evidence stayed waiting until someone ran `origin land` again, even once the statements it lacked were issued. A CI worker answering it couldn't make it continue. The queue now keeps who submitted each waiting landing, with their token's scope and expiry, and the service retries the landings waiting for evidence about a subject whenever statements about it arrive, for their submitter, under the policy in force then. A failed or refused retry is logged and leaves the landing waiting: the statements stand. A server retries every waiting landing when it opens a repository, since a crash may have cut a retry short. A landing whose submitter's token expired is no longer retried: it waits until someone lands it again, and `origin land --status` says so. `origin annotate` goes through the service, so it resumes landings too. --- README.md | 7 +- apps/origin-src/src/permissions.rs | 12 ++ apps/origin-src/src/queue/mod.rs | 57 +++++-- apps/origin-src/src/queue/pending.rs | 62 +++++-- apps/origin-src/src/queue/session.rs | 10 +- apps/origin-src/src/queue/tests/changes.rs | 33 +++- apps/origin-src/src/queue/tests/evidence.rs | 8 +- apps/origin-src/src/queue/tests/mod.rs | 1 + apps/origin-src/src/server.rs | 10 +- apps/origin-src/src/service.rs | 173 +++++++++++++++++--- apps/origin-src/src/sync.rs | 34 ++++ apps/origin-src/src/workspace/annotate.rs | 7 +- apps/origin-src/src/workspace/land.rs | 17 +- apps/origin-src/tests/cli.rs | 11 +- apps/origin-src/tests/http.rs | 23 ++- crates/origin-shared/src/access.rs | 3 +- crates/origin-shared/src/landing.rs | 14 ++ docs/openapi.json | 9 + 18 files changed, 414 insertions(+), 77 deletions(-) diff --git a/README.md b/README.md index 93abbb1b..8cbc954d 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,8 @@ change), and appends an acceptance signed by your node, which must be the target's authority. A landing that conflicts or lacks evidence waits: issue the statements, or a new revision, and run `origin land` again. Policy is a target too: edit it with `origin new --on policy`, then `origin land`. +Issuing a statement a waiting landing lacks, to the repository that orders +its target, lets it continue: the queue retries it for whoever submitted it. Workspaces work like git worktrees: each has its own current change and shares the repository's records, so agents can work side by side. A new @@ -178,7 +180,10 @@ for a token acting for you with a narrower scope, such as `write src`, without storing it. A server's operator signs one for any principal with `origin token issue --config origin-server.toml --as user:agent-1 --scope ...`. A token never grants more than its principal's rights, lasts at most -7 days, and a token issued with a token expires with it. +7 days, and a token issued with a token expires with it. A landing that +waits is retried for its submitter when its evidence arrives, until their +token expires: then `origin land --status` says so, and it waits for +someone to land it again. `converge` merges the files of a change's heads. A text file two heads changed holds both versions between conflict markers (`<<<<<<<`, `=======`, diff --git a/apps/origin-src/src/permissions.rs b/apps/origin-src/src/permissions.rs index b0169d47..b8b965b0 100644 --- a/apps/origin-src/src/permissions.rs +++ b/apps/origin-src/src/permissions.rs @@ -83,6 +83,18 @@ pub struct Scope { } impl Caller { + /// When the caller's token expires, in seconds since the Unix epoch, if + /// it's a scoped one. + #[must_use] + pub fn expires(&self) -> Option { + match self { + Self::Principal { + scope: Some(scope), .. + } => Some(scope.expires), + Self::Principal { scope: None, .. } | Self::Owner | Self::Anonymous => None, + } + } + /// Who the caller is, unless the owner or anonymous. #[must_use] pub fn principal(&self) -> Option<&Principal> { diff --git a/apps/origin-src/src/queue/mod.rs b/apps/origin-src/src/queue/mod.rs index b1f9cf11..1c4e99fb 100644 --- a/apps/origin-src/src/queue/mod.rs +++ b/apps/origin-src/src/queue/mod.rs @@ -27,7 +27,9 @@ //! with the same input digest are promoted to it first, and a valid //! promotion claims what its original does, as its original's issuer. //! 4. **Missing evidence** leaves the landing waiting, until the statements -//! are issued and the landing is retried. +//! are issued and the landing is retried, for its submitter, under the +//! policy in force then: the [service](crate::service) retries it +//! whenever statements about its subject arrive. //! 5. **Otherwise** this node signs an acceptance naming what landed, the //! evidence and the policy, and appends it to the target's chain. //! @@ -43,8 +45,8 @@ //! //! The queue of each target lives in `queue//`: a `lock` held //! while landing, so landings on one target never race, and a file for each -//! landing that waits, `change-` or `target-`, so waiting -//! landings can be listed and retried. +//! landing that waits, `change-` or `target-`, naming its +//! submitter, so waiting landings can be listed and retried. mod pending; mod session; @@ -64,7 +66,7 @@ use origin_shared::{ use crate::annotations::{AnnotateError, Annotations}; use crate::conflict::Conflicts; -use crate::permissions::Forbidden; +use crate::permissions::{Caller, Forbidden}; use crate::policy::{Policy, PolicyError}; use crate::store::{Store, StoreError}; @@ -77,8 +79,19 @@ pub struct Queue<'a, P = Native> { store: &'a Store

, key: &'a NodeKey, node: PrincipalName, + /// Who submits the landings, which a waiting one is retried for. + submitter: Caller, /// What the submitter may do with each path. - submitter: PathAccess, + paths: PathAccess, +} + +/// A landing that waits, and who submitted it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Waiting { + /// The landing. + pub pending: Pending, + /// Its submitter, whose rights it lands with when it's retried. + pub submitter: Caller, } impl<'a, P: Platform> Queue<'a, P> { @@ -89,16 +102,18 @@ impl<'a, P: Platform> Queue<'a, P> { store, key, node, - submitter: PathAccess::uniform(Level::Write), + submitter: Caller::Owner, + paths: PathAccess::uniform(Level::Write), } } - /// The queues, landing for a submitter who may do `paths`: everything, - /// by default. + /// The queues, landing for `submitter`, who may do `paths`: the owner, + /// who may do everything, by default. #[must_use] - pub fn submitted_by(self, paths: PathAccess) -> Self { + pub fn submitted_by(self, submitter: Caller, paths: PathAccess) -> Self { Self { - submitter: paths, + submitter, + paths, ..self } } @@ -297,9 +312,21 @@ impl<'a, P: Platform> Queue<'a, P> { /// /// # Errors /// + /// Fails like [`Queue::waiting`]. + pub fn pending(store: &Store

) -> Result, StoreError> { + Ok(Self::waiting(store)? + .into_iter() + .map(|waiting| waiting.pending) + .collect()) + } + + /// Every landing that waits, with its submitter, sorted by target. + /// + /// # Errors + /// /// Fails if the queues cannot be listed, or a landing cannot be read or /// is malformed. - pub fn pending(store: &Store

) -> Result, StoreError> { + pub fn waiting(store: &Store

) -> Result, StoreError> { let root = store.queue_dir(); let list = |dir: &PathBuf| match fs::read_dir(dir) { Ok(entries) => entries @@ -322,15 +349,15 @@ impl<'a, P: Platform> Queue<'a, P> { Err(error) if error.kind() == io::ErrorKind::NotFound => continue, Err(source) => return Err(StoreError::io(&path, source)), }; - let mut landing = PendingFile::decode(&text) + let mut waiting = PendingFile::decode(&text) .ok_or_else(|| StoreError::Malformed(path.clone()))?; - if let Blocked::Conflict { statement, paths } = &mut landing.blocked { + if let Blocked::Conflict { statement, paths } = &mut waiting.pending.blocked { *paths = Conflicts::listed(store, &store.get(*statement)?)?.paths(); } - pending.push(landing); + pending.push(waiting); } } - pending.sort_by(|a, b| a.onto.cmp(&b.onto)); + pending.sort_by(|a, b| a.pending.onto.cmp(&b.pending.onto)); Ok(pending) } diff --git a/apps/origin-src/src/queue/pending.rs b/apps/origin-src/src/queue/pending.rs index cf239fcf..e00beb43 100644 --- a/apps/origin-src/src/queue/pending.rs +++ b/apps/origin-src/src/queue/pending.rs @@ -5,6 +5,10 @@ use origin_shared::RecordId; use origin_shared::landing::{Blocked, Pending, Proposal}; use origin_shared::policy::Requirement; +use crate::permissions::{Caller, Scope}; + +use super::Waiting; + /// The format of the files keeping waiting landings. pub(super) struct PendingFile; @@ -13,10 +17,13 @@ impl PendingFile { const HEADER: &str = "origin pending 1"; /// Encodes the landing as lines: the header, `onto `, `change - /// ` or `target `, `subject `, then a `missing - /// ` line for each requirement it lacks, or - /// `conflict `, whose payload lists the paths. - pub(super) fn encode(pending: &Pending) -> String { + /// ` or `target `, `subject `, `by owner` or `by + /// ` for its submitter, then if their token is scoped, an + /// `expires ` line and a `scope ` line for each of + /// its capabilities, then a + /// `missing ` line for each requirement it + /// lacks, or `conflict `, whose payload lists the paths. + pub(super) fn encode(pending: &Pending, submitter: &Caller) -> String { let mut lines = vec![Self::HEADER.to_owned(), format!("onto {}", pending.onto)]; lines.push(match &pending.proposal { Proposal::Change(change) => format!("change {change}"), @@ -29,6 +36,18 @@ impl PendingFile { RecordId::Acceptance(id) => ("acceptance", id.to_hex()), }; lines.push(format!("subject {kind} {id}")); + match submitter { + Caller::Principal { principal, scope } => { + lines.push(format!("by {principal}")); + if let Some(scope) = scope { + lines.push(format!("expires {}", scope.expires)); + let capabilities = scope.capabilities.iter(); + lines.extend(capabilities.map(|capability| format!("scope {capability}"))); + } + } + // Anonymous callers never land. + Caller::Owner | Caller::Anonymous => lines.push("by owner".to_owned()), + } match &pending.blocked { Blocked::Evidence(missing) => lines.extend(missing.iter().map(|requirement| { format!( @@ -43,7 +62,7 @@ impl PendingFile { /// Decodes what [`PendingFile::encode`] wrote, without the conflicting /// paths, or `None` if it's malformed. - pub(super) fn decode(text: &str) -> Option { + pub(super) fn decode(text: &str) -> Option { let mut lines = text.lines(); if lines.next()? != Self::HEADER { return None; @@ -61,10 +80,18 @@ impl PendingFile { ("acceptance", id) => RecordId::Acceptance(id.parse().ok()?), _ => return None, }; + let principal = match lines.next()?.strip_prefix("by ")? { + "owner" => None, + principal => Some(principal.parse().ok()?), + }; + let mut expires = None; + let mut capabilities = Vec::new(); let mut missing = Vec::new(); let mut conflict = None; for line in lines { match line.split_once(' ')? { + ("expires", at) => expires = Some(at.parse().ok()?), + ("scope", capability) => capabilities.push(capability.parse().ok()?), ("missing", requirement) => { let mut fields = requirement.split(' '); missing.push(Requirement { @@ -84,11 +111,26 @@ impl PendingFile { }, None => Blocked::Evidence(missing), }; - Some(Pending { - onto, - proposal, - subject, - blocked, + if expires.is_none() && !capabilities.is_empty() { + return None; + } + let scope = expires.map(|expires| Scope { + capabilities, + expires, + }); + let submitter = match principal { + Some(principal) => Caller::Principal { principal, scope }, + None => Caller::Owner, + }; + Some(Waiting { + pending: Pending { + onto, + proposal, + subject, + blocked, + expires, + }, + submitter, }) } } diff --git a/apps/origin-src/src/queue/session.rs b/apps/origin-src/src/queue/session.rs index 2eb1e015..470bc468 100644 --- a/apps/origin-src/src/queue/session.rs +++ b/apps/origin-src/src/queue/session.rs @@ -199,9 +199,9 @@ impl Session<'_, '_, P> { if !candidate.trees.is_empty() { store.write_all(&candidate.trees)?; } - if !self.queue.submitter.writes_all() { + if !self.queue.paths.writes_all() { for change in store.diff(self.state, candidate.state)? { - if !self.queue.submitter.writes(&change.path) { + if !self.queue.paths.writes(&change.path) { return Err(Forbidden::Write(change.path).into()); } } @@ -229,7 +229,7 @@ impl Session<'_, '_, P> { store.write_all(&records)?; records.clear(); // Only from what the submitter sees. - let mut reader = Reader::new(store, &self.queue.submitter); + let mut reader = Reader::new(store, &self.queue.paths); let promotions = self.annotations.promotions( candidate.subject, &self.queue.principal(), @@ -257,6 +257,7 @@ impl Session<'_, '_, P> { proposal: candidate.kept_as, subject: candidate.subject, blocked: Blocked::Evidence(missing), + expires: self.queue.submitter.expires(), }; self.keep(&pending)?; return Ok(Landing::Pending(pending)); @@ -340,6 +341,7 @@ impl Session<'_, '_, P> { statement, paths: conflicts.paths(), }, + expires: self.queue.submitter.expires(), }; self.keep(&pending)?; Ok(Landing::Pending(pending)) @@ -360,7 +362,7 @@ impl Session<'_, '_, P> { let write = self.store().durable_write(); write.stage( self.pending_path(&pending.proposal)?, - PendingFile::encode(pending).as_bytes(), + PendingFile::encode(pending, &self.queue.submitter).as_bytes(), )?; let waiting = Effect::Waiting { onto: pending.onto.clone(), diff --git a/apps/origin-src/src/queue/tests/changes.rs b/apps/origin-src/src/queue/tests/changes.rs index 28769a43..9ecffa24 100644 --- a/apps/origin-src/src/queue/tests/changes.rs +++ b/apps/origin-src/src/queue/tests/changes.rs @@ -170,10 +170,15 @@ fn pending_landings_round_trip() { verdict: Verdict::Pass, issuer: "group:runners".parse().unwrap(), }]), + expires: None, + }; + let owner = Waiting { + pending: pending.clone(), + submitter: Caller::Owner, }; assert_eq!( - PendingFile::decode(&PendingFile::encode(&pending)), - Some(pending.clone()) + PendingFile::decode(&PendingFile::encode(&pending, &Caller::Owner)), + Some(owner) ); let conflict = Pending { proposal: change(9), @@ -183,10 +188,26 @@ fn pending_landings_round_trip() { }, ..pending }; - assert_eq!( - PendingFile::decode(&PendingFile::encode(&conflict)), - Some(conflict) - ); + let scoped = |capabilities: &[&str]| Waiting { + pending: Pending { + expires: Some(1_900_000_000), + ..conflict.clone() + }, + submitter: Caller::Principal { + principal: "user:agent".parse().unwrap(), + scope: Some(Scope { + capabilities: capabilities.iter().map(|c| c.parse().unwrap()).collect(), + expires: 1_900_000_000, + }), + }, + }; + // A token scoped to nothing stays scoped. + for scoped in [scoped(&["write src", "land *"]), scoped(&[])] { + assert_eq!( + PendingFile::decode(&PendingFile::encode(&scoped.pending, &scoped.submitter)), + Some(scoped) + ); + } assert_eq!(PendingFile::decode("origin pending 2\n"), None); } diff --git a/apps/origin-src/src/queue/tests/evidence.rs b/apps/origin-src/src/queue/tests/evidence.rs index cbec373f..f49aaaef 100644 --- a/apps/origin-src/src/queue/tests/evidence.rs +++ b/apps/origin-src/src/queue/tests/evidence.rs @@ -126,7 +126,13 @@ fn promotes_only_what_the_submitter_sees() { let blind = PathAccess::new(Level::Write, [(secrets, Level::None)]); let waiting = repo .queue() - .submitted_by(blind) + .submitted_by( + Caller::Principal { + principal: "user:eve".parse().unwrap(), + scope: None, + }, + blind, + ) .land_change( &mut repo.annotations(), ChangeId::from_bytes([2; 16]), diff --git a/apps/origin-src/src/queue/tests/mod.rs b/apps/origin-src/src/queue/tests/mod.rs index 93100034..66512310 100644 --- a/apps/origin-src/src/queue/tests/mod.rs +++ b/apps/origin-src/src/queue/tests/mod.rs @@ -19,6 +19,7 @@ use origin_shared::{ use super::*; use crate::annotations::Annotations; use crate::conflict::Conflicts; +use crate::permissions::{Caller, Scope}; use crate::policy::{Policy, PolicyError}; use crate::store::Store; use crate::tree::tests::build; diff --git a/apps/origin-src/src/server.rs b/apps/origin-src/src/server.rs index 60bbc9c1..38da0569 100644 --- a/apps/origin-src/src/server.rs +++ b/apps/origin-src/src/server.rs @@ -209,11 +209,14 @@ impl Repositories { } } - /// Opens the repositories at the given paths, served by `node`. + /// Opens the repositories at the given paths, served by `node`, and + /// retries the landings waiting for evidence in each (see + /// [`OriginService::resume_waiting`]). /// /// # Errors /// - /// Fails if one has no repository. + /// Fails if one has no repository, or its waiting landings cannot be + /// read. pub fn open( repos: BTreeMap, node: &Node, @@ -223,6 +226,9 @@ impl Repositories { for (name, path) in repos { let service = OriginService::open(path, node.clone()) .with_context(|| format!("cannot serve repository `{name}`"))?; + service + .resume_waiting() + .with_context(|| format!("cannot read the landings waiting in `{name}`"))?; repositories.insert(name, service); } Ok(repositories) diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index 833763a9..048db7dd 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -25,7 +25,7 @@ use std::path::PathBuf; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::time::Duration; -use origin_platform::Native; +use origin_platform::{LockedFile, Native}; use origin_shared::access::{PathAccess, Rights, Token}; use origin_shared::api::{ Annotation, At, BrowseQuery, ErrorCode, EventsQuery, Expected, FetchSnapshot, Inventory, @@ -33,7 +33,7 @@ use origin_shared::api::{ NewTarget, RevisionEntry, Revisions, Stored, TargetInfo, TokenRequest, }; use origin_shared::event::{EventKind, Filter, Page}; -use origin_shared::landing::{Pending, Proposal}; +use origin_shared::landing::{Blocked, Pending, Proposal}; use origin_shared::object::DecodeError; use origin_shared::pack::{Pack, Packer, Part}; use origin_shared::{ @@ -48,7 +48,7 @@ use crate::index::Index; pub use crate::permissions::Caller; use crate::permissions::{Batch, Forbidden, PutError, Reader, Writer}; use crate::policy::{Policy, PolicyError}; -use crate::queue::{LandError, Queue}; +use crate::queue::{LandError, Queue, Waiting}; use crate::store::{Store, StoreError}; use crate::tree::Snapshots; @@ -601,7 +601,9 @@ impl OriginService { /// 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. + /// `core.divergent` for the changes the revisions made diverge, and + /// retries the landings waiting for evidence about what the statements + /// are about. /// /// # Errors /// @@ -656,6 +658,7 @@ impl OriginService { let mut promotions = Vec::new(); let mut decoded = Vec::new(); let mut changes = HashSet::new(); + let mut subjects = HashSet::new(); for object in pack.objects { let id = object.id(); let record = object @@ -701,10 +704,12 @@ impl OriginService { decoded.push((id, record)); } Object::Statement(ref statement) if statement.promoted_from.is_some() => { + subjects.insert(statement.subject); promotions.push((object, statement.clone())); decoded.push((id, record)); } - Object::Statement(_) => { + Object::Statement(ref statement) => { + subjects.insert(statement.subject); statements.push(object); decoded.push((id, record)); } @@ -717,18 +722,10 @@ impl OriginService { new += self.store.write_all(&snapshots)?; } self.check_writes(caller, &held, &decoded)?; - // Held until the records are published, so nothing else moves the - // changes in between: see `Store::lock_pushes`. - let _pushing = if !revisions.is_empty() || !expect.is_empty() { - let lock = self.store.lock_pushes()?; - self.check_heads(caller, expect)?; - Some(lock) - } else { - None - }; - // 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`. + let pushing = self.lock_heads(caller, !revisions.is_empty(), expect)?; + // In layers, each 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 [statements, revisions] { if !layer.is_empty() { new += self.store.write_all(&layer)?; @@ -743,10 +740,33 @@ impl OriginService { Ok(()) })?; } + // Landings take their queue's lock, then this one, to rebase. + drop(pushing); self.wakeup.notify(); + self.resume(Some(&subjects))?; Ok(Stored { new: new as u64 }) } + /// Takes the lock every publication of revisions takes (see + /// [`Store::lock_pushes`]), if a put publishes `revisions` or `expect`s + /// heads, which it checks: held until the records are published, so + /// nothing else moves the changes in between. + fn lock_heads( + &self, + caller: &Caller, + revisions: bool, + expect: &[Expected], + ) -> Result, ServiceError> { + if !revisions && expect.is_empty() { + return Ok(None); + } + let lock = self.store.lock_pushes()?; + if !expect.is_empty() { + self.check_heads(caller, expect)?; + } + Ok(Some(lock)) + } + /// Checks that the caller may put the records of `decoded`, which a /// batch of the objects `held` brings: anyone's statements of a /// reserved kind must come from whom [`Policy::authorizes`] names, and @@ -888,6 +908,51 @@ impl OriginService { }) } + /// Retries the landings waiting for evidence, about one of `subjects`, + /// which statements were just issued about, or all without them, each + /// for its submitter: the queue continues when the evidence arrives. A + /// retry the policy in force refuses, or that fails, leaves the landing + /// as it was, and is logged: the statements that triggered it stand. A + /// landing whose submitter's token expired isn't retried: it waits + /// until someone lands it again, as [`Pending::expired`] says. + /// + /// # Errors + /// + /// Fails if the waiting landings cannot be read. + pub(crate) fn resume(&self, subjects: Option<&HashSet>) -> Result<(), ServiceError> { + if subjects.is_some_and(HashSet::is_empty) { + return Ok(()); + } + for Waiting { pending, submitter } in Queue::waiting(&self.store)? { + let about = subjects.is_none_or(|subjects| subjects.contains(&pending.subject)); + if !about || !matches!(pending.blocked, Blocked::Evidence(_)) || pending.expired() { + continue; + } + let request = LandRequest { + proposal: pending.proposal, + onto: Some(pending.onto), + }; + if let Err(error) = self.land(&submitter, &request) { + tracing::warn!( + error = %anyhow::Error::from(error), + "a waiting landing cannot continue" + ); + } + } + Ok(()) + } + + /// Retries every landing waiting for evidence, as a service just opened + /// does: the evidence may have arrived as a crash cut short the retry + /// it triggers. + /// + /// # Errors + /// + /// Fails if the waiting landings cannot be read. + pub fn resume_waiting(&self) -> Result<(), ServiceError> { + self.resume(None) + } + /// Writes the `promotions` [`OriginService::put_records`] puts, once /// [`Store::claim`] accepts each, returning how many were new. Their /// originals are never promotions, so they're stored by now. @@ -1045,7 +1110,7 @@ impl OriginService { } }; let queue = Queue::new(&self.store, &self.node.key, self.node.name.clone()) - .submitted_by(rights.paths.clone()); + .submitted_by(caller.clone(), rights.paths.clone()); let landed = self.annotations(|annotations| { let landed = match &request.proposal { Proposal::Change(change) => { @@ -1433,9 +1498,12 @@ impl ServiceError { #[cfg(test)] mod tests { - use origin_shared::{EncodedObject, Record, RepoPath}; + use origin_shared::Record; + use origin_shared::landing::Landing; use super::*; + use crate::permissions::Scope; + use crate::queue::tests::{Repo, ci_test}; /// A service of `repo`, and the objects that put a revision with a /// conflict: its description, the conflict's payload, the revision and @@ -1529,9 +1597,72 @@ mod tests { let policy = Policy::initial(&node.name, &node.key.public(), None); let service = OriginService::create(dir.path().join("repo"), node, &policy).unwrap(); // A landing holds an index all along: a read meanwhile takes another. + let read = service.annotations(|_| { + service.annotations(|annotations| Ok(annotations.index().changes().count())) + }); + assert_eq!(read.unwrap(), 0); + assert_eq!(service.kept_indexes().len(), 2, "both kept for later calls"); + } + + /// A repository whose `main` requires a passing `ci.test` from + /// `user:ci`, and its authority's service. + fn requiring_ci() -> (Repo, OriginService) { + let repo = Repo::new( + "[targets.main]\nauthority = \"node:queue\"\n\ + require = [{ kind = \"ci.test\", verdict = \"pass\", issuer = \"user:ci\" }]\n", + ); + let node = Node { + name: "queue".parse().unwrap(), + key: Arc::new(NodeKey::from_bytes(&[7; 32])), + }; + let service = OriginService::new(repo.store.clone(), node); + (repo, service) + } + + fn land(service: &OriginService, caller: &Caller, change: u8) -> Vec { + let request = LandRequest { + proposal: Proposal::Change(ChangeId::from_bytes([change; 16])), + onto: Some(TargetName::MAIN), + }; + service.land(caller, &request).unwrap().landings + } + + #[test] + fn landings_whose_token_expired_wait_to_be_landed_again() { + let (repo, service) = requiring_ci(); + let revision = repo.change_on_main(1, &[("src/a", "a")]); + let expired = Caller::Principal { + principal: "user:eve".parse().unwrap(), + scope: Some(Scope { + capabilities: ["land *", "read /", "write /"] + .map(|capability| capability.parse().unwrap()) + .to_vec(), + expires: 1, + }), + }; + assert!(matches!( + &land(&service, &expired, 1)[..], + [Landing::Pending(_)] + )); + let tip = repo.tip(&TargetName::MAIN); + let pass = ci_test(revision, "user:ci").encode(); service - .annotations(|_| service.annotations(|_| Ok(()))) + .put_records( + &Caller::Owner, + Pack { + objects: vec![pass], + }, + ) .unwrap(); - assert_eq!(service.kept_indexes().len(), 2, "both kept for later calls"); + assert_eq!(repo.tip(&TargetName::MAIN), tip, "not for eve's token"); + let waiting = service.landings(&Caller::Owner).unwrap(); + assert!( + matches!(&waiting[..], [pending] if pending.expired()), + "{waiting:?}" + ); + assert!(matches!( + &land(&service, &Caller::Owner, 1)[..], + [Landing::Landed { .. }] + )); } } diff --git a/apps/origin-src/src/sync.rs b/apps/origin-src/src/sync.rs index a8ef5254..4ebe31ff 100644 --- a/apps/origin-src/src/sync.rs +++ b/apps/origin-src/src/sync.rs @@ -2230,6 +2230,40 @@ mod tests { assert_eq!(transfer.joined, HashSet::from([fail, flaky])); } + #[test] + fn a_push_in_parts_never_lands_a_result_its_replacement_follows() { + let server = Repo::new( + "[targets.main]\nauthority = \"node:queue\"\n\ + require = [{ kind = \"ci.test\", verdict = \"pass\", issuer = \"user:ada\" }]\n", + ); + let revision = server.change_on_main(1, &[("src/a", "a")]); + let change = ChangeId::from_bytes([1; 16]); + let waits = server.land(1); + assert!(matches!( + waits[..], + [origin_shared::landing::Landing::Pending(_)] + )); + let client = Client::new(&server); + client.sync().fetch_chains(&[TargetName::MAIN]).unwrap(); + client.sync().fetch_changes(&[change]).unwrap(); + // The check passed, then failed when it ran again: both go, one + // object a request but for them. + let pass = ci_test(revision, "user:ada"); + let fail = Statement { + verdict: Some(Verdict::Fail), + supersedes: Some(pass.encode().id().into()), + ..pass.clone() + }; + client + .store + .write_all(&[pass.encode(), fail.encode()]) + .unwrap(); + let tip = server.tip(&TargetName::MAIN); + let pushed = client.sync().with_pack_limit(1).push(&[change]).unwrap(); + assert_eq!(pushed.statements, 2); + assert_eq!(server.tip(&TargetName::MAIN), tip); + } + #[test] fn a_push_in_parts_never_lands_an_abandoned_revision() { use std::os::unix::fs::{MetadataExt, PermissionsExt}; diff --git a/apps/origin-src/src/workspace/annotate.rs b/apps/origin-src/src/workspace/annotate.rs index a2ca687d..539dc54d 100644 --- a/apps/origin-src/src/workspace/annotate.rs +++ b/apps/origin-src/src/workspace/annotate.rs @@ -118,8 +118,9 @@ impl Workspace { /// `origin annotate --pass|--fail|--neutral|--withdraw`: /// issues a statement about a revision as the user, superseding the /// user's latest one of the same kind about it, as - /// [`Annotations::supersede`] does. Without a `verdict`, it withdraws - /// that one: see [`Statement::withdraws`]. + /// [`Annotations::supersede`] does, and resumes the landings waiting + /// for evidence about it. Without a `verdict`, it withdraws that one: + /// see [`Statement::withdraws`]. /// /// # Errors /// @@ -157,6 +158,8 @@ impl Workspace { } issued => issued?, }; + self.service(Some(annotations.into_index()))? + .resume(Some(&HashSet::from([subject])))?; if let Some(verdict) = statement.verdict { println!( "Issued statement {}: {} {verdict} about {}", diff --git a/apps/origin-src/src/workspace/land.rs b/apps/origin-src/src/workspace/land.rs index 72612f46..23b0fa20 100644 --- a/apps/origin-src/src/workspace/land.rs +++ b/apps/origin-src/src/workspace/land.rs @@ -508,6 +508,7 @@ impl Workspace { proposal, subject, blocked, + .. } = pending; let retry = match proposal { Proposal::Change(change) => format!("origin land {} --onto {onto}", change.short()), @@ -520,10 +521,18 @@ impl Workspace { "The landing of {proposal} on `{onto}` waits for {}", missing.join(", ") ); - println!( - " about {}: once they're issued, run `{retry}`", - subject.describe() - ); + if pending.expired() { + println!( + " about {}, but the token it was submitted with expired, so it's no \ + longer retried: run `{retry}`", + subject.describe() + ); + } else { + println!( + " about {}: once they're issued, run `{retry}`", + subject.describe() + ); + } } Blocked::Conflict { paths, .. } => { println!( diff --git a/apps/origin-src/tests/cli.rs b/apps/origin-src/tests/cli.rs index a115dbeb..17305dcc 100644 --- a/apps/origin-src/tests/cli.rs +++ b/apps/origin-src/tests/cli.rs @@ -1336,13 +1336,16 @@ fn landings_wait_for_the_evidence_policy_requires() { "{waiting}" ); assert_eq!(repo.ok(&["land", "--status"]), waiting); - // A result withdrawn is no evidence. - repo.ok(&["annotate", "@", "ci.test", "--pass", "--inputs", "src"]); + // A failure, then its withdrawal, are no evidence: each retries the + // landing, which waits. + repo.ok(&["annotate", "@", "ci.test", "--fail", "--inputs", "src"]); repo.ok(&["annotate", "@", "ci.test", "--withdraw"]); - assert_eq!(repo.ok(&["land"]), waiting); + assert_eq!(repo.ok(&["land", "--status"]), waiting); + // The statement lets the landing go on. repo.ok(&["annotate", "@", "ci.test", "--pass", "--inputs", "src"]); - assert!(repo.ok(&["land"]).contains(" on main #1\n")); assert_eq!(repo.ok(&["land", "--status"]), "No landing waits.\n"); + assert!(repo.ok(&["log", "main"]).contains("main #1 ")); + repo.ok(&["pull"]); // Only the authority lands: here, after a policy edit hands `main` to // another node. diff --git a/apps/origin-src/tests/http.rs b/apps/origin-src/tests/http.rs index 02b15d64..db9ece25 100644 --- a/apps/origin-src/tests/http.rs +++ b/apps/origin-src/tests/http.rs @@ -15,9 +15,9 @@ use origin_shared::event::EventKind; use origin_shared::landing::{Blocked, Landing, Proposal}; use origin_shared::pack::Pack; use origin_shared::{ - AttachmentId, Base, ChangeId, Digest, EncodedObject, EntryKind, EntryName, Inputs, Kind, - NodeKey, Period, Record, RecordId, RepoPath, Revision, RevisionId, Source, Statement, - TargetName, Tree, TreeEntry, TreeId, Verdict, + AcceptanceId, 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::auth::{Credentials, StaticTokens}; use origin_src::http::Api; @@ -196,12 +196,17 @@ impl Made { /// The tip of `main`, to make revisions on. async fn main_tip(repo: &Repo) -> Base { + Base::Acceptance(main_head(repo).await) +} + +/// The latest acceptance of `main`. +async fn main_head(repo: &Repo) -> AcceptanceId { let targets = repo.targets().await.unwrap(); let main = targets .iter() .find(|target| target.name == TargetName::MAIN) .unwrap(); - Base::Acceptance(main.head.acceptance) + main.head.acceptance } fn ci_test(subject: RevisionId, issuer: &str) -> EncodedObject { @@ -750,10 +755,16 @@ async fn landings_wait_for_evidence() { code(repo.put_records(&own).await.unwrap_err()), ErrorCode::Forbidden ); + // The evidence arriving lands the change, for its submitter. + let before = main_head(repo).await; server.ci.put_records(&forged).await.unwrap(); - let landed = repo.land(&land).await.unwrap(); - assert!(matches!(landed.landings[..], [Landing::Landed { .. }])); assert_eq!(repo.landings().await.unwrap(), []); + assert_ne!(main_head(repo).await, before); + let landed = repo.land(&land).await.unwrap(); + assert!( + matches!(landed.landings[..], [Landing::Unchanged(_)]), + "{landed:?}" + ); } #[tokio::test] diff --git a/crates/origin-shared/src/access.rs b/crates/origin-shared/src/access.rs index 6adcd695..b74ae345 100644 --- a/crates/origin-shared/src/access.rs +++ b/crates/origin-shared/src/access.rs @@ -513,7 +513,8 @@ impl Token { } } - fn now() -> u64 { + /// Now, in seconds since the Unix epoch, as expiries count. + pub(crate) fn now() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map_or(0, |since| since.as_secs()) diff --git a/crates/origin-shared/src/landing.rs b/crates/origin-shared/src/landing.rs index f5cd8be6..ff87d278 100644 --- a/crates/origin-shared/src/landing.rs +++ b/crates/origin-shared/src/landing.rs @@ -47,6 +47,11 @@ pub struct Pending { pub subject: RecordId, /// Why it waits. pub blocked: Blocked, + /// When the token of its submitter, whom it's retried for, expires, in + /// seconds since the Unix epoch, if it's a scoped one. Once it has, the + /// landing is no longer retried: it waits until it's landed again. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub expires: Option, } /// Why a landing waits. @@ -65,6 +70,15 @@ pub enum Blocked { }, } +impl Pending { + /// Whether its submitter's token expired, so it's no longer retried. + #[must_use] + pub fn expired(&self) -> bool { + self.expires + .is_some_and(|expires| expires <= crate::access::Token::now()) + } +} + impl Landing { /// What the landing lands. #[must_use] diff --git a/docs/openapi.json b/docs/openapi.json index 1e3d3823..6a3caf92 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -1962,6 +1962,15 @@ "$ref": "#/components/schemas/Blocked", "description": "Why it waits." }, + "expires": { + "type": [ + "integer", + "null" + ], + "format": "int64", + "description": "When the token of its submitter, whom it's retried for, expires, in\nseconds since the Unix epoch, if it's a scoped one. Once it has, the\nlanding is no longer retried: it waits until it's landed again.", + "minimum": 0 + }, "onto": { "$ref": "#/components/schemas/TargetName", "description": "The target it lands on."