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/<agent> 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.
This commit is contained in:
parent
8a0615ccfc
commit
1a31a4cd5a
4 changed files with 499 additions and 25 deletions
|
|
@ -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;
|
||||
|
|
|
|||
159
swarm-controller/src/forge/repo_avatar.rs
Normal file
159
swarm-controller/src/forge/repo_avatar.rs
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
//! The avatar of an agent's config repo, `agent-configs/<agent>`: 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")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -80,6 +80,13 @@ pub(crate) trait MetaRepo {
|
|||
cleared: &str,
|
||||
resolved: &str,
|
||||
) -> impl Future<Output = Result<usize>> + 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<Output = Result<()>> + 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<std::sync::Arc<forge::Client>>,
|
||||
/// The repo avatars asked for, `None` being a removal; the forge
|
||||
/// refusing them is `avatar_fails`.
|
||||
avatars: Mutex<Vec<(String, Option<Vec<u8>>)>>,
|
||||
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: "<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: "<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: "<svg/>".to_owned(),
|
||||
png: None,
|
||||
}),
|
||||
vec![],
|
||||
),
|
||||
(
|
||||
Some(IconRead::Set {
|
||||
svg: "<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]
|
||||
|
|
|
|||
Loading…
Reference in a new issue