Watch
0
0
Fork
You've already forked hyperhive
0

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:
iris 2026-11-22 23:23:30 +01:00 • committed by mara
commit 1a31a4cd5a
2 changed files with 499 additions and 25 deletions

View 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")
);
}
}

View file

@ -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()