Watch
0
0
Fork
You've already forked hyperhive
0

swarm-controller: agent I/O and reader handlers take narrow sub-states

This commit is contained in:
atlas 2026-11-30 11:18:02 +01:00 • committed by mara
commit 78a59f1e79
13 changed files with 207 additions and 50 deletions

View file

@ -14,7 +14,7 @@ use serde::Serialize;
use swarm_wire::agent_commands::{self, Skills};
use utoipa::ToSchema;
use crate::routes::AppState;
use crate::agents::AgentIoState;
/// The commands the swarm UI offers every agent: the name without the slash,
/// and what it does.
@ -103,7 +103,7 @@ fn build(published: Option<Skills>) -> Vec<CommandEntry> {
tag = "agents"
)]
pub(crate) async fn list_commands(
State(state): State<AppState>,
State(state): State<AgentIoState>,
Path(agent): Path<String>,
) -> Result<Json<Vec<CommandEntry>>, problem_details::ProblemDetails> {
let agent = hive_types::Ident::parse(&agent)

View file

@ -22,7 +22,8 @@ use serde::Serialize;
use swarm_queue_client::{AgentControl, AgentControlReply};
use utoipa::ToSchema;
use crate::routes::{AppState, error_problem};
use crate::agents::AgentIoState;
use crate::routes::error_problem;
/// What became of one command.
#[derive(Debug, PartialEq, Eq)]
@ -91,7 +92,7 @@ pub struct CancelResponse {
tag = "agents"
)]
pub(crate) async fn post_agent_cancel(
State(state): State<AppState>,
State(state): State<AgentIoState>,
Path(agent): Path<String>,
headers: HeaderMap,
) -> Result<Json<CancelResponse>, ProblemDetails> {
@ -135,7 +136,7 @@ pub(crate) async fn post_agent_cancel(
tag = "agents"
)]
pub(crate) async fn post_agent_new_session(
State(state): State<AppState>,
State(state): State<AgentIoState>,
Path(agent): Path<String>,
headers: HeaderMap,
) -> Result<Json<CancelResponse>, ProblemDetails> {

View file

@ -20,6 +20,7 @@
//! loses the text.
use std::collections::HashSet;
use std::sync::Arc;
use std::time::Duration;
use axum::Json;
@ -31,7 +32,8 @@ use serde::{Deserialize, Serialize};
use swarm_queue_client::AgentInput;
use utoipa::ToSchema;
use crate::routes::{AppState, error_problem};
use crate::agents::AgentIoState;
use crate::routes::error_problem;
/// The header the gateway names the session's user in.
const SENDER_HEADER: &str = "remote-user";
@ -147,14 +149,15 @@ impl InputSink for async_nats::Client {
tag = "agents"
)]
pub(crate) async fn post_agent_input(
State(state): State<AppState>,
State(state): State<AgentIoState>,
Path(agent): Path<String>,
headers: HeaderMap,
Json(req): Json<PostAgentInputRequest>,
) -> Result<StatusCode, ProblemDetails> {
let (agent, input) =
message(&headers, &agent, req.body).map_err(|(s, d)| error_problem(s, d))?;
let client = queue(&state).map_err(|d| error_problem(StatusCode::SERVICE_UNAVAILABLE, &d))?;
let client = queue_of(state.status.as_ref())
.map_err(|d| error_problem(StatusCode::SERVICE_UNAVAILABLE, &d))?;
send(&client, &agent, &input).await
}
@ -180,23 +183,26 @@ pub(crate) async fn post_agent_input(
tag = "agents"
)]
pub(crate) async fn post_agents_broadcast(
State(state): State<AppState>,
State(state): State<AgentIoState>,
headers: HeaderMap,
Json(req): Json<BroadcastRequest>,
) -> Result<Json<BroadcastResponse>, ProblemDetails> {
let (agents, input) =
broadcast(&headers, req.agents, req.body).map_err(|(s, d)| error_problem(s, &d))?;
let roster = roster(&state).await?;
let roster = roster_of(state.auth.as_ref()).await?;
known(&agents, &roster).map_err(|(s, d)| error_problem(s, &d))?;
let client = queue(&state).map_err(|d| error_problem(StatusCode::SERVICE_UNAVAILABLE, &d))?;
let client = queue_of(state.status.as_ref())
.map_err(|d| error_problem(StatusCode::SERVICE_UNAVAILABLE, &d))?;
Ok(Json(BroadcastResponse {
results: send_all(&client, agents, &input).await,
}))
}
/// The connected queue client, or why there is none: the caller's 503.
fn queue(state: &AppState) -> Result<async_nats::Client, String> {
let Some(status) = state.status.as_ref() else {
fn queue_of(
status: Option<&Arc<crate::status::StatusReader>>,
) -> Result<async_nats::Client, String> {
let Some(status) = status else {
return Err("no swarm queue is configured on this host".to_owned());
};
let client = status.queue_client();
@ -205,8 +211,10 @@ fn queue(state: &AppState) -> Result<async_nats::Client, String> {
}
/// The swarm roster, or the 503 `GET /api/agents` answers when it has none.
pub(crate) async fn roster(state: &AppState) -> Result<Vec<String>, ProblemDetails> {
let Some(bridge) = state.auth.as_ref() else {
pub(crate) async fn roster_of(
auth: Option<&Arc<crate::auth::AuthBridge>>,
) -> Result<Vec<String>, ProblemDetails> {
let Some(bridge) = auth else {
return Err(error_problem(
StatusCode::SERVICE_UNAVAILABLE,
"no identity bridge is configured on this host",

View file

@ -24,7 +24,6 @@ use std::collections::BTreeMap;
use std::time::Duration;
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use problem_details::ProblemDetails;
use swarm_controller_api::ssh::SshCa;
@ -32,7 +31,7 @@ use swarm_queue_client::agent_permissions;
use swarm_secret_client::{client::DEFAULT_CERT_MOUNT, policy};
use swarm_wire::agent_permissions::AgentPermissions;
use crate::routes::{AppState, error_problem};
use crate::routes::error_problem;
use crate::schedules::read_or_default;
use crate::store::AccessStore;
@ -214,9 +213,7 @@ async fn pass(queue: &async_nats::Client) -> anyhow::Result<()> {
),
tag = "agents"
)]
pub(crate) async fn get_ssh_ca(
State(_state): State<AppState>,
) -> Result<Json<SshCa>, ProblemDetails> {
pub(crate) async fn get_ssh_ca() -> Result<Json<SshCa>, ProblemDetails> {
let store = crate::store::connect().await.map_err(|e| {
error_problem(
StatusCode::BAD_GATEWAY,

View file

@ -40,7 +40,7 @@ use futures_util::{Stream, StreamExt as _, stream};
/// agent's one-minute re-sends, so one missed re-send does not hide it.
const REPLAY_MAX_AGE: Duration = Duration::from_secs(150);
use crate::routes::AppState;
use crate::agents::AgentIoState;
#[utoipa::path(
get,
@ -68,7 +68,7 @@ use crate::routes::AppState;
tag = "agents"
)]
pub(crate) async fn stream_agent_state(
State(state): State<AppState>,
State(state): State<AgentIoState>,
Path(agent): Path<String>,
) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, problem_details::ProblemDetails> {
let Some(status) = state.status.as_ref() else {

View file

@ -14,7 +14,7 @@ use serde::Serialize;
use swarm_wire::agent_todos::{self, Todos};
use utoipa::ToSchema;
use crate::routes::AppState;
use crate::agents::AgentIoState;
/// One open todo.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, ToSchema)]
@ -74,7 +74,7 @@ fn build(published: Option<Todos>) -> Vec<TodoEntry> {
tag = "agents"
)]
pub(crate) async fn list_todos(
State(state): State<AppState>,
State(state): State<AgentIoState>,
Path(agent): Path<String>,
) -> Result<Json<Vec<TodoEntry>>, problem_details::ProblemDetails> {
let agent = hive_types::Ident::parse(&agent)

View file

@ -20,7 +20,8 @@ use swarm_queue_client::AgentControl;
use swarm_queue_client::agents_md::{Apply, ApplyReply, Mirror};
use crate::agent_control::{ControlSink, Outcome};
use crate::routes::{AppState, error_problem, wanted_error_status};
use crate::agents::{AgentIoState, AgentReadersState};
use crate::routes::{error_problem, wanted_error_status};
/// Reads the `agents-md` bucket, the way [`crate::agent_icon::AgentIconReader`]
/// reads the icon bucket, and creates it: the agents writing it cannot.
@ -103,7 +104,7 @@ impl AgentsMdReader {
tag = "agents"
)]
pub(crate) async fn get_agents_md(
State(state): State<AppState>,
State(state): State<AgentReadersState>,
Path(name): Path<String>,
) -> Result<Json<AgentsMdView>, ProblemDetails> {
let Some(reader) = state.agents_md.as_ref() else {
@ -163,7 +164,7 @@ struct CurrentRevision {
tag = "agents"
)]
pub(crate) async fn put_agents_md(
State(state): State<AppState>,
State(state): State<AgentIoState>,
Path(agent): Path<String>,
headers: HeaderMap,
Json(edit): Json<AgentsMdEdit>,

View file

@ -38,7 +38,8 @@ use swarm_controller_api::messages::SwarmMessage;
use swarm_wire::agent_term;
use utoipa::IntoParams;
use crate::routes::{AppState, error_problem};
use crate::agents::AgentIoState;
use crate::routes::error_problem;
/// `since_minutes` when the query names none.
const DEFAULT_SINCE_MINUTES: u64 = 60;
@ -81,7 +82,7 @@ pub struct MessagesQuery {
tag = "agents"
)]
pub(crate) async fn stream_messages(
State(state): State<AppState>,
State(state): State<AgentIoState>,
query: Result<Query<MessagesQuery>, QueryRejection>,
) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, problem_details::ProblemDetails> {
let Query(query) = query.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.body_text()))?;
@ -95,7 +96,7 @@ pub(crate) async fn stream_messages(
"no swarm queue is configured on this host",
));
};
let roster = crate::agent_input::roster(&state).await?;
let roster = crate::agent_input::roster_of(state.auth.as_ref()).await?;
let client = status.queue_client();
swarm_queue_client::ensure_connected(&client).map_err(|e| {
error_problem(

View file

@ -26,3 +26,133 @@ pub(crate) mod schedules;
pub(crate) mod subagent_term;
pub(crate) mod term_stream;
pub(crate) mod wanted;
use std::sync::Arc;
use axum::extract::FromRef;
use crate::routes::AppState;
/// What the agent I/O handlers (commands, control, todos, input, the term,
/// message and state streams, subagents) may reach of [`AppState`]: the queue
/// reader, the identity bridge for the roster, the per-agent status reader and
/// the reported turn-state headers.
///
/// Derived per request from [`AppState`] (`FromRef`), so each field is a clone
/// of the same `Arc`. The SSE streams take their subscriber inside the handler
/// and hold nothing of this past it.
#[derive(Clone)]
pub(crate) struct AgentIoState {
pub(crate) status: Option<Arc<crate::status::StatusReader>>,
pub(crate) auth: Option<Arc<crate::auth::AuthBridge>>,
pub(crate) agent_status: Option<Arc<crate::agent_status::AgentStatusReader>>,
pub(crate) reported_inference: Option<Arc<crate::inference::Reported>>,
}
impl FromRef<AppState> for AgentIoState {
fn from_ref(state: &AppState) -> Self {
Self {
status: state.status.clone(),
auth: state.auth.clone(),
agent_status: state.agent_status.clone(),
reported_inference: state.reported_inference.clone(),
}
}
}
/// What the agent read routes (roster, icon, `AGENTS.md`) may reach of
/// [`AppState`]: the identity bridge and the icon and `AGENTS.md` readers.
///
/// Derived per request from [`AppState`] (`FromRef`), so each field is a clone
/// of the same `Arc`.
#[derive(Clone)]
pub(crate) struct AgentReadersState {
pub(crate) auth: Option<Arc<crate::auth::AuthBridge>>,
pub(crate) agent_icons: Option<Arc<crate::agent_icon::AgentIconReader>>,
pub(crate) agents_md: Option<Arc<crate::agents_md::AgentsMdReader>>,
}
impl FromRef<AppState> for AgentReadersState {
fn from_ref(state: &AppState) -> Self {
Self {
auth: state.auth.clone(),
agent_icons: state.agent_icons.clone(),
agents_md: state.agents_md.clone(),
}
}
}
#[cfg(test)]
mod tests {
use axum::http::StatusCode;
use crate::routes::AppState;
use crate::routes::tests::state_with_roster;
async fn disconnected_client() -> async_nats::Client {
async_nats::ConnectOptions::new()
.retry_on_initial_connect()
.connect("127.0.0.1:1")
.await
.expect("retry_on_initial_connect returns without waiting for a real connection")
}
async fn get(state: AppState, path: &str) -> (StatusCode, String) {
use axum::body::Body;
use axum::http::Request;
use tower::ServiceExt as _;
let res = crate::startup::build_app(state)
.oneshot(Request::get(path).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())
}
/// Through the real router, so `AgentIoState::from_ref` runs: a queue that
/// is configured but not connected answers 503 naming the connection, and
/// without one the 503 says none is configured.
#[tokio::test]
async fn agent_io_state_carries_the_queue_reader() {
let (state, _sched) = state_with_roster();
let (code, body) = get(state.clone(), "/api/agents/iris/subagents").await;
assert_eq!(code, StatusCode::SERVICE_UNAVAILABLE);
assert!(body.contains("no swarm queue is configured"), "{body}");
let state = AppState {
status: Some(std::sync::Arc::new(crate::status::StatusReader::new(
disconnected_client().await,
std::time::Duration::from_mins(1),
))),
..state
};
let (code, body) = get(state, "/api/agents/iris/subagents").await;
assert_eq!(code, StatusCode::SERVICE_UNAVAILABLE);
assert!(!body.contains("no swarm queue is configured"), "{body}");
}
/// Through the real router, so `AgentReadersState::from_ref` runs: an icon
/// reader on a client that never connected is asked and fails 503 with the
/// connection's reason; without one the 503 says no queue is wired up.
#[tokio::test]
async fn agent_readers_state_carries_the_icon_reader() {
let (state, _sched) = state_with_roster();
let (code, body) = get(state.clone(), "/api/agents/iris/icon").await;
assert_eq!(code, StatusCode::SERVICE_UNAVAILABLE);
assert!(body.contains("no swarm queue is wired up"), "{body}");
let state = AppState {
agent_icons: Some(std::sync::Arc::new(
crate::agent_icon::AgentIconReader::new(disconnected_client().await),
)),
..state
};
let (code, body) = get(state, "/api/agents/iris/icon").await;
assert_eq!(code, StatusCode::SERVICE_UNAVAILABLE);
assert!(!body.contains("no swarm queue is wired up"), "{body}");
}
}

View file

@ -13,6 +13,7 @@ use swarm_controller_api::agents::{CreateAgentRequest, CreateAgentResponse};
use swarm_secret_client::observability::Grant;
use utoipa::ToSchema;
use crate::agents::AgentReadersState;
use crate::jobq::{SwarmNodeKind, SwarmResourceKind, declare_agent_job};
use crate::observability_grant::{self, grant_of, mirror, require_tolerant};
use crate::routes::hives::HiveEntry;
@ -46,7 +47,7 @@ use crate::{
tag = "agents"
)]
pub(crate) async fn get_agents(
State(state): State<AppState>,
State(state): State<AgentReadersState>,
) -> Result<Json<Vec<String>>, StatusUnavailable> {
let Some(bridge) = state.auth.as_ref() else {
return Err(StatusUnavailable(
@ -1169,7 +1170,7 @@ const ICON_MAX_AGE: u32 = 300;
tag = "agents"
)]
pub(crate) async fn get_agent_icon(
State(state): State<AppState>,
State(state): State<AgentReadersState>,
Path(name): Path<String>,
) -> Result<axum::response::Response, problem_details::ProblemDetails> {
use axum::http::{StatusCode, header};
@ -1232,7 +1233,12 @@ mod tests {
let (state, _sched) = state_with_roster();
assert!(state.auth.is_none(), "the fixture must have no bridge");
let err = super::get_agents(axum::extract::State(state))
let err =
super::get_agents(axum::extract::State(
<crate::agents::AgentReadersState as axum::extract::FromRef<
crate::routes::AppState,
>>::from_ref(&state),
))
.await
.expect_err("a bridge-less controller cannot produce a roster");
let resp = err.into_response();
@ -1273,7 +1279,11 @@ mod tests {
);
let err = super::get_agent_icon(
axum::extract::State(state),
axum::extract::State(
<crate::agents::AgentReadersState as axum::extract::FromRef<
crate::routes::AppState,
>>::from_ref(&state),
),
axum::extract::Path("iris".to_owned()),
)
.await
@ -2627,7 +2637,11 @@ mod tests {
};
let problem = super::get_agent_icon(
axum::extract::State(state),
axum::extract::State(
<crate::agents::AgentReadersState as axum::extract::FromRef<
crate::routes::AppState,
>>::from_ref(&state),
),
axum::extract::Path("iris".to_owned()),
)
.await

View file

@ -39,7 +39,7 @@ use serde::Serialize;
use swarm_wire::subagent_term;
use utoipa::ToSchema;
use crate::routes::AppState;
use crate::agents::AgentIoState;
use crate::wanted::WantedWriter;
/// How often [`spawn`] checks every live agent's stream. Also how long a newly
@ -213,11 +213,11 @@ impl SubagentState {
tag = "agents"
)]
pub(crate) async fn list_subagents(
State(state): State<AppState>,
State(state): State<AgentIoState>,
Path(agent): Path<String>,
) -> Result<Json<Vec<SubagentEntry>>, problem_details::ProblemDetails> {
let agent = ident(&agent).map_err(bad_request)?;
let client = connected_client(&state).map_err(|e| unavailable(&e))?;
let client = connected_client_of(state.status.as_ref()).map_err(|e| unavailable(&e))?;
let js = async_nats::jetstream::new(client.clone());
let stream_name = subagent_term::stream_name(&agent);
let stream = match js.get_stream(&stream_name).await {
@ -438,13 +438,13 @@ async fn newest_row(
tag = "agents"
)]
pub(crate) async fn stream_subagent_term(
State(state): State<AppState>,
State(state): State<AgentIoState>,
Path((agent, subagent)): Path<(String, String)>,
headers: HeaderMap,
) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, problem_details::ProblemDetails> {
let agent = ident(&agent).map_err(bad_request)?;
let subagent = ident(&subagent).map_err(bad_request)?;
let client = connected_client(&state).map_err(|e| unavailable(&e))?;
let client = connected_client_of(state.status.as_ref()).map_err(|e| unavailable(&e))?;
let stream = crate::term_stream::replay_or_live(
&client,
&subagent_term::stream_name(&agent),
@ -458,11 +458,10 @@ pub(crate) async fn stream_subagent_term(
/// The queue client, or why there is none: the 503 every queue-backed route
/// answers.
fn connected_client(state: &AppState) -> Result<async_nats::Client, String> {
let status = state
.status
.as_ref()
.ok_or_else(|| "no swarm queue is configured on this host".to_owned())?;
fn connected_client_of(
status: Option<&Arc<crate::status::StatusReader>>,
) -> Result<async_nats::Client, String> {
let status = status.ok_or_else(|| "no swarm queue is configured on this host".to_owned())?;
let client = status.queue_client();
swarm_queue_client::ensure_connected(&client).map_err(|e| swarm_queue_client::chain(&e))?;
Ok(client)

View file

@ -37,7 +37,7 @@ use futures_util::stream::BoxStream;
use futures_util::{Stream, StreamExt as _};
use swarm_wire::agent_term;
use crate::routes::AppState;
use crate::agents::AgentIoState;
#[utoipa::path(
get,
@ -63,7 +63,7 @@ use crate::routes::AppState;
tag = "agents"
)]
pub(crate) async fn stream_agent_term(
State(state): State<AppState>,
State(state): State<AgentIoState>,
Path(agent): Path<String>,
headers: HeaderMap,
) -> Result<Sse<impl Stream<Item = Result<Event, Infallible>>>, problem_details::ProblemDetails> {

View file

@ -1031,7 +1031,9 @@ mod tests {
async fn listing_subagents_needs_a_queue_and_an_identifier() {
let (state, _sched) = state_with_roster();
let no_queue = crate::subagent_term::list_subagents(
axum::extract::State(state.clone()),
axum::extract::State(<crate::agents::AgentIoState as axum::extract::FromRef<
crate::routes::AppState,
>>::from_ref(&state)),
axum::extract::Path("iris".to_owned()),
)
.await
@ -1042,7 +1044,9 @@ mod tests {
"{no_queue:?}"
);
let bad_name = crate::subagent_term::list_subagents(
axum::extract::State(state),
axum::extract::State(<crate::agents::AgentIoState as axum::extract::FromRef<
crate::routes::AppState,
>>::from_ref(&state)),
axum::extract::Path("iris.sub".to_owned()),
)
.await
@ -1061,7 +1065,9 @@ mod tests {
let (state, _sched) = state_with_roster();
for subagent in ["*", ">", "a.b"] {
let Err(problem) = crate::subagent_term::stream_subagent_term(
axum::extract::State(state.clone()),
axum::extract::State(<crate::agents::AgentIoState as axum::extract::FromRef<
crate::routes::AppState,
>>::from_ref(&state)),
axum::extract::Path(("iris".to_owned(), subagent.to_owned())),
axum::http::HeaderMap::new(),
)