swarm-controller: move the review concern into its own module
Refs #6897
This commit is contained in:
parent
b52fc0ec8e
commit
237cdaffaa
11 changed files with 24 additions and 12 deletions
7
swarm-controller/src/review/mod.rs
Normal file
7
swarm-controller/src/review/mod.rs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
//! The review concern: the review classifier, requested reviews and the
|
||||
//! notification flows, with their routes.
|
||||
|
||||
pub(crate) mod notify_flows;
|
||||
pub(crate) mod notify_router_api;
|
||||
pub(crate) mod request_reviewer;
|
||||
pub(crate) mod review_classifier;
|
||||
768
swarm-controller/src/review/notify_flows.rs
Normal file
768
swarm-controller/src/review/notify_flows.rs
Normal file
|
|
@ -0,0 +1,768 @@
|
|||
//! `GET` and `PUT /api/notify/flows`: which of the notification router's
|
||||
//! built-in flows are switched off, and the custom flows.
|
||||
//!
|
||||
//! The flows are one document under one key ([`notify_flows::KEY`] in
|
||||
//! [`notify_flows::BUCKET`]), which only this daemon writes, as the schedule
|
||||
//! definitions are. A `PUT` replaces the whole document in one
|
||||
//! compare-and-set, after [`Document::check`]. The router reads the key
|
||||
//! every few seconds, so a change applies to the next event with no restart.
|
||||
//! No document means the built-in flows alone.
|
||||
//!
|
||||
//! The built-in flows are defined in code, in `swarm_wire::notify_flows`, and
|
||||
//! the document stores only their disabled ids, so a `GET` shows the ones
|
||||
//! this build knows.
|
||||
|
||||
use anyhow::Context as _;
|
||||
use async_nats::jetstream::kv::Store;
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::extract::rejection::JsonRejection;
|
||||
use axum::http::StatusCode;
|
||||
use problem_details::ProblemDetails;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
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};
|
||||
|
||||
/// How many times a losing writer re-reads and re-applies, as in
|
||||
/// `wanted::MAX_ATTEMPTS`.
|
||||
const MAX_ATTEMPTS: usize = 5;
|
||||
|
||||
/// What `GET` and a successful `PUT` answer.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, ToSchema)]
|
||||
pub(crate) struct FlowsView {
|
||||
/// The revision of the stored document, to send back in a `PUT`; `0` when
|
||||
/// none is stored.
|
||||
revision: u64,
|
||||
/// The ids of the built-in flows that are switched off, and the keys of the
|
||||
/// archetype flows that are.
|
||||
disabled_builtins: Vec<String>,
|
||||
/// The built-in flows this build ships, all of them, switched off or not.
|
||||
builtins: Vec<Flow>,
|
||||
/// The custom flows.
|
||||
flows: Vec<Flow>,
|
||||
/// The flows archetypes carry, each with the agents it runs for. They follow
|
||||
/// their archetype, so they are not in the document; a `PUT` switches one off
|
||||
/// with its `key` in `disabled_builtins`. An older controller's answer has
|
||||
/// none.
|
||||
archetype_flows: Vec<ArchetypeFlowView>,
|
||||
/// What this build accepts: source events, fields, node kinds and limits,
|
||||
/// for an editor to offer. An older controller's answer has none.
|
||||
schema: notify_flows::Schema,
|
||||
}
|
||||
|
||||
/// One flow an archetype carries.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, ToSchema)]
|
||||
pub(crate) struct ArchetypeFlowView {
|
||||
/// The archetype's name.
|
||||
archetype: String,
|
||||
/// What names the flow in `disabled_builtins` (off for every member), in the
|
||||
/// router's log and in a todo's source. `<key>@<agent>` in
|
||||
/// `disabled_builtins` switches it off for one member.
|
||||
key: String,
|
||||
/// The flow as the archetype declares it, under its own `id`.
|
||||
flow: Flow,
|
||||
/// The agents of the archetype, by name.
|
||||
members: Vec<String>,
|
||||
}
|
||||
|
||||
/// The body of a `PUT`: the whole document.
|
||||
#[derive(Debug, Clone, Deserialize, ToSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct PutFlows {
|
||||
/// The `revision` the client read, `0` for "no document stored". The
|
||||
/// `PUT` is refused when the stored revision is another, which includes a
|
||||
/// document written since a client read `0`. A KV revision is never `0`.
|
||||
revision: u64,
|
||||
/// The ids of the built-in flows to switch off.
|
||||
#[serde(default)]
|
||||
disabled_builtins: Vec<String>,
|
||||
/// The custom flows.
|
||||
#[serde(default)]
|
||||
flows: Vec<Flow>,
|
||||
}
|
||||
|
||||
impl FlowsView {
|
||||
fn of(doc: Document, revision: u64, archetype_flows: Vec<ArchetypeFlowView>) -> Self {
|
||||
Self {
|
||||
revision,
|
||||
disabled_builtins: doc.disabled_builtins,
|
||||
builtins: notify_flows::builtins(),
|
||||
flows: doc.flows,
|
||||
archetype_flows,
|
||||
schema: notify_flows::schema(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the key holds.
|
||||
pub(crate) enum Stored {
|
||||
/// No key, or a deleted one.
|
||||
Nothing,
|
||||
Document(Document),
|
||||
/// A document this build cannot read, with why.
|
||||
Unreadable(DecodeError),
|
||||
}
|
||||
|
||||
/// The stored document, with the revision to write against.
|
||||
pub(crate) async fn stored(store: &Store) -> anyhow::Result<(Stored, Option<u64>)> {
|
||||
struct Read(Stored);
|
||||
impl Default for Read {
|
||||
fn default() -> Self {
|
||||
Self(Stored::Nothing)
|
||||
}
|
||||
}
|
||||
let (Read(stored), revision) = read_with(store, notify_flows::KEY, |bytes| {
|
||||
Ok(Read(match Document::decode(bytes) {
|
||||
Ok(doc) => Stored::Document(doc),
|
||||
Err(e) => Stored::Unreadable(e),
|
||||
}))
|
||||
})
|
||||
.await?;
|
||||
Ok((stored, revision))
|
||||
}
|
||||
|
||||
/// Open [`notify_flows::BUCKET`], creating it if nothing has yet.
|
||||
pub(crate) async fn open(client: &async_nats::Client) -> anyhow::Result<Store> {
|
||||
let js = async_nats::jetstream::new(client.clone());
|
||||
if let Ok(store) = js.get_key_value(notify_flows::BUCKET).await {
|
||||
return Ok(store);
|
||||
}
|
||||
js.create_key_value(async_nats::jetstream::kv::Config {
|
||||
bucket: notify_flows::BUCKET.to_owned(),
|
||||
description: "The notification router's flows: disabled built-ins and custom flows"
|
||||
.to_owned(),
|
||||
history: 1,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.with_context(|| format!("creating the {} bucket", notify_flows::BUCKET))
|
||||
}
|
||||
|
||||
pub(crate) fn queue_problem(e: &anyhow::Error) -> ProblemDetails {
|
||||
tracing::warn!(error = %format!("{e:#}"), "notify flows: queue failure");
|
||||
error_problem(wanted_error_status(e), &format!("{e:#}"))
|
||||
}
|
||||
|
||||
/// Read the flows. Creates the `notify-flows` bucket when it is missing, as a
|
||||
/// `PUT` does, so the router finds it empty rather than absent.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/notify/flows",
|
||||
responses(
|
||||
(status = 200, description = "the stored document, with the built-in flows this \
|
||||
build ships; with none stored, no disabled built-ins and no custom flows",
|
||||
body = FlowsView),
|
||||
(status = 409, description = "the stored document is not one this build reads, \
|
||||
such as a newer build's version (problem+json)", body = String),
|
||||
(status = 503, description = "no swarm queue is configured on this host, or it is \
|
||||
not connected (problem+json)", body = String),
|
||||
(status = 500, description = "the flows could not be read (problem+json)",
|
||||
body = String),
|
||||
),
|
||||
tag = "notify"
|
||||
)]
|
||||
pub(crate) async fn get_flows(
|
||||
State(state): State<AppState>,
|
||||
) -> Result<Json<FlowsView>, ProblemDetails> {
|
||||
let client = queue(&state).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 {
|
||||
Stored::Nothing => Ok(Json(FlowsView::of(
|
||||
Document::default(),
|
||||
revision.unwrap_or(0),
|
||||
archetype_flows(&client).await,
|
||||
))),
|
||||
Stored::Document(doc) => Ok(Json(FlowsView::of(
|
||||
doc,
|
||||
revision.unwrap_or(0),
|
||||
archetype_flows(&client).await,
|
||||
))),
|
||||
Stored::Unreadable(e) => Err(unreadable(&e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The flows the archetypes carry, with their agents. A read that fails is
|
||||
/// logged and leaves the list empty: the document is still served.
|
||||
async fn archetype_flows(client: &async_nats::Client) -> Vec<ArchetypeFlowView> {
|
||||
let found = async {
|
||||
// The router's members: the archetype keys of the agents in the swarm.
|
||||
let roster = swarm_queue_client::agent_status::roster(client)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("listing the agents: {e}"))?;
|
||||
let mut refs = crate::agent_archetype::all(client).await?;
|
||||
refs.retain(|agent, _| roster.contains(agent));
|
||||
let mut records = BTreeMap::new();
|
||||
if let Some(store) = archetypes::open(client).await? {
|
||||
let sources: BTreeSet<&str> = refs.values().map(|r| r.source.as_str()).collect();
|
||||
for source in sources {
|
||||
let (record, _, _) = read_or_default::<SourceRecord>(&store, source).await?;
|
||||
records.insert(source.to_owned(), record);
|
||||
}
|
||||
}
|
||||
anyhow::Ok(flows_of(&refs, &records).0)
|
||||
}
|
||||
.await;
|
||||
match found {
|
||||
Ok(found) => found
|
||||
.into_iter()
|
||||
.map(|f| ArchetypeFlowView {
|
||||
key: f.key(),
|
||||
archetype: f.archetype,
|
||||
flow: f.flow,
|
||||
members: f.members,
|
||||
})
|
||||
.collect(),
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
error = %format!("{e:#}"),
|
||||
"notify flows: reading the archetype flows failed; none shown"
|
||||
);
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `disabled` less the switch-offs for `agent` alone (`archetype:…/…@agent`; no
|
||||
/// built-in id has an `@`),
|
||||
/// or `None` when it has none. The per-archetype keys stay.
|
||||
fn without_agent_keys(disabled: &[String], agent: &str) -> Option<Vec<String>> {
|
||||
let suffix = format!("@{agent}");
|
||||
let kept: Vec<String> = disabled
|
||||
.iter()
|
||||
.filter(|k| !k.ends_with(&suffix))
|
||||
.cloned()
|
||||
.collect();
|
||||
(kept.len() != disabled.len()).then_some(kept)
|
||||
}
|
||||
|
||||
/// Remove the keys that switch archetype flows off for `agent` from the stored
|
||||
/// document, in the compare-and-set loop a `PUT` uses, so a concurrent edit
|
||||
/// is not lost. Answers the keys removed. No write when there are none.
|
||||
async fn clear_agent_keys(client: &async_nats::Client, agent: &str) -> anyhow::Result<Vec<String>> {
|
||||
let store = open(client).await?;
|
||||
for _ in 0..MAX_ATTEMPTS {
|
||||
let (current, revision) = stored(&store).await?;
|
||||
let Stored::Document(mut doc) = current else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let Some(kept) = without_agent_keys(&doc.disabled_builtins, agent) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let removed: Vec<String> = doc
|
||||
.disabled_builtins
|
||||
.iter()
|
||||
.filter(|k| !kept.contains(k))
|
||||
.cloned()
|
||||
.collect();
|
||||
doc.disabled_builtins = kept;
|
||||
if write_revision(&store, notify_flows::KEY, &doc, revision)
|
||||
.await?
|
||||
.is_some()
|
||||
{
|
||||
return Ok(removed);
|
||||
}
|
||||
}
|
||||
anyhow::bail!("gave up after {MAX_ATTEMPTS} conflicting writes")
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
let cleared = async {
|
||||
let client = queue(state).map_err(|(_, why)| anyhow::anyhow!(why))?;
|
||||
clear_agent_keys(&client, agent).await
|
||||
}
|
||||
.await;
|
||||
match cleared {
|
||||
Ok(removed) if removed.is_empty() => {}
|
||||
Ok(removed) => {
|
||||
tracing::info!(
|
||||
hive,
|
||||
agent,
|
||||
?removed,
|
||||
"destroyed agent's flow switch-offs cleared"
|
||||
);
|
||||
}
|
||||
Err(e) => tracing::error!(
|
||||
hive,
|
||||
agent,
|
||||
error = %format!("{e:#}"),
|
||||
"clearing this agent's flow switch-offs (`archetype:…@<agent>` in the flows \
|
||||
document's disabled list) FAILED; it was destroyed anyway, so a new agent of the \
|
||||
same name starts with those flows off. Declaring the agent destroyed again \
|
||||
re-runs this."
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn unreadable(why: &DecodeError) -> ProblemDetails {
|
||||
error_problem(
|
||||
StatusCode::CONFLICT,
|
||||
&format!("the stored flows document is not one this build reads: {why}"),
|
||||
)
|
||||
}
|
||||
|
||||
/// The document a body describes, or the first way it fails
|
||||
/// [`Document::check`].
|
||||
pub(crate) fn checked_document(
|
||||
disabled_builtins: Vec<String>,
|
||||
flows: Vec<Flow>,
|
||||
) -> Result<Document, String> {
|
||||
let doc = Document {
|
||||
version: notify_flows::VERSION,
|
||||
disabled_builtins,
|
||||
flows,
|
||||
};
|
||||
doc.check().map(|()| doc)
|
||||
}
|
||||
|
||||
/// Replace the flows.
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/api/notify/flows",
|
||||
request_body = PutFlows,
|
||||
responses(
|
||||
(status = 200, description = "the document as stored; the router applies it from \
|
||||
its next event", body = FlowsView),
|
||||
(status = 400, description = "not JSON or not this shape, or the document fails its \
|
||||
check: a `disabled_builtins` entry that is no built-in, a custom flow whose id \
|
||||
is another's or a built-in's, a flow that is not a tree (one `source`, one \
|
||||
parent for every other node, every node reachable, no children under a \
|
||||
`todo`), more than 64 nodes, 16 levels or 100 flows, an id that is not 1 to 64 \
|
||||
letters, digits, `-` or `_`, a source event the router is not sent, a condition \
|
||||
or recipient field that is no event field, or an upsert with no text \
|
||||
(problem+json)", body = String),
|
||||
(status = 409, description = "the stored document is not at `revision` (another write landed, or one now exists where the client read none), or the stored \
|
||||
document is a version this build does not read, which a `PUT` would erase \
|
||||
(problem+json)", body = String),
|
||||
(status = 503, description = "no swarm queue is configured on this host, or it is \
|
||||
not connected (problem+json)", body = String),
|
||||
(status = 500, description = "the flows could not be written (problem+json)",
|
||||
body = String),
|
||||
),
|
||||
tag = "notify"
|
||||
)]
|
||||
pub(crate) async fn put_flows(
|
||||
State(state): State<AppState>,
|
||||
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 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))?;
|
||||
// An unreadable document is replaced only when it is not a version
|
||||
// this build does not know: a newer build's document is kept for it.
|
||||
if let Stored::Unreadable(why @ DecodeError::UnknownVersion(_)) = ¤t {
|
||||
return Err(unreadable(why));
|
||||
}
|
||||
if put.revision != revision.unwrap_or(0) {
|
||||
return Err(error_problem(
|
||||
StatusCode::CONFLICT,
|
||||
&format!(
|
||||
"the flows are not at revision {}; read them again",
|
||||
put.revision
|
||||
),
|
||||
));
|
||||
}
|
||||
if let Some(written) = write_revision(&store, notify_flows::KEY, &doc, revision)
|
||||
.await
|
||||
.map_err(|e| queue_problem(&e))?
|
||||
{
|
||||
tracing::info!(
|
||||
disabled = ?doc.disabled_builtins,
|
||||
custom = doc.flows.len(),
|
||||
"set the notification router's flows"
|
||||
);
|
||||
return Ok(Json(FlowsView::of(
|
||||
doc,
|
||||
written,
|
||||
archetype_flows(&client).await,
|
||||
)));
|
||||
}
|
||||
}
|
||||
Err(queue_problem(&anyhow::anyhow!(
|
||||
"gave up writing the notification flows after {MAX_ATTEMPTS} conflicting writes"
|
||||
)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use swarm_wire::notify_flows::{Edge, Node, NodeKind, Recipients, TodoSink};
|
||||
use swarm_wire::router_todo::Op;
|
||||
|
||||
use super::*;
|
||||
use crate::test_nats::TestNats;
|
||||
|
||||
fn custom(id: &str) -> Flow {
|
||||
Flow {
|
||||
id: id.to_owned(),
|
||||
name: "new to triage".to_owned(),
|
||||
enabled: true,
|
||||
nodes: vec![
|
||||
Node {
|
||||
id: "source".to_owned(),
|
||||
kind: NodeKind::Source {
|
||||
events: vec!["issues".to_owned()],
|
||||
},
|
||||
},
|
||||
Node {
|
||||
id: "sink".to_owned(),
|
||||
kind: NodeKind::Todo(TodoSink {
|
||||
to: Recipients::Agent("triage".to_owned()),
|
||||
op: Op::Upsert,
|
||||
key: "forge:{repo}#{number}:triage".to_owned(),
|
||||
prefix: false,
|
||||
text: "triage {repo}#{number}".to_owned(),
|
||||
}),
|
||||
},
|
||||
],
|
||||
edges: vec![Edge {
|
||||
from: "source".to_owned(),
|
||||
to: "sink".to_owned(),
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn body(revision: u64, disabled: &[&str], flows: Vec<Flow>) -> Json<PutFlows> {
|
||||
Json(PutFlows {
|
||||
revision,
|
||||
disabled_builtins: disabled.iter().map(|s| (*s).to_owned()).collect(),
|
||||
flows,
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_flows_are_read_replaced_and_checked_on_save() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
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");
|
||||
assert_eq!(view.revision, 0);
|
||||
assert!(view.disabled_builtins.is_empty() && view.flows.is_empty());
|
||||
assert_eq!(view.builtins.len(), notify_flows::builtins().len());
|
||||
assert!(view.builtins.iter().any(|f| f.id == "head-classifier"));
|
||||
let json = serde_json::to_value(&view).expect("serializes");
|
||||
assert_eq!(json["schema"]["limits"]["max_nodes"], 64);
|
||||
assert_eq!(json["schema"]["node_kinds"][0]["kind"], "source");
|
||||
assert_eq!(view.schema, notify_flows::schema());
|
||||
|
||||
let Json(saved) = put_flows(
|
||||
State(state.clone()),
|
||||
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");
|
||||
assert_eq!(read, saved);
|
||||
assert_eq!(read.disabled_builtins, ["unassigned"]);
|
||||
assert_eq!(read.flows[0].id, "triage");
|
||||
|
||||
// The stored bytes are the document the router decodes.
|
||||
let store = open(&client).await.expect("bucket");
|
||||
let bytes = store
|
||||
.get(notify_flows::KEY)
|
||||
.await
|
||||
.expect("read")
|
||||
.expect("stored");
|
||||
let doc = Document::decode(&bytes).expect("the router reads it");
|
||||
assert_eq!(
|
||||
doc.active().0.len(),
|
||||
notify_flows::builtins().len(),
|
||||
"the built-ins less the switched-off one, and the custom flow"
|
||||
);
|
||||
|
||||
// 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])))
|
||||
.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![])))
|
||||
.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");
|
||||
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![])))
|
||||
.await
|
||||
.expect_err("stale");
|
||||
assert_eq!(outdated.status, Some(StatusCode::CONFLICT), "{outdated:?}");
|
||||
let Json(next) = put_flows(State(state.clone()), Ok(body(revision, &[], vec![])))
|
||||
.await
|
||||
.expect("current revision");
|
||||
assert!(next.revision > revision);
|
||||
assert!(next.flows.is_empty());
|
||||
}
|
||||
|
||||
/// A document of a version this build does not know is neither served
|
||||
/// nor replaced, and a garbled one is replaced.
|
||||
#[tokio::test]
|
||||
async fn a_document_of_another_version_is_kept_and_a_garbled_one_is_replaced() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = crate::agent_limits::tests::state(&client);
|
||||
let store = open(&client).await.expect("bucket");
|
||||
|
||||
store
|
||||
.put(
|
||||
notify_flows::KEY,
|
||||
br#"{"version":3,"flows":[]}"#.to_vec().into(),
|
||||
)
|
||||
.await
|
||||
.expect("seed");
|
||||
let got = get_flows(State(state.clone()))
|
||||
.await
|
||||
.expect_err("version 3");
|
||||
assert_eq!(got.status, Some(StatusCode::CONFLICT), "{got:?}");
|
||||
let refused = put_flows(State(state.clone()), Ok(body(0, &[], vec![])))
|
||||
.await
|
||||
.expect_err("version 3 is kept");
|
||||
assert_eq!(refused.status, Some(StatusCode::CONFLICT), "{refused:?}");
|
||||
let kept = store
|
||||
.get(notify_flows::KEY)
|
||||
.await
|
||||
.expect("read")
|
||||
.expect("stored");
|
||||
assert_eq!(&kept[..], br#"{"version":3,"flows":[]}"#);
|
||||
|
||||
// Control: garbage that names no version is replaced by a save.
|
||||
let garbage = store
|
||||
.put(notify_flows::KEY, b"garbage".to_vec().into())
|
||||
.await
|
||||
.expect("seed");
|
||||
let _ = put_flows(State(state.clone()), Ok(body(garbage, &["closed"], vec![])))
|
||||
.await
|
||||
.expect("replaces garbage");
|
||||
let Json(view) = get_flows(State(state)).await.expect("readable again");
|
||||
assert_eq!(view.disabled_builtins, ["closed"]);
|
||||
}
|
||||
|
||||
/// A page that read no document cannot erase one written since: its
|
||||
/// `revision: 0` means "create", and the document exists by then.
|
||||
#[tokio::test]
|
||||
async fn a_page_that_read_nothing_cannot_erase_a_flow_written_after() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = crate::agent_limits::tests::state(&client);
|
||||
|
||||
let Json(page) = get_flows(State(state.clone())).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");
|
||||
// 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");
|
||||
assert_eq!(erased.status, Some(StatusCode::CONFLICT), "{erased:?}");
|
||||
let Json(after) = get_flows(State(state.clone())).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),
|
||||
Ok(body(after.revision, &["closed"], after.flows.clone())),
|
||||
)
|
||||
.await
|
||||
.expect("the switch with the revision it read");
|
||||
assert_eq!(switched.disabled_builtins, ["closed"]);
|
||||
assert_eq!(switched.flows[0].id, "triage");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_template_naming_no_event_field_is_refused_on_save() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = crate::agent_limits::tests::state(&client);
|
||||
|
||||
let mut typo = custom("typo");
|
||||
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])))
|
||||
.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")])))
|
||||
.await
|
||||
.expect("{number} is a field");
|
||||
}
|
||||
|
||||
/// The archetypes' flows are listed with their agents; their keys go in the
|
||||
/// disabled list, a key for a flow that is gone is kept, and a key of no
|
||||
/// valid shape is refused.
|
||||
#[tokio::test]
|
||||
async fn archetype_flows_are_listed_and_their_keys_are_saved() {
|
||||
use swarm_queue_client::agent_archetype::ArchetypeRef;
|
||||
use swarm_queue_client::archetypes::{ArchetypeMeta, BUILTIN_SOURCE, SourceRecord};
|
||||
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = crate::agent_limits::tests::state(&client);
|
||||
|
||||
let mut members = custom("new-issues");
|
||||
members.nodes[1].kind = NodeKind::Todo(TodoSink {
|
||||
to: Recipients::Members,
|
||||
op: Op::Upsert,
|
||||
key: "forge:{{ repo }}#{{ number }}:triage".to_owned(),
|
||||
prefix: false,
|
||||
text: "triage {{ repo }}#{{ number }}".to_owned(),
|
||||
});
|
||||
let record = SourceRecord {
|
||||
source: BUILTIN_SOURCE.to_owned(),
|
||||
archetypes: [
|
||||
(
|
||||
"triage".to_owned(),
|
||||
ArchetypeMeta {
|
||||
description: "d".to_owned(),
|
||||
flows: vec![members.clone()],
|
||||
..ArchetypeMeta::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
"reviewer".to_owned(),
|
||||
ArchetypeMeta {
|
||||
description: "d".to_owned(),
|
||||
..ArchetypeMeta::default()
|
||||
},
|
||||
),
|
||||
]
|
||||
.into(),
|
||||
refused: BTreeMap::default(),
|
||||
};
|
||||
let records = swarm_queue_client::archetypes::open_or_create(&client)
|
||||
.await
|
||||
.expect("records");
|
||||
records
|
||||
.put(BUILTIN_SOURCE, serde_json::to_vec(&record).unwrap().into())
|
||||
.await
|
||||
.expect("put the record");
|
||||
let choices = swarm_queue_client::agent_archetype::open_or_create(&client)
|
||||
.await
|
||||
.expect("choices");
|
||||
for (agent, archetype) in [
|
||||
("alice", "triage"),
|
||||
("bob", "triage"),
|
||||
("carol", "reviewer"),
|
||||
// In the bucket but not in the swarm: the router sends it nothing.
|
||||
("dave", "triage"),
|
||||
] {
|
||||
let choice = ArchetypeRef {
|
||||
source: BUILTIN_SOURCE.to_owned(),
|
||||
name: archetype.to_owned(),
|
||||
};
|
||||
choices
|
||||
.put(agent, serde_json::to_vec(&choice).unwrap().into())
|
||||
.await
|
||||
.expect("put the choice");
|
||||
}
|
||||
|
||||
let status = swarm_queue_client::agent_status::open_or_create(&client)
|
||||
.await
|
||||
.expect("status");
|
||||
for agent in ["alice", "bob", "carol"] {
|
||||
status
|
||||
.put(format!("hive.{agent}"), "{}".into())
|
||||
.await
|
||||
.expect("put the status");
|
||||
}
|
||||
|
||||
let Json(view) = get_flows(State(state.clone())).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");
|
||||
assert_eq!(listed.archetype, "triage");
|
||||
assert_eq!(listed.flow, members);
|
||||
assert_eq!(listed.members, ["alice", "bob"]);
|
||||
|
||||
// Off for everyone, off for one agent, and a key of a flow that is gone.
|
||||
let keys = [
|
||||
"archetype:triage/new-issues",
|
||||
"archetype:triage/new-issues@alice",
|
||||
"archetype:gone/flow",
|
||||
];
|
||||
let Json(saved) = put_flows(State(state.clone()), Ok(body(0, &keys, vec![])))
|
||||
.await
|
||||
.expect("the keys are saved");
|
||||
assert_eq!(saved.disabled_builtins, keys);
|
||||
assert_eq!(
|
||||
saved.archetype_flows.len(),
|
||||
1,
|
||||
"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);
|
||||
assert_eq!(refused.status, Some(StatusCode::BAD_REQUEST), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Destroying an agent removes its own switch-offs from the document and
|
||||
/// nothing else; a document without any is not written.
|
||||
#[tokio::test]
|
||||
async fn a_destroyed_agents_switch_offs_are_cleared_and_nothing_else() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = crate::agent_limits::tests::state(&client);
|
||||
|
||||
let keys = [
|
||||
"archetype:a/f",
|
||||
"archetype:a/f@alice",
|
||||
"archetype:a/f@bob",
|
||||
"archetype:a/g@alice",
|
||||
"closed",
|
||||
];
|
||||
let Json(saved) = put_flows(State(state.clone()), 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");
|
||||
assert_eq!(
|
||||
after.disabled_builtins,
|
||||
["archetype:a/f", "archetype:a/f@bob", "closed"]
|
||||
);
|
||||
assert!(after.revision > saved.revision);
|
||||
|
||||
// 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");
|
||||
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");
|
||||
assert_eq!(same.disabled_builtins, after.disabled_builtins);
|
||||
}
|
||||
}
|
||||
543
swarm-controller/src/review/notify_router_api.rs
Normal file
543
swarm-controller/src/review/notify_router_api.rs
Normal file
|
|
@ -0,0 +1,543 @@
|
|||
//! `GET /api/notify/deliveries`, `GET /api/notify/dry-run` and
|
||||
//! `POST /api/notify/dry-run`: what the
|
||||
//! notification router has delivered, and what the saved flows, or a draft,
|
||||
//! would do with
|
||||
//! the newest forge events.
|
||||
//!
|
||||
//! The router keeps the log and the events, so each is a NATS request to it
|
||||
//! (`swarm_wire::router_api`). A router that predates them, or none at all,
|
||||
//! has no subscriber: the queue answers "no responders" at once and these
|
||||
//! answer 503 saying so, as they do when it hears the request and stays
|
||||
//! silent. The saved document is what `GET /api/notify/flows` shows; the `POST`
|
||||
//! sends the same request with the body's document, checked as a `PUT` checks
|
||||
//! it.
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::rejection::JsonRejection;
|
||||
use axum::extract::{Query, State};
|
||||
use axum::http::StatusCode;
|
||||
use problem_details::ProblemDetails;
|
||||
use serde::Deserialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use swarm_wire::notify_flows::{Document, Flow};
|
||||
use swarm_wire::router_api::{
|
||||
DELIVERIES_SUBJECT, DRY_RUN_SUBJECT, Deliveries, DeliveriesRequest, DryRun, DryRunRequest,
|
||||
REPLY_DEADLINE, Refused,
|
||||
};
|
||||
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};
|
||||
|
||||
/// Ask the router on `subject` and decode its answer as `T`.
|
||||
///
|
||||
/// 503: nothing hears the request, or what hears it does not answer in time;
|
||||
/// both mean the running router does not have this feature. 502: it answered
|
||||
/// with a refusal or with something this build cannot read.
|
||||
async fn ask<T: DeserializeOwned>(
|
||||
client: &async_nats::Client,
|
||||
subject: &str,
|
||||
body: Vec<u8>,
|
||||
) -> Result<T, ProblemDetails> {
|
||||
use async_nats::RequestErrorKind;
|
||||
|
||||
let sent = async_nats::Request::new()
|
||||
.payload(body.into())
|
||||
.timeout(Some(REPLY_DEADLINE));
|
||||
let reply = client
|
||||
.send_request(subject.to_owned(), sent)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
let detail = match e.kind() {
|
||||
RequestErrorKind::NoResponders => "the notification router does not answer this: \
|
||||
it is not running, or it is an older build than this controller"
|
||||
.to_owned(),
|
||||
RequestErrorKind::TimedOut => format!(
|
||||
"the notification router sent no answer within {}s",
|
||||
REPLY_DEADLINE.as_secs()
|
||||
),
|
||||
_ => format!("asking the notification router failed: {e}"),
|
||||
};
|
||||
error_problem(StatusCode::SERVICE_UNAVAILABLE, &detail)
|
||||
})?;
|
||||
if let Ok(answer) = serde_json::from_slice::<T>(&reply.payload) {
|
||||
return Ok(answer);
|
||||
}
|
||||
let detail = match serde_json::from_slice::<Refused>(&reply.payload) {
|
||||
Ok(Refused { error }) => format!("the notification router refused: {error}"),
|
||||
Err(e) => format!("the notification router's answer did not decode: {e}"),
|
||||
};
|
||||
Err(error_problem(StatusCode::BAD_GATEWAY, &detail))
|
||||
}
|
||||
|
||||
/// `get_deliveries`'s query.
|
||||
#[derive(Deserialize, IntoParams)]
|
||||
pub struct DeliveriesQuery {
|
||||
/// At most this many rows; 100 when absent, and the log keeps 500.
|
||||
limit: Option<usize>,
|
||||
}
|
||||
|
||||
/// The newest deliveries the router made, newest first.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/notify/deliveries",
|
||||
params(DeliveriesQuery),
|
||||
responses(
|
||||
(status = 200, description = "the router's deliveries log, newest first: when, which \
|
||||
flow and node, the event and issue, who got it, and whether it went through",
|
||||
body = Deliveries),
|
||||
(status = 502, description = "the router refused, or its answer did not decode \
|
||||
(problem+json)", body = String),
|
||||
(status = 503, description = "no swarm queue is configured or connected here, or the \
|
||||
router does not answer: it is not running, or it predates the log (problem+json)",
|
||||
body = String),
|
||||
),
|
||||
tag = "notify"
|
||||
)]
|
||||
pub(crate) async fn get_deliveries(
|
||||
State(state): State<AppState>,
|
||||
Query(query): Query<DeliveriesQuery>,
|
||||
) -> Result<Json<Deliveries>, ProblemDetails> {
|
||||
let client = queue(&state).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)
|
||||
}
|
||||
|
||||
/// The saved flows run over the newest 50 forge events, delivering nothing:
|
||||
/// how many events reached each node.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/notify/dry-run",
|
||||
responses(
|
||||
(status = 200, description = "per flow that would run, the number of the newest 50 \
|
||||
events that reached each node", body = DryRun),
|
||||
(status = 409, description = "the stored document is not one this build reads \
|
||||
(problem+json)", body = String),
|
||||
(status = 502, description = "the router refused, or its answer did not decode \
|
||||
(problem+json)", body = String),
|
||||
(status = 503, description = "no swarm queue is configured or connected here, or the \
|
||||
router does not answer: it is not running, or it predates the dry run \
|
||||
(problem+json)", body = String),
|
||||
(status = 500, description = "the saved flows could not be read (problem+json)",
|
||||
body = String),
|
||||
),
|
||||
tag = "notify"
|
||||
)]
|
||||
pub(crate) async fn get_dry_run(
|
||||
State(state): State<AppState>,
|
||||
) -> Result<Json<DryRun>, ProblemDetails> {
|
||||
let client = queue(&state).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 {
|
||||
Stored::Nothing => Document::default(),
|
||||
Stored::Document(doc) => doc,
|
||||
Stored::Unreadable(e) => return Err(unreadable(&e)),
|
||||
};
|
||||
let body = serde_json::to_vec(&DryRunRequest { document }).expect("a request encodes");
|
||||
ask(&client, DRY_RUN_SUBJECT, body).await.map(Json)
|
||||
}
|
||||
|
||||
/// The body of `POST /api/notify/dry-run`: the document of a `PUT`, whose
|
||||
/// `revision` may be present and is ignored.
|
||||
#[derive(Debug, Clone, Deserialize, ToSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct DraftFlows {
|
||||
/// Ignored.
|
||||
#[serde(default, rename = "revision")]
|
||||
_revision: u64,
|
||||
/// The ids of the built-in flows to switch off.
|
||||
#[serde(default)]
|
||||
disabled_builtins: Vec<String>,
|
||||
/// The custom flows.
|
||||
#[serde(default)]
|
||||
flows: Vec<Flow>,
|
||||
}
|
||||
|
||||
/// A draft flows document run over the newest 50 forge events, delivering and
|
||||
/// saving nothing: how many events reached each node.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/notify/dry-run",
|
||||
request_body = DraftFlows,
|
||||
responses(
|
||||
(status = 200, description = "per flow that would run, the number of the newest 50 \
|
||||
events that reached each node", body = DryRun),
|
||||
(status = 400, description = "not JSON or not this shape, or the document fails the \
|
||||
check `PUT /api/notify/flows` applies (problem+json)", body = String),
|
||||
(status = 502, description = "the router refused, or its answer did not decode \
|
||||
(problem+json)", body = String),
|
||||
(status = 503, description = "no swarm queue is configured or connected here, or the \
|
||||
router does not answer: it is not running, or it predates the dry run \
|
||||
(problem+json)", body = String),
|
||||
),
|
||||
tag = "notify"
|
||||
)]
|
||||
pub(crate) async fn post_dry_run(
|
||||
State(state): State<AppState>,
|
||||
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 body = serde_json::to_vec(&DryRunRequest { document }).expect("a request encodes");
|
||||
ask(&client, DRY_RUN_SUBJECT, body).await.map(Json)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use axum::extract::rejection::MissingJsonContentType;
|
||||
use futures_util::StreamExt as _;
|
||||
use swarm_wire::notify_flows::{self, Document};
|
||||
use swarm_wire::router_api::{FlowHits, NodeHits};
|
||||
|
||||
use super::*;
|
||||
use crate::test_nats::TestNats;
|
||||
|
||||
fn query(limit: Option<usize>) -> Query<DeliveriesQuery> {
|
||||
Query(DeliveriesQuery { limit })
|
||||
}
|
||||
|
||||
/// Answer the next request on `subject` with `reply`, handing the request
|
||||
/// body back.
|
||||
async fn answer(
|
||||
client: &async_nats::Client,
|
||||
subject: &'static str,
|
||||
reply: Vec<u8>,
|
||||
) -> tokio::task::JoinHandle<Vec<u8>> {
|
||||
let mut requests = client.subscribe(subject).await.expect("subscribed");
|
||||
client.flush().await.expect("flushed");
|
||||
let client = client.clone();
|
||||
tokio::spawn(async move {
|
||||
let m = requests.next().await.expect("a request");
|
||||
client
|
||||
.publish(m.reply.expect("a reply subject"), reply.into())
|
||||
.await
|
||||
.expect("answered");
|
||||
m.payload.to_vec()
|
||||
})
|
||||
}
|
||||
|
||||
/// A router that predates the log and the dry run has no subscriber: both
|
||||
/// answer 503 with the reason, not 500 and not a hang. The control is the
|
||||
/// same two calls with a router answering.
|
||||
#[tokio::test]
|
||||
async fn without_a_router_that_answers_both_are_unavailable() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = crate::agent_limits::tests::state(&client);
|
||||
|
||||
let deliveries = get_deliveries(State(state.clone()), query(None))
|
||||
.await
|
||||
.expect_err("nobody answers");
|
||||
assert_eq!(deliveries.status, Some(StatusCode::SERVICE_UNAVAILABLE));
|
||||
assert!(
|
||||
deliveries
|
||||
.detail
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.contains("older build"),
|
||||
"{deliveries:?}"
|
||||
);
|
||||
let dry = get_dry_run(State(state.clone()))
|
||||
.await
|
||||
.expect_err("nobody answers");
|
||||
assert_eq!(dry.status, Some(StatusCode::SERVICE_UNAVAILABLE));
|
||||
assert!(
|
||||
dry.detail
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.contains("older build"),
|
||||
"{dry:?}"
|
||||
);
|
||||
|
||||
// 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))
|
||||
.await
|
||||
.expect("answered");
|
||||
assert!(got.rows.is_empty());
|
||||
rows.await.expect("the router task");
|
||||
let hits = DryRun {
|
||||
events: 0,
|
||||
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");
|
||||
assert_eq!(got, hits);
|
||||
dry_run.await.expect("the router task");
|
||||
}
|
||||
|
||||
/// No queue on this host is 503 too.
|
||||
#[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))
|
||||
.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));
|
||||
}
|
||||
|
||||
/// The limit reaches the router, and the dry run sends the saved document.
|
||||
#[tokio::test]
|
||||
async fn the_limit_and_the_saved_document_reach_the_router() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
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)))
|
||||
.await
|
||||
.expect("answered");
|
||||
let request: DeliveriesRequest =
|
||||
serde_json::from_slice(&asked.await.expect("task")).expect("a request");
|
||||
assert_eq!(request.limit, Some(7));
|
||||
|
||||
// Nothing saved: the default document.
|
||||
let reply = DryRun {
|
||||
events: 3,
|
||||
flows: vec![FlowHits {
|
||||
flow: "assigned".to_owned(),
|
||||
nodes: vec![NodeHits {
|
||||
node: "source".to_owned(),
|
||||
hits: 3,
|
||||
}],
|
||||
}],
|
||||
};
|
||||
let asked = answer(
|
||||
&client,
|
||||
DRY_RUN_SUBJECT,
|
||||
serde_json::to_vec(&reply).unwrap(),
|
||||
)
|
||||
.await;
|
||||
let Json(got) = get_dry_run(State(state.clone())).await.expect("answered");
|
||||
assert_eq!(got, reply);
|
||||
let sent: DryRunRequest =
|
||||
serde_json::from_slice(&asked.await.expect("task")).expect("a request");
|
||||
assert_eq!(sent.document, Document::default());
|
||||
|
||||
// A saved document: the router gets that one.
|
||||
let store = open(&client).await.expect("bucket");
|
||||
let saved = Document {
|
||||
disabled_builtins: vec!["closed".to_owned()],
|
||||
..Document::default()
|
||||
};
|
||||
store
|
||||
.put(
|
||||
notify_flows::KEY,
|
||||
serde_json::to_vec(&saved).unwrap().into(),
|
||||
)
|
||||
.await
|
||||
.expect("seed");
|
||||
let asked = answer(
|
||||
&client,
|
||||
DRY_RUN_SUBJECT,
|
||||
serde_json::to_vec(&reply).unwrap(),
|
||||
)
|
||||
.await;
|
||||
let _ = get_dry_run(State(state)).await.expect("answered");
|
||||
let sent: DryRunRequest =
|
||||
serde_json::from_slice(&asked.await.expect("task")).expect("a request");
|
||||
assert_eq!(sent.document, saved);
|
||||
}
|
||||
|
||||
/// A refusal from the router is 502 with its reason; an unreadable saved
|
||||
/// document is 409 and never reaches the router.
|
||||
#[tokio::test]
|
||||
async fn a_refusal_is_502_and_an_unreadable_document_is_409() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = crate::agent_limits::tests::state(&client);
|
||||
|
||||
let router = answer(
|
||||
&client,
|
||||
DRY_RUN_SUBJECT,
|
||||
br#"{"error":"no events"}"#.to_vec(),
|
||||
)
|
||||
.await;
|
||||
let refused = get_dry_run(State(state.clone()))
|
||||
.await
|
||||
.expect_err("refused");
|
||||
assert_eq!(refused.status, Some(StatusCode::BAD_GATEWAY));
|
||||
assert!(
|
||||
refused
|
||||
.detail
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.contains("no events")
|
||||
);
|
||||
router.await.expect("the router task");
|
||||
|
||||
let store = open(&client).await.expect("bucket");
|
||||
store
|
||||
.put(
|
||||
notify_flows::KEY,
|
||||
br#"{"version":3,"flows":[]}"#.to_vec().into(),
|
||||
)
|
||||
.await
|
||||
.expect("seed");
|
||||
let unreadable = get_dry_run(State(state)).await.expect_err("version 3");
|
||||
assert_eq!(unreadable.status, Some(StatusCode::CONFLICT));
|
||||
}
|
||||
|
||||
fn draft(flows: &serde_json::Value) -> Json<DraftFlows> {
|
||||
Json(
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"revision": 7,
|
||||
"disabled_builtins": ["closed"],
|
||||
"flows": flows,
|
||||
}))
|
||||
.expect("a draft"),
|
||||
)
|
||||
}
|
||||
|
||||
fn sink_flow(id: &str) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"id": id, "name": "n", "enabled": true,
|
||||
"nodes": [
|
||||
{"id": "source", "kind": "source", "events": ["issues"]},
|
||||
{"id": "sink", "kind": "todo", "to": {"agent": "triage"}, "op": "upsert",
|
||||
"key": "k", "prefix": false, "text": "t"},
|
||||
],
|
||||
"edges": [{"from": "source", "to": "sink"}],
|
||||
})
|
||||
}
|
||||
|
||||
/// A valid draft reaches the router as the request's document, with the
|
||||
/// body's `revision` dropped, and the router's counts come back.
|
||||
#[tokio::test]
|
||||
async fn a_valid_draft_is_forwarded_and_the_counts_come_back() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = crate::agent_limits::tests::state(&client);
|
||||
let reply = DryRun {
|
||||
events: 2,
|
||||
flows: vec![FlowHits {
|
||||
flow: "mine".to_owned(),
|
||||
nodes: vec![NodeHits {
|
||||
node: "source".to_owned(),
|
||||
hits: 2,
|
||||
}],
|
||||
}],
|
||||
};
|
||||
let router = answer(
|
||||
&client,
|
||||
DRY_RUN_SUBJECT,
|
||||
serde_json::to_vec(&reply).unwrap(),
|
||||
)
|
||||
.await;
|
||||
let Json(got) = post_dry_run(
|
||||
State(state),
|
||||
Ok(draft(&serde_json::json!([sink_flow("mine")]))),
|
||||
)
|
||||
.await
|
||||
.expect("answered");
|
||||
assert_eq!(got, reply);
|
||||
let sent: DryRunRequest =
|
||||
serde_json::from_slice(&router.await.expect("task")).expect("a request");
|
||||
assert_eq!(sent.document.disabled_builtins, ["closed"]);
|
||||
assert_eq!(sent.document.flows.len(), 1);
|
||||
assert_eq!(sent.document.flows[0].id, "mine");
|
||||
}
|
||||
|
||||
/// A tree that fails the check is 400 with `PUT`'s message and never
|
||||
/// reaches the router; a body that is not a document is 400 too. The
|
||||
/// control is the valid draft above, which the same router subscription
|
||||
/// would have received.
|
||||
#[tokio::test]
|
||||
async fn an_invalid_draft_is_400_and_never_forwarded() {
|
||||
let nats = TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let state = crate::agent_limits::tests::state(&client);
|
||||
let mut requests = client.subscribe(DRY_RUN_SUBJECT).await.expect("subscribed");
|
||||
client.flush().await.expect("flushed");
|
||||
|
||||
let mut orphan = sink_flow("orphan");
|
||||
orphan["edges"] = serde_json::json!([]);
|
||||
let refused = post_dry_run(
|
||||
State(state.clone()),
|
||||
Ok(draft(&serde_json::json!([orphan]))),
|
||||
)
|
||||
.await
|
||||
.expect_err("an orphan node");
|
||||
assert_eq!(refused.status, Some(StatusCode::BAD_REQUEST));
|
||||
let put = checked_document(
|
||||
Vec::new(),
|
||||
serde_json::from_value(serde_json::json!([{
|
||||
"id": "orphan", "name": "n", "enabled": true,
|
||||
"nodes": [
|
||||
{"id": "source", "kind": "source", "events": ["issues"]},
|
||||
{"id": "sink", "kind": "todo", "to": {"agent": "triage"}, "op": "upsert",
|
||||
"key": "k", "prefix": false, "text": "t"},
|
||||
],
|
||||
"edges": [],
|
||||
}]))
|
||||
.unwrap(),
|
||||
)
|
||||
.expect_err("the same check");
|
||||
assert_eq!(
|
||||
refused.detail.as_deref(),
|
||||
Some(put.as_str()),
|
||||
"PUT's message"
|
||||
);
|
||||
|
||||
let typo: Result<Json<DraftFlows>, JsonRejection> = Err(
|
||||
JsonRejection::MissingJsonContentType(MissingJsonContentType::default()),
|
||||
);
|
||||
let refused = post_dry_run(State(state.clone()), typo)
|
||||
.await
|
||||
.expect_err("not json");
|
||||
assert_eq!(refused.status, Some(StatusCode::BAD_REQUEST));
|
||||
|
||||
// Nothing was forwarded: the next request on the subject is the
|
||||
// control's, not either refusal's.
|
||||
let control = post_dry_run(
|
||||
State(state),
|
||||
Ok(draft(&serde_json::json!([sink_flow("ok")]))),
|
||||
);
|
||||
let (sent, got) = tokio::join!(
|
||||
async {
|
||||
let m = requests.next().await.expect("the control's request");
|
||||
let sent: DryRunRequest = serde_json::from_slice(&m.payload).expect("request");
|
||||
client
|
||||
.publish(
|
||||
m.reply.expect("reply"),
|
||||
serde_json::to_vec(&DryRun {
|
||||
events: 0,
|
||||
flows: Vec::new(),
|
||||
})
|
||||
.unwrap()
|
||||
.into(),
|
||||
)
|
||||
.await
|
||||
.expect("answered");
|
||||
sent
|
||||
},
|
||||
control
|
||||
);
|
||||
assert_eq!(sent.document.flows[0].id, "ok");
|
||||
assert!(got.is_ok());
|
||||
}
|
||||
|
||||
/// With no router the draft is 503; with no queue it is 503 too.
|
||||
#[tokio::test]
|
||||
async fn a_draft_without_a_router_is_unavailable() {
|
||||
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");
|
||||
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");
|
||||
assert_eq!(b.status, Some(StatusCode::SERVICE_UNAVAILABLE));
|
||||
}
|
||||
}
|
||||
388
swarm-controller/src/review/request_reviewer.rs
Normal file
388
swarm-controller/src/review/request_reviewer.rs
Normal file
|
|
@ -0,0 +1,388 @@
|
|||
//! Requesting a review for the notification router, which holds no forge
|
||||
//! token.
|
||||
//!
|
||||
//! The router sends a [`RequestReviewer`] on
|
||||
//! `swarm_wire::router_sink::REQUEST_REVIEWER_SUBJECT` and [`spawn`]'s
|
||||
//! responder answers with an [`Outcome`] on the reply subject, having acted
|
||||
//! under the controller's token. A reviewer whose review of the PR's head
|
||||
//! already stands is skipped: requesting it again makes the forge dismiss it,
|
||||
//! approval included. What stands is [`hive_types::review`], the rule
|
||||
//! `hive-forge pr assign-reviewer` applies too.
|
||||
//!
|
||||
//! The request may be repeated (the router's event comes back after a failed
|
||||
//! step): a reviewer with a request pending is a no-op for the forge, and one
|
||||
//! who has reviewed since stands and is skipped.
|
||||
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use futures_util::StreamExt as _;
|
||||
use hive_types::review::{ReviewInfo, standing};
|
||||
use swarm_wire::router_sink::{Outcome, REQUEST_REVIEWER_SUBJECT, RequestReviewer, WORK_DEADLINE};
|
||||
|
||||
use crate::forge;
|
||||
use crate::jobq::Late;
|
||||
use crate::review_classifier::split_repo;
|
||||
use crate::routes::AppState;
|
||||
|
||||
/// How long to wait before subscribing again.
|
||||
const RETRY: Duration = Duration::from_secs(5);
|
||||
|
||||
/// The forge as the responder uses it: [`forge::Client`] in production, a fake
|
||||
/// in the tests.
|
||||
pub(crate) trait ReviewForge {
|
||||
fn reviews(
|
||||
&self,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
number: i64,
|
||||
) -> impl Future<Output = anyhow::Result<Vec<ReviewInfo>>> + Send;
|
||||
|
||||
fn request(
|
||||
&self,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
number: i64,
|
||||
reviewer: &str,
|
||||
) -> impl Future<Output = anyhow::Result<()>> + Send;
|
||||
}
|
||||
|
||||
impl ReviewForge for forge::Client {
|
||||
async fn reviews(
|
||||
&self,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
number: i64,
|
||||
) -> anyhow::Result<Vec<ReviewInfo>> {
|
||||
self.pull_reviews(owner, repo, number).await
|
||||
}
|
||||
|
||||
async fn request(
|
||||
&self,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
number: i64,
|
||||
reviewer: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
self.request_review(owner, repo, number, reviewer).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer the router's review requests for as long as the controller runs.
|
||||
pub(crate) fn spawn(state: &AppState) {
|
||||
let Some(client) = state.status.as_ref().map(|s| s.queue_client()) else {
|
||||
tracing::warn!("no swarm queue is configured on this host; review requests go unanswered");
|
||||
return;
|
||||
};
|
||||
let forge = Arc::clone(&state.forge);
|
||||
tokio::spawn(async move { follow(&client, &forge).await });
|
||||
}
|
||||
|
||||
/// Subscribe to the requests and answer each, and subscribe again if the
|
||||
/// subscription ends.
|
||||
async fn follow<F: ReviewForge>(client: &async_nats::Client, forge: &Late<Arc<F>>) {
|
||||
loop {
|
||||
match client.subscribe(REQUEST_REVIEWER_SUBJECT).await {
|
||||
Ok(mut requests) => {
|
||||
tracing::info!(
|
||||
subject = REQUEST_REVIEWER_SUBJECT,
|
||||
"request reviewer: answering requests"
|
||||
);
|
||||
while let Some(msg) = requests.next().await {
|
||||
let Some(reply) = msg.reply.clone() else {
|
||||
continue;
|
||||
};
|
||||
let outcome = answer(forge.get().map(Arc::as_ref), &msg.payload).await;
|
||||
match &outcome {
|
||||
Outcome::Error(why) => {
|
||||
tracing::warn!(%why, "request reviewer: not requested");
|
||||
}
|
||||
other => {
|
||||
tracing::info!(outcome = %other.encode(), "request reviewer: answered");
|
||||
}
|
||||
}
|
||||
if let Err(e) = client.publish(reply, outcome.encode().into()).await {
|
||||
tracing::warn!(error = %e, "request reviewer: answering failed");
|
||||
}
|
||||
}
|
||||
tracing::warn!("request reviewer: subscription ended");
|
||||
}
|
||||
Err(e) => tracing::warn!(error = %e, "request reviewer: subscribe failed"),
|
||||
}
|
||||
tokio::time::sleep(RETRY).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// What to answer to one request `payload`, `forge` being `None` while the
|
||||
/// controller has no forge access.
|
||||
async fn answer<F: ReviewForge>(forge: Option<&F>, payload: &[u8]) -> Outcome {
|
||||
let request: RequestReviewer = match serde_json::from_slice(payload) {
|
||||
Ok(request) => request,
|
||||
Err(e) => return Outcome::Error(format!("the request does not decode: {e}")),
|
||||
};
|
||||
let Some(forge) = forge else {
|
||||
return Outcome::Error("this controller has no forge access yet".to_owned());
|
||||
};
|
||||
match tokio::time::timeout(WORK_DEADLINE, act(forge, &request)).await {
|
||||
Ok(outcome) => outcome,
|
||||
Err(_) => Outcome::Error(format!(
|
||||
"the forge did not answer within {}s",
|
||||
WORK_DEADLINE.as_secs()
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn act<F: ReviewForge>(forge: &F, request: &RequestReviewer) -> Outcome {
|
||||
let RequestReviewer {
|
||||
repo,
|
||||
number,
|
||||
reviewer,
|
||||
} = request;
|
||||
let (owner, name) = match split_repo(repo) {
|
||||
Ok(split) => split,
|
||||
Err(why) => return Outcome::Error(why),
|
||||
};
|
||||
let Ok(number_i64) = i64::try_from(*number) else {
|
||||
return Outcome::Error(format!("PR number {number} is out of range"));
|
||||
};
|
||||
if reviewer.trim().is_empty() {
|
||||
return Outcome::Error("no reviewer named".to_owned());
|
||||
}
|
||||
let reviews = match forge.reviews(owner, name, number_i64).await {
|
||||
Ok(reviews) => reviews,
|
||||
Err(e) => return Outcome::Error(format!("{e:#}")),
|
||||
};
|
||||
if let Some(review) = standing(&reviews, reviewer) {
|
||||
return Outcome::Skipped(format!(
|
||||
"{reviewer} already has a standing {} review on {repo}#{number}",
|
||||
review.state
|
||||
));
|
||||
}
|
||||
match forge.request(owner, name, number_i64, reviewer).await {
|
||||
Ok(()) => Outcome::Requested,
|
||||
Err(e) => Outcome::Error(format!("{e:#}")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Mutex;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Fake {
|
||||
reviews: Vec<ReviewInfo>,
|
||||
reviews_fail: bool,
|
||||
request_fail: bool,
|
||||
asked: Mutex<Vec<(String, i64, String)>>,
|
||||
}
|
||||
|
||||
impl ReviewForge for Fake {
|
||||
async fn reviews(&self, _: &str, _: &str, _: i64) -> anyhow::Result<Vec<ReviewInfo>> {
|
||||
if self.reviews_fail {
|
||||
anyhow::bail!("the forge is down");
|
||||
}
|
||||
Ok(self.reviews.clone())
|
||||
}
|
||||
|
||||
async fn request(
|
||||
&self,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
number: i64,
|
||||
reviewer: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
if self.request_fail {
|
||||
anyhow::bail!("422: the reviewer is the PR's author");
|
||||
}
|
||||
self.asked.lock().unwrap().push((
|
||||
format!("{owner}/{repo}"),
|
||||
number,
|
||||
reviewer.to_owned(),
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn review(login: &str, verdict: &str, stale: bool, dismissed: bool) -> ReviewInfo {
|
||||
ReviewInfo {
|
||||
login: login.to_owned(),
|
||||
state: verdict.to_owned(),
|
||||
stale,
|
||||
dismissed,
|
||||
}
|
||||
}
|
||||
|
||||
fn payload(repo: &str, number: u64, reviewer: &str) -> Vec<u8> {
|
||||
serde_json::to_vec(&RequestReviewer {
|
||||
repo: repo.to_owned(),
|
||||
number,
|
||||
reviewer: reviewer.to_owned(),
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn asked(fake: &Fake) -> Vec<(String, i64, String)> {
|
||||
fake.asked.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_reviewer_with_no_review_is_requested() {
|
||||
let fake = Fake::default();
|
||||
let got = answer(Some(&fake), &payload("o/r", 7, "review-classifier")).await;
|
||||
assert_eq!(got, Outcome::Requested);
|
||||
assert_eq!(
|
||||
asked(&fake),
|
||||
[("o/r".to_owned(), 7, "review-classifier".to_owned())]
|
||||
);
|
||||
}
|
||||
|
||||
/// A review that still stands is skipped, because requesting from its
|
||||
/// reviewer would make the forge dismiss it.
|
||||
#[tokio::test]
|
||||
async fn a_standing_review_is_skipped_and_a_stale_or_dismissed_one_is_requested_again() {
|
||||
let reviewer = "review-classifier";
|
||||
let standing = Fake {
|
||||
reviews: vec![review(reviewer, "APPROVED", false, false)],
|
||||
..Fake::default()
|
||||
};
|
||||
let got = answer(Some(&standing), &payload("o/r", 7, reviewer)).await;
|
||||
assert!(
|
||||
matches!(&got, Outcome::Skipped(why) if why.contains("APPROVED") && why.contains("o/r#7")),
|
||||
"{got:?}"
|
||||
);
|
||||
assert!(asked(&standing).is_empty(), "nothing was requested");
|
||||
|
||||
for (stale, dismissed) in [(true, false), (false, true)] {
|
||||
let fake = Fake {
|
||||
reviews: vec![review(reviewer, "APPROVED", stale, dismissed)],
|
||||
..Fake::default()
|
||||
};
|
||||
let got = answer(Some(&fake), &payload("o/r", 7, reviewer)).await;
|
||||
assert_eq!(
|
||||
got,
|
||||
Outcome::Requested,
|
||||
"stale {stale}, dismissed {dismissed}"
|
||||
);
|
||||
assert_eq!(asked(&fake).len(), 1);
|
||||
}
|
||||
|
||||
// Another reviewer's standing review is no reason to skip this one.
|
||||
let other = Fake {
|
||||
reviews: vec![review("argus", "APPROVED", false, false)],
|
||||
..Fake::default()
|
||||
};
|
||||
let got = answer(Some(&other), &payload("o/r", 7, reviewer)).await;
|
||||
assert_eq!(got, Outcome::Requested);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_forge_failure_is_an_error_and_a_failed_read_requests_nothing() {
|
||||
let down = Fake {
|
||||
reviews_fail: true,
|
||||
..Fake::default()
|
||||
};
|
||||
let got = answer(Some(&down), &payload("o/r", 7, "review-classifier")).await;
|
||||
assert!(
|
||||
matches!(&got, Outcome::Error(e) if e.contains("the forge is down")),
|
||||
"{got:?}"
|
||||
);
|
||||
assert!(asked(&down).is_empty());
|
||||
|
||||
let refused = Fake {
|
||||
request_fail: true,
|
||||
..Fake::default()
|
||||
};
|
||||
let got = answer(Some(&refused), &payload("o/r", 7, "review-classifier")).await;
|
||||
assert!(
|
||||
matches!(&got, Outcome::Error(e) if e.contains("422")),
|
||||
"{got:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_request_that_is_malformed_or_has_no_forge_is_an_error() {
|
||||
let fake = Fake::default();
|
||||
for bad in [
|
||||
b"not json".to_vec(),
|
||||
payload("no-slash", 7, "review-classifier"),
|
||||
payload("o/r", 7, " "),
|
||||
payload("o/r", u64::MAX, "review-classifier"),
|
||||
] {
|
||||
let got = answer(Some(&fake), &bad).await;
|
||||
assert!(
|
||||
matches!(got, Outcome::Error(_)),
|
||||
"{:?}",
|
||||
String::from_utf8_lossy(&bad)
|
||||
);
|
||||
}
|
||||
assert!(asked(&fake).is_empty());
|
||||
let none: Option<&Fake> = None;
|
||||
let got = answer(none, &payload("o/r", 7, "review-classifier")).await;
|
||||
assert!(
|
||||
matches!(&got, Outcome::Error(e) if e.contains("no forge")),
|
||||
"{got:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The built-in flow's reviewer is the account the controller makes.
|
||||
#[test]
|
||||
fn the_built_in_flow_requests_the_classifiers_account() {
|
||||
assert_eq!(
|
||||
swarm_wire::notify_flows::CLASSIFIER_ACCOUNT,
|
||||
forge::classifier_account::LOGIN
|
||||
);
|
||||
}
|
||||
|
||||
/// Against a real server: a request sent the way the router sends it comes
|
||||
/// back with the outcome, and a subscriber before the controller is up
|
||||
/// leaves the sender with no responders.
|
||||
#[tokio::test]
|
||||
async fn a_request_over_the_queue_is_answered_with_its_outcome() {
|
||||
let nats = crate::test_nats::TestNats::start();
|
||||
let router = nats.client().await;
|
||||
let ask = |body: Vec<u8>| {
|
||||
let router = router.clone();
|
||||
async move {
|
||||
let sent = async_nats::Request::new()
|
||||
.payload(body.into())
|
||||
.timeout(Some(Duration::from_secs(5)));
|
||||
router.send_request(REQUEST_REVIEWER_SUBJECT, sent).await
|
||||
}
|
||||
};
|
||||
assert!(
|
||||
ask(payload("o/r", 7, "review-classifier")).await.is_err(),
|
||||
"no controller listening"
|
||||
);
|
||||
|
||||
let fake = Arc::new(Fake {
|
||||
reviews: vec![review("argus", "APPROVED", false, false)],
|
||||
..Fake::default()
|
||||
});
|
||||
let late: Late<Arc<Fake>> = Arc::default();
|
||||
late.set(Arc::clone(&fake)).ok().unwrap();
|
||||
let controller = nats.client().await;
|
||||
tokio::spawn(async move { follow(&controller, &late).await });
|
||||
// The subscription is processed once a request gets through.
|
||||
let mut reply = None;
|
||||
for _ in 0..50 {
|
||||
if let Ok(msg) = ask(payload("o/r", 7, "review-classifier")).await {
|
||||
reply = Some(msg);
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
let reply = reply.expect("the controller answers");
|
||||
assert_eq!(
|
||||
Outcome::decode(&String::from_utf8_lossy(&reply.payload)),
|
||||
Outcome::Requested
|
||||
);
|
||||
let skipped = ask(payload("o/r", 7, "argus")).await.unwrap();
|
||||
assert!(matches!(
|
||||
Outcome::decode(&String::from_utf8_lossy(&skipped.payload)),
|
||||
Outcome::Skipped(_)
|
||||
));
|
||||
}
|
||||
}
|
||||
1620
swarm-controller/src/review/review_classifier.rs
Normal file
1620
swarm-controller/src/review/review_classifier.rs
Normal file
File diff suppressed because it is too large
Load diff
323
swarm-controller/src/review/review_classifier/keys.rs
Normal file
323
swarm-controller/src/review/review_classifier/keys.rs
Normal file
|
|
@ -0,0 +1,323 @@
|
|||
//! `GET /api/review-classifier/keys` and `PUT /api/review-classifier/keys/{runtime}`:
|
||||
//! the keys the classifier's two runtimes run on, written from the swarm UI
|
||||
//! instead of by hand in the secret store's UI.
|
||||
//!
|
||||
//! The controller only writes. Its store policy holds `create` and `update`
|
||||
//! on the two leaves and no `read` of their values, so no route here answers a
|
||||
//! key, and the one metadata read tells whether a key is set and when it last
|
||||
//! changed. The classifier reads the key from the same leaf on every run, so
|
||||
//! a new key applies from the next run with no restart.
|
||||
|
||||
use std::future::Future;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::rejection::JsonRejection;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use problem_details::ProblemDetails;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use swarm_secret_client::{
|
||||
SecretStore,
|
||||
acp::ProviderKey,
|
||||
review_classifier::{ApiKey, acp_provider_key_path, api_key_path},
|
||||
};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::routes::{AppState, error_problem};
|
||||
|
||||
/// The most bytes a key may have. Provider keys run to a few hundred.
|
||||
const MAX_KEY_BYTES: usize = 4096;
|
||||
|
||||
/// Which runtime a key is for, as the path spells it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Which {
|
||||
/// The Anthropic API key the `api-key` runtime runs `claude` with.
|
||||
ApiKey,
|
||||
/// The provider key the `acp` runtime runs its agent with.
|
||||
Acp,
|
||||
}
|
||||
|
||||
impl Which {
|
||||
fn parse(s: &str) -> Option<Self> {
|
||||
match s {
|
||||
"api-key" => Some(Self::ApiKey),
|
||||
"acp" => Some(Self::Acp),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn path(self) -> Result<String, swarm_secret_client::Error> {
|
||||
match self {
|
||||
Self::ApiKey => api_key_path(),
|
||||
Self::Acp => acp_provider_key_path(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether one key is stored. Never the key.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, ToSchema)]
|
||||
pub(crate) struct KeyState {
|
||||
/// A key is stored.
|
||||
set: bool,
|
||||
/// When the key last changed, as the store spells it (RFC 3339), or
|
||||
/// `null` when none is stored.
|
||||
updated: Option<String>,
|
||||
}
|
||||
|
||||
/// Both keys' state, what both routes answer.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, ToSchema)]
|
||||
pub(crate) struct Keys {
|
||||
/// The Anthropic API key of the `api-key` runtime.
|
||||
api_key: KeyState,
|
||||
/// The provider key of the `acp` runtime.
|
||||
acp: KeyState,
|
||||
}
|
||||
|
||||
/// The body of a `PUT`: the key.
|
||||
#[derive(Deserialize, ToSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct KeyBody {
|
||||
/// The key. Surrounding whitespace is dropped, so a pasted trailing
|
||||
/// newline is harmless.
|
||||
api_key: String,
|
||||
}
|
||||
|
||||
/// The two store calls a route makes, so a test can stand in for the store.
|
||||
trait KeyStore {
|
||||
/// Store `key` at `path`, replacing what's there.
|
||||
fn put(&self, which: Which, key: &str) -> impl Future<Output = Result<(), String>> + Send;
|
||||
|
||||
/// When the leaf last changed, or `None` when nothing is stored.
|
||||
fn updated(&self, which: Which) -> impl Future<Output = Result<Option<String>, String>> + Send;
|
||||
}
|
||||
|
||||
impl KeyStore for SecretStore {
|
||||
async fn put(&self, which: Which, key: &str) -> Result<(), String> {
|
||||
let path = which.path().map_err(|e| e.to_string())?;
|
||||
let result = match which {
|
||||
Which::ApiKey => {
|
||||
self.write(
|
||||
&path,
|
||||
&ApiKey {
|
||||
api_key: key.to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
Which::Acp => {
|
||||
self.write(
|
||||
&path,
|
||||
&ProviderKey {
|
||||
api_key: key.to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
};
|
||||
result.map_err(|e| format!("writing {path}: {e}"))
|
||||
}
|
||||
|
||||
async fn updated(&self, which: Which) -> Result<Option<String>, String> {
|
||||
let path = which.path().map_err(|e| e.to_string())?;
|
||||
self.updated_time(&path)
|
||||
.await
|
||||
.map_err(|e| format!("reading {path}'s metadata: {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// A key to store, or why it's refused.
|
||||
fn check(key: &str) -> Result<&str, String> {
|
||||
let key = key.trim();
|
||||
if key.is_empty() {
|
||||
return Err("the key is empty".to_owned());
|
||||
}
|
||||
if key.len() > MAX_KEY_BYTES {
|
||||
return Err(format!("the key is over {MAX_KEY_BYTES} bytes"));
|
||||
}
|
||||
if key.chars().any(|c| c.is_whitespace() || c.is_control()) {
|
||||
return Err("the key holds whitespace or a control character".to_owned());
|
||||
}
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
async fn state_of(store: &impl KeyStore, which: Which) -> Result<KeyState, String> {
|
||||
let updated = store.updated(which).await?;
|
||||
Ok(KeyState {
|
||||
set: updated.is_some(),
|
||||
updated,
|
||||
})
|
||||
}
|
||||
|
||||
async fn both(store: &impl KeyStore) -> Result<Keys, String> {
|
||||
Ok(Keys {
|
||||
api_key: state_of(store, Which::ApiKey).await?,
|
||||
acp: state_of(store, Which::Acp).await?,
|
||||
})
|
||||
}
|
||||
|
||||
fn store_problem(why: &str) -> ProblemDetails {
|
||||
tracing::warn!(error = %why, "review classifier keys: store failure");
|
||||
error_problem(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
&format!("the secret store refused: {why}"),
|
||||
)
|
||||
}
|
||||
|
||||
async fn connect() -> Result<SecretStore, ProblemDetails> {
|
||||
crate::store::connect()
|
||||
.await
|
||||
.map_err(|e| store_problem(&format!("logging in: {e}")))
|
||||
}
|
||||
|
||||
/// Whether each runtime's key is stored.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/review-classifier/keys",
|
||||
responses(
|
||||
(status = 200, description = "whether each key is stored and when it last changed; \
|
||||
never a key", body = Keys),
|
||||
(status = 503, description = "the secret store couldn't be reached, or refused \
|
||||
(problem+json)", body = String),
|
||||
),
|
||||
tag = "review-classifier"
|
||||
)]
|
||||
pub(crate) async fn get_keys(State(_state): State<AppState>) -> Result<Json<Keys>, ProblemDetails> {
|
||||
let store = connect().await?;
|
||||
both(&store).await.map(Json).map_err(|e| store_problem(&e))
|
||||
}
|
||||
|
||||
/// Store a runtime's key.
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/api/review-classifier/keys/{runtime}",
|
||||
params(("runtime" = String, Path, description = "`api-key` or `acp`")),
|
||||
request_body = KeyBody,
|
||||
responses(
|
||||
(status = 200, description = "both keys' state after the write; never a key",
|
||||
body = Keys),
|
||||
(status = 400, description = "not JSON or not this shape, a runtime other than \
|
||||
`api-key` or `acp`, or a key that is empty, over 4096 bytes or holds \
|
||||
whitespace (problem+json)", body = String),
|
||||
(status = 401, description = "the request carries no `Remote-User`, so there is \
|
||||
no operator to name (problem+json)", body = String),
|
||||
(status = 503, description = "the secret store couldn't be reached, or refused \
|
||||
(problem+json)", body = String),
|
||||
),
|
||||
tag = "review-classifier"
|
||||
)]
|
||||
pub(crate) async fn put_key(
|
||||
State(_state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
Path(runtime): Path<String>,
|
||||
body: Result<Json<KeyBody>, JsonRejection>,
|
||||
) -> Result<Json<Keys>, ProblemDetails> {
|
||||
let operator = super::operator(&headers).ok_or_else(|| {
|
||||
error_problem(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"no Remote-User header: the gateway names the operator, and this request did not \
|
||||
come through it",
|
||||
)
|
||||
})?;
|
||||
let which = Which::parse(&runtime).ok_or_else(|| {
|
||||
error_problem(
|
||||
StatusCode::BAD_REQUEST,
|
||||
&format!("{runtime:?} is not a runtime with a key: use `api-key` or `acp`"),
|
||||
)
|
||||
})?;
|
||||
let Json(body) = body.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.body_text()))?;
|
||||
let key = check(&body.api_key).map_err(|why| error_problem(StatusCode::BAD_REQUEST, &why))?;
|
||||
let store = connect().await?;
|
||||
store.put(which, key).await.map_err(|e| store_problem(&e))?;
|
||||
// The key itself is never logged.
|
||||
tracing::info!(%operator, ?which, "set a review classifier key");
|
||||
both(&store).await.map(Json).map_err(|e| store_problem(&e))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Mutex;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A store holding what was put, with a leaf's time when it has a key.
|
||||
#[derive(Default)]
|
||||
struct Fake {
|
||||
put: Mutex<Vec<(Which, String)>>,
|
||||
refuse: bool,
|
||||
}
|
||||
|
||||
impl KeyStore for Fake {
|
||||
async fn put(&self, which: Which, key: &str) -> Result<(), String> {
|
||||
if self.refuse {
|
||||
return Err("denied".to_owned());
|
||||
}
|
||||
self.put.lock().unwrap().push((which, key.to_owned()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn updated(&self, which: Which) -> Result<Option<String>, String> {
|
||||
if self.refuse {
|
||||
return Err("denied".to_owned());
|
||||
}
|
||||
let put = self.put.lock().unwrap();
|
||||
Ok(put
|
||||
.iter()
|
||||
.any(|(w, _)| *w == which)
|
||||
.then(|| "2026-11-11T10:00:00Z".to_owned()))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_runtime_is_one_of_two_words() {
|
||||
assert_eq!(Which::parse("api-key"), Some(Which::ApiKey));
|
||||
assert_eq!(Which::parse("acp"), Some(Which::Acp));
|
||||
assert_eq!(Which::parse("api_key"), None);
|
||||
assert_eq!(Which::parse(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_leaves_are_the_ones_the_policy_grants() {
|
||||
assert_eq!(
|
||||
Which::ApiKey.path().unwrap(),
|
||||
"swarm/services/review-classifier/anthropic-api-key"
|
||||
);
|
||||
assert_eq!(
|
||||
Which::Acp.path().unwrap(),
|
||||
"swarm/services/review-classifier/acp-provider"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_newline_is_dropped_and_a_bad_key_refused() {
|
||||
assert_eq!(check("sk-ant-x\n"), Ok("sk-ant-x"));
|
||||
assert!(check(" ").is_err());
|
||||
assert!(check("two words").is_err());
|
||||
assert!(check("a\u{0}b").is_err());
|
||||
assert!(check(&"k".repeat(MAX_KEY_BYTES + 1)).is_err());
|
||||
assert!(check(&"k".repeat(MAX_KEY_BYTES)).is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_state_says_set_once_a_key_is_stored_and_never_holds_it() {
|
||||
let store = Fake::default();
|
||||
let before = both(&store).await.unwrap();
|
||||
assert!(!before.api_key.set && !before.acp.set);
|
||||
assert_eq!(before.api_key.updated, None);
|
||||
|
||||
store.put(Which::ApiKey, "sk-secret").await.unwrap();
|
||||
let after = both(&store).await.unwrap();
|
||||
assert!(after.api_key.set && !after.acp.set);
|
||||
assert!(after.api_key.updated.is_some());
|
||||
let json = serde_json::to_string(&after).unwrap();
|
||||
assert!(!json.contains("sk-secret"), "{json}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_refusing_store_is_an_error_not_unset() {
|
||||
let store = Fake {
|
||||
refuse: true,
|
||||
..Fake::default()
|
||||
};
|
||||
assert!(both(&store).await.is_err());
|
||||
}
|
||||
}
|
||||
289
swarm-controller/src/review/review_classifier/metrics.rs
Normal file
289
swarm-controller/src/review/review_classifier/metrics.rs
Normal file
|
|
@ -0,0 +1,289 @@
|
|||
//! OTEL export of what review requests and review runs come to: the counters
|
||||
//! `hyperhive.review_classifier.requests` (`outcome`), `.verdicts` (`outcome`)
|
||||
//! and `.checks` (`check`, `result`), and the histogram
|
||||
//! `hyperhive.review_classifier.run.duration` in seconds (`outcome`). The
|
||||
//! classifier service exports the retries beside its cost counters, see
|
||||
//! `swarm-review-classifier`'s `cost` module.
|
||||
//!
|
||||
//! Same exporter as [`crate::vcs_metrics`], built on the first record; with no
|
||||
//! `OTEL_EXPORTER_OTLP_ENDPOINT` every record does nothing.
|
||||
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use opentelemetry::KeyValue;
|
||||
use opentelemetry::metrics::{Counter, Histogram, MeterProvider as _};
|
||||
use opentelemetry_sdk::metrics::SdkMeterProvider;
|
||||
use swarm_wire::review_classifier::{Row, Verdict as RowVerdict};
|
||||
|
||||
use super::runs::RunOutcome;
|
||||
|
||||
/// What became of a review request.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) enum Request {
|
||||
/// Stored in the request queue.
|
||||
Queued,
|
||||
/// The queue did not store it; a no-verdict comment was posted.
|
||||
QueueFailed,
|
||||
/// Taken from the queue but unreadable, and dropped.
|
||||
Unparsable,
|
||||
/// Taken while the PR's review was going; put back in the queue.
|
||||
Deferred,
|
||||
/// Taken, and a fresh run began.
|
||||
Started,
|
||||
/// Taken for a head already reviewed; its verdict was posted again.
|
||||
Reposted,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
const fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Queued => "queued",
|
||||
Self::QueueFailed => "queue_failed",
|
||||
Self::Unparsable => "unparsable",
|
||||
Self::Deferred => "deferred",
|
||||
Self::Started => "started",
|
||||
Self::Reposted => "reposted",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The review event a run chose.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) enum Choice {
|
||||
Approve,
|
||||
RequestChanges,
|
||||
NoVerdict,
|
||||
}
|
||||
|
||||
impl Choice {
|
||||
const fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Approve => "approve",
|
||||
Self::RequestChanges => "request_changes",
|
||||
Self::NoVerdict => "no_verdict",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A run's `outcome` label: the verdict names, plus `post_failed`.
|
||||
const fn run_label(outcome: RunOutcome) -> &'static str {
|
||||
match outcome {
|
||||
RunOutcome::Approved => "approve",
|
||||
RunOutcome::ChangesRequested => "request_changes",
|
||||
RunOutcome::NoVerdict => "no_verdict",
|
||||
RunOutcome::PostFailed => "post_failed",
|
||||
RunOutcome::QueueFull => "queue_full",
|
||||
RunOutcome::Done => "done",
|
||||
RunOutcome::Failed => "failed",
|
||||
}
|
||||
}
|
||||
|
||||
/// A row's `result` label.
|
||||
const fn check_result(row: &Row) -> &'static str {
|
||||
match (row.error.is_some(), row.verdict) {
|
||||
(true, _) => "no_answer",
|
||||
(false, RowVerdict::Match) => "match",
|
||||
(false, RowVerdict::NoMatch) => "no_match",
|
||||
(false, RowVerdict::NotApplicable) => "unsure",
|
||||
}
|
||||
}
|
||||
|
||||
/// Seconds. A run is one model call per classification plus the forge reads
|
||||
/// and the post.
|
||||
const DURATION_BOUNDARIES: [f64; 12] = [
|
||||
1.0, 2.0, 5.0, 10.0, 20.0, 30.0, 60.0, 90.0, 120.0, 180.0, 300.0, 600.0,
|
||||
];
|
||||
|
||||
struct Instruments {
|
||||
/// Exports only while it lives.
|
||||
_provider: SdkMeterProvider,
|
||||
requests: Counter<u64>,
|
||||
verdicts: Counter<u64>,
|
||||
checks: Counter<u64>,
|
||||
duration: Histogram<f64>,
|
||||
}
|
||||
|
||||
impl Instruments {
|
||||
fn new(provider: &SdkMeterProvider) -> Self {
|
||||
let meter = provider.meter("hyperhive.review_classifier");
|
||||
Self {
|
||||
_provider: provider.clone(),
|
||||
requests: meter
|
||||
.u64_counter("hyperhive.review_classifier.requests")
|
||||
.build(),
|
||||
verdicts: meter
|
||||
.u64_counter("hyperhive.review_classifier.verdicts")
|
||||
.build(),
|
||||
checks: meter
|
||||
.u64_counter("hyperhive.review_classifier.checks")
|
||||
.build(),
|
||||
duration: meter
|
||||
.f64_histogram("hyperhive.review_classifier.run.duration")
|
||||
.with_unit("s")
|
||||
.with_boundaries(DURATION_BOUNDARIES.to_vec())
|
||||
.build(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The recorder: a handle on the instruments, or on nothing where no
|
||||
/// collector is configured.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Metrics(Option<Arc<Instruments>>);
|
||||
|
||||
static GLOBAL: OnceLock<Option<Arc<Instruments>>> = OnceLock::new();
|
||||
|
||||
impl Metrics {
|
||||
/// The process's recorder, building its exporter on the first call.
|
||||
pub(crate) fn global() -> Self {
|
||||
Self(GLOBAL.get_or_init(|| build().map(Arc::new)).clone())
|
||||
}
|
||||
|
||||
/// Records nothing.
|
||||
#[cfg(test)]
|
||||
pub(super) const fn off() -> Self {
|
||||
Self(None)
|
||||
}
|
||||
|
||||
/// Instruments on `provider`.
|
||||
#[cfg(test)]
|
||||
pub(super) fn on(provider: &SdkMeterProvider) -> Self {
|
||||
Self(Some(Arc::new(Instruments::new(provider))))
|
||||
}
|
||||
|
||||
pub(super) fn request(&self, request: Request) {
|
||||
if let Some(inst) = &self.0 {
|
||||
inst.requests
|
||||
.add(1, &[KeyValue::new("outcome", request.label())]);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn verdict(&self, choice: Choice) {
|
||||
if let Some(inst) = &self.0 {
|
||||
inst.verdicts
|
||||
.add(1, &[KeyValue::new("outcome", choice.label())]);
|
||||
}
|
||||
}
|
||||
|
||||
/// One count per classification the run answered or failed to.
|
||||
pub(super) fn checks(&self, rows: &[Row]) {
|
||||
let Some(inst) = &self.0 else { return };
|
||||
for row in rows {
|
||||
inst.checks.add(
|
||||
1,
|
||||
&[
|
||||
KeyValue::new("check", row.name.clone()),
|
||||
KeyValue::new("result", check_result(row)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn run_duration(&self, outcome: RunOutcome, seconds: f64) {
|
||||
if let Some(inst) = &self.0 {
|
||||
inst.duration
|
||||
.record(seconds, &[KeyValue::new("outcome", run_label(outcome))]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn build() -> Option<Instruments> {
|
||||
let endpoint = crate::vcs_metrics::endpoint()?;
|
||||
let interval = crate::vcs_metrics::EXPORT_INTERVAL;
|
||||
match crate::vcs_metrics::build_provider(interval) {
|
||||
Ok(provider) => {
|
||||
tracing::info!(%endpoint, ?interval, "otel review-classifier metrics: exporter enabled");
|
||||
Some(Instruments::new(&provider))
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = ?e, "otel review-classifier metrics: exporter init failed");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) mod testing {
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use opentelemetry_sdk::metrics::data::{
|
||||
AggregatedMetrics, MetricData, ResourceMetrics, ScopeMetrics,
|
||||
};
|
||||
use opentelemetry_sdk::metrics::{InMemoryMetricExporter, PeriodicReader};
|
||||
|
||||
use super::{Metrics, SdkMeterProvider};
|
||||
|
||||
/// Instruments on a provider that exports to memory.
|
||||
pub(in crate::review::review_classifier) struct Recorder {
|
||||
pub(in crate::review::review_classifier) metrics: Metrics,
|
||||
provider: SdkMeterProvider,
|
||||
exporter: InMemoryMetricExporter,
|
||||
}
|
||||
|
||||
impl Recorder {
|
||||
pub(in crate::review::review_classifier) fn new() -> Self {
|
||||
let exporter = InMemoryMetricExporter::default();
|
||||
let reader = PeriodicReader::builder(exporter.clone()).build();
|
||||
let provider = SdkMeterProvider::builder().with_reader(reader).build();
|
||||
Self {
|
||||
metrics: Metrics::on(&provider),
|
||||
provider,
|
||||
exporter,
|
||||
}
|
||||
}
|
||||
|
||||
/// `read` of the newest export of the metric `name`.
|
||||
fn export<R>(&self, name: &str, read: impl FnOnce(&AggregatedMetrics) -> R) -> Option<R> {
|
||||
self.provider.force_flush().expect("flush");
|
||||
let all = self.exporter.get_finished_metrics().expect("metrics");
|
||||
all.last()
|
||||
.into_iter()
|
||||
.flat_map(ResourceMetrics::scope_metrics)
|
||||
.flat_map(ScopeMetrics::metrics)
|
||||
.find(|m| m.name() == name)
|
||||
.map(|m| read(m.data()))
|
||||
}
|
||||
|
||||
/// The counter `name`'s value per label set, each set as
|
||||
/// `key=value,key=value` in key order. Empty when nothing was added.
|
||||
pub(in crate::review::review_classifier) fn counter(
|
||||
&self,
|
||||
name: &str,
|
||||
) -> BTreeMap<String, u64> {
|
||||
self.export(name, |data| {
|
||||
let AggregatedMetrics::U64(MetricData::Sum(sum)) = data else {
|
||||
panic!("not a u64 sum: {data:?}");
|
||||
};
|
||||
sum.data_points()
|
||||
.map(|p| (labels(p.attributes()), p.value()))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The histogram `name`'s sample count per label set, as
|
||||
/// [`Self::counter`] writes them.
|
||||
pub(in crate::review::review_classifier) fn histogram(
|
||||
&self,
|
||||
name: &str,
|
||||
) -> BTreeMap<String, u64> {
|
||||
self.export(name, |data| {
|
||||
let AggregatedMetrics::F64(MetricData::Histogram(h)) = data else {
|
||||
panic!("not an f64 histogram: {data:?}");
|
||||
};
|
||||
h.data_points()
|
||||
.map(|p| (labels(p.attributes()), p.count()))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
fn labels<'a>(attributes: impl Iterator<Item = &'a opentelemetry::KeyValue>) -> String {
|
||||
let mut all: Vec<String> = attributes
|
||||
.map(|kv| format!("{}={}", kv.key, kv.value))
|
||||
.collect();
|
||||
all.sort();
|
||||
all.join(",")
|
||||
}
|
||||
}
|
||||
843
swarm-controller/src/review/review_classifier/open_pr.rs
Normal file
843
swarm-controller/src/review/review_classifier/open_pr.rs
Normal file
|
|
@ -0,0 +1,843 @@
|
|||
//! `POST /api/review-classifier/open-pr`: put classifications written on the
|
||||
//! try-out page on a new branch of the repo, for the operator to open a PR
|
||||
//! from.
|
||||
//!
|
||||
//! The classifications are merged by trimmed name into the rules file on the
|
||||
//! repo's default branch: one with a name the file holds replaces that entry,
|
||||
//! one with a new name goes at the end, and every other entry stays. A repo
|
||||
//! with no rules file gets `.hyperhive/review-classifier.yml`. In a YAML file,
|
||||
//! the entries the merge leaves alone keep their text, comments included.
|
||||
//!
|
||||
//! The commit is made by the classifier's forge account
|
||||
//! ([`LOGIN`]) with its own token, on a branch of the repo itself, so that
|
||||
//! account needs write access to the repo. Its author is the operator: the
|
||||
//! `Remote-User` the gateway sets names the forge account of the same login,
|
||||
//! since a forge account made by an SSO login is named after the SSO user.
|
||||
//! The answer links to the forge's compare page for the branch, where the
|
||||
//! operator opens the PR as themselves.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::future::Future;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::extract::rejection::JsonRejection;
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use forgejo_api::{ApiErrorKind, ForgejoError};
|
||||
use problem_details::ProblemDetails;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use swarm_wire::review_classifier::{CLASSIFICATION_LIMITS, Classification, Polarity};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use super::{FileSource, RULES_PATHS, check_classifications, operator, parse_rules, split_repo};
|
||||
use crate::forge::classifier_account::{BranchCommit, CommitAuthor, LOGIN};
|
||||
use crate::forge::{self, BranchFile};
|
||||
use crate::routes::{AppState, error_problem};
|
||||
|
||||
/// Where a branch's name starts, so the forge's branch list groups them.
|
||||
const BRANCH_PREFIX: &str = "review-classifier/";
|
||||
|
||||
/// The longest a line of a folded YAML description gets, indent included.
|
||||
const YAML_WIDTH: usize = 78;
|
||||
|
||||
/// Classifications to propose to a repo.
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
pub(crate) struct OpenPrRequest {
|
||||
/// `owner/name`.
|
||||
repo: String,
|
||||
/// One to ten, each with a distinct name.
|
||||
classifications: Vec<Classification>,
|
||||
}
|
||||
|
||||
/// The branch the commit went on.
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub(crate) struct OpenPrBranch {
|
||||
branch: String,
|
||||
/// The rules file the commit wrote.
|
||||
path: String,
|
||||
/// The forge's page comparing `branch` with the default branch, where
|
||||
/// the PR is opened.
|
||||
compare_url: String,
|
||||
}
|
||||
|
||||
/// Where the commit is made: the forge in production, a fake in the tests.
|
||||
pub(crate) trait BranchSink {
|
||||
/// The forge account `login` as a commit author, or `None` when the
|
||||
/// forge has none.
|
||||
fn commit_author(
|
||||
&self,
|
||||
login: &str,
|
||||
) -> impl Future<Output = anyhow::Result<Option<CommitAuthor>>> + Send;
|
||||
|
||||
fn push(
|
||||
&self,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
commit: BranchCommit,
|
||||
) -> impl Future<Output = anyhow::Result<()>> + Send;
|
||||
}
|
||||
|
||||
impl BranchSink for forge::Client {
|
||||
async fn commit_author(&self, login: &str) -> anyhow::Result<Option<CommitAuthor>> {
|
||||
forge::Client::commit_author(self, login).await
|
||||
}
|
||||
|
||||
async fn push(&self, owner: &str, repo: &str, commit: BranchCommit) -> anyhow::Result<()> {
|
||||
self.push_classifier_branch(owner, repo, commit).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Put classifications on a new branch, authored by the operator.
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/api/review-classifier/open-pr",
|
||||
request_body = OpenPrRequest,
|
||||
responses(
|
||||
(status = 201, description = "the branch is on the forge; open the PR at \
|
||||
`compare_url`", body = OpenPrBranch),
|
||||
(status = 400, description = "the body is not this shape, or fails a check the \
|
||||
try-out POST makes on its repo or classifications (problem+json)", body = String),
|
||||
(status = 401, description = "the request carries no `Remote-User`, so there is no \
|
||||
author (problem+json)", body = String),
|
||||
(status = 403, description = "the forge refused the classifier's account the push: \
|
||||
it is not a collaborator with write access on the repo (problem+json)",
|
||||
body = String),
|
||||
(status = 404, description = "the forge knows no such repo, or its default branch \
|
||||
has no commit (problem+json)", body = String),
|
||||
(status = 409, description = "the forge has no account named like the operator, who \
|
||||
has to log in to it once; or the default branch's rules file changed while the \
|
||||
commit was made (problem+json)", body = String),
|
||||
(status = 422, description = "the default branch holds both rules files, or one the \
|
||||
`rules` GET refuses; the rules already hold every classification as it is; or \
|
||||
the merged rules fail the try-out POST's checks, such as more than a thousand \
|
||||
(problem+json)", body = String),
|
||||
(status = 503, description = "this host has no forge token yet, or the classifier's \
|
||||
account has none in the store; or the forge failed or did not answer within two \
|
||||
minutes (problem+json)", body = String),
|
||||
),
|
||||
tag = "review-classifier"
|
||||
)]
|
||||
pub(crate) async fn post_open_pr(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
body: Result<Json<OpenPrRequest>, JsonRejection>,
|
||||
) -> Result<(StatusCode, Json<OpenPrBranch>), ProblemDetails> {
|
||||
let operator = operator(&headers).ok_or_else(|| {
|
||||
error_problem(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"no Remote-User header: the gateway names the operator, and this request did not \
|
||||
come through it",
|
||||
)
|
||||
})?;
|
||||
let Json(req) = body.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.body_text()))?;
|
||||
let (owner, name) =
|
||||
split_repo(&req.repo).map_err(|d| error_problem(StatusCode::BAD_REQUEST, &d))?;
|
||||
check_classifications(&req.classifications, *CLASSIFICATION_LIMITS.end())
|
||||
.map_err(|d| error_problem(StatusCode::BAD_REQUEST, &d))?;
|
||||
#[cfg(test)]
|
||||
if let Some(fake) = state.try_outs.fake.clone() {
|
||||
return open(&*fake, &operator, owner, name, req.classifications).await;
|
||||
}
|
||||
let Some(forge) = state.forge.get() else {
|
||||
return Err(error_problem(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"no forge access on this host yet",
|
||||
));
|
||||
};
|
||||
open(forge.as_ref(), &operator, owner, name, req.classifications).await
|
||||
}
|
||||
|
||||
/// Resolve the author, merge the rules and push the branch.
|
||||
async fn open<F: FileSource + BranchSink + Sync>(
|
||||
forge: &F,
|
||||
operator: &str,
|
||||
owner: &str,
|
||||
name: &str,
|
||||
rows: Vec<Classification>,
|
||||
) -> Result<(StatusCode, Json<OpenPrBranch>), ProblemDetails> {
|
||||
let repo = format!("{owner}/{name}");
|
||||
let author = deadline(forge.commit_author(operator))
|
||||
.await?
|
||||
.map_err(|e| forge_problem(&e, &repo))?
|
||||
.ok_or_else(|| {
|
||||
error_problem(
|
||||
StatusCode::CONFLICT,
|
||||
&format!(
|
||||
"the forge has no account {operator}, to name as the commit's author: log in \
|
||||
to the forge once, then try again"
|
||||
),
|
||||
)
|
||||
})?;
|
||||
let read = deadline(forge.default_branch_files(owner, name, &RULES_PATHS))
|
||||
.await?
|
||||
.map_err(|e| forge_problem(&e, &repo))?
|
||||
.ok_or_else(|| {
|
||||
error_problem(
|
||||
StatusCode::NOT_FOUND,
|
||||
&format!("{repo} has no commit on its default branch to branch from"),
|
||||
)
|
||||
})?;
|
||||
let existing = match read.files.as_slice() {
|
||||
[] => None,
|
||||
[file] => Some(file),
|
||||
_ => {
|
||||
return Err(error_problem(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
&format!(
|
||||
"{repo}'s default branch {} holds both rules files: keep one",
|
||||
read.branch
|
||||
),
|
||||
));
|
||||
}
|
||||
};
|
||||
let merged =
|
||||
merge(existing, rows).map_err(|d| error_problem(StatusCode::UNPROCESSABLE_ENTITY, &d))?;
|
||||
let web_url = read.web_url.ok_or_else(|| {
|
||||
error_problem(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
&format!("the forge named no web page for {repo}"),
|
||||
)
|
||||
})?;
|
||||
let branch =
|
||||
branch_name(operator).map_err(|e| error_problem(StatusCode::INTERNAL_SERVER_ERROR, &e))?;
|
||||
let compare_url = format!(
|
||||
"{}/compare/{}...{branch}",
|
||||
web_url.as_str().trim_end_matches('/'),
|
||||
read.branch
|
||||
);
|
||||
let commit = BranchCommit {
|
||||
base: read.branch,
|
||||
branch: branch.clone(),
|
||||
path: merged.path.clone(),
|
||||
sha: merged.sha,
|
||||
content: merged.content,
|
||||
message: merged.message,
|
||||
author,
|
||||
};
|
||||
deadline(forge.push(owner, name, commit))
|
||||
.await?
|
||||
.map_err(|e| push_problem(&e, &repo))?;
|
||||
tracing::info!(%repo, %branch, %operator, path = %merged.path, "review classifier branch pushed");
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(OpenPrBranch {
|
||||
branch,
|
||||
path: merged.path,
|
||||
compare_url,
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
async fn deadline<T>(work: impl Future<Output = T>) -> Result<T, ProblemDetails> {
|
||||
forge::within_forge_deadline("review classifier branch", work)
|
||||
.await
|
||||
.ok_or_else(|| {
|
||||
error_problem(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"the forge did not answer within the deadline",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// A fresh branch for `operator`: [`BRANCH_PREFIX`], their name in the
|
||||
/// characters a ref takes without question, and eight random hex digits.
|
||||
fn branch_name(operator: &str) -> Result<String, String> {
|
||||
let mut bytes = [0u8; 4];
|
||||
getrandom::fill(&mut bytes).map_err(|e| format!("drawing a branch name: {e}"))?;
|
||||
let who: String = operator
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_alphanumeric() {
|
||||
c.to_ascii_lowercase()
|
||||
} else {
|
||||
'-'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let mut name = format!("{BRANCH_PREFIX}{who}-");
|
||||
for b in bytes {
|
||||
let _ = write!(name, "{b:02x}");
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// 404 for a repo the forge doesn't know, 503 for anything else.
|
||||
fn forge_problem(e: &anyhow::Error, repo: &str) -> ProblemDetails {
|
||||
if forge_status(e) == Some(StatusCode::NOT_FOUND) {
|
||||
return error_problem(StatusCode::NOT_FOUND, &format!("no repo {repo}"));
|
||||
}
|
||||
let detail = format!("{e:#}");
|
||||
tracing::warn!(error = %detail, %repo, "preparing a review classifier branch failed");
|
||||
error_problem(StatusCode::SERVICE_UNAVAILABLE, &detail)
|
||||
}
|
||||
|
||||
/// 403 when the account may not push, 409 when the rules file or the
|
||||
/// branch changed under the commit, 503 for anything else.
|
||||
fn push_problem(e: &anyhow::Error, repo: &str) -> ProblemDetails {
|
||||
let detail = format!("{e:#}");
|
||||
tracing::warn!(error = %detail, %repo, "pushing a review classifier branch failed");
|
||||
match forge_status(e) {
|
||||
// The forge hides a repo the account can't read behind a 404.
|
||||
Some(StatusCode::FORBIDDEN | StatusCode::NOT_FOUND) => error_problem(
|
||||
StatusCode::FORBIDDEN,
|
||||
&format!(
|
||||
"{LOGIN} may not push to {repo}: a repo admin adds it as a collaborator with \
|
||||
write access ({detail})"
|
||||
),
|
||||
),
|
||||
Some(StatusCode::CONFLICT | StatusCode::UNPROCESSABLE_ENTITY) => error_problem(
|
||||
StatusCode::CONFLICT,
|
||||
&format!("the default branch changed while the branch was made: try again ({detail})"),
|
||||
),
|
||||
_ => error_problem(StatusCode::SERVICE_UNAVAILABLE, &detail),
|
||||
}
|
||||
}
|
||||
|
||||
/// The forge's status, when a forge answer is what failed.
|
||||
fn forge_status(e: &anyhow::Error) -> Option<StatusCode> {
|
||||
match e.downcast_ref::<ForgejoError>()? {
|
||||
ForgejoError::ApiError(api) => match api.error_kind() {
|
||||
ApiErrorKind::Forbidden | ApiErrorKind::Unauthorized => Some(StatusCode::FORBIDDEN),
|
||||
ApiErrorKind::NotFound { .. } => Some(StatusCode::NOT_FOUND),
|
||||
ApiErrorKind::ValidationFailed => Some(StatusCode::UNPROCESSABLE_ENTITY),
|
||||
ApiErrorKind::Other(s) => Some(*s),
|
||||
_ => None,
|
||||
},
|
||||
ForgejoError::UnexpectedStatusCode(s) => Some(*s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The rules file a commit writes.
|
||||
#[derive(Debug)]
|
||||
struct Merged {
|
||||
path: String,
|
||||
/// The blob it replaces; `None` when the repo has no rules file.
|
||||
sha: Option<String>,
|
||||
content: Vec<u8>,
|
||||
message: String,
|
||||
}
|
||||
|
||||
/// `rows` merged into `existing`, or why they can't be.
|
||||
fn merge(existing: Option<&BranchFile>, rows: Vec<Classification>) -> Result<Merged, String> {
|
||||
let [yml, _] = RULES_PATHS;
|
||||
let (path, sha, text, current) = match existing {
|
||||
Some(file) => (
|
||||
file.path.clone(),
|
||||
Some(file.sha.clone()),
|
||||
Some(String::from_utf8_lossy(&file.bytes).into_owned()),
|
||||
parse_rules(&file.path, &file.bytes)?,
|
||||
),
|
||||
None => (yml.to_owned(), None, None, Vec::new()),
|
||||
};
|
||||
let mut merged = current.clone();
|
||||
let (mut added, mut changed) = (Vec::new(), Vec::new());
|
||||
for row in rows {
|
||||
let row = Classification {
|
||||
name: row.name.trim().to_owned(),
|
||||
description: row.description.trim().to_owned(),
|
||||
..row
|
||||
};
|
||||
match merged.iter().position(|c| c.name.trim() == row.name) {
|
||||
Some(i) if merged[i] == row => {}
|
||||
Some(i) => {
|
||||
changed.push(row.name.clone());
|
||||
merged[i] = row;
|
||||
}
|
||||
None => {
|
||||
added.push(row.name.clone());
|
||||
merged.push(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
if added.is_empty() && changed.is_empty() {
|
||||
return Err(format!(
|
||||
"{path} already holds every classification as it is"
|
||||
));
|
||||
}
|
||||
check_classifications(&merged, *CLASSIFICATION_LIMITS.end())
|
||||
.map_err(|e| format!("{path} with these merged: {e}"))?;
|
||||
let content = if std::path::Path::new(&path)
|
||||
.extension()
|
||||
.is_some_and(|e| e == "json")
|
||||
{
|
||||
let mut json = serde_json::to_string_pretty(&serde_json::json!({
|
||||
"classifications": merged,
|
||||
}))
|
||||
.map_err(|e| format!("encoding {path}: {e}"))?;
|
||||
json.push('\n');
|
||||
json
|
||||
} else {
|
||||
yaml(text.as_deref(), ¤t, &merged)
|
||||
};
|
||||
let mut message = String::from("review classifier:");
|
||||
for (verb, names) in [("add", &added), ("update", &changed)] {
|
||||
if !names.is_empty() {
|
||||
let sep = if message.ends_with(':') { " " } else { "; " };
|
||||
let _ = write!(message, "{sep}{verb} {}", names.join(", "));
|
||||
}
|
||||
}
|
||||
Ok(Merged {
|
||||
path,
|
||||
sha,
|
||||
content: content.into_bytes(),
|
||||
message,
|
||||
})
|
||||
}
|
||||
|
||||
/// `merged` as a YAML rules file. Each entry of `text` that `merged` holds
|
||||
/// unchanged at the same place keeps its text, as long as the result reads
|
||||
/// back as `merged`; otherwise the whole file is written out.
|
||||
fn yaml(text: Option<&str>, current: &[Classification], merged: &[Classification]) -> String {
|
||||
if let Some((head, entries, indent)) = text.and_then(entry_lines) {
|
||||
let mut out = head;
|
||||
for (i, c) in merged.iter().enumerate() {
|
||||
match entries.get(i) {
|
||||
Some(kept) if current.get(i) == Some(c) => out.push_str(kept),
|
||||
_ => {
|
||||
if !out.is_empty() && !out.ends_with('\n') {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str(&yaml_entry(c, &indent));
|
||||
}
|
||||
}
|
||||
}
|
||||
if parse_rules(".yml", out.as_bytes()).as_deref() == Ok(merged) {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
let mut out = String::from("classifications:\n");
|
||||
for c in merged {
|
||||
out.push_str(&yaml_entry(c, " "));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `text` split into what comes before the first entry of its
|
||||
/// `classifications:` list, the text of each entry up to the next one, and
|
||||
/// the indent of their `-`. `None` when no entry follows that key. The split
|
||||
/// is only a guess at the layout: [`yaml`] keeps it when what it builds reads
|
||||
/// back as it should.
|
||||
fn entry_lines(text: &str) -> Option<(String, Vec<String>, String)> {
|
||||
let lines: Vec<&str> = text.split_inclusive('\n').collect();
|
||||
let key = lines
|
||||
.iter()
|
||||
.position(|l| l.trim_end() == "classifications:")?;
|
||||
let first = key
|
||||
+ 1
|
||||
+ lines[key + 1..]
|
||||
.iter()
|
||||
.position(|l| !l.trim().is_empty() && !l.trim_start().starts_with('#'))?;
|
||||
let indent: String = lines[first].chars().take_while(|c| *c == ' ').collect();
|
||||
let mut entries: Vec<String> = Vec::new();
|
||||
for line in &lines[first..] {
|
||||
if line
|
||||
.strip_prefix(indent.as_str())
|
||||
.is_some_and(|rest| rest.starts_with("- "))
|
||||
{
|
||||
entries.push((*line).to_owned());
|
||||
} else {
|
||||
entries.last_mut()?.push_str(line);
|
||||
}
|
||||
}
|
||||
Some((lines[..first].concat(), entries, indent))
|
||||
}
|
||||
|
||||
/// One classification as an entry of a YAML block list, its `-` at
|
||||
/// `indent`.
|
||||
fn yaml_entry(c: &Classification, indent: &str) -> String {
|
||||
let polarity = match c.polarity {
|
||||
Polarity::Positive => "positive",
|
||||
Polarity::Negative => "negative",
|
||||
};
|
||||
let inner = format!("{indent} ");
|
||||
let mut out = format!("{indent}- name: {}\n", yaml_name(&c.name));
|
||||
if foldable(&c.description) {
|
||||
let _ = writeln!(out, "{inner}description: >-");
|
||||
let lead = format!("{inner} ");
|
||||
let mut line = String::new();
|
||||
for word in c.description.split(' ') {
|
||||
if !line.is_empty() && lead.len() + line.len() + 1 + word.len() > YAML_WIDTH {
|
||||
let _ = writeln!(out, "{lead}{line}");
|
||||
line.clear();
|
||||
}
|
||||
if !line.is_empty() {
|
||||
line.push(' ');
|
||||
}
|
||||
line.push_str(word);
|
||||
}
|
||||
let _ = writeln!(out, "{lead}{line}");
|
||||
} else {
|
||||
let _ = writeln!(out, "{inner}description: {}", json_string(&c.description));
|
||||
}
|
||||
let _ = writeln!(out, "{inner}polarity: {polarity}");
|
||||
let _ = writeln!(out, "{inner}threshold: {}", c.threshold);
|
||||
out
|
||||
}
|
||||
|
||||
/// `name` bare when it can't read as anything but that string, quoted
|
||||
/// otherwise.
|
||||
fn yaml_name(name: &str) -> String {
|
||||
let bare = name.starts_with(|c: char| c.is_ascii_lowercase())
|
||||
&& name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
|
||||
&& !matches!(
|
||||
name,
|
||||
"y" | "n" | "yes" | "no" | "on" | "off" | "true" | "false" | "null"
|
||||
);
|
||||
if bare {
|
||||
name.to_owned()
|
||||
} else {
|
||||
json_string(name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a folded block scalar reads back as exactly `s`, which is trimmed
|
||||
/// and not empty: one line of printable text, words split by single spaces.
|
||||
fn foldable(s: &str) -> bool {
|
||||
!s.contains(" ") && !s.chars().any(char::is_control)
|
||||
}
|
||||
|
||||
/// `s` as a double-quoted scalar; JSON's escapes are YAML's too.
|
||||
fn json_string(s: &str) -> String {
|
||||
serde_json::Value::from(s).to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{Request, StatusCode};
|
||||
use swarm_wire::review_classifier::{Overall, Reply};
|
||||
use tower::ServiceExt as _;
|
||||
|
||||
use super::super::tests::Fake;
|
||||
use super::*;
|
||||
|
||||
fn rule(name: &str, description: &str) -> Classification {
|
||||
Classification {
|
||||
name: name.to_owned(),
|
||||
description: description.to_owned(),
|
||||
polarity: Polarity::Negative,
|
||||
threshold: 70,
|
||||
}
|
||||
}
|
||||
|
||||
fn file(path: &str, text: &str) -> BranchFile {
|
||||
BranchFile {
|
||||
path: path.to_owned(),
|
||||
sha: "b1".to_owned(),
|
||||
bytes: text.as_bytes().to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
const OWN: &str = include_str!("../../../../.hyperhive/review-classifier.yml");
|
||||
|
||||
#[test]
|
||||
fn a_new_rule_leaves_every_existing_entry_as_it_was_written() {
|
||||
let [yml, _] = RULES_PATHS;
|
||||
// This repo's file without its last entry: the file may already hold
|
||||
// the cap, and the property under test is how a new entry is appended,
|
||||
// not how many entries the file has today.
|
||||
let last = OWN.rfind("\n - name:").expect("a last entry") + 1;
|
||||
let own = &OWN[..last];
|
||||
let before = parse_rules(yml, own.as_bytes()).expect("this repo's rules parse");
|
||||
let new = rule(
|
||||
"no-todo",
|
||||
"The diff adds a TODO or FIXME comment without a tracker reference next to it, \
|
||||
which leaves the follow-up with nobody to own it.",
|
||||
);
|
||||
let merged = merge(Some(&file(yml, own)), vec![new.clone()]).expect("merges");
|
||||
let text = String::from_utf8(merged.content).expect("utf-8");
|
||||
assert!(text.starts_with(own), "{text}");
|
||||
assert_eq!(merged.sha.as_deref(), Some("b1"));
|
||||
assert_eq!(merged.message, "review classifier: add no-todo");
|
||||
let after = parse_rules(yml, text.as_bytes()).expect("parses");
|
||||
assert_eq!(after, [before, vec![new.clone()]].concat());
|
||||
assert!(text.lines().all(|l| l.len() <= YAML_WIDTH), "{text}");
|
||||
|
||||
let unterminated = own.trim_end();
|
||||
let merged = merge(Some(&file(yml, unterminated)), vec![new]).expect("merges");
|
||||
let text = String::from_utf8(merged.content).expect("utf-8");
|
||||
assert!(
|
||||
text.starts_with(&format!("{unterminated}\n - name: no-todo\n")),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rule_with_a_known_name_replaces_that_entry_in_place() {
|
||||
let [yml, json] = RULES_PATHS;
|
||||
let mut before = parse_rules(yml, OWN.as_bytes()).expect("this repo's rules parse");
|
||||
let mut edited = before[1].clone();
|
||||
edited.threshold = 90;
|
||||
let padded = Classification {
|
||||
name: format!(" {} ", edited.name),
|
||||
..edited.clone()
|
||||
};
|
||||
let merged = merge(Some(&file(yml, OWN)), vec![padded.clone()]).expect("merges");
|
||||
let after = parse_rules(yml, &merged.content).expect("parses");
|
||||
before[1] = edited.clone();
|
||||
assert_eq!(after, before);
|
||||
assert_eq!(
|
||||
merged.message,
|
||||
format!("review classifier: update {}", edited.name)
|
||||
);
|
||||
|
||||
let as_json = serde_json::json!({ "classifications": [&before[0], &before[2]] });
|
||||
let merged = merge(
|
||||
Some(&file(json, &as_json.to_string())),
|
||||
vec![padded, rule("x", "y")],
|
||||
)
|
||||
.expect("merges");
|
||||
let after = parse_rules(json, &merged.content).expect("parses");
|
||||
assert_eq!(
|
||||
after,
|
||||
[
|
||||
before[0].clone(),
|
||||
before[2].clone(),
|
||||
edited.clone(),
|
||||
rule("x", "y")
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
merged.message,
|
||||
format!("review classifier: add {}, x", edited.name)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_rules_file_creates_the_yaml_one() {
|
||||
let rules = vec![
|
||||
rule("no-ads", "No ads."),
|
||||
rule("null", "N."),
|
||||
rule("Yes: #1", "A \"quote\"."),
|
||||
// A full line, then a double space where the wrap falls.
|
||||
rule("spaced", &format!("{} y", "x".repeat(72))),
|
||||
rule("broken", "A\nnewline."),
|
||||
];
|
||||
let merged = merge(None, rules.clone()).expect("merges");
|
||||
let [yml, _] = RULES_PATHS;
|
||||
assert_eq!(merged.path, yml);
|
||||
assert_eq!(merged.sha, None);
|
||||
let after = parse_rules(yml, &merged.content).expect("parses");
|
||||
assert_eq!(after, rules);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_list_the_splice_cant_follow_is_written_out_whole() {
|
||||
let [yml, _] = RULES_PATHS;
|
||||
let flow =
|
||||
"classifications: [{name: a, description: b, polarity: negative, threshold: 70}]";
|
||||
let merged = merge(Some(&file(yml, flow)), vec![rule("c", "d")]).expect("merges");
|
||||
let after = parse_rules(yml, &merged.content).expect("parses");
|
||||
assert_eq!(after, [rule("a", "b"), rule("c", "d")]);
|
||||
|
||||
// Kept as it is, `b` would point at an anchor the new `a` lacks.
|
||||
let aliased = "\
|
||||
classifications:
|
||||
- name: a
|
||||
description: &shared Shared.
|
||||
polarity: negative
|
||||
threshold: 70
|
||||
- name: b
|
||||
description: *shared
|
||||
polarity: negative
|
||||
threshold: 70
|
||||
";
|
||||
let mut a = rule("a", "Its own.");
|
||||
a.threshold = 90;
|
||||
let merged = merge(Some(&file(yml, aliased)), vec![a.clone()]).expect("merges");
|
||||
let after = parse_rules(yml, &merged.content).expect("parses");
|
||||
assert_eq!(after, [a, rule("b", "Shared.")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_new_or_too_many_or_a_bad_file_is_refused() {
|
||||
let [yml, _] = RULES_PATHS;
|
||||
let before = parse_rules(yml, OWN.as_bytes()).expect("this repo's rules parse");
|
||||
let err = merge(Some(&file(yml, OWN)), before.clone()).expect_err("nothing to change");
|
||||
assert!(err.contains("already holds"), "{err}");
|
||||
let many: Vec<_> = (0..=1000 - before.len())
|
||||
.map(|i| rule(&format!("extra-{i}"), "d"))
|
||||
.collect();
|
||||
let err = merge(Some(&file(yml, OWN)), many).expect_err("1001");
|
||||
assert!(err.contains("1001 classifications"), "{err}");
|
||||
let err = merge(Some(&file(yml, "nope: 1")), vec![rule("a", "b")]).expect_err("bad");
|
||||
assert!(err.contains(yml), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_branch_name_is_a_plain_ref_under_the_prefix() {
|
||||
let name = branch_name("Alice Smith/../x").expect("a name");
|
||||
let (who, hex) = name
|
||||
.strip_prefix(BRANCH_PREFIX)
|
||||
.and_then(|r| r.rsplit_once('-'))
|
||||
.expect("prefix and suffix");
|
||||
assert_eq!(who, "alice-smith----x");
|
||||
assert_eq!(hex.len(), 8);
|
||||
assert!(hex.bytes().all(|b| b.is_ascii_hexdigit()), "{name}");
|
||||
}
|
||||
|
||||
fn app(fake: Fake) -> axum::Router {
|
||||
let (mut state, _) = crate::routes::tests::state_with_roster();
|
||||
state.try_outs.fake = Some(Arc::new(fake));
|
||||
crate::startup::build_app(state)
|
||||
}
|
||||
|
||||
fn fake() -> Fake {
|
||||
Fake::new(
|
||||
Reply::Done {
|
||||
rows: Vec::new(),
|
||||
overall: Overall::Approve,
|
||||
},
|
||||
vec![super::super::tests::rules_json()],
|
||||
)
|
||||
}
|
||||
|
||||
fn body(repo: &str) -> String {
|
||||
serde_json::json!({
|
||||
"repo": repo,
|
||||
"classifications": [{
|
||||
"name": "no-ads",
|
||||
"description": "No ads.",
|
||||
"polarity": "negative",
|
||||
"threshold": 80,
|
||||
}],
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
async fn post(
|
||||
app: &axum::Router,
|
||||
user: Option<&str>,
|
||||
body: String,
|
||||
) -> (StatusCode, serde_json::Value) {
|
||||
let mut req = Request::post("/api/review-classifier/open-pr")
|
||||
.header("content-type", "application/json");
|
||||
if let Some(user) = user {
|
||||
req = req.header("remote-user", user);
|
||||
}
|
||||
let res = app
|
||||
.clone()
|
||||
.oneshot(req.body(Body::from(body)).expect("a request"))
|
||||
.await
|
||||
.expect("infallible");
|
||||
let status = res.status();
|
||||
let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("a body");
|
||||
(status, serde_json::from_slice(&bytes).unwrap_or_default())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_branch_is_pushed_as_the_operator_and_linked_for_the_pr() {
|
||||
let fake = fake();
|
||||
let pushed = Arc::clone(&fake.pushed);
|
||||
let (status, answer) = post(&app(fake), Some("alice"), body("o/r")).await;
|
||||
assert_eq!(status, StatusCode::CREATED, "{answer}");
|
||||
let branch = answer["branch"].as_str().expect("a branch");
|
||||
assert!(branch.starts_with("review-classifier/alice-"), "{branch}");
|
||||
assert_eq!(
|
||||
answer["compare_url"],
|
||||
format!("https://forge.test/o/r/compare/main...{branch}")
|
||||
);
|
||||
let [_, json] = RULES_PATHS;
|
||||
assert_eq!(answer["path"], json);
|
||||
let pushed = pushed.lock().expect("unpoisoned");
|
||||
let [(repo, commit)] = pushed.as_slice() else {
|
||||
panic!("one push expected: {pushed:?}");
|
||||
};
|
||||
assert_eq!(repo, "o/r");
|
||||
assert_eq!(
|
||||
commit.author,
|
||||
CommitAuthor {
|
||||
name: "Alice".to_owned(),
|
||||
email: "alice@example.test".to_owned(),
|
||||
}
|
||||
);
|
||||
assert_eq!(commit.base, "main");
|
||||
assert_eq!(commit.branch, branch);
|
||||
assert_eq!(commit.sha.as_deref(), Some(format!("sha-{json}").as_str()));
|
||||
let names: Vec<_> = parse_rules(json, &commit.content)
|
||||
.expect("parses")
|
||||
.into_iter()
|
||||
.map(|c| c.name)
|
||||
.collect();
|
||||
assert_eq!(names, ["datetime", "no-ads"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_author_is_the_session_user_not_one_in_the_body() {
|
||||
let fake = fake();
|
||||
let pushed = Arc::clone(&fake.pushed);
|
||||
let mut body: serde_json::Value = serde_json::from_str(&body("o/r")).expect("json");
|
||||
body["author"] = "alice".into();
|
||||
let (status, answer) = post(&app(fake), Some("bob"), body.to_string()).await;
|
||||
assert_eq!(status, StatusCode::CREATED, "{answer}");
|
||||
let pushed = pushed.lock().expect("unpoisoned");
|
||||
assert_eq!(pushed[0].1.author.email, "bob@example.test");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_session_user_or_no_forge_account_pushes_nothing() {
|
||||
for (user, want, says) in [
|
||||
(None, StatusCode::UNAUTHORIZED, "Remote-User"),
|
||||
(Some(" "), StatusCode::UNAUTHORIZED, "Remote-User"),
|
||||
(
|
||||
Some("mallory"),
|
||||
StatusCode::CONFLICT,
|
||||
"log in to the forge once",
|
||||
),
|
||||
] {
|
||||
let fake = fake();
|
||||
let pushed = Arc::clone(&fake.pushed);
|
||||
let (status, problem) = post(&app(fake), user, body("o/r")).await;
|
||||
assert_eq!(status, want, "{user:?}: {problem}");
|
||||
let detail = problem["detail"].as_str().expect("a detail");
|
||||
assert!(detail.contains(says), "{user:?}: {detail}");
|
||||
assert!(pushed.lock().expect("unpoisoned").is_empty(), "{user:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_refused_push_names_the_missing_access() {
|
||||
for (refusal, want, says) in [
|
||||
(StatusCode::FORBIDDEN, StatusCode::FORBIDDEN, "write access"),
|
||||
(StatusCode::NOT_FOUND, StatusCode::FORBIDDEN, "write access"),
|
||||
(StatusCode::CONFLICT, StatusCode::CONFLICT, "try again"),
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"500",
|
||||
),
|
||||
] {
|
||||
let mut fake = fake();
|
||||
fake.push_refusal = Some(refusal);
|
||||
let (status, problem) = post(&app(fake), Some("alice"), body("o/r")).await;
|
||||
assert_eq!(status, want, "{refusal}: {problem}");
|
||||
let detail = problem["detail"].as_str().expect("a detail");
|
||||
assert!(detail.contains(says), "{refusal}: {detail}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_bad_body_or_repo_is_refused_before_the_forge() {
|
||||
for (body, want) in [
|
||||
("{".to_owned(), StatusCode::BAD_REQUEST),
|
||||
(body("o"), StatusCode::BAD_REQUEST),
|
||||
(
|
||||
serde_json::json!({ "repo": "o/r", "classifications": [] }).to_string(),
|
||||
StatusCode::BAD_REQUEST,
|
||||
),
|
||||
(body("o/elsewhere"), StatusCode::NOT_FOUND),
|
||||
(body("o/empty"), StatusCode::NOT_FOUND),
|
||||
(body("o/down"), StatusCode::SERVICE_UNAVAILABLE),
|
||||
] {
|
||||
let (status, problem) = post(&app(fake()), Some("alice"), body.clone()).await;
|
||||
assert_eq!(status, want, "{body}: {problem}");
|
||||
}
|
||||
}
|
||||
}
|
||||
3511
swarm-controller/src/review/review_classifier/review.rs
Normal file
3511
swarm-controller/src/review/review_classifier/review.rs
Normal file
File diff suppressed because it is too large
Load diff
751
swarm-controller/src/review/review_classifier/runs.rs
Normal file
751
swarm-controller/src/review/review_classifier/runs.rs
Normal file
|
|
@ -0,0 +1,751 @@
|
|||
//! `GET /api/review-classifier/runs`: the review classifier's finished runs,
|
||||
//! try-outs and requested reviews both, newest first.
|
||||
//!
|
||||
//! The newest [`MAX_RUNS`] are one JSON array under [`KEY`] in [`BUCKET`],
|
||||
//! which only this daemon reads or writes. Recording a run is one
|
||||
//! compare-and-set on that key, as for `schedules::DEFINITIONS_KEY`; one key,
|
||||
//! because listing a bucket's keys needs a consumer grant this daemon holds
|
||||
//! for no bucket of its own.
|
||||
//!
|
||||
//! Every recorded run is also one `info` event, [`EVENT`], carrying the
|
||||
//! record's fields, so a run whose write failed is still in the log store.
|
||||
//! A record holds no diff, no commit text and no token count or cost.
|
||||
|
||||
use std::future::Future;
|
||||
|
||||
use anyhow::Context as _;
|
||||
use async_nats::jetstream::kv::Store;
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use problem_details::ProblemDetails;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use swarm_wire::review_classifier::{Overall, Reply, Row};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::routes::{AppState, error_problem};
|
||||
use crate::schedules::{read_with, write};
|
||||
|
||||
/// The bucket holding the runs. Agents hold no grant on it.
|
||||
pub const BUCKET: &str = "review-classifier-runs";
|
||||
|
||||
/// The one key in [`BUCKET`].
|
||||
pub const KEY: &str = "recent";
|
||||
|
||||
/// How many runs the list keeps; recording one more drops the oldest.
|
||||
pub(crate) const MAX_RUNS: usize = 100;
|
||||
|
||||
/// How many times a losing writer re-reads and re-applies, as in
|
||||
/// `schedules::MAX_ATTEMPTS`.
|
||||
const MAX_ATTEMPTS: usize = 5;
|
||||
|
||||
/// The message of the event [`Runs::record`] logs for every run.
|
||||
pub(crate) const EVENT: &str = "review classifier run finished";
|
||||
|
||||
/// What started a run.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub(crate) enum Trigger {
|
||||
/// The swarm UI's try-out page.
|
||||
TryOut,
|
||||
/// A review request on the forge.
|
||||
Review,
|
||||
}
|
||||
|
||||
/// How a run ended.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub(crate) enum RunOutcome {
|
||||
/// A review approved the PR.
|
||||
Approved,
|
||||
/// A review requested changes.
|
||||
ChangesRequested,
|
||||
/// A comment was posted: the request could not be queued, the rules did
|
||||
/// not load, the PR was unreadable, the run failed, the classifier sent a
|
||||
/// different number of answers than it was sent classifications, or any
|
||||
/// classification got none.
|
||||
NoVerdict,
|
||||
/// No run started, as every run and wait place was taken; a comment
|
||||
/// saying so was posted. This build records none; it is here so that a
|
||||
/// stored record of it still reads.
|
||||
QueueFull,
|
||||
/// The review could not be posted.
|
||||
PostFailed,
|
||||
/// A try-out the classifier answered.
|
||||
Done,
|
||||
/// A try-out that failed.
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// One finished run.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
|
||||
pub(crate) struct RunRecord {
|
||||
/// A try-out's id is the one its POST answered with.
|
||||
pub(super) id: String,
|
||||
pub(super) trigger: Trigger,
|
||||
/// `owner/name`.
|
||||
pub(super) repo: String,
|
||||
pub(super) pr: u64,
|
||||
/// The swarm UI user who started a try-out, or the forge user who
|
||||
/// requested the review.
|
||||
pub(super) requester: String,
|
||||
/// The commit the run read. Absent when the PR was not read.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) head_sha: Option<String>,
|
||||
/// A hash of the title and description the run read, which the verdict
|
||||
/// also depends on. Absent when the PR was not read, and on a run recorded
|
||||
/// before this was kept.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) described: Option<String>,
|
||||
/// Unix seconds: a try-out's POST, or a review's start once it had a
|
||||
/// run place.
|
||||
pub(super) started_unix: i64,
|
||||
pub(super) finished_unix: i64,
|
||||
pub(super) outcome: RunOutcome,
|
||||
/// Why, for every outcome but `approved`, `changes-requested` and
|
||||
/// `done`. A review that re-posts an earlier run's verdict names that
|
||||
/// run here.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) detail: Option<String>,
|
||||
/// As the try-out GET returns them, when the classifier answered.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) rows: Option<Vec<Row>>,
|
||||
/// As the try-out GET returns it, when the classifier answered.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) overall: Option<Overall>,
|
||||
/// The posted review, when one was posted and the forge named its URL.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) review_url: Option<String>,
|
||||
}
|
||||
|
||||
/// The rows and the overall verdict of `reply`, when the classifier
|
||||
/// answered.
|
||||
pub(super) fn answer(reply: &Reply) -> (Option<Vec<Row>>, Option<Overall>) {
|
||||
match reply {
|
||||
Reply::Done { rows, overall } => (Some(rows.clone()), Some(*overall)),
|
||||
Reply::Failed { .. } => (None, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry of the stored list.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(untagged)]
|
||||
pub(crate) enum Stored {
|
||||
Run(RunRecord),
|
||||
/// A record this build cannot decode, such as one a newer build wrote.
|
||||
/// Left out of the list but kept, counted toward [`MAX_RUNS`] and written
|
||||
/// back as it was read, so a newer build reads it again after a
|
||||
/// roll-forward.
|
||||
Unreadable(serde_json::Value),
|
||||
}
|
||||
|
||||
/// Where the runs are kept: [`BUCKET`] in production, a fake in the tests.
|
||||
pub(crate) trait RunDoc {
|
||||
/// The entries, with the revision to write them back against.
|
||||
fn read(&self) -> impl Future<Output = anyhow::Result<(Vec<Stored>, Option<u64>)>> + Send;
|
||||
/// `Ok(false)` when another write landed since `revision`.
|
||||
fn write(
|
||||
&self,
|
||||
runs: Vec<Stored>,
|
||||
revision: Option<u64>,
|
||||
) -> impl Future<Output = anyhow::Result<bool>> + Send;
|
||||
}
|
||||
|
||||
impl RunDoc for Store {
|
||||
async fn read(&self) -> anyhow::Result<(Vec<Stored>, Option<u64>)> {
|
||||
read_with(self, KEY, |bytes| Ok(decode(bytes))).await
|
||||
}
|
||||
|
||||
async fn write(&self, runs: Vec<Stored>, revision: Option<u64>) -> anyhow::Result<bool> {
|
||||
write(self, KEY, &runs, revision).await
|
||||
}
|
||||
}
|
||||
|
||||
/// The entries in `bytes`, the stored document, with a warning when any is
|
||||
/// [`Stored::Unreadable`]. A document that is not a JSON array reads as no
|
||||
/// entries, with a warning, and the next write replaces it.
|
||||
fn decode(bytes: &[u8]) -> Vec<Stored> {
|
||||
let values: Vec<serde_json::Value> = match serde_json::from_slice(bytes) {
|
||||
Ok(values) => values,
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
bucket = BUCKET, key = KEY, error = %e,
|
||||
"the review classifier runs are not decodable; reading them as none"
|
||||
);
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
let mut unreadable = 0_usize;
|
||||
let mut first_error = None;
|
||||
let entries = values
|
||||
.into_iter()
|
||||
.map(|value| match RunRecord::deserialize(&value) {
|
||||
Ok(run) => Stored::Run(run),
|
||||
Err(e) => {
|
||||
unreadable += 1;
|
||||
first_error.get_or_insert(e);
|
||||
Stored::Unreadable(value)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if let Some(error) = first_error {
|
||||
tracing::warn!(
|
||||
bucket = BUCKET, key = KEY, unreadable, %error,
|
||||
"review classifier runs this build cannot decode are left out of the list and kept"
|
||||
);
|
||||
}
|
||||
entries
|
||||
}
|
||||
|
||||
/// Put `run` first in `doc`, keeping the newest [`MAX_RUNS`], re-reading and
|
||||
/// re-applying when another write landed in between.
|
||||
async fn push(doc: &impl RunDoc, run: &RunRecord) -> anyhow::Result<()> {
|
||||
for _ in 0..MAX_ATTEMPTS {
|
||||
let (runs, revision) = doc.read().await?;
|
||||
if doc.write(newest(run, runs), revision).await? {
|
||||
return Ok(());
|
||||
}
|
||||
tracing::debug!("review classifier runs: write lost a race, retrying");
|
||||
}
|
||||
anyhow::bail!("gave up recording the run after {MAX_ATTEMPTS} conflicting writes")
|
||||
}
|
||||
|
||||
/// `runs` with `run` in front, cut to [`MAX_RUNS`] entries.
|
||||
fn newest(run: &RunRecord, mut runs: Vec<Stored>) -> Vec<Stored> {
|
||||
runs.insert(0, Stored::Run(run.clone()));
|
||||
runs.truncate(MAX_RUNS);
|
||||
runs
|
||||
}
|
||||
|
||||
/// The runs' store, as [`AppState`] holds it.
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum Runs {
|
||||
/// [`BUCKET`] on the swarm queue, when this host has one.
|
||||
Live(Option<async_nats::Client>),
|
||||
/// An in-memory document a test reads back.
|
||||
#[cfg(test)]
|
||||
Fake(std::sync::Arc<tests::FakeDoc>),
|
||||
}
|
||||
|
||||
/// Why the runs' store could not be reached: always 503.
|
||||
struct Unreachable(String);
|
||||
|
||||
impl Runs {
|
||||
/// Log `run` and add it to the list. A failed write is logged and
|
||||
/// changes nothing else.
|
||||
pub(crate) async fn record(&self, run: RunRecord) {
|
||||
log(&run);
|
||||
if let Err(e) = self.push(&run).await {
|
||||
tracing::warn!(
|
||||
id = %run.id, error = %format!("{e:#}"),
|
||||
"storing a review classifier run failed; the run is in this log only"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async fn push(&self, run: &RunRecord) -> anyhow::Result<()> {
|
||||
match self {
|
||||
Self::Live(client) => {
|
||||
let store = open(client.as_ref()).await.map_err(|Unreachable(e)| {
|
||||
anyhow::anyhow!(e).context(format!("opening the {BUCKET} bucket"))
|
||||
})?;
|
||||
push(&store, run).await
|
||||
}
|
||||
#[cfg(test)]
|
||||
Self::Fake(doc) => push(&**doc, run).await,
|
||||
}
|
||||
}
|
||||
|
||||
/// The newest recorded review of `head` on `repo`'s PR `pr`, read with the
|
||||
/// title and description `described` hashes, if any.
|
||||
pub(crate) async fn newest_review(
|
||||
&self,
|
||||
repo: &str,
|
||||
pr: u64,
|
||||
head: &str,
|
||||
described: &str,
|
||||
) -> anyhow::Result<Option<RunRecord>> {
|
||||
let (runs, _) = match self {
|
||||
Self::Live(client) => {
|
||||
let store = open(client.as_ref()).await.map_err(|Unreachable(e)| {
|
||||
anyhow::anyhow!(e).context(format!("opening the {BUCKET} bucket"))
|
||||
})?;
|
||||
RunDoc::read(&store).await?
|
||||
}
|
||||
#[cfg(test)]
|
||||
Self::Fake(doc) => doc.read().await?,
|
||||
};
|
||||
Ok(runs.into_iter().find_map(|entry| match entry {
|
||||
Stored::Run(run)
|
||||
if run.trigger == Trigger::Review
|
||||
&& run.repo == repo
|
||||
&& run.pr == pr
|
||||
&& run.head_sha.as_deref() == Some(head)
|
||||
&& run.described.as_deref() == Some(described) =>
|
||||
{
|
||||
Some(run)
|
||||
}
|
||||
_ => None,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn list(&self) -> Result<Vec<RunRecord>, ProblemDetails> {
|
||||
let read = match self {
|
||||
Self::Live(client) => {
|
||||
let store = open(client.as_ref())
|
||||
.await
|
||||
.map_err(|Unreachable(e)| error_problem(StatusCode::SERVICE_UNAVAILABLE, &e))?;
|
||||
RunDoc::read(&store).await
|
||||
}
|
||||
#[cfg(test)]
|
||||
Self::Fake(doc) => doc.read().await,
|
||||
};
|
||||
read.map(|(runs, _)| {
|
||||
runs.into_iter()
|
||||
.filter_map(|entry| match entry {
|
||||
Stored::Run(run) => Some(run),
|
||||
Stored::Unreadable(_) => None,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.map_err(|e| {
|
||||
let detail = format!("{e:#}");
|
||||
tracing::warn!(error = %detail, "reading the review classifier runs failed");
|
||||
error_problem(StatusCode::INTERNAL_SERVER_ERROR, &detail)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Open [`BUCKET`], creating it if nothing has yet.
|
||||
async fn open(client: Option<&async_nats::Client>) -> Result<Store, Unreachable> {
|
||||
let client = client
|
||||
.ok_or_else(|| Unreachable("no swarm queue is configured on this host".to_owned()))?;
|
||||
swarm_queue_client::ensure_connected(client)
|
||||
.map_err(|e| Unreachable(swarm_queue_client::chain(&e)))?;
|
||||
let js = async_nats::jetstream::new(client.clone());
|
||||
if let Ok(store) = js.get_key_value(BUCKET).await {
|
||||
return Ok(store);
|
||||
}
|
||||
js.create_key_value(async_nats::jetstream::kv::Config {
|
||||
bucket: BUCKET.to_owned(),
|
||||
description: "The review classifier's newest finished runs".to_owned(),
|
||||
history: 1,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.with_context(|| format!("creating the {BUCKET} bucket"))
|
||||
.map_err(|e| Unreachable(format!("{e:#}")))
|
||||
}
|
||||
|
||||
/// `value` as its one serde word, as the route spells it.
|
||||
fn word<T: Serialize>(value: &T) -> String {
|
||||
serde_json::to_value(value)
|
||||
.ok()
|
||||
.and_then(|v| v.as_str().map(str::to_owned))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The [`EVENT`] for `run`, one field per record field. `rows` is the JSON
|
||||
/// the route returns for them.
|
||||
fn log(run: &RunRecord) {
|
||||
let rows = run
|
||||
.rows
|
||||
.as_ref()
|
||||
.and_then(|rows| serde_json::to_string(rows).ok());
|
||||
tracing::info!(
|
||||
id = %run.id,
|
||||
trigger = %word(&run.trigger),
|
||||
repo = %run.repo,
|
||||
pr = run.pr,
|
||||
requester = %run.requester,
|
||||
head_sha = run.head_sha.as_deref(),
|
||||
started_unix = run.started_unix,
|
||||
finished_unix = run.finished_unix,
|
||||
outcome = %word(&run.outcome),
|
||||
detail = run.detail.as_deref(),
|
||||
rows = rows.as_deref(),
|
||||
overall = run.overall.as_ref().map(word).as_deref(),
|
||||
review_url = run.review_url.as_deref(),
|
||||
"{EVENT}"
|
||||
);
|
||||
}
|
||||
|
||||
/// List the review classifier's finished runs.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/review-classifier/runs",
|
||||
responses(
|
||||
(status = 200, description = "the newest 100 finished runs, try-outs and requested \
|
||||
reviews, newest first; empty when there are none", body = Vec<RunRecord>),
|
||||
(status = 503, description = "no swarm queue is configured on this host, it is not \
|
||||
connected, or the runs' bucket could not be opened (problem+json)", body = String),
|
||||
(status = 500, description = "the runs could not be read (problem+json)",
|
||||
body = String),
|
||||
),
|
||||
tag = "review-classifier"
|
||||
)]
|
||||
pub(crate) async fn get_runs(
|
||||
State(state): State<AppState>,
|
||||
) -> Result<Json<Vec<RunRecord>>, ProblemDetails> {
|
||||
state.runs.list().await.map(Json)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::Request;
|
||||
use swarm_wire::review_classifier::{Polarity, Verdict};
|
||||
use tower::ServiceExt as _;
|
||||
use tracing_subscriber::layer::SubscriberExt as _;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A document in memory. Each of the first `conflicts` writes loses to a
|
||||
/// write that lands one run in between; a document set to `fail` fails
|
||||
/// every read.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct FakeDoc {
|
||||
state: Mutex<(Vec<Stored>, u64)>,
|
||||
conflicts: Mutex<usize>,
|
||||
fail: bool,
|
||||
}
|
||||
|
||||
impl FakeDoc {
|
||||
pub(crate) fn failing() -> Self {
|
||||
Self {
|
||||
fail: true,
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn conflicting(conflicts: usize) -> Self {
|
||||
Self {
|
||||
conflicts: Mutex::new(conflicts),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The decodable runs, as the list shows them.
|
||||
pub(crate) fn runs(&self) -> Vec<RunRecord> {
|
||||
self.entries()
|
||||
.into_iter()
|
||||
.filter_map(|entry| match entry {
|
||||
Stored::Run(run) => Some(run),
|
||||
Stored::Unreadable(_) => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn entries(&self) -> Vec<Stored> {
|
||||
self.state.lock().expect("unpoisoned").0.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl RunDoc for FakeDoc {
|
||||
async fn read(&self) -> anyhow::Result<(Vec<Stored>, Option<u64>)> {
|
||||
anyhow::ensure!(!self.fail, "the store is down");
|
||||
let (runs, revision) = self.state.lock().expect("unpoisoned").clone();
|
||||
Ok((runs, Some(revision).filter(|r| *r > 0)))
|
||||
}
|
||||
|
||||
async fn write(&self, runs: Vec<Stored>, revision: Option<u64>) -> anyhow::Result<bool> {
|
||||
let mut state = self.state.lock().expect("unpoisoned");
|
||||
let mut conflicts = self.conflicts.lock().expect("unpoisoned");
|
||||
if *conflicts > 0 {
|
||||
*conflicts -= 1;
|
||||
let mut other = record(&format!("other-{conflicts}"));
|
||||
other.trigger = Trigger::Review;
|
||||
state.0.insert(0, Stored::Run(other));
|
||||
state.1 += 1;
|
||||
}
|
||||
if revision.unwrap_or(0) != state.1 {
|
||||
return Ok(false);
|
||||
}
|
||||
*state = (runs, state.1 + 1);
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record(id: &str) -> RunRecord {
|
||||
RunRecord {
|
||||
id: id.to_owned(),
|
||||
trigger: Trigger::TryOut,
|
||||
repo: "o/r".to_owned(),
|
||||
pr: 7,
|
||||
requester: "alice".to_owned(),
|
||||
head_sha: Some("abc123".to_owned()),
|
||||
described: None,
|
||||
started_unix: 1_000,
|
||||
finished_unix: 1_060,
|
||||
outcome: RunOutcome::Done,
|
||||
detail: None,
|
||||
rows: None,
|
||||
overall: None,
|
||||
review_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn ids(runs: &[RunRecord]) -> Vec<&str> {
|
||||
runs.iter().map(|r| r.id.as_str()).collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_newest_hundred_survive_newest_first() {
|
||||
let doc = FakeDoc::default();
|
||||
for i in 0..=MAX_RUNS {
|
||||
push(&doc, &record(&format!("r{i}"))).await.expect("stored");
|
||||
}
|
||||
let runs = doc.runs();
|
||||
assert_eq!(runs.len(), 100);
|
||||
assert_eq!(runs[0].id, "r100");
|
||||
assert_eq!(runs[99].id, "r1", "r0, the oldest, is gone");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_write_that_lost_a_race_is_redone_on_the_winner() {
|
||||
let doc = FakeDoc::conflicting(2);
|
||||
push(&doc, &record("mine")).await.expect("stored");
|
||||
assert_eq!(ids(&doc.runs()), ["mine", "other-0", "other-1"]);
|
||||
|
||||
let doc = FakeDoc::conflicting(MAX_ATTEMPTS);
|
||||
let err = push(&doc, &record("mine")).await.expect_err("gives up");
|
||||
assert!(err.to_string().contains("conflicting writes"), "{err}");
|
||||
assert!(!ids(&doc.runs()).contains(&"mine"));
|
||||
}
|
||||
|
||||
/// The bucket on a real server: created on first use, written, read back.
|
||||
#[tokio::test]
|
||||
async fn runs_round_trip_through_the_bucket() {
|
||||
let nats = crate::test_nats::TestNats::start();
|
||||
let runs = Runs::Live(Some(nats.client().await));
|
||||
runs.record(record("a")).await;
|
||||
runs.record(record("b")).await;
|
||||
let listed = runs.list().await.expect("listed");
|
||||
assert_eq!(ids(&listed), ["b", "a"]);
|
||||
}
|
||||
|
||||
/// A record from a newer build among readable ones, and a document that
|
||||
/// is no list at all: listing and recording both keep working. The newer
|
||||
/// record is left out of the list and written back as it was; the
|
||||
/// non-list document is replaced by one this build decodes.
|
||||
#[tokio::test]
|
||||
async fn an_undecodable_record_is_kept_and_a_non_list_replaced() {
|
||||
let nats = crate::test_nats::TestNats::start();
|
||||
let client = nats.client().await;
|
||||
let Ok(store) = open(Some(&client)).await else {
|
||||
panic!("the bucket did not open");
|
||||
};
|
||||
let runs = Runs::Live(Some(client));
|
||||
let stored = || async {
|
||||
let entry = store.get(KEY).await.expect("readable").expect("a document");
|
||||
serde_json::from_slice::<Vec<serde_json::Value>>(&entry).expect("a JSON array")
|
||||
};
|
||||
|
||||
let mut newer = serde_json::to_value(record("newer")).expect("encodes");
|
||||
newer["outcome"] = "a-later-outcome".into();
|
||||
let doc = serde_json::json!([record("b"), newer, record("a")]);
|
||||
store
|
||||
.put(KEY, doc.to_string().into())
|
||||
.await
|
||||
.expect("written");
|
||||
assert_eq!(ids(&runs.list().await.expect("listed")), ["b", "a"]);
|
||||
runs.record(record("c")).await;
|
||||
assert_eq!(ids(&runs.list().await.expect("listed")), ["c", "b", "a"]);
|
||||
let after = stored().await;
|
||||
assert_eq!(after.len(), 4, "{after:?}");
|
||||
assert_eq!(after[2], newer, "kept untouched, in its place");
|
||||
|
||||
store
|
||||
.put(KEY, br#"{"not":"a list"}"#.to_vec().into())
|
||||
.await
|
||||
.expect("written");
|
||||
assert!(runs.list().await.expect("listed").is_empty());
|
||||
runs.record(record("d")).await;
|
||||
let after = stored().await;
|
||||
let decoded: Vec<RunRecord> = serde_json::from_value(after.into()).expect("decodes whole");
|
||||
assert_eq!(ids(&decoded), ["d"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unreadable_entry_counts_toward_the_hundred() {
|
||||
let doc = FakeDoc::default();
|
||||
{
|
||||
let mut state = doc.state.lock().expect("unpoisoned");
|
||||
state.0 = (0..MAX_RUNS - 1)
|
||||
.map(|i| Stored::Run(record(&format!("r{i}"))))
|
||||
.collect();
|
||||
state
|
||||
.0
|
||||
.insert(50, Stored::Unreadable(serde_json::json!({"from": "later"})));
|
||||
state.1 = 1;
|
||||
}
|
||||
push(&doc, &record("new")).await.expect("stored");
|
||||
let entries = doc.entries();
|
||||
assert_eq!(entries.len(), MAX_RUNS);
|
||||
assert!(entries.iter().any(|e| matches!(e, Stored::Unreadable(_))));
|
||||
assert_eq!(
|
||||
doc.runs().len(),
|
||||
MAX_RUNS - 1,
|
||||
"the unreadable entry took a run's place"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_route_lists_the_runs_newest_first_and_a_down_store_is_an_error() {
|
||||
let doc = Arc::new(FakeDoc::default());
|
||||
let mut reviewed = record("b");
|
||||
reviewed.trigger = Trigger::Review;
|
||||
reviewed.outcome = RunOutcome::NoVerdict;
|
||||
reviewed.detail = Some("the rules did not load".to_owned());
|
||||
reviewed.head_sha = None;
|
||||
push(&*doc, &record("a")).await.expect("stored");
|
||||
push(&*doc, &reviewed).await.expect("stored");
|
||||
|
||||
let get = |runs: Runs| async move {
|
||||
let (mut state, _) = crate::routes::tests::state_with_roster();
|
||||
state.runs = runs;
|
||||
let res = crate::startup::build_app(state)
|
||||
.oneshot(
|
||||
Request::get("/api/review-classifier/runs")
|
||||
.body(Body::empty())
|
||||
.expect("a request"),
|
||||
)
|
||||
.await
|
||||
.expect("infallible");
|
||||
let status = res.status();
|
||||
let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("a body");
|
||||
let body: serde_json::Value = serde_json::from_slice(&bytes).expect("JSON");
|
||||
(status, body)
|
||||
};
|
||||
let (status, body) = get(Runs::Fake(doc)).await;
|
||||
assert_eq!(status, StatusCode::OK, "{body}");
|
||||
assert_eq!(body[0]["id"], "b");
|
||||
assert_eq!(body[0]["trigger"], "review");
|
||||
assert_eq!(body[0]["outcome"], "no-verdict");
|
||||
assert_eq!(body[0]["detail"], "the rules did not load");
|
||||
assert!(body[0].get("head_sha").is_none(), "{body}");
|
||||
assert_eq!(body[1]["trigger"], "try-out");
|
||||
assert_eq!(body[1]["outcome"], "done");
|
||||
|
||||
let (status, body) = get(Runs::Fake(Arc::new(FakeDoc::failing()))).await;
|
||||
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{body}");
|
||||
let (status, body) = get(Runs::Live(None)).await;
|
||||
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{body}");
|
||||
assert_eq!(body["detail"], "no swarm queue is configured on this host");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_carries_no_diff_commit_text_or_cost() {
|
||||
let mut run = record("a");
|
||||
run.rows = Some(Vec::new());
|
||||
run.overall = Some(Overall::Approve);
|
||||
run.detail = Some("why".to_owned());
|
||||
run.review_url = Some("https://forge/o/r/pulls/7#issuecomment-1".to_owned());
|
||||
let value = serde_json::to_value(&run).expect("encodes");
|
||||
let mut keys: Vec<_> = value.as_object().expect("an object").keys().collect();
|
||||
keys.sort();
|
||||
assert_eq!(
|
||||
keys,
|
||||
[
|
||||
"detail",
|
||||
"finished_unix",
|
||||
"head_sha",
|
||||
"id",
|
||||
"outcome",
|
||||
"overall",
|
||||
"pr",
|
||||
"repo",
|
||||
"requester",
|
||||
"review_url",
|
||||
"rows",
|
||||
"started_unix",
|
||||
"trigger",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// Every field of every event, by name.
|
||||
#[derive(Clone, Default)]
|
||||
struct Fields(Arc<Mutex<Vec<(String, String)>>>);
|
||||
|
||||
impl tracing::field::Visit for Fields {
|
||||
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
|
||||
self.0
|
||||
.lock()
|
||||
.expect("unpoisoned")
|
||||
.push((field.name().to_owned(), format!("{value:?}")));
|
||||
}
|
||||
|
||||
fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
|
||||
self.0
|
||||
.lock()
|
||||
.expect("unpoisoned")
|
||||
.push((field.name().to_owned(), value.to_owned()));
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for Fields {
|
||||
fn on_event(
|
||||
&self,
|
||||
event: &tracing::Event<'_>,
|
||||
_: tracing_subscriber::layer::Context<'_, S>,
|
||||
) {
|
||||
event.record(&mut self.clone());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_log_event_carries_the_records_fields() {
|
||||
let mut run = record("a");
|
||||
run.trigger = Trigger::Review;
|
||||
run.outcome = RunOutcome::ChangesRequested;
|
||||
run.rows = Some(vec![Row {
|
||||
name: "datetime".to_owned(),
|
||||
polarity: Polarity::Positive,
|
||||
verdict: Verdict::NoMatch,
|
||||
certainty: 90,
|
||||
threshold: 80,
|
||||
counted: true,
|
||||
passed: false,
|
||||
reason: "No zone.".to_owned(),
|
||||
error: None,
|
||||
}]);
|
||||
run.overall = Some(Overall::RequestChanges);
|
||||
run.review_url = Some("https://forge/o/r/pulls/7#issuecomment-1".to_owned());
|
||||
let fields = Fields::default();
|
||||
let subscriber = tracing_subscriber::registry().with(fields.clone());
|
||||
tracing::subscriber::with_default(subscriber, || log(&run));
|
||||
|
||||
let got = fields.0.lock().expect("unpoisoned").clone();
|
||||
let field = |name: &str| {
|
||||
got.iter()
|
||||
.find(|(n, _)| n == name)
|
||||
.map_or_else(|| panic!("no {name} in {got:?}"), |(_, v)| v.clone())
|
||||
};
|
||||
assert_eq!(field("message"), EVENT);
|
||||
assert_eq!(field("id"), "a");
|
||||
assert_eq!(field("trigger"), "review");
|
||||
assert_eq!(field("repo"), "o/r");
|
||||
assert_eq!(field("pr"), "7");
|
||||
assert_eq!(field("requester"), "alice");
|
||||
assert_eq!(field("head_sha"), "abc123");
|
||||
assert_eq!(field("started_unix"), "1000");
|
||||
assert_eq!(field("finished_unix"), "1060");
|
||||
assert_eq!(field("outcome"), "changes-requested");
|
||||
assert_eq!(field("overall"), "request-changes");
|
||||
assert_eq!(
|
||||
field("review_url"),
|
||||
"https://forge/o/r/pulls/7#issuecomment-1"
|
||||
);
|
||||
let rows: Vec<Row> = serde_json::from_str(&field("rows")).expect("the rows as JSON");
|
||||
assert_eq!(Some(rows), run.rows);
|
||||
assert!(
|
||||
!got.iter().any(|(n, _)| n == "detail"),
|
||||
"an absent field is left out: {got:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
881
swarm-controller/src/review/review_classifier/settings.rs
Normal file
881
swarm-controller/src/review/review_classifier/settings.rs
Normal file
|
|
@ -0,0 +1,881 @@
|
|||
//! `GET` and `PUT /api/review-classifier/settings`: the runtime, model and
|
||||
//! effort every run uses, how many requested reviews run at once and how many
|
||||
//! classifications one run carries, for the whole swarm.
|
||||
//!
|
||||
//! The settings are one document under one key ([`KEY`] in [`BUCKET`]),
|
||||
//! which only this daemon reads or writes, as the schedule definitions are.
|
||||
//! No document is [`Settings::default`]. A try-out reads them when it starts
|
||||
//! and a review when it gets its place, and each sends the runtime, model and
|
||||
//! effort in its run request, so a change applies to the next run with no
|
||||
//! restart. A `PUT` changes only the fields its body names.
|
||||
|
||||
use std::future::Future;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use anyhow::Context as _;
|
||||
use async_nats::jetstream::kv::Store;
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::extract::rejection::JsonRejection;
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use problem_details::ProblemDetails;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use swarm_wire::agent_inference::Effort;
|
||||
use swarm_wire::review_classifier::{
|
||||
Acp, CLASSIFICATION_LIMITS, DEFAULT_MAX_CLASSIFICATIONS, Runtime,
|
||||
};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::routes::{AppState, error_problem, wanted_error_status};
|
||||
use crate::schedules::{queue, read_with, refused, write};
|
||||
|
||||
/// The bucket holding the settings. No other service holds a grant on it.
|
||||
pub const BUCKET: &str = "review-classifier-settings";
|
||||
|
||||
/// The one key in [`BUCKET`].
|
||||
pub const KEY: &str = "all";
|
||||
|
||||
/// How many times a losing writer re-reads and re-applies, as in
|
||||
/// `wanted::MAX_ATTEMPTS`.
|
||||
const MAX_ATTEMPTS: usize = 5;
|
||||
|
||||
/// What `max_concurrent_reviews` may be. Each running review is one `claude`
|
||||
/// at a time in the classifier's container, which has no bound of its own.
|
||||
pub(crate) const CONCURRENT_REVIEWS: RangeInclusive<usize> = 1..=8;
|
||||
|
||||
/// The review classifier's settings: the value under [`KEY`], and what both
|
||||
/// routes answer.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Settings {
|
||||
/// The model every classification on the API key runtime runs on, as
|
||||
/// claude's `--model` takes it: one word, not starting with `-`.
|
||||
pub(crate) model: String,
|
||||
/// One of `low`, `medium`, `high`, `xhigh`, `max`; `null` runs at the
|
||||
/// runtime's own default. An ACP agent gets it only where it offers it.
|
||||
#[serde(default)]
|
||||
#[schema(value_type = Option<String>)]
|
||||
pub(crate) effort: Option<Effort>,
|
||||
/// How many requested reviews run at once, 1 to 8. Try-outs don't count.
|
||||
pub(crate) max_concurrent_reviews: usize,
|
||||
/// The most classifications one run carries, 1 to 1000: a try-out, or a
|
||||
/// review of a repo whose rules file holds more, is refused above it. The
|
||||
/// classifications of a run go one after another, each for up to three
|
||||
/// minutes. A document stored before this field has the default.
|
||||
#[serde(default = "default_max_classifications")]
|
||||
pub(crate) max_classifications: usize,
|
||||
/// Whether a posted PR review lists only the rules that failed, rather than
|
||||
/// every rule with its result. A review with no failed rule says so in a
|
||||
/// line. A try-out shows every rule either way. A document stored before this
|
||||
/// field has `false`.
|
||||
#[serde(default)]
|
||||
pub(crate) failures_only: bool,
|
||||
/// What every classification runs on.
|
||||
#[serde(default)]
|
||||
pub(crate) runtime: RuntimeKind,
|
||||
/// The provider the `acp` runtime runs on. Kept while the runtime is
|
||||
/// `api-key`, so switching back and forth needs no re-entry.
|
||||
#[serde(default)]
|
||||
pub(crate) acp: Option<Acp>,
|
||||
}
|
||||
|
||||
/// Which runtime the classifications run on.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub(crate) enum RuntimeKind {
|
||||
/// `claude` on the classifier's Anthropic API key.
|
||||
#[default]
|
||||
ApiKey,
|
||||
/// An ACP agent on the classifier's ACP provider key, at [`Settings::acp`].
|
||||
Acp,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
model: swarm_wire::review_classifier::DEFAULT_MODEL.to_owned(),
|
||||
effort: None,
|
||||
max_concurrent_reviews: 2,
|
||||
max_classifications: DEFAULT_MAX_CLASSIFICATIONS,
|
||||
failures_only: false,
|
||||
runtime: RuntimeKind::ApiKey,
|
||||
acp: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_max_classifications() -> usize {
|
||||
DEFAULT_MAX_CLASSIFICATIONS
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
/// What is wrong with these settings, if anything.
|
||||
fn check(&self) -> Result<(), String> {
|
||||
crate::inference::check_model(&self.model, "model")?;
|
||||
if !CONCURRENT_REVIEWS.contains(&self.max_concurrent_reviews) {
|
||||
return Err(format!(
|
||||
"max_concurrent_reviews {} is not {} to {}",
|
||||
self.max_concurrent_reviews,
|
||||
CONCURRENT_REVIEWS.start(),
|
||||
CONCURRENT_REVIEWS.end()
|
||||
));
|
||||
}
|
||||
if !CLASSIFICATION_LIMITS.contains(&self.max_classifications) {
|
||||
return Err(format!(
|
||||
"max_classifications {} is not {} to {}",
|
||||
self.max_classifications,
|
||||
CLASSIFICATION_LIMITS.start(),
|
||||
CLASSIFICATION_LIMITS.end()
|
||||
));
|
||||
}
|
||||
if let Some(acp) = &self.acp {
|
||||
check_acp(acp)?;
|
||||
}
|
||||
self.runtime().map(|_| ())
|
||||
}
|
||||
|
||||
/// The runtime a run request carries. An `acp` runtime with no provider
|
||||
/// is an error rather than the API key runtime, which would send the PR
|
||||
/// to a provider nobody chose.
|
||||
pub(crate) fn runtime(&self) -> Result<Runtime, String> {
|
||||
match (self.runtime, &self.acp) {
|
||||
(RuntimeKind::ApiKey, _) => Ok(Runtime::ApiKey),
|
||||
(RuntimeKind::Acp, Some(acp)) => Ok(Runtime::Acp(acp.clone())),
|
||||
(RuntimeKind::Acp, None) => {
|
||||
Err("the runtime is `acp` but no `acp` provider is set".to_owned())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What is wrong with `acp`, if anything.
|
||||
fn check_acp(acp: &Acp) -> Result<(), String> {
|
||||
let url = url::Url::parse(&acp.base_url)
|
||||
.map_err(|e| format!("acp.base_url {:?} is not a URL: {e}", acp.base_url))?;
|
||||
if url.scheme() != "https" {
|
||||
return Err(format!("acp.base_url {:?} is not https://", acp.base_url));
|
||||
}
|
||||
if acp.model.is_empty()
|
||||
|| acp
|
||||
.model
|
||||
.chars()
|
||||
.any(|c| c.is_whitespace() || c.is_control())
|
||||
{
|
||||
return Err(format!(
|
||||
"acp.model {:?} is empty or has whitespace",
|
||||
acp.model
|
||||
));
|
||||
}
|
||||
let prices = &acp.prices;
|
||||
for (name, price) in [
|
||||
("input", Some(prices.input)),
|
||||
("output", Some(prices.output)),
|
||||
("cache_read", prices.cache_read),
|
||||
("cache_write", prices.cache_write),
|
||||
] {
|
||||
if price.is_some_and(|p| !p.is_finite() || p < 0.0) {
|
||||
return Err(format!("acp.prices.{name} is not a price of 0 or more"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The body of a `PUT`: any of the fields of [`Settings`]. A field left out
|
||||
/// keeps its stored value; `null` sets `effort` or `acp` to none.
|
||||
#[derive(Debug, Clone, Default, Deserialize, ToSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct SettingsUpdate {
|
||||
#[serde(default, deserialize_with = "present")]
|
||||
#[schema(value_type = Option<String>)]
|
||||
model: Option<String>,
|
||||
#[serde(default)]
|
||||
#[schema(value_type = Option<String>, nullable)]
|
||||
effort: Nullable<Effort>,
|
||||
#[serde(default, deserialize_with = "present")]
|
||||
#[schema(value_type = Option<usize>)]
|
||||
max_concurrent_reviews: Option<usize>,
|
||||
#[serde(default, deserialize_with = "present")]
|
||||
#[schema(value_type = Option<usize>)]
|
||||
max_classifications: Option<usize>,
|
||||
#[serde(default, deserialize_with = "present")]
|
||||
#[schema(value_type = Option<bool>)]
|
||||
failures_only: Option<bool>,
|
||||
#[serde(default, deserialize_with = "present")]
|
||||
#[schema(value_type = Option<RuntimeKind>)]
|
||||
runtime: Option<RuntimeKind>,
|
||||
#[serde(default)]
|
||||
#[schema(value_type = Option<Acp>, nullable)]
|
||||
acp: Nullable<Acp>,
|
||||
}
|
||||
|
||||
/// A field of a [`SettingsUpdate`] that may be `null`.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
enum Nullable<T> {
|
||||
/// Left out of the body.
|
||||
#[default]
|
||||
Absent,
|
||||
/// In the body, `None` for `null`.
|
||||
Present(Option<T>),
|
||||
}
|
||||
|
||||
impl<'de, T: Deserialize<'de>> Deserialize<'de> for Nullable<T> {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(value: D) -> Result<Self, D::Error> {
|
||||
Option::<T>::deserialize(value).map(Self::Present)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Nullable<T> {
|
||||
/// The value in the body, else `stored`.
|
||||
fn or(self, stored: Option<T>) -> Option<T> {
|
||||
match self {
|
||||
Self::Absent => stored,
|
||||
Self::Present(value) => value,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A field that is in the body, as its own type allows it: `null` only where
|
||||
/// that type is an `Option`.
|
||||
fn present<'de, T: Deserialize<'de>, D: serde::Deserializer<'de>>(
|
||||
value: D,
|
||||
) -> Result<Option<T>, D::Error> {
|
||||
T::deserialize(value).map(Some)
|
||||
}
|
||||
|
||||
impl SettingsUpdate {
|
||||
/// `stored` with this update's fields in place of its own.
|
||||
fn apply(self, stored: Settings) -> Settings {
|
||||
Settings {
|
||||
model: self.model.unwrap_or(stored.model),
|
||||
effort: self.effort.or(stored.effort),
|
||||
max_concurrent_reviews: self
|
||||
.max_concurrent_reviews
|
||||
.unwrap_or(stored.max_concurrent_reviews),
|
||||
max_classifications: self
|
||||
.max_classifications
|
||||
.unwrap_or(stored.max_classifications),
|
||||
failures_only: self.failures_only.unwrap_or(stored.failures_only),
|
||||
runtime: self.runtime.unwrap_or(stored.runtime),
|
||||
acp: self.acp.or(stored.acp),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a run reads the settings: the queue in production, a fake in the
|
||||
/// tests.
|
||||
pub(crate) trait SettingsSource {
|
||||
fn settings(&self) -> impl Future<Output = anyhow::Result<Settings>> + Send;
|
||||
}
|
||||
|
||||
impl SettingsSource for async_nats::Client {
|
||||
async fn settings(&self) -> anyhow::Result<Settings> {
|
||||
let (settings, _) = stored(&open(self).await?)
|
||||
.await
|
||||
.context("reading the review classifier's settings")?;
|
||||
Ok(settings)
|
||||
}
|
||||
}
|
||||
|
||||
/// The stored settings, with the revision to write them back against.
|
||||
async fn stored(store: &Store) -> anyhow::Result<(Settings, Option<u64>)> {
|
||||
read_with(store, KEY, |bytes| Ok(decode(bytes))).await
|
||||
}
|
||||
|
||||
/// Every field of [`Settings`]. `a_full_document_round_trips` fails when one
|
||||
/// is missing.
|
||||
const FIELDS: &[&str] = &[
|
||||
"model",
|
||||
"effort",
|
||||
"max_concurrent_reviews",
|
||||
"max_classifications",
|
||||
"failures_only",
|
||||
"runtime",
|
||||
"acp",
|
||||
];
|
||||
|
||||
/// `bytes`, the stored document, as settings. Unlike a `PUT` body, a field
|
||||
/// not in [`FIELDS`], such as one a newer build added, is ignored; a document
|
||||
/// that still does not decode is [`Settings::default`], with a warning,
|
||||
/// until the next `PUT` replaces it.
|
||||
fn decode(bytes: &[u8]) -> Settings {
|
||||
let decoded = serde_json::from_slice(bytes).and_then(|mut value: serde_json::Value| {
|
||||
if let Some(fields) = value.as_object_mut() {
|
||||
fields.retain(|name, _| FIELDS.contains(&name.as_str()));
|
||||
}
|
||||
serde_json::from_value(value)
|
||||
});
|
||||
decoded.unwrap_or_else(|e| {
|
||||
tracing::warn!(
|
||||
bucket = BUCKET, key = KEY, error = %e,
|
||||
"the review classifier settings are not decodable; using the defaults"
|
||||
);
|
||||
Settings::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// Open [`BUCKET`], creating it if nothing has yet.
|
||||
async fn open(client: &async_nats::Client) -> anyhow::Result<Store> {
|
||||
let js = async_nats::jetstream::new(client.clone());
|
||||
if let Ok(store) = js.get_key_value(BUCKET).await {
|
||||
return Ok(store);
|
||||
}
|
||||
js.create_key_value(async_nats::jetstream::kv::Config {
|
||||
bucket: BUCKET.to_owned(),
|
||||
description: "The review classifier's swarm-wide settings".to_owned(),
|
||||
history: 1,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.with_context(|| format!("creating the {BUCKET} bucket"))
|
||||
}
|
||||
|
||||
fn queue_problem(e: &anyhow::Error) -> ProblemDetails {
|
||||
tracing::warn!(error = %format!("{e:#}"), "review classifier settings: queue failure");
|
||||
error_problem(wanted_error_status(e), &format!("{e:#}"))
|
||||
}
|
||||
|
||||
/// Read the settings.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/review-classifier/settings",
|
||||
responses(
|
||||
(status = 200, description = "the settings in force; with none stored, \
|
||||
`{\"model\":\"haiku\",\"effort\":null,\"max_concurrent_reviews\":2,\
|
||||
\"max_classifications\":10,\"failures_only\":false,\"runtime\":\"api-key\",\"acp\":null}`",
|
||||
body = Settings),
|
||||
(status = 503, description = "no swarm queue is configured on this host, or it is \
|
||||
not connected (problem+json)", body = String),
|
||||
(status = 500, description = "the settings could not be read (problem+json)",
|
||||
body = String),
|
||||
),
|
||||
tag = "review-classifier"
|
||||
)]
|
||||
pub(crate) async fn get_settings(
|
||||
State(state): State<AppState>,
|
||||
) -> Result<Json<Settings>, ProblemDetails> {
|
||||
let client = queue(&state).map_err(refused)?;
|
||||
client
|
||||
.settings()
|
||||
.await
|
||||
.map(Json)
|
||||
.map_err(|e| queue_problem(&e))
|
||||
}
|
||||
|
||||
/// Change the settings.
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/api/review-classifier/settings",
|
||||
request_body = SettingsUpdate,
|
||||
responses(
|
||||
(status = 200, description = "the settings as stored: the body's fields over the \
|
||||
stored ones, which apply from the next run", body = Settings),
|
||||
(status = 400, description = "not JSON or not this shape: an unknown field, a \
|
||||
`null` other than for `effort` or `acp`, an effort other than the five \
|
||||
levels, a negative or non-integer `max_concurrent_reviews` or \
|
||||
`max_classifications`, a `failures_only` that is not a boolean, a runtime other \
|
||||
than `api-key` or `acp`, an `acp` without `base_url`, `model` or `prices`; or, \
|
||||
once applied, a model that is empty, has whitespace or starts with `-`, \
|
||||
`max_concurrent_reviews` outside 1 to 8, `max_classifications` outside 1 to \
|
||||
1000, an `acp.base_url` that is not \
|
||||
https://, an empty `acp.model` or one with whitespace, a negative price, or \
|
||||
the `acp` runtime with no `acp` provider (problem+json)", body = String),
|
||||
(status = 401, description = "the request carries no `Remote-User`, so there is no \
|
||||
operator to name (problem+json)", body = String),
|
||||
(status = 503, description = "no swarm queue is configured on this host, or it is \
|
||||
not connected (problem+json)", body = String),
|
||||
(status = 500, description = "the settings could not be written (problem+json)",
|
||||
body = String),
|
||||
),
|
||||
tag = "review-classifier"
|
||||
)]
|
||||
pub(crate) async fn put_settings(
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
body: Result<Json<SettingsUpdate>, JsonRejection>,
|
||||
) -> Result<Json<Settings>, ProblemDetails> {
|
||||
let operator = super::operator(&headers).ok_or_else(|| {
|
||||
error_problem(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"no Remote-User header: the gateway names the operator, and this request did not \
|
||||
come through it",
|
||||
)
|
||||
})?;
|
||||
let Json(update) = body.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.body_text()))?;
|
||||
let client = queue(&state).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))?;
|
||||
let value = update.clone().apply(current);
|
||||
value
|
||||
.check()
|
||||
.map_err(|why| error_problem(StatusCode::BAD_REQUEST, &why))?;
|
||||
if write(&store, KEY, &value, revision)
|
||||
.await
|
||||
.map_err(|e| queue_problem(&e))?
|
||||
{
|
||||
state.reviews.resize(value.max_concurrent_reviews);
|
||||
tracing::info!(%operator, ?value, "set the review classifier's settings");
|
||||
return Ok(Json(value));
|
||||
}
|
||||
}
|
||||
Err(queue_problem(&anyhow::anyhow!(
|
||||
"gave up writing the review classifier's settings after {MAX_ATTEMPTS} conflicting \
|
||||
writes"
|
||||
)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use axum::body::Body;
|
||||
use axum::http::Request;
|
||||
use tower::ServiceExt as _;
|
||||
|
||||
use super::*;
|
||||
use crate::test_nats::TestNats;
|
||||
|
||||
fn settings(json: &str) -> serde_json::Result<Settings> {
|
||||
serde_json::from_str(json)
|
||||
}
|
||||
|
||||
fn update(json: &str) -> serde_json::Result<SettingsUpdate> {
|
||||
serde_json::from_str(json)
|
||||
}
|
||||
|
||||
/// A valid ACP provider with every price set.
|
||||
fn provider() -> Acp {
|
||||
Acp {
|
||||
base_url: "https://llm.example/v1".to_owned(),
|
||||
model: "Qwen/Qwen3-35B".to_owned(),
|
||||
prices: swarm_wire::review_classifier::Prices {
|
||||
input: 0.5,
|
||||
output: 2.0,
|
||||
cache_read: Some(0.05),
|
||||
cache_write: Some(0.6),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_document_is_todays_values() {
|
||||
assert_eq!(
|
||||
serde_json::to_value(Settings::default()).unwrap(),
|
||||
serde_json::json!({
|
||||
"model": "haiku", "effort": null, "max_concurrent_reviews": 2,
|
||||
"max_classifications": 10, "failures_only": false, "runtime": "api-key", "acp": null,
|
||||
})
|
||||
);
|
||||
assert_eq!(Settings::default().runtime(), Ok(Runtime::ApiKey));
|
||||
}
|
||||
|
||||
/// Every field set, every `Option` `Some`: a stored document keeps all of
|
||||
/// them, so a field missing from [`FIELDS`] fails here.
|
||||
#[test]
|
||||
fn a_full_document_round_trips() {
|
||||
let full = Settings {
|
||||
model: "sonnet".to_owned(),
|
||||
effort: Some(Effort::High),
|
||||
max_concurrent_reviews: 5,
|
||||
max_classifications: 40,
|
||||
failures_only: true,
|
||||
runtime: RuntimeKind::Acp,
|
||||
acp: Some(provider()),
|
||||
};
|
||||
let encoded = serde_json::to_value(&full).unwrap();
|
||||
let mut keys: Vec<_> = encoded.as_object().unwrap().keys().collect();
|
||||
let mut fields = FIELDS.to_vec();
|
||||
keys.sort_unstable();
|
||||
fields.sort_unstable();
|
||||
assert_eq!(keys, fields);
|
||||
assert_eq!(decode(&serde_json::to_vec(&full).unwrap()), full);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_settings_are_refused() {
|
||||
for json in [
|
||||
r#"{"model":"","max_concurrent_reviews":2}"#,
|
||||
r#"{"model":"opus 4","max_concurrent_reviews":2}"#,
|
||||
r#"{"model":"--print","max_concurrent_reviews":2}"#,
|
||||
r#"{"model":"haiku","max_concurrent_reviews":0}"#,
|
||||
r#"{"model":"haiku","max_concurrent_reviews":9}"#,
|
||||
] {
|
||||
assert!(settings(json).unwrap().check().is_err(), "{json}");
|
||||
}
|
||||
// Control: the bounds themselves, and a full model id.
|
||||
for json in [
|
||||
r#"{"model":"claude-haiku-4-5","max_concurrent_reviews":1}"#,
|
||||
r#"{"model":"haiku","effort":"max","max_concurrent_reviews":8}"#,
|
||||
] {
|
||||
assert!(settings(json).unwrap().check().is_ok(), "{json}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rules_per_run_limit_is_one_to_a_thousand_and_ten_until_set() {
|
||||
for count in [0, 1001, 5000] {
|
||||
let bad = Settings {
|
||||
max_classifications: count,
|
||||
..Settings::default()
|
||||
};
|
||||
assert!(bad.check().is_err(), "{count}");
|
||||
}
|
||||
for count in [1, 10, 1000] {
|
||||
let ok = Settings {
|
||||
max_classifications: count,
|
||||
..Settings::default()
|
||||
};
|
||||
assert!(ok.check().is_ok(), "{count}");
|
||||
}
|
||||
// A document stored before the field existed decodes with the default.
|
||||
let old = r#"{"model":"haiku","effort":null,"max_concurrent_reviews":2}"#;
|
||||
assert_eq!(decode(old.as_bytes()).max_classifications, 10);
|
||||
// An update changes it alone.
|
||||
let raised = update(r#"{"max_classifications":300}"#)
|
||||
.unwrap()
|
||||
.apply(Settings::default());
|
||||
assert_eq!(
|
||||
raised,
|
||||
Settings {
|
||||
max_classifications: 300,
|
||||
..Settings::default()
|
||||
}
|
||||
);
|
||||
assert!(update(r#"{"max_classifications":null}"#).is_err());
|
||||
assert!(update(r#"{"max_classifications":-1}"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_acp_provider_is_refused() {
|
||||
let with = |change: fn(&mut Acp)| {
|
||||
let mut acp = provider();
|
||||
change(&mut acp);
|
||||
Settings {
|
||||
runtime: RuntimeKind::Acp,
|
||||
acp: Some(acp),
|
||||
..Settings::default()
|
||||
}
|
||||
};
|
||||
for (why, bad) in [
|
||||
(
|
||||
"http",
|
||||
with(|a| a.base_url = "http://llm.example/v1".to_owned()),
|
||||
),
|
||||
("no URL", with(|a| a.base_url = "llm.example".to_owned())),
|
||||
(
|
||||
"ftp",
|
||||
with(|a| a.base_url = "ftp://llm.example/v1".to_owned()),
|
||||
),
|
||||
("empty model", with(|a| a.model = String::new())),
|
||||
(
|
||||
"model with a space",
|
||||
with(|a| a.model = "qwen 3".to_owned()),
|
||||
),
|
||||
("negative input", with(|a| a.prices.input = -1.0)),
|
||||
("negative output", with(|a| a.prices.output = -1.0)),
|
||||
(
|
||||
"negative cache read",
|
||||
with(|a| a.prices.cache_read = Some(-0.1)),
|
||||
),
|
||||
(
|
||||
"negative cache write",
|
||||
with(|a| a.prices.cache_write = Some(-0.1)),
|
||||
),
|
||||
("infinite", with(|a| a.prices.input = f64::INFINITY)),
|
||||
] {
|
||||
assert!(bad.check().is_err(), "{why}");
|
||||
}
|
||||
// Control: the valid provider, and one with free tokens and no cache
|
||||
// prices.
|
||||
assert!(with(|_| ()).check().is_ok());
|
||||
let free = with(|a| {
|
||||
a.prices.input = 0.0;
|
||||
a.prices.cache_read = None;
|
||||
a.prices.cache_write = None;
|
||||
});
|
||||
assert!(free.check().is_ok());
|
||||
assert_eq!(free.runtime(), Ok(Runtime::Acp(free.acp.clone().unwrap())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_acp_runtime_without_a_provider_is_refused_not_run_on_the_api_key() {
|
||||
let missing = Settings {
|
||||
runtime: RuntimeKind::Acp,
|
||||
..Settings::default()
|
||||
};
|
||||
assert!(missing.runtime().is_err());
|
||||
assert!(missing.check().is_err());
|
||||
// Control: a provider kept while the runtime is the API key's is
|
||||
// fine, and runs on the API key.
|
||||
let kept = Settings {
|
||||
acp: Some(provider()),
|
||||
..Settings::default()
|
||||
};
|
||||
assert!(kept.check().is_ok());
|
||||
assert_eq!(kept.runtime(), Ok(Runtime::ApiKey));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_shape_does_not_decode() {
|
||||
for json in [
|
||||
r#"{"model":null}"#,
|
||||
r#"{"max_concurrent_reviews":null}"#,
|
||||
r#"{"runtime":null}"#,
|
||||
r#"{"effort":"extreme"}"#,
|
||||
r#"{"effort":"HIGH"}"#,
|
||||
r#"{"max_concurrent_reviews":-1}"#,
|
||||
r#"{"max_concurrent_reviews":2.5}"#,
|
||||
r#"{"api_key":"x"}"#,
|
||||
r#"{"runtime":"subscription"}"#,
|
||||
r#"{"acp":{"base_url":"https://x","model":"m"}}"#,
|
||||
r#"{"acp":{"base_url":"https://x","model":"m","prices":{"input":1}}}"#,
|
||||
r#"{"acp":{"base_url":"https://x","model":"m","prices":{"input":1,"output":1},"api_key":"x"}}"#,
|
||||
] {
|
||||
assert!(update(json).is_err(), "{json}");
|
||||
}
|
||||
// Control: every field may be left out, and `effort` and `acp` may be
|
||||
// null.
|
||||
let empty = update("{}").unwrap();
|
||||
assert_eq!(empty.apply(Settings::default()), Settings::default());
|
||||
let cleared = update(r#"{"effort":null,"acp":null}"#).unwrap();
|
||||
assert_eq!(
|
||||
(cleared.effort, cleared.acp),
|
||||
(Nullable::Present(None), Nullable::Present(None)),
|
||||
"null is a value, not a field left out"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_update_changes_only_the_fields_it_names() {
|
||||
let stored = Settings {
|
||||
model: "sonnet".to_owned(),
|
||||
effort: Some(Effort::High),
|
||||
max_concurrent_reviews: 3,
|
||||
max_classifications: 25,
|
||||
failures_only: true,
|
||||
runtime: RuntimeKind::Acp,
|
||||
acp: Some(provider()),
|
||||
};
|
||||
let model_only = update(r#"{"model":"opus"}"#).unwrap().apply(stored.clone());
|
||||
assert_eq!(
|
||||
model_only,
|
||||
Settings {
|
||||
model: "opus".to_owned(),
|
||||
..stored.clone()
|
||||
}
|
||||
);
|
||||
let cleared = update(r#"{"effort":null,"runtime":"api-key","acp":null}"#)
|
||||
.unwrap()
|
||||
.apply(stored.clone());
|
||||
assert_eq!(
|
||||
cleared,
|
||||
Settings {
|
||||
effort: None,
|
||||
runtime: RuntimeKind::ApiKey,
|
||||
acp: None,
|
||||
..stored
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/// An app whose queue is `nats`.
|
||||
async fn app(nats: &TestNats) -> (axum::Router, AppState) {
|
||||
let (mut state, _) = crate::routes::tests::state_with_roster();
|
||||
state.status = Some(std::sync::Arc::new(crate::status::StatusReader::new(
|
||||
nats.client().await,
|
||||
std::time::Duration::from_mins(1),
|
||||
)));
|
||||
(crate::startup::build_app(state.clone()), state)
|
||||
}
|
||||
|
||||
async fn send(
|
||||
app: &axum::Router,
|
||||
req: Request<Body>,
|
||||
) -> (StatusCode, serde_json::Value, Option<String>) {
|
||||
let res = app.clone().oneshot(req).await.expect("infallible");
|
||||
let status = res.status();
|
||||
let kind = res
|
||||
.headers()
|
||||
.get("content-type")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::to_owned);
|
||||
let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("a body");
|
||||
(
|
||||
status,
|
||||
serde_json::from_slice(&bytes).unwrap_or_default(),
|
||||
kind,
|
||||
)
|
||||
}
|
||||
|
||||
fn get() -> Request<Body> {
|
||||
Request::get("/api/review-classifier/settings")
|
||||
.body(Body::empty())
|
||||
.expect("a request")
|
||||
}
|
||||
|
||||
fn put(body: &str) -> Request<Body> {
|
||||
Request::put("/api/review-classifier/settings")
|
||||
.header("content-type", "application/json")
|
||||
.header("remote-user", "alice")
|
||||
.body(Body::from(body.to_owned()))
|
||||
.expect("a request")
|
||||
}
|
||||
|
||||
/// A stored field this build does not know is ignored, and a document
|
||||
/// that still does not decode reads as the defaults; either way the GET
|
||||
/// and a run's read keep working, and a PUT, even of the defaults,
|
||||
/// replaces it with one that decodes.
|
||||
#[tokio::test]
|
||||
async fn an_undecodable_document_reads_as_the_defaults_until_a_put() {
|
||||
let nats = TestNats::start();
|
||||
let (app, _) = app(&nats).await;
|
||||
let client = nats.client().await;
|
||||
let store = open(&client).await.expect("the bucket");
|
||||
let defaults = serde_json::to_value(Settings::default()).unwrap();
|
||||
|
||||
let newer = serde_json::json!({
|
||||
"model": "sonnet", "effort": "high", "max_concurrent_reviews": 3, "later": true,
|
||||
});
|
||||
store
|
||||
.put(KEY, newer.to_string().into())
|
||||
.await
|
||||
.expect("written");
|
||||
let (status, read, _) = send(&app, get()).await;
|
||||
assert_eq!(status, StatusCode::OK, "{read}");
|
||||
assert_eq!(
|
||||
read,
|
||||
serde_json::json!({
|
||||
"model": "sonnet", "effort": "high", "max_concurrent_reviews": 3,
|
||||
"max_classifications": 10, "failures_only": false, "runtime": "api-key", "acp": null,
|
||||
})
|
||||
);
|
||||
|
||||
store
|
||||
.put(
|
||||
KEY,
|
||||
br#"{"model":"sonnet","effort":"later"}"#.to_vec().into(),
|
||||
)
|
||||
.await
|
||||
.expect("written");
|
||||
let (status, read, _) = send(&app, get()).await;
|
||||
assert_eq!(status, StatusCode::OK, "{read}");
|
||||
assert_eq!(read, defaults);
|
||||
assert_eq!(
|
||||
client.settings().await.expect("readable"),
|
||||
Settings::default()
|
||||
);
|
||||
|
||||
let (status, stored, _) = send(&app, put(&defaults.to_string())).await;
|
||||
assert_eq!(status, StatusCode::OK, "{stored}");
|
||||
let entry = store.get(KEY).await.expect("readable").expect("a document");
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<Settings>(&entry).expect("decodes strictly"),
|
||||
Settings::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_put_is_what_the_get_and_the_next_run_read() {
|
||||
let nats = TestNats::start();
|
||||
let (app, state) = app(&nats).await;
|
||||
let (status, before, _) = send(&app, get()).await;
|
||||
assert_eq!(status, StatusCode::OK, "{before}");
|
||||
assert_eq!(before, serde_json::to_value(Settings::default()).unwrap());
|
||||
|
||||
let wanted = serde_json::json!({
|
||||
"model": "sonnet", "effort": "high", "max_concurrent_reviews": 5,
|
||||
"max_classifications": 10, "failures_only": false, "runtime": "api-key", "acp": null,
|
||||
});
|
||||
let (status, stored, _) = send(&app, put(&wanted.to_string())).await;
|
||||
assert_eq!(status, StatusCode::OK, "{stored}");
|
||||
assert_eq!(stored, wanted);
|
||||
let (_, after, _) = send(&app, get()).await;
|
||||
assert_eq!(after, wanted);
|
||||
assert_eq!(state.reviews.limit(), 5);
|
||||
|
||||
let client = nats.client().await;
|
||||
let read = client.settings().await.expect("readable");
|
||||
assert_eq!(
|
||||
(read.model.as_str(), read.effort),
|
||||
("sonnet", Some(Effort::High))
|
||||
);
|
||||
|
||||
// The same value again is no conflict.
|
||||
let (status, _, _) = send(&app, put(&wanted.to_string())).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
}
|
||||
|
||||
/// The swarm UI's settings form PUTs the model, effort and limit alone;
|
||||
/// that save keeps the runtime and the provider.
|
||||
#[tokio::test]
|
||||
async fn a_put_without_the_runtime_keeps_the_stored_one() {
|
||||
let nats = TestNats::start();
|
||||
let (app, _) = app(&nats).await;
|
||||
let acp = serde_json::to_value(provider()).unwrap();
|
||||
let switch = serde_json::json!({ "runtime": "acp", "acp": acp });
|
||||
let (status, stored, _) = send(&app, put(&switch.to_string())).await;
|
||||
assert_eq!(status, StatusCode::OK, "{stored}");
|
||||
assert_eq!(stored["model"], "haiku", "the rest kept its defaults");
|
||||
|
||||
let form = r#"{"model":"sonnet","effort":null,"max_concurrent_reviews":4}"#;
|
||||
let (status, stored, _) = send(&app, put(form)).await;
|
||||
assert_eq!(status, StatusCode::OK, "{stored}");
|
||||
let (_, after, _) = send(&app, get()).await;
|
||||
assert_eq!(
|
||||
after,
|
||||
serde_json::json!({
|
||||
"model": "sonnet", "effort": null, "max_concurrent_reviews": 4,
|
||||
"max_classifications": 10, "failures_only": false, "runtime": "acp", "acp": acp,
|
||||
})
|
||||
);
|
||||
let read = nats.client().await.settings().await.expect("readable");
|
||||
assert_eq!(read.runtime(), Ok(Runtime::Acp(provider())));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_refused_put_is_a_problem_and_changes_nothing() {
|
||||
let nats = TestNats::start();
|
||||
let (app, state) = app(&nats).await;
|
||||
for bad in [
|
||||
"not json",
|
||||
r#"{"model":null}"#,
|
||||
r#"{"model":"haiku","effort":"extreme","max_concurrent_reviews":2}"#,
|
||||
r#"{"model":"-x","max_concurrent_reviews":2}"#,
|
||||
r#"{"model":"haiku","max_concurrent_reviews":9}"#,
|
||||
r#"{"runtime":"acp"}"#,
|
||||
r#"{"acp":{"base_url":"http://x","model":"m","prices":{"input":1,"output":1}}}"#,
|
||||
] {
|
||||
let (status, problem, kind) = send(&app, put(bad)).await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST, "{bad}: {problem}");
|
||||
assert!(problem["detail"].is_string(), "{bad}: {problem}");
|
||||
assert_eq!(kind.as_deref(), Some("application/problem+json"), "{bad}");
|
||||
}
|
||||
let (_, after, _) = send(&app, get()).await;
|
||||
assert_eq!(after, serde_json::to_value(Settings::default()).unwrap());
|
||||
assert_eq!(state.reviews.limit(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_put_without_an_operator_is_401() {
|
||||
let (state, _) = crate::routes::tests::state_with_roster();
|
||||
let req = Request::put("/api/review-classifier/settings")
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(
|
||||
serde_json::to_string(&Settings::default()).unwrap(),
|
||||
))
|
||||
.expect("a request");
|
||||
let (status, _, _) = send(&crate::startup::build_app(state), req).await;
|
||||
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn without_a_queue_both_verbs_are_503() {
|
||||
let (state, _) = crate::routes::tests::state_with_roster();
|
||||
let app = crate::startup::build_app(state);
|
||||
let (status, _, _) = send(&app, get()).await;
|
||||
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
let body = serde_json::to_string(&Settings::default()).unwrap();
|
||||
let (status, _, _) = send(&app, put(&body)).await;
|
||||
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue