feat(test-client): add buzz-acceptance relay probe (#9767)

## Summary

Adds `buzz-acceptance`, a third binary in `buzz-test-client` (next to
`buzz-loadgen`). One run checks the relay's core jobs once against one
relay and exits. It is meant to run on a schedule (for example a
Kubernetes CronJob) or as a deployment step (for example an Argo
Rollouts `job` analysis against the canary Service).

Checks, in order:

| Check | Stages |
|---|---|
| `relay_info` | `nip11` (the response must be a NIP-11 document) |
| `connect_auth` | `ws_connect`, `nip42_auth` |
| `channel_create` | `create` (a private, per-run channel with a 1 h
TTL) |
| `publish` | `ok` |
| `fanout` | `connect_second`, `subscribe`, `publish`, `receive` |
| `history` | `req_eose` (the published event is in a fresh REQ, intact)
|
| `access_control` | `unauthenticated_rejected`,
`pubkey_mismatch_rejected` |
| `cleanup` | `connect`, `delete_channel` (on a fresh connection) |

`access_control` passes only on the relay's own denial reasons:
`auth-required:` for a write on a socket that sent the NIP-FI assertion
but skipped NIP-42 AUTH, and `invalid: event pubkey does not match
authenticated identity` for a write signed by another key. A closed
socket or any other reason fails the stage.

`fanout` reads the listener while the publish waits for its OK, so
`receive` measures delivery (publish → arrival on the second socket),
not the publisher's acknowledgement.

`fanout` and `history` verify the event they get back (`Event::verify`:
id and signature against its content). An event the relay corrupted
under its original id fails the stage.

A channel is never stranded on purpose. If the create times out or the
socket drops, the probe keeps the channel id and `cleanup` deletes it
over a fresh connection. A failed cleanup names the channel. The TTL
archives any channel a killed run leaves behind.

Output:

- A JSON report on stdout: each check's result, the stage that failed,
and each completed stage's duration.
- Optional DogStatsD metrics (`--statsd-addr`): `<prefix>.runs`,
`<prefix>.run.seconds`, `<prefix>.check.runs{check,result,stage}`,
`<prefix>.check.seconds{check,result}`,
`<prefix>.stage.seconds{check,stage}`. Every series also carries
`relay_version` (from NIP-11) and any `--tag k:v`.
- Exit code 0 when every check passed, 1 when a check failed, 2 when the
probe could not run or send its metrics.

A check whose prerequisite failed is reported as `skipped`, so each
failure is counted once, at its cause, and every run reports the same
set of checks.

### NIP-FI

On a relay that enforces NIP-FI, pass `--assertion-file` (a regular
file, at most 16 KiB; a FIFO or larger file fails the connection at
once). The probe reads the file before every connection and sends it as
`Nostr-Federated-Identity: Bearer …`. Another process (for example a
sidecar) keeps it fresh. How the assertion is minted is deployment
configuration and stays out of this repo.

## What got simpler

Nothing got simpler. This adds one binary. It reuses `buzz-ws-client`
and the crate's existing dependencies, and adds no new crate and no new
dependency (`clap` gains its `env` feature).

## Testing

- Unit tests drive the probe against a scripted relay: a publisher OK
that arrives 600 ms after delivery (`receive` stays under 300 ms), a
refusal with the wrong reason and a closed socket (both fail
`access_control`), an unanswered create and a socket lost after create
(both still delete that exact channel), and a failed cleanup (the error
names the channel). Also: metric lines and tags, one datagram per line,
stage timeout, assertion file limits, and an unreachable relay.
- `tests/e2e_acceptance.rs` runs in CI's Relay E2E lane against a live
relay. It runs the shared runner and the binary itself: exit 0 with JSON
and datagrams on a pass, exit 1 when a check fails, exit 2 when the
probe cannot run.

## Follow-ups (not in this PR)

- Image and CronJob / Rollouts wiring.
- Before the probe can gate a canary: a dial override that keeps the
canonical Host and signed relay URL (like `buzz-loadgen`'s
`connect_addr`).
- Before it can gate a promotion: a build identifier from the relay.
`relay_version` is the Cargo package version, which several image builds
can share.
- Confirm the delete took effect: read the channel back after
`delete_channel` returns `OK true`. This needs a stable relay read
contract for deleted channels. Until then the 1 h TTL bounds any channel
a silent delete failure leaves behind. The scheduled deployment can also
sweep stale probe channels at start.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Luke Tornquist
2026-11-20 14:16:02 -05:00
committed by GitHub
parent e95d7a9509
commit 9f49216f8b
10 changed files with 1745 additions and 8 deletions

View File

@@ -692,7 +692,7 @@ jobs:
./scripts/start-relay-for-tests.sh --no-build
- name: Relay E2E tests
run: |
cargo test -p buzz-test-client --test e2e_persona --test e2e_team_catalog --test e2e_nostr_interop --test e2e_thread_roots --test e2e_project -- --ignored --nocapture
cargo test -p buzz-test-client --test e2e_persona --test e2e_team_catalog --test e2e_nostr_interop --test e2e_thread_roots --test e2e_project --test e2e_acceptance -- --ignored --nocapture
cargo test -p buzz-test-client --test e2e_relay invite -- --ignored --nocapture
cargo test -p buzz-test-client --test e2e_relay nip43_membership_snapshots_are_rejected -- --ignored --nocapture
cargo test -p buzz-test-client --test e2e_relay nip_ia_archive_snapshots_are_rejected -- --ignored --nocapture

View File

@@ -679,9 +679,10 @@ test-unit:
# relay events and agent prompts. They are infra-free; ignored lifecycle
# tests remain excluded and run in their dedicated integration lanes.
cargo nextest run -p buzz-acp --lib
# Load generator scenario, identity, shard and stats unit tests; all
# infra-free. Keep scripts/run-tests.sh in step.
cargo nextest run -p buzz-test-client --lib -E 'test(/^loadgen::/)'
# Load generator and acceptance probe unit tests; all infra-free (the
# probe's run against a scripted in-process relay). Keep
# scripts/run-tests.sh in step.
cargo nextest run -p buzz-test-client --lib -E 'test(/^(loadgen|acceptance)::/)'
else
./scripts/run-tests.sh unit
fi

View File

@@ -24,7 +24,7 @@ uuid = { workspace = true }
url = { workspace = true }
rustls = "0.23"
base64 = { workspace = true }
clap = { version = "4", features = ["derive"] }
clap = { version = "4", features = ["derive", "env"] }
hex = { workspace = true }
reqwest = { workspace = true }
sha2 = { workspace = true }
@@ -53,3 +53,7 @@ path = "src/main.rs"
[[bin]]
name = "buzz-loadgen"
path = "src/bin/loadgen.rs"
[[bin]]
name = "buzz-acceptance"
path = "src/bin/acceptance.rs"

View File

@@ -0,0 +1,193 @@
//! A scripted relay for the probe's tests: just enough NIP-01 and NIP-42 to
//! run every check, with knobs to delay, drop or close on chosen writes,
//! or to corrupt the events it serves.
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use futures_util::{SinkExt, StreamExt};
use nostr::{Event, PublicKey};
use serde_json::{json, Value};
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use tokio_tungstenite::tungstenite::Message;
use super::{AUTH_REQUIRED, PUBKEY_MISMATCH};
/// How the relay answers a write on a connection that skipped AUTH.
pub enum Unauthenticated {
/// `OK false` with this reason.
Reason(String),
/// Close the socket without answering.
Close,
}
/// What the relay does differently from accepting every write at once.
pub struct Script {
/// Wait this long before the OK for these kinds.
pub ack_delay: HashMap<u16, Duration>,
/// Never answer writes of these kinds (they are still stored).
pub no_ack: HashSet<u16>,
/// Accept writes of these kinds, then close the socket.
pub close_after: HashSet<u16>,
/// The answer to a write without AUTH.
pub unauthenticated: Unauthenticated,
/// Serve events of these kinds, stored and live, with altered content
/// under their original id and signature.
pub corrupt: HashSet<u16>,
}
impl Default for Script {
fn default() -> Self {
Self {
ack_delay: HashMap::new(),
no_ack: HashSet::new(),
close_after: HashSet::new(),
unauthenticated: Unauthenticated::Reason(format!("{AUTH_REQUIRED} not authenticated")),
corrupt: HashSet::new(),
}
}
}
type Outbox = mpsc::UnboundedSender<String>;
impl Script {
/// `event` as the relay serves it.
fn served(&self, event: &Event) -> Value {
let mut value = json!(event);
if self.corrupt.contains(&event.kind.as_u16()) {
value["content"] = json!(format!("{} (corrupted)", event.content));
}
value
}
}
struct Shared {
script: Script,
/// Every event written to the relay, accepted or not, in order.
events: Mutex<Vec<Event>>,
/// Live subscriptions: subscription id and the connection to send to.
live: Mutex<Vec<(String, Outbox)>>,
}
/// A running scripted relay.
pub struct FakeRelay {
/// Its `ws://` URL.
pub url: String,
shared: Arc<Shared>,
}
impl FakeRelay {
/// Every event written so far, in order.
pub fn events(&self) -> Vec<Event> {
self.shared.events.lock().unwrap().clone()
}
}
/// Starts a relay that follows `script` on a free local port.
pub async fn start(script: Script) -> FakeRelay {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("ws://{}", listener.local_addr().unwrap());
let shared = Arc::new(Shared {
script,
events: Mutex::new(Vec::new()),
live: Mutex::new(Vec::new()),
});
let accept = shared.clone();
tokio::spawn(async move {
while let Ok((tcp, _)) = listener.accept().await {
tokio::spawn(serve(tcp, accept.clone()));
}
});
FakeRelay { url, shared }
}
async fn serve(tcp: tokio::net::TcpStream, shared: Arc<Shared>) {
// A plain HTTP request (the NIP-11 fetch) fails the upgrade; that is fine.
let Ok(ws) = tokio_tungstenite::accept_async(tcp).await else {
return;
};
let (mut sink, mut stream) = ws.split();
let (out, mut outbox) = mpsc::unbounded_channel::<String>();
let writer = tokio::spawn(async move {
while let Some(text) = outbox.recv().await {
if sink.send(Message::Text(text.into())).await.is_err() {
break;
}
}
});
let send = |out: &Outbox, value: Value| {
let _ = out.send(value.to_string());
};
send(&out, json!(["AUTH", "challenge"]));
let mut authed: Option<PublicKey> = None;
while let Some(Ok(frame)) = stream.next().await {
let Message::Text(text) = frame else { continue };
let Ok(Value::Array(msg)) = serde_json::from_str::<Value>(&text) else {
continue;
};
match msg.first().and_then(Value::as_str) {
Some("AUTH") => {
let event: Event = serde_json::from_value(msg[1].clone()).unwrap();
authed = Some(event.pubkey);
send(&out, json!(["OK", event.id.to_hex(), true, ""]));
}
Some("REQ") => {
let sub = msg[1].as_str().unwrap().to_string();
let filter = &msg[2];
if let Some(ids) = filter["ids"].as_array() {
let stored = shared.events.lock().unwrap().clone();
for event in stored {
if ids.contains(&json!(event.id.to_hex())) {
send(&out, json!(["EVENT", sub, shared.script.served(&event)]));
}
}
}
if filter["limit"] == json!(0) {
shared.live.lock().unwrap().push((sub.clone(), out.clone()));
}
send(&out, json!(["EOSE", sub]));
}
Some("EVENT") => {
let event: Event = serde_json::from_value(msg[1].clone()).unwrap();
shared.events.lock().unwrap().push(event.clone());
let id = event.id.to_hex();
let Some(pubkey) = authed else {
match &shared.script.unauthenticated {
Unauthenticated::Reason(reason) => {
send(&out, json!(["OK", id, false, reason]))
}
Unauthenticated::Close => break,
}
continue;
};
if event.pubkey != pubkey {
send(&out, json!(["OK", id, false, PUBKEY_MISMATCH]));
continue;
}
let kind = event.kind.as_u16();
if kind == super::KIND_MESSAGE {
let served = shared.script.served(&event);
for (sub, to) in shared.live.lock().unwrap().iter() {
send(to, json!(["EVENT", sub, served]));
}
}
if shared.script.no_ack.contains(&kind) {
continue;
}
if let Some(delay) = shared.script.ack_delay.get(&kind) {
tokio::time::sleep(*delay).await;
}
send(&out, json!(["OK", id, true, ""]));
if shared.script.close_after.contains(&kind) {
break;
}
}
_ => {}
}
}
drop(out);
let _ = writer.await;
}

View File

@@ -0,0 +1,213 @@
//! DogStatsD lines for an acceptance [`Report`], sent over UDP.
//!
//! The format is the plain StatsD text protocol with the DogStatsD tag
//! extension (`name:value|type|#k:v,k:v`). Each line goes in its own datagram,
//! so no packet can exceed a path MTU however many tags an operator adds.
use std::net::SocketAddr;
use super::{Outcome, Report};
/// Every line for `report`: one run count and duration, then per check a run
/// count (tagged with its result and the stage that failed, or `none`), its
/// duration, and the duration of each stage it completed.
///
/// `tags` are added to every line, after `relay_version` when the relay
/// reported one. Skipped checks are counted but carry no duration.
pub fn lines(prefix: &str, report: &Report, tags: &[String]) -> Vec<String> {
let mut common: Vec<String> = Vec::new();
if let Some(version) = &report.relay_version {
common.push(format!("relay_version:{}", tag_value(version)));
}
common.extend(tags.iter().map(|t| tag_value(t)));
let line = |name: &str, value: String, kind: &str, own: &[String]| {
let all: Vec<&str> = own
.iter()
.chain(common.iter())
.map(String::as_str)
.collect();
format!("{prefix}.{name}:{value}|{kind}|#{}", all.join(","))
};
let run_result = if report.passed {
Outcome::Success
} else {
Outcome::Failure
};
let mut out = vec![
line(
"runs",
"1".into(),
"c",
&[format!("result:{}", run_result.as_str())],
),
line(
"run.seconds",
seconds(report.seconds),
"d",
&[format!("result:{}", run_result.as_str())],
),
];
for check in &report.checks {
let result = format!("result:{}", check.result.as_str());
let name = format!("check:{}", check.check);
let stage = format!("stage:{}", check.failed_stage.unwrap_or("none"));
out.push(line(
"check.runs",
"1".into(),
"c",
&[name.clone(), result.clone(), stage],
));
if check.result == Outcome::Skipped {
continue;
}
out.push(line(
"check.seconds",
seconds(check.seconds),
"d",
&[name.clone(), result],
));
for timing in &check.stages {
out.push(line(
"stage.seconds",
seconds(timing.seconds),
"d",
&[name.clone(), format!("stage:{}", timing.stage)],
));
}
}
out
}
/// Sends each of `lines` to `addr` as its own UDP datagram.
///
/// Fails on the first datagram the socket refuses, so a misconfigured agent
/// address is an error for the caller rather than a run with no metrics.
pub async fn send(addr: SocketAddr, lines: &[String]) -> std::io::Result<()> {
let bind: SocketAddr = if addr.is_ipv4() {
([0, 0, 0, 0], 0).into()
} else {
([0u16; 8], 0).into()
};
let socket = tokio::net::UdpSocket::bind(bind).await?;
for line in lines {
socket.send_to(line.as_bytes(), addr).await?;
}
Ok(())
}
/// Seconds with millisecond precision; StatsD values are plain decimals.
fn seconds(s: f64) -> String {
format!("{s:.3}")
}
/// `value` with the characters that end a DogStatsD tag or line replaced.
fn tag_value(value: &str) -> String {
value
.chars()
.map(|c| match c {
',' | '|' | '#' | '\n' | '\r' | ' ' => '_',
c => c,
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::acceptance::{CheckReport, StageTiming};
fn report() -> Report {
Report {
relay_url: "wss://relay.example".into(),
relay_version: Some("1.2.3".into()),
passed: false,
seconds: 1.5,
checks: vec![
CheckReport {
check: "publish",
result: Outcome::Success,
failed_stage: None,
error: None,
seconds: 0.25,
stages: vec![StageTiming {
stage: "ok",
seconds: 0.25,
}],
},
CheckReport {
check: "fanout",
result: Outcome::Failure,
failed_stage: Some("receive"),
error: Some("timed out after 10s".into()),
seconds: 10.0,
stages: vec![StageTiming {
stage: "subscribe",
seconds: 0.004,
}],
},
CheckReport {
check: "history",
result: Outcome::Skipped,
failed_stage: None,
error: Some("publish failed".into()),
seconds: 0.0,
stages: vec![],
},
],
}
}
#[test]
fn lines_tag_every_series_and_skip_durations_for_skipped_checks() {
let tags = vec!["env:staging".to_string(), "target:a,b|c".to_string()];
let got = lines("buzz.acceptance", &report(), &tags);
let common = "relay_version:1.2.3,env:staging,target:a_b_c";
let want = vec![
format!("buzz.acceptance.runs:1|c|#result:failure,{common}"),
format!("buzz.acceptance.run.seconds:1.500|d|#result:failure,{common}"),
format!(
"buzz.acceptance.check.runs:1|c|#check:publish,result:success,stage:none,{common}"
),
format!("buzz.acceptance.check.seconds:0.250|d|#check:publish,result:success,{common}"),
format!("buzz.acceptance.stage.seconds:0.250|d|#check:publish,stage:ok,{common}"),
format!(
"buzz.acceptance.check.runs:1|c|#check:fanout,result:failure,stage:receive,{common}"
),
format!("buzz.acceptance.check.seconds:10.000|d|#check:fanout,result:failure,{common}"),
format!("buzz.acceptance.stage.seconds:0.004|d|#check:fanout,stage:subscribe,{common}"),
format!(
"buzz.acceptance.check.runs:1|c|#check:history,result:skipped,stage:none,{common}"
),
];
assert_eq!(got, want);
}
#[test]
fn lines_without_relay_version_or_tags_still_tag_check_and_result() {
let mut r = report();
r.relay_version = None;
r.passed = true;
r.checks.truncate(1);
let got = lines("p", &r, &[]);
assert_eq!(got[0], "p.runs:1|c|#result:success");
assert_eq!(
got[2],
"p.check.runs:1|c|#check:publish,result:success,stage:none"
);
}
#[tokio::test]
async fn send_puts_each_line_in_its_own_datagram() {
let agent = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let addr = agent.local_addr().unwrap();
let sent = vec!["a.b:1|c|#x:y".to_string(), "a.c:2|d|#x:y".to_string()];
send(addr, &sent).await.unwrap();
let mut buf = [0u8; 512];
for want in &sent {
let n = agent.recv(&mut buf).await.unwrap();
assert_eq!(std::str::from_utf8(&buf[..n]).unwrap(), want);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,126 @@
//! Relay acceptance probe: checks the relay's core jobs once and exits.
//!
//! Prints a JSON report on stdout. Exits 0 when every check passed, 1 when a
//! check failed, and 2 when the probe itself could not run or report.
//!
//! Usage:
//! buzz-acceptance --relay-url wss://relay.example [--assertion-file <path>]
//! [--statsd-addr 127.0.0.1:8125] [--tag env:staging]...
use std::net::SocketAddr;
use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;
use buzz_test_client::acceptance::{self, metrics, Config};
use clap::Parser;
use nostr::Keys;
/// The longest resolving the metrics address or sending the metrics may take.
const METRICS_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Parser)]
#[command(
name = "buzz-acceptance",
about = "Check a Buzz relay's core jobs once and report each one"
)]
struct Cli {
/// The relay's WebSocket URL.
#[arg(long, env = "BUZZ_RELAY_URL")]
relay_url: String,
/// Secret key (hex or nsec) to authenticate and sign as. Without one the
/// probe uses a new key, which works only on a relay that admits any key.
#[arg(long, env = "BUZZ_PRIVATE_KEY", hide_env_values = true)]
private_key: Option<String>,
/// File holding a NIP-FI assertion for the key, read before every
/// connection. Keep it fresh from another process.
#[arg(long, env = "BUZZ_ACCEPTANCE_ASSERTION_FILE")]
assertion_file: Option<PathBuf>,
/// The longest any one stage may take, in seconds.
#[arg(long, default_value_t = 10)]
stage_timeout_secs: u64,
/// DogStatsD address (`host:port`) to send metrics to.
#[arg(long, env = "BUZZ_ACCEPTANCE_STATSD_ADDR")]
statsd_addr: Option<String>,
/// Metric name prefix.
#[arg(long, default_value = "buzz.acceptance")]
metric_prefix: String,
/// A `key:value` tag for every metric. Repeat for more.
#[arg(long = "tag")]
tags: Vec<String>,
}
fn main() -> ExitCode {
let _ = rustls::crypto::CryptoProvider::install_default(
rustls::crypto::aws_lc_rs::default_provider(),
);
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.with_writer(std::io::stderr)
.init();
let cli = Cli::parse();
let runtime = match tokio::runtime::Runtime::new() {
Ok(runtime) => runtime,
Err(e) => {
eprintln!("buzz-acceptance: start runtime: {e}");
return ExitCode::from(2);
}
};
let result = runtime.block_on(probe(cli));
// A timed-out hostname lookup keeps running on a blocking thread; do not
// let it hold the exit.
runtime.shutdown_timeout(Duration::from_secs(1));
match result {
Ok(true) => ExitCode::SUCCESS,
Ok(false) => ExitCode::from(1),
Err(e) => {
eprintln!("buzz-acceptance: {e:#}");
ExitCode::from(2)
}
}
}
/// Runs the probe, prints its report and sends its metrics. Returns whether
/// every check passed.
async fn probe(cli: Cli) -> anyhow::Result<bool> {
let keys = match &cli.private_key {
Some(key) => Keys::parse(key).map_err(|e| anyhow::anyhow!("private key: {e}"))?,
None => Keys::generate(),
};
let statsd = match &cli.statsd_addr {
Some(addr) => Some(resolve(addr).await?),
None => None,
};
let cfg = Config {
relay_url: cli.relay_url,
keys,
assertion_file: cli.assertion_file,
stage_timeout: Duration::from_secs(cli.stage_timeout_secs),
};
let report = acceptance::run(&cfg).await;
println!("{}", serde_json::to_string(&report)?);
if let Some(addr) = statsd {
let lines = metrics::lines(&cli.metric_prefix, &report, &cli.tags);
tokio::time::timeout(METRICS_TIMEOUT, metrics::send(addr, &lines))
.await
.map_err(|_| anyhow::anyhow!("send metrics to {addr}: timed out"))?
.map_err(|e| anyhow::anyhow!("send metrics to {addr}: {e}"))?;
}
Ok(report.passed)
}
/// Resolves `host:port` once, before the run, so a bad address fails fast.
/// An IP literal never reaches the resolver.
async fn resolve(addr: &str) -> anyhow::Result<SocketAddr> {
if let Ok(literal) = addr.parse() {
return Ok(literal);
}
tokio::time::timeout(METRICS_TIMEOUT, tokio::net::lookup_host(addr))
.await
.map_err(|_| anyhow::anyhow!("resolve statsd address {addr}: timed out"))?
.map_err(|e| anyhow::anyhow!("resolve statsd address {addr}: {e}"))?
.next()
.ok_or_else(|| anyhow::anyhow!("statsd address {addr} resolved to nothing"))
}

View File

@@ -14,6 +14,9 @@ use tracing::debug;
use buzz_ws_client::NostrWsConnection;
pub use buzz_ws_client::{parse_relay_message, OkResponse, RelayMessage, WsClientError};
/// Relay acceptance probe behind the `buzz-acceptance` binary.
pub mod acceptance;
/// Scenario-driven load generator behind the `buzz-loadgen` binary.
/// The scenario schema is documented in `perf/LOADGEN.md`.
#[allow(missing_docs)]

View File

@@ -0,0 +1,159 @@
//! The `buzz-acceptance` probe against a running relay: every check passes,
//! through the shared runner and through the binary.
//!
//! Requires a running relay, so it is `#[ignore]`d. Start the relay, then run:
//!
//! ```text
//! RELAY_URL=ws://localhost:3000 cargo test -p buzz-test-client --test e2e_acceptance -- --ignored
//! ```
use std::io::Read;
use std::net::UdpSocket;
use std::process::{Command, Output, Stdio};
use std::time::{Duration, Instant};
use buzz_test_client::acceptance::{self, Config, Outcome, CHECKS};
use nostr::Keys;
fn relay_url() -> String {
std::env::var("RELAY_URL").unwrap_or_else(|_| "ws://localhost:3000".into())
}
#[tokio::test]
#[ignore]
async fn every_acceptance_check_passes_against_a_live_relay() {
let report = acceptance::run(&Config {
relay_url: relay_url(),
keys: Keys::generate(),
assertion_file: None,
stage_timeout: Duration::from_secs(10),
})
.await;
let summary = serde_json::to_string_pretty(&report).unwrap();
assert!(report.passed, "{summary}");
let names: Vec<&str> = report.checks.iter().map(|c| c.check).collect();
assert_eq!(names, CHECKS, "{summary}");
for check in &report.checks {
assert_eq!(check.result, Outcome::Success, "{summary}");
}
assert!(report.relay_version.is_some(), "{summary}");
}
/// Runs the binary with `args`, metrics sent to a local listener. Returns
/// its output and every datagram that arrived.
fn probe(args: &[&str]) -> (Output, Vec<String>) {
let agent = UdpSocket::bind("127.0.0.1:0").unwrap();
agent
.set_read_timeout(Some(Duration::from_millis(500)))
.unwrap();
let addr = agent.local_addr().unwrap().to_string();
let mut child = Command::new(env!("CARGO_BIN_EXE_buzz-acceptance"))
.args(args)
.args(["--statsd-addr", &addr, "--tag", "env:test"])
.env_remove("BUZZ_PRIVATE_KEY")
.env_remove("BUZZ_RELAY_URL")
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
// Drain both pipes while the child runs, so a chatty child cannot fill a
// pipe and stall before the deadline.
let stdout = drain(child.stdout.take().unwrap());
let stderr = drain(child.stderr.take().unwrap());
let deadline = Instant::now() + Duration::from_secs(120);
let status = loop {
if let Some(status) = child.try_wait().unwrap() {
break status;
}
if Instant::now() > deadline {
let _ = child.kill();
let _ = child.wait();
panic!("buzz-acceptance did not exit within 120 s");
}
std::thread::sleep(Duration::from_millis(50));
};
let output = Output {
status,
stdout: stdout.join().unwrap(),
stderr: stderr.join().unwrap(),
};
let mut lines = Vec::new();
let mut buf = [0u8; 2048];
while let Ok(n) = agent.recv(&mut buf) {
lines.push(String::from_utf8_lossy(&buf[..n]).into_owned());
}
(output, lines)
}
/// Reads `pipe` to its end on a thread, keeping at most 4 MiB.
fn drain(pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<Vec<u8>> {
std::thread::spawn(move || {
let mut pipe = pipe;
let mut kept = Vec::new();
let _ = (&mut pipe).take(4 << 20).read_to_end(&mut kept);
let _ = std::io::copy(&mut pipe, &mut std::io::sink());
kept
})
}
fn report(output: &Output) -> serde_json::Value {
serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
panic!(
"stdout is not a JSON report ({e}): {}",
String::from_utf8_lossy(&output.stdout)
)
})
}
#[test]
#[ignore]
fn the_binary_passes_against_a_live_relay_and_sends_metrics() {
let (output, lines) = probe(&["--relay-url", &relay_url()]);
let report = report(&output);
assert_eq!(output.status.code(), Some(0), "{report}");
assert_eq!(report["passed"], true);
assert!(
lines.iter().any(
|l| l.starts_with("buzz.acceptance.runs:1|c|#result:success,")
&& l.ends_with(",env:test")
),
"{lines:?}"
);
assert!(
lines.iter().any(|l| l.starts_with(
"buzz.acceptance.check.runs:1|c|#check:fanout,result:success,stage:none,"
)),
"{lines:?}"
);
}
#[test]
#[ignore]
fn the_binary_exits_1_and_reports_when_a_check_fails() {
let (output, lines) = probe(&[
"--relay-url",
"ws://127.0.0.1:1",
"--stage-timeout-secs",
"2",
]);
let report = report(&output);
assert_eq!(output.status.code(), Some(1), "{report}");
assert_eq!(report["passed"], false);
assert_eq!(report["checks"][1]["failed_stage"], "ws_connect");
assert!(
lines
.iter()
.any(|l| l == "buzz.acceptance.runs:1|c|#result:failure,env:test"),
"{lines:?}"
);
}
#[test]
#[ignore]
fn the_binary_exits_2_when_it_cannot_run() {
let (output, lines) = probe(&["--relay-url", &relay_url(), "--private-key", "not-a-key"]);
assert_eq!(output.status.code(), Some(2));
assert!(output.stdout.is_empty());
assert!(lines.is_empty(), "{lines:?}");
}

View File

@@ -580,9 +580,10 @@ run_unit_tests() {
run_test_step "buzz-relay boot lifecycle tests" \
cargo test -p buzz-relay --test boot_lifecycle -- --nocapture
# Load generator unit tests are infra-free. Keep in step with `just test-unit`.
run_test_step "buzz-test-client loadgen unit tests" \
cargo test -p buzz-test-client --lib loadgen:: -- --nocapture
# Load generator and acceptance probe unit tests are infra-free. Keep in
# step with `just test-unit`.
run_test_step "buzz-test-client loadgen and acceptance unit tests" \
cargo test -p buzz-test-client --lib -- --nocapture loadgen:: acceptance::
}
# ---- DB / integration tests (infra required) --------------------------------