Watch
0
0
Fork
You've already forked hyperhive
0

swarm-controller: the notify handlers take a status-only sub-state

This commit is contained in:
atlas 2026-11-29 14:03:26 +01:00 • committed by mara
commit 0fd9847363
2 changed files with 146 additions and 80 deletions

View file

@ -15,19 +15,38 @@
use anyhow::Context as _;
use async_nats::jetstream::kv::Store;
use axum::Json;
use axum::extract::State;
use axum::extract::rejection::JsonRejection;
use axum::extract::{FromRef, State};
use axum::http::StatusCode;
use problem_details::ProblemDetails;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use swarm_queue_client::archetypes::{self, SourceRecord, flows_of};
use swarm_wire::notify_flows::{self, DecodeError, Document, Flow};
use utoipa::ToSchema;
use crate::routes::{AppState, error_problem, wanted_error_status};
use crate::schedules::{queue, read_or_default, read_with, refused, write_revision};
use crate::schedules::{queue_of, read_or_default, read_with, refused, write_revision};
use crate::status::StatusReader;
/// What the notify routes may reach of [`AppState`]: the queue connection.
///
/// Derived per request from [`AppState`] (`FromRef`), so the field is a clone
/// of the same `Arc` and nothing is held twice.
#[derive(Clone)]
pub(crate) struct NotifyState {
pub(crate) status: Option<Arc<StatusReader>>,
}
impl FromRef<AppState> for NotifyState {
fn from_ref(state: &AppState) -> Self {
Self {
status: state.status.clone(),
}
}
}
/// How many times a losing writer re-reads and re-applies, as in
/// `wanted::MAX_ATTEMPTS`.
@ -168,9 +187,9 @@ pub(crate) fn queue_problem(e: &anyhow::Error) -> ProblemDetails {
tag = "notify"
)]
pub(crate) async fn get_flows(
State(state): State<AppState>,
State(state): State<NotifyState>,
) -> Result<Json<FlowsView>, ProblemDetails> {
let client = queue(&state).map_err(refused)?;
let client = queue_of(state.status.as_ref()).map_err(refused)?;
let store = open(&client).await.map_err(|e| queue_problem(&e))?;
let (stored, revision) = stored(&store).await.map_err(|e| queue_problem(&e))?;
match stored {
@ -276,8 +295,18 @@ async fn clear_agent_keys(client: &async_nats::Client, agent: &str) -> anyhow::R
/// 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<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))?;
clear_agent_keys(&client, agent).await
}
.await;
@ -351,13 +380,13 @@ pub(crate) fn checked_document(
tag = "notify"
)]
pub(crate) async fn put_flows(
State(state): State<AppState>,
State(state): State<NotifyState>,
body: Result<Json<PutFlows>, JsonRejection>,
) -> Result<Json<FlowsView>, ProblemDetails> {
let Json(put) = body.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.body_text()))?;
let doc = checked_document(put.disabled_builtins, put.flows)
.map_err(|why| error_problem(StatusCode::BAD_REQUEST, &why))?;
let client = queue(&state).map_err(refused)?;
let client = queue_of(state.status.as_ref()).map_err(refused)?;
let store = open(&client).await.map_err(|e| queue_problem(&e))?;
for _ in 0..MAX_ATTEMPTS {
let (current, revision) = stored(&store).await.map_err(|e| queue_problem(&e))?;
@ -398,12 +427,17 @@ pub(crate) async fn put_flows(
#[cfg(test)]
mod tests {
use axum::extract::FromRef;
use swarm_wire::notify_flows::{Edge, Node, NodeKind, Recipients, TodoSink};
use swarm_wire::router_todo::Op;
use super::*;
use crate::test_nats::TestNats;
fn sub(state: &AppState) -> State<NotifyState> {
State(NotifyState::from_ref(state))
}
fn custom(id: &str) -> Flow {
Flow {
id: id.to_owned(),
@ -442,6 +476,30 @@ mod tests {
})
}
#[tokio::test]
async fn the_flows_route_reaches_the_queue_through_build_app() {
use tower::ServiceExt as _;
let nats = TestNats::start();
let client = nats.client().await;
let app = crate::startup::build_app(crate::agent_limits::tests::state(&client));
let res = app
.oneshot(
axum::http::Request::get("/api/notify/flows")
.header("remote-user", "alice")
.body(axum::body::Body::empty())
.expect("a request"),
)
.await
.expect("infallible");
assert_eq!(res.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
.await
.expect("a body");
let view: serde_json::Value = serde_json::from_slice(&bytes).expect("json");
assert_eq!(view["revision"], 0, "{view}");
}
#[tokio::test]
async fn the_flows_are_read_replaced_and_checked_on_save() {
let nats = TestNats::start();
@ -449,7 +507,7 @@ mod tests {
let state = crate::agent_limits::tests::state(&client);
// Nothing stored: the built-ins alone, none off, no revision.
let Json(view) = get_flows(State(state.clone())).await.expect("get");
let Json(view) = get_flows(sub(&state)).await.expect("get");
assert_eq!(view.revision, 0);
assert!(view.disabled_builtins.is_empty() && view.flows.is_empty());
assert_eq!(view.builtins.len(), notify_flows::builtins().len());
@ -460,14 +518,14 @@ mod tests {
assert_eq!(view.schema, notify_flows::schema());
let Json(saved) = put_flows(
State(state.clone()),
sub(&state),
Ok(body(0, &["unassigned"], vec![custom("triage")])),
)
.await
.expect("put");
let revision = saved.revision;
assert_ne!(revision, 0);
let Json(read) = get_flows(State(state.clone())).await.expect("get");
let Json(read) = get_flows(sub(&state)).await.expect("get");
assert_eq!(read, saved);
assert_eq!(read.disabled_builtins, ["unassigned"]);
assert_eq!(read.flows[0].id, "triage");
@ -489,23 +547,23 @@ mod tests {
// A refused save changes nothing: an orphan node, and a built-in that does not exist.
let mut orphan = custom("orphan");
orphan.edges.clear();
let refused = put_flows(State(state.clone()), Ok(body(revision, &[], vec![orphan])))
let refused = put_flows(sub(&state), Ok(body(revision, &[], vec![orphan])))
.await
.expect_err("an orphan node");
assert_eq!(refused.status, Some(StatusCode::BAD_REQUEST), "{refused:?}");
let unknown = put_flows(State(state.clone()), Ok(body(revision, &["nope"], vec![])))
let unknown = put_flows(sub(&state), Ok(body(revision, &["nope"], vec![])))
.await
.expect_err("no such built-in");
assert_eq!(unknown.status, Some(StatusCode::BAD_REQUEST), "{unknown:?}");
let Json(after) = get_flows(State(state.clone())).await.expect("get");
let Json(after) = get_flows(sub(&state)).await.expect("get");
assert_eq!(after, saved);
// A stale revision is refused; the current one lands.
let outdated = put_flows(State(state.clone()), Ok(body(revision + 100, &[], vec![])))
let outdated = put_flows(sub(&state), Ok(body(revision + 100, &[], vec![])))
.await
.expect_err("stale");
assert_eq!(outdated.status, Some(StatusCode::CONFLICT), "{outdated:?}");
let Json(next) = put_flows(State(state.clone()), Ok(body(revision, &[], vec![])))
let Json(next) = put_flows(sub(&state), Ok(body(revision, &[], vec![])))
.await
.expect("current revision");
assert!(next.revision > revision);
@ -528,11 +586,9 @@ mod tests {
)
.await
.expect("seed");
let got = get_flows(State(state.clone()))
.await
.expect_err("version 3");
let got = get_flows(sub(&state)).await.expect_err("version 3");
assert_eq!(got.status, Some(StatusCode::CONFLICT), "{got:?}");
let refused = put_flows(State(state.clone()), Ok(body(0, &[], vec![])))
let refused = put_flows(sub(&state), Ok(body(0, &[], vec![])))
.await
.expect_err("version 3 is kept");
assert_eq!(refused.status, Some(StatusCode::CONFLICT), "{refused:?}");
@ -548,10 +604,10 @@ mod tests {
.put(notify_flows::KEY, b"garbage".to_vec().into())
.await
.expect("seed");
let _ = put_flows(State(state.clone()), Ok(body(garbage, &["closed"], vec![])))
let _ = put_flows(sub(&state), Ok(body(garbage, &["closed"], vec![])))
.await
.expect("replaces garbage");
let Json(view) = get_flows(State(state)).await.expect("readable again");
let Json(view) = get_flows(sub(&state)).await.expect("readable again");
assert_eq!(view.disabled_builtins, ["closed"]);
}
@ -563,30 +619,24 @@ mod tests {
let client = nats.client().await;
let state = crate::agent_limits::tests::state(&client);
let Json(page) = get_flows(State(state.clone())).await.expect("get");
let Json(page) = get_flows(sub(&state)).await.expect("get");
assert_eq!(page.revision, 0);
// The API writes a custom flow while the page is open.
let Json(api) = put_flows(
State(state.clone()),
Ok(body(0, &[], vec![custom("triage")])),
)
.await
.expect("the API's write");
let Json(api) = put_flows(sub(&state), Ok(body(0, &[], vec![custom("triage")])))
.await
.expect("the API's write");
// The page's first switch carries what it read.
let erased = put_flows(
State(state.clone()),
Ok(body(page.revision, &["closed"], vec![])),
)
.await
.expect_err("the page read nothing, and a document exists");
let erased = put_flows(sub(&state), Ok(body(page.revision, &["closed"], vec![])))
.await
.expect_err("the page read nothing, and a document exists");
assert_eq!(erased.status, Some(StatusCode::CONFLICT), "{erased:?}");
let Json(after) = get_flows(State(state.clone())).await.expect("get");
let Json(after) = get_flows(sub(&state)).await.expect("get");
assert_eq!(after, api);
assert_eq!(after.flows[0].id, "triage");
// Control: re-read, the same switch lands and keeps the flow.
let Json(switched) = put_flows(
State(state),
sub(&state),
Ok(body(after.revision, &["closed"], after.flows.clone())),
)
.await
@ -605,12 +655,12 @@ mod tests {
if let NodeKind::Todo(sink) = &mut typo.nodes[1].kind {
sink.key = "forge:{{ repo }}#{{ numbr }}:triage".to_owned();
}
let refused = put_flows(State(state.clone()), Ok(body(0, &[], vec![typo])))
let refused = put_flows(sub(&state), Ok(body(0, &[], vec![typo])))
.await
.expect_err("numbr is no field");
assert_eq!(refused.status, Some(StatusCode::BAD_REQUEST), "{refused:?}");
// Control: the same flow spelled right is stored.
let _ = put_flows(State(state), Ok(body(0, &[], vec![custom("typo")])))
let _ = put_flows(sub(&state), Ok(body(0, &[], vec![custom("typo")])))
.await
.expect("{number} is a field");
}
@ -694,7 +744,7 @@ mod tests {
.expect("put the status");
}
let Json(view) = get_flows(State(state.clone())).await.expect("get");
let Json(view) = get_flows(sub(&state)).await.expect("get");
assert_eq!(view.archetype_flows.len(), 1, "{:?}", view.archetype_flows);
let listed = &view.archetype_flows[0];
assert_eq!(listed.key, "archetype:triage/new-issues");
@ -708,7 +758,7 @@ mod tests {
"archetype:triage/new-issues@alice",
"archetype:gone/flow",
];
let Json(saved) = put_flows(State(state.clone()), Ok(body(0, &keys, vec![])))
let Json(saved) = put_flows(sub(&state), Ok(body(0, &keys, vec![])))
.await
.expect("the keys are saved");
assert_eq!(saved.disabled_builtins, keys);
@ -718,12 +768,9 @@ mod tests {
"a PUT answers with them too"
);
for bad in ["archetype:triage", "archetype:/x", "archetype:a/b@", "nope"] {
let refused = put_flows(
State(state.clone()),
Ok(body(saved.revision, &[bad], vec![])),
)
.await
.expect_err(bad);
let refused = put_flows(sub(&state), Ok(body(saved.revision, &[bad], vec![])))
.await
.expect_err(bad);
assert_eq!(refused.status, Some(StatusCode::BAD_REQUEST), "{bad}");
}
}
@ -743,13 +790,13 @@ mod tests {
"archetype:a/g@alice",
"closed",
];
let Json(saved) = put_flows(State(state.clone()), Ok(body(0, &keys, vec![])))
let Json(saved) = put_flows(sub(&state), Ok(body(0, &keys, vec![])))
.await
.expect("put");
let removed = clear_agent_keys(&client, "alice").await.expect("clear");
assert_eq!(removed, ["archetype:a/f@alice", "archetype:a/g@alice"]);
let Json(after) = get_flows(State(state.clone())).await.expect("get");
let Json(after) = get_flows(sub(&state)).await.expect("get");
assert_eq!(
after.disabled_builtins,
["archetype:a/f", "archetype:a/f@bob", "closed"]
@ -758,11 +805,11 @@ mod tests {
// Nothing of alice's left: no write.
assert!(clear_agent_keys(&client, "alice").await.unwrap().is_empty());
let Json(same) = get_flows(State(state.clone())).await.expect("get");
let Json(same) = get_flows(sub(&state)).await.expect("get");
assert_eq!(same.revision, after.revision);
// A name that is the end of another's is not it.
assert!(clear_agent_keys(&client, "ob").await.unwrap().is_empty());
let Json(same) = get_flows(State(state)).await.expect("get");
let Json(same) = get_flows(sub(&state)).await.expect("get");
assert_eq!(same.disabled_builtins, after.disabled_builtins);
}
}

View file

@ -26,9 +26,11 @@ use swarm_wire::router_api::{
};
use utoipa::{IntoParams, ToSchema};
use crate::notify_flows::{Stored, checked_document, open, queue_problem, stored, unreadable};
use crate::routes::{AppState, error_problem};
use crate::schedules::{queue, refused};
use crate::notify_flows::{
NotifyState, Stored, checked_document, open, queue_problem, stored, unreadable,
};
use crate::routes::error_problem;
use crate::schedules::{queue_of, refused};
/// Ask the router on `subject` and decode its answer as `T`.
///
@ -96,10 +98,10 @@ pub struct DeliveriesQuery {
tag = "notify"
)]
pub(crate) async fn get_deliveries(
State(state): State<AppState>,
State(state): State<NotifyState>,
Query(query): Query<DeliveriesQuery>,
) -> Result<Json<Deliveries>, ProblemDetails> {
let client = queue(&state).map_err(refused)?;
let client = queue_of(state.status.as_ref()).map_err(refused)?;
let body =
serde_json::to_vec(&DeliveriesRequest { limit: query.limit }).expect("a request encodes");
ask(&client, DELIVERIES_SUBJECT, body).await.map(Json)
@ -126,9 +128,9 @@ pub(crate) async fn get_deliveries(
tag = "notify"
)]
pub(crate) async fn get_dry_run(
State(state): State<AppState>,
State(state): State<NotifyState>,
) -> Result<Json<DryRun>, ProblemDetails> {
let client = queue(&state).map_err(refused)?;
let client = queue_of(state.status.as_ref()).map_err(refused)?;
let store = open(&client).await.map_err(|e| queue_problem(&e))?;
let (saved, _) = stored(&store).await.map_err(|e| queue_problem(&e))?;
let document = match saved {
@ -176,13 +178,13 @@ pub(crate) struct DraftFlows {
tag = "notify"
)]
pub(crate) async fn post_dry_run(
State(state): State<AppState>,
State(state): State<NotifyState>,
body: Result<Json<DraftFlows>, JsonRejection>,
) -> Result<Json<DryRun>, ProblemDetails> {
let Json(draft) = body.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.body_text()))?;
let document = checked_document(draft.disabled_builtins, draft.flows)
.map_err(|why| error_problem(StatusCode::BAD_REQUEST, &why))?;
let client = queue(&state).map_err(refused)?;
let client = queue_of(state.status.as_ref()).map_err(refused)?;
let body = serde_json::to_vec(&DryRunRequest { document }).expect("a request encodes");
ask(&client, DRY_RUN_SUBJECT, body).await.map(Json)
}
@ -196,6 +198,7 @@ mod tests {
use super::*;
use crate::test_nats::TestNats;
use axum::extract::FromRef;
fn query(limit: Option<usize>) -> Query<DeliveriesQuery> {
Query(DeliveriesQuery { limit })
@ -230,7 +233,7 @@ mod tests {
let client = nats.client().await;
let state = crate::agent_limits::tests::state(&client);
let deliveries = get_deliveries(State(state.clone()), query(None))
let deliveries = get_deliveries(State(NotifyState::from_ref(&state)), query(None))
.await
.expect_err("nobody answers");
assert_eq!(deliveries.status, Some(StatusCode::SERVICE_UNAVAILABLE));
@ -242,7 +245,7 @@ mod tests {
.contains("older build"),
"{deliveries:?}"
);
let dry = get_dry_run(State(state.clone()))
let dry = get_dry_run(State(NotifyState::from_ref(&state)))
.await
.expect_err("nobody answers");
assert_eq!(dry.status, Some(StatusCode::SERVICE_UNAVAILABLE));
@ -256,7 +259,7 @@ mod tests {
// Control: with a router answering, the same calls are 200.
let rows = answer(&client, DELIVERIES_SUBJECT, br#"{"rows":[]}"#.to_vec()).await;
let Json(got) = get_deliveries(State(state.clone()), query(None))
let Json(got) = get_deliveries(State(NotifyState::from_ref(&state)), query(None))
.await
.expect("answered");
assert!(got.rows.is_empty());
@ -266,7 +269,9 @@ mod tests {
flows: Vec::new(),
};
let dry_run = answer(&client, DRY_RUN_SUBJECT, serde_json::to_vec(&hits).unwrap()).await;
let Json(got) = get_dry_run(State(state)).await.expect("answered");
let Json(got) = get_dry_run(State(NotifyState::from_ref(&state)))
.await
.expect("answered");
assert_eq!(got, hits);
dry_run.await.expect("the router task");
}
@ -275,10 +280,12 @@ mod tests {
#[tokio::test]
async fn without_a_queue_both_are_unavailable() {
let (state, _) = crate::routes::tests::state_with_roster();
let a = get_deliveries(State(state.clone()), query(None))
let a = get_deliveries(State(NotifyState::from_ref(&state)), query(None))
.await
.expect_err("no queue");
let b = get_dry_run(State(NotifyState::from_ref(&state)))
.await
.expect_err("no queue");
let b = get_dry_run(State(state)).await.expect_err("no queue");
assert_eq!(a.status, Some(StatusCode::SERVICE_UNAVAILABLE));
assert_eq!(b.status, Some(StatusCode::SERVICE_UNAVAILABLE));
}
@ -291,7 +298,7 @@ mod tests {
let state = crate::agent_limits::tests::state(&client);
let asked = answer(&client, DELIVERIES_SUBJECT, br#"{"rows":[]}"#.to_vec()).await;
let _ = get_deliveries(State(state.clone()), query(Some(7)))
let _ = get_deliveries(State(NotifyState::from_ref(&state)), query(Some(7)))
.await
.expect("answered");
let request: DeliveriesRequest =
@ -315,7 +322,9 @@ mod tests {
serde_json::to_vec(&reply).unwrap(),
)
.await;
let Json(got) = get_dry_run(State(state.clone())).await.expect("answered");
let Json(got) = get_dry_run(State(NotifyState::from_ref(&state)))
.await
.expect("answered");
assert_eq!(got, reply);
let sent: DryRunRequest =
serde_json::from_slice(&asked.await.expect("task")).expect("a request");
@ -340,7 +349,9 @@ mod tests {
serde_json::to_vec(&reply).unwrap(),
)
.await;
let _ = get_dry_run(State(state)).await.expect("answered");
let _ = get_dry_run(State(NotifyState::from_ref(&state)))
.await
.expect("answered");
let sent: DryRunRequest =
serde_json::from_slice(&asked.await.expect("task")).expect("a request");
assert_eq!(sent.document, saved);
@ -360,7 +371,7 @@ mod tests {
br#"{"error":"no events"}"#.to_vec(),
)
.await;
let refused = get_dry_run(State(state.clone()))
let refused = get_dry_run(State(NotifyState::from_ref(&state)))
.await
.expect_err("refused");
assert_eq!(refused.status, Some(StatusCode::BAD_GATEWAY));
@ -381,7 +392,9 @@ mod tests {
)
.await
.expect("seed");
let unreadable = get_dry_run(State(state)).await.expect_err("version 3");
let unreadable = get_dry_run(State(NotifyState::from_ref(&state)))
.await
.expect_err("version 3");
assert_eq!(unreadable.status, Some(StatusCode::CONFLICT));
}
@ -432,7 +445,7 @@ mod tests {
)
.await;
let Json(got) = post_dry_run(
State(state),
State(NotifyState::from_ref(&state)),
Ok(draft(&serde_json::json!([sink_flow("mine")]))),
)
.await
@ -460,7 +473,7 @@ mod tests {
let mut orphan = sink_flow("orphan");
orphan["edges"] = serde_json::json!([]);
let refused = post_dry_run(
State(state.clone()),
State(NotifyState::from_ref(&state)),
Ok(draft(&serde_json::json!([orphan]))),
)
.await
@ -489,7 +502,7 @@ mod tests {
let typo: Result<Json<DraftFlows>, JsonRejection> = Err(
JsonRejection::MissingJsonContentType(MissingJsonContentType::default()),
);
let refused = post_dry_run(State(state.clone()), typo)
let refused = post_dry_run(State(NotifyState::from_ref(&state)), typo)
.await
.expect_err("not json");
assert_eq!(refused.status, Some(StatusCode::BAD_REQUEST));
@ -497,7 +510,7 @@ mod tests {
// Nothing was forwarded: the next request on the subject is the
// control's, not either refusal's.
let control = post_dry_run(
State(state),
State(NotifyState::from_ref(&state)),
Ok(draft(&serde_json::json!([sink_flow("ok")]))),
);
let (sent, got) = tokio::join!(
@ -530,14 +543,20 @@ mod tests {
let nats = TestNats::start();
let client = nats.client().await;
let state = crate::agent_limits::tests::state(&client);
let b = post_dry_run(State(state), Ok(draft(&serde_json::json!([]))))
.await
.expect_err("nobody answers");
let b = post_dry_run(
State(NotifyState::from_ref(&state)),
Ok(draft(&serde_json::json!([]))),
)
.await
.expect_err("nobody answers");
assert_eq!(b.status, Some(StatusCode::SERVICE_UNAVAILABLE));
let (state, _) = crate::routes::tests::state_with_roster();
let b = post_dry_run(State(state), Ok(draft(&serde_json::json!([]))))
.await
.expect_err("no queue");
let b = post_dry_run(
State(NotifyState::from_ref(&state)),
Ok(draft(&serde_json::json!([]))),
)
.await
.expect_err("no queue");
assert_eq!(b.status, Some(StatusCode::SERVICE_UNAVAILABLE));
}
}