swarm-controller: move the observability concern into its own module
Refs #6897
This commit is contained in:
parent
9b2ba275d8
commit
cd8feedf73
5 changed files with 32 additions and 27 deletions
391
swarm-controller/src/observability/alerts.rs
Normal file
391
swarm-controller/src/observability/alerts.rs
Normal file
|
|
@ -0,0 +1,391 @@
|
|||
//! `GET /api/alerts`: the alerts the swarm's Grafana holds right now, read at
|
||||
//! request time for swarm-ui's alerts page.
|
||||
//!
|
||||
//! Grafana's URL comes from `swarm-controller.nix`
|
||||
//! (`SWARM_CONTROLLER_GRAFANA_URL`). The token is a Viewer service account's,
|
||||
//! read from the swarm's secret store at
|
||||
//! `swarm_secret_client::grafana::controller_token_path` under this daemon's
|
||||
//! own certificate. `swarm-bao-grafana-controller-token`, on Grafana's host,
|
||||
//! mints it and replaces it whenever Grafana refuses the stored one, so a 401
|
||||
//! here re-reads the store once before giving up.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use problem_details::ProblemDetails;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::routes::{AppState, error_problem};
|
||||
|
||||
/// The env var `swarm-controller.nix` sets.
|
||||
const URL_ENV: &str = "SWARM_CONTROLLER_GRAFANA_URL";
|
||||
|
||||
/// Grafana's Prometheus-compatible list of alert instances, relative to its
|
||||
/// base URL. Instances in the `Normal` state are not listed.
|
||||
const ALERTS_PATH: &str = "api/prometheus/grafana/api/v1/alerts";
|
||||
|
||||
/// Bound on reaching Grafana.
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
/// Bound on one whole request to Grafana, body included.
|
||||
const TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
type TokenFuture = Pin<Box<dyn Future<Output = Result<String>> + Send>>;
|
||||
|
||||
/// Where the token comes from: the store in the daemon, a stand-in in tests.
|
||||
pub(crate) type TokenSource = Arc<dyn Fn() -> TokenFuture + Send + Sync>;
|
||||
|
||||
/// One alert instance, as `GET /api/alerts` serves it.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, ToSchema)]
|
||||
pub(crate) struct Alert {
|
||||
/// The rule's title (Grafana's `alertname` label).
|
||||
pub name: String,
|
||||
/// Grafana's state for the instance: `Alerting`, `Pending`, `NoData` or
|
||||
/// `Error`.
|
||||
pub state: String,
|
||||
/// When the instance entered its state, RFC 3339, as Grafana reports it.
|
||||
pub active_at: Option<String>,
|
||||
/// The rule's `summary` annotation, templated by Grafana.
|
||||
pub summary: Option<String>,
|
||||
/// Every label of the instance, as Grafana reports them.
|
||||
pub labels: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PromResponse {
|
||||
data: PromData,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PromData {
|
||||
alerts: Vec<PromAlert>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PromAlert {
|
||||
#[serde(default)]
|
||||
labels: BTreeMap<String, String>,
|
||||
#[serde(default)]
|
||||
annotations: BTreeMap<String, String>,
|
||||
state: String,
|
||||
#[serde(rename = "activeAt")]
|
||||
active_at: Option<String>,
|
||||
}
|
||||
|
||||
impl From<PromAlert> for Alert {
|
||||
fn from(a: PromAlert) -> Self {
|
||||
Self {
|
||||
name: a.labels.get("alertname").cloned().unwrap_or_default(),
|
||||
state: a.state,
|
||||
active_at: a.active_at,
|
||||
summary: a.annotations.get("summary").cloned(),
|
||||
labels: a.labels,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Grafana's alerts API, with the token last read from the store.
|
||||
pub(crate) struct Grafana {
|
||||
http: reqwest::Client,
|
||||
alerts_url: url::Url,
|
||||
source: TokenSource,
|
||||
token: tokio::sync::Mutex<Option<String>>,
|
||||
}
|
||||
|
||||
impl Grafana {
|
||||
/// # Errors
|
||||
/// A base URL the alerts path cannot be joined onto, or a client that
|
||||
/// cannot be built.
|
||||
pub(crate) fn new(base: &url::Url, source: TokenSource, timeout: Duration) -> Result<Self> {
|
||||
let http = reqwest::Client::builder()
|
||||
.connect_timeout(CONNECT_TIMEOUT)
|
||||
.timeout(timeout)
|
||||
.build()
|
||||
.context("building the Grafana HTTP client")?;
|
||||
Ok(Self {
|
||||
http,
|
||||
alerts_url: base
|
||||
.join(ALERTS_PATH)
|
||||
.with_context(|| format!("joining {ALERTS_PATH} onto {base}"))?,
|
||||
source,
|
||||
token: tokio::sync::Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
/// The held token, or a fresh one from the source when `reread` or none is
|
||||
/// held yet.
|
||||
async fn token(&self, reread: bool) -> Result<String> {
|
||||
let mut held = self.token.lock().await;
|
||||
if let Some(t) = held.as_ref().filter(|_| !reread) {
|
||||
return Ok(t.clone());
|
||||
}
|
||||
let fresh = (self.source)().await?;
|
||||
*held = Some(fresh.clone());
|
||||
Ok(fresh)
|
||||
}
|
||||
|
||||
async fn get(&self, token: &str) -> Result<reqwest::Response> {
|
||||
self.http
|
||||
.get(self.alerts_url.clone())
|
||||
.bearer_auth(token)
|
||||
.send()
|
||||
.await
|
||||
.with_context(|| format!("GET {}", self.alerts_url))
|
||||
}
|
||||
|
||||
/// Every alert instance Grafana lists now.
|
||||
///
|
||||
/// # Errors
|
||||
/// No token in the store, Grafana unreachable or slower than the client's
|
||||
/// timeout, a 401 for both the held token and a re-read one, any other
|
||||
/// non-success status, or a body that is not the alerts shape.
|
||||
pub(crate) async fn alerts(&self) -> Result<Vec<Alert>> {
|
||||
let mut res = self.get(&self.token(false).await?).await?;
|
||||
if res.status() == reqwest::StatusCode::UNAUTHORIZED {
|
||||
res = self.get(&self.token(true).await?).await?;
|
||||
}
|
||||
let status = res.status();
|
||||
if !status.is_success() {
|
||||
anyhow::bail!("Grafana answered {status} to GET {}", self.alerts_url);
|
||||
}
|
||||
let body: PromResponse = res
|
||||
.json()
|
||||
.await
|
||||
.with_context(|| format!("reading Grafana's answer to GET {}", self.alerts_url))?;
|
||||
Ok(body.data.alerts.into_iter().map(Alert::from).collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// One login and one read. An empty value is refused like an absent one.
|
||||
async fn token_from_store() -> Result<String> {
|
||||
let path = swarm_secret_client::grafana::controller_token_path()?;
|
||||
let store = crate::store::connect()
|
||||
.await
|
||||
.context("logging in to the swarm secret store")?;
|
||||
let stored: Option<swarm_secret_client::grafana::ControllerToken> = store
|
||||
.read_optional(&path)
|
||||
.await
|
||||
.with_context(|| format!("reading {path}"))?;
|
||||
match stored {
|
||||
Some(t) if !t.value.trim().is_empty() => Ok(t.value.trim().to_owned()),
|
||||
_ => anyhow::bail!(
|
||||
"nothing at {path}: swarm-bao-grafana-controller-token, on the host that runs \
|
||||
Grafana, has not stored this daemon's Grafana token"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The daemon's Grafana client, or `None` when `SWARM_CONTROLLER_GRAFANA_URL`
|
||||
/// is unset or unusable, which is logged.
|
||||
pub(crate) fn from_env() -> Option<Arc<Grafana>> {
|
||||
let raw = std::env::var(URL_ENV).ok()?;
|
||||
let built = url::Url::parse(&raw)
|
||||
.with_context(|| format!("parse {URL_ENV} ({raw}) as a URL"))
|
||||
.and_then(|base| {
|
||||
let source: TokenSource = Arc::new(|| Box::pin(token_from_store()));
|
||||
Grafana::new(&base, source, TIMEOUT)
|
||||
});
|
||||
match built {
|
||||
Ok(g) => Some(Arc::new(g)),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %format!("{e:#}"), "Grafana misconfigured; /api/alerts is off");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The alerts the swarm's Grafana holds now: firing, pending, and those whose
|
||||
/// rule has no data or failed to evaluate.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/alerts",
|
||||
responses(
|
||||
(status = 200, description = "every alert instance Grafana lists now", body = Vec<Alert>),
|
||||
(status = 503, description = "no Grafana is configured here, its token is not in the store \
|
||||
yet, or Grafana refused, failed or did not answer in time (problem+json)", body = String),
|
||||
),
|
||||
tag = "alerts"
|
||||
)]
|
||||
pub(crate) async fn get_alerts(
|
||||
State(state): State<AppState>,
|
||||
) -> Result<Json<Vec<Alert>>, ProblemDetails> {
|
||||
let Some(grafana) = state.alerts.as_ref() else {
|
||||
return Err(error_problem(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"no Grafana is configured on this host",
|
||||
));
|
||||
};
|
||||
grafana.alerts().await.map(Json).map_err(|e| {
|
||||
let detail = format!("{e:#}");
|
||||
tracing::warn!(error = %detail, "reading Grafana's alerts failed");
|
||||
error_problem(StatusCode::SERVICE_UNAVAILABLE, &detail)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::body::Body;
|
||||
use axum::http::{HeaderMap, Request};
|
||||
use std::sync::Mutex;
|
||||
use tower::ServiceExt as _;
|
||||
|
||||
/// What the stand-in Grafana answers to a request with the accepted token.
|
||||
const ALERTS_BODY: &str = r#"{"status":"success","data":{"alerts":[{
|
||||
"labels":{"alertname":"swarm queue connect failed","hive":"pr1ma","agent":"atlas"},
|
||||
"annotations":{"summary":"pr1ma/atlas could not connect"},
|
||||
"state":"Alerting","activeAt":"2026-10-15T09:00:00Z","value":"1e+00"}]}}"#;
|
||||
|
||||
/// A stand-in Grafana on a loopback port: the alerts path answers
|
||||
/// [`ALERTS_BODY`] to `Bearer <accepts>` and 401 to anything else, after
|
||||
/// `delay`.
|
||||
async fn fake_grafana(accepts: &'static str, delay: Duration) -> url::Url {
|
||||
let app = axum::Router::new().route(
|
||||
&format!("/{ALERTS_PATH}"),
|
||||
axum::routing::get(move |headers: HeaderMap| async move {
|
||||
tokio::time::sleep(delay).await;
|
||||
let ok = headers
|
||||
.get(axum::http::header::AUTHORIZATION)
|
||||
.is_some_and(|v| v == format!("Bearer {accepts}").as_str());
|
||||
if ok {
|
||||
(StatusCode::OK, ALERTS_BODY)
|
||||
} else {
|
||||
(StatusCode::UNAUTHORIZED, "")
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await });
|
||||
url::Url::parse(&format!("http://{addr}/")).unwrap()
|
||||
}
|
||||
|
||||
/// A token source handing out `tokens` in order, the last one forever,
|
||||
/// counting its calls.
|
||||
fn tokens(tokens: &'static [&'static str]) -> (TokenSource, Arc<Mutex<usize>>) {
|
||||
let calls = Arc::new(Mutex::new(0));
|
||||
let counted = Arc::clone(&calls);
|
||||
let source: TokenSource = Arc::new(move || {
|
||||
let mut n = counted.lock().unwrap();
|
||||
let t = tokens[(*n).min(tokens.len() - 1)];
|
||||
*n += 1;
|
||||
Box::pin(async move { Ok(t.to_owned()) })
|
||||
});
|
||||
(source, calls)
|
||||
}
|
||||
|
||||
async fn get_alerts_with(grafana: Option<Grafana>) -> (StatusCode, serde_json::Value) {
|
||||
let (mut state, _) = crate::routes::tests::state_with_roster();
|
||||
state.alerts = grafana.map(Arc::new);
|
||||
let req = Request::get("/api/alerts")
|
||||
.body(Body::empty())
|
||||
.expect("a request");
|
||||
let res = crate::startup::build_app(state)
|
||||
.oneshot(req)
|
||||
.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 serves_grafanas_alerts_read_with_the_stored_token() {
|
||||
let base = fake_grafana("viewer-token", Duration::ZERO).await;
|
||||
let (source, calls) = tokens(&["viewer-token"]);
|
||||
let grafana = Grafana::new(&base, source, TIMEOUT).unwrap();
|
||||
let (status, body) = get_alerts_with(Some(grafana)).await;
|
||||
assert_eq!(status, StatusCode::OK, "{body}");
|
||||
assert_eq!(
|
||||
body,
|
||||
serde_json::json!([{
|
||||
"name": "swarm queue connect failed",
|
||||
"state": "Alerting",
|
||||
"active_at": "2026-10-15T09:00:00Z",
|
||||
"summary": "pr1ma/atlas could not connect",
|
||||
"labels": {
|
||||
"alertname": "swarm queue connect failed",
|
||||
"hive": "pr1ma",
|
||||
"agent": "atlas",
|
||||
},
|
||||
}])
|
||||
);
|
||||
assert_eq!(*calls.lock().unwrap(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_held_token_is_reused_across_requests() {
|
||||
let base = fake_grafana("viewer-token", Duration::ZERO).await;
|
||||
let (source, calls) = tokens(&["viewer-token"]);
|
||||
let grafana = Grafana::new(&base, source, TIMEOUT).unwrap();
|
||||
grafana.alerts().await.unwrap();
|
||||
grafana.alerts().await.unwrap();
|
||||
assert_eq!(*calls.lock().unwrap(), 1);
|
||||
}
|
||||
|
||||
/// The minting unit replaces a token Grafana refuses, so a 401 re-reads
|
||||
/// the store and sends the request once more.
|
||||
#[tokio::test]
|
||||
async fn a_refused_token_is_read_again_from_the_store() {
|
||||
let base = fake_grafana("replaced", Duration::ZERO).await;
|
||||
let (source, calls) = tokens(&["stale", "replaced"]);
|
||||
let grafana = Grafana::new(&base, source, TIMEOUT).unwrap();
|
||||
let alerts = grafana.alerts().await.unwrap();
|
||||
assert_eq!(alerts.len(), 1);
|
||||
assert_eq!(*calls.lock().unwrap(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_token_refused_twice_is_a_503_naming_the_status() {
|
||||
let base = fake_grafana("replaced", Duration::ZERO).await;
|
||||
let (source, calls) = tokens(&["stale"]);
|
||||
let grafana = Grafana::new(&base, source, TIMEOUT).unwrap();
|
||||
let (status, body) = get_alerts_with(Some(grafana)).await;
|
||||
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert!(body["detail"].as_str().unwrap().contains("401"), "{body}");
|
||||
assert_eq!(*calls.lock().unwrap(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_grafana_slower_than_the_timeout_is_a_503() {
|
||||
let base = fake_grafana("viewer-token", Duration::from_secs(5)).await;
|
||||
let (source, _) = tokens(&["viewer-token"]);
|
||||
let grafana = Grafana::new(&base, source, Duration::from_millis(200)).unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
let (status, _) = get_alerts_with(Some(grafana)).await;
|
||||
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert!(started.elapsed() < Duration::from_secs(4));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_token_in_the_store_is_a_503_saying_so() {
|
||||
let base = fake_grafana("viewer-token", Duration::ZERO).await;
|
||||
let source: TokenSource =
|
||||
Arc::new(|| Box::pin(async { anyhow::bail!("nothing at the token path") }));
|
||||
let grafana = Grafana::new(&base, source, TIMEOUT).unwrap();
|
||||
let (status, body) = get_alerts_with(Some(grafana)).await;
|
||||
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert!(
|
||||
body["detail"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("nothing at the token path"),
|
||||
"{body}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_grafana_configured_is_a_503() {
|
||||
let (status, _) = get_alerts_with(None).await;
|
||||
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
}
|
||||
}
|
||||
298
swarm-controller/src/observability/held_deploys.rs
Normal file
298
swarm-controller/src/observability/held_deploys.rs
Normal file
|
|
@ -0,0 +1,298 @@
|
|||
//! The `swarm.deploys.held` gauge: how many agents have a deploy held back by
|
||||
//! the build gate, exported on the jobq exporter. Grafana alerts when it stays
|
||||
//! above zero (`hh-deploys-held`, `nix/host-modules/swarm-grafana.nix`).
|
||||
//!
|
||||
//! An agent counts when its latest `BuildMeta` node is `Failed`, or when its
|
||||
//! latest `TriggerDeploy` is `Skipped` behind a `CopyAtticFacts` that `Failed`.
|
||||
//! It counts once, under one of two `reason` labels:
|
||||
//! - `failed`: `nix` failed, its timeout included.
|
||||
//! - `unavailable`: the build got no verdict (no builder, a forge error, no
|
||||
//! `internal/meta` head, a missing read grant, a closure the builder built but
|
||||
//! didn't push to the cache), or the cache facts couldn't be copied to the hive.
|
||||
//!
|
||||
//! The ten-minute timer declares either again. A pending, running or finished
|
||||
//! build, or a deploy past its copy, does not count, so the value falls to zero
|
||||
//! when the retry succeeds.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use hive_jobq::State;
|
||||
use opentelemetry::KeyValue;
|
||||
use opentelemetry::metrics::MeterProvider as _;
|
||||
use opentelemetry_sdk::metrics::SdkMeterProvider;
|
||||
|
||||
use crate::jobq::{SwarmNodeKind, SwarmResourceKind};
|
||||
use crate::meta_build;
|
||||
|
||||
/// The gauge's name. The Grafana rule selects it by this name.
|
||||
pub(crate) const METRIC: &str = "swarm.deploys.held";
|
||||
|
||||
/// The latest node of each agent whose payload `pick` returns the agent of.
|
||||
fn latest_per_agent(
|
||||
graph: &hive_jobq::Graph<SwarmNodeKind, SwarmResourceKind>,
|
||||
pick: impl Fn(&SwarmNodeKind) -> Option<&String>,
|
||||
) -> std::collections::BTreeMap<&String, &hive_jobq::Node<SwarmNodeKind, SwarmResourceKind>> {
|
||||
let mut latest = std::collections::BTreeMap::new();
|
||||
for n in graph.nodes() {
|
||||
if let Some(agent) = pick(&n.payload)
|
||||
&& latest
|
||||
.get(agent)
|
||||
.is_none_or(|l: &&hive_jobq::Node<_, _>| l.id < n.id)
|
||||
{
|
||||
latest.insert(agent, n);
|
||||
}
|
||||
}
|
||||
latest
|
||||
}
|
||||
|
||||
/// Held agents as `(failed, unavailable)`.
|
||||
fn count(graph: &hive_jobq::Graph<SwarmNodeKind, SwarmResourceKind>) -> (u64, u64) {
|
||||
let builds = latest_per_agent(graph, |p| match p {
|
||||
SwarmNodeKind::BuildMeta { agent, .. } => Some(agent),
|
||||
_ => None,
|
||||
});
|
||||
let deploys = latest_per_agent(graph, |p| match p {
|
||||
SwarmNodeKind::TriggerDeploy { agent, .. } => Some(agent),
|
||||
_ => None,
|
||||
});
|
||||
let copy_failed = |deploy: &hive_jobq::Node<SwarmNodeKind, SwarmResourceKind>| {
|
||||
deploy.state == State::Skipped
|
||||
&& deploy.deps.iter().any(|d| match d {
|
||||
hive_jobq::Dep::Node { id, .. } => graph.node(*id).is_some_and(|dep| {
|
||||
matches!(dep.payload, SwarmNodeKind::CopyAtticFacts { .. })
|
||||
&& dep.state == State::Failed
|
||||
}),
|
||||
hive_jobq::Dep::Resource { .. } => false,
|
||||
})
|
||||
};
|
||||
let (mut failed, mut unavailable) = (0, 0);
|
||||
for (agent, build) in &builds {
|
||||
if build.state == State::Failed {
|
||||
if build
|
||||
.error
|
||||
.as_deref()
|
||||
.is_some_and(meta_build::is_no_verdict)
|
||||
{
|
||||
unavailable += 1;
|
||||
} else {
|
||||
failed += 1;
|
||||
}
|
||||
} else if deploys.get(agent).is_some_and(|d| copy_failed(d)) {
|
||||
unavailable += 1;
|
||||
}
|
||||
}
|
||||
(failed, unavailable)
|
||||
}
|
||||
|
||||
/// Register the gauge on `provider`, reading `jobq` at each export. Nothing when
|
||||
/// no exporter is configured.
|
||||
pub(crate) fn register(
|
||||
provider: Option<&SdkMeterProvider>,
|
||||
jobq: &Arc<Mutex<hive_jobq::scheduler::Scheduler<SwarmNodeKind, SwarmResourceKind>>>,
|
||||
) {
|
||||
let Some(provider) = provider else {
|
||||
return;
|
||||
};
|
||||
let jobq = Arc::clone(jobq);
|
||||
provider
|
||||
.meter("hyperhive.deploy_gate")
|
||||
.u64_observable_gauge(METRIC)
|
||||
.with_description("agents whose deploy the build gate is holding back, by reason")
|
||||
.with_callback(move |obs| {
|
||||
let (failed, unavailable) = count(
|
||||
jobq.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.graph(),
|
||||
);
|
||||
obs.observe(failed, &[KeyValue::new("reason", "failed")]);
|
||||
obs.observe(unavailable, &[KeyValue::new("reason", "unavailable")]);
|
||||
})
|
||||
.build();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use hive_jobq::scheduler::{Outcome, Scheduler};
|
||||
use opentelemetry_sdk::metrics::data::{AggregatedMetrics, MetricData, ResourceMetrics};
|
||||
use opentelemetry_sdk::metrics::{InMemoryMetricExporter, PeriodicReader};
|
||||
|
||||
use super::*;
|
||||
|
||||
type Jobq = Arc<Mutex<Scheduler<SwarmNodeKind, SwarmResourceKind>>>;
|
||||
|
||||
/// A scheduler where each of `builds` (agent, outcome) ran once, in order.
|
||||
async fn after(builds: &[(&str, Outcome)]) -> Jobq {
|
||||
let jobq: Jobq = Arc::new(Mutex::new(Scheduler::new(
|
||||
hive_jobq::Graph::new(),
|
||||
hive_jobq::resources::ResourceTable::new(),
|
||||
)));
|
||||
for (agent, outcome) in builds {
|
||||
jobq.lock()
|
||||
.unwrap()
|
||||
.append(
|
||||
SwarmNodeKind::BuildMeta {
|
||||
agent: (*agent).to_owned(),
|
||||
pr: None,
|
||||
},
|
||||
Vec::new(),
|
||||
None,
|
||||
)
|
||||
.expect("insert");
|
||||
let outcome = outcome.clone();
|
||||
Scheduler::claim_next(&jobq, move |_, _, b| async move { (b, outcome) })
|
||||
.expect("runnable")
|
||||
.await
|
||||
.1
|
||||
.expect("no growth");
|
||||
}
|
||||
jobq
|
||||
}
|
||||
|
||||
fn failed() -> Outcome {
|
||||
Outcome::Failed("error: attribute missing".to_owned())
|
||||
}
|
||||
|
||||
fn unavailable() -> Outcome {
|
||||
Outcome::Failed(format!("{}no builder", meta_build::NO_VERDICT_PREFIX))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_latest_build_holds_its_agent_by_reason() {
|
||||
let jobq = after(&[
|
||||
("atlas", failed()),
|
||||
("argus", unavailable()),
|
||||
("iris", Outcome::Done),
|
||||
])
|
||||
.await;
|
||||
assert_eq!(count(jobq.lock().unwrap().graph()), (1, 1));
|
||||
}
|
||||
|
||||
/// Only an agent's latest build counts: a green build after a red one
|
||||
/// releases it, and a red one after a green one holds it.
|
||||
#[tokio::test]
|
||||
async fn only_the_latest_build_of_an_agent_counts() {
|
||||
let released = after(&[("atlas", failed()), ("atlas", Outcome::Done)]).await;
|
||||
assert_eq!(count(released.lock().unwrap().graph()), (0, 0));
|
||||
let held = after(&[("atlas", Outcome::Done), ("atlas", failed())]).await;
|
||||
assert_eq!(count(held.lock().unwrap().graph()), (1, 0));
|
||||
}
|
||||
|
||||
/// A scheduler where one declaration of `agent`'s build, facts copy and
|
||||
/// deploy ran, the build and the copy ending as given.
|
||||
async fn declared(jobq: &Jobq, agent: &str, build: Outcome, copy: Outcome) {
|
||||
jobq.lock()
|
||||
.unwrap()
|
||||
.insert_job(None, |b| {
|
||||
let build = b.node(SwarmNodeKind::BuildMeta {
|
||||
agent: agent.to_owned(),
|
||||
pr: None,
|
||||
});
|
||||
let copy = b.node(SwarmNodeKind::CopyAtticFacts {
|
||||
hive: "pr1ma".to_owned(),
|
||||
});
|
||||
let deploy = b
|
||||
.node(SwarmNodeKind::TriggerDeploy {
|
||||
hive: "pr1ma".to_owned(),
|
||||
agent: agent.to_owned(),
|
||||
rev: None,
|
||||
})
|
||||
.after_ok(build)
|
||||
.after_ok(copy);
|
||||
vec![deploy.guid()]
|
||||
})
|
||||
.expect("insert");
|
||||
while let Some(runner) = Scheduler::claim_next(jobq, {
|
||||
let (build, copy) = (build.clone(), copy.clone());
|
||||
move |_, kind, b| async move {
|
||||
let outcome = match kind {
|
||||
SwarmNodeKind::BuildMeta { .. } => build,
|
||||
SwarmNodeKind::CopyAtticFacts { .. } => copy,
|
||||
_ => Outcome::Done,
|
||||
};
|
||||
(b, outcome)
|
||||
}
|
||||
}) {
|
||||
runner.await.1.expect("no growth");
|
||||
}
|
||||
}
|
||||
|
||||
fn empty_jobq() -> Jobq {
|
||||
Arc::new(Mutex::new(Scheduler::new(
|
||||
hive_jobq::Graph::new(),
|
||||
hive_jobq::resources::ResourceTable::new(),
|
||||
)))
|
||||
}
|
||||
|
||||
/// A deploy the facts copy held back counts as unavailable, and a green
|
||||
/// build with a green copy does not (the control that the deploy runs).
|
||||
#[tokio::test]
|
||||
async fn a_failed_facts_copy_holds_its_agent_as_unavailable() {
|
||||
let jobq = empty_jobq();
|
||||
declared(
|
||||
&jobq,
|
||||
"atlas",
|
||||
Outcome::Done,
|
||||
Outcome::Failed("denied".into()),
|
||||
)
|
||||
.await;
|
||||
declared(&jobq, "argus", Outcome::Done, Outcome::Done).await;
|
||||
assert_eq!(count(jobq.lock().unwrap().graph()), (0, 1));
|
||||
}
|
||||
|
||||
/// An agent whose build and copy both failed counts once, under the build's
|
||||
/// reason; a retry that goes through releases it.
|
||||
#[tokio::test]
|
||||
async fn a_failed_build_and_copy_count_once_and_a_good_retry_releases() {
|
||||
let jobq = empty_jobq();
|
||||
declared(&jobq, "atlas", failed(), Outcome::Failed("denied".into())).await;
|
||||
assert_eq!(count(jobq.lock().unwrap().graph()), (1, 0));
|
||||
declared(
|
||||
&jobq,
|
||||
"atlas",
|
||||
Outcome::Done,
|
||||
Outcome::Failed("denied".into()),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(count(jobq.lock().unwrap().graph()), (0, 1));
|
||||
declared(&jobq, "atlas", Outcome::Done, Outcome::Done).await;
|
||||
assert_eq!(count(jobq.lock().unwrap().graph()), (0, 0));
|
||||
}
|
||||
|
||||
/// The gauge reads the graph at export time and labels both reasons, zero
|
||||
/// included, so a rule sees the series before anything is held.
|
||||
#[tokio::test]
|
||||
async fn the_gauge_exports_both_reasons() {
|
||||
let jobq = after(&[("atlas", failed())]).await;
|
||||
let exporter = InMemoryMetricExporter::default();
|
||||
let reader = PeriodicReader::builder(exporter.clone()).build();
|
||||
let provider = SdkMeterProvider::builder().with_reader(reader).build();
|
||||
register(Some(&provider), &jobq);
|
||||
provider.force_flush().expect("flush");
|
||||
let all = exporter.get_finished_metrics().expect("metrics");
|
||||
let mut points = Vec::new();
|
||||
for m in all
|
||||
.last()
|
||||
.into_iter()
|
||||
.flat_map(ResourceMetrics::scope_metrics)
|
||||
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
|
||||
.filter(|m| m.name() == METRIC)
|
||||
{
|
||||
let AggregatedMetrics::U64(MetricData::Gauge(g)) = m.data() else {
|
||||
panic!("not a u64 gauge: {:?}", m.data());
|
||||
};
|
||||
for p in g.data_points() {
|
||||
let reason = p
|
||||
.attributes()
|
||||
.find(|kv| kv.key.as_str() == "reason")
|
||||
.map(|kv| kv.value.to_string())
|
||||
.expect("a reason");
|
||||
points.push((reason, p.value()));
|
||||
}
|
||||
}
|
||||
points.sort();
|
||||
assert_eq!(
|
||||
points,
|
||||
[("failed".to_owned(), 1), ("unavailable".to_owned(), 0)]
|
||||
);
|
||||
}
|
||||
}
|
||||
7
swarm-controller/src/observability/mod.rs
Normal file
7
swarm-controller/src/observability/mod.rs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
//! The observability concern: the Grafana alerts route, the held-deploy
|
||||
//! gauge, the OTLP HTTP client and the forge metrics helpers.
|
||||
|
||||
pub(crate) mod alerts;
|
||||
pub(crate) mod held_deploys;
|
||||
pub(crate) mod otel_http_client;
|
||||
pub(crate) mod vcs_metrics;
|
||||
442
swarm-controller/src/observability/otel_http_client.rs
Normal file
442
swarm-controller/src/observability/otel_http_client.rs
Normal file
|
|
@ -0,0 +1,442 @@
|
|||
//! An [`opentelemetry_http::HttpClient`] that authenticates every request
|
||||
//! with a fresh, audience-scoped bearer token minted from this daemon's own
|
||||
//! [`swarm_queue_client::QueueConfig`] identity — "one identity per
|
||||
//! principal" applied to a third destination (the queue connection and
|
||||
//! `auth.rs`'s bridge client, `swarm_queue_client::mint_token_for`, are the
|
||||
//! other two).
|
||||
//!
|
||||
//! Lives here, not in `swarm-queue-client` (mara's own call during review:
|
||||
//! it does not belong in the queue-connect crate) — this daemon is the only
|
||||
//! caller, and the module only *reuses* that crate's
|
||||
//! `QueueConfig`/`mint_token_for_blocking`, it doesn't extend the
|
||||
//! queue-connect contract those exist for.
|
||||
//!
|
||||
//! Exists for exactly one shape of caller: an OTLP metric exporter whose
|
||||
//! `PeriodicReader` drives export from a background thread with **no tokio
|
||||
//! reactor** (`opentelemetry-otlp`'s `reqwest-blocking-client` feature is
|
||||
//! chosen everywhere in this workspace for that reason — see
|
||||
//! `vcs_metrics`'s module doc). That constraint is why this mints via
|
||||
//! [`swarm_queue_client::mint_token_for_blocking`] rather than the async
|
||||
//! `swarm_queue_client::mint_token_for`: the latter needs a runtime to
|
||||
//! `.await` on, which the calling thread does not have.
|
||||
//!
|
||||
//! Per-request, not per-tick or cached: `opentelemetry-otlp` 0.32 exposes
|
||||
//! `WithHttpConfig::with_http_client`, a seam for a caller-supplied
|
||||
//! [`opentelemetry_http::HttpClient`] — strictly better than minting once
|
||||
//! and setting a static header (`WithHttpConfig::with_headers`), because a
|
||||
//! tick that runs long, retries, or fires late can outlive a token minted
|
||||
//! before it started, and that failure is intermittent — the worst kind to
|
||||
//! debug through a metrics pipeline that is itself the thing being fixed.
|
||||
|
||||
use std::fmt;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use bytes::Bytes;
|
||||
use http::{Request, Response};
|
||||
use opentelemetry_http::{HttpClient, HttpError};
|
||||
use swarm_queue_client::{QueueConfig, chain, mint_token_for_blocking};
|
||||
|
||||
/// How long a failure of the same kind stays quiet after it was logged.
|
||||
/// Every push in between is counted and the count rides on the next line.
|
||||
const REPEAT_INTERVAL: Duration = Duration::from_mins(10);
|
||||
|
||||
/// The most of a refusal's response body a log line carries. The collector
|
||||
/// and authelia both answer with a one-line JSON error, well under this.
|
||||
const BODY_SNIPPET_CHARS: usize = 200;
|
||||
|
||||
/// See the module doc. Wraps a plain `reqwest::blocking::Client` — deliberately
|
||||
/// not `opentelemetry_http`'s own blanket impl for that type (behind its
|
||||
/// `reqwest-blocking` cargo feature, unused here): that impl has no seam to
|
||||
/// mint a token per call, which is this type's entire reason to exist.
|
||||
#[derive(Debug)]
|
||||
pub struct AuthenticatedHttpClient {
|
||||
inner: reqwest::blocking::Client,
|
||||
cfg: QueueConfig,
|
||||
/// The audience requested at the token endpoint — see
|
||||
/// [`swarm_queue_client::mint_token_for_blocking`]'s own doc (via
|
||||
/// `swarm_queue_client::mint_token_for`'s) for why this has to be asked
|
||||
/// for explicitly rather than left to whatever the identity's default is.
|
||||
audience: String,
|
||||
failures: Mutex<FailureLog>,
|
||||
}
|
||||
|
||||
impl AuthenticatedHttpClient {
|
||||
/// `inner` is the caller's own client (already configured with
|
||||
/// whatever timeout/TLS trust the destination needs) — this type only
|
||||
/// adds the auth header, it does not build a client of its own, so a
|
||||
/// caller reusing an existing `reqwest::blocking::Client` doesn't pay
|
||||
/// for a second connection pool.
|
||||
#[must_use]
|
||||
pub fn new(
|
||||
inner: reqwest::blocking::Client,
|
||||
cfg: QueueConfig,
|
||||
audience: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
cfg,
|
||||
audience: audience.into(),
|
||||
failures: Mutex::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// One push: mint, then post. A failure carries what to log beside the
|
||||
/// error the SDK gets back.
|
||||
fn send(&self, request: Request<Bytes>) -> Result<Response<Bytes>, Failed> {
|
||||
let token = mint_token_for_blocking(&self.cfg, Some(&self.audience), None)
|
||||
.map_err(|e| Failed::new(Failure::Token, chain(&e), e))?;
|
||||
self.post(&token, request)
|
||||
}
|
||||
|
||||
/// The HTTP half of [`Self::send`], with the token already minted.
|
||||
fn post(&self, token: &str, mut request: Request<Bytes>) -> Result<Response<Bytes>, Failed> {
|
||||
let header = http::HeaderValue::from_str(&format!("Bearer {token}"))
|
||||
.map_err(|e| Failed::new(Failure::Token, e.to_string(), e))?;
|
||||
request
|
||||
.headers_mut()
|
||||
.insert(http::header::AUTHORIZATION, header);
|
||||
|
||||
let req = request
|
||||
.try_into()
|
||||
.map_err(|e: reqwest::Error| Failed::new(Failure::Transport, chain(&e), e))?;
|
||||
let mut response = self
|
||||
.inner
|
||||
.execute(req)
|
||||
.map_err(|e| Failed::new(Failure::Transport, chain(&e), e))?;
|
||||
let status = response.status();
|
||||
// Same header/body reassembly `opentelemetry_http`'s own blocking
|
||||
// impl does — `reqwest::blocking::Response` and `http::Response`
|
||||
// are different types, so this is the required conversion, not an
|
||||
// extra step invented here.
|
||||
let headers = std::mem::take(response.headers_mut());
|
||||
let body = response
|
||||
.bytes()
|
||||
.map_err(|e| Failed::new(Failure::Transport, chain(&e), e))?;
|
||||
if !status.is_success() {
|
||||
let detail = snippet(&body);
|
||||
let error = format!("the collector answered {status}: {detail}");
|
||||
return Err(Failed::new(Failure::Status(status.as_u16()), detail, error));
|
||||
}
|
||||
let mut http_response = Response::builder()
|
||||
.status(status)
|
||||
.body(body)
|
||||
.map_err(|e| Failed::new(Failure::Transport, e.to_string(), e))?;
|
||||
*http_response.headers_mut() = headers;
|
||||
Ok(http_response)
|
||||
}
|
||||
|
||||
/// The SDK reports a failed export only at debug level, so this is the
|
||||
/// one place a refused push shows up: a warning per kind of failure,
|
||||
/// repeated every [`REPEAT_INTERVAL`] while it persists, and one info
|
||||
/// line when a push succeeds after failing.
|
||||
fn log(&self, outcome: Result<(), &Failed>) {
|
||||
let mut failures = self.failures.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match outcome {
|
||||
Ok(()) => {
|
||||
if failures.succeeded() == Verdict::Recovered {
|
||||
tracing::info!(
|
||||
client_id = %self.cfg.client_id,
|
||||
"otel export: push to the collector succeeded after failing"
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(failed) => {
|
||||
if let Verdict::Warn { suppressed } = failures.failed(failed.kind, Instant::now()) {
|
||||
tracing::warn!(
|
||||
failure = %failed.kind,
|
||||
detail = %failed.detail,
|
||||
suppressed,
|
||||
client_id = %self.cfg.client_id,
|
||||
audience = %self.audience,
|
||||
"otel export: push to the collector failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl HttpClient for AuthenticatedHttpClient {
|
||||
/// `async fn` in signature, synchronous in body — matching
|
||||
/// `opentelemetry_http`'s own `reqwest::blocking::Client` impl exactly
|
||||
/// (see that impl's source): the trait is async because some callers
|
||||
/// need that, not because this one does, and the module doc explains
|
||||
/// why this specific caller deliberately runs on a thread with nothing
|
||||
/// to yield to.
|
||||
async fn send_bytes(&self, request: Request<Bytes>) -> Result<Response<Bytes>, HttpError> {
|
||||
let outcome = self.send(request);
|
||||
self.log(outcome.as_ref().map(|_| ()));
|
||||
outcome.map_err(|failed| failed.error)
|
||||
}
|
||||
}
|
||||
|
||||
/// What stopped one push. Coarse on purpose: a collector down for an hour
|
||||
/// is one kind of failure, logged once, not sixty.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Failure {
|
||||
/// No token: authelia refused the request or could not be reached.
|
||||
Token,
|
||||
/// No answer from the collector: DNS, connect, TLS, or a cut-off body.
|
||||
Transport,
|
||||
/// The collector, or the gateway in front of it, answered non-2xx.
|
||||
Status(u16),
|
||||
}
|
||||
|
||||
impl fmt::Display for Failure {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Token => f.write_str("token"),
|
||||
Self::Transport => f.write_str("transport"),
|
||||
Self::Status(code) => write!(f, "status {code}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Failed {
|
||||
kind: Failure,
|
||||
detail: String,
|
||||
error: HttpError,
|
||||
}
|
||||
|
||||
impl Failed {
|
||||
fn new(kind: Failure, detail: String, error: impl Into<HttpError>) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
detail,
|
||||
error: error.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a push outcome is worth a log line.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum Verdict {
|
||||
Quiet,
|
||||
/// Log this failure; `suppressed` pushes failed the same way unlogged
|
||||
/// since the last line about it.
|
||||
Warn {
|
||||
suppressed: u64,
|
||||
},
|
||||
/// The first success after a logged failure.
|
||||
Recovered,
|
||||
}
|
||||
|
||||
/// The failure streak in progress, if any.
|
||||
#[derive(Debug, Default)]
|
||||
struct FailureLog {
|
||||
streak: Option<Streak>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Streak {
|
||||
kind: Failure,
|
||||
logged_at: Instant,
|
||||
suppressed: u64,
|
||||
}
|
||||
|
||||
impl FailureLog {
|
||||
fn failed(&mut self, kind: Failure, now: Instant) -> Verdict {
|
||||
match &mut self.streak {
|
||||
Some(streak) if streak.kind == kind => {
|
||||
if now.duration_since(streak.logged_at) < REPEAT_INTERVAL {
|
||||
streak.suppressed += 1;
|
||||
return Verdict::Quiet;
|
||||
}
|
||||
streak.logged_at = now;
|
||||
Verdict::Warn {
|
||||
suppressed: std::mem::take(&mut streak.suppressed),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.streak = Some(Streak {
|
||||
kind,
|
||||
logged_at: now,
|
||||
suppressed: 0,
|
||||
});
|
||||
Verdict::Warn { suppressed: 0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn succeeded(&mut self) -> Verdict {
|
||||
if self.streak.take().is_some() {
|
||||
Verdict::Recovered
|
||||
} else {
|
||||
Verdict::Quiet
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The start of a response body as one log-safe line.
|
||||
fn snippet(body: &[u8]) -> String {
|
||||
let text = String::from_utf8_lossy(body);
|
||||
let text = text.trim();
|
||||
let mut out: String = text
|
||||
.chars()
|
||||
.take(BODY_SNIPPET_CHARS)
|
||||
.map(|c| if c.is_control() { ' ' } else { c })
|
||||
.collect();
|
||||
if text.chars().count() > BODY_SNIPPET_CHARS {
|
||||
out.push('…');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
use swarm_queue_client::ClientSecret;
|
||||
|
||||
fn client() -> AuthenticatedHttpClient {
|
||||
let inner = reqwest::blocking::Client::builder()
|
||||
.no_proxy()
|
||||
.build()
|
||||
.expect("client");
|
||||
let cfg = QueueConfig {
|
||||
url: "nats://127.0.0.1:4222".to_owned(),
|
||||
token_endpoint: "http://127.0.0.1:9/token".to_owned(),
|
||||
client_id: "swarm-controller".to_owned(),
|
||||
client_secret: ClientSecret::File(PathBuf::from("/nonexistent")),
|
||||
ca_file: None,
|
||||
};
|
||||
AuthenticatedHttpClient::new(inner, cfg, "swarm-controller")
|
||||
}
|
||||
|
||||
fn request(url: &str) -> Request<Bytes> {
|
||||
Request::post(url)
|
||||
.body(Bytes::from_static(b"{}"))
|
||||
.expect("request")
|
||||
}
|
||||
|
||||
/// A stub collector answering every request with `status` and `body`.
|
||||
async fn collector(status: http::StatusCode, body: &'static str) -> String {
|
||||
let app = axum::Router::new().fallback(move || async move { (status, body) });
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind");
|
||||
let url = format!("http://{}/v1/metrics", listener.local_addr().expect("addr"));
|
||||
tokio::spawn(async move { axum::serve(listener, app).await });
|
||||
url
|
||||
}
|
||||
|
||||
async fn post(url: String) -> Result<Response<Bytes>, (Failure, String)> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
client()
|
||||
.post("a-token", request(&url))
|
||||
.map_err(|f| (f.kind, f.detail))
|
||||
})
|
||||
.await
|
||||
.expect("joined")
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_refusal_is_classified_by_status_with_the_body() {
|
||||
let url = collector(
|
||||
http::StatusCode::UNAUTHORIZED,
|
||||
r#"{"code":16,"message":"authentication didn't succeed"}"#,
|
||||
)
|
||||
.await;
|
||||
let (kind, detail) = post(url).await.expect_err("refused");
|
||||
assert_eq!(kind, Failure::Status(401));
|
||||
assert_eq!(
|
||||
detail,
|
||||
r#"{"code":16,"message":"authentication didn't succeed"}"#
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn an_accepted_push_is_returned_as_is() {
|
||||
let url = collector(http::StatusCode::OK, "{}").await;
|
||||
let response = post(url).await.expect("accepted");
|
||||
assert_eq!(response.status(), http::StatusCode::OK);
|
||||
assert_eq!(response.body().as_ref(), b"{}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn an_unreachable_collector_is_a_transport_failure() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
let url = format!("http://{}/v1/metrics", listener.local_addr().expect("addr"));
|
||||
drop(listener);
|
||||
let (kind, _) = post(url).await.expect_err("unreachable");
|
||||
assert_eq!(kind, Failure::Transport);
|
||||
}
|
||||
|
||||
/// The mint runs first: no token, no request, and the failure says so.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_failed_mint_is_a_token_failure() {
|
||||
let url = collector(http::StatusCode::OK, "{}").await;
|
||||
let kind = tokio::task::spawn_blocking(move || client().send(request(&url)).err())
|
||||
.await
|
||||
.expect("joined")
|
||||
.expect("no token")
|
||||
.kind;
|
||||
assert_eq!(kind, Failure::Token);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repeated_failure_is_logged_once_per_interval_with_the_count() {
|
||||
let mut log = FailureLog::default();
|
||||
let t0 = Instant::now();
|
||||
let kind = Failure::Status(401);
|
||||
assert_eq!(log.failed(kind, t0), Verdict::Warn { suppressed: 0 });
|
||||
for minute in 1..10 {
|
||||
assert_eq!(
|
||||
log.failed(kind, t0 + Duration::from_mins(minute)),
|
||||
Verdict::Quiet
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
log.failed(kind, t0 + REPEAT_INTERVAL),
|
||||
Verdict::Warn { suppressed: 9 }
|
||||
);
|
||||
assert_eq!(
|
||||
log.failed(kind, t0 + REPEAT_INTERVAL + Duration::from_mins(1)),
|
||||
Verdict::Quiet
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_different_failure_is_logged_at_once() {
|
||||
let mut log = FailureLog::default();
|
||||
let t0 = Instant::now();
|
||||
assert_eq!(
|
||||
log.failed(Failure::Token, t0),
|
||||
Verdict::Warn { suppressed: 0 }
|
||||
);
|
||||
assert_eq!(
|
||||
log.failed(Failure::Status(401), t0),
|
||||
Verdict::Warn { suppressed: 0 }
|
||||
);
|
||||
assert_eq!(
|
||||
log.failed(Failure::Status(404), t0),
|
||||
Verdict::Warn { suppressed: 0 }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovery_is_logged_once_and_only_after_a_failure() {
|
||||
let mut log = FailureLog::default();
|
||||
let t0 = Instant::now();
|
||||
assert_eq!(log.succeeded(), Verdict::Quiet);
|
||||
log.failed(Failure::Transport, t0);
|
||||
assert_eq!(log.succeeded(), Verdict::Recovered);
|
||||
assert_eq!(log.succeeded(), Verdict::Quiet);
|
||||
assert_eq!(
|
||||
log.failed(Failure::Transport, t0),
|
||||
Verdict::Warn { suppressed: 0 }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_body_is_cut_on_a_character_boundary() {
|
||||
let body = "é".repeat(BODY_SNIPPET_CHARS + 5);
|
||||
let cut = snippet(body.as_bytes());
|
||||
assert_eq!(cut.chars().count(), BODY_SNIPPET_CHARS + 1);
|
||||
assert!(cut.ends_with('…'));
|
||||
assert_eq!(snippet(b" short\nbody \n"), "short body");
|
||||
}
|
||||
}
|
||||
500
swarm-controller/src/observability/vcs_metrics.rs
Normal file
500
swarm-controller/src/observability/vcs_metrics.rs
Normal file
|
|
@ -0,0 +1,500 @@
|
|||
//! OTEL export of commit/push activity across every forge repo in the
|
||||
//! instance — the metric forgejo's own native `/metrics` endpoint (see
|
||||
//! `docs/2-handbook/swarm/forge.md`'s note on the survey that shipped it) does not carry.
|
||||
//! That endpoint gives issue/comment/repo counts because Forgejo tracks
|
||||
//! those as durable rows it can `SELECT COUNT(*)` on demand; a commit or a
|
||||
//! push is not stored anywhere as a row to count, only observed in passing
|
||||
//! as a webhook fires. So this is occurrence-driven, not poll-driven: the
|
||||
//! push and commit counters are recorded straight from [`record_push`],
|
||||
//! called once per verified `push` delivery on
|
||||
//! [`crate::webhook::DeliveryKind::VcsActivity`]. The default-branch merge
|
||||
//! and line counters come from [`count_default_branch_push`], which asks the
|
||||
//! forge to compare the push and runs after the delivery is answered.
|
||||
//! Nothing is scanned periodically.
|
||||
//!
|
||||
//! Same SDK setup as `hive_jobq_metrics` (this daemon's other OTEL
|
||||
//! exporter): blocking OTLP client on the `PeriodicReader`'s own background
|
||||
//! thread, `service.name` + `HYPERHIVE_OTEL_EXTRA_RESOURCE_ATTRIBUTES` for
|
||||
//! the resource, `OTEL_EXPORTER_OTLP_ENDPOINT` as the sole enable signal,
|
||||
//! a fixed 60 s export cadence. Recording is
|
||||
//! synchronous (`counter.add`, called at the event site) rather than
|
||||
//! observable/polled — see `hive-agent::otel_turn_metrics`'s doc comment
|
||||
//! for why an occurrence, unlike a live gauge, has nothing to poll between
|
||||
//! events.
|
||||
|
||||
use std::future::Future;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::forge::LineStats;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use opentelemetry::KeyValue;
|
||||
use opentelemetry::metrics::{Counter, MeterProvider as _};
|
||||
use opentelemetry_otlp::{MetricExporter, Protocol, WithExportConfig, WithHttpConfig};
|
||||
use opentelemetry_sdk::Resource;
|
||||
use opentelemetry_sdk::metrics::{PeriodicReader, SdkMeterProvider};
|
||||
|
||||
/// Export cadence. Matches every other OTEL exporter in this tree.
|
||||
pub(crate) const EXPORT_INTERVAL: Duration = Duration::from_mins(1);
|
||||
|
||||
/// One push delivery, as parsed off the webhook body — just the fields
|
||||
/// this module needs, not a full mirror of Forgejo's push-event schema.
|
||||
/// Kept separate from the wire parsing so a test can construct one without
|
||||
/// a JSON literal.
|
||||
pub(crate) struct PushActivity {
|
||||
/// The pushed ref, e.g. `refs/heads/main`.
|
||||
pub(crate) git_ref: String,
|
||||
/// `repository.default_branch`; empty when the payload names none, in
|
||||
/// which case no push counts as a default-branch push.
|
||||
pub(crate) default_branch: String,
|
||||
/// The ref's tip before and after the push. All zeros means the ref did
|
||||
/// not exist before (`before`) or no longer exists (`after`).
|
||||
pub(crate) before: String,
|
||||
pub(crate) after: String,
|
||||
/// `repository.full_name` (`org/repo`) — the attribute every series
|
||||
/// this module emits carries, so a dashboard can break activity down
|
||||
/// per repo without a second join.
|
||||
pub(crate) repo: String,
|
||||
/// `commits.len()` from the payload. A push with zero commits is real
|
||||
/// (a branch delete, a force-push moving the ref backward) and still
|
||||
/// counted as a push — just with a commit delta of zero, not skipped.
|
||||
pub(crate) commit_count: u64,
|
||||
}
|
||||
|
||||
/// Parse a Forgejo `push` webhook body into a [`PushActivity`]. `None` on
|
||||
/// anything unparseable — a malformed body is logged and dropped by the
|
||||
/// caller, not a reason to fail the delivery Forgejo already got a 200 for.
|
||||
pub(crate) fn parse_push(body: &[u8]) -> Option<PushActivity> {
|
||||
let v: serde_json::Value = serde_json::from_slice(body).ok()?;
|
||||
let repo = v.get("repository")?.get("full_name")?.as_str()?.to_owned();
|
||||
let commit_count = v.get("commits")?.as_array()?.len();
|
||||
let text = |v: Option<&serde_json::Value>| {
|
||||
v.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned()
|
||||
};
|
||||
Some(PushActivity {
|
||||
git_ref: text(v.get("ref")),
|
||||
default_branch: text(v.get("repository").and_then(|r| r.get("default_branch"))),
|
||||
before: text(v.get("before")),
|
||||
after: text(v.get("after")),
|
||||
repo,
|
||||
commit_count: u64::try_from(commit_count).unwrap_or(u64::MAX),
|
||||
})
|
||||
}
|
||||
|
||||
struct Instruments {
|
||||
_provider: SdkMeterProvider,
|
||||
commit_count: Counter<u64>,
|
||||
push_count: Counter<u64>,
|
||||
merges: Counter<u64>,
|
||||
lines_added: Counter<u64>,
|
||||
lines_deleted: Counter<u64>,
|
||||
}
|
||||
|
||||
static INSTRUMENTS: OnceLock<Option<Instruments>> = OnceLock::new();
|
||||
|
||||
/// Record one push delivery. A no-op when OTEL isn't configured
|
||||
/// (`OTEL_EXPORTER_OTLP_ENDPOINT` unset) — the same graceful-absence shape
|
||||
/// every other exporter in this tree uses, so a deployment with no
|
||||
/// collector pays nothing beyond the one-time `OnceLock` check.
|
||||
pub(crate) fn record_push(activity: &PushActivity) {
|
||||
let Some(inst) = INSTRUMENTS.get_or_init(build).as_ref() else {
|
||||
return;
|
||||
};
|
||||
let attrs = [KeyValue::new("repo", activity.repo.clone())];
|
||||
inst.push_count.add(1, &attrs);
|
||||
if activity.commit_count > 0 {
|
||||
inst.commit_count.add(activity.commit_count, &attrs);
|
||||
}
|
||||
}
|
||||
|
||||
/// What one default-branch push adds to the counters.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) struct DefaultBranchTally {
|
||||
/// `None` when the lines are unknown: the push created the branch, or
|
||||
/// the compare failed. Nothing is added to the line counters then.
|
||||
pub(crate) lines: Option<LineStats>,
|
||||
}
|
||||
|
||||
fn is_null_sha(sha: &str) -> bool {
|
||||
!sha.is_empty() && sha.bytes().all(|b| b == b'0')
|
||||
}
|
||||
|
||||
/// The counts a push adds, or `None` when it did not move the repo's default
|
||||
/// branch (another ref, a deleted branch, or a payload naming no default).
|
||||
///
|
||||
/// Every other push to the default branch counts one merge. Lines come from
|
||||
/// `compare(before, after)`, except for a push that created the branch (no
|
||||
/// `before` to compare against). A failed compare is logged and skips the
|
||||
/// lines only.
|
||||
///
|
||||
/// A force-push counts what the compare returns: the commits reachable from
|
||||
/// `after` and not from `before`, with their stats. The commits the push
|
||||
/// discarded are not subtracted, so a rewrite of already-counted history
|
||||
/// counts those lines a second time.
|
||||
pub(crate) async fn default_branch_tally<F, Fut>(
|
||||
activity: &PushActivity,
|
||||
compare: F,
|
||||
) -> Option<DefaultBranchTally>
|
||||
where
|
||||
F: FnOnce(String, String) -> Fut,
|
||||
Fut: Future<Output = Result<LineStats>>,
|
||||
{
|
||||
if activity.default_branch.is_empty()
|
||||
|| activity.git_ref != format!("refs/heads/{}", activity.default_branch)
|
||||
|| activity.after.is_empty()
|
||||
|| is_null_sha(&activity.after)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if activity.before.is_empty() || is_null_sha(&activity.before) {
|
||||
return Some(DefaultBranchTally { lines: None });
|
||||
}
|
||||
let lines = match compare(activity.before.clone(), activity.after.clone()).await {
|
||||
Ok(lines) => Some(lines),
|
||||
Err(e) => {
|
||||
tracing::warn!(repo = %activity.repo, error = ?e, "vcs-metrics: compare failed; push counted without lines");
|
||||
None
|
||||
}
|
||||
};
|
||||
Some(DefaultBranchTally { lines })
|
||||
}
|
||||
|
||||
/// Count `activity` on the default-branch counters, comparing through
|
||||
/// `forge`. Runs after the webhook has answered; nothing here can fail it.
|
||||
pub(crate) async fn count_default_branch_push(
|
||||
activity: PushActivity,
|
||||
forge: Option<Arc<crate::forge::Client>>,
|
||||
) {
|
||||
let Some((owner, name)) = activity.repo.split_once('/') else {
|
||||
return;
|
||||
};
|
||||
let tally = default_branch_tally(&activity, |before, after| async move {
|
||||
let forge = forge.context("no forge client")?;
|
||||
forge.compare_line_stats(owner, name, &before, &after).await
|
||||
})
|
||||
.await;
|
||||
if let Some(tally) = tally {
|
||||
record_default_branch(&activity.repo, &tally);
|
||||
}
|
||||
}
|
||||
|
||||
fn record_default_branch(repo: &str, tally: &DefaultBranchTally) {
|
||||
let Some(inst) = INSTRUMENTS.get_or_init(build).as_ref() else {
|
||||
return;
|
||||
};
|
||||
let attrs = [KeyValue::new("repo", repo.to_owned())];
|
||||
inst.merges.add(1, &attrs);
|
||||
if let Some(lines) = tally.lines {
|
||||
inst.lines_added.add(lines.added, &attrs);
|
||||
inst.lines_deleted.add(lines.deleted, &attrs);
|
||||
}
|
||||
}
|
||||
|
||||
fn build() -> Option<Instruments> {
|
||||
let endpoint = endpoint()?;
|
||||
let interval = EXPORT_INTERVAL;
|
||||
match build_provider(interval) {
|
||||
Ok(provider) => {
|
||||
tracing::info!(%endpoint, ?interval, "otel vcs-metrics: exporter enabled");
|
||||
let meter = provider.meter("hyperhive.vcs");
|
||||
Some(Instruments {
|
||||
commit_count: meter
|
||||
.u64_counter("hyperhive.vcs.commit.count")
|
||||
.with_description("commits observed across every forge push delivery")
|
||||
.build(),
|
||||
push_count: meter
|
||||
.u64_counter("hyperhive.vcs.push.count")
|
||||
.with_description("push deliveries observed, one per webhook event")
|
||||
.build(),
|
||||
merges: meter
|
||||
.u64_counter("hyperhive.vcs.default_branch.merges")
|
||||
.with_description("pushes that moved a repo's default branch")
|
||||
.build(),
|
||||
lines_added: meter
|
||||
.u64_counter("hyperhive.vcs.default_branch.lines_added")
|
||||
.with_description("lines added by commits pushed to a repo's default branch")
|
||||
.build(),
|
||||
lines_deleted: meter
|
||||
.u64_counter("hyperhive.vcs.default_branch.lines_deleted")
|
||||
.with_description("lines deleted by commits pushed to a repo's default branch")
|
||||
.build(),
|
||||
_provider: provider,
|
||||
})
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = ?e, "otel vcs-metrics: exporter init failed");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn build_provider(interval: Duration) -> Result<SdkMeterProvider> {
|
||||
// Same http/json, endpoint-from-env-only construction as
|
||||
// `hive_jobq_metrics::build_provider` — see that module's doc comment
|
||||
// for why `with_endpoint` is deliberately never called here.
|
||||
//
|
||||
// `.with_http_client(..)`: unlike the hive tier's own exporters, this
|
||||
// one crosses a real trust boundary (the swarm-tier `otlp/swarm`
|
||||
// receiver checks a bearer token's audience, see
|
||||
// `crate::otel_http_client`'s module doc) — a plain endpoint-only
|
||||
// client would be refused at the receiver.
|
||||
let exporter = MetricExporter::builder()
|
||||
.with_http()
|
||||
.with_protocol(Protocol::HttpJson)
|
||||
.with_http_client(authenticated_http_client()?)
|
||||
.build()
|
||||
.context("build OTLP metric exporter")?;
|
||||
let reader = PeriodicReader::builder(exporter)
|
||||
.with_interval(interval)
|
||||
.build();
|
||||
Ok(SdkMeterProvider::builder()
|
||||
.with_reader(reader)
|
||||
.with_resource(resource())
|
||||
.build())
|
||||
}
|
||||
|
||||
/// Build the [`crate::otel_http_client::AuthenticatedHttpClient`] this
|
||||
/// exporter pushes through.
|
||||
///
|
||||
/// The queue identity is read from [`crate::queue_identity::get`] rather
|
||||
/// than threaded in from a caller — by the time this runs, [`endpoint`] has
|
||||
/// already confirmed OTEL is configured for this host, and `queueEnv` is set
|
||||
/// **unconditionally** for every `swarm-controller` (the nix module's own
|
||||
/// words: "a controller without a queue is not a lighter controller, it is
|
||||
/// a broken one"). So an absent queue identity here is never a supported
|
||||
/// "OTEL enabled, queue not configured" deployment shape — it is a
|
||||
/// deployment bug, and gets the same `Err` treatment `build()`'s caller
|
||||
/// already applies to any other exporter-construction failure.
|
||||
///
|
||||
/// `SWARM_CONTROLLER_OTEL_AUDIENCE` names the audience `otlp/swarm`'s
|
||||
/// authenticator checks — set by the same nix option that sets
|
||||
/// `OTEL_EXPORTER_OTLP_ENDPOINT`, so the two are never independently absent.
|
||||
///
|
||||
/// No CA handling here unlike [`swarm_queue_client::QueueConfig::ca_file`]
|
||||
/// (which `mint_token_for_blocking` already applies to the TOKEN endpoint
|
||||
/// internally): the metrics endpoint is reached through the gateway with a
|
||||
/// certificate the store's `pki` mount issued, and this whole process
|
||||
/// already trusts that mount's root via `SSL_CERT_FILE` (`hive-ca-trust.nix`,
|
||||
/// applied host-wide to this unit for the same reason the forge client needs
|
||||
/// no special handling either) — a second, narrower trust bundle here would
|
||||
/// just be the same fact stated twice.
|
||||
pub(crate) fn authenticated_http_client() -> Result<crate::otel_http_client::AuthenticatedHttpClient>
|
||||
{
|
||||
let cfg = crate::queue_identity::get().cloned().ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"SWARM_CONTROLLER_NATS_URL and friends are unset, but OTEL_EXPORTER_OTLP_ENDPOINT \
|
||||
is — the queue is required for every controller, so this combination is a \
|
||||
deployment bug, not a supported partial config"
|
||||
)
|
||||
})?;
|
||||
let audience = std::env::var("SWARM_CONTROLLER_OTEL_AUDIENCE").context(
|
||||
"SWARM_CONTROLLER_OTEL_AUDIENCE is unset, but OTEL_EXPORTER_OTLP_ENDPOINT is — the nix \
|
||||
module sets both together",
|
||||
)?;
|
||||
Ok(crate::otel_http_client::AuthenticatedHttpClient::new(
|
||||
reqwest::blocking::Client::new(),
|
||||
cfg,
|
||||
audience,
|
||||
))
|
||||
}
|
||||
|
||||
/// `service.name = swarm-controller` plus whatever the operator set in
|
||||
/// `HYPERHIVE_OTEL_EXTRA_RESOURCE_ATTRIBUTES` — same channel
|
||||
/// `hive_jobq_metrics::resource` reads, since both live in this one binary.
|
||||
fn resource() -> Resource {
|
||||
let mut builder = Resource::builder().with_service_name("swarm-controller");
|
||||
for (k, v) in resource_attributes() {
|
||||
builder = builder.with_attribute(KeyValue::new(k, v));
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
|
||||
pub(crate) fn endpoint() -> Option<String> {
|
||||
std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT")
|
||||
.ok()
|
||||
.map(|s| s.trim().to_owned())
|
||||
.filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
fn resource_attributes() -> Vec<(String, String)> {
|
||||
std::env::var("HYPERHIVE_OTEL_EXTRA_RESOURCE_ATTRIBUTES")
|
||||
.ok()
|
||||
.map(|s| parse_kv(&s))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Byte-identical logic to `hive_jobq_metrics::parse_kv` — small enough
|
||||
/// that sharing it isn't worth a dependency edge, kept in lockstep on
|
||||
/// purpose.
|
||||
fn parse_kv(s: &str) -> Vec<(String, String)> {
|
||||
s.split([',', '\n'])
|
||||
.filter_map(|pair| {
|
||||
let pair = pair.trim();
|
||||
if pair.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (k, v) = pair.split_once('=')?;
|
||||
let k = k.trim();
|
||||
if k.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some((k.to_owned(), v.trim().to_owned()))
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::parse_push;
|
||||
|
||||
/// A realistic (trimmed) Forgejo push payload — two commits on one ref.
|
||||
#[test]
|
||||
fn parses_repo_and_commit_count_from_a_real_shaped_payload() {
|
||||
let body = br#"{
|
||||
"ref": "refs/heads/main",
|
||||
"repository": { "full_name": "hyperhive/hyperhive" },
|
||||
"commits": [
|
||||
{"id": "abc123", "message": "first"},
|
||||
{"id": "def456", "message": "second"}
|
||||
]
|
||||
}"#;
|
||||
let activity = parse_push(body).expect("valid push payload parses");
|
||||
assert_eq!(activity.repo, "hyperhive/hyperhive");
|
||||
assert_eq!(activity.commit_count, 2);
|
||||
}
|
||||
|
||||
/// A branch delete or a force-push landing on an already-known tip both
|
||||
/// arrive with an empty `commits` array — still a real push, at zero
|
||||
/// commits, not something to reject as malformed.
|
||||
#[test]
|
||||
fn a_push_with_zero_commits_still_parses() {
|
||||
let body = br#"{
|
||||
"repository": { "full_name": "agents/test-1" },
|
||||
"commits": []
|
||||
}"#;
|
||||
let activity = parse_push(body).expect("empty commits is still a valid push");
|
||||
assert_eq!(activity.repo, "agents/test-1");
|
||||
assert_eq!(activity.commit_count, 0);
|
||||
}
|
||||
|
||||
/// Missing `repository.full_name` or a non-array `commits` must not
|
||||
/// panic or silently default — the caller needs to know parsing failed
|
||||
/// so it can log and drop rather than emit a mislabeled data point.
|
||||
#[test]
|
||||
fn malformed_or_missing_fields_refuse_rather_than_default() {
|
||||
assert!(
|
||||
parse_push(b"{}").is_none(),
|
||||
"empty object has neither field"
|
||||
);
|
||||
assert!(
|
||||
parse_push(br#"{"repository": {}, "commits": []}"#).is_none(),
|
||||
"missing full_name must refuse"
|
||||
);
|
||||
assert!(
|
||||
parse_push(br#"{"repository": {"full_name": "a/b"}, "commits": "oops"}"#).is_none(),
|
||||
"commits must be an array, not any other JSON type"
|
||||
);
|
||||
assert!(parse_push(b"not json at all").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod default_branch_tests {
|
||||
use super::{DefaultBranchTally, PushActivity, default_branch_tally};
|
||||
use crate::forge::LineStats;
|
||||
|
||||
const SHA_A: &str = "1111111111111111111111111111111111111111";
|
||||
const SHA_B: &str = "2222222222222222222222222222222222222222";
|
||||
const ZEROS: &str = "0000000000000000000000000000000000000000";
|
||||
|
||||
fn push(git_ref: &str, before: &str, after: &str) -> PushActivity {
|
||||
PushActivity {
|
||||
git_ref: git_ref.to_owned(),
|
||||
default_branch: "main".to_owned(),
|
||||
before: before.to_owned(),
|
||||
after: after.to_owned(),
|
||||
repo: "hyperhive/hyperhive".to_owned(),
|
||||
commit_count: 1,
|
||||
}
|
||||
}
|
||||
|
||||
async fn tally(
|
||||
activity: &PushActivity,
|
||||
compare: anyhow::Result<LineStats>,
|
||||
) -> Option<DefaultBranchTally> {
|
||||
default_branch_tally(activity, |_, _| async move { compare }).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_default_branch_push_counts_the_merge_and_the_compared_lines() {
|
||||
let lines = LineStats {
|
||||
added: 12,
|
||||
deleted: 3,
|
||||
};
|
||||
let got = tally(&push("refs/heads/main", SHA_A, SHA_B), Ok(lines)).await;
|
||||
assert_eq!(got, Some(DefaultBranchTally { lines: Some(lines) }));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_push_to_another_branch_counts_nothing() {
|
||||
let lines = LineStats {
|
||||
added: 12,
|
||||
deleted: 3,
|
||||
};
|
||||
let got = tally(&push("refs/heads/feature", SHA_A, SHA_B), Ok(lines)).await;
|
||||
assert_eq!(got, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deleting_the_default_branch_counts_nothing() {
|
||||
let got = tally(
|
||||
&push("refs/heads/main", SHA_A, ZEROS),
|
||||
Ok(LineStats::default()),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(got, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_new_default_branch_counts_the_merge_and_no_lines() {
|
||||
let called = std::sync::atomic::AtomicBool::new(false);
|
||||
let got = default_branch_tally(&push("refs/heads/main", ZEROS, SHA_B), |_, _| async {
|
||||
called.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
Ok(LineStats::default())
|
||||
})
|
||||
.await;
|
||||
assert_eq!(got, Some(DefaultBranchTally { lines: None }));
|
||||
assert!(!called.load(std::sync::atomic::Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_compare_error_counts_the_merge_and_skips_the_lines() {
|
||||
let got = tally(
|
||||
&push("refs/heads/main", SHA_A, SHA_B),
|
||||
Err(anyhow::anyhow!("forge answered 500")),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(got, Some(DefaultBranchTally { lines: None }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_fields_parse_off_the_payload() {
|
||||
let body = br#"{
|
||||
"ref": "refs/heads/main",
|
||||
"before": "1111111111111111111111111111111111111111",
|
||||
"after": "2222222222222222222222222222222222222222",
|
||||
"repository": { "full_name": "a/b", "default_branch": "main" },
|
||||
"commits": []
|
||||
}"#;
|
||||
let a = super::parse_push(body).expect("parses");
|
||||
assert_eq!(
|
||||
(a.git_ref.as_str(), a.default_branch.as_str()),
|
||||
("refs/heads/main", "main")
|
||||
);
|
||||
assert_eq!((a.before.as_str(), a.after.as_str()), (SHA_A, SHA_B));
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue