Watch
0
0
Fork
You've already forked hyperhive
0

swarm-controller: the agents status handler takes two narrow sub-states

This commit is contained in:
atlas 2026-11-30 12:05:53 +01:00 • committed by mara
commit 5616b221b8

View file

@ -14,7 +14,7 @@ use swarm_secret_client::observability::Grant;
use utoipa::ToSchema;
use crate::agents::AgentReadersState;
use crate::jobq::{SwarmNodeKind, SwarmResourceKind, declare_agent_job};
use crate::jobq::{Late, SwarmNodeKind, SwarmResourceKind, declare_agent_job};
use crate::observability_grant::{self, grant_of, mirror, require_tolerant};
use crate::routes::hives::HiveEntry;
use crate::routes::{AppState, StatusUnavailable, error_problem, wanted_error_status};
@ -419,6 +419,55 @@ pub(crate) async fn get_hive_wanted(
Ok(Json(declaration.as_ref().map(render).unwrap_or_default()))
}
/// What the agents status handler may reach of [`AppState`] to build the
/// roster rows: the per-agent status reader, the identity bridge, the
/// config-PR cache, the login flags and the swarm queue reader.
///
/// Derived per request from [`AppState`] (`FromRef`), so each field is a clone
/// of the same `Arc` or cheap handle and nothing is held twice. `config_prs`
/// stays the late cell, so a cache that arrives after startup is seen by the
/// next request.
#[derive(Clone)]
pub(crate) struct AgentStatusViewState {
pub(crate) agent_status: Option<Arc<agent_status::AgentStatusReader>>,
pub(crate) auth: Option<Arc<auth::AuthBridge>>,
pub(crate) config_prs: Late<Arc<crate::config_pr::ConfigPrCache>>,
pub(crate) agent_login: Option<Arc<crate::agent_login::Reported>>,
pub(crate) status: Option<Arc<crate::status::StatusReader>>,
}
impl FromRef<AppState> for AgentStatusViewState {
fn from_ref(state: &AppState) -> Self {
Self {
agent_status: state.agent_status.clone(),
auth: state.auth.clone(),
config_prs: Arc::clone(&state.config_prs),
agent_login: state.agent_login.clone(),
status: state.status.clone(),
}
}
}
/// What the agents status handler may reach of [`AppState`] to show where
/// each agent is declared: the wanted-state writer and the hive list.
///
/// A second sub-state beside [`AgentStatusViewState`], so neither passes six
/// fields.
#[derive(Clone)]
pub(crate) struct DeclaredPlacementState {
pub(crate) wanted: Option<Arc<wanted::WantedWriter>>,
pub(crate) hives: Arc<Vec<HiveEntry>>,
}
impl FromRef<AppState> for DeclaredPlacementState {
fn from_ref(state: &AppState) -> Self {
Self {
wanted: state.wanted.clone(),
hives: Arc::clone(&state.hives),
}
}
}
/// What each agent last said about itself, its open config PR if any, and
/// its declared wanted state if any, read at request time — the single
/// call swarm-ui's agent roster page fills its whole table from (mara,
@ -431,8 +480,8 @@ pub(crate) async fn get_hive_wanted(
/// and `wanted` are both merged in here rather than inside
/// `agent_status::AgentStatusReader`: that module has no forge client or
/// wanted-state writer and is not the place to add one just for a single
/// field, whereas this handler already holds `AppState::config_prs` and
/// `AppState::wanted` alongside the roster-shaped status view — the one
/// field, whereas this handler already holds the config-PR cache and
/// the wanted-state writer alongside the roster-shaped status view — the one
/// spot that has all three without adding an avoidable dependency to a
/// reader that stays deliberately narrow. Both fields are absent on rows
/// where the underlying store isn't configured or has nothing on record,
@ -449,14 +498,15 @@ pub(crate) async fn get_hive_wanted(
tag = "agents"
)]
pub(crate) async fn get_agents_status(
State(state): State<AppState>,
State(view): State<AgentStatusViewState>,
State(placement): State<DeclaredPlacementState>,
) -> Result<Json<Vec<agent_status::AgentStatusRow>>, StatusUnavailable> {
let Some(reader) = state.agent_status.as_ref() else {
let Some(reader) = view.agent_status.as_ref() else {
return Err(StatusUnavailable(
"no swarm queue is configured on this host".to_owned(),
));
};
let Some(bridge) = state.auth.as_ref() else {
let Some(bridge) = view.auth.as_ref() else {
return Err(StatusUnavailable(
"no identity bridge is configured on this host".to_owned(),
));
@ -468,7 +518,7 @@ pub(crate) async fn get_agents_status(
})?;
match reader.view(&roster, std::time::SystemTime::now()).await {
Ok(mut rows) => {
if let Some(cache) = state.config_prs.get() {
if let Some(cache) = view.config_prs.get() {
let mut config_prs = cache.snapshot();
for row in &mut rows {
row.config_pr = config_prs.remove(&row.name);
@ -478,7 +528,7 @@ pub(crate) async fn get_agents_status(
// `config_pr` above — one read per distinct hive, not one per
// agent, since a declaration is already a hive's whole agent
// map.
if let Some(writer) = state.wanted.as_ref() {
if let Some(writer) = placement.wanted.as_ref() {
// Owned `String` keys, not `&str` borrowed from `rows` —
// `declarations` outlives the loop below that needs `rows`
// mutably, so it cannot hold a live borrow into it.
@ -487,7 +537,7 @@ pub(crate) async fn get_agents_status(
// A row with no hive has never reported; the hive that
// declares it is the only place its hive is on record.
if rows.iter().any(|r| r.hive.is_none()) {
hives.extend(state.hives.iter().map(|h| h.name.clone()));
hives.extend(placement.hives.iter().map(|h| h.name.clone()));
}
let mut declarations: std::collections::HashMap<
String,
@ -512,7 +562,7 @@ pub(crate) async fn get_agents_status(
}
merge_wanted(&mut rows, &declarations);
}
if let Some(login) = state.agent_login.as_ref() {
if let Some(login) = view.agent_login.as_ref() {
for row in &mut rows {
row.needs_login = login.get(&row.name);
row.paused_by_hive = login.paused_by_hive(&row.name);
@ -520,7 +570,7 @@ pub(crate) async fn get_agents_status(
}
// Absent on a failed read, like `wanted`: one unreadable bucket
// must not blank the roster.
if let Some(reader) = state.status.as_ref() {
if let Some(reader) = view.status.as_ref() {
match agent_archetype::of_agents(&reader.queue_client(), &rows).await {
Ok(mut archetypes) => {
for row in &mut rows {
@ -2776,4 +2826,96 @@ mod tests {
axum::http::StatusCode::SERVICE_UNAVAILABLE
);
}
/// Every field of both status sub-states is the `AppState` field it is
/// derived from: the same `Arc`, not a copy or an empty value.
#[tokio::test]
async fn the_status_sub_states_share_the_app_state_fields() {
use axum::extract::FromRef as _;
use std::sync::Arc;
let nats = crate::test_nats::TestNats::start();
let client = nats.client().await;
let (state, _sched) = state_with_roster();
let state = crate::routes::AppState {
agent_status: Some(Arc::new(agent_status::AgentStatusReader::new(
client.clone(),
std::time::Duration::from_mins(1),
))),
status: Some(Arc::new(crate::status::StatusReader::new(
client.clone(),
std::time::Duration::from_mins(1),
))),
wanted: Some(Arc::new(wanted::WantedWriter::new(client))),
agent_login: Some(Arc::new(crate::agent_login::Reported::default())),
..state
};
let view = AgentStatusViewState::from_ref(&state);
assert!(Arc::ptr_eq(
view.agent_status.as_ref().expect("agent_status"),
state.agent_status.as_ref().expect("held")
));
assert!(Arc::ptr_eq(
view.agent_login.as_ref().expect("agent_login"),
state.agent_login.as_ref().expect("held")
));
assert!(Arc::ptr_eq(
view.status.as_ref().expect("status"),
state.status.as_ref().expect("held")
));
assert!(Arc::ptr_eq(&view.config_prs, &state.config_prs));
assert!(view.auth.is_none(), "the fixture holds no bridge");
let placement = DeclaredPlacementState::from_ref(&state);
assert!(Arc::ptr_eq(
placement.wanted.as_ref().expect("wanted"),
state.wanted.as_ref().expect("held")
));
assert!(Arc::ptr_eq(&placement.hives, &state.hives));
}
/// Through the real router, so both extractors run: with a status reader
/// but no bridge the route answers 503 naming the bridge, and with
/// neither it names the queue.
#[tokio::test]
async fn the_status_route_names_what_is_missing() {
use axum::body::Body;
use axum::http::Request;
use tower::ServiceExt as _;
let get = |state: crate::routes::AppState| async move {
let res = crate::startup::build_app(state)
.oneshot(
Request::get("/api/agents/status")
.body(Body::empty())
.expect("a request"),
)
.await
.expect("answers");
let code = res.status();
let body = axum::body::to_bytes(res.into_body(), usize::MAX)
.await
.expect("a body");
(code, String::from_utf8_lossy(&body).into_owned())
};
let nats = crate::test_nats::TestNats::start();
let client = nats.client().await;
let (state, _sched) = state_with_roster();
let (code, body) = get(state.clone()).await;
assert_eq!(code, axum::http::StatusCode::SERVICE_UNAVAILABLE);
assert!(body.contains("swarm queue"), "{body}");
let state = crate::routes::AppState {
agent_status: Some(std::sync::Arc::new(agent_status::AgentStatusReader::new(
client,
std::time::Duration::from_mins(1),
))),
..state
};
let (code, body) = get(state).await;
assert_eq!(code, axum::http::StatusCode::SERVICE_UNAVAILABLE);
assert!(body.contains("identity bridge"), "{body}");
}
}