swarm-controller: set_agent_state takes the placement sub-state and the forge

This commit is contained in:
atlas 2026-11-30 13:27:17 +01:00
commit c79c894ebe
5 changed files with 116 additions and 53 deletions

View file

@ -5,12 +5,15 @@
//! destroy deletes it. The hive reads it to know the agent has no
//! config repo; the swarm builds the agent from the archetype's module.
use std::sync::Arc;
use problem_details::ProblemDetails;
use swarm_queue_client::agent_archetype::{self, ArchetypeRef};
use swarm_queue_client::archetypes::SourceRecord;
use crate::routes::{AppState, error_problem};
use crate::schedules::{queue, read_or_default, write_revision};
use crate::routes::error_problem;
use crate::schedules::{queue_of, read_or_default, write_revision};
use crate::status::StatusReader;
/// How many times a losing writer re-reads and re-applies, as in
/// `wanted::MAX_ATTEMPTS`.
@ -151,9 +154,9 @@ pub(crate) async fn all(
/// Delete a destroyed agent's key, so the next agent of that name is not
/// built from this one's archetype. A failure is logged and does not stop the
/// destroy, as in `agent_permissions::clear_on_destroy`.
pub(crate) async fn clear_on_destroy(state: &AppState, hive: &str, agent: &str) {
pub(crate) async fn clear_on_destroy(status: Option<&Arc<StatusReader>>, hive: &str, agent: &str) {
let cleared = async {
let client = queue(state).map_err(|(_, why)| anyhow::anyhow!(why))?;
let client = queue_of(status).map_err(|(_, why)| anyhow::anyhow!(why))?;
agent_archetype::open_or_create(&client)
.await?
.delete(agent)

View file

@ -3,14 +3,20 @@
//! pushes or PRs, and unarchived when an agent of the same name is created
//! again (`forge::Client::create_repo`).
use crate::routes::AppState;
use std::sync::Arc;
use crate::jobq::Late;
/// Archive `agent`'s config repo. A failure is logged and does not stop the
/// destroy, as in `agent_archetype::clear_on_destroy`: an agent that cannot be
/// torn down is the larger harm, and declaring it destroyed again re-runs
/// this.
pub(crate) async fn archive_on_destroy(state: &AppState, hive: &str, agent: &str) {
let Some(forge) = state.forge.get() else {
pub(crate) async fn archive_on_destroy(
forge: &Late<Arc<crate::forge::Client>>,
hive: &str,
agent: &str,
) {
let Some(forge) = forge.get() else {
tracing::warn!(
hive,
agent,

View file

@ -34,7 +34,8 @@ use crate::observability_grant::{
self, GrantLeaves, adds, grant_of, mirror, require_tolerant_agent, revokes,
};
use crate::routes::{AppState, error_problem, wanted_error_status};
use crate::schedules::{live, queue, read_or_default, refused, write, write_revision};
use crate::schedules::{live, queue, queue_of, read_or_default, refused, write, write_revision};
use crate::status::StatusReader;
use crate::wanted::WantedWriter;
/// How many times a losing writer re-reads and re-applies, as in
@ -431,13 +432,18 @@ async fn delete_with(
/// not stop the destroy; declaring the agent destroyed again re-runs it. The
/// mirrored grant goes first: if that write fails the record stays too, so the
/// two agree.
pub(crate) async fn clear_on_destroy(state: &AppState, hive: &str, agent: &str) {
clear_with(&observability_grant::Store, state, hive, agent).await;
pub(crate) async fn clear_on_destroy(status: Option<&Arc<StatusReader>>, hive: &str, agent: &str) {
clear_with(&observability_grant::Store, status, hive, agent).await;
}
async fn clear_with(leaves: &impl GrantLeaves, state: &AppState, hive: &str, agent: &str) {
async fn clear_with(
leaves: &impl GrantLeaves,
status: Option<&Arc<StatusReader>>,
hive: &str,
agent: &str,
) {
let cleared = async {
let client = queue(state).map_err(|(_, why)| anyhow::anyhow!(why))?;
let client = queue_of(status).map_err(|(_, why)| anyhow::anyhow!(why))?;
let store = agent_permissions::open_or_create(&client).await?;
let (current, _, _) = read_or_default::<AgentPermissions>(&store, agent).await?;
mirror(leaves, agent, &held(&current), &[]).await?;
@ -1623,13 +1629,13 @@ pub(crate) mod tests {
record(&client, r#"["logs"]"#).await;
leaves.fail(true);
super::clear_with(&leaves, &state, "pr1ma", "atlas").await;
super::clear_with(&leaves, state.status.as_ref(), "pr1ma", "atlas").await;
assert_eq!(
published(&client, "atlas").await.as_deref(),
Some(r#"{"permissions":["logs"]}"#)
);
leaves.fail(false);
super::clear_with(&leaves, &state, "pr1ma", "atlas").await;
super::clear_with(&leaves, state.status.as_ref(), "pr1ma", "atlas").await;
assert_eq!(published(&client, "atlas").await, None);
assert_eq!(leaves.get("atlas"), Some(Grant::default()));
}
@ -2102,7 +2108,8 @@ pub(crate) mod tests {
let _ = put(&state, "atlas", granted()).await.expect("set");
let _ = crate::routes::agents::set_agent_state(
State(state.clone()),
State(PlacementState::from_ref(&state)),
State(crate::git_forge::GitForgeState::from_ref(&state)),
Path(("pr1ma".to_owned(), "atlas".to_owned())),
axum::Json(crate::routes::agents::SetAgentStateRequest {
state: swarm_wire::wanted::AgentState::Destroyed,

View file

@ -4,11 +4,14 @@
//! creation; a destroy deletes it. The agent's harness reads its own key at
//! start and writes the file only when none exists.
use std::sync::Arc;
use problem_details::ProblemDetails;
use swarm_queue_client::agents_md_initial::{self, Initial, MAX_BYTES};
use crate::routes::{AppState, error_problem};
use crate::schedules::{queue, read_or_default, write_revision};
use crate::routes::error_problem;
use crate::schedules::{queue_of, read_or_default, write_revision};
use crate::status::StatusReader;
/// How many times a losing writer re-reads and re-applies, as in
/// `wanted::MAX_ATTEMPTS`.
@ -96,9 +99,9 @@ pub(crate) async fn restore(client: &async_nats::Client, agent: &str, replaced:
/// Delete a destroyed agent's key, so the next agent of that name does not
/// start from this one's text. A failure is logged and does not stop the
/// destroy, as in `agent_archetype::clear_on_destroy`.
pub(crate) async fn clear_on_destroy(state: &AppState, hive: &str, agent: &str) {
pub(crate) async fn clear_on_destroy(status: Option<&Arc<StatusReader>>, hive: &str, agent: &str) {
let cleared = async {
let client = queue(state).map_err(|(_, why)| anyhow::anyhow!(why))?;
let client = queue_of(status).map_err(|(_, why)| anyhow::anyhow!(why))?;
agents_md_initial::open_or_create(&client)
.await?
.delete(agent)
@ -244,7 +247,8 @@ mod tests {
assert!(published(&client, "atlas").await.is_some());
let _ = crate::routes::agents::set_agent_state(
State(state.clone()),
State(PlacementState::from_ref(&state)),
State(crate::git_forge::GitForgeState::from_ref(&state)),
Path(("pr1ma".to_owned(), "atlas".to_owned())),
axum::Json(crate::routes::agents::SetAgentStateRequest {
state: swarm_wire::wanted::AgentState::Destroyed,

View file

@ -14,6 +14,7 @@ use swarm_secret_client::observability::Grant;
use utoipa::ToSchema;
use crate::agents::AgentReadersState;
use crate::git_forge::GitForgeState;
use crate::jobq::{Late, SwarmNodeKind, SwarmResourceKind, declare_agent_job};
use crate::observability_grant::{self, grant_of, mirror, require_tolerant};
use crate::routes::hives::HiveEntry;
@ -200,7 +201,8 @@ fn declaration_target(
tag = "agents"
)]
pub(crate) async fn set_agent_state(
State(state): State<AppState>,
State(state): State<PlacementState>,
State(GitForgeState { forge }): State<GitForgeState>,
axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>,
Json(req): Json<SetAgentStateRequest>,
) -> Result<Json<Vec<AgentDeclaration>>, problem_details::ProblemDetails> {
@ -255,13 +257,13 @@ pub(crate) async fn set_agent_state(
// logged — by the time the operator's call returns.
if revokes_queue_credential(req.state) {
revoke_or_complain(&hive, &agent).await;
agent_permissions::clear_on_destroy(&state, &hive, &agent).await;
agent_archetype::clear_on_destroy(&state, &hive, &agent).await;
crate::notify_flows::clear_on_destroy(&state, &hive, &agent).await;
agents_md_initial::clear_on_destroy(&state, &hive, &agent).await;
egress_allow::clear_on_destroy(&state, &hive, &agent).await;
egress_deny::clear_on_destroy(&state, &hive, &agent).await;
crate::agent_config_repo::archive_on_destroy(&state, &hive, &agent).await;
agent_permissions::clear_on_destroy(state.status.as_ref(), &hive, &agent).await;
agent_archetype::clear_on_destroy(state.status.as_ref(), &hive, &agent).await;
crate::notify_flows::clear_on_destroy(state.status.as_ref(), &hive, &agent).await;
agents_md_initial::clear_on_destroy(state.status.as_ref(), &hive, &agent).await;
egress_allow::clear_on_destroy(state.status.as_ref(), &hive, &agent).await;
egress_deny::clear_on_destroy(state.status.as_ref(), &hive, &agent).await;
crate::agent_config_repo::archive_on_destroy(&forge, &hive, &agent).await;
}
Ok(Json(render(&declaration)))
}
@ -2306,7 +2308,8 @@ mod tests {
..state
};
super::set_agent_state(
axum::extract::State(state),
axum::extract::State(PlacementState::from_ref(&state)),
axum::extract::State(GitForgeState::from_ref(&state)),
axum::extract::Path(("pr1ma".to_owned(), agent.to_owned())),
axum::Json(SetAgentStateRequest {
state: wanted_state,
@ -2661,7 +2664,8 @@ mod tests {
let state = state_with_disconnected_wanted().await;
let result = super::set_agent_state(
axum::extract::State(state),
axum::extract::State(PlacementState::from_ref(&state)),
axum::extract::State(GitForgeState::from_ref(&state)),
axum::extract::Path(("pr1ma".to_owned(), "atlas".to_owned())),
axum::Json(SetAgentStateRequest {
state: swarm_wire::wanted::AgentState::Paused,
@ -2706,7 +2710,8 @@ mod tests {
let state = state_with_disconnected_wanted().await;
let result = super::set_agent_state(
axum::extract::State(state),
axum::extract::State(PlacementState::from_ref(&state)),
axum::extract::State(GitForgeState::from_ref(&state)),
axum::extract::Path(("not-a-hive".to_owned(), "atlas".to_owned())),
axum::Json(SetAgentStateRequest {
state: swarm_wire::wanted::AgentState::Paused,
@ -2918,4 +2923,45 @@ mod tests {
assert_eq!(code, axum::http::StatusCode::SERVICE_UNAVAILABLE);
assert!(body.contains("identity bridge"), "{body}");
}
/// The forge extractor of the state route shares the app state's forge
/// cell instead of owning one, so a client that arrives after startup is
/// seen by the destroy's archive step.
#[tokio::test]
async fn the_state_route_shares_the_forge_cell() {
let (state, _sched) = state_with_roster();
assert!(Arc::ptr_eq(
&GitForgeState::from_ref(&state).forge,
&state.forge
));
}
/// Through the router, both extractors of the state route build and the
/// handler runs: a destroy on a swarm with no queue is refused with the
/// reason the placement sub-state's writer lookup gives.
#[tokio::test]
async fn a_destroy_through_the_router_reaches_the_handler() {
use tower::ServiceExt as _;
let (state, _sched) = state_with_roster();
let response = crate::startup::build_app(state)
.oneshot(request(
"PUT",
"/api/hives/pr1ma/agents/atlas/state",
r#"{"state":"destroyed"}"#,
))
.await
.expect("answers");
assert_eq!(
response.status(),
axum::http::StatusCode::SERVICE_UNAVAILABLE
);
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.expect("a body");
assert!(
String::from_utf8_lossy(&body).contains("wired up no swarm queue"),
"{body:?}"
);
}
}