diff --git a/Cargo.lock b/Cargo.lock index 63112a43a..80b1b5f38 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5476,6 +5476,7 @@ dependencies = [ "tokio", "tracing", "url", + "x509-cert", ] [[package]] diff --git a/swarm-ci-metrics/Cargo.toml b/swarm-ci-metrics/Cargo.toml index 46f427675..9c847e9df 100644 --- a/swarm-ci-metrics/Cargo.toml +++ b/swarm-ci-metrics/Cargo.toml @@ -32,6 +32,8 @@ url.workspace = true [dev-dependencies] # A scratch state directory for the cursor tests. tempfile = "3" +# Builds the client certificate the cert-gauge tests read. +x509-cert.workspace = true [lints] workspace = true diff --git a/swarm-ci-metrics/src/main.rs b/swarm-ci-metrics/src/main.rs index f03157d27..9f4f08f74 100644 --- a/swarm-ci-metrics/src/main.rs +++ b/swarm-ci-metrics/src/main.rs @@ -18,10 +18,10 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::time::Duration; -use anyhow::{Context as _, Result, bail}; +use anyhow::{Context as _, Result, anyhow, bail}; use forge_client::async_client; use forgejo_api::Forgejo; -use forgejo_api::structs::{ActionRun, ListActionRunsQuery, RepoSearchQuery}; +use forgejo_api::structs::{ActionRun, ListActionRunsQuery, RepoSearchQuery, Repository}; use swarm_queue_client::{ClientSecret, QueueConfig}; use swarm_secret_client::ci_metrics::{ClientSecret as StoredClientSecret, client_secret_path}; use swarm_secret_client::client::ENV_CLIENT_CERT; @@ -47,89 +47,191 @@ const PAGE: u32 = 50; /// The pause before each further page of one listing. const PAGE_DELAY: Duration = Duration::from_secs(1); -struct Config { - forge_url: url::Url, +/// What a pass talks to: the forge, the identity provider and the collector. +/// [`Live`] speaks HTTP to all three; the tests' stand-in answers from memory, +/// so no test opens a socket. +trait Remote { + /// The pause before each further page of one listing. + fn page_delay(&self) -> Duration { + PAGE_DELAY + } + + /// One page of the forge's repo search, as the account sees it. + async fn search_repos(&self, page: u32) -> Result>; + + /// One page of the runs of `owner/name`, newest first. + async fn list_runs(&self, owner: &str, name: &str, page: u32) -> Result>; + + /// A bearer token the collector accepts. + async fn mint_token(&self) -> Result; + + /// POST one OTLP JSON `body` to the collector; an error unless it answers + /// 2xx. + async fn post_otlp(&self, bearer: &str, body: &serde_json::Value) -> Result<()>; +} + +/// The daemon's [`Remote`]: the forge, the collector and the identity +/// provider over HTTP. +struct Live { + forge: Forgejo, + http: reqwest::Client, /// `…/v1/metrics` on this service's collector route. metrics_url: String, queue: QueueConfig, +} + +impl Remote for Live { + async fn search_repos(&self, page: u32) -> Result> { + Ok(self + .forge + .repo_search(RepoSearchQuery::default()) + .page(page) + .page_size(PAGE) + .send() + .await? + .data + .unwrap_or_default()) + } + + async fn list_runs(&self, owner: &str, name: &str, page: u32) -> Result> { + Ok(self + .forge + .list_action_runs(owner, name, ListActionRunsQuery::default()) + .page(page) + .page_size(PAGE) + .send() + .await? + .workflow_runs + .unwrap_or_default()) + } + + async fn mint_token(&self) -> Result { + Ok( + swarm_queue_client::mint_token_for(&self.queue, Some(&self.queue.client_id), None) + .await?, + ) + } + + async fn post_otlp(&self, bearer: &str, body: &serde_json::Value) -> Result<()> { + post(&self.http, &self.metrics_url, bearer, body).await + } +} + +/// Where the settings come from: the process environment in `main`. +type Lookup<'a> = &'a dyn Fn(&str) -> Result; + +/// The `SWARM_CI_METRICS_` setting, or an error naming it. +fn var(get: Lookup<'_>, name: &str) -> Result { + let full = format!("{PREFIX}_{name}"); + get(&full).with_context(|| format!("{full} is unset")) +} + +/// The settings the unit's environment carries besides the client id. +struct Env { + forge_url: url::Url, + /// `…/v1/metrics` on this service's collector route. + metrics_url: String, + token_endpoint: String, state_file: PathBuf, } +impl Env { + fn read(get: Lookup<'_>) -> Result { + let state_dir = get("STATE_DIRECTORY").context("STATE_DIRECTORY is unset")?; + Ok(Self { + forge_url: var(get, "FORGE_URL")? + .parse() + .context("parsing the forge URL")?, + metrics_url: format!( + "{}/v1/metrics", + var(get, "OTLP_ENDPOINT")?.trim_end_matches('/') + ), + token_endpoint: var(get, "OIDC_TOKEN_ENDPOINT")?, + state_file: PathBuf::from(state_dir).join("cursor.json"), + }) + } +} + #[tokio::main] async fn main() -> Result<()> { hive_log::init(); swarm_secret_client::install_crypto_provider(); - let var = |name: &str| { - let full = format!("{PREFIX}_{name}"); - std::env::var(&full).with_context(|| format!("{full} is unset")) - }; - let client_id = var("OIDC_CLIENT_ID")?; + let get = |name: &str| std::env::var(name); + let client_id = var(&get, "OIDC_CLIENT_ID")?; let secret = client_secret(&client_id).await?; let reread_id = client_id.clone(); let secret = StoredSecret::new(client_id.clone(), secret, move || { let client_id = reread_id.clone(); async move { client_secret(&client_id).await.map_err(Into::into) } }); - let state_dir = std::env::var("STATE_DIRECTORY").context("STATE_DIRECTORY is unset")?; - let cfg = Config { - forge_url: var("FORGE_URL")?.parse().context("parsing the forge URL")?, - metrics_url: format!("{}/v1/metrics", var("OTLP_ENDPOINT")?.trim_end_matches('/')), - queue: QueueConfig { - // `mint_token_for` reads only the token endpoint and the client. - url: String::new(), - token_endpoint: var("OIDC_TOKEN_ENDPOINT")?, - client_id, - client_secret: ClientSecret::Stored(secret), - ca_file: None, - }, - state_file: PathBuf::from(state_dir).join("cursor.json"), + let env = Env::read(&get)?; + let queue = QueueConfig { + // `mint_token_for` reads only the token endpoint and the client. + url: String::new(), + token_endpoint: env.token_endpoint, + client_id, + client_secret: ClientSecret::Stored(secret), + ca_file: None, }; - let forge = async_client(cfg.forge_url.clone(), &forge_token().await?) - .context("building the forge client")?; - let http = reqwest::Client::builder() - .timeout(Duration::from_secs(30)) - .build() - .context("building the OTLP client")?; - push_cert(&cfg, &http).await; - let mut state = cursor::State::load(&cfg.state_file)?; - let repos = repos(&forge).await?; + let remote = Live { + forge: async_client(env.forge_url, &forge_token().await?) + .context("building the forge client")?, + http: reqwest::Client::builder() + .timeout(Duration::from_secs(30)) + .build() + .context("building the OTLP client")?, + metrics_url: env.metrics_url, + queue, + }; + push_cert(&remote, std::env::var(ENV_CLIENT_CERT).ok().as_deref()).await; + let mut state = cursor::State::load(&env.state_file)?; + let repos = repos(&remote).await?; tracing::info!(repos = repos.len(), "ci metrics: pass starting"); let mut failed = 0; for repo in &repos { - if let Err(e) = repo_pass(&cfg, &forge, &http, &mut state, repo).await { + if let Err(e) = repo_pass(&remote, &env.state_file, &mut state, repo).await { tracing::warn!(repo, error = %format!("{e:#}"), "ci metrics: repo pass failed"); failed += 1; } } + finish(failed, repos.len()) +} + +/// The pass's verdict: an error when any repo failed, so the unit is reported +/// as failed. +fn finish(failed: usize, total: usize) -> Result<()> { if failed > 0 { - bail!( - "{failed} of {} repos failed; their cursors stay where they were", - repos.len() - ); + bail!("{failed} of {total} repos failed; their cursors stay where they were"); } Ok(()) } +/// How many skipped runs each reason accounts for. +fn skip_counts(skip: &[(u64, sample::Skip)]) -> BTreeMap { + let mut counts = BTreeMap::new(); + for (_, why) in skip { + *counts.entry(*why).or_default() += 1; + } + counts +} + /// One repo: walk, plan, push, move the cursor. async fn repo_pass( - cfg: &Config, - forge: &Forgejo, - http: &reqwest::Client, + remote: &impl Remote, + state_file: &Path, state: &mut cursor::State, repo: &str, ) -> Result<()> { - let runs = walk(forge, repo, state.repo(repo)).await?; + let runs = walk(remote, repo, state.repo(repo)).await?; let plan = pass::plan(state, repo, &runs, time::OffsetDateTime::now_utc()); - let mut skipped: BTreeMap = BTreeMap::new(); - for (_, why) in &plan.skip { - *skipped.entry(*why).or_default() += 1; - } + let skipped = skip_counts(&plan.skip); let pushing = plan.push.len(); let pending = plan.lowest_pending; let bearer = if pushing > 0 { - swarm_queue_client::mint_token_for(&cfg.queue, Some(&cfg.queue.client_id), None) + remote + .mint_token() .await .context("minting a token for the collector")? } else { @@ -139,8 +241,8 @@ async fn repo_pass( state, repo, plan, - async |samples| push(http, &cfg.metrics_url, &bearer, samples).await, - |s| s.save(&cfg.state_file), + async |samples| remote.post_otlp(&bearer, &otlp::body(samples)).await, + |s| s.save(state_file), ) .await?; tracing::info!( @@ -157,105 +259,131 @@ async fn repo_pass( /// The `cert` label this service's certificate is reported under. const CERT_LABEL: &str = "ci-metrics"; +/// The two `bao.client_cert.*` gauges for the certificate file at `path` (what +/// [`ENV_CLIENT_CERT`] names), stamped `now_nanos`. None when there is no path +/// or the file is not a readable certificate. +fn cert_gauges(path: Option<&str>, now_nanos: i128) -> Option { + let Some(path) = path else { + tracing::debug!("ci metrics: {ENV_CLIENT_CERT} is unset, no client-cert gauges"); + return None; + }; + match cert::file_validity(Path::new(path)) { + Ok((not_before, not_after)) => Some(otlp::cert_body( + CERT_LABEL, not_before, not_after, now_nanos, + )), + Err(e) => { + tracing::debug!(error = %e, "ci metrics: no client-cert gauges"); + None + } + } +} + /// Pushes the two `bao.client_cert.*` gauges for this service's own store -/// certificate ([`ENV_CLIENT_CERT`]), once per pass, stamped now. +/// certificate (`cert_path`, from [`ENV_CLIENT_CERT`]), once per pass, stamped +/// now. /// /// An unreadable file or a refused push is logged and the pass carries on: the /// runs are the pass's work, and this is a report about the process doing it. -async fn push_cert(cfg: &Config, http: &reqwest::Client) { - let Ok(path) = std::env::var(ENV_CLIENT_CERT) else { - tracing::debug!("ci metrics: {ENV_CLIENT_CERT} is unset, no client-cert gauges"); +async fn push_cert(remote: &impl Remote, cert_path: Option<&str>) { + let now = time::OffsetDateTime::now_utc().unix_timestamp_nanos(); + let Some(body) = cert_gauges(cert_path, now) else { return; }; - let (not_before, not_after) = match cert::file_validity(Path::new(&path)) { - Ok(window) => window, - Err(e) => { - tracing::debug!(error = %e, "ci metrics: no client-cert gauges"); - return; - } - }; - let now = time::OffsetDateTime::now_utc().unix_timestamp_nanos(); - let body = otlp::cert_body(CERT_LABEL, not_before, not_after, now); let pushed = async { - let bearer = - swarm_queue_client::mint_token_for(&cfg.queue, Some(&cfg.queue.client_id), None) - .await - .context("minting a token for the collector")?; - post(http, &cfg.metrics_url, &bearer, &body).await + let bearer = remote + .mint_token() + .await + .context("minting a token for the collector")?; + remote.post_otlp(&bearer, &body).await }; if let Err(e) = pushed.await { tracing::warn!(error = %format!("{e:#}"), "ci metrics: pushing the client-cert gauges failed"); } } +/// `r`'s `owner/name` when it has Actions and is neither archived nor a mirror. +fn wanted_repo(r: Repository) -> Option { + let wanted = r.has_actions == Some(true) && r.archived != Some(true) && r.mirror != Some(true); + r.full_name.filter(|_| wanted) +} + /// Every repo the account sees that has Actions and is neither archived nor a /// mirror, as `owner/name`. -async fn repos(forge: &Forgejo) -> Result> { +async fn repos(remote: &impl Remote) -> Result> { let mut out = Vec::new(); for page in 1.. { - let found = forge - .repo_search(RepoSearchQuery::default()) - .page(page) - .page_size(PAGE) - .send() + let found = remote + .search_repos(page) .await - .context("searching the forge's repos")? - .data - .unwrap_or_default(); + .context("searching the forge's repos")?; let last = found.len() < PAGE as usize; - out.extend(found.into_iter().filter_map(|r| { - let wanted = - r.has_actions == Some(true) && r.archived != Some(true) && r.mirror != Some(true); - r.full_name.filter(|_| wanted) - })); + out.extend(found.into_iter().filter_map(wanted_repo)); if last { break; } - tokio::time::sleep(PAGE_DELAY).await; + tokio::time::sleep(remote.page_delay()).await; } Ok(out) } +/// Whether the walk down a repo's runs stops after `found`, one page of them: +/// the page is short, so it was the last, or it holds a run below the cursor. +fn walk_done(found: &[ActionRun], cursor: &cursor::RepoCursor) -> bool { + found.len() < PAGE as usize + || found.iter().any(|r| { + r.index_in_repo + .and_then(|n| u64::try_from(n).ok()) + .is_some_and(|n| cursor.is_below(n)) + }) +} + /// The runs of `repo`, newest first, down to the first page that reaches below /// the cursor. -async fn walk(forge: &Forgejo, repo: &str, cursor: &cursor::RepoCursor) -> Result> { +async fn walk( + remote: &impl Remote, + repo: &str, + cursor: &cursor::RepoCursor, +) -> Result> { let (owner, name) = repo .split_once('/') .with_context(|| format!("{repo:?} is not owner/name"))?; let mut runs = Vec::new(); for page in 1.. { - let found = forge - .list_action_runs(owner, name, ListActionRunsQuery::default()) - .page(page) - .page_size(PAGE) - .send() + let found = remote + .list_runs(owner, name, page) .await - .with_context(|| format!("listing the runs of {repo}, page {page}"))? - .workflow_runs - .unwrap_or_default(); - let done = found.len() < PAGE as usize - || found.iter().any(|r| { - r.index_in_repo - .and_then(|n| u64::try_from(n).ok()) - .is_some_and(|n| cursor.is_below(n)) - }); + .with_context(|| format!("listing the runs of {repo}, page {page}"))?; + let done = walk_done(&found, cursor); runs.extend(found); if done { break; } - tokio::time::sleep(PAGE_DELAY).await; + tokio::time::sleep(remote.page_delay()).await; } Ok(runs) } -/// POST `samples` to the collector; an error unless it answers 2xx. -async fn push( +/// The request that POSTs one OTLP JSON `body` to the collector at `url`. +fn post_request( http: &reqwest::Client, url: &str, bearer: &str, - samples: &[sample::RunSamples], -) -> Result<()> { - post(http, url, bearer, &otlp::body(samples)).await + body: &serde_json::Value, +) -> Result { + http.post(url) + .bearer_auth(bearer) + .json(body) + .build() + .with_context(|| format!("pushing to {url}")) +} + +/// The error for a collector that answered `status` and `answer`: its start, +/// not a whole page of it. +fn refused(url: &str, status: reqwest::StatusCode, answer: &str) -> anyhow::Error { + anyhow!( + "{url} answered {status}: {}", + answer.chars().take(300).collect::() + ) } /// POST one OTLP JSON `body` to the collector; an error unless it answers 2xx. @@ -266,19 +394,13 @@ async fn post( body: &serde_json::Value, ) -> Result<()> { let resp = http - .post(url) - .bearer_auth(bearer) - .json(body) - .send() + .execute(post_request(http, url, bearer, body)?) .await .with_context(|| format!("pushing to {url}"))?; let status = resp.status(); if !status.is_success() { - let body = resp.text().await.unwrap_or_default(); - bail!( - "{url} answered {status}: {}", - body.chars().take(300).collect::() - ); + let answer = resp.text().await.unwrap_or_default(); + return Err(refused(url, status, &answer)); } Ok(()) } @@ -291,10 +413,16 @@ async fn forge_token() -> Result { .read_optional(&path) .await .with_context(|| format!("reading {path}"))?; - match stored { - Some(c) if !c.value.trim().is_empty() => Ok(c.value.trim().to_owned()), - _ => bail!("nothing at {path}: swarm-controller has not minted the ci-metrics forge token"), - } + let Some(token) = stored.and_then(|c| trimmed(&c.value)) else { + bail!("nothing at {path}: swarm-controller has not minted the ci-metrics forge token"); + }; + Ok(token) +} + +/// `value` without surrounding whitespace, or None when nothing is left. +fn trimmed(value: &str) -> Option { + let value = value.trim(); + (!value.is_empty()).then(|| value.to_owned()) } /// This service's OIDC client secret, which authelia's mint writes. @@ -305,13 +433,13 @@ async fn client_secret(client_id: &str) -> Result { .read_optional(&path) .await .with_context(|| format!("reading {path}"))?; - match stored { - Some(s) if !s.value.trim().is_empty() => Ok(s.value.trim().to_owned()), - _ => bail!( + let Some(secret) = stored.and_then(|s| trimmed(&s.value)) else { + bail!( "nothing at {path}: authelia's mint, in its container, has not \ stored this service's client secret" - ), - } + ); + }; + Ok(secret) } async fn login() -> Result { @@ -319,3 +447,775 @@ async fn login() -> Result { .await .context("logging in to the secret store") } + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + + use serde_json::{Value, json}; + + use super::*; + + /// The window [`cert_pem`] is built with, unix seconds: 2026-01-01T00:00:00Z + /// to 2026-04-01T00:00:00Z. + const CERT_NOT_BEFORE: i64 = 1_767_225_600; + const CERT_NOT_AFTER: i64 = 1_775_001_600; + + /// A certificate valid from [`CERT_NOT_BEFORE`] to [`CERT_NOT_AFTER`], + /// PEM-encoded. The name, key and signature are placeholders: the service + /// reads the window and verifies nothing. + fn cert_pem() -> String { + use x509_cert::der::{ + EncodePem as _, + asn1::{BitString, ObjectIdentifier, UtcTime}, + pem::LineEnding, + }; + use x509_cert::{ + Certificate, TbsCertificate, Version, + name::Name, + serial_number::SerialNumber, + spki::{AlgorithmIdentifierOwned, SubjectPublicKeyInfoOwned}, + time::{Time, Validity}, + }; + + let time = |secs: i64| { + let secs = u64::try_from(secs).expect("a date after 1970"); + Time::UtcTime( + UtcTime::from_unix_duration(std::time::Duration::from_secs(secs)) + .expect("a date UTCTime can hold"), + ) + }; + let algorithm = AlgorithmIdentifierOwned { + oid: ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2"), + parameters: None, + }; + let bits = BitString::from_bytes(&[0]).expect("a bit string"); + let cert = Certificate { + tbs_certificate: TbsCertificate { + version: Version::V3, + serial_number: SerialNumber::new(&[1]).expect("a serial number"), + signature: algorithm.clone(), + issuer: Name::default(), + validity: Validity { + not_before: time(CERT_NOT_BEFORE), + not_after: time(CERT_NOT_AFTER), + }, + subject: Name::default(), + subject_public_key_info: SubjectPublicKeyInfoOwned { + algorithm: algorithm.clone(), + subject_public_key: bits.clone(), + }, + issuer_unique_id: None, + subject_unique_id: None, + extensions: None, + }, + signature_algorithm: algorithm, + signature: bits, + }; + cert.to_pem(LineEnding::LF).expect("encodes") + } + + // ---- a stand-in for the forge, the identity provider and the collector, + // ---- answering from memory + + /// What the stand-in answers: a value, or the text of an error. + type Reply = Result; + + /// One call the stand-in took. + #[derive(Debug, Clone, PartialEq)] + enum Call { + Search(u32), + Runs(String, u32), + Token, + Post { bearer: String, body: Value }, + } + + struct Fake { + /// The repo search, one reply per page (JSON `Repository`s). + search: Vec>>, + /// The runs of each `owner/name`, one reply per page (JSON `ActionRun`s). + runs: BTreeMap<&'static str, Vec>>>, + token: Reply<&'static str>, + /// What each post answers, in order; the rest succeed. + posts: Mutex>>, + calls: Mutex>, + } + + impl Fake { + fn new() -> Self { + Self { + search: Vec::new(), + runs: BTreeMap::new(), + token: Ok("tok"), + posts: Mutex::new(Vec::new()), + calls: Mutex::new(Vec::new()), + } + } + + fn with_runs(mut self, repo: &'static str, pages: Vec>>) -> Self { + self.runs.insert(repo, pages); + self + } + + fn with_posts(self, replies: Vec>) -> Self { + *self.posts.lock().expect("the replies") = replies; + self + } + + fn calls(&self) -> Vec { + self.calls.lock().expect("the calls").clone() + } + + fn log(&self, call: Call) { + self.calls.lock().expect("the calls").push(call); + } + + /// The bodies posted to the collector, in order. + fn posted(&self) -> Vec { + self.calls() + .into_iter() + .filter_map(|c| match c { + Call::Post { body, .. } => Some(body), + _ => None, + }) + .collect() + } + } + + fn pages(replies: &[Reply>], page: u32) -> Reply> + where + T: Clone, + { + replies + .get(page as usize - 1) + .cloned() + .unwrap_or(Ok(Vec::new())) + } + + impl Remote for Fake { + fn page_delay(&self) -> Duration { + Duration::ZERO + } + + async fn search_repos(&self, page: u32) -> Result> { + self.log(Call::Search(page)); + pages(&self.search, page) + .map_err(|e| anyhow!(e))? + .into_iter() + .map(|v| Ok(serde_json::from_value(v)?)) + .collect() + } + + async fn list_runs(&self, owner: &str, name: &str, page: u32) -> Result> { + let repo = format!("{owner}/{name}"); + self.log(Call::Runs(repo.clone(), page)); + pages( + self.runs.get(repo.as_str()).map_or(&[], Vec::as_slice), + page, + ) + .map_err(|e| anyhow!(e))? + .into_iter() + .map(|v| Ok(serde_json::from_value(v)?)) + .collect() + } + + async fn mint_token(&self) -> Result { + self.log(Call::Token); + self.token.map(str::to_owned).map_err(|e| anyhow!(e)) + } + + async fn post_otlp(&self, bearer: &str, body: &Value) -> Result<()> { + self.log(Call::Post { + bearer: bearer.to_owned(), + body: body.clone(), + }); + let mut replies = self.posts.lock().expect("the replies"); + let reply = if replies.is_empty() { + Ok(()) + } else { + replies.remove(0) + }; + reply.map_err(|e| anyhow!(e)) + } + } + + // ---- fixtures + + fn env_of( + pairs: &[(&str, &str)], + ) -> impl Fn(&str) -> Result + use<> { + let map: BTreeMap = pairs + .iter() + .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) + .collect(); + move |key| map.get(key).cloned().ok_or(std::env::VarError::NotPresent) + } + + const ALL_SETTINGS: [(&str, &str); 5] = [ + ("STATE_DIRECTORY", "/var/lib/swarm-ci-metrics"), + ("SWARM_CI_METRICS_FORGE_URL", "https://forge.example/"), + ( + "SWARM_CI_METRICS_OTLP_ENDPOINT", + "https://collector.example/route//", + ), + ( + "SWARM_CI_METRICS_OIDC_TOKEN_ENDPOINT", + "https://auth.example/api/oidc/token", + ), + ("SWARM_CI_METRICS_OIDC_CLIENT_ID", "swarm-ci-metrics"), + ]; + + /// A finished run as the forge lists it, number `n`. + fn finished(n: i64) -> Value { + json!({ + "index_in_repo": n, + "status": "success", + "event": "pull_request", + "prettyref": format!("#{n}"), + "workflow_id": "ci.yml", + "commit_sha": format!("{n:040}"), + "created": "2026-10-16T16:50:38+02:00", + "started": "2026-10-16T16:55:17+02:00", + "stopped": "2026-10-16T17:13:30+02:00", + "updated": null, + "html_url": null, + }) + } + + /// A run still going, with no `created` so that it is never abandoned. + fn going(n: i64) -> Value { + json!({ + "index_in_repo": n, + "status": "running", + "event": "push", + "prettyref": "main", + "workflow_id": "ci.yml", + "commit_sha": format!("{n:040}"), + "created": null, + "started": null, + "stopped": null, + "updated": null, + "html_url": null, + }) + } + + fn action_run(v: Value) -> ActionRun { + serde_json::from_value(v).expect("an ActionRun") + } + + fn repository(v: Value) -> Repository { + serde_json::from_value(v).expect("a Repository") + } + + /// A full page of runs numbered downward from `from`. + fn full_page(from: i64) -> Vec { + (0..i64::from(PAGE)).map(|i| finished(from - i)).collect() + } + + /// The `dataPoints` of the `n`th gauge of an OTLP body. + fn points(body: &Value, n: usize) -> usize { + body["resourceMetrics"][0]["scopeMetrics"][0]["metrics"][n]["gauge"]["dataPoints"] + .as_array() + .expect("points") + .len() + } + + // ---- the settings + + #[test] + fn the_settings_come_from_the_units_environment() { + let env = Env::read(&env_of(&ALL_SETTINGS)).expect("every setting is set"); + assert_eq!(env.forge_url.as_str(), "https://forge.example/"); + // Every trailing slash of the endpoint goes before the path is added. + assert_eq!( + env.metrics_url, + "https://collector.example/route/v1/metrics" + ); + assert_eq!(env.token_endpoint, "https://auth.example/api/oidc/token"); + assert_eq!( + env.state_file, + PathBuf::from("/var/lib/swarm-ci-metrics/cursor.json") + ); + assert_eq!( + var(&env_of(&ALL_SETTINGS), "OIDC_CLIENT_ID").expect("set"), + "swarm-ci-metrics" + ); + } + + #[test] + fn an_unset_setting_is_named_by_its_full_variable() { + for (missing, named) in [ + ("STATE_DIRECTORY", "STATE_DIRECTORY"), + ("SWARM_CI_METRICS_FORGE_URL", "SWARM_CI_METRICS_FORGE_URL"), + ( + "SWARM_CI_METRICS_OTLP_ENDPOINT", + "SWARM_CI_METRICS_OTLP_ENDPOINT", + ), + ( + "SWARM_CI_METRICS_OIDC_TOKEN_ENDPOINT", + "SWARM_CI_METRICS_OIDC_TOKEN_ENDPOINT", + ), + ] { + let others: Vec<(&str, &str)> = ALL_SETTINGS + .iter() + .copied() + .filter(|(k, _)| *k != missing) + .collect(); + let Err(e) = Env::read(&env_of(&others)) else { + panic!("{missing} was not needed"); + }; + assert_eq!( + format!("{e:#}").split(':').next(), + Some(format!("{named} is unset").as_str()) + ); + } + let Err(e) = var(&env_of(&[]), "OIDC_CLIENT_ID") else { + panic!("an empty environment has a client id"); + }; + assert!( + format!("{e:#}").starts_with("SWARM_CI_METRICS_OIDC_CLIENT_ID is unset"), + "{e:#}" + ); + } + + #[test] + fn a_forge_url_that_does_not_parse_is_an_error() { + let bad: Vec<(&str, &str)> = ALL_SETTINGS + .iter() + .map(|&(k, v)| { + if k == "SWARM_CI_METRICS_FORGE_URL" { + (k, "not a url") + } else { + (k, v) + } + }) + .collect(); + let Err(e) = Env::read(&env_of(&bad)) else { + panic!("a bad URL was accepted"); + }; + assert!(format!("{e:#}").contains("parsing the forge URL"), "{e:#}"); + } + + // ---- the small decisions + + #[test] + fn a_repo_is_polled_only_with_actions_and_neither_archived_nor_a_mirror() { + let repo = |extra: Value| { + let mut v = json!({ "full_name": "o/r", "has_actions": true }); + v.as_object_mut() + .expect("an object") + .extend(extra.as_object().expect("an object").clone()); + wanted_repo(repository(v)) + }; + assert_eq!(repo(json!({})), Some("o/r".to_owned())); + assert_eq!( + repo(json!({ "archived": false, "mirror": false })), + Some("o/r".to_owned()) + ); + assert_eq!(repo(json!({ "has_actions": false })), None); + assert_eq!(repo(json!({ "has_actions": null })), None); + assert_eq!(repo(json!({ "archived": true })), None); + assert_eq!(repo(json!({ "mirror": true })), None); + assert_eq!( + wanted_repo(repository(json!({ "has_actions": true }))), + None + ); + } + + #[test] + fn the_walk_stops_on_a_short_page_or_a_page_below_the_cursor() { + let cursor = cursor::RepoCursor { + low: 100, + ..cursor::RepoCursor::default() + }; + let full = |from: i64| -> Vec { + (0..i64::from(PAGE)) + .map(|i| action_run(finished(from + i))) + .collect() + }; + // A short page is the last one. + assert!(walk_done(&full(500)[..10], &cursor)); + assert!(walk_done(&[], &cursor)); + // A full page of runs above the cursor has more behind it. + assert!(!walk_done(&full(500), &cursor)); + // A full page that reaches below the cursor does not. + assert!(walk_done(&full(80), &cursor)); + // A run with no number is no evidence either way. + let mut nameless = full(500); + nameless[0] = action_run( + json!({ "status": "success", "created": null, "started": null, + "stopped": null, "updated": null, "html_url": null }), + ); + assert!(!walk_done(&nameless, &cursor)); + } + + #[test] + fn an_empty_or_blank_stored_value_is_nothing() { + assert_eq!(trimmed(" tok\n"), Some("tok".to_owned())); + assert_eq!(trimmed("tok"), Some("tok".to_owned())); + assert_eq!(trimmed(""), None); + assert_eq!(trimmed(" \t\n"), None); + } + + #[test] + fn a_pass_fails_when_any_repo_did_and_says_how_many() { + assert!(finish(0, 5).is_ok()); + assert!(finish(0, 0).is_ok()); + assert_eq!( + finish(1, 5).expect_err("one failed").to_string(), + "1 of 5 repos failed; their cursors stay where they were" + ); + let e = finish(2, 5).expect_err("two failed"); + assert_eq!( + e.to_string(), + "2 of 5 repos failed; their cursors stay where they were" + ); + } + + #[test] + fn skipped_runs_are_counted_by_reason() { + use sample::Skip::{Abandoned, Cancelled}; + let counts = skip_counts(&[(1, Cancelled), (2, Abandoned), (3, Cancelled)]); + assert_eq!(counts.get(&Cancelled), Some(&2)); + assert_eq!(counts.get(&Abandoned), Some(&1)); + assert_eq!(counts.len(), 2); + assert!(skip_counts(&[]).is_empty()); + } + + // ---- the certificate gauges + + #[test] + fn the_cert_gauges_report_the_files_window_at_the_given_time() { + let dir = tempfile::tempdir().expect("a scratch dir"); + let path = dir.path().join("cert.pem"); + std::fs::write(&path, cert_pem()).expect("the cert"); + let body = cert_gauges(path.to_str(), 42).expect("a readable certificate"); + let metrics = &body["resourceMetrics"][0]["scopeMetrics"][0]["metrics"]; + let value = |n: usize| { + metrics[n]["gauge"]["dataPoints"][0]["asInt"] + .as_str() + .expect("an int") + .to_owned() + }; + assert_eq!(value(0), CERT_NOT_BEFORE.to_string()); + assert_eq!(value(1), CERT_NOT_AFTER.to_string()); + assert_eq!( + metrics[0]["gauge"]["dataPoints"][0]["timeUnixNano"], + json!("42") + ); + } + + #[test] + fn no_gauges_without_a_path_or_with_a_file_that_is_no_certificate() { + assert!(cert_gauges(None, 1).is_none()); + assert!(cert_gauges(Some("/nonexistent/cert.pem"), 1).is_none()); + let dir = tempfile::tempdir().expect("a scratch dir"); + let path = dir.path().join("cert.pem"); + std::fs::write(&path, "not a certificate").expect("the file"); + assert!(cert_gauges(path.to_str(), 1).is_none()); + } + + // ---- the request to the collector + + #[test] + fn a_post_is_a_json_post_with_the_bearer() { + let request = post_request( + &reqwest::Client::new(), + "https://collector.example/in", + "tok", + &json!({ "a": 1 }), + ) + .expect("a request"); + assert_eq!(request.method(), reqwest::Method::POST); + assert_eq!(request.url().as_str(), "https://collector.example/in"); + assert_eq!(request.headers()["authorization"], "Bearer tok"); + assert_eq!(request.headers()["content-type"], "application/json"); + let body = request.body().and_then(|b| b.as_bytes()).expect("a body"); + assert_eq!(body, br#"{"a":1}"#); + } + + #[test] + fn a_refusal_names_the_url_the_status_and_the_start_of_the_answer() { + let long = "x".repeat(400); + let e = refused( + "https://collector.example/in", + reqwest::StatusCode::SERVICE_UNAVAILABLE, + &long, + ); + assert_eq!( + e.to_string(), + format!( + "https://collector.example/in answered 503 Service Unavailable: {}", + "x".repeat(300) + ) + ); + assert_eq!( + refused("u", reqwest::StatusCode::BAD_GATEWAY, "short").to_string(), + "u answered 502 Bad Gateway: short" + ); + } + + #[tokio::test] + async fn a_post_to_nothing_names_the_url_it_could_not_reach() { + // Port 0 is never listenable, so the connect fails and nothing is bound. + let gone = "http://127.0.0.1:0/in"; + let e = post(&reqwest::Client::new(), gone, "tok", &json!({})) + .await + .expect_err("nobody listens"); + assert_eq!(e.to_string(), format!("pushing to {gone}")); + } + + // ---- the repo search + + #[tokio::test] + async fn the_repos_polled_are_the_search_hits_that_pass_the_filter() { + let mut fake = Fake::new(); + fake.search = vec![Ok(vec![ + json!({ "full_name": "o/a", "has_actions": true }), + json!({ "full_name": "o/archived", "has_actions": true, "archived": true }), + json!({ "full_name": "o/mirror", "has_actions": true, "mirror": true }), + json!({ "full_name": "o/no-actions", "has_actions": false }), + json!({ "full_name": "o/b", "has_actions": true }), + ])]; + assert_eq!(repos(&fake).await.expect("a search"), ["o/a", "o/b"]); + assert_eq!(fake.calls(), [Call::Search(1)]); + } + + #[tokio::test] + async fn a_full_page_of_hits_has_a_next_page_and_a_short_one_ends_the_search() { + let page = |name: &str| -> Vec { + let mut hits = vec![json!({ "full_name": name, "has_actions": true })]; + hits.extend((1..PAGE).map(|_| json!({ "full_name": "o/x", "has_actions": false }))); + hits + }; + let mut fake = Fake::new(); + fake.search = vec![ + Ok(page("o/first")), + Ok(vec![json!({ "full_name": "o/last", "has_actions": true })]), + Ok(vec![json!({ "full_name": "o/never", "has_actions": true })]), + ]; + assert_eq!(repos(&fake).await.expect("a search"), ["o/first", "o/last"]); + assert_eq!(fake.calls(), [Call::Search(1), Call::Search(2)]); + } + + #[tokio::test] + async fn a_search_the_forge_refuses_is_an_error_naming_it() { + let mut fake = Fake::new(); + fake.search = vec![Err("the forge said 500")]; + let e = repos(&fake).await.expect_err("a refused search"); + assert!( + format!("{e:#}").contains("searching the forge's repos"), + "{e:#}" + ); + assert!(format!("{e:#}").contains("the forge said 500"), "{e:#}"); + } + + // ---- the walk down one repo's runs + + #[tokio::test] + async fn a_walk_reads_the_runs_the_forge_lists() { + let fake = Fake::new().with_runs("o/r", vec![Ok(vec![finished(3), finished(2), going(1)])]); + let runs = walk(&fake, "o/r", &cursor::RepoCursor::default()) + .await + .expect("a listing"); + assert_eq!(runs.len(), 3); + assert_eq!(fake.calls(), [Call::Runs("o/r".to_owned(), 1)]); + } + + #[tokio::test] + async fn a_walk_goes_on_past_a_full_page_above_the_cursor_and_stops_below_it() { + let cursor = cursor::RepoCursor { + low: 100, + ..cursor::RepoCursor::default() + }; + // Page 1 is full and above the cursor, page 2 is full and reaches below + // it, so page 3 is never asked for. + let fake = Fake::new().with_runs( + "o/r", + vec![ + Ok(full_page(500)), + Ok(full_page(120)), + Ok(vec![finished(1)]), + ], + ); + let runs = walk(&fake, "o/r", &cursor).await.expect("a listing"); + assert_eq!(runs.len(), 2 * PAGE as usize); + assert_eq!( + fake.calls(), + [ + Call::Runs("o/r".to_owned(), 1), + Call::Runs("o/r".to_owned(), 2) + ] + ); + } + + #[tokio::test] + async fn a_failed_listing_names_the_repo_and_the_page() { + let fake = + Fake::new().with_runs("o/r", vec![Ok(full_page(500)), Err("the forge said 500")]); + let e = walk(&fake, "o/r", &cursor::RepoCursor::default()) + .await + .expect_err("a refused listing"); + assert!( + format!("{e:#}").contains("listing the runs of o/r, page 2"), + "{e:#}" + ); + assert!(format!("{e:#}").contains("the forge said 500"), "{e:#}"); + } + + #[tokio::test] + async fn a_repo_name_without_an_owner_is_refused_before_any_request() { + let fake = Fake::new(); + let e = walk(&fake, "norepo", &cursor::RepoCursor::default()) + .await + .expect_err("no owner"); + assert!(format!("{e:#}").contains("is not owner/name"), "{e:#}"); + assert!(fake.calls().is_empty()); + } + + // ---- one repo's pass, end to end + + #[tokio::test] + async fn a_repo_pass_pushes_the_finished_runs_and_moves_the_cursor_to_the_one_still_going() { + let dir = tempfile::tempdir().expect("a scratch dir"); + let state_file = dir.path().join("cursor.json"); + let fake = Fake::new().with_runs("o/r", vec![Ok(vec![going(3), finished(2), finished(1)])]); + let mut state = cursor::State::default(); + repo_pass(&fake, &state_file, &mut state, "o/r") + .await + .expect("a pass"); + let calls = fake.calls(); + assert_eq!(calls[..2], [Call::Runs("o/r".to_owned(), 1), Call::Token]); + let Call::Post { bearer, body } = &calls[2] else { + panic!("a push after the token: {calls:?}"); + }; + assert_eq!(bearer, "tok"); + assert_eq!(points(body, 0), 2); + assert_eq!(calls.len(), 3, "one chunk of two runs"); + let saved = cursor::State::load(&state_file).expect("a saved cursor"); + assert_eq!(saved.repos["o/r"].low, 3); + assert!(saved.repos["o/r"].handled.is_empty()); + } + + #[tokio::test] + async fn the_samples_pushed_are_the_otlp_body_of_the_finished_runs() { + let dir = tempfile::tempdir().expect("a scratch dir"); + let fake = Fake::new().with_runs("o/r", vec![Ok(vec![finished(1)])]); + let mut state = cursor::State::default(); + repo_pass(&fake, &dir.path().join("cursor.json"), &mut state, "o/r") + .await + .expect("a pass"); + let verdict = sample::classify( + "o/r", + &action_run(finished(1)), + time::OffsetDateTime::now_utc(), + ); + let sample::Verdict::Push(samples) = verdict else { + panic!("a finished run is pushed"); + }; + assert_eq!(fake.posted(), [otlp::body(std::slice::from_ref(&*samples))]); + } + + #[tokio::test] + async fn a_push_the_collector_refuses_leaves_the_cursor_where_it_was() { + let dir = tempfile::tempdir().expect("a scratch dir"); + let state_file = dir.path().join("cursor.json"); + let fake = Fake::new() + .with_runs("o/r", vec![Ok(vec![finished(2), finished(1)])]) + .with_posts(vec![Err("the collector said 503")]); + let mut state = cursor::State::default(); + let e = repo_pass(&fake, &state_file, &mut state, "o/r") + .await + .expect_err("a refused push"); + assert!(format!("{e:#}").contains("the collector said 503"), "{e:#}"); + assert!(!state_file.exists(), "nothing was marked handled on disk"); + assert!(state.repos["o/r"].handled.is_empty()); + } + + #[tokio::test] + async fn a_pass_with_nothing_to_push_mints_no_token_but_still_moves_the_cursor() { + let dir = tempfile::tempdir().expect("a scratch dir"); + let state_file = dir.path().join("cursor.json"); + let fake = Fake::new().with_runs("o/r", vec![Ok(vec![going(7)])]); + let mut state = cursor::State::default(); + repo_pass(&fake, &state_file, &mut state, "o/r") + .await + .expect("a pass"); + assert_eq!(fake.calls(), [Call::Runs("o/r".to_owned(), 1)]); + let saved = cursor::State::load(&state_file).expect("a saved cursor"); + assert_eq!(saved.repos["o/r"].low, 7); + } + + #[tokio::test] + async fn a_token_the_identity_provider_refuses_fails_the_pass_before_any_push() { + let dir = tempfile::tempdir().expect("a scratch dir"); + let state_file = dir.path().join("cursor.json"); + let mut fake = Fake::new().with_runs("o/r", vec![Ok(vec![finished(1)])]); + fake.token = Err("the provider said 401"); + let mut state = cursor::State::default(); + let e = repo_pass(&fake, &state_file, &mut state, "o/r") + .await + .expect_err("a refused token"); + assert!( + format!("{e:#}").contains("minting a token for the collector"), + "{e:#}" + ); + assert!(fake.posted().is_empty()); + assert!(!state_file.exists()); + } + + #[tokio::test] + async fn a_repo_whose_listing_fails_fails_its_pass() { + let dir = tempfile::tempdir().expect("a scratch dir"); + let fake = Fake::new().with_runs("o/r", vec![Err("the forge said 500")]); + let mut state = cursor::State::default(); + let e = repo_pass(&fake, &dir.path().join("cursor.json"), &mut state, "o/r") + .await + .expect_err("a refused listing"); + assert!( + format!("{e:#}").contains("listing the runs of o/r"), + "{e:#}" + ); + } + + // ---- the certificate push + + #[tokio::test] + async fn the_cert_gauges_are_pushed_with_a_minted_bearer() { + let dir = tempfile::tempdir().expect("a scratch dir"); + let cert = dir.path().join("cert.pem"); + std::fs::write(&cert, cert_pem()).expect("the cert"); + let fake = Fake::new(); + push_cert(&fake, cert.to_str()).await; + let calls = fake.calls(); + assert_eq!(calls.len(), 2); + assert_eq!(calls[0], Call::Token); + let Call::Post { bearer, body } = &calls[1] else { + panic!("a push after the token: {calls:?}"); + }; + assert_eq!(bearer, "tok"); + assert!(body.to_string().contains(&CERT_NOT_AFTER.to_string())); + } + + #[tokio::test] + async fn without_a_certificate_the_pass_pushes_no_gauges_and_asks_for_no_token() { + let fake = Fake::new(); + push_cert(&fake, None).await; + push_cert(&fake, Some("/nonexistent/cert.pem")).await; + assert!(fake.calls().is_empty()); + } + + #[tokio::test] + async fn a_refused_cert_push_is_logged_and_the_pass_carries_on() { + let dir = tempfile::tempdir().expect("a scratch dir"); + let cert = dir.path().join("cert.pem"); + std::fs::write(&cert, cert_pem()).expect("the cert"); + let mut refused_token = Fake::new(); + refused_token.token = Err("the provider said 401"); + push_cert(&refused_token, cert.to_str()).await; + assert_eq!(refused_token.calls(), [Call::Token]); + let refused_push = Fake::new().with_posts(vec![Err("the collector said 500")]); + push_cert(&refused_push, cert.to_str()).await; + assert_eq!(refused_push.posted().len(), 1); + } +}