swarm-controller: placement sub-state for create_agent, get_hive_wanted, post_agent_custom
This commit is contained in:
parent
78a59f1e79
commit
9b19fbe398
5 changed files with 236 additions and 80 deletions
|
|
@ -22,8 +22,8 @@ use serde::Serialize;
|
|||
use swarm_queue_client::agent_archetype::ArchetypeRef;
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::routes::agents::{claiming_hives, read_declarations};
|
||||
use crate::routes::{AppState, error_problem};
|
||||
use crate::routes::agents::{PlacementState, claiming_hives, read_declarations_of};
|
||||
use crate::routes::error_problem;
|
||||
use swarm_wire::hive_status::{Capabilities, NO_CONFIG_CHECKOUT};
|
||||
|
||||
use crate::status::{Freshness, HiveStatus};
|
||||
|
|
@ -51,13 +51,13 @@ pub struct ConvertResponse {
|
|||
tag = "agents"
|
||||
)]
|
||||
pub(crate) async fn post_agent_custom(
|
||||
State(state): State<AppState>,
|
||||
State(state): State<PlacementState>,
|
||||
Path(agent): Path<String>,
|
||||
) -> Result<Json<ConvertResponse>, ProblemDetails> {
|
||||
let agent = hive_types::Ident::parse(&agent)
|
||||
.map_err(|reason| error_problem(StatusCode::BAD_REQUEST, reason))?
|
||||
.into_string();
|
||||
let client = schedules::queue(&state).map_err(schedules::refused)?;
|
||||
let client = schedules::queue_of(state.status.as_ref()).map_err(schedules::refused)?;
|
||||
let internal =
|
||||
|e: anyhow::Error| error_problem(StatusCode::INTERNAL_SERVER_ERROR, &format!("{e:#}"));
|
||||
|
||||
|
|
@ -67,7 +67,7 @@ pub(crate) async fn post_agent_custom(
|
|||
let (archetype, _, _) = schedules::read_or_default::<Option<ArchetypeRef>>(&store, &agent)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
let declared = read_declarations(&state, state.hives.iter())
|
||||
let declared = read_declarations_of(state.wanted.as_deref(), state.hives.iter())
|
||||
.await
|
||||
.map_err(|(hive, e)| {
|
||||
internal(e.context(format!("read where hive {hive} places agents")))
|
||||
|
|
@ -316,6 +316,35 @@ mod tests {
|
|||
const URL: &str =
|
||||
"git+http://forge/hyperhive/hyperhive.git?rev=1111111111111111111111111111111111111111";
|
||||
|
||||
/// Through the router, the queue status and the wanted state reach the
|
||||
/// handler: an agent a hive declares gets as far as that hive's
|
||||
/// capabilities, which it has not reported (409). Without a queue the same
|
||||
/// request is 503.
|
||||
#[tokio::test]
|
||||
async fn a_conversion_through_the_router_reaches_the_hive_check() {
|
||||
use tower::ServiceExt as _;
|
||||
|
||||
let post = |state: crate::routes::AppState| {
|
||||
crate::startup::build_app(state).oneshot(
|
||||
axum::http::Request::post("/api/agents/atlas/custom")
|
||||
.body(axum::body::Body::empty())
|
||||
.expect("a request"),
|
||||
)
|
||||
};
|
||||
let nats = crate::test_nats::TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = crate::agent_limits::tests::declared(&client).await;
|
||||
assert_eq!(
|
||||
post(state).await.expect("answers").status(),
|
||||
StatusCode::CONFLICT
|
||||
);
|
||||
let bare = crate::routes::AppState::for_test();
|
||||
assert_eq!(
|
||||
post(bare).await.expect("answers").status(),
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
);
|
||||
}
|
||||
|
||||
fn reviewer() -> ArchetypeRef {
|
||||
ArchetypeRef {
|
||||
source: "hyperhive".to_owned(),
|
||||
|
|
|
|||
|
|
@ -871,8 +871,9 @@ pub(crate) mod tests {
|
|||
put_agent_permissions, seed_into,
|
||||
};
|
||||
use crate::observability_grant::fake::Leaves;
|
||||
use crate::routes::agents::PlacementState;
|
||||
use crate::test_nats::TestNats;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::extract::{FromRef as _, Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use hive_types::Permission;
|
||||
use swarm_secret_client::observability::Grant;
|
||||
|
|
@ -1329,7 +1330,7 @@ pub(crate) mod tests {
|
|||
let state = crate::agent_limits::tests::declared(&client).await;
|
||||
let create = |permissions, unrestricted_internet| {
|
||||
crate::routes::agents::create_agent(
|
||||
State(state.clone()),
|
||||
State(PlacementState::from_ref(&state)),
|
||||
axum::Json(swarm_controller_api::agents::CreateAgentRequest {
|
||||
name: "atlas".to_owned(),
|
||||
hive: "pr1ma".to_owned(),
|
||||
|
|
@ -2036,7 +2037,7 @@ pub(crate) mod tests {
|
|||
let state = crate::agent_limits::tests::declared(&client).await;
|
||||
let create = |name: &str, permissions, unrestricted_internet| {
|
||||
crate::routes::agents::create_agent(
|
||||
State(state.clone()),
|
||||
State(PlacementState::from_ref(&state)),
|
||||
axum::Json(swarm_controller_api::agents::CreateAgentRequest {
|
||||
name: name.to_owned(),
|
||||
hive: "pr1ma".to_owned(),
|
||||
|
|
@ -2110,7 +2111,7 @@ pub(crate) mod tests {
|
|||
.await
|
||||
.expect("destroyed");
|
||||
let _ = crate::routes::agents::create_agent(
|
||||
State(state.clone()),
|
||||
State(PlacementState::from_ref(&state)),
|
||||
axum::Json(swarm_controller_api::agents::CreateAgentRequest {
|
||||
name: "atlas".to_owned(),
|
||||
hive: "pr1ma".to_owned(),
|
||||
|
|
|
|||
|
|
@ -121,7 +121,8 @@ pub(crate) async fn clear_on_destroy(state: &AppState, hive: &str, agent: &str)
|
|||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use axum::extract::{Path, State};
|
||||
use crate::routes::agents::PlacementState;
|
||||
use axum::extract::{FromRef as _, Path, State};
|
||||
use axum::http::StatusCode;
|
||||
|
||||
use super::*;
|
||||
|
|
@ -171,7 +172,7 @@ mod tests {
|
|||
let state = crate::agent_limits::tests::declared(&client).await;
|
||||
|
||||
let problem = crate::routes::agents::create_agent(
|
||||
State(state.clone()),
|
||||
State(PlacementState::from_ref(&state)),
|
||||
axum::Json(request("iris", Some("a".repeat(MAX_BYTES + 1)))),
|
||||
)
|
||||
.await
|
||||
|
|
@ -188,7 +189,7 @@ mod tests {
|
|||
assert_eq!(queued, 0, "nothing is queued for a refused create");
|
||||
|
||||
let _ = crate::routes::agents::create_agent(
|
||||
State(state.clone()),
|
||||
State(PlacementState::from_ref(&state)),
|
||||
axum::Json(request("iris", Some("# iris\n".to_owned()))),
|
||||
)
|
||||
.await
|
||||
|
|
@ -200,7 +201,7 @@ mod tests {
|
|||
|
||||
// Control: no `agents_md` writes no key.
|
||||
let _ = crate::routes::agents::create_agent(
|
||||
State(state.clone()),
|
||||
State(PlacementState::from_ref(&state)),
|
||||
axum::Json(request("damocles", None)),
|
||||
)
|
||||
.await
|
||||
|
|
@ -216,7 +217,7 @@ mod tests {
|
|||
let client = nats.client().await;
|
||||
let state = crate::agent_limits::tests::declared(&client).await;
|
||||
let _ = crate::routes::agents::create_agent(
|
||||
State(state.clone()),
|
||||
State(PlacementState::from_ref(&state)),
|
||||
axum::Json(request("iris", Some(String::new()))),
|
||||
)
|
||||
.await
|
||||
|
|
@ -235,7 +236,7 @@ mod tests {
|
|||
let client = nats.client().await;
|
||||
let state = crate::agent_limits::tests::declared(&client).await;
|
||||
let _ = crate::routes::agents::create_agent(
|
||||
State(state.clone()),
|
||||
State(PlacementState::from_ref(&state)),
|
||||
axum::Json(request("atlas", Some("old".to_owned()))),
|
||||
)
|
||||
.await
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
//! Creating agents, declaring their wanted state, and reading the roster,
|
||||
//! their status and their icons.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use anyhow::Result;
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Path, State},
|
||||
extract::{FromRef, Path, State},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use swarm_controller_api::agents::{CreateAgentRequest, CreateAgentResponse};
|
||||
|
|
@ -125,22 +125,55 @@ pub(crate) fn hive_in(
|
|||
Ok(hive)
|
||||
}
|
||||
|
||||
/// What the placement handlers may reach of [`AppState`]: the wanted-state
|
||||
/// writer and hive list that say where an agent runs, the job graph and the
|
||||
/// queue status a creation goes through, the identity bridge's roster, and the
|
||||
/// gate that serialises placements.
|
||||
///
|
||||
/// Derived per request from [`AppState`] (`FromRef`), so each field is a clone
|
||||
/// of the same `Arc` or cheap handle and nothing is held twice. `create_gate`
|
||||
/// in particular must stay the one mutex: a fresh one per request would let
|
||||
/// two creations of the same name pass the placed-elsewhere check together.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct PlacementState {
|
||||
pub(crate) status: Option<Arc<crate::status::StatusReader>>,
|
||||
pub(crate) wanted: Option<Arc<wanted::WantedWriter>>,
|
||||
pub(crate) hives: Arc<Vec<HiveEntry>>,
|
||||
pub(crate) jobq: Arc<Mutex<hive_jobq::scheduler::Scheduler<SwarmNodeKind, SwarmResourceKind>>>,
|
||||
pub(crate) auth: Option<Arc<auth::AuthBridge>>,
|
||||
pub(crate) create_gate: Arc<tokio::sync::Mutex<()>>,
|
||||
}
|
||||
|
||||
impl FromRef<AppState> for PlacementState {
|
||||
fn from_ref(state: &AppState) -> Self {
|
||||
Self {
|
||||
status: state.status.clone(),
|
||||
wanted: state.wanted.clone(),
|
||||
hives: Arc::clone(&state.hives),
|
||||
jobq: Arc::clone(&state.jobq),
|
||||
auth: state.auth.clone(),
|
||||
create_gate: Arc::clone(&state.create_gate),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Both declaration handlers below take the same hive name and reject it the
|
||||
/// same way, and need the writer besides.
|
||||
fn declaration_target(
|
||||
state: &AppState,
|
||||
wanted: Option<&Arc<wanted::WantedWriter>>,
|
||||
hives: &[HiveEntry],
|
||||
hive: &str,
|
||||
) -> Result<(Arc<wanted::WantedWriter>, String), (axum::http::StatusCode, String)> {
|
||||
// Before the name checks, so a deployment with no queue answers 503
|
||||
// whatever the caller spelled.
|
||||
let writer = state.wanted.clone().ok_or_else(|| {
|
||||
let writer = wanted.cloned().ok_or_else(|| {
|
||||
(
|
||||
axum::http::StatusCode::SERVICE_UNAVAILABLE,
|
||||
"this deployment wired up no swarm queue, so there is nowhere to publish a declaration"
|
||||
.to_owned(),
|
||||
)
|
||||
})?;
|
||||
Ok((writer, swarm_hive(state, hive)?))
|
||||
Ok((writer, hive_in(hives, hive)?))
|
||||
}
|
||||
|
||||
/// Declare what this swarm wants of one agent on one hive.
|
||||
|
|
@ -171,8 +204,8 @@ pub(crate) async fn set_agent_state(
|
|||
axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>,
|
||||
Json(req): Json<SetAgentStateRequest>,
|
||||
) -> Result<Json<Vec<AgentDeclaration>>, problem_details::ProblemDetails> {
|
||||
let (writer, hive) =
|
||||
declaration_target(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
|
||||
let (writer, hive) = declaration_target(state.wanted.as_ref(), &state.hives, &hive)
|
||||
.map_err(|(s, d)| error_problem(s, &d))?;
|
||||
let agent = hive_types::Ident::parse(&agent)
|
||||
.map_err(|reason| error_problem(axum::http::StatusCode::BAD_REQUEST, reason))?
|
||||
.into_string();
|
||||
|
|
@ -187,7 +220,7 @@ pub(crate) async fn set_agent_state(
|
|||
let gate = state.create_gate.lock().await;
|
||||
// Before the declaration is read, so a creation finishing in between
|
||||
// is in the snapshot or in the declaration.
|
||||
let queued = queued_placements_now(&state);
|
||||
let queued = queued_placements_now(&state.jobq);
|
||||
let here = writer.view(&hive).await.map_err(|e| {
|
||||
let detail = format!(
|
||||
"cannot tell whether {agent:?} is already declared on hive {hive:?}, so it was \
|
||||
|
|
@ -202,7 +235,7 @@ pub(crate) async fn set_agent_state(
|
|||
hive_types::reserved_names_raw().as_deref(),
|
||||
|| in_roster(state.auth.as_deref(), &agent),
|
||||
queued,
|
||||
|| declarations_elsewhere(&state, &agent, &hive),
|
||||
|| declarations_elsewhere(state.wanted.as_deref(), &state.hives, &agent, &hive),
|
||||
)
|
||||
.await?;
|
||||
Some(gate)
|
||||
|
|
@ -374,11 +407,11 @@ async fn revoke_or_complain(hive: &str, agent: &str) {
|
|||
tag = "agents"
|
||||
)]
|
||||
pub(crate) async fn get_hive_wanted(
|
||||
State(state): State<AppState>,
|
||||
State(state): State<PlacementState>,
|
||||
axum::extract::Path(hive): axum::extract::Path<String>,
|
||||
) -> Result<Json<Vec<AgentDeclaration>>, problem_details::ProblemDetails> {
|
||||
let (writer, hive) =
|
||||
declaration_target(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
|
||||
let (writer, hive) = declaration_target(state.wanted.as_ref(), &state.hives, &hive)
|
||||
.map_err(|(s, d)| error_problem(s, &d))?;
|
||||
let declaration = writer.view(&hive).await.map_err(|e| {
|
||||
tracing::warn!(hive = %hive, error = %format!("{e:#}"), "reading the declaration failed");
|
||||
error_problem(wanted_error_status(&e), &format!("{e:#}"))
|
||||
|
|
@ -579,7 +612,7 @@ fn merge_wanted(
|
|||
tag = "agents"
|
||||
)]
|
||||
pub(crate) async fn create_agent(
|
||||
State(state): State<AppState>,
|
||||
State(state): State<PlacementState>,
|
||||
Json(req): Json<CreateAgentRequest>,
|
||||
) -> Result<Json<CreateAgentResponse>, problem_details::ProblemDetails> {
|
||||
let agent = hive_types::Ident::parse(&req.name)
|
||||
|
|
@ -652,7 +685,7 @@ pub(crate) async fn create_agent(
|
|||
}
|
||||
// Checked after the roster, so a mistyped hive stays a 400 while the queue
|
||||
// is down.
|
||||
let settings_queue = settings.queue(&state).await?;
|
||||
let settings_queue = settings.queue(state.status.as_ref()).await?;
|
||||
let requested = settings.permissions.permissions.clone().unwrap_or_default();
|
||||
if grant_of(&requested) != Grant::default() {
|
||||
require_tolerant(&settings_queue, &hive)
|
||||
|
|
@ -727,15 +760,15 @@ pub(crate) async fn create_agent(
|
|||
|
||||
/// A 409 when `agent` is already placed on a hive other than `hive`.
|
||||
async fn refuse_if_placed_elsewhere(
|
||||
state: &AppState,
|
||||
state: &PlacementState,
|
||||
agent: &str,
|
||||
hive: &str,
|
||||
) -> Result<(), problem_details::ProblemDetails> {
|
||||
let elsewhere = placements_elsewhere(
|
||||
agent,
|
||||
hive,
|
||||
|| queued_placements_now(state),
|
||||
|| declarations_elsewhere(state, agent, hive),
|
||||
|| queued_placements_now(&state.jobq),
|
||||
|| declarations_elsewhere(state.wanted.as_deref(), &state.hives, agent, hive),
|
||||
)
|
||||
.await?;
|
||||
if elsewhere.is_empty() {
|
||||
|
|
@ -795,9 +828,9 @@ impl CreateSettings {
|
|||
/// stored list holds it.
|
||||
async fn queue(
|
||||
&self,
|
||||
state: &AppState,
|
||||
status: Option<&Arc<crate::status::StatusReader>>,
|
||||
) -> Result<async_nats::Client, problem_details::ProblemDetails> {
|
||||
let client = schedules::queue(state).map_err(schedules::refused)?;
|
||||
let client = schedules::queue_of(status).map_err(schedules::refused)?;
|
||||
if let Some(archetype) = &self.archetype {
|
||||
agent_archetype::check(&client, archetype).await?;
|
||||
}
|
||||
|
|
@ -909,11 +942,12 @@ where
|
|||
/// declaration and an absent one look the same, and reading "absent" is how
|
||||
/// a duplicate would get through.
|
||||
async fn declarations_elsewhere(
|
||||
state: &AppState,
|
||||
wanted: Option<&wanted::WantedWriter>,
|
||||
hives: &[HiveEntry],
|
||||
agent: &str,
|
||||
hive: &str,
|
||||
) -> Result<Vec<(String, swarm_wire::wanted::HiveWanted)>, problem_details::ProblemDetails> {
|
||||
read_declarations(state, state.hives.iter().filter(|h| h.name != hive))
|
||||
read_declarations_of(wanted, hives.iter().filter(|h| h.name != hive))
|
||||
.await
|
||||
.map_err(|(other, e)| {
|
||||
let detail = format!(
|
||||
|
|
@ -927,15 +961,6 @@ async fn declarations_elsewhere(
|
|||
/// The published wanted state of each of `hives` that has one. No queue wired
|
||||
/// up reads as nothing declared anywhere. The error names the hive whose read
|
||||
/// failed.
|
||||
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)> {
|
||||
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>,
|
||||
|
|
@ -972,11 +997,11 @@ pub(crate) fn claiming_hives(
|
|||
}
|
||||
|
||||
/// [`queued_placements`] of the swarm's own queue, as it is now.
|
||||
fn queued_placements_now(state: &AppState) -> Vec<(String, String)> {
|
||||
fn queued_placements_now(
|
||||
jobq: &Mutex<hive_jobq::scheduler::Scheduler<SwarmNodeKind, SwarmResourceKind>>,
|
||||
) -> Vec<(String, String)> {
|
||||
queued_placements(
|
||||
state
|
||||
.jobq
|
||||
.lock()
|
||||
jobq.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.graph(),
|
||||
)
|
||||
|
|
@ -1303,7 +1328,7 @@ mod tests {
|
|||
let (state, sched) = state_with_roster();
|
||||
|
||||
let err = super::create_agent(
|
||||
axum::extract::State(state),
|
||||
axum::extract::State(PlacementState::from_ref(&state)),
|
||||
axum::Json(CreateAgentRequest {
|
||||
name: "atlas".to_owned(),
|
||||
hive: "pr1maa".to_owned(),
|
||||
|
|
@ -1347,7 +1372,7 @@ mod tests {
|
|||
// about the id allocator rather than about this endpoint. What the
|
||||
// accept arm is actually for is the queue count below.
|
||||
let _queued = super::create_agent(
|
||||
axum::extract::State(state),
|
||||
axum::extract::State(PlacementState::from_ref(&state)),
|
||||
axum::Json(CreateAgentRequest {
|
||||
name: "atlas".to_owned(),
|
||||
hive: "pr1ma".to_owned(),
|
||||
|
|
@ -1406,9 +1431,12 @@ mod tests {
|
|||
let (_nats, state, sched) = state_with_roster_queued().await;
|
||||
let body = format!(r#"{{"name":"atlas","hive":"pr1ma","{field}":{value}}}"#);
|
||||
let req: CreateAgentRequest = serde_json::from_str(&body).expect("body parses");
|
||||
let err = super::create_agent(axum::extract::State(state), axum::Json(req))
|
||||
.await
|
||||
.expect_err("a bad setting must be refused");
|
||||
let err = super::create_agent(
|
||||
axum::extract::State(PlacementState::from_ref(&state)),
|
||||
axum::Json(req),
|
||||
)
|
||||
.await
|
||||
.expect_err("a bad setting must be refused");
|
||||
assert_eq!(
|
||||
axum::response::IntoResponse::into_response(err).status(),
|
||||
StatusCode::BAD_REQUEST,
|
||||
|
|
@ -1427,9 +1455,12 @@ mod tests {
|
|||
r#"{"name":"atlas","hive":"pr1ma","limits":{"cpu_quota":"400%"}}"#,
|
||||
)
|
||||
.expect("body parses");
|
||||
let err = super::create_agent(axum::extract::State(state), axum::Json(req))
|
||||
.await
|
||||
.expect_err("no queue means the caps cannot be stored");
|
||||
let err = super::create_agent(
|
||||
axum::extract::State(PlacementState::from_ref(&state)),
|
||||
axum::Json(req),
|
||||
)
|
||||
.await
|
||||
.expect_err("no queue means the caps cannot be stored");
|
||||
assert_eq!(
|
||||
axum::response::IntoResponse::into_response(err).status(),
|
||||
axum::http::StatusCode::SERVICE_UNAVAILABLE
|
||||
|
|
@ -1449,9 +1480,12 @@ mod tests {
|
|||
"inference":{"model":"opus","max_subagents":3}}"#,
|
||||
)
|
||||
.expect("body parses");
|
||||
let _queued = super::create_agent(axum::extract::State(state.clone()), axum::Json(req))
|
||||
.await
|
||||
.expect("a valid creation with settings goes through");
|
||||
let _queued = super::create_agent(
|
||||
axum::extract::State(PlacementState::from_ref(&state)),
|
||||
axum::Json(req),
|
||||
)
|
||||
.await
|
||||
.expect("a valid creation with settings goes through");
|
||||
|
||||
assert_eq!(
|
||||
crate::agent_limits::tests::published(&client, "atlas")
|
||||
|
|
@ -1575,9 +1609,12 @@ mod tests {
|
|||
"inference":{{"model":"opus"}}}}"#
|
||||
))
|
||||
.expect("body parses");
|
||||
let err = super::create_agent(axum::extract::State(state.clone()), axum::Json(req))
|
||||
.await
|
||||
.expect_err("the inference write must fail");
|
||||
let err = super::create_agent(
|
||||
axum::extract::State(PlacementState::from_ref(&state)),
|
||||
axum::Json(req),
|
||||
)
|
||||
.await
|
||||
.expect_err("the inference write must fail");
|
||||
assert_eq!(
|
||||
err.status,
|
||||
Some(axum::http::StatusCode::INTERNAL_SERVER_ERROR),
|
||||
|
|
@ -1620,9 +1657,12 @@ mod tests {
|
|||
"inference":{"model":"-opus"}}"#,
|
||||
)
|
||||
.expect("body parses");
|
||||
let err = super::create_agent(axum::extract::State(state.clone()), axum::Json(req))
|
||||
.await
|
||||
.expect_err("a bad model must be refused");
|
||||
let err = super::create_agent(
|
||||
axum::extract::State(PlacementState::from_ref(&state)),
|
||||
axum::Json(req),
|
||||
)
|
||||
.await
|
||||
.expect_err("a bad model must be refused");
|
||||
assert_eq!(
|
||||
axum::response::IntoResponse::into_response(err).status(),
|
||||
axum::http::StatusCode::BAD_REQUEST
|
||||
|
|
@ -1647,7 +1687,10 @@ mod tests {
|
|||
r#"{{"name":"atlas","hive":"pr1ma","permissions":[{perms}]}}"#
|
||||
))
|
||||
.expect("body parses");
|
||||
super::create_agent(axum::extract::State(state.clone()), axum::Json(req))
|
||||
super::create_agent(
|
||||
axum::extract::State(PlacementState::from_ref(&state)),
|
||||
axum::Json(req),
|
||||
)
|
||||
};
|
||||
let err = create(r#""messaging","logs""#).await.expect_err("refused");
|
||||
assert_eq!(
|
||||
|
|
@ -1689,7 +1732,7 @@ mod tests {
|
|||
hive: &str,
|
||||
) -> Result<(), problem_details::ProblemDetails> {
|
||||
super::create_agent(
|
||||
axum::extract::State(state.clone()),
|
||||
axum::extract::State(PlacementState::from_ref(state)),
|
||||
axum::Json(CreateAgentRequest {
|
||||
name: name.to_owned(),
|
||||
hive: hive.to_owned(),
|
||||
|
|
@ -2471,9 +2514,12 @@ mod tests {
|
|||
"archetype":{"source":"hyperhive","name":"reviewer"}}"#,
|
||||
)
|
||||
.expect("body parses");
|
||||
let _queued = super::create_agent(axum::extract::State(state.clone()), axum::Json(req))
|
||||
.await
|
||||
.expect("a listed archetype goes through");
|
||||
let _queued = super::create_agent(
|
||||
axum::extract::State(PlacementState::from_ref(&state)),
|
||||
axum::Json(req),
|
||||
)
|
||||
.await
|
||||
.expect("a listed archetype goes through");
|
||||
|
||||
let stored = swarm_queue_client::agent_archetype::open_or_create(&client)
|
||||
.await
|
||||
|
|
@ -2513,9 +2559,12 @@ mod tests {
|
|||
"archetype":{archetype}}}"#
|
||||
))
|
||||
.expect("body parses");
|
||||
let err = super::create_agent(axum::extract::State(state.clone()), axum::Json(req))
|
||||
.await
|
||||
.expect_err("an unlisted archetype must be refused");
|
||||
let err = super::create_agent(
|
||||
axum::extract::State(PlacementState::from_ref(&state)),
|
||||
axum::Json(req),
|
||||
)
|
||||
.await
|
||||
.expect_err("an unlisted archetype must be refused");
|
||||
assert_eq!(
|
||||
err.status,
|
||||
Some(axum::http::StatusCode::BAD_REQUEST),
|
||||
|
|
@ -2585,7 +2634,7 @@ mod tests {
|
|||
let state = state_with_disconnected_wanted().await;
|
||||
|
||||
let result = super::get_hive_wanted(
|
||||
axum::extract::State(state),
|
||||
axum::extract::State(PlacementState::from_ref(&state)),
|
||||
axum::extract::Path("pr1ma".to_owned()),
|
||||
)
|
||||
.await;
|
||||
|
|
@ -2652,4 +2701,79 @@ mod tests {
|
|||
"{problem:?}"
|
||||
);
|
||||
}
|
||||
|
||||
async fn through_the_router(
|
||||
state: crate::routes::AppState,
|
||||
request: axum::http::Request<axum::body::Body>,
|
||||
) -> axum::http::StatusCode {
|
||||
use tower::ServiceExt as _;
|
||||
|
||||
crate::startup::build_app(state)
|
||||
.oneshot(request)
|
||||
.await
|
||||
.expect("answers")
|
||||
.status()
|
||||
}
|
||||
|
||||
fn request(method: &str, path: &str, body: &str) -> axum::http::Request<axum::body::Body> {
|
||||
axum::http::Request::builder()
|
||||
.method(method)
|
||||
.uri(path)
|
||||
.header("content-type", "application/json")
|
||||
.body(axum::body::Body::from(body.to_owned()))
|
||||
.expect("a request")
|
||||
}
|
||||
|
||||
/// The sub-state shares the gate with the app state instead of owning one.
|
||||
#[tokio::test]
|
||||
async fn the_placement_state_shares_the_create_gate() {
|
||||
let (state, _sched) = state_with_roster();
|
||||
let placement = PlacementState::from_ref(&state);
|
||||
assert!(Arc::ptr_eq(&placement.create_gate, &state.create_gate));
|
||||
}
|
||||
|
||||
/// Through the router: a creation waits while the gate is held elsewhere,
|
||||
/// and finishes once it is released. A gate the extractor built afresh
|
||||
/// would let it through at once.
|
||||
#[tokio::test]
|
||||
async fn a_creation_through_the_router_waits_on_the_shared_gate() {
|
||||
let nats = crate::test_nats::TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = crate::agent_limits::tests::state(&client);
|
||||
let held = Arc::clone(&state.create_gate).lock_owned().await;
|
||||
let create = through_the_router(
|
||||
state,
|
||||
request("POST", "/api/agents", r#"{"name":"iris","hive":"pr1ma"}"#),
|
||||
);
|
||||
let mut create = std::pin::pin!(create);
|
||||
|
||||
tokio::time::timeout(std::time::Duration::from_millis(500), &mut create)
|
||||
.await
|
||||
.expect_err("the gate is held, so the creation must still be waiting");
|
||||
drop(held);
|
||||
let status = tokio::time::timeout(std::time::Duration::from_secs(30), create)
|
||||
.await
|
||||
.expect("the released gate lets the creation finish");
|
||||
assert_eq!(status, axum::http::StatusCode::OK);
|
||||
}
|
||||
|
||||
/// Through the router, the wanted-state writer reaches the read route: a
|
||||
/// state with one answers 200, the same request without one 503.
|
||||
#[tokio::test]
|
||||
async fn the_wanted_read_route_sees_the_writer() {
|
||||
let nats = crate::test_nats::TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = crate::agent_limits::tests::declared(&client).await;
|
||||
let get = || request("GET", "/api/hives/pr1ma/wanted", "");
|
||||
|
||||
assert_eq!(
|
||||
through_the_router(state, get()).await,
|
||||
axum::http::StatusCode::OK
|
||||
);
|
||||
let (bare, _sched) = state_with_roster();
|
||||
assert_eq!(
|
||||
through_the_router(bare, get()).await,
|
||||
axum::http::StatusCode::SERVICE_UNAVAILABLE
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2053,6 +2053,7 @@ pub(crate) fn queue_agent_renewals(
|
|||
mod tests {
|
||||
use super::*;
|
||||
use crate::routes::tests::state_with_roster_queued;
|
||||
use axum::extract::FromRef as _;
|
||||
|
||||
pub(crate) fn changed(agent: &str, rev: &str, pr: u64) -> crate::config_pr::ChangedConfigPr {
|
||||
crate::config_pr::ChangedConfigPr {
|
||||
|
|
@ -2509,7 +2510,7 @@ mod tests {
|
|||
|
||||
let (_nats, state, sched) = state_with_roster_queued().await;
|
||||
let _queued = crate::routes::agents::create_agent(
|
||||
axum::extract::State(state),
|
||||
axum::extract::State(crate::routes::agents::PlacementState::from_ref(&state)),
|
||||
axum::Json(swarm_controller_api::agents::CreateAgentRequest {
|
||||
name: "atlas".to_owned(),
|
||||
hive: "pr1ma".to_owned(),
|
||||
|
|
@ -3506,7 +3507,7 @@ mod tests {
|
|||
|
||||
let (_nats, state, sched) = state_with_roster_queued().await;
|
||||
let _queued = crate::routes::agents::create_agent(
|
||||
axum::extract::State(state),
|
||||
axum::extract::State(crate::routes::agents::PlacementState::from_ref(&state)),
|
||||
axum::Json(swarm_controller_api::agents::CreateAgentRequest {
|
||||
name: "atlas".to_owned(),
|
||||
hive: "pr1ma".to_owned(),
|
||||
|
|
@ -3559,7 +3560,7 @@ mod tests {
|
|||
|
||||
let (_nats, state, sched) = state_with_roster_queued().await;
|
||||
let _queued = crate::routes::agents::create_agent(
|
||||
axum::extract::State(state),
|
||||
axum::extract::State(crate::routes::agents::PlacementState::from_ref(&state)),
|
||||
axum::Json(swarm_controller_api::agents::CreateAgentRequest {
|
||||
name: "atlas".to_owned(),
|
||||
hive: "pr1ma".to_owned(),
|
||||
|
|
@ -3620,7 +3621,7 @@ mod tests {
|
|||
|
||||
let (_nats, state, sched) = state_with_roster_queued().await;
|
||||
let _queued = crate::routes::agents::create_agent(
|
||||
axum::extract::State(state),
|
||||
axum::extract::State(crate::routes::agents::PlacementState::from_ref(&state)),
|
||||
axum::Json(swarm_controller_api::agents::CreateAgentRequest {
|
||||
name: "atlas".to_owned(),
|
||||
hive: "pr1ma".to_owned(),
|
||||
|
|
@ -3897,7 +3898,7 @@ mod tests {
|
|||
|
||||
let (_nats, state, sched) = state_with_roster_queued().await;
|
||||
let _queued = crate::routes::agents::create_agent(
|
||||
axum::extract::State(state),
|
||||
axum::extract::State(crate::routes::agents::PlacementState::from_ref(&state)),
|
||||
axum::Json(swarm_controller_api::agents::CreateAgentRequest {
|
||||
name: "atlas".to_owned(),
|
||||
hive: "pr1ma".to_owned(),
|
||||
|
|
|
|||
Loading…
Reference in a new issue