Watch
0
0
Fork
You've already forked hyperhive
0

swarm-controller: the forge webhook takes two narrow sub-states

This commit is contained in:
atlas 2026-11-30 03:46:25 +01:00
commit 98341e24a6
6 changed files with 231 additions and 42 deletions

View file

@ -930,7 +930,16 @@ pub(crate) async fn read_declarations<'a>(
state: &AppState,
hives: impl Iterator<Item = &'a HiveEntry>,
) -> Result<Vec<(String, swarm_wire::wanted::HiveWanted)>, (String, anyhow::Error)> {
let Some(writer) = state.wanted.as_deref() else {
read_declarations_of(state.wanted.as_deref(), hives).await
}
/// [`read_declarations`] over the wanted-state writer alone, for a caller that
/// holds only that.
pub(crate) async fn read_declarations_of<'a>(
writer: Option<&wanted::WantedWriter>,
hives: impl Iterator<Item = &'a HiveEntry>,
) -> Result<Vec<(String, swarm_wire::wanted::HiveWanted)>, (String, anyhow::Error)> {
let Some(writer) = writer else {
return Ok(Vec::new());
};
let mut declared = Vec::new();

View file

@ -6,8 +6,7 @@ use std::sync::{Arc, Mutex};
use anyhow::Result;
use swarm_authelia_bridge_sock::BridgeResponse;
use crate::routes::AppState;
use crate::routes::agents::{claiming_hives, read_declarations};
use crate::routes::agents::{claiming_hives, read_declarations_of};
use crate::startup::PUBLIC_URL_ENV;
use crate::{
agent_identity, agent_renewal, auth, builder, config_pr, forge, matrix_account, meta_build,
@ -1295,11 +1294,13 @@ pub(crate) fn spawn_jobq_worker(
/// Queue a build check of a config PR's new head. Every head is built, on
/// whichever hive the agent runs: the check builds on the builder's own
/// agent base.
pub(crate) fn queue_config_build(state: &AppState, changed: config_pr::ChangedConfigPr) {
pub(crate) fn queue_config_build(
jobq: &Mutex<hive_jobq::scheduler::Scheduler<SwarmNodeKind, SwarmResourceKind>>,
changed: config_pr::ChangedConfigPr,
) {
let (agent, rev, pr) = (changed.agent.clone(), changed.rev.clone(), changed.pr);
let queued = queue_build(
&mut state
.jobq
&mut jobq
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner),
changed,
@ -1354,11 +1355,13 @@ pub(crate) fn queue_build(
/// records an agent's hive (see `forge::initial_agent_nix`). Zero claimants or
/// several deploy nothing: there is no hive to send it to, or no telling which.
pub(crate) async fn queue_merged_config_deploy(
state: &AppState,
wanted: Option<&crate::wanted::WantedWriter>,
hives: &[crate::routes::hives::HiveEntry],
jobq: &Mutex<hive_jobq::scheduler::Scheduler<SwarmNodeKind, SwarmResourceKind>>,
merged: config_pr::MergedConfigPr,
) {
let config_pr::MergedConfigPr { agent, rev, pr } = merged;
let declared = match read_declarations(state, state.hives.iter()).await {
let declared = match read_declarations_of(wanted, hives.iter()).await {
Ok(declared) => declared,
Err((hive, e)) => {
tracing::warn!(
@ -1376,7 +1379,7 @@ pub(crate) async fn queue_merged_config_deploy(
);
return;
};
insert_merged_deploy(&state.jobq, hive, &agent, &rev, Some(pr));
insert_merged_deploy(jobq, hive, &agent, &rev, Some(pr));
}
/// Insert the [`merged_deploy_job`] of `agent`'s config at `rev` on `hive`.

View file

@ -15,8 +15,11 @@
//! `pull_request_mergeability` event of `crate::pr_conflicts`, the same way.
use axum::http::HeaderMap;
use std::sync::Arc;
use std::time::Duration;
use crate::status::StatusReader;
/// The header naming the delivery's event type.
const EVENT_TYPE_HEADER: &str = "x-forgejo-event-type";
@ -49,7 +52,7 @@ fn subject(headers: &HeaderMap) -> Result<String, NotKept> {
/// Keep one verified delivery in the stream, and wait for the stream's ack.
pub(crate) async fn publish(
state: &crate::routes::AppState,
status: Option<&Arc<StatusReader>>,
headers: &HeaderMap,
body: axum::body::Bytes,
) -> Result<(), NotKept> {
@ -58,13 +61,13 @@ pub(crate) async fn publish(
if let Some(id) = headers.get(DELIVERY_HEADER).and_then(|v| v.to_str().ok()) {
message = message.message_id(id);
}
keep(state, subject, message).await
keep(status, subject, message).await
}
/// Keep an event this daemon makes itself, of `event_type`, in the stream, and
/// wait for the stream's ack. The router reads it like a delivery.
pub(crate) async fn publish_event(
state: &crate::routes::AppState,
status: Option<&Arc<StatusReader>>,
event_type: &str,
body: Vec<u8>,
) -> Result<(), NotKept> {
@ -73,7 +76,7 @@ pub(crate) async fn publish_event(
}
let message = async_nats::jetstream::message::PublishMessage::build().payload(body.into());
keep(
state,
status,
swarm_wire::forge_events::subject(event_type),
message,
)
@ -81,11 +84,11 @@ pub(crate) async fn publish_event(
}
async fn keep(
state: &crate::routes::AppState,
status: Option<&Arc<StatusReader>>,
subject: String,
message: async_nats::jetstream::message::PublishMessage,
) -> Result<(), NotKept> {
let Some(status) = state.status.as_ref() else {
let Some(status) = status else {
return Err(NotKept::Queue("no swarm queue is configured".to_owned()));
};
let client = status.queue_client();

View file

@ -17,14 +17,16 @@
use std::collections::{BTreeSet, HashMap, HashSet};
use std::future::Future;
use std::sync::{LazyLock, Mutex, PoisonError};
use std::sync::{Arc, LazyLock, Mutex, PoisonError};
use std::time::Duration;
use forgejo_api::structs::PullRequest;
use serde_json::{Value as Json, json};
use swarm_wire::forge_events::MERGEABILITY_EVENT;
use crate::routes::AppState;
use crate::forge::Client;
use crate::jobq::Late;
use crate::status::StatusReader;
/// How long after a push the forge gets to recompute before the first read.
const SETTLE: Duration = Duration::from_secs(30);
@ -352,16 +354,16 @@ async fn bounded<T>(work: &str, fut: impl Future<Output = anyhow::Result<T>>) ->
/// A push arrived on the `vcs-activity` hook. Starts the check for its branch
/// unless the branch has no PR to find or a check is already under way, in
/// which case that one runs again when it is done.
pub(crate) fn on_push(state: &AppState, body: &[u8]) {
pub(crate) fn on_push(forge: &Late<Arc<Client>>, status: Option<&Arc<StatusReader>>, body: &[u8]) {
let Some(push) = BranchPush::parse(body) else {
return;
};
if begin_check(&OPEN_PULLS, &RUNNING, &push) {
tokio::spawn(watch(state.clone(), push));
tokio::spawn(watch(Arc::clone(forge), status.cloned(), push));
}
}
async fn watch(state: AppState, push: BranchPush) {
async fn watch(forge: Late<Arc<Client>>, status: Option<Arc<StatusReader>>, push: BranchPush) {
let mut running = Held {
debounce: &RUNNING,
key: push.key(),
@ -372,7 +374,7 @@ async fn watch(state: AppState, push: BranchPush) {
};
loop {
tokio::time::sleep(SETTLE).await;
if let Some(forge) = state.forge.get() {
if let Some(forge) = forge.get() {
check(
&push,
RECHECK,
@ -385,10 +387,10 @@ async fn watch(state: AppState, push: BranchPush) {
Ok(listed.iter().filter_map(Pull::from_listed).collect())
},
|action, body| {
let (state, push) = (&state, &push);
let (status, push) = (status.as_ref(), &push);
async move {
if let Err(not_kept) =
crate::forge_events::publish_event(state, MERGEABILITY_EVENT, body)
crate::forge_events::publish_event(status, MERGEABILITY_EVENT, body)
.await
{
tracing::warn!(repo = %push.repo, action, reason = ?not_kept, "pr conflicts: event not kept");

View file

@ -18,16 +18,21 @@
use anyhow::{Context as _, Result};
use axum::{
body::Bytes,
extract::{Path, State},
extract::{FromRef, Path, State},
http::{HeaderMap, StatusCode},
response::{IntoResponse as _, Response},
};
use hive_jobq::scheduler::Scheduler;
use hmac::{Hmac, KeyInit as _, Mac as _};
use sha2::Sha256;
use std::sync::Arc;
use std::sync::{Arc, Mutex};
use crate::jobq::Late;
use crate::jobq::{Late, SwarmNodeKind, SwarmResourceKind};
use crate::review_classifier::runs::Runs;
use crate::routes::AppState;
use crate::routes::hives::HiveEntry;
use crate::status::StatusReader;
use crate::wanted::WantedWriter;
/// The legacy home of the HMAC secret, relative to the daemon's state directory.
///
@ -574,6 +579,56 @@ pub(crate) fn verify(
.map_err(|_| Refusal::BadSignature("X-Hub-Signature-256 mismatch".to_owned()))
}
/// What the webhook handler may reach of [`AppState`] to verify and route a
/// delivery: the HMAC secret, the swarm queue, the forge, and the review runs.
///
/// Derived per request from [`AppState`] (`FromRef`), so each field is a clone
/// of the same `Arc` or cheap handle and nothing is held twice. `forge` and
/// `webhook_secret` stay the late cells, so a value that arrives after startup
/// is seen by the next request and by a task spawned from this one.
#[derive(Clone)]
pub(crate) struct WebhookState {
pub(crate) webhook_secret: Late<Arc<str>>,
pub(crate) status: Option<Arc<StatusReader>>,
pub(crate) forge: Late<Arc<crate::forge::Client>>,
pub(crate) runs: Runs,
}
impl FromRef<AppState> for WebhookState {
fn from_ref(state: &AppState) -> Self {
Self {
webhook_secret: Arc::clone(&state.webhook_secret),
status: state.status.clone(),
forge: Arc::clone(&state.forge),
runs: state.runs.clone(),
}
}
}
/// What the webhook handler may reach of [`AppState`] to act on a `config-pr`
/// delivery: the config-PR cache, the job graph, and the wanted state and hive
/// list that say where a merged PR's agent runs.
///
/// A second sub-state beside [`WebhookState`], so neither passes six fields.
#[derive(Clone)]
pub(crate) struct ConfigDeployState {
pub(crate) config_prs: Late<Arc<crate::config_pr::ConfigPrCache>>,
pub(crate) jobq: Arc<Mutex<Scheduler<SwarmNodeKind, SwarmResourceKind>>>,
pub(crate) wanted: Option<Arc<WantedWriter>>,
pub(crate) hives: Arc<Vec<HiveEntry>>,
}
impl FromRef<AppState> for ConfigDeployState {
fn from_ref(state: &AppState) -> Self {
Self {
config_prs: Arc::clone(&state.config_prs),
jobq: Arc::clone(&state.jobq),
wanted: state.wanted.clone(),
hives: Arc::clone(&state.hives),
}
}
}
/// POST `/webhook/forge/{kind}` — a swarm-wide Forgejo delivery.
///
/// Verifies the HMAC over the raw body, then acts per `kind`: a `Knowledge`
@ -619,7 +674,8 @@ pub(crate) fn verify(
tag = "webhook"
)]
pub(crate) async fn post_webhook_forge(
State(state): State<AppState>,
State(hook): State<WebhookState>,
State(deploy): State<ConfigDeployState>,
Path(kind): Path<String>,
headers: HeaderMap,
body: Bytes,
@ -628,7 +684,7 @@ pub(crate) async fn post_webhook_forge(
// caller learning which `{kind}` values exist, from the difference
// between 404 and 401, is a small leak — but it is free to close.
if let Err(refusal) = verify(
state.webhook_secret.get().map(AsRef::as_ref),
hook.webhook_secret.get().map(AsRef::as_ref),
&headers,
&body,
) {
@ -652,16 +708,22 @@ pub(crate) async fn post_webhook_forge(
);
match kind {
DeliveryKind::Knowledge => announce_knowledge_change(&state).await,
DeliveryKind::Knowledge => announce_knowledge_change(hook.status.as_ref()).await,
DeliveryKind::ConfigPr => {
if let Some(cache) = state.config_prs.get() {
if let Some(cache) = deploy.config_prs.get() {
cache.apply_webhook_delivery(&body);
}
if let Some(merged) = crate::config_pr::merged(&body) {
crate::jobq::queue_merged_config_deploy(&state, merged).await;
crate::jobq::queue_merged_config_deploy(
deploy.wanted.as_deref(),
&deploy.hives,
&deploy.jobq,
merged,
)
.await;
}
if let Some(changed) = crate::config_pr::changed_head(&body) {
crate::jobq::queue_config_build(&state, changed);
crate::jobq::queue_config_build(&deploy.jobq, changed);
}
}
DeliveryKind::VcsActivity => {
@ -669,21 +731,28 @@ pub(crate) async fn post_webhook_forge(
crate::vcs_metrics::record_push(&activity);
// The compare runs after the delivery is answered, so a slow
// or failing forge never delays or fails the webhook.
let forge = state.forge.get().map(Arc::clone);
let forge = hook.forge.get().map(Arc::clone);
tokio::spawn(crate::vcs_metrics::count_default_branch_push(
activity, forge,
));
crate::pr_conflicts::on_push(&state, &body);
crate::pr_conflicts::on_push(&hook.forge, hook.status.as_ref(), &body);
} else {
tracing::warn!("webhook: vcs-activity delivery did not parse as a push payload");
}
}
DeliveryKind::ReviewRequest => crate::review_classifier::review::on_delivery(&state, &body),
DeliveryKind::ReviewRequest => crate::review_classifier::review::on_delivery(
&hook.forge,
hook.status.as_ref(),
&hook.runs,
&body,
),
DeliveryKind::Issues | DeliveryKind::PullRequest | DeliveryKind::WorkflowRun => {
if kind == DeliveryKind::PullRequest {
crate::pr_conflicts::on_pull_request(&body);
}
if let Err(not_kept) = crate::forge_events::publish(&state, &headers, body).await {
if let Err(not_kept) =
crate::forge_events::publish(hook.status.as_ref(), &headers, body).await
{
tracing::warn!(kind = <&str>::from(kind), reason = ?not_kept, "webhook: forge event not kept");
return (StatusCode::SERVICE_UNAVAILABLE, "forge event not kept").into_response();
}
@ -717,8 +786,8 @@ pub(crate) async fn post_webhook_forge(
/// call — it reaches a client as a timeout, or as nothing at all. The `flush`
/// below therefore proves the bytes left this process, and nothing more; if
/// hives stop hearing events, the server log is the place that knows why.
async fn announce_knowledge_change(state: &AppState) {
let Some(status) = state.status.as_ref() else {
async fn announce_knowledge_change(status: Option<&Arc<StatusReader>>) {
let Some(status) = status else {
// Verified, accepted, and dropped. Worth a warning rather than
// silence: the forge will report a 200 and nobody would otherwise
// learn that the delivery reached a controller with nowhere to put it.
@ -1305,4 +1374,100 @@ mod tests {
assert_eq!(slot.get().map(|s| &**s), Some(IN_STORE));
}
/// A signed `kind` delivery of `body` through the real router, so both
/// sub-states' `FromRef` run. `sig_secret` signs it.
async fn deliver(
state: crate::routes::AppState,
kind: &str,
sig_secret: &str,
body: &[u8],
) -> StatusCode {
use tower::ServiceExt as _;
let request = axum::http::Request::post(format!("/webhook/forge/{kind}"))
.header("x-hub-signature-256", sign(sig_secret, body))
.body(axum::body::Body::from(body.to_vec()))
.expect("a request");
crate::startup::build_app(state)
.oneshot(request)
.await
.expect("answers")
.status()
}
fn state_with_secret(secret: &str) -> crate::routes::AppState {
let state = crate::routes::AppState::for_test();
state
.webhook_secret
.set(Arc::from(secret))
.expect("the cell was empty");
state
}
fn pending_builds(state: &crate::routes::AppState) -> usize {
let sched = state.jobq.lock().expect("unpoisoned");
sched
.graph()
.nodes()
.filter(|n| matches!(n.payload, crate::jobq::SwarmNodeKind::BuildAgent { .. }))
.count()
}
fn config_pr_delivery(action: &str) -> Vec<u8> {
serde_json::json!({
"action": action,
"pull_request": {
"number": 5,
"state": "open",
"head": { "ref": "fix", "sha": "def456" },
"base": { "ref": "main", "sha": "abc123" },
},
"repository": { "name": "damocles" },
})
.to_string()
.into_bytes()
}
/// `WebhookState` carries the secret: a delivery signed with it passes
/// verification and reaches the kind check (404 for an unknown kind), one
/// signed with another secret is refused first (401).
#[tokio::test]
async fn the_webhook_state_carries_the_secret_the_signature_is_checked_against() {
let body = b"{}";
assert_eq!(
deliver(state_with_secret("s3cret"), "no-such-kind", "s3cret", body).await,
StatusCode::NOT_FOUND
);
assert_eq!(
deliver(state_with_secret("s3cret"), "no-such-kind", "other", body).await,
StatusCode::UNAUTHORIZED
);
}
/// `ConfigDeployState` carries the job graph: a pushed config PR head
/// queues its build in the graph the app state holds, and a delivery that
/// reports no new head queues nothing.
#[tokio::test]
async fn a_config_pr_delivery_queues_its_build_in_the_apps_job_graph() {
let state = state_with_secret("s3cret");
let code = deliver(
state.clone(),
"config-pr",
"s3cret",
&config_pr_delivery("synchronized"),
)
.await;
assert_eq!((code, pending_builds(&state)), (StatusCode::OK, 1));
let state = state_with_secret("s3cret");
let code = deliver(
state.clone(),
"config-pr",
"s3cret",
&config_pr_delivery("edited"),
)
.await;
assert_eq!((code, pending_builds(&state)), (StatusCode::OK, 0));
}
}

View file

@ -49,7 +49,9 @@ use super::{FileSource, PullSource, RunSink, split_repo};
use crate::agent_renewal::unix_now;
use crate::forge::pull_diff::CONTEXT_LINES;
use crate::forge::{self, PullForReview, classifier_account::LOGIN, classifier_account::Review};
use crate::jobq::Late;
use crate::routes::AppState;
use crate::status::StatusReader;
/// The waits before each retry of a post that failed with a [`transient`]
/// error or got no answer: six tries spread over about five minutes, sized to
@ -326,11 +328,16 @@ impl Drop for Slot {
/// Queue the review request in a verified `review-request` delivery that
/// asks for [`LOGIN`], and return at once.
pub(crate) fn on_delivery(state: &AppState, body: &[u8]) {
pub(crate) fn on_delivery(
forge: &Late<Arc<forge::Client>>,
status: Option<&Arc<StatusReader>>,
runs: &Runs,
body: &[u8],
) {
let Some(request) = Requested::parse(body) else {
return;
};
let Some(forge) = state.forge.get().map(Arc::clone) else {
let Some(forge) = forge.get().map(Arc::clone) else {
tracing::warn!(
repo = %format!("{}/{}", request.owner, request.name),
pr = request.pr,
@ -338,8 +345,8 @@ pub(crate) fn on_delivery(state: &AppState, body: &[u8]) {
);
return;
};
let client = state.status.as_ref().map(|s| s.queue_client());
let runs = state.runs.clone();
let client = status.map(|s| s.queue_client());
let runs = runs.clone();
let metrics = Metrics::global();
tokio::spawn(async move { accept(client.as_ref(), &*forge, &runs, &metrics, &request).await });
}