From 1a31a4cd5a856ffa012184a96535f9845d333109 Mon Sep 17 00:00:00 2001 From: iris Date: Sun, 22 Nov 2026 23:23:30 +0100 Subject: [PATCH] swarm: set an agent's config repo avatar from its icon The agent module exposes the PNG nix renders from the agent's icon as the read-only option services.hyperhive.agent.iconPng, which the forge and matrix avatar syncs now share. When the builder reads an icon it builds that one attribute with nix build and sends the file, base64, next to the SVG in the meta build reply, so the builder runs no renderer of its own. After recording the icon, the controller sets the avatar of agent-configs/ from the PNG as the forge admin, removes the avatar when the icon is removed, and leaves it alone when the builder sent no PNG. A marker per repo holds the image's fingerprint, so a build whose icon did not change makes no forge call; a forge that refuses the avatar does not fail the build. An old builder sends no PNG, so it changes nothing. --- Cargo.lock | 1 + docs/4-implementation/swarm/builder.md | 23 ++- docs/4-implementation/swarm/controller.md | 6 + nix/agent-modules/default.nix | 19 +++ nix/agent-modules/forge.nix | 12 +- nix/agent-modules/matrix.nix | 4 +- nix/module-eval/agent-icon.nix | 10 ++ swarm-builder/Cargo.toml | 2 + swarm-builder/src/nix_build.rs | 156 ++++++++++++++++- swarm-controller/src/forge.rs | 1 + swarm-controller/src/forge/repo_avatar.rs | 159 ++++++++++++++++++ swarm-controller/src/forge/service_avatars.rs | 2 +- swarm-controller/src/meta_build.rs | 117 ++++++++++++- swarm-wire/src/builder.rs | 12 +- 14 files changed, 499 insertions(+), 25 deletions(-) create mode 100644 swarm-controller/src/forge/repo_avatar.rs diff --git a/Cargo.lock b/Cargo.lock index 0b127158a..63112a43a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5441,6 +5441,7 @@ version = "0.1.0" dependencies = [ "anyhow", "async-nats", + "base64 0.22.1", "futures-util", "hive-log", "hive-types", diff --git a/docs/4-implementation/swarm/builder.md b/docs/4-implementation/swarm/builder.md index 124e1c2fe..eb644ac6a 100644 --- a/docs/4-implementation/swarm/builder.md +++ b/docs/4-implementation/swarm/builder.md @@ -322,15 +322,28 @@ closure record. The same `nix eval` reads the SVG file the option names (the eva applies `builtins.readFile`, so the builder needs no store path), and the reply's `icon` is one of: -- `set` with the SVG's text, for an option that names a file of at most 256 KiB; +- `set` with the SVG's text, for an option that names a file of at most 256 KiB, + and `png`, the 512 by 512 pixel PNG nix renders from it + (`services.hyperhive.agent.iconPng`, the image the agent uploads as its own + avatar). The builder builds that one attribute with `nix build` and reads the + file, so it runs no renderer of its own, and the reply carries it as base64 + when it's at most 256 KiB. A PNG that doesn't build or read back leaves `png` + out and still sends the SVG; - `unset`, for a null option or a module that doesn't declare it; - left out, for a failed eval, a timeout, an empty file or an oversize one. The controller writes the key `` of the `agent-icons` KV bucket from a -`set`, deletes it on `unset` and leaves it on a missing field. The controller logs a write -that fails and doesn't fail the build or the deploy. An agent's icon changes when -the swarm builds and deploys its config, not when its container restarts, and an -agent that has never run has one as soon as its first build succeeds. +`set`, deletes it on `unset` and leaves it on a missing field. The controller +logs a write that fails and doesn't fail the build or the deploy. The controller +also sets the avatar of the agent's config repo (`agent-configs/`) from +`png`, and removes it on `unset`; a `set` without a `png` leaves the avatar as +it is. A marker per repo in the controller's state directory +(`forge-repo-avatar-`) holds the image's SHA-256, so a build whose icon +didn't change makes no forge call, and `unset` deletes only an avatar the +controller set. A forge that refuses the avatar fails nothing; the next build +tries again. An agent's icon changes when the swarm builds and deploys its +config, not when its container restarts, and an agent that has never run has one +as soon as its first build succeeds. Mixed versions: diff --git a/docs/4-implementation/swarm/controller.md b/docs/4-implementation/swarm/controller.md index 3428644a4..5a35ac868 100644 --- a/docs/4-implementation/swarm/controller.md +++ b/docs/4-implementation/swarm/controller.md @@ -409,6 +409,12 @@ one per hive. It ensures them at start and every five minutes after - the `agent-configs` org avatar (`deploy.swarm-controller.configOrgAvatarPng`). +The config repos get the agent's icon too. When a build sets the agent's icon, +the controller sets the avatar of `agent-configs/` from the PNG the +builder rendered (`forge/repo_avatar.rs`), as the forge admin, who may edit any +repo's avatar. A marker per repo (`forge-repo-avatar-`) holds the image's +SHA-256, as for the service accounts below. + The swarm's own forge accounts (`builder`, `ci-metrics` and `review-classifier`) get an avatar too, from a separate pass in the controller (`forge/service_avatars.rs`). Each has an icon in a hexagonal frame (`branding/service-.svg`, rendered to a PNG diff --git a/nix/agent-modules/default.nix b/nix/agent-modules/default.nix index 72d725f98..7b55dddcd 100644 --- a/nix/agent-modules/default.nix +++ b/nix/agent-modules/default.nix @@ -149,6 +149,25 @@ in ''; }; + options.services.hyperhive.agent.iconPng = lib.mkOption { + type = lib.types.nullOr lib.types.package; + readOnly = true; + default = + if config.services.hyperhive.agent.icon == null then + null + else + pkgs.runCommand "hive-agent-icon.png" { nativeBuildInputs = [ pkgs.librsvg ]; } '' + rsvg-convert -f png -w 512 -h 512 ${config.services.hyperhive.agent.icon} -o $out + ''; + defaultText = lib.literalMD "`icon` rasterized to a 512×512 PNG, or `null` when no icon is set"; + description = '' + `icon` rasterized to a 512×512 PNG at build time: the image the agent + uploads as its forge and matrix avatar, and the one the swarm builder + builds and sends to the controller, which sets it as the avatar of the + agent's config repo. Read-only; `null` when no icon is set. + ''; + }; + config = { assertions = [ # Guard the inputs-routed-as-output pattern: the agent flake.nix is diff --git a/nix/agent-modules/forge.nix b/nix/agent-modules/forge.nix index ef21e43f1..cdd04c042 100644 --- a/nix/agent-modules/forge.nix +++ b/nix/agent-modules/forge.nix @@ -21,13 +21,11 @@ let if [ -s "$f" ] && [ -r "$f" ]; then TOKEN_FILE="$f"; break; fi done ''; - # Same 512×512 rasterization of the agent icon the matrix avatar - # sync uses (./matrix.nix — identical derivation, same store path). - # Only forced when an icon is configured AND a forge is (the avatar-sync - # unit below, the one thing that references this, is gated on both). - iconPng = pkgs.runCommand "hive-agent-icon.png" { nativeBuildInputs = [ pkgs.librsvg ]; } '' - rsvg-convert -f png -w 512 -h 512 ${config.services.hyperhive.agent.icon} -o $out - ''; + # The 512×512 rasterization of the agent icon (`services.hyperhive.agent.iconPng`, + # declared in ./default.nix and shared with the matrix avatar sync and the + # swarm builder). Only forced when an icon is configured AND a forge is (the + # avatar-sync unit below, the one thing that references this, is gated on both). + iconPng = config.services.hyperhive.agent.iconPng; # git credential helper for the hive forge --- the exact shape # `./github.nix` uses for github.com, for the same two reasons: the token diff --git a/nix/agent-modules/matrix.nix b/nix/agent-modules/matrix.nix index c6fec6b55..a938ce0f6 100644 --- a/nix/agent-modules/matrix.nix +++ b/nix/agent-modules/matrix.nix @@ -46,9 +46,7 @@ let # Only forced when an icon is configured — the `HIVE_ICON_PNG` daemon-env # entry is gated on `services.hyperhive.agent.icon != null`, so this binding stays lazy # when no icon is set. - iconPng = pkgs.runCommand "hive-agent-icon.png" { nativeBuildInputs = [ pkgs.librsvg ]; } '' - rsvg-convert -f png -w 512 -h 512 ${config.services.hyperhive.agent.icon} -o $out - ''; + iconPng = config.services.hyperhive.agent.iconPng; in { options.services.hyperhive.agent.matrix.url = lib.mkOption { diff --git a/nix/module-eval/agent-icon.nix b/nix/module-eval/agent-icon.nix index f88430642..b63e89a3a 100644 --- a/nix/module-eval/agent-icon.nix +++ b/nix/module-eval/agent-icon.nix @@ -29,7 +29,17 @@ let # SVG: the icon is only ever a gate here, and nothing this case reads # rasterizes it. agentIconNoForge = agentWith { services.hyperhive.agent.icon = pkgs.emptyFile; }; + agentNoIcon = agentWith { }; cases = [ + { + # The builder builds this option and sends the PNG to the controller for + # the config repo's avatar, so it must be a derivation when an icon is set + # and null when none is (the builder skips the build then). + name = "iconPng is the rasterized icon, and null without one"; + ok = + lib.isDerivation agentIconNoForge.services.hyperhive.agent.iconPng + && agentNoIcon.services.hyperhive.agent.iconPng == null; + } { # The absence class, and a gate asymmetry nothing else can see. A `.path` # unit is `wantedBy = multi-user.target` and names a `Unit=` by diff --git a/swarm-builder/Cargo.toml b/swarm-builder/Cargo.toml index f1cd1212e..e4848cadf 100644 --- a/swarm-builder/Cargo.toml +++ b/swarm-builder/Cargo.toml @@ -11,6 +11,8 @@ path = "src/main.rs" [dependencies] anyhow.workspace = true async-nats.workspace = true +# The icon's PNG rides in the reply as base64. +base64.workspace = true # StreamExt::next on the subscription. futures-util.workspace = true hive-log.workspace = true diff --git a/swarm-builder/src/nix_build.rs b/swarm-builder/src/nix_build.rs index aba96310a..49d32206a 100644 --- a/swarm-builder/src/nix_build.rs +++ b/swarm-builder/src/nix_build.rs @@ -247,6 +247,40 @@ impl Builder { } } + /// The agent's icon as the PNG the forge takes as an avatar, base64: the + /// image nix itself renders from the icon (`services.hyperhive.agent.iconPng`), + /// built here so the builder runs no renderer of its own. `None` when it + /// did not build or read back: the reply then carries the SVG alone, which + /// leaves the avatar as it is. + async fn icon_png(&self, job: &BuildFromMeta, token: &str) -> Option { + use base64::Engine as _; + let mut cmd = self.nix_command(token); + cmd.args(BUILD_FLAGS) + .arg(format!("{}.{ICON_PNG_OPTION}", self.meta_config(job))); + let path = match run_raw(cmd, self.deadline).await { + Ok((status, out, _)) if status.success() => String::from_utf8_lossy(&out) + .lines() + .next()? + .trim() + .to_owned(), + Ok((status, _, err)) => { + tracing::warn!(agent = %job.agent, error = %tail(&String::from_utf8_lossy(&err), status), "the agent's icon PNG did not build; the reply carries the SVG alone"); + return None; + } + Err(why) => { + tracing::warn!(agent = %job.agent, %why, "the agent's icon PNG did not build; the reply carries the SVG alone"); + return None; + } + }; + match read_png(std::path::Path::new(&path)).await { + Ok(png) => Some(base64::engine::general_purpose::STANDARD.encode(png)), + Err(why) => { + tracing::warn!(agent = %job.agent, %why, "the agent's icon PNG was not read; the reply carries the SVG alone"); + None + } + } + } + /// The agent's `services.hyperhive.agent.icon`: the text of the SVG file the /// option names, read by the eval itself so the builder needs no store /// path. An option that is null, or that the agent's module does not declare, @@ -257,7 +291,13 @@ impl Builder { .eval_option_applied(job, token, ICON_OPTION, Some(ICON_APPLY)) .await { - Eval::Value(out) => parse_icon(&out), + Eval::Value(out) => match parse_icon(&out)? { + IconRead::Set { svg, .. } => { + let png = self.icon_png(job, token).await; + Some(IconRead::Set { svg, png }) + } + unset @ IconRead::Unset => Some(unset), + }, Eval::Missing => Some(IconRead::Unset), Eval::Unknown => None, } @@ -314,6 +354,14 @@ const ICON_APPLY: &str = "p: if p == null then null else builtins.readFile p"; /// and an icon is a small drawing. A larger file is left out as unread. const ICON_MAX_BYTES: usize = 256 * 1024; +/// The agent option holding the PNG nix renders from its icon: a derivation, or +/// null when there is no icon. +const ICON_PNG_OPTION: &str = "services.hyperhive.agent.iconPng"; + +/// The largest rendering the reply carries, in bytes. An icon at that size is +/// far below it; a drawing that is not is left out. +const ICON_PNG_MAX_BYTES: usize = 256 * 1024; + /// What `nix eval --json` of an agent option came to. enum Eval { /// It printed a value. @@ -353,10 +401,29 @@ fn parse_icon(out: &[u8]) -> Option { ); None } - Some(svg) => Some(IconRead::Set { svg }), + Some(svg) => Some(IconRead::Set { svg, png: None }), } } +/// The PNG file at `path`, which `nix build` printed: not empty, and at most +/// [`ICON_PNG_MAX_BYTES`]. +async fn read_png(path: &std::path::Path) -> Result, String> { + let png = tokio::fs::read(path) + .await + .map_err(|e| format!("reading {}: {e}", path.display()))?; + if png.is_empty() { + return Err(format!("{} is empty", path.display())); + } + if png.len() > ICON_PNG_MAX_BYTES { + return Err(format!( + "{} is {} bytes, over the {ICON_PNG_MAX_BYTES} the reply carries", + path.display(), + png.len() + )); + } + Ok(png) +} + /// `nix eval --json` of a [`NixBuilds`]: the spelling, or `None` when the /// output is not a string. fn parse_nix_builds(out: &[u8]) -> Option { @@ -730,6 +797,7 @@ mod tests { "echo '\"\"'", Some(IconRead::Set { svg: "".to_owned(), + png: None, }), ), ("echo null", Some(IconRead::Unset)), @@ -756,6 +824,90 @@ mod tests { } } + /// A `nix` that answers the icon option with an SVG and the PNG option with + /// what `png` makes of a file path, a build for anything else with a store path. + fn icon_nix(tag: &str, png: &str) -> PathBuf { + fake_nix( + tag, + &format!( + "for a in \"$@\"; do last=$a; done; case \"$last\" in *agent.iconPng) {png};; *agent.icon) echo '\"\"';; *) if [ \"$1\" = eval ]; then echo false; else echo /nix/store/x; fi;; esac\n" + ), + ) + } + + /// The PNG nix renders goes in the reply, base64, beside the SVG; one that + /// did not build, is missing, empty or too large leaves the PNG out and still + /// sends the SVG. + #[tokio::test] + async fn an_icon_png_nix_built_goes_in_the_reply() { + use base64::Engine as _; + let dir = std::env::temp_dir().join(format!("icon-png-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("scratch dir"); + let ok = dir.join("ok.png"); + std::fs::write(&ok, "PNGDATA").expect("write png"); + let empty = dir.join("empty.png"); + std::fs::write(&empty, "").expect("write png"); + let big = dir.join("big.png"); + std::fs::write(&big, vec![0u8; ICON_PNG_MAX_BYTES + 1]).expect("write png"); + for (i, (answer, want)) in [ + ( + format!("echo {}", ok.display()), + Some(base64::engine::general_purpose::STANDARD.encode("PNGDATA")), + ), + ("echo error: boom >&2; exit 1".to_owned(), None), + (format!("echo {}", dir.join("missing.png").display()), None), + (format!("echo {}", empty.display()), None), + (format!("echo {}", big.display()), None), + ("true".to_owned(), None), + ] + .into_iter() + .enumerate() + { + let b = Builder { + nix: icon_nix(&format!("png-{i}"), &answer), + ..builder() + }; + let reply = b.build_from_meta(&meta_job(), "t").await; + let FromMetaReply::Built { + icon: Some(IconRead::Set { svg, png }), + .. + } = reply + else { + panic!("{answer}: {reply:?}"); + }; + assert_eq!(svg, ""); + assert_eq!(png, want, "{answer}"); + } + let _ = std::fs::remove_dir_all(&dir); + } + + /// An agent with no icon has no PNG to build: the PNG option is not read. + #[tokio::test] + async fn an_agent_with_no_icon_builds_no_png() { + let nix = fake_nix( + "no-icon-png", + "for a in \"$@\"; do last=$a; done; case \"$last\" in *agent.iconPng) echo called > \"$0.called\"; echo /nix/store/x;; *agent.icon) echo null;; *) if [ \"$1\" = eval ]; then echo false; else echo /nix/store/x; fi;; esac\n", + ); + let marker = PathBuf::from(format!("{}.called", nix.display())); + let _ = std::fs::remove_file(&marker); + let b = Builder { nix, ..builder() }; + let reply = b.build_from_meta(&meta_job(), "t").await; + assert!( + matches!( + &reply, + FromMetaReply::Built { + icon: Some(IconRead::Unset), + .. + } + ), + "{reply:?}" + ); + assert!( + !marker.exists(), + "the PNG option was read for an agent with no icon" + ); + } + /// An icon file over the cap is left out of the reply rather than sent: the /// reply is one queue message. #[test] diff --git a/swarm-controller/src/forge.rs b/swarm-controller/src/forge.rs index 75461be34..75a228423 100644 --- a/swarm-controller/src/forge.rs +++ b/swarm-controller/src/forge.rs @@ -61,6 +61,7 @@ pub mod operator_profiles; pub(crate) mod pr_comment; pub mod pr_report; pub mod pull_diff; +pub mod repo_avatar; pub mod review_request; pub mod runner_token; pub mod service_avatars; diff --git a/swarm-controller/src/forge/repo_avatar.rs b/swarm-controller/src/forge/repo_avatar.rs new file mode 100644 index 000000000..ea22f259f --- /dev/null +++ b/swarm-controller/src/forge/repo_avatar.rs @@ -0,0 +1,159 @@ +//! The avatar of an agent's config repo, `agent-configs/`: the agent's +//! icon, so the repos are told apart in the forge's lists. The builder renders +//! the icon to a PNG when it builds the agent (the forge takes bitmaps), and +//! the controller sets it here; an agent whose icon is removed loses it, and the +//! forge shows its default again. +//! +//! The controller sets the avatar as the forge admin, which may edit any repo's. +//! A marker per repo under the state directory holds the fingerprint of the +//! image last set, so a build whose icon did not change makes no forge call, the +//! way [`super::service_avatars`] spares its uploads. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use base64::Engine as _; +use forgejo_api::structs::UpdateRepoAvatarOption; + +use super::service_avatars::fingerprint; +use super::{Client, is_repo_not_found}; + +/// What a build's icon asks of the forge. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Step { + /// The avatar is as the icon wants it already. + Keep, + /// Upload the image, then record this fingerprint. + Set(String), + /// Delete the avatar we set, then forget the fingerprint. + Remove, +} + +/// What to do for an icon: `png` is its rendering (`None` for an agent with no +/// icon), `last` the fingerprint of the image set before (`None` for none). +pub(crate) fn plan(last: Option<&str>, png: Option<&[u8]>) -> Step { + match (png, last) { + (Some(png), Some(last)) if fingerprint(png) == last => Step::Keep, + (Some(png), _) => Step::Set(fingerprint(png)), + (None, Some(_)) => Step::Remove, + (None, None) => Step::Keep, + } +} + +/// Where `repo`'s marker lives. +fn marker(state_dir: &Path, repo: &str) -> PathBuf { + state_dir.join(format!("forge-repo-avatar-{repo}")) +} + +impl Client { + /// Make `owner/repo`'s avatar the PNG `png`, or remove it for `None`, unless + /// that is what was set last. Done by the controller, as the forge admin. + /// + /// # Errors + /// The forge refusing the upload or the delete; a marker that cannot be + /// written only costs a repeat call. + pub async fn sync_repo_avatar( + &self, + owner: &str, + repo: &str, + png: Option<&[u8]>, + ) -> Result<()> { + let marker = marker(&crate::webhook::state_dir(), repo); + let seen = std::fs::read_to_string(&marker).ok(); + match plan(seen.as_deref().map(str::trim), png) { + Step::Keep => Ok(()), + Step::Set(print) => { + let image = + base64::engine::general_purpose::STANDARD.encode(png.unwrap_or_default()); + self.api + .call(|api| { + api.repo_update_avatar( + owner, + repo, + UpdateRepoAvatarOption { + image: Some(image.clone()), + }, + ) + .into_future() + }) + .await + .with_context(|| format!("set the avatar of {owner}/{repo}"))?; + write_marker(&marker, &print); + tracing::info!(%owner, %repo, "repo avatar: set from the agent's icon"); + Ok(()) + } + Step::Remove => { + match self + .api + .call(|api| api.repo_delete_avatar(owner, repo).into_future()) + .await + { + Ok(()) => {} + // The repo is gone, so its avatar is too. + Err(e) if is_repo_not_found(&e) => {} + Err(e) => { + return Err(e) + .with_context(|| format!("remove the avatar of {owner}/{repo}")); + } + } + if let Err(e) = std::fs::remove_file(&marker) + && e.kind() != std::io::ErrorKind::NotFound + { + tracing::warn!(error = %e, marker = %marker.display(), "repo avatar: removed, but its marker could not be deleted"); + } + tracing::info!(%owner, %repo, "repo avatar: removed with the agent's icon"); + Ok(()) + } + } + } +} + +fn write_marker(marker: &Path, print: &str) { + if let Err(e) = std::fs::write(marker, print) { + tracing::warn!(error = %e, marker = %marker.display(), "repo avatar: set, but its marker could not be written"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_new_icon_is_set() { + let png = b"PNG one"; + assert_eq!(plan(None, Some(png)), Step::Set(fingerprint(png))); + } + + #[test] + fn the_same_icon_again_makes_no_call() { + let png = b"PNG one"; + assert_eq!(plan(Some(&fingerprint(png)), Some(png)), Step::Keep); + } + + #[test] + fn a_changed_icon_is_set_again() { + let (old, new) = (b"PNG one", b"PNG two"); + assert_eq!( + plan(Some(&fingerprint(old)), Some(new)), + Step::Set(fingerprint(new)) + ); + } + + /// Only an avatar the controller set is taken away: an agent that never had + /// an icon costs no delete on each build. + #[test] + fn a_removed_icon_removes_the_avatar_we_set_and_only_that() { + assert_eq!(plan(Some("abc"), None), Step::Remove); + assert_eq!(plan(None, None), Step::Keep); + } + + #[test] + fn each_repo_has_its_own_marker() { + let dir = Path::new("/state"); + assert_ne!(marker(dir, "atlas"), marker(dir, "argus")); + assert_eq!( + marker(dir, "atlas"), + Path::new("/state/forge-repo-avatar-atlas") + ); + } +} diff --git a/swarm-controller/src/forge/service_avatars.rs b/swarm-controller/src/forge/service_avatars.rs index 87343cd2a..0eb9477f9 100644 --- a/swarm-controller/src/forge/service_avatars.rs +++ b/swarm-controller/src/forge/service_avatars.rs @@ -67,7 +67,7 @@ fn pick_icon(dir: &Path, login: &str) -> PathBuf { } /// What the marker holds: the SHA-256 of the image, in hex. -fn fingerprint(image: &[u8]) -> String { +pub(super) fn fingerprint(image: &[u8]) -> String { use std::fmt::Write as _; Sha256::digest(image) .iter() diff --git a/swarm-controller/src/meta_build.rs b/swarm-controller/src/meta_build.rs index a28631854..beb090d63 100644 --- a/swarm-controller/src/meta_build.rs +++ b/swarm-controller/src/meta_build.rs @@ -80,6 +80,13 @@ pub(crate) trait MetaRepo { cleared: &str, resolved: &str, ) -> impl Future> + Send; + /// Make the avatar of `agent`'s config repo the PNG `png`, or remove it + /// for `None`. + fn set_repo_avatar( + &self, + agent: &str, + png: Option<&[u8]>, + ) -> impl Future> + Send; } impl MetaRepo for forge::Client { @@ -127,6 +134,14 @@ impl MetaRepo for forge::Client { ) .await } + + async fn set_repo_avatar(&self, agent: &str, png: Option<&[u8]>) -> Result<()> { + crate::jobq::forge_node( + "build_meta", + self.sync_repo_avatar(forge::CONFIG_ORG, agent, png), + ) + .await + } } /// Where a build is sent and its closure recorded: the queue in production, a @@ -185,7 +200,7 @@ impl MetaBuilds for async_nats::Client { .await .context("opening the agent-icons bucket")?; match icon { - IconRead::Set { svg } => store + IconRead::Set { svg, .. } => store .put(agent, svg.clone().into_bytes().into()) .await .map(|_| ()) @@ -198,6 +213,30 @@ impl MetaBuilds for async_nats::Client { } } +/// Follow the agent's icon in the avatar of its config repo: a rendered icon +/// sets it, an icon that was removed removes it, and an icon the builder could +/// not render leaves it as it is. Like the icon above, a failure is logged and +/// leaves the deploy alone: the next build tries again. +async fn set_repo_avatar(head: &impl MetaRepo, agent: &str, icon: &IconRead) { + use base64::Engine as _; + let png = match icon { + IconRead::Set { png: Some(png), .. } => { + match base64::engine::general_purpose::STANDARD.decode(png) { + Ok(bytes) => Some(bytes), + Err(e) => { + tracing::warn!(%agent, error = %e, "build_meta: the builder's icon rendering is not base64; the repo avatar is left as it is"); + return; + } + } + } + IconRead::Set { png: None, .. } => return, + IconRead::Unset => None, + }; + if let Err(e) = head.set_repo_avatar(agent, png.as_deref()).await { + tracing::warn!(%agent, error = %format!("{e:#}"), "build_meta: the agent's repo avatar was not updated"); + } +} + /// The most of `nix`'s tail a PR comment carries, in bytes: the builder's own cap /// on the tail it sends. const COMMENT_TAIL_BYTES: usize = 4000; @@ -398,10 +437,11 @@ pub(crate) async fn run( // The icon is the agent's config, so it follows the build, not the // cache push or the record below. A write that fails is logged and // leaves the deploy alone: the next build writes it again. - if let Some(icon) = &icon - && let Err(e) = queue.record_icon(&agent, icon).await - { - tracing::warn!(%agent, error = %format!("{e:#}"), "build_meta: the agent's icon was not recorded"); + if let Some(icon) = &icon { + if let Err(e) = queue.record_icon(&agent, icon).await { + tracing::warn!(%agent, error = %format!("{e:#}"), "build_meta: the agent's icon was not recorded"); + } + set_repo_avatar(head, &agent, icon).await; } let built_rev = meta_rev.clone(); let closure = AgentClosure { @@ -448,6 +488,10 @@ mod tests { grant_fails: bool, /// The forge a PR comment goes to; `None` panics on a comment. comments: Option>, + /// The repo avatars asked for, `None` being a removal; the forge + /// refusing them is `avatar_fails`. + avatars: Mutex>)>>, + avatar_fails: bool, } impl FakeHead { @@ -456,6 +500,8 @@ mod tests { head, grant_fails: false, comments: None, + avatars: Mutex::new(Vec::new()), + avatar_fails: false, } } } @@ -499,6 +545,15 @@ mod tests { .clear_marker(forge::CONFIG_ORG, agent, pr, marker, cleared, resolved) .await } + + async fn set_repo_avatar(&self, agent: &str, png: Option<&[u8]>) -> Result<()> { + anyhow::ensure!(!self.avatar_fails, "the forge refused the avatar"); + self.avatars + .lock() + .unwrap() + .push((agent.to_owned(), png.map(<[u8]>::to_vec))); + Ok(()) + } } /// A queue that answers every build with `reply`, and keeps what it was @@ -728,6 +783,7 @@ mod tests { async fn the_icon_the_builder_read_is_set_removed_or_left() { let svg = IconRead::Set { svg: "".to_owned(), + png: None, }; for (read, written) in [ (Some(svg.clone()), vec![("atlas".to_owned(), svg)]), @@ -746,6 +802,57 @@ mod tests { } } + /// The repo avatar follows the icon: a rendered icon sets it, a removed one + /// removes it, and one the builder could not render leaves it alone. + #[tokio::test] + async fn the_repo_avatar_follows_the_icon() { + use base64::Engine as _; + let png = base64::engine::general_purpose::STANDARD.encode("PNGDATA"); + for (read, asked) in [ + ( + Some(IconRead::Set { + svg: "".to_owned(), + png: Some(png), + }), + vec![("atlas".to_owned(), Some(b"PNGDATA".to_vec()))], + ), + (Some(IconRead::Unset), vec![("atlas".to_owned(), None)]), + ( + Some(IconRead::Set { + svg: "".to_owned(), + png: None, + }), + vec![], + ), + ( + Some(IconRead::Set { + svg: "".to_owned(), + png: Some("not base64!".to_owned()), + }), + vec![], + ), + (None, vec![]), + ] { + let head = FakeHead::reading(Ok(Some(REV))); + let queue = FakeQueue::built_with_icon(read); + assert_eq!(run_with(&head, &queue).await, Outcome::Done); + assert_eq!(*head.avatars.lock().unwrap(), asked); + } + } + + /// The avatar is not what the deploy waits on either: a forge that refuses + /// it leaves the build green and the closure recorded. + #[tokio::test] + async fn a_repo_avatar_the_forge_refuses_does_not_fail_the_build() { + let head = FakeHead { + avatar_fails: true, + ..FakeHead::reading(Ok(Some(REV))) + }; + let queue = FakeQueue::built_with_icon(Some(IconRead::Unset)); + assert_eq!(run_with(&head, &queue).await, Outcome::Done); + assert_eq!(queue.recorded.lock().unwrap().len(), 1, "still recorded"); + } + /// The icon is not what the deploy waits on: a write the queue refuses /// leaves the build green. #[tokio::test] diff --git a/swarm-wire/src/builder.rs b/swarm-wire/src/builder.rs index 5bdb8498c..233749f70 100644 --- a/swarm-wire/src/builder.rs +++ b/swarm-wire/src/builder.rs @@ -141,8 +141,15 @@ pub struct BuildFromMeta { #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "state", rename_all = "kebab-case")] pub enum IconRead { - /// The option names an SVG file; `svg` is its text. - Set { svg: String }, + /// The option names an SVG file; `svg` is its text, and `png` is the + /// builder's rendering of it, base64, for the forge, whose avatars are + /// bitmaps. `png` is absent when the builder could not render it, and from a + /// builder that predates it; neither removes an avatar. + Set { + svg: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + png: Option, + }, /// The option is not set: the agent has no icon, and an icon it had is /// removed. Unset, @@ -294,6 +301,7 @@ mod tests { nix_builds: Some(NixBuilds::Disabled), icon: Some(IconRead::Set { svg: "".to_owned(), + png: None, }), }, json!({