Watch
0
0
Fork
You've already forked hyperhive
0

swarm-controller: move the deploy concern into its own module

Refs #6897
This commit is contained in:
atlas 2026-11-27 20:46:23 +01:00 • committed by mara
commit 352af3ea59
10 changed files with 17 additions and 10 deletions

View file

@ -0,0 +1,421 @@
//! The cache facts a hive pulls with, copied to where the hive may read them.
//!
//! The cache's operator keeps four facts under `swarm/services/attic/`
//! ([`swarm_secret_client::attic`]). A hive's store identity reads
//! `swarm/hives/<hive>/*` and nothing under `swarm/services/`, so every
//! [`RECONCILE_INTERVAL`] this writes each fact that is stored to every hive's
//! `attic/` prefix, and leaves a copy that already holds the value alone.
//!
//! A deploy waits for the same copy: the `CopyAtticFacts` node ([`copy_node`])
//! copies to the one hive the deploy goes to, through the same [`copy_hive`] as
//! the pass, so a hive is told to deploy only once its facts are in its prefix.
//!
//! A fact that is not stored is not copied, and a copy whose source is gone
//! stays: neither the pass nor the node deletes. A swarm with no cache stores
//! none, so both write nothing.
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context, Result};
use hive_jobq::scheduler::Outcome;
use swarm_secret_client::SecretStore;
use swarm_secret_client::attic::{Fact, Leaf, hive_path, service_path};
/// How often [`spawn`] copies.
const RECONCILE_INTERVAL: Duration = Duration::from_mins(5);
/// A pass that has not finished by now is given up on; the next tick retries.
const PASS_DEADLINE: Duration = Duration::from_mins(2);
/// The two store calls a pass makes, so a test can stand in for the store.
pub(crate) trait FactStore {
/// The fact at `path`; `None` when nothing is stored there.
async fn read(&self, path: &str) -> Result<Option<String>>;
/// Store `value` at `path`, replacing what is there.
async fn write(&self, path: &str, value: &str) -> Result<()>;
}
impl FactStore for SecretStore {
async fn read(&self, path: &str) -> Result<Option<String>> {
Ok(self.read_optional::<Fact>(path).await?.map(|f| f.value))
}
async fn write(&self, path: &str, value: &str) -> Result<()> {
let fact = Fact {
value: value.to_owned(),
};
Ok(SecretStore::write(self, path, &fact).await?)
}
}
/// What one pass did.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct Copied {
/// Copies written because they were absent or held another value.
pub written: usize,
/// Hives whose copies could not all be checked or written.
pub failed: usize,
}
/// The stored facts, as `(leaf, value)`. An empty value counts as not stored.
async fn sources(store: &impl FactStore) -> Result<Vec<(Leaf, String)>> {
let mut found = Vec::new();
for leaf in Leaf::ALL {
let path = service_path(leaf)?;
let stored = store
.read(&path)
.await
.with_context(|| format!("reading {path}"))?;
if let Some(value) = stored.filter(|v| !v.trim().is_empty()) {
found.push((leaf, value));
}
}
Ok(found)
}
/// Bring `hive`'s copies up to `sources`; how many were written.
async fn copy_hive(
store: &impl FactStore,
hive: &str,
sources: &[(Leaf, String)],
) -> Result<usize> {
let mut written = 0;
for (leaf, value) in sources {
let path = hive_path(hive, *leaf)?;
let current = store
.read(&path)
.await
.with_context(|| format!("reading {path}"))?;
if current.as_deref() == Some(value.as_str()) {
continue;
}
store
.write(&path, value)
.await
.with_context(|| format!("writing {path}"))?;
written += 1;
}
Ok(written)
}
/// The stored facts copied to `hive`; how many copies were written. The one
/// hive [`copy_node`] serves; [`copy_pass`] reads the sources once for all of
/// them instead.
///
/// # Errors
/// A source or a copy that cannot be read, or a copy that cannot be written.
pub(crate) async fn ensure_copied(store: &impl FactStore, hive: &str) -> Result<usize> {
copy_hive(store, hive, &sources(store).await?).await
}
/// The `CopyAtticFacts` node's work: [`ensure_copied`] for `hive`, `Failed`
/// with the cause when it errors. Written copies are logged; a hive whose
/// copies are current is `Done` without a write.
pub(crate) async fn copy_node(store: &impl FactStore, hive: &str) -> Outcome {
match ensure_copied(store, hive).await {
Ok(written) => {
if written > 0 {
tracing::info!(hive, written, "attic facts: copied for a deploy");
}
Outcome::Done
}
Err(e) => Outcome::Failed(format!(
"the cache facts could not be copied to {hive}: {e:#}"
)),
}
}
/// [`copy_node`] against the swarm's store, within [`PASS_DEADLINE`].
pub(crate) async fn copy_node_now(hive: &str) -> Outcome {
let work = async {
match crate::store::connect().await {
Ok(store) => copy_node(&store, hive).await,
Err(e) => Outcome::Failed(format!("logging in to the swarm secret store: {e}")),
}
};
tokio::time::timeout(PASS_DEADLINE, work)
.await
.unwrap_or_else(|_| {
Outcome::Failed(format!(
"copying the cache facts to {hive} timed out after {}s",
PASS_DEADLINE.as_secs()
))
})
}
/// One pass over `hives`.
///
/// # Errors
/// When a source cannot be read, which stops the pass before any copy: a
/// failed read is not an absent fact. A hive that fails is counted in
/// [`Copied::failed`] and logged, and the others are still copied.
pub(crate) async fn copy_pass(store: &impl FactStore, hives: &[String]) -> Result<Copied> {
let sources = sources(store).await?;
let mut done = Copied::default();
for hive in hives {
match copy_hive(store, hive, &sources).await {
Ok(n) => done.written += n,
Err(e) => {
tracing::warn!(hive, error = %format!("{e:#}"), "attic facts: copy failed");
done.failed += 1;
}
}
}
Ok(done)
}
/// Copy now and every [`RECONCILE_INTERVAL`] after. A pass that fails is
/// logged and retried on the next tick; it never stops the daemon.
pub fn spawn(hives: Vec<String>) {
let hives = Arc::new(hives);
tokio::spawn(async move {
let mut ticker = tokio::time::interval(RECONCILE_INTERVAL);
loop {
ticker.tick().await;
let pass = async {
let store = crate::store::connect()
.await
.context("logging in to the swarm secret store")?;
copy_pass(&store, &hives).await
};
match tokio::time::timeout(PASS_DEADLINE, pass).await {
Ok(Ok(done)) if done.written > 0 || done.failed > 0 => tracing::info!(
written = done.written,
failed = done.failed,
"attic facts: copied to the hives"
),
Ok(Ok(_)) => tracing::debug!("attic facts: every hive's copy is current"),
Ok(Err(e)) => tracing::warn!(
error = %format!("{e:#}"),
retry_in_s = RECONCILE_INTERVAL.as_secs(),
"attic facts: pass failed; retrying next tick"
),
Err(_) => tracing::warn!(
deadline_s = PASS_DEADLINE.as_secs(),
"attic facts: pass timed out; retrying next tick"
),
}
}
});
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use std::sync::Mutex;
use super::*;
/// An in-memory store that counts writes and can refuse reads or writes
/// under a prefix.
#[derive(Default)]
struct Memory {
kv: Mutex<BTreeMap<String, String>>,
writes: Mutex<Vec<String>>,
refuse: Option<&'static str>,
}
impl Memory {
fn with(pairs: &[(&str, &str)]) -> Self {
let m = Self::default();
for (path, value) in pairs {
m.kv.lock()
.unwrap()
.insert((*path).to_owned(), (*value).to_owned());
}
m
}
fn get(&self, path: &str) -> Option<String> {
self.kv.lock().unwrap().get(path).cloned()
}
}
impl FactStore for Memory {
async fn read(&self, path: &str) -> Result<Option<String>> {
Ok(self.get(path))
}
async fn write(&self, path: &str, value: &str) -> Result<()> {
if self.refuse.is_some_and(|p| path.starts_with(p)) {
anyhow::bail!("denied");
}
self.writes.lock().unwrap().push(path.to_owned());
self.kv
.lock()
.unwrap()
.insert(path.to_owned(), value.to_owned());
Ok(())
}
}
const SOURCES: [(&str, &str); 4] = [
("swarm/services/attic/pull-token", "tok"),
("swarm/services/attic/url", "https://cache.example"),
("swarm/services/attic/cache", "swarm"),
("swarm/services/attic/public-key", "swarm:AAAA"),
];
fn hives() -> Vec<String> {
vec!["alpha".to_owned(), "beta".to_owned()]
}
#[tokio::test]
async fn present_facts_reach_every_hive() {
let store = Memory::with(&SOURCES);
let done = copy_pass(&store, &hives()).await.expect("pass");
assert_eq!(
done,
Copied {
written: 8,
failed: 0
}
);
for hive in hives() {
assert_eq!(
store
.get(&format!("swarm/hives/{hive}/attic/pull-token"))
.as_deref(),
Some("tok")
);
assert_eq!(
store
.get(&format!("swarm/hives/{hive}/attic/public-key"))
.as_deref(),
Some("swarm:AAAA")
);
}
// Presence control for the absence cases below: copies are the only
// thing a pass writes under a hive.
assert!(store.get("swarm/hives/alpha/forge/token").is_none());
}
#[tokio::test]
async fn absent_facts_write_nothing() {
let store = Memory::default();
let done = copy_pass(&store, &hives()).await.expect("pass");
assert_eq!(done, Copied::default());
assert!(store.writes.lock().unwrap().is_empty());
}
#[tokio::test]
async fn only_the_stored_facts_are_copied_and_an_empty_one_is_not_stored() {
let store = Memory::with(&[
("swarm/services/attic/pull-token", "tok"),
("swarm/services/attic/url", " \n"),
]);
copy_pass(&store, &hives()).await.expect("pass");
assert_eq!(
store.get("swarm/hives/alpha/attic/pull-token").as_deref(),
Some("tok")
);
assert!(store.get("swarm/hives/alpha/attic/url").is_none());
assert!(store.get("swarm/hives/alpha/attic/cache").is_none());
}
#[tokio::test]
async fn a_current_copy_is_not_rewritten_and_a_changed_value_is() {
let store = Memory::with(&SOURCES);
copy_pass(&store, &hives()).await.expect("first");
let again = copy_pass(&store, &hives()).await.expect("second");
assert_eq!(again, Copied::default(), "unchanged values are not written");
store.kv.lock().unwrap().insert(
"swarm/services/attic/pull-token".to_owned(),
"rotated".to_owned(),
);
let rotated = copy_pass(&store, &hives()).await.expect("third");
assert_eq!(
rotated,
Copied {
written: 2,
failed: 0
}
);
assert_eq!(
store.get("swarm/hives/beta/attic/pull-token").as_deref(),
Some("rotated")
);
}
#[tokio::test]
async fn a_removed_source_leaves_the_copies() {
let store = Memory::with(&SOURCES);
copy_pass(&store, &hives()).await.expect("first");
store
.kv
.lock()
.unwrap()
.remove("swarm/services/attic/pull-token");
copy_pass(&store, &hives()).await.expect("second");
assert_eq!(
store.get("swarm/hives/alpha/attic/pull-token").as_deref(),
Some("tok")
);
}
/// The node and the pass copy through the same `copy_hive`: for one hive
/// they leave the store holding the same values.
#[tokio::test]
async fn the_node_and_the_pass_leave_the_same_copies() {
let by_pass = Memory::with(&SOURCES);
copy_pass(&by_pass, &["alpha".to_owned()])
.await
.expect("pass");
let by_node = Memory::with(&SOURCES);
assert_eq!(copy_node(&by_node, "alpha").await, Outcome::Done);
for leaf in Leaf::ALL {
let path = hive_path("alpha", leaf).expect("a hive path");
assert!(by_pass.get(&path).is_some(), "the pass wrote {path}");
assert_eq!(by_node.get(&path), by_pass.get(&path), "{path}");
}
}
/// The node copies for its hive only, and a hive already current is `Done`
/// without a write.
#[tokio::test]
async fn the_node_copies_for_its_own_hive_and_leaves_a_current_copy_alone() {
let store = Memory::with(&SOURCES);
assert_eq!(copy_node(&store, "alpha").await, Outcome::Done);
assert_eq!(
store.get("swarm/hives/alpha/attic/pull-token").as_deref(),
Some("tok")
);
assert!(store.get("swarm/hives/beta/attic/pull-token").is_none());
let writes = store.writes.lock().unwrap().len();
assert_eq!(copy_node(&store, "alpha").await, Outcome::Done);
assert_eq!(store.writes.lock().unwrap().len(), writes);
}
/// A copy that cannot be written fails the node, naming the hive and the
/// cause. Control: the same store copies for the hive it does not refuse.
#[tokio::test]
async fn a_copy_that_cannot_be_written_fails_the_node() {
let mut store = Memory::with(&SOURCES);
store.refuse = Some("swarm/hives/alpha/");
let Outcome::Failed(error) = copy_node(&store, "alpha").await else {
panic!("a refused write is not Done")
};
assert!(error.contains("alpha"), "{error}");
assert!(error.contains("denied"), "{error}");
assert_eq!(copy_node(&store, "beta").await, Outcome::Done);
}
#[tokio::test]
async fn one_hive_failing_does_not_stop_the_others() {
let mut store = Memory::with(&SOURCES);
store.refuse = Some("swarm/hives/alpha/");
let done = copy_pass(&store, &hives()).await.expect("pass");
assert_eq!(
done,
Copied {
written: 4,
failed: 1
}
);
assert!(store.get("swarm/hives/beta/attic/cache").is_some());
assert!(store.get("swarm/hives/alpha/attic/cache").is_none());
}
}

View file

@ -0,0 +1,567 @@
//! The `BuildAgent` node: send a config PR's head to the swarm builder over the
//! queue, turn its answer into the [`CONTEXT`] commit status on that head, and
//! record the build, `nix`'s tail with it, in [`runs`]. The status links to the
//! swarm UI's builds page for that build.
//!
//! Nothing is pushed, and the closure the builder made stays in its host's
//! store. A red status blocks nothing; the merge deploys as before. The build
//! that does gate a deploy is `meta_build`'s.
//!
//! Builds share one `SwarmResourceKind::Builder` slot, so one runs at a time,
//! and a newer push replaces its PR's build while that build is still
//! pending (`queue_build`).
pub(crate) mod runs;
use std::future::Future;
use forgejo_api::structs::CommitStatusState;
use hive_jobq::scheduler::Outcome;
use swarm_wire::builder::{BuildAgent, REPLY_DEADLINE, Reply, SUBJECT};
use crate::agent_renewal::unix_now;
use crate::forge::{self, CONFIG_ORG};
use runs::{BuildOutcome, BuildRecord};
/// The commit status context the check writes.
pub const CONTEXT: &str = "swarm-builder";
/// Where a build is sent: the queue in production, a fake in the tests.
/// `Err` is a build that never reached a builder or never came back.
pub(crate) trait BuildSink {
fn build(&self, request: Vec<u8>) -> impl Future<Output = Result<Reply, String>> + Send;
}
impl BuildSink for async_nats::Client {
async fn build(&self, request: Vec<u8>) -> Result<Reply, String> {
use async_nats::RequestErrorKind;
let sent = async_nats::Request::new()
.payload(request.into())
.timeout(Some(REPLY_DEADLINE));
match self.send_request(SUBJECT, sent).await {
Ok(msg) => serde_json::from_slice(&msg.payload)
.map_err(|e| format!("the builder's reply did not decode: {e}")),
Err(e) => Err(match e.kind() {
RequestErrorKind::NoResponders => "no swarm builder is listening: \
deploy.builder.enable is set on no host, or its service is not connected \
to the swarm queue"
.to_owned(),
RequestErrorKind::TimedOut => format!(
"the swarm builder sent no answer within {} minutes",
REPLY_DEADLINE.as_secs() / 60
),
_ => format!("sending the build to the swarm builder failed: {e}"),
}),
}
}
}
/// Where a status is written: the forge in production, a fake in the tests.
pub(crate) trait StatusSink {
fn set(
&self,
agent: &str,
rev: &str,
state: CommitStatusState,
description: &str,
target_url: Option<&str>,
) -> impl Future<Output = anyhow::Result<()>> + Send;
}
impl StatusSink for forge::Client {
async fn set(
&self,
agent: &str,
rev: &str,
state: CommitStatusState,
description: &str,
target_url: Option<&str>,
) -> anyhow::Result<()> {
forge::within_forge_deadline(
"build_agent status",
self.create_commit_status(
CONFIG_ORG,
agent,
rev,
forge::CommitStatus {
context: CONTEXT,
state,
description,
target_url,
},
),
)
.await
.unwrap_or_else(|| Err(anyhow::anyhow!("no answer from the forge")))
}
}
/// Build `job`, record it in `builds`, and write its status, linking to the
/// recorded build under `link_base` (the swarm vhost's public URL) when there is
/// one. The node fails when the build does, so the Jobs page shows red where
/// the PR does.
pub(crate) async fn run(
queue: Option<&impl BuildSink>,
statuses: Option<&impl StatusSink>,
builds: &runs::Builds,
link_base: Option<&str>,
job: BuildAgent,
) -> Outcome {
let Some(statuses) = statuses else {
return Outcome::Failed(
"no forge access here (SWARM_CONTROLLER_FORGE_URL unset, or its token not in the \
swarm secret store), so no build status can be written"
.to_owned(),
);
};
let started_unix = unix_now();
let set = |state, description: String, link: Option<String>| {
let job = &job;
async move {
statuses
.set(&job.agent, &job.rev, state, &description, link.as_deref())
.await
.map_err(|e| format!("{e:#}"))
}
};
let finish =
|outcome, text: String| record(builds, link_base, &job, started_unix, outcome, text);
let Some(queue) = queue else {
let error = "no swarm queue is configured on this host, so no build can be sent";
let link = finish(BuildOutcome::Error, error.to_owned()).await;
return settle(
set(CommitStatusState::Error, error.to_owned(), link).await,
error,
);
};
if let Err(e) = set(
CommitStatusState::Pending,
"building on the swarm builder".to_owned(),
None,
)
.await
{
tracing::warn!(agent = %job.agent, rev = %job.rev, error = %e, "build_agent: the pending status was not written");
}
let request = match serde_json::to_vec(&job) {
Ok(request) => request,
Err(e) => return Outcome::Failed(format!("encoding the build: {e}")),
};
match queue.build(request).await {
Ok(Reply::Built { out_path }) => {
tracing::info!(agent = %job.agent, rev = %job.rev, %out_path, "build_agent: built");
let link = finish(BuildOutcome::Built, out_path.clone()).await;
match set(CommitStatusState::Success, out_path, link).await {
Ok(()) => Outcome::Done,
Err(e) => Outcome::Failed(format!("built, but the status was not written: {e}")),
}
}
Ok(Reply::Failed { error_tail }) => {
let last = last_line(&error_tail).to_owned();
let link = finish(BuildOutcome::Failed, error_tail.clone()).await;
settle(
set(CommitStatusState::Failure, last, link).await,
&format!("the build failed: {error_tail}"),
)
}
Err(error) => {
let link = finish(BuildOutcome::Error, error.clone()).await;
settle(
set(CommitStatusState::Error, error.clone(), link).await,
&error,
)
}
}
}
/// Store the build of `job` that ended as `outcome`, `text` being its store
/// path, `nix`'s tail or the reason. The link to it, when it was
/// stored and `link_base` is known.
async fn record(
builds: &runs::Builds,
link_base: Option<&str>,
job: &BuildAgent,
started_unix: i64,
outcome: BuildOutcome,
text: String,
) -> Option<String> {
let mut build = BuildRecord {
id: format!(
"{}-{}-{started_unix}",
job.agent,
job.rev.get(..12).unwrap_or(&job.rev)
),
repo: format!("{CONFIG_ORG}/{}", job.agent),
pr: Some(job.pr),
agent: None,
head_sha: job.rev.clone(),
started_unix,
finished_unix: unix_now(),
outcome,
out_path: None,
error_tail: None,
detail: None,
};
*match outcome {
BuildOutcome::Built => &mut build.out_path,
BuildOutcome::Failed => &mut build.error_tail,
BuildOutcome::Error => &mut build.detail,
} = Some(text);
if !builds.record(&build).await {
return None;
}
link_base.map(|base| format!("{}/jobs?run={}", base.trim_end_matches('/'), build.id))
}
/// A failed node carrying `error`, and the status write's own failure when
/// there was one.
fn settle(written: Result<(), String>, error: &str) -> Outcome {
match written {
Ok(()) => Outcome::Failed(error.to_owned()),
Err(e) => Outcome::Failed(format!("{error} (and the status was not written: {e})")),
}
}
/// The last non-blank line of `tail`, which for `nix` is the error itself.
fn last_line(tail: &str) -> &str {
tail.lines()
.rev()
.map(str::trim)
.find(|l| !l.is_empty())
.unwrap_or("the build failed")
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use super::runs::tests::FakeDoc;
use super::*;
const BASE: &str = "https://swarm.example";
struct FakeQueue(Result<Reply, String>);
impl BuildSink for FakeQueue {
async fn build(&self, request: Vec<u8>) -> Result<Reply, String> {
let sent: BuildAgent = serde_json::from_slice(&request).expect("a build request");
assert_eq!(sent, job());
self.0.clone()
}
}
#[derive(Default)]
struct FakeStatuses(Mutex<Vec<(CommitStatusState, String, Option<String>)>>);
impl StatusSink for FakeStatuses {
async fn set(
&self,
agent: &str,
rev: &str,
state: CommitStatusState,
description: &str,
target_url: Option<&str>,
) -> anyhow::Result<()> {
assert_eq!((agent, rev), ("atlas", "abc"));
self.0.lock().unwrap().push((
state,
description.to_owned(),
target_url.map(str::to_owned),
));
Ok(())
}
}
fn store() -> runs::Builds {
runs::Builds::Fake(Arc::new(FakeDoc::default()))
}
fn job() -> BuildAgent {
BuildAgent {
agent: "atlas".to_owned(),
rev: "abc".to_owned(),
pr: 3,
}
}
async fn statuses_after(queue: Option<FakeQueue>) -> (Outcome, Vec<CommitStatusState>) {
let statuses = FakeStatuses::default();
let outcome = run(queue.as_ref(), Some(&statuses), &store(), Some(BASE), job()).await;
let states = statuses.0.into_inner().unwrap();
(outcome, states.into_iter().map(|(s, _, _)| s).collect())
}
#[tokio::test]
async fn a_built_config_goes_pending_then_green() {
let (outcome, states) = statuses_after(Some(FakeQueue(Ok(Reply::Built {
out_path: "/nix/store/x".to_owned(),
}))))
.await;
assert!(matches!(outcome, Outcome::Done));
assert_eq!(
states,
[CommitStatusState::Pending, CommitStatusState::Success]
);
}
/// The build, the doc it was recorded in, and the statuses written.
async fn recorded(
reply: Result<Reply, String>,
doc: FakeDoc,
link_base: Option<&str>,
) -> (
Outcome,
Vec<runs::BuildRecord>,
Vec<(CommitStatusState, String, Option<String>)>,
) {
let statuses = FakeStatuses::default();
let doc = Arc::new(doc);
let outcome = run(
Some(&FakeQueue(reply)),
Some(&statuses),
&runs::Builds::Fake(Arc::clone(&doc)),
link_base,
job(),
)
.await;
(outcome, doc.builds(), statuses.0.into_inner().unwrap())
}
#[tokio::test]
async fn a_failed_build_goes_red_with_its_last_line_and_links_to_its_recorded_tail() {
let tail = "evaluating\nerror: boom\n";
let (outcome, builds, written) = recorded(
Ok(Reply::Failed {
error_tail: tail.to_owned(),
}),
FakeDoc::default(),
Some("https://swarm.example/"),
)
.await;
assert!(matches!(&outcome, Outcome::Failed(e) if e.contains("error: boom")));
let [build] = builds.as_slice() else {
panic!("one build recorded: {builds:?}")
};
assert_eq!(build.repo, "agent-configs/atlas");
assert_eq!((build.pr, build.head_sha.as_str()), (Some(3), "abc"));
assert_eq!(build.outcome, BuildOutcome::Failed);
assert_eq!(build.error_tail.as_deref(), Some(tail));
assert_eq!((&build.out_path, &build.detail), (&None, &None));
assert!(build.id.starts_with("atlas-abc-"), "{}", build.id);
assert!(build.finished_unix >= build.started_unix);
let link = format!("https://swarm.example/jobs?run={}", build.id);
assert_eq!(
written,
[
(
CommitStatusState::Pending,
"building on the swarm builder".to_owned(),
None
),
(
CommitStatusState::Failure,
"error: boom".to_owned(),
Some(link)
),
]
);
}
#[tokio::test]
async fn a_built_config_and_a_missing_builder_are_recorded_and_linked_too() {
let (_, builds, written) = recorded(
Ok(Reply::Built {
out_path: "/nix/store/x".to_owned(),
}),
FakeDoc::default(),
Some(BASE),
)
.await;
assert_eq!(builds[0].outcome, BuildOutcome::Built);
assert_eq!(builds[0].out_path.as_deref(), Some("/nix/store/x"));
assert!(written[1].2.is_some(), "{written:?}");
let (_, builds, written) = recorded(
Err("no swarm builder".to_owned()),
FakeDoc::default(),
Some(BASE),
)
.await;
assert_eq!(builds[0].outcome, BuildOutcome::Error);
assert_eq!(builds[0].detail.as_deref(), Some("no swarm builder"));
assert_eq!(written[1].0, CommitStatusState::Error);
assert!(written[1].2.is_some(), "{written:?}");
}
/// No link to a build that was not stored, nor without the swarm's URL;
/// the status is written either way.
#[tokio::test]
async fn a_status_links_only_to_a_stored_build_under_a_known_url() {
let failed = || {
Ok(Reply::Failed {
error_tail: "error: boom".to_owned(),
})
};
let (_, builds, written) = recorded(failed(), FakeDoc::failing(), Some(BASE)).await;
assert!(builds.is_empty());
assert_eq!(
written.last(),
Some(&(CommitStatusState::Failure, "error: boom".to_owned(), None))
);
let (_, builds, written) = recorded(failed(), FakeDoc::default(), None).await;
assert_eq!(builds.len(), 1, "recorded all the same");
assert_eq!(written.last().map(|w| &w.2), Some(&None));
}
/// A superseded build that finishes after the newer head's writes only on
/// its own commit, so the newer head keeps its status.
#[tokio::test]
async fn a_late_superseded_build_writes_only_on_its_own_commit() {
struct ByRevQueue;
impl BuildSink for ByRevQueue {
async fn build(&self, request: Vec<u8>) -> Result<Reply, String> {
let sent: BuildAgent = serde_json::from_slice(&request).expect("a build request");
Ok(if sent.rev == "old" {
Reply::Failed {
error_tail: "error: boom".to_owned(),
}
} else {
Reply::Built {
out_path: "/nix/store/new".to_owned(),
}
})
}
}
#[derive(Default)]
struct ByRev(Mutex<Vec<(String, CommitStatusState)>>);
impl StatusSink for ByRev {
async fn set(
&self,
_: &str,
rev: &str,
state: CommitStatusState,
_: &str,
_: Option<&str>,
) -> anyhow::Result<()> {
self.0.lock().unwrap().push((rev.to_owned(), state));
Ok(())
}
}
let statuses = ByRev::default();
let at = |rev: &str| BuildAgent {
rev: rev.to_owned(),
..job()
};
run(
Some(&ByRevQueue),
Some(&statuses),
&store(),
None,
at("new"),
)
.await;
run(
Some(&ByRevQueue),
Some(&statuses),
&store(),
None,
at("old"),
)
.await;
let written = statuses.0.into_inner().unwrap();
let last_on = |rev: &str| {
written
.iter()
.rev()
.find(|(r, _)| r == rev)
.map(|(_, s)| *s)
};
assert_eq!(last_on("new"), Some(CommitStatusState::Success));
assert_eq!(last_on("old"), Some(CommitStatusState::Failure));
}
#[tokio::test]
async fn no_builder_is_an_error_status_not_a_failure() {
let (outcome, states) =
statuses_after(Some(FakeQueue(Err("no swarm builder".to_owned())))).await;
assert!(matches!(outcome, Outcome::Failed(_)));
assert_eq!(
states,
[CommitStatusState::Pending, CommitStatusState::Error]
);
}
#[tokio::test]
async fn no_queue_is_an_error_status() {
let (outcome, states) = statuses_after(None).await;
assert!(matches!(&outcome, Outcome::Failed(e) if e.contains("no swarm queue")));
assert_eq!(states, [CommitStatusState::Error]);
}
#[tokio::test]
async fn no_forge_fails_the_node_without_sending_the_build() {
struct Unreachable;
impl BuildSink for Unreachable {
async fn build(&self, _: Vec<u8>) -> Result<Reply, String> {
panic!("a build with nowhere to report must not be sent")
}
}
let outcome = run(
Some(&Unreachable),
None::<&FakeStatuses>,
&store(),
None,
job(),
)
.await;
assert!(matches!(&outcome, Outcome::Failed(e) if e.contains("no forge access")));
}
/// The queue half against a real server: no builder listening names the
/// option, and a listener's reply comes back decoded.
#[tokio::test]
async fn a_build_reaches_a_listening_builder_and_fails_without_one() {
use futures_util::StreamExt as _;
let nats = crate::test_nats::TestNats::start();
let client = nats.client().await;
let unanswered = client.build(b"{}".to_vec()).await;
assert!(
matches!(&unanswered, Err(e) if e.contains("deploy.builder.enable")),
"{unanswered:?}"
);
let builder = nats.client().await;
let mut requests = builder
.queue_subscribe(SUBJECT, swarm_wire::builder::QUEUE_GROUP.to_owned())
.await
.expect("subscribe");
// A message the builder sends itself and receives back proves the
// server processed the subscription before it.
let mut probe = builder
.subscribe("builder-test.probe")
.await
.expect("subscribe");
builder
.publish("builder-test.probe", "".into())
.await
.expect("publish");
probe.next().await.expect("the probe comes back");
let built = Reply::Built {
out_path: "/nix/store/x".to_owned(),
};
let answer = built.clone();
tokio::spawn(async move {
let msg = requests.next().await.expect("a request");
let reply = serde_json::to_vec(&answer).expect("encodes");
builder
.publish(msg.reply.expect("a reply subject"), reply.into())
.await
.expect("publish");
});
assert_eq!(client.build(b"{}".to_vec()).await, Ok(built));
}
}

View file

@ -0,0 +1,503 @@
//! `GET /api/builder/runs`: the swarm builder's finished builds, newest
//! first, each with what `nix` printed when it failed; and
//! `GET /api/builder/runs/{id}`, one of them, which its commit status links to.
//!
//! The newest [`MAX_RUNS`] are one JSON array under [`KEY`] in [`BUCKET`],
//! which only this daemon reads or writes, kept the way
//! `review_classifier::runs` keeps the classifier's: one compare-and-set
//! document, with entries this build cannot decode kept as they were.
use std::future::Future;
use anyhow::Context as _;
use async_nats::jetstream::kv::Store;
use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use problem_details::ProblemDetails;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::routes::{AppState, error_problem};
use crate::schedules::{read_with, write};
/// The bucket holding the builds. Agents hold no grant on it.
pub const BUCKET: &str = "builder-runs";
/// The one key in [`BUCKET`].
pub const KEY: &str = "recent";
/// How many builds the list keeps; recording one more drops the oldest.
pub(crate) const MAX_RUNS: usize = 100;
/// How many times a losing writer re-reads and re-applies.
const MAX_ATTEMPTS: usize = 5;
/// How a build ended, as its commit status reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum BuildOutcome {
/// The config built: `success`.
Built,
/// `nix` failed or timed out: `failure`.
Failed,
/// No build ran or none came back: `error`.
Error,
}
/// One finished build.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
pub(crate) struct BuildRecord {
/// `<agent>-<first 12 of head_sha>-<started_unix>`, the last segment
/// of the link on the build's status.
pub(crate) id: String,
/// `agent-configs/<agent>` for a config PR's build, `internal/meta` for a
/// deploy's (`meta_build`).
pub(crate) repo: String,
/// The config PR a build checks. A `meta_build` build has none.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) pr: Option<u64>,
/// The agent a `meta_build` build built; a PR build's is in `repo`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) agent: Option<String>,
/// The commit built: the PR's head, or `internal/meta`'s for a deploy's
/// build.
pub(crate) head_sha: String,
/// Unix seconds: when the node sent the build, and when its answer came.
pub(crate) started_unix: i64,
pub(crate) finished_unix: i64,
pub(crate) outcome: BuildOutcome,
/// The system closure's store path, for `built`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) out_path: Option<String>,
/// The last lines `nix` printed, for `failed`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) error_tail: Option<String>,
/// Why no build ran or came back, for `error`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) detail: Option<String>,
}
/// One entry of the stored list.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(untagged)]
pub(crate) enum Stored {
Build(BuildRecord),
/// A record this build cannot decode, such as one a newer build wrote.
/// Left out of the list but kept, counted toward [`MAX_RUNS`] and written
/// back as it was read.
Unreadable(serde_json::Value),
}
/// Where the builds are kept: [`BUCKET`] in production, a fake in the tests.
pub(crate) trait BuildDoc {
/// The entries, with the revision to write them back against.
fn read(&self) -> impl Future<Output = anyhow::Result<(Vec<Stored>, Option<u64>)>> + Send;
/// `Ok(false)` when another write landed since `revision`.
fn write(
&self,
builds: Vec<Stored>,
revision: Option<u64>,
) -> impl Future<Output = anyhow::Result<bool>> + Send;
}
impl BuildDoc for Store {
async fn read(&self) -> anyhow::Result<(Vec<Stored>, Option<u64>)> {
read_with(self, KEY, |bytes| Ok(decode(bytes))).await
}
async fn write(&self, builds: Vec<Stored>, revision: Option<u64>) -> anyhow::Result<bool> {
write(self, KEY, &builds, revision).await
}
}
/// The entries in `bytes`. A document that is not a JSON array reads as no
/// entries, with a warning, and the next write replaces it.
fn decode(bytes: &[u8]) -> Vec<Stored> {
let values: Vec<serde_json::Value> = match serde_json::from_slice(bytes) {
Ok(values) => values,
Err(e) => {
tracing::warn!(
bucket = BUCKET, key = KEY, error = %e,
"the builder runs are not decodable; reading them as none"
);
return Vec::new();
}
};
values
.into_iter()
.map(|value| match BuildRecord::deserialize(&value) {
Ok(build) => Stored::Build(build),
Err(e) => {
tracing::warn!(
bucket = BUCKET, key = KEY, error = %e,
"a builder run this build cannot decode is left out of the list and kept"
);
Stored::Unreadable(value)
}
})
.collect()
}
/// Put `build` first in `doc`, keeping the newest [`MAX_RUNS`], re-reading and
/// re-applying when another write landed in between.
async fn push(doc: &impl BuildDoc, build: &BuildRecord) -> anyhow::Result<()> {
for _ in 0..MAX_ATTEMPTS {
let (mut builds, revision) = doc.read().await?;
builds.insert(0, Stored::Build(build.clone()));
builds.truncate(MAX_RUNS);
if doc.write(builds, revision).await? {
return Ok(());
}
tracing::debug!("builder runs: write lost a race, retrying");
}
anyhow::bail!("gave up recording the build after {MAX_ATTEMPTS} conflicting writes")
}
/// The builds' store.
#[derive(Clone)]
pub(crate) enum Builds {
/// [`BUCKET`] on the swarm queue, when this host has one.
Live(Option<async_nats::Client>),
/// An in-memory document a test reads back.
#[cfg(test)]
Fake(std::sync::Arc<tests::FakeDoc>),
}
/// Why the builds' store could not be reached: always 503.
struct Unreachable(String);
impl Builds {
/// Add `build` to the list. `false`, with a warning, when the write
/// failed.
pub(crate) async fn record(&self, build: &BuildRecord) -> bool {
let pushed = match self {
Self::Live(client) => match open(client.as_ref()).await {
Ok(store) => push(&store, build).await,
Err(Unreachable(e)) => {
Err(anyhow::anyhow!(e).context(format!("opening the {BUCKET} bucket")))
}
},
#[cfg(test)]
Self::Fake(doc) => push(&**doc, build).await,
};
match pushed {
Ok(()) => true,
Err(e) => {
tracing::warn!(
id = %build.id, repo = %build.repo, head_sha = %build.head_sha,
error = %format!("{e:#}"),
"storing a builder run failed; its status links to nothing"
);
false
}
}
}
async fn list(&self) -> Result<Vec<BuildRecord>, ProblemDetails> {
let read = match self {
Self::Live(client) => {
let store = open(client.as_ref())
.await
.map_err(|Unreachable(e)| error_problem(StatusCode::SERVICE_UNAVAILABLE, &e))?;
BuildDoc::read(&store).await
}
#[cfg(test)]
Self::Fake(doc) => doc.read().await,
};
read.map(|(builds, _)| {
builds
.into_iter()
.filter_map(|entry| match entry {
Stored::Build(build) => Some(build),
Stored::Unreadable(_) => None,
})
.collect()
})
.map_err(|e| {
let detail = format!("{e:#}");
tracing::warn!(error = %detail, "reading the builder runs failed");
error_problem(StatusCode::INTERNAL_SERVER_ERROR, &detail)
})
}
}
/// Open [`BUCKET`], creating it if nothing has yet.
async fn open(client: Option<&async_nats::Client>) -> Result<Store, Unreachable> {
let client = client
.ok_or_else(|| Unreachable("no swarm queue is configured on this host".to_owned()))?;
swarm_queue_client::ensure_connected(client)
.map_err(|e| Unreachable(swarm_queue_client::chain(&e)))?;
let js = async_nats::jetstream::new(client.clone());
if let Ok(store) = js.get_key_value(BUCKET).await {
return Ok(store);
}
js.create_key_value(async_nats::jetstream::kv::Config {
bucket: BUCKET.to_owned(),
description: "The swarm builder's newest finished builds".to_owned(),
history: 1,
..Default::default()
})
.await
.with_context(|| format!("creating the {BUCKET} bucket"))
.map_err(|e| Unreachable(format!("{e:#}")))
}
/// List the swarm builder's finished builds.
#[utoipa::path(
get,
path = "/api/builder/runs",
responses(
(status = 200, description = "the newest 100 finished builds, newest first; empty \
when there are none", body = Vec<BuildRecord>),
(status = 503, description = "no swarm queue is configured on this host, it is not \
connected, or the builds' bucket could not be opened (problem+json)", body = String),
(status = 500, description = "the builds could not be read (problem+json)",
body = String),
),
tag = "builder"
)]
pub(crate) async fn get_runs(
State(state): State<AppState>,
) -> Result<Json<Vec<BuildRecord>>, ProblemDetails> {
state.builds.list().await.map(Json)
}
/// One finished build: the link a `swarm-builder` commit status carries.
#[utoipa::path(
get,
path = "/api/builder/runs/{id}",
params(("id" = String, Path, description = "the build's id, as the list names it")),
responses(
(status = 200, description = "the build, with `nix`'s tail when it failed",
body = BuildRecord),
(status = 404, description = "no build has this id among the newest 100 \
(problem+json)", body = String),
(status = 503, description = "as for the list (problem+json)", body = String),
(status = 500, description = "as for the list (problem+json)", body = String),
),
tag = "builder"
)]
pub(crate) async fn get_run(
State(state): State<AppState>,
Path(id): Path<String>,
) -> Result<Json<BuildRecord>, ProblemDetails> {
state
.builds
.list()
.await?
.into_iter()
.find(|build| build.id == id)
.map(Json)
.ok_or_else(|| {
error_problem(
StatusCode::NOT_FOUND,
"no build has this id among the newest 100",
)
})
}
#[cfg(test)]
pub(crate) mod tests {
use std::sync::{Arc, Mutex};
use axum::body::Body;
use axum::http::Request;
use tower::ServiceExt as _;
use super::*;
/// A document in memory. Each of the first `conflicts` writes loses to a
/// write that lands one build in between; a document set to `fail` fails
/// every read.
#[derive(Default)]
pub(crate) struct FakeDoc {
state: Mutex<(Vec<Stored>, u64)>,
conflicts: Mutex<usize>,
fail: bool,
}
impl FakeDoc {
pub(crate) fn failing() -> Self {
Self {
fail: true,
..Self::default()
}
}
/// The decodable builds, as the list shows them.
pub(crate) fn builds(&self) -> Vec<BuildRecord> {
self.state
.lock()
.expect("unpoisoned")
.0
.iter()
.filter_map(|entry| match entry {
Stored::Build(build) => Some(build.clone()),
Stored::Unreadable(_) => None,
})
.collect()
}
}
impl BuildDoc for FakeDoc {
async fn read(&self) -> anyhow::Result<(Vec<Stored>, Option<u64>)> {
anyhow::ensure!(!self.fail, "the store is down");
let (builds, revision) = self.state.lock().expect("unpoisoned").clone();
Ok((builds, Some(revision).filter(|r| *r > 0)))
}
async fn write(&self, builds: Vec<Stored>, revision: Option<u64>) -> anyhow::Result<bool> {
let mut state = self.state.lock().expect("unpoisoned");
let mut conflicts = self.conflicts.lock().expect("unpoisoned");
if *conflicts > 0 {
*conflicts -= 1;
state
.0
.insert(0, Stored::Build(record(&format!("other-{conflicts}"))));
state.1 += 1;
}
if revision.unwrap_or(0) != state.1 {
return Ok(false);
}
*state = (builds, state.1 + 1);
Ok(true)
}
}
pub(crate) fn record(id: &str) -> BuildRecord {
BuildRecord {
id: id.to_owned(),
repo: "agent-configs/atlas".to_owned(),
pr: Some(3),
agent: None,
head_sha: "abc".to_owned(),
started_unix: 1_000,
finished_unix: 1_060,
outcome: BuildOutcome::Failed,
out_path: None,
error_tail: Some("evaluating\nerror: boom".to_owned()),
detail: None,
}
}
fn ids(builds: &[BuildRecord]) -> Vec<&str> {
builds.iter().map(|b| b.id.as_str()).collect()
}
#[tokio::test]
async fn the_newest_hundred_survive_newest_first() {
let doc = FakeDoc::default();
for i in 0..=MAX_RUNS {
push(&doc, &record(&format!("r{i}"))).await.expect("stored");
}
let builds = doc.builds();
assert_eq!(builds.len(), 100);
assert_eq!(builds[0].id, "r100");
assert_eq!(builds[99].id, "r1", "r0, the oldest, is gone");
}
#[tokio::test]
async fn a_write_that_lost_a_race_is_redone_on_the_winner() {
let doc = FakeDoc {
conflicts: Mutex::new(2),
..FakeDoc::default()
};
push(&doc, &record("mine")).await.expect("stored");
assert_eq!(ids(&doc.builds()), ["mine", "other-0", "other-1"]);
}
/// The bucket on a real server: created on first use, written, read
/// back; a record from a newer build is left out and kept in its place.
#[tokio::test]
async fn builds_round_trip_through_the_bucket_and_keep_an_undecodable_one() {
let nats = crate::test_nats::TestNats::start();
let client = nats.client().await;
let builds = Builds::Live(Some(client.clone()));
assert!(builds.record(&record("a")).await);
assert!(builds.record(&record("b")).await);
assert_eq!(ids(&builds.list().await.expect("listed")), ["b", "a"]);
let Ok(store) = open(Some(&client)).await else {
panic!("the bucket did not open");
};
let mut newer = serde_json::to_value(record("newer")).expect("encodes");
newer["outcome"] = "a-later-outcome".into();
let doc = serde_json::json!([newer, record("b"), record("a")]);
store
.put(KEY, doc.to_string().into())
.await
.expect("written");
assert!(builds.record(&record("c")).await);
assert_eq!(ids(&builds.list().await.expect("listed")), ["c", "b", "a"]);
let entry = store.get(KEY).await.expect("readable").expect("a document");
let after: Vec<serde_json::Value> = serde_json::from_slice(&entry).expect("a JSON array");
assert_eq!(after.len(), 4, "{after:?}");
assert_eq!(after[1], newer, "kept untouched, in its place");
}
#[tokio::test]
async fn a_failed_write_is_reported() {
assert!(
!Builds::Fake(Arc::new(FakeDoc::failing()))
.record(&record("a"))
.await
);
assert!(!Builds::Live(None).record(&record("a")).await);
}
#[tokio::test]
async fn the_route_lists_the_builds_with_their_tail_and_a_down_store_is_an_error() {
let doc = Arc::new(FakeDoc::default());
let mut built = record("a");
built.outcome = BuildOutcome::Built;
built.out_path = Some("/nix/store/x".to_owned());
built.error_tail = None;
push(&*doc, &built).await.expect("stored");
push(&*doc, &record("b")).await.expect("stored");
let get_at = |builds: Builds, path: &'static str| async move {
let (mut state, _) = crate::routes::tests::state_with_roster();
state.builds = builds;
let res = crate::startup::build_app(state)
.oneshot(Request::get(path).body(Body::empty()).expect("a request"))
.await
.expect("infallible");
let status = res.status();
let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
.await
.expect("a body");
let body: serde_json::Value = serde_json::from_slice(&bytes).expect("JSON");
(status, body)
};
let get = |builds: Builds| get_at(builds, "/api/builder/runs");
let (status, body) = get(Builds::Fake(Arc::clone(&doc))).await;
assert_eq!(status, StatusCode::OK, "{body}");
assert_eq!(body[0]["id"], "b");
assert_eq!(body[0]["repo"], "agent-configs/atlas");
assert_eq!(body[0]["head_sha"], "abc");
assert_eq!(body[0]["outcome"], "failed");
assert_eq!(body[0]["error_tail"], "evaluating\nerror: boom");
assert!(body[0].get("out_path").is_none(), "{body}");
assert_eq!(body[1]["outcome"], "built");
assert_eq!(body[1]["out_path"], "/nix/store/x");
assert!(body[1].get("error_tail").is_none(), "{body}");
let one = |path| get_at(Builds::Fake(Arc::clone(&doc)), path);
let (status, body) = one("/api/builder/runs/b").await;
assert_eq!(status, StatusCode::OK, "{body}");
assert_eq!(body["id"], "b");
assert_eq!(body["error_tail"], "evaluating\nerror: boom");
let (status, body) = one("/api/builder/runs/a").await;
assert_eq!(status, StatusCode::OK, "{body}");
assert_eq!(body["outcome"], "built");
let (status, body) = one("/api/builder/runs/nope").await;
assert_eq!(status, StatusCode::NOT_FOUND, "{body}");
let (status, body) = get(Builds::Fake(Arc::new(FakeDoc::failing()))).await;
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{body}");
let (status, body) = get(Builds::Live(None)).await;
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{body}");
assert_eq!(body["detail"], "no swarm queue is configured on this host");
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,496 @@
//! Build the head of an agent's config repo that moved without a build.
//!
//! A merged config PR is built and deployed from its webhook delivery
//! (`crate::webhook`). A delivery that never arrives leaves `main` ahead of
//! what the agent runs, and nothing else asks for a build. Every
//! `config_pr::POLL_INTERVAL` the config scan calls [`run`], which compares each
//! placed agent's `agent-configs/<agent>` `main` with the config commit its
//! latest green build used, and queues the build and deploy the webhook would
//! have queued ([`crate::jobq::insert_merged_deploy`]) for each that differs.
//!
//! The config commit a build used is the pin of `agent-<agent>` in the
//! `flake.nix` of the `internal/meta` commit its [`AgentClosure`] record names.
//! The pin in `internal/meta`'s head is not the record: a later meta update for
//! another agent moves every pin, built or not.
//!
//! Left alone:
//! - An agent no hive places, or more than one does.
//! - An agent with no record, or whose recorded flake pins no config commit for
//! it: nothing was built from its config repo to differ from.
//! - A head whose deploy the graph holds in any state, or an agent with a deploy
//! in flight. A head that was tried and failed is not queued again here: the
//! meta timer builds it again every round (`jobq::queue_meta_update`). The
//! graph is in memory, so a restart tries each such head once more.
use std::collections::{BTreeSet, HashMap};
use std::future::Future;
use std::sync::{Arc, Mutex};
use anyhow::{Context as _, Result};
use async_nats::jetstream::kv::Store;
use swarm_wire::agent_closures::AgentClosure;
use crate::forge::{self, objects::SHARED_ORG};
use crate::jobq::{SwarmNodeKind, SwarmResourceKind};
use crate::meta_flake::{CONFIG_BRANCH, META_REPO};
use crate::wanted::WantedWriter;
type Jobq = Mutex<hive_jobq::scheduler::Scheduler<SwarmNodeKind, SwarmResourceKind>>;
/// What a pass reads and does outside the process, so a test can stand in for it.
trait World {
/// Every `(hive, agent)` a hive places.
fn placements(&self) -> impl Future<Output = Result<BTreeSet<(String, String)>>> + Send;
/// Every config repo's `(agent, head commit)`.
fn heads(&self) -> impl Future<Output = Result<Vec<(String, String)>>> + Send;
/// The config commit `agent`'s latest green build used; `None` when there is
/// no such build or it pinned none.
fn built(&self, agent: &str) -> impl Future<Output = Result<Option<String>>> + Send;
/// Whether the graph holds a deploy of `agent` at `head`, or one still
/// running.
fn attempted(&self, agent: &str, head: &str) -> bool;
/// Queue the build and deploy of `agent` at `head` on `hive`. Whether it was
/// queued.
fn queue(&self, hive: &str, agent: &str, head: &str) -> bool;
}
/// Whether `graph` holds a `TriggerDeploy` of `agent` that is not finished, or
/// one at `head` in any state.
fn attempted(
graph: &hive_jobq::Graph<SwarmNodeKind, SwarmResourceKind>,
agent: &str,
head: &str,
) -> bool {
graph.nodes().any(|n| match &n.payload {
SwarmNodeKind::TriggerDeploy { agent: a, rev, .. } if a == agent => {
!n.state.is_terminal() || rev.as_deref() == Some(head)
}
_ => false,
})
}
/// One pass: each head that differs from what was built is queued once. The
/// `(agent, head)` it queued, in order.
///
/// # Errors
/// A read that failed before any agent was looked at (the placements, the
/// heads). A failure on one agent is logged and the pass goes on.
async fn pass(world: &impl World) -> Result<Vec<(String, String)>> {
let placed = world
.placements()
.await
.context("reading where the hives place agents")?;
let heads = world.heads().await.context("reading the config heads")?;
let mut queued = Vec::new();
for (agent, head) in heads {
let mut hives = placed.iter().filter(|(_, a)| *a == agent);
let (Some((hive, _)), None) = (hives.next(), hives.next()) else {
continue;
};
if world.attempted(&agent, &head) {
continue;
}
let built = match world.built(&agent).await {
Ok(Some(built)) => built,
Ok(None) => continue,
Err(e) => {
tracing::warn!(%agent, error = %format!("{e:#}"), "config drift: reading the built config commit failed");
continue;
}
};
if built == head {
continue;
}
tracing::info!(
%agent, %head, %built, %hive,
"config drift: agent-configs main moved to a head no build used, and no webhook build was seen; queueing it"
);
if world.queue(hive, &agent, &head) {
queued.push((agent, head));
}
}
Ok(queued)
}
/// What [`run`] needs beyond the forge client.
pub(crate) struct Deps {
pub(crate) jobq: Arc<Jobq>,
pub(crate) wanted: Arc<WantedWriter>,
pub(crate) hives: Vec<String>,
pub(crate) queue: async_nats::Client,
}
/// One pass against the live swarm. A pass that fails is logged and the next
/// scan tries again.
pub(crate) async fn run(deps: &Deps, forge: &Arc<forge::Client>) {
let closures = match swarm_queue_client::agent_closures::open_or_create(&deps.queue).await {
Ok(closures) => closures,
Err(e) => {
tracing::warn!(error = %e, "config drift: opening the agent-closures bucket failed");
return;
}
};
let world = Live {
deps,
forge: Arc::clone(forge),
closures,
flakes: Mutex::default(),
};
match pass(&world).await {
Ok(queued) if !queued.is_empty() => {
tracing::info!("config drift: pass queued {} builds", queued.len());
}
Ok(_) => tracing::debug!("config drift: pass done, no drift"),
Err(e) => tracing::warn!(error = %format!("{e:#}"), "config drift: pass failed"),
}
}
/// The real world of one pass.
struct Live<'a> {
deps: &'a Deps,
forge: Arc<forge::Client>,
closures: Store,
/// `internal/meta`'s `flake.nix` by commit, for the commits read this pass.
flakes: Mutex<HashMap<String, Option<String>>>,
}
impl Live<'_> {
/// `flake.nix` of `internal/meta` at `meta_rev`; `None` when it has none.
async fn flake_at(&self, meta_rev: &str) -> Result<Option<String>> {
if let Some(read) = self.flakes.lock().unwrap().get(meta_rev) {
return Ok(read.clone());
}
let flake = self
.forge
.file_at_commit(SHARED_ORG, META_REPO, meta_rev, "flake.nix")
.await
.with_context(|| {
format!("reading flake.nix of {SHARED_ORG}/{META_REPO} at {meta_rev}")
})?
.map(|bytes| String::from_utf8_lossy(&bytes).into_owned());
self.flakes
.lock()
.unwrap()
.insert(meta_rev.to_owned(), flake.clone());
Ok(flake)
}
}
impl World for Live<'_> {
async fn placements(&self) -> Result<BTreeSet<(String, String)>> {
crate::jobq::placements(&self.deps.wanted, &self.deps.hives).await
}
async fn heads(&self) -> Result<Vec<(String, String)>> {
self.forge.list_config_heads(CONFIG_BRANCH).await
}
async fn built(&self, agent: &str) -> Result<Option<String>> {
let (record, _) = crate::schedules::read_with(&self.closures, agent, |bytes| {
Ok(Some(serde_json::from_slice::<AgentClosure>(bytes)?))
})
.await?;
let Some(record) = record else {
return Ok(None);
};
let Some(flake) = self.flake_at(&record.meta_rev).await? else {
return Ok(None);
};
Ok(hive_meta_flake::pinned_rev(&flake, &format!("agent-{agent}")).map(str::to_owned))
}
fn attempted(&self, agent: &str, head: &str) -> bool {
attempted(
self.deps
.jobq
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.graph(),
agent,
head,
)
}
fn queue(&self, hive: &str, agent: &str, head: &str) -> bool {
crate::jobq::insert_merged_deploy(&self.deps.jobq, hive, agent, head, None)
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use hive_jobq::State;
use hive_jobq::scheduler::{Outcome, Scheduler};
use super::*;
const OLD: &str = "1111111111111111111111111111111111111111";
const HEAD: &str = "2222222222222222222222222222222222222222";
const NEWER: &str = "3333333333333333333333333333333333333333";
/// The swarm as a pass sees it. The graph is a real scheduler: what the pass
/// queues, and what it finds queued, go through the production code.
struct Fake {
placed: BTreeSet<(String, String)>,
heads: Vec<(String, String)>,
built: BTreeMap<String, Result<Option<String>, String>>,
jobq: Arc<Jobq>,
}
impl Fake {
/// `atlas` is placed on `pr1ma`, its `main` is at `HEAD` and its last
/// build used `OLD`.
fn drifted() -> Self {
Self {
placed: [("pr1ma".to_owned(), "atlas".to_owned())].into(),
heads: vec![("atlas".to_owned(), HEAD.to_owned())],
built: BTreeMap::from([("atlas".to_owned(), Ok(Some(OLD.to_owned())))]),
jobq: Arc::new(Mutex::new(Scheduler::new(
hive_jobq::Graph::new(),
hive_jobq::resources::ResourceTable::new(),
))),
}
}
fn built_at(mut self, agent: &str, rev: &str) -> Self {
self.built
.insert(agent.to_owned(), Ok(Some(rev.to_owned())));
self
}
/// The `rev` of every deploy of `agent` in the graph, oldest first.
fn deploys(&self, agent: &str) -> Vec<(Option<String>, State)> {
let guard = self.jobq.lock().unwrap();
let mut nodes: Vec<_> = guard
.graph()
.nodes()
.filter_map(|n| match &n.payload {
SwarmNodeKind::TriggerDeploy { agent: a, rev, .. } if a == agent => {
Some((n.id, rev.clone(), n.state))
}
_ => None,
})
.collect();
nodes.sort_by_key(|(id, _, _)| *id);
nodes
.into_iter()
.map(|(_, rev, state)| (rev, state))
.collect()
}
/// Run every runnable node; the builds fail when `builds_fail`.
async fn drain(&self, builds_fail: bool) {
while let Some(runner) =
Scheduler::claim_next(&self.jobq, move |_id, kind, builder| async move {
let outcome = match kind {
SwarmNodeKind::BuildMeta { .. } if builds_fail => {
Outcome::Failed("error: attribute missing".to_owned())
}
_ => Outcome::Done,
};
(builder, outcome)
})
{
runner.await.1.expect("no growth declared");
}
}
}
impl World for Fake {
async fn placements(&self) -> Result<BTreeSet<(String, String)>> {
Ok(self.placed.clone())
}
async fn heads(&self) -> Result<Vec<(String, String)>> {
Ok(self.heads.clone())
}
async fn built(&self, agent: &str) -> Result<Option<String>> {
match self.built.get(agent) {
Some(Ok(rev)) => Ok(rev.clone()),
Some(Err(e)) => anyhow::bail!("{e}"),
None => Ok(None),
}
}
fn attempted(&self, agent: &str, head: &str) -> bool {
attempted(self.jobq.lock().unwrap().graph(), agent, head)
}
fn queue(&self, hive: &str, agent: &str, head: &str) -> bool {
crate::jobq::insert_merged_deploy(&self.jobq, hive, agent, head, None)
}
}
fn queued(agent: &str, head: &str) -> Vec<(String, String)> {
vec![(agent.to_owned(), head.to_owned())]
}
#[tokio::test]
async fn a_head_that_moved_without_a_build_queues_one_build() {
let world = Fake::drifted();
assert_eq!(pass(&world).await.unwrap(), queued("atlas", HEAD));
assert_eq!(
world.deploys("atlas"),
[(Some(HEAD.to_owned()), State::Pending)]
);
let guard = world.jobq.lock().unwrap();
let hives: Vec<_> = guard
.graph()
.nodes()
.filter_map(|n| match &n.payload {
SwarmNodeKind::TriggerDeploy { hive, .. } => Some(hive.clone()),
_ => None,
})
.collect();
assert_eq!(hives, ["pr1ma"]);
}
#[tokio::test]
async fn a_head_that_was_built_queues_nothing() {
let world = Fake::drifted().built_at("atlas", HEAD);
assert_eq!(pass(&world).await.unwrap(), []);
assert_eq!(world.deploys("atlas"), []);
}
#[tokio::test]
async fn a_head_already_queued_is_not_queued_again() {
let world = Fake::drifted();
assert_eq!(pass(&world).await.unwrap(), queued("atlas", HEAD));
assert_eq!(pass(&world).await.unwrap(), []);
assert_eq!(world.deploys("atlas").len(), 1);
}
#[tokio::test]
async fn a_head_a_webhook_queued_is_not_queued_again() {
let world = Fake::drifted();
assert!(crate::jobq::insert_merged_deploy(
&world.jobq,
"pr1ma",
"atlas",
HEAD,
Some(7)
));
assert_eq!(pass(&world).await.unwrap(), []);
assert_eq!(world.deploys("atlas").len(), 1);
}
#[tokio::test]
async fn a_head_whose_build_failed_is_not_queued_every_pass() {
let world = Fake::drifted();
assert_eq!(pass(&world).await.unwrap(), queued("atlas", HEAD));
world.drain(true).await;
assert_eq!(
world.deploys("atlas"),
[(Some(HEAD.to_owned()), State::Skipped)]
);
for _ in 0..3 {
assert_eq!(pass(&world).await.unwrap(), []);
}
assert_eq!(world.deploys("atlas").len(), 1);
}
#[tokio::test]
async fn a_newer_head_is_queued_after_a_failed_one() {
let mut world = Fake::drifted();
assert_eq!(pass(&world).await.unwrap(), queued("atlas", HEAD));
world.drain(true).await;
world.heads = vec![("atlas".to_owned(), NEWER.to_owned())];
assert_eq!(pass(&world).await.unwrap(), queued("atlas", NEWER));
}
#[tokio::test]
async fn a_deploy_in_flight_holds_back_a_newer_head_until_it_ends() {
let mut world = Fake::drifted();
assert_eq!(pass(&world).await.unwrap(), queued("atlas", HEAD));
world.heads = vec![("atlas".to_owned(), NEWER.to_owned())];
assert_eq!(pass(&world).await.unwrap(), []);
world.drain(false).await;
// The build recorded the closure from `HEAD`.
world
.built
.insert("atlas".to_owned(), Ok(Some(HEAD.to_owned())));
assert_eq!(pass(&world).await.unwrap(), queued("atlas", NEWER));
}
#[tokio::test]
async fn an_agent_nobody_places_or_two_hives_place_is_left_alone() {
let mut world = Fake::drifted();
world.heads = vec![
("atlas".to_owned(), HEAD.to_owned()),
("ghost".to_owned(), HEAD.to_owned()),
("twin".to_owned(), HEAD.to_owned()),
];
world.placed.insert(("pr1ma".to_owned(), "twin".to_owned()));
world.placed.insert(("hive2".to_owned(), "twin".to_owned()));
let world = world.built_at("ghost", OLD).built_at("twin", OLD);
assert_eq!(pass(&world).await.unwrap(), queued("atlas", HEAD));
}
#[tokio::test]
async fn an_agent_with_no_build_to_compare_is_left_alone() {
let mut world = Fake::drifted();
world.heads = vec![
("atlas".to_owned(), HEAD.to_owned()),
("fresh".to_owned(), HEAD.to_owned()),
];
world
.placed
.insert(("pr1ma".to_owned(), "fresh".to_owned()));
world.built.insert("fresh".to_owned(), Ok(None));
assert_eq!(pass(&world).await.unwrap(), queued("atlas", HEAD));
}
#[tokio::test]
async fn an_agent_whose_build_cannot_be_read_does_not_stop_the_others() {
let mut world = Fake::drifted();
world.heads = vec![
("broken".to_owned(), HEAD.to_owned()),
("atlas".to_owned(), HEAD.to_owned()),
];
world
.placed
.insert(("pr1ma".to_owned(), "broken".to_owned()));
world
.built
.insert("broken".to_owned(), Err("kv unreachable".to_owned()));
assert_eq!(pass(&world).await.unwrap(), queued("atlas", HEAD));
assert_eq!(world.deploys("broken"), []);
}
#[tokio::test]
async fn another_agents_deploy_does_not_hold_this_one_back() {
let mut world = Fake::drifted();
world.heads = vec![
("atlas".to_owned(), HEAD.to_owned()),
("iris".to_owned(), HEAD.to_owned()),
];
world.placed.insert(("pr1ma".to_owned(), "iris".to_owned()));
let world = world.built_at("iris", OLD);
assert!(crate::jobq::insert_merged_deploy(
&world.jobq,
"pr1ma",
"iris",
HEAD,
None
));
assert_eq!(pass(&world).await.unwrap(), queued("atlas", HEAD));
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,100 @@
//! The hyperhive pin the controller last sent the hives to build from.
//!
//! One key ([`KEY`]) in [`BUCKET`], which only this daemon reads or writes.
//! The `UpdateMeta` node fans out whenever the pin `internal/meta` holds is
//! not the one recorded here, and the `RecordFanout` node writes it once every
//! `TriggerDeploy` of that fan-out is done or skipped by its build gate. A pass
//! that dies, or a deploy that fails, before then leaves the record stale, so
//! the next pass sends the deploys again. A deploy the gate skipped counts as
//! sent: `jobq::queue_meta_update` declares it again on every round until its
//! build succeeds. A deploy is idempotent per pin, so sending twice is safe and
//! sending never is not.
//!
//! With no record, as on the first pass of a controller that has never written
//! one, the pin is not the recorded one and the agents are sent a deploy.
use std::future::Future;
use anyhow::{Context as _, Result};
use async_nats::jetstream::kv::Store;
/// The bucket holding the record. Agents hold no grant on it.
pub(crate) const BUCKET: &str = "meta-fanout";
/// The one key in [`BUCKET`]: the pin, as a rev string.
const KEY: &str = "pin";
/// Where the record lives: the bucket in production, a fake in the tests.
pub(crate) trait PinStore {
/// The recorded pin; `None` when none was ever written.
fn recorded(&self) -> impl Future<Output = Result<Option<String>>> + Send;
fn record(&self, pin: &str) -> impl Future<Output = Result<()>> + Send;
}
impl PinStore for Store {
async fn recorded(&self) -> Result<Option<String>> {
let entry = self
.get(KEY)
.await
.with_context(|| format!("read {BUCKET}/{KEY}"))?;
Ok(entry.map(|b| String::from_utf8_lossy(&b).into_owned()))
}
async fn record(&self, pin: &str) -> Result<()> {
self.put(KEY, pin.to_owned().into())
.await
.map(|_| ())
.with_context(|| format!("write {BUCKET}/{KEY}"))
}
}
/// Open [`BUCKET`], creating it if nothing has yet.
async fn open(client: &async_nats::Client) -> Result<Store> {
let js = async_nats::jetstream::new(client.clone());
if let Ok(store) = js.get_key_value(BUCKET).await {
return Ok(store);
}
js.create_key_value(async_nats::jetstream::kv::Config {
bucket: BUCKET.to_owned(),
description: "The hyperhive pin the controller last sent the hives to build from"
.to_owned(),
history: 1,
..Default::default()
})
.await
.with_context(|| format!("creating the {BUCKET} bucket"))
}
/// The pin recorded in the bucket on `client`, opening or creating it.
///
/// # Errors
/// The bucket cannot be opened or created, or its key cannot be read.
pub(crate) async fn recorded(client: &async_nats::Client) -> Result<Option<String>> {
open(client).await?.recorded().await
}
/// Record `pin` as sent, in the bucket on `client`.
///
/// # Errors
/// The bucket cannot be opened or created, or the key cannot be written.
pub(crate) async fn record(client: &async_nats::Client, pin: &str) -> Result<()> {
open(client).await?.record(pin).await
}
#[cfg(test)]
mod tests {
use super::*;
/// The bucket on a real server: absent until written, then the pin
/// written, and a second write replaces it.
#[tokio::test]
async fn the_pin_round_trips_through_the_bucket() {
let nats = crate::test_nats::TestNats::start();
let client = nats.client().await;
assert_eq!(recorded(&client).await.expect("opens"), None);
record(&client, "aaaa").await.expect("written");
assert_eq!(recorded(&client).await.expect("read"), Some("aaaa".into()));
record(&client, "bbbb").await.expect("replaced");
assert_eq!(recorded(&client).await.expect("read"), Some("bbbb".into()));
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,11 @@
//! The deploy concern: the job graph and its worker, builds, the meta flake and
//! its fan-out, cache misses, config drift and the attic copy.
pub(crate) mod attic_copy;
pub(crate) mod builder;
pub(crate) mod cache_miss;
pub(crate) mod config_drift;
pub(crate) mod jobq;
pub(crate) mod meta_build;
pub(crate) mod meta_fanout;
pub(crate) mod meta_flake;