From c5a4715035789c4f698d502edadd60723794ce89 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 16:03:52 +0100 Subject: [PATCH] feat(ci): answer check requests as a worker Nothing answered `check.requested`: a landing waiting for a `ci.*` result waited until someone ran the check by hand. `origin ci worker --remote ` long-polls a remote's `check.requested` events with a scoped token, and runs each check requested on the landing's subject, as the `checks.toml` at the tip of the target it lands on defines it, never the candidate's: a change can't redefine the checks that guard its target. Its statements let the landings continue. The events are only a prompt, so the worker also reconciles: at start, once the remote can be reached again, and every minute, it answers every check a waiting landing lacks that it hasn't answered yet. While the remote can't be reached (`RemoteError::is_unreachable`), it waits and tries again, so it outlives server restarts and loses no check. The end-to-end helpers can restart a server at the same address, and start one with an admin. --- AGENTS.md | 10 +- README.md | 20 +- apps/origin-ci/src/lib.rs | 8 +- apps/origin-ci/src/main.rs | 30 +++ apps/origin-ci/src/worker.rs | 304 ++++++++++++++++++++++++++++ apps/origin-ci/tests/ci.rs | 262 +++++++++++++++++++++++- apps/origin-src/src/remote.rs | 11 + apps/origin-src/tests/common/mod.rs | 76 +++++-- 8 files changed, 690 insertions(+), 31 deletions(-) create mode 100644 apps/origin-ci/src/worker.rs diff --git a/AGENTS.md b/AGENTS.md index b11bab17..68453579 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,10 +28,12 @@ review bots read and write at the same time, written in Rust. resolves from `policy.toml`. `plugin.rs` runs `origin ` as `origin-` from `PATH`, passing the repository in the environment. - `apps/origin-ci`: the CI plugin, `origin-ci`. It reads `checks.toml` - from the revision it checks (`origin ci run`). It runs each check in a - checkout of the revision of its own, and issues the results. Like every - plugin, it uses only the public API: `Remote`, which is the SDK over HTTP - or the service in-process, never origin-src's internals. + from the revision it checks as a tool (`origin ci run`), or as a worker + answering `check.requested` (`origin ci worker`), from the tip of the + target landed on, never the candidate. It runs each check in a checkout + of the revision of its own, and issues the results. Like every plugin, it + uses only the public API: `Remote`, which is the SDK over HTTP or the + service in-process, never origin-src's internals. - `tools/xtask`: development tasks, run with `cargo xtask`, such as timing origin against git (`just bench-git`). diff --git a/README.md b/README.md index e8d919d6..d1f1dedc 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ origin token issue --scope "write src" [--ttl 1h] # a short-lived token for an origin ci run [] # run the checks of checks.toml, and issue their results origin ci exec lint --inputs src -- cargo clippy # run a command as the check ci.lint, now +origin ci worker --remote # run the checks a server's landings wait for ``` Landing rebases a change onto the target's tip, file by file, checks the @@ -153,7 +154,17 @@ with 0, with the last 64 KiB of its output as the payload, declaring its inputs, `checks.toml` always among them, command and toolchain output, so its result is promoted to every revision where they're the same. A check a result of the same issuer already covers, ran or promoted, is skipped. -`origin ci run` reads the checks from the revision it checks. +`origin ci run` reads the checks from the revision it checks. A worker +reads them from the tip of the target being landed on, never from the +candidate, so a change can't redefine the checks that guard the target: an +edit to `checks.toml` takes effect once it has landed, after passing the +checks in force. The worker's results declare the target's `checks.toml` +among their inputs, not the candidate's, so a candidate that restores an +older one doesn't bring back the results of the older checks. Nor are +results promoted from one target to another, +whose checks may differ: landing a target on another runs the checks of +the one it lands on. A target without a `checks.toml` gets no +answer from the worker. Each command runs in a process group of its own. On Linux, what it leaves running in that group is killed once it ends, or if the run was killed, by the next run; a process that leaves the group escapes. @@ -167,7 +178,12 @@ check fails. `origin ci exec [--rev ] [--inputs ...] [--toolchain ] [--external] -- ` runs a command as the check `ci.` the same way, in a checkout of the revision, with the command as its definition: always, even if a result covers it, superseding -your previous result of that kind. Its checkouts +your previous result of that kind. `origin ci worker` answers a remote's `check.requested` events +with a token of its own, such as one from `origin token issue --scope "read +/" --scope "annotate ci.*"`: its statements land what waited for them. When +it starts, once the remote is back after going away, and every minute, it +also answers every landing that waits for a check it hasn't run, so no +check is lost to a missed event, a restart or a failed run. Its checkouts live in `$XDG_STATE_HOME/origin-ci/` (or `~/.local/state/`). ## Permissions diff --git a/apps/origin-ci/src/lib.rs b/apps/origin-ci/src/lib.rs index 1de55c8a..e7556f66 100644 --- a/apps/origin-ci/src/lib.rs +++ b/apps/origin-ci/src/lib.rs @@ -4,10 +4,12 @@ //! //! As a tool, `origin ci run` checks a revision of the repository it runs //! in, as the user, and `origin ci exec` runs a command given to it as a -//! check the same way. It talks to origin only through its public API: the -//! SDK over HTTP, or for a repository on a local path, the same service -//! in-process. +//! check the same way. As a worker, `origin ci worker` answers a remote's +//! `check.requested` events, with a token that annotates `ci.*`. Both talk +//! to origin only through its public API: the SDK over HTTP, or for a +//! repository on a local path, the same service in-process. pub mod checks; pub mod runner; pub mod state; +pub mod worker; diff --git a/apps/origin-ci/src/main.rs b/apps/origin-ci/src/main.rs index f54017bb..84170de9 100644 --- a/apps/origin-ci/src/main.rs +++ b/apps/origin-ci/src/main.rs @@ -7,6 +7,7 @@ use clap::{Parser, Subcommand}; use origin_ci::checks::Check; use origin_ci::runner::{Outcome, Runner}; use origin_ci::state::State; +use origin_ci::worker::Worker; use origin_shared::api::At; use origin_shared::{ChangeId, RecordId, RepoPath, RevisionId}; use origin_src::config::UserConfig; @@ -60,6 +61,23 @@ enum Command { #[arg(last = true, required = true)] command: Vec, }, + /// Run the checks a remote's landings wait for, until stopped. Its + /// token, in `$ORIGIN_TOKEN` or the configuration, must read the + /// repository and annotate `ci.*`, such as one issued with `--scope + /// "read /" --scope "annotate ci.*"`. Checks don't inherit + /// `$ORIGIN_TOKEN`, so they don't print it by accident, but they run as + /// the worker's user and can read whatever it can, the token included: + /// run the worker as a user of its own, with a token scoped as above. + /// Runs each check as the + /// `checks.toml` at the tip of the target landed on defines it, never + /// the candidate's. Answers the landings that wait first, and outlives + /// the remote going away. + Worker { + /// The repository: `http://host[:port]/`, or a path. + /// By default, this repository's remote. + #[arg(long)] + remote: Option, + }, } fn main() -> ExitCode { @@ -95,6 +113,18 @@ impl Cli { let check = Check::adhoc(&name, &command, inputs, toolchain, external)?; Ok(Self::report(&[runner.exec(subject, &check)?])) } + Command::Worker { remote } => { + let url = match (remote, context.and_then(|context| context.remote)) { + (Some(url), _) => RemoteUrl::parse(&url)?, + (None, Some(url)) => url, + (None, None) => bail!("give the worker a --remote"), + }; + let runner = Self::runner(&url, &config)?; + let mut worker = Worker::new(runner, &State::open(&url)?)?; + println!("Answering the check requests of {url}"); + worker.run()?; + Ok(ExitCode::SUCCESS) + } } } diff --git a/apps/origin-ci/src/worker.rs b/apps/origin-ci/src/worker.rs new file mode 100644 index 00000000..99be20a8 --- /dev/null +++ b/apps/origin-ci/src/worker.rs @@ -0,0 +1,304 @@ +//! Worker mode: answering a remote's `check.requested` events, which its +//! landing queue emits for each `ci.*` statement a waiting landing lacks. +//! +//! The worker long-polls the events and runs each check requested, so the +//! statement issued lets the landing continue. It runs the check on the +//! landing's subject as defined by the `checks.toml` at the tip of the +//! target it lands on, never the candidate's own: the statements of a +//! trusted runner satisfy the target's requirements, so a change that +//! redefines a required check, to pass trivially, must not make the worker +//! say it passed. A target without a tip or a `checks.toml` there leaves +//! the request unanswered, until the worker reconciles. The events are only a +//! prompt: one can come while the worker is down, and a check can fail to +//! run. So the worker also reconciles: when it starts, once the remote can +//! be reached again, and every [`Worker::RECONCILE`], it lists the landings +//! that wait, which the remote enumerates, and answers every check they +//! lack that it hasn't answered yet. Its cursor then moves to the end of +//! the events, read first, so none after the landings listed is missed. +//! While the remote can't be reached, it waits and tries again, then +//! reconciles, so a check the remote cut short by going away runs again. +//! Events come at least once, and a check that already has a result is +//! skipped, so nothing runs twice. + +use std::collections::HashSet; +use std::thread; +use std::time::{Duration, Instant}; + +use origin_platform::LockedFile; +use origin_shared::api::{At, ErrorCode, EventsQuery, List}; +use origin_shared::event::{EventKind, Page}; +use origin_shared::landing::{Blocked, Pending}; +use origin_shared::policy::{KindPattern, Requirement}; +use origin_shared::{Kind, Period, RecordId, TargetName}; + +use crate::checks::Checks; +use origin_src::remote::RemoteError; + +use crate::runner::{Outcome, RunError, Runner}; +use crate::state::{State, StateError}; + +/// A worker running the checks a remote requests. +#[derive(Debug)] +pub struct Worker { + runner: Runner, + /// The cursor to read after: `None` until the waiting landings were + /// answered. + cursor: Option, + /// When the waiting landings were last answered. + reconciled: Instant, + /// The checks answered, by subject and kind, of the landings that + /// still wait: reconciling skips them. + answered: HashSet<(RecordId, Kind)>, + _lock: LockedFile, +} + +impl Worker { + /// How long each long-poll waits. + pub const WAIT: Duration = Duration::from_secs(30); + + /// How often the worker answers every landing that waits, whatever the + /// events said. + pub const RECONCILE: Duration = Duration::from_mins(1); + + /// How long the worker first waits for a remote it can't reach, which + /// doubles each time, up to [`Worker::MAX_RETRY`]. + const FIRST_RETRY: Duration = Duration::from_millis(250); + + /// The longest the worker waits before trying a remote again. + const MAX_RETRY: Duration = Duration::from_secs(8); + + /// A worker for `runner`'s remote, which answers every landing that + /// waits first. + /// + /// # Errors + /// + /// Fails if another worker uses `state`. + pub fn new(runner: Runner, state: &State) -> Result { + let lock = state + .lock_worker()? + .ok_or_else(|| WorkerError::Busy(state.dir().display().to_string()))?; + Ok(Self { + runner, + cursor: None, + reconciled: Instant::now(), + answered: HashSet::new(), + _lock: lock, + }) + } + + /// Answers requests until stopped, printing each outcome, and each + /// check that cannot run, which is tried again when the worker next + /// reconciles. + /// + /// # Errors + /// + /// Fails if the remote refuses. + pub fn run(&mut self) -> Result<(), WorkerError> { + loop { + for Answer { + subject, + kind, + result, + } in self.next(Self::WAIT)? + { + match result { + Ok(outcome) => println!("{outcome}, about {subject}"), + Err(error) => eprintln!( + "cannot check {subject} for {kind}, which waits until the worker \ + reconciles: {:#}", + anyhow::Error::from(error) + ), + } + } + } + } + + /// Answers requests like [`Worker::poll`], waiting for the remote as + /// long as it can't be reached, then reconciling: a check may have + /// been cut short meanwhile. + /// + /// # Errors + /// + /// Fails like [`Worker::poll`], but for a remote that can't be reached. + pub fn next(&mut self, wait: Duration) -> Result, WorkerError> { + let mut retry = Self::FIRST_RETRY; + loop { + match self.poll(wait) { + Err(WorkerError::Remote(error)) if error.is_unreachable() => { + eprintln!( + "Cannot reach the remote, trying again in {:.2}s: {:#}", + retry.as_secs_f64(), + anyhow::Error::from(error) + ); + thread::sleep(retry); + retry = (retry * 2).min(Self::MAX_RETRY); + self.cursor = None; + } + answers => return answers, + } + } + } + + /// Waits up to `wait` for requests, and answers them; or reconciles + /// instead, without a cursor, or once [`Worker::RECONCILE`] passed. + /// + /// # Errors + /// + /// Fails if the remote cannot be reached or refuses. + pub fn poll(&mut self, wait: Duration) -> Result, WorkerError> { + let cursor = match self.cursor { + Some(cursor) if self.reconciled.elapsed() < Self::RECONCILE => cursor, + _ => return self.reconcile(), + }; + let page = match self.events(Some(cursor), Some(wait)) { + Ok(page) => page, + Err(error) if error.code() == Some(ErrorCode::Expired) => { + eprintln!("The remote no longer keeps the events after the cursor: reconciling"); + return self.reconcile(); + } + Err(error) => return Err(error.into()), + }; + let Page { events, next, .. } = page; + let mut answered = Vec::new(); + for event in events { + if let EventKind::CheckRequested { + onto, + subject, + requirement, + } = &event.kind + { + answered.extend(self.answer(*subject, onto, requirement)?); + } + } + self.cursor = Some(next); + Ok(answered) + } + + /// Answers every check a landing that waits lacks, but those answered + /// already, then moves the cursor to the end of the events, read first. + /// + /// # Errors + /// + /// Fails if the remote cannot be reached or refuses. + pub fn reconcile(&mut self) -> Result, WorkerError> { + let end = self.events(None, None)?.next; + let mut lacking = Vec::new(); + for Pending { + onto, + subject, + blocked, + .. + } in self.runner.remote().landings()? + { + if let Blocked::Evidence(missing) = blocked { + lacking.extend( + missing + .into_iter() + .map(|requirement| (subject, onto.clone(), requirement)), + ); + } + } + // What no longer waits needs no answer. + self.answered.retain(|(subject, kind)| { + lacking + .iter() + .any(|(lacks, _, requirement)| lacks == subject && requirement.kind == *kind) + }); + let mut answered = Vec::new(); + for (subject, onto, requirement) in &lacking { + if !self + .answered + .contains(&(*subject, requirement.kind.clone())) + { + answered.extend(self.answer(*subject, onto, requirement)?); + } + } + self.cursor = Some(end); + self.reconciled = Instant::now(); + Ok(answered) + } + + /// The `check.requested` events after `cursor`, or from now, waiting up + /// to `wait` for some. + fn events(&self, cursor: Option, wait: Option) -> Result { + self.runner.remote().events(&EventsQuery { + cursor, + wait: wait.map(Period), + kind: List(vec![KindPattern::Exact( + Kind::new("check.requested").expect("a valid kind"), + )]), + ..EventsQuery::default() + }) + } + + /// Runs the check `requirement` asks for about `subject`, landing + /// `onto` a target, if it's one of `ci.*`, as the target's tip defines + /// it, remembering it once it ran or was covered. + /// + /// # Errors + /// + /// Fails if the remote can't be reached, which cut the check short. + fn answer( + &mut self, + subject: RecordId, + onto: &TargetName, + requirement: &Requirement, + ) -> Result, WorkerError> { + let namespace = KindPattern::Prefix(Kind::new(Checks::NAMESPACE).expect("a valid kind")); + if !namespace.matches(&requirement.kind) { + return Ok(None); + } + let kind = requirement.kind.clone(); + let from = At::Target(onto.clone()); + let result = self + .runner + .check(subject, &from, Some(&kind)) + .and_then(|outcomes| { + outcomes + .into_iter() + .next() + .ok_or_else(|| RunError::UnknownCheck { + at: from.clone(), + kind: kind.clone(), + }) + }); + match result { + Err(RunError::Remote(error)) if error.is_unreachable() => return Err(error.into()), + Ok(_) => { + self.answered.insert((subject, kind.clone())); + } + Err(_) => {} + } + Ok(Some(Answer { + subject, + kind, + result, + })) + } +} + +/// How a request for a check went. +#[derive(Debug)] +pub struct Answer { + /// The record to check. + pub subject: RecordId, + /// The kind of statement requested. + pub kind: Kind, + /// What became of the check, or why it cannot run, so it's tried again + /// when the worker next reconciles. + pub result: Result, +} + +/// A failure of the worker. +#[derive(Debug, thiserror::Error)] +pub enum WorkerError { + /// Another worker uses the state directory. + #[error("another worker answers this remote's requests, with {0}")] + Busy(String), + /// The worker's lock cannot be taken. + #[error(transparent)] + State(#[from] StateError), + /// The remote cannot be reached or refused. + #[error(transparent)] + Remote(#[from] RemoteError), +} diff --git a/apps/origin-ci/tests/ci.rs b/apps/origin-ci/tests/ci.rs index b3b881eb..81da6a91 100644 --- a/apps/origin-ci/tests/ci.rs +++ b/apps/origin-ci/tests/ci.rs @@ -1,15 +1,18 @@ //! End-to-end tests of `origin ci`, through the real `origin` and -//! `origin-ci` binaries, as a tool in a working copy. +//! `origin-ci` binaries: as a tool in a working copy, and as a worker +//! answering a server's check requests. #[path = "../../origin-src/tests/common/mod.rs"] mod common; use std::fs; use std::path::Path; +use std::process::Child; +use std::sync::mpsc::Receiver; use std::thread; use std::time::{Duration, Instant}; -use common::Repo; +use common::{Repo, Server, User}; use origin_platform::{Native, Processes}; use origin_shared::{Digest, Inputs, RecordId}; use origin_src::annotations::Annotations; @@ -246,6 +249,210 @@ fn a_promotion_of_a_result_taken_back_covers_nothing() { assert_eq!(runs(&log), 2); } +/// The policy rules that make `main` require a passing `ci.test` from the +/// runners, `user:ci`. +const RULES: &str = "\n[groups]\nrunners = [\"user:ci\"]\n"; + +/// A server whose admin, alice, landed [`checks`] on `main`, then made it +/// require `ci.test`, landing the rule over HTTP, and her clone of `main`. +fn server(log: &Path) -> (Server, Repo) { + let server = Server::start_with(&["--admin", "user:alice"]); + let alice = User::new("alice"); + let main = Repo::clone(&alice, &server.url(), &[]); + main.write("checks.toml", &checks(log)); + main.write("src/lib.rs", "fn a() {}\n"); + assert!(land(&main, "Add the library").contains("Landed change")); + + let policy = Repo::clone(&alice, &server.url(), &["--target", "policy"]); + let toml = policy.read("policy.toml").replace( + "[targets.main]\nauthority = \"node:hosted\"\n", + "[targets.main]\nauthority = \"node:hosted\"\n\ + require = [{ kind = \"ci.test\", verdict = \"pass\", issuer = \"group:runners\" }]\n", + ); + policy.write("policy.toml", &(toml + RULES)); + policy.ok(&["describe", "Require tests"]); + policy.ok(&["push"]); + assert!(policy.ok(&["land"]).contains(" on policy #1\n")); + (server, main) +} + +/// Describes, pushes and lands the working copy's change, returning what +/// `land` printed. +fn land(repo: &Repo, description: &str) -> String { + repo.ok(&["describe", description]); + repo.ok(&["push"]); + repo.ok(&["land"]) +} + +/// Starts a worker answering the server's requests as `user:ci`, with a +/// token that only reads and annotates `ci.*`, keeping its state in +/// `worker`'s configuration directory. +fn worker(server: &Server, worker: &User) -> (Child, Receiver) { + let token = server.issue_token("user:ci", &["read /", "annotate ci.*"]); + let outside = tempfile::tempdir().unwrap(); + let (child, lines) = worker + .with_token(&token) + .spawn(outside.path(), &["ci", "worker", "--remote", &server.url()]); + let started = lines.recv_timeout(Duration::from_secs(10)).unwrap(); + assert!( + started.starts_with("Answering the check requests of "), + "{started}" + ); + (child, lines) +} + +/// Waits for the worker's next outcome. +fn outcome(lines: &Receiver) -> String { + lines.recv_timeout(Duration::from_secs(20)).unwrap() +} + +#[test] +fn workers_run_requested_checks_and_landings_continue() { + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("log"); + let (server, alice) = server(&log); + alice.write("src/lib.rs", "fn b() {}\n"); + let waiting = land(&alice, "Change the library"); + assert!( + waiting.contains("waits for ci.test pass from group:runners"), + "{waiting}" + ); + + // The worker answers the landing that waited before it started, and + // the statement lands it. + let runner = User::anonymous("ci"); + let (mut child, lines) = worker(&server, &runner); + let ran = outcome(&lines); + assert!(ran.starts_with("ci.test pass in "), "{ran}"); + assert_eq!(runs(&log), 1); + assert_eq!(alice.ok(&["land", "--status"]), "No landing waits.\n"); + alice.ok(&["pull"]); + assert!(alice.ok(&["log", "main"]).contains("Change the library")); + + // A docs-only change lands at once: its result is promoted. + alice.write("docs/guide.md", "# Guide\n"); + let landed = land(&alice, "Document it"); + assert!(landed.contains("Landed change"), "{landed}"); + assert_eq!(runs(&log), 1); + + // A change to the check lands at once: the worker runs `main`'s, + // which it doesn't change, on the same `src`, so the result is + // promoted. + alice.write( + "checks.toml", + &checks(&log).replace("echo tested", "echo tested again"), + ); + let landed = land(&alice, "Change the check"); + assert!(landed.contains("Landed change"), "{landed}"); + assert_eq!(runs(&log), 1); + + // Landed, the new check runs: `main`'s `checks.toml` is one of its + // inputs, so no result of the old one is promoted. + alice.write("docs/guide.md", "# Guide\n\nMore.\n"); + let waiting = land(&alice, "Document more"); + assert!(waiting.contains("waits for ci.test"), "{waiting}"); + let ran = outcome(&lines); + assert!(ran.starts_with("ci.test pass in "), "{ran}"); + assert_eq!(runs(&log), 2); + + // Restarted, the worker answers the requests made while it was down. + child.kill().unwrap(); + child.wait().unwrap(); + alice.ok(&["pull"]); + alice.write("src/lib.rs", "fn c() {}\n"); + let waiting = land(&alice, "Change it again"); + assert!(waiting.contains("waits for ci.test"), "{waiting}"); + let (mut child, lines) = worker(&server, &runner); + let ran = outcome(&lines); + assert!(ran.starts_with("ci.test pass in "), "{ran}"); + assert_eq!(runs(&log), 3); + alice.ok(&["pull"]); + assert!(alice.ok(&["log", "main"]).contains("Change it again")); + + // A target landing on `main` is checked as the merge it would make, a + // revision on `main`'s tip. + alice.ok(&["target", "new", "feature", "--from", "main"]); + alice.ok(&["new", "--on", "feature", "Feature work"]); + alice.write("src/feature.rs", "fn feature() {}\n"); + assert!(land(&alice, "Feature work").contains(" on feature #1")); + let waiting = alice.ok(&["land", "--from", "feature", "--onto", "main"]); + assert!(waiting.contains("waits for ci.test"), "{waiting}"); + let ran = outcome(&lines); + assert!( + ran.starts_with("ci.test pass in ") && ran.contains("revision:"), + "{ran}" + ); + assert_eq!(alice.ok(&["land", "--status"]), "No landing waits.\n"); + child.kill().unwrap(); + child.wait().unwrap(); +} + +#[test] +fn results_stand_for_the_checks_in_force_on_the_target() { + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("log"); + let (server, alice) = server(&log); + let runner = User::anonymous("ci"); + let (mut child, lines) = worker(&server, &runner); + alice.write("src/lib.rs", "fn b() {}\n"); + let waiting = land(&alice, "Change the library"); + assert!(waiting.contains("waits for ci.test"), "{waiting}"); + let ran = outcome(&lines); + assert!(ran.starts_with("ci.test pass in "), "{ran}"); + assert_eq!(runs(&log), 1); + + // With `main`'s checks unchanged, a docs-only change has the result + // promoted, and so does a change to `checks.toml` that requires a + // file `src` lacks. + alice.ok(&["pull"]); + alice.write("docs/guide.md", "# Guide\n\n"); + let landed = land(&alice, "Document it"); + assert!(landed.contains("Landed change"), "{landed}"); + let strict = checks(&log).replace("src/lib.rs", "src/missing.rs"); + alice.write("checks.toml", &strict); + let landed = land(&alice, "Require more"); + assert!(landed.contains("Landed change"), "{landed}"); + + // Restoring the old checks doesn't bring back the result they had + // with the same `src`: the worker runs `main`'s, which fails. + alice.write("checks.toml", &checks(&log)); + let waiting = land(&alice, "Restore the old checks"); + assert!(waiting.contains("waits for ci.test"), "{waiting}"); + let ran = outcome(&lines); + assert!(ran.starts_with("ci.test fail in "), "{ran}"); + assert_eq!(runs(&log), 1); + child.kill().unwrap(); + child.wait().unwrap(); +} + +#[test] +fn workers_run_the_checks_of_the_target_not_the_candidate() { + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("log"); + let (server, alice) = server(&log); + let runner = User::anonymous("ci"); + let (mut child, lines) = worker(&server, &runner); + + // A change that breaks `main`'s `ci.test`, and redefines it to pass. + fs::remove_file(alice.path("src/lib.rs")).unwrap(); + alice.write("src/main.rs", "fn main() {}\n"); + alice.write("checks.toml", "[checks.test]\ncommand = \"true\"\n"); + let waiting = land(&alice, "Pass trivially"); + assert!(waiting.contains("waits for ci.test"), "{waiting}"); + + // The worker runs `main`'s, which fails, and the landing waits. + let ran = outcome(&lines); + assert!(ran.starts_with("ci.test fail in "), "{ran}"); + let status = alice.ok(&["land", "--status"]); + assert!(status.contains("waits for ci.test"), "{status}"); + + // `origin ci run` checks the revision as its own `checks.toml` says. + let stdout = String::from_utf8(alice.run(alice.root(), &["ci", "run"]).stdout).unwrap(); + assert!(stdout.contains("ci.test pass in "), "{stdout}"); + child.kill().unwrap(); + child.wait().unwrap(); +} + #[test] fn checks_run_in_checkouts_of_their_own() { let repo = Repo::new(); @@ -302,6 +509,57 @@ fn checks_never_see_the_runners_token() { assert!(stdout.contains("ci.token pass in "), "{stdout}"); } +#[test] +fn workers_outlive_the_server_and_lose_no_check() { + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("log"); + let (mut server, alice) = server(&log); + let runner = User::anonymous("ci"); + let (mut child, lines) = worker(&server, &runner); + + // The server goes away while the worker waits for events. + server.restart(|| thread::sleep(Duration::from_millis(500))); + alice.write("src/lib.rs", "fn b() {}\n"); + let waiting = land(&alice, "Change the library"); + assert!(waiting.contains("waits for ci.test"), "{waiting}"); + let ran = outcome(&lines); + assert!(ran.starts_with("ci.test pass in "), "{ran}"); + assert_eq!(runs(&log), 1); + alice.ok(&["pull"]); + + // And while a check runs, so its result cannot be issued: once the + // server is back, the check runs again, and the landing goes on. A + // slower check lands at once, with the result of `main`'s promoted. + alice.write( + "checks.toml", + &format!( + "[checks.test]\ncommand = \"echo ran >> {} && sleep 1\"\ninputs = [\"src\"]\n", + log.display() + ), + ); + let landed = land(&alice, "Take longer"); + assert!(landed.contains("Landed change"), "{landed}"); + alice.write("src/lib.rs", "fn c() {}\n"); + let waiting = land(&alice, "Change it again"); + assert!(waiting.contains("waits for ci.test"), "{waiting}"); + let asked = Instant::now(); + while runs(&log) < 2 { + assert!( + asked.elapsed() < Duration::from_secs(60), + "the check never ran again" + ); + thread::sleep(Duration::from_millis(20)); + } + // The check ends meanwhile, and fails to issue its result. + server.restart(|| thread::sleep(Duration::from_secs(2))); + let ran = outcome(&lines); + assert!(ran.starts_with("ci.test pass in "), "{ran}"); + assert_eq!(runs(&log), 3); + assert_eq!(alice.ok(&["land", "--status"]), "No landing waits.\n"); + child.kill().unwrap(); + child.wait().unwrap(); +} + /// Whether the process `pid` runs, as `kill -0` finds it. fn alive(pid: &str) -> bool { let probe = std::process::Command::new("kill") diff --git a/apps/origin-src/src/remote.rs b/apps/origin-src/src/remote.rs index d717b2f9..17b09a7a 100644 --- a/apps/origin-src/src/remote.rs +++ b/apps/origin-src/src/remote.rs @@ -259,6 +259,17 @@ pub enum RemoteError { } impl RemoteError { + /// Whether the remote cannot be reached for now, or failed on its side, + /// as a server does while it restarts: asking again later may work. + #[must_use] + pub fn is_unreachable(&self) -> bool { + match self { + Self::Http(origin_client::Error::Transport(_)) => true, + Self::Http(origin_client::Error::Status(status)) => *status >= 500, + _ => false, + } + } + /// What kind of refusal this is, if the remote refused. #[must_use] pub fn code(&self) -> Option { diff --git a/apps/origin-src/tests/common/mod.rs b/apps/origin-src/tests/common/mod.rs index 821aa4f4..f93ef5cd 100644 --- a/apps/origin-src/tests/common/mod.rs +++ b/apps/origin-src/tests/common/mod.rs @@ -85,6 +85,26 @@ impl User { self.config.path() } + /// Starts a long-running command in `cwd`, returning it and its output + /// lines as they come. + pub fn spawn(&self, cwd: &Path, args: &[&str]) -> (Child, mpsc::Receiver) { + let mut child = self + .command(cwd, args) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let stdout = BufReader::new(child.stdout.take().unwrap()); + let (send, receive) = mpsc::channel(); + thread::spawn(move || { + for line in stdout.lines() { + if send.send(line.unwrap()).is_err() { + break; + } + } + }); + (child, receive) + } + /// `origin` with `args`, run in `cwd` as this user, with the plugins /// built with it on `$PATH`, keeping their state in the configuration /// directory. @@ -166,22 +186,7 @@ impl Repo { /// Starts a long-running command, such as `watch`, returning it and its /// output lines as they come. pub fn spawn(&self, args: &[&str]) -> (Child, mpsc::Receiver) { - let mut child = self - .user - .command(self.root(), args) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let stdout = BufReader::new(child.stdout.take().unwrap()); - let (send, receive) = mpsc::channel(); - thread::spawn(move || { - for line in stdout.lines() { - if send.send(line.unwrap()).is_err() { - break; - } - } - }); - (child, receive) + self.user.spawn(self.root(), args) } /// The revision the working copy is, in full. @@ -353,6 +358,12 @@ impl Server { } pub fn start() -> Self { + Self::start_with(&[]) + } + + /// Starts a server whose repository `origin repo create` made with + /// `args`, such as `--admin user:alice`. + pub fn start_with(args: &[&str]) -> Self { let dir = tempfile::tempdir().unwrap(); let config = dir.path().join("origin-server.toml"); let tokens: Vec<_> = Self::USERS @@ -368,12 +379,12 @@ impl Server { ), ) .unwrap(); - let origin = |args: &[&str]| { + let server = |args: &[&str]| { let mut command = Command::new(origin()); command.args(args).arg("--config").arg(&config); command }; - let created = origin(&["repo", "create"]) + let created = server(&[&["repo", "create"], args].concat()) .arg(dir.path().join("repos/demo")) .output() .unwrap(); @@ -382,7 +393,16 @@ impl Server { "{}", String::from_utf8_lossy(&created.stderr) ); - let mut child = origin(&["serve"]) + let (child, base) = Self::serve(&config); + Self { dir, child, base } + } + + /// Runs `origin serve` with `config`, returning it and its base URL + /// once it listens. + fn serve(config: &Path) -> (Child, String) { + let mut child = Command::new(origin()) + .args(["serve", "--config"]) + .arg(config) .stdout(Stdio::piped()) .stderr(Stdio::null()) .spawn() @@ -396,7 +416,23 @@ impl Server { .strip_prefix("Listening on ") .unwrap() .to_owned(); - Self { dir, child, base } + (child, base) + } + + /// Kills the server, runs `meanwhile`, then serves the repository again + /// at the same address. + pub fn restart(&mut self, meanwhile: impl FnOnce()) { + let _ = self.child.kill(); + let _ = self.child.wait(); + meanwhile(); + let config = self.dir().join("origin-server.toml"); + let address = self.base.strip_prefix("http://").unwrap(); + let toml = fs::read_to_string(&config).unwrap(); + let toml = toml.replace("127.0.0.1:0", address); + fs::write(&config, toml).unwrap(); + let (child, base) = Self::serve(&config); + assert_eq!(base, self.base); + self.child = child; } /// The directory holding the server's configuration, key and