Files
buzz/crates/buzz-test-client/tests/e2e_acceptance.rs
Luke Tornquist 9f49216f8b 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>
2026-11-20 14:16:02 -05:00

160 lines
5.1 KiB
Rust

//! 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:?}");
}