diff --git a/swarm-controller/src/agents/agent_archetype.rs b/swarm-controller/src/agents/agent_archetype.rs index 22b226ca1..bde7f77dd 100644 --- a/swarm-controller/src/agents/agent_archetype.rs +++ b/swarm-controller/src/agents/agent_archetype.rs @@ -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>, 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) diff --git a/swarm-controller/src/agents/agent_config_repo.rs b/swarm-controller/src/agents/agent_config_repo.rs index 070a48ae7..6dc331c5d 100644 --- a/swarm-controller/src/agents/agent_config_repo.rs +++ b/swarm-controller/src/agents/agent_config_repo.rs @@ -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>, + hive: &str, + agent: &str, +) { + let Some(forge) = forge.get() else { tracing::warn!( hive, agent, diff --git a/swarm-controller/src/agents/agent_permissions.rs b/swarm-controller/src/agents/agent_permissions.rs index 06f443811..fc1195cfd 100644 --- a/swarm-controller/src/agents/agent_permissions.rs +++ b/swarm-controller/src/agents/agent_permissions.rs @@ -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>, 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>, + 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::(&store, agent).await?; mirror(leaves, agent, &held(¤t), &[]).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, diff --git a/swarm-controller/src/agents/agents_md_initial.rs b/swarm-controller/src/agents/agents_md_initial.rs index 573e68e56..78711d93c 100644 --- a/swarm-controller/src/agents/agents_md_initial.rs +++ b/swarm-controller/src/agents/agents_md_initial.rs @@ -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>, 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, diff --git a/swarm-controller/src/agents/routes.rs b/swarm-controller/src/agents/routes.rs index 46e938a1b..f06961b27 100644 --- a/swarm-controller/src/agents/routes.rs +++ b/swarm-controller/src/agents/routes.rs @@ -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, + State(state): State, + State(GitForgeState { forge }): State, axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>, Json(req): Json, ) -> Result>, 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:?}" + ); + } } diff --git a/swarm-controller/src/review/notify_flows.rs b/swarm-controller/src/review/notify_flows.rs index e6ef8ac06..9350fd874 100644 --- a/swarm-controller/src/review/notify_flows.rs +++ b/swarm-controller/src/review/notify_flows.rs @@ -294,17 +294,7 @@ async fn clear_agent_keys(client: &async_nats::Client, agent: &str) -> anyhow::R /// Clear a destroyed agent's per-agent switch-offs, so a new agent of that /// name starts with every archetype flow on. A failure is logged with the keys /// left behind and does not stop the destroy. -pub(crate) async fn clear_on_destroy(state: &AppState, hive: &str, agent: &str) { - clear_on_destroy_of(state.status.as_ref(), hive, agent).await; -} - -/// [`clear_on_destroy`] over the status reader alone, for a caller that holds -/// only that. -pub(crate) async fn clear_on_destroy_of( - status: Option<&Arc>, - hive: &str, - agent: &str, -) { +pub(crate) async fn clear_on_destroy(status: Option<&Arc>, hive: &str, agent: &str) { let cleared = async { let client = queue_of(status).map_err(|(_, why)| anyhow::anyhow!(why))?; clear_agent_keys(&client, agent).await diff --git a/swarm-controller/src/secrets/backend_egress.rs b/swarm-controller/src/secrets/backend_egress.rs index 9ee092338..5e34e07d7 100644 --- a/swarm-controller/src/secrets/backend_egress.rs +++ b/swarm-controller/src/secrets/backend_egress.rs @@ -879,7 +879,7 @@ mod tests { .await .expect("seed"); - crate::egress_allow::clear_on_destroy(&state, "pr1ma", "atlas").await; + crate::egress_allow::clear_on_destroy(state.status.as_ref(), "pr1ma", "atlas").await; assert_eq!(list_of(&client).await, [manual("crates.io", "iris")]); } diff --git a/swarm-controller/src/secrets/egress_allow.rs b/swarm-controller/src/secrets/egress_allow.rs index 205d1830b..bf7e1a6e0 100644 --- a/swarm-controller/src/secrets/egress_allow.rs +++ b/swarm-controller/src/secrets/egress_allow.rs @@ -14,6 +14,8 @@ //! refused when the proxy already allows it to everyone. The names the proxy //! always allows are the ones in [`ENV_BASE_DOMAINS`]. +use std::sync::Arc; + use axum::Json; use axum::extract::State; use axum::http::StatusCode; @@ -22,9 +24,10 @@ use swarm_controller_api::egress::{AllowedDomain, AllowedDomains}; use swarm_queue_client::egress_allow; use swarm_wire::egress_allow::{AllowList, Entry, KEY, MAX_ENTRIES, covered_by, normalize_domain}; -use crate::routes::{AppState, error_problem, wanted_error_status}; -use crate::schedules::{live_of, queue, queue_of, read_or_default, refused, write_revision}; +use crate::routes::{error_problem, wanted_error_status}; +use crate::schedules::{live_of, queue_of, read_or_default, refused, write_revision}; use crate::secrets::SecretsState; +use crate::status::StatusReader; /// How many times a losing writer re-reads and re-applies, as in /// `wanted::MAX_ATTEMPTS`. @@ -345,9 +348,9 @@ pub(crate) async fn modify( /// is free again once its agent is destroyed, and the next agent of that name /// would inherit what it left. 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>, 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))?; modify(&client, |mut list| { list.entries.retain(|e| e.agent.as_deref() != Some(agent)); list @@ -371,6 +374,7 @@ pub(crate) async fn clear_on_destroy(state: &AppState, hive: &str, agent: &str) mod tests { use super::*; use crate::agent_limits::tests::{declared, state}; + use crate::routes::AppState; use crate::test_nats::TestNats; use axum::extract::FromRef as _; diff --git a/swarm-controller/src/secrets/egress_deny.rs b/swarm-controller/src/secrets/egress_deny.rs index c7bcc969a..bec057dcd 100644 --- a/swarm-controller/src/secrets/egress_deny.rs +++ b/swarm-controller/src/secrets/egress_deny.rs @@ -23,6 +23,8 @@ //! (`swarm_wire::hive_status::EGRESS_DENY_APPLIED`); [`behind`] names the hives //! whose report does not match, which the reads show as `behind`. +use std::sync::Arc; + use axum::Json; use axum::extract::State; use axum::http::StatusCode; @@ -32,10 +34,10 @@ use swarm_queue_client::egress_allow; use swarm_wire::egress_allow::{DENY_KEY, DenyEntry, DenyList, MAX_ENTRIES, normalize_domain}; use swarm_wire::hive_status::egress_deny_applied; -use crate::routes::{AppState, error_problem, wanted_error_status}; -use crate::schedules::{live_of, queue, queue_of, read_or_default, refused, write_revision}; +use crate::routes::{error_problem, wanted_error_status}; +use crate::schedules::{live_of, queue_of, read_or_default, refused, write_revision}; use crate::secrets::SecretsState; -use crate::status::{Freshness, HiveStatus}; +use crate::status::{Freshness, HiveStatus, StatusReader}; /// How many times a losing writer re-reads and re-applies, as in /// `egress_allow::MAX_ATTEMPTS`. @@ -306,9 +308,9 @@ pub(crate) async fn remove_denied_domain( /// is destroyed, and the next agent of that name would inherit what it left. A /// list that was never written stays unwritten. A failure is logged and does /// not stop the destroy, as in `egress_allow::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>, 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 Some(store) = egress_allow::open(&client).await? else { return Ok(()); }; @@ -345,6 +347,7 @@ pub(crate) async fn clear_on_destroy(state: &AppState, hive: &str, agent: &str) mod tests { use super::*; use crate::agent_limits::tests::{declared, state}; + use crate::routes::AppState; use crate::test_nats::TestNats; use axum::extract::FromRef as _; use swarm_wire::hive_status::EGRESS_DENY_APPLIED; @@ -695,7 +698,7 @@ mod tests { add(&state, "evil.com", None).await.expect("swarm-wide"); add(&state, "bad.io", Some("atlas")).await.expect("atlas's"); - clear_on_destroy(&state, "pr1ma", "atlas").await; + clear_on_destroy(state.status.as_ref(), "pr1ma", "atlas").await; assert_eq!(listed(&state).await, [("evil.com".to_owned(), None)]); }