From c46306578e474c330fffb276abdd3c0bb486dd4d Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sun, 29 Nov 2026 09:21:16 -0500 Subject: [PATCH 01/10] feat(relay): the process-wide counters and their exposition --- crates/nostream-relay/src/connection.rs | 56 +- crates/nostream-relay/src/handlers/auth.rs | 6 +- crates/nostream-relay/src/handlers/event.rs | 3 + crates/nostream-relay/src/handlers/mod.rs | 36 +- .../nostream-relay/src/handlers/subscribe.rs | 28 +- crates/nostream-relay/src/lib.rs | 7 +- crates/nostream-relay/src/metrics.rs | 515 ++++++++++++++++++ crates/nostream-relay/src/relay.rs | 15 + crates/nostream-relay/src/testing.rs | 6 + crates/nostream-relay/tests/connection.rs | 3 + crates/nostream-relay/tests/handlers.rs | 1 + crates/nostream-relay/tests/limits.rs | 1 + crates/nostream-relay/tests/metrics.rs | 311 +++++++++++ crates/nostream-relay/tests/strategies.rs | 1 + 14 files changed, 969 insertions(+), 20 deletions(-) create mode 100644 crates/nostream-relay/src/metrics.rs create mode 100644 crates/nostream-relay/tests/metrics.rs diff --git a/crates/nostream-relay/src/connection.rs b/crates/nostream-relay/src/connection.rs index 48b827ea0..d7f189b72 100644 --- a/crates/nostream-relay/src/connection.rs +++ b/crates/nostream-relay/src/connection.rs @@ -18,6 +18,7 @@ use nostream_core::random::RandomSource; use nostream_core::{Event, Filter, Pubkey}; use crate::error::RelayError; +use crate::metrics::RelayMetrics; use crate::sink::FrameSink; /// The socket the acceptor hands over: a negotiated websocket over the accepted TCP stream. @@ -39,6 +40,9 @@ pub struct Connection { subscriptions: Mutex>, session: Mutex, in_flight: Mutex, + /// The process-wide subscription gauge, adjusted here so no path can remove a + /// subscription without decrementing (ADR 0021, decision 4). + metrics: Arc, } /// The reads running on one socket, each owned by the generation it was given. @@ -114,34 +118,54 @@ impl Connection { }, )); - Ok(Self::new(remote_address, session)) + Ok(Self::new( + remote_address, + session, + Arc::clone(&context.metrics), + )) } /// The per-socket state, with no socket: the shape [`Connection::accept`] builds and the /// one tests build directly. - pub fn new(remote_address: String, session: Nip42Session) -> Self { + pub fn new(remote_address: String, session: Nip42Session, metrics: Arc) -> Self { Self { remote_address, subscriptions: Mutex::new(HashMap::new()), session: Mutex::new(session), in_flight: Mutex::new(InFlightReads::default()), + metrics, } } /// Registers or replaces one subscription (`onSubscribed`). + /// + /// A re-`REQ` under an existing id replaces in place and adds nothing to the gauge: the + /// gauge counts registered subscriptions, not `REQ` frames (ADR 0021, decision 4). pub fn subscribe(&self, subscription: Subscription) { - self.subscriptions + let replaced = self + .subscriptions .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .insert(subscription.id.clone(), subscription); + + if replaced.is_none() { + self.metrics.subscription_added(); + } } /// Removes one subscription (`onUnsubscribed`), returning it when it existed. pub fn unsubscribe(&self, id: &str) -> Option { - self.subscriptions + let removed = self + .subscriptions .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) - .remove(id) + .remove(id); + + if removed.is_some() { + self.metrics.subscriptions_removed(1); + } + + removed } /// Every registered subscription, in id order, which is the order a drain writes its @@ -322,10 +346,20 @@ impl Connection { /// Connection close (`onClientClose`): clears the subscription table and the auth /// session, and aborts every in-flight read. pub fn close(&self) { - self.subscriptions - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .clear(); + let cleared = { + let mut subscriptions = self + .subscriptions + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let cleared = subscriptions.len(); + subscriptions.clear(); + cleared + }; + + if cleared > 0 { + self.metrics + .subscriptions_removed(i64::try_from(cleared).unwrap_or(i64::MAX)); + } self.session .lock() @@ -344,11 +378,13 @@ impl Connection { } /// The state a connection is accepted with: the settings it reads through, the randomness its -/// challenge is minted from, and the sink the challenge leaves through. +/// challenge is minted from, the sink the challenge leaves through, and the counters this +/// socket adjusts. pub struct ConnectionContext { pub settings: Arc, pub random: Arc, pub sink: FrameSink, + pub metrics: Arc, } /// One negentropy session (oracle `041fe34e`; no session file exists at this branch's capture). diff --git a/crates/nostream-relay/src/handlers/auth.rs b/crates/nostream-relay/src/handlers/auth.rs index 196867e52..4b0b0f018 100644 --- a/crates/nostream-relay/src/handlers/auth.rs +++ b/crates/nostream-relay/src/handlers/auth.rs @@ -23,16 +23,16 @@ pub fn handle(message: AuthMessage, context: &HandlerContext) { match nip42::authenticate(&event, &challenge, &relay_url, now) { Ok(pubkey) => { if !context.connection.authenticate(pubkey, event.id, now) { - context.send_ok(event.id, false, "invalid: auth event already used", None); + context.send_auth_ok(event.id, false, "invalid: auth event already used", None); return; } - context.send_ok(event.id, true, "", None); + context.send_auth_ok(event.id, true, "", None); } Err(failure) => { let reason = format!("invalid: {}", failure.message()); - context.send_ok(event.id, false, &reason, None); + context.send_auth_ok(event.id, false, &reason, None); } } } diff --git a/crates/nostream-relay/src/handlers/event.rs b/crates/nostream-relay/src/handlers/event.rs index b733475b1..ecbda9d76 100644 --- a/crates/nostream-relay/src/handlers/event.rs +++ b/crates/nostream-relay/src/handlers/event.rs @@ -54,6 +54,9 @@ fn answer_gate(context: &HandlerContext, event_id: nostream_core::EventId, gate: /// The handler's entry point (`handleMessage`). pub async fn handle(event: Event, context: &HandlerContext) { + // Before any validation: the family counts what clients sent, not what the relay kept. + context.metrics.event_received(event.kind.0); + if let Some(reason) = is_event_valid(&event, context.relay_url()) { context.send_ok(event.id, false, &reason, None); return; diff --git a/crates/nostream-relay/src/handlers/mod.rs b/crates/nostream-relay/src/handlers/mod.rs index de7293bfd..e15847d07 100644 --- a/crates/nostream-relay/src/handlers/mod.rs +++ b/crates/nostream-relay/src/handlers/mod.rs @@ -51,6 +51,7 @@ use nostream_storage::repositories::{ use crate::connection::Connection; use crate::hidden_content::HiddenContentCache; use crate::limits::RateLimits; +use crate::metrics::RelayMetrics; use crate::relay_key::RelayKeySource; use crate::sink::FrameSink; use crate::wot::WotGraph; @@ -102,6 +103,8 @@ pub struct HandlerContext { pub keys: Arc, pub broadcast: broadcast::Sender>, pub pow: Arc>, + /// The process-wide counters this socket's handlers move. + pub metrics: Arc, } impl HandlerContext { @@ -147,13 +150,44 @@ impl HandlerContext { } } - /// `["OK", , , ]` with the optional backoff slot. + /// `["OK", , , ]` with the optional backoff slot, counting the + /// event handler's verdict before the frame is queued. + /// + /// This is the EVENT path's one OK choke point, which is where the capture counts + /// (`src/telemetry/event-metrics.ts:6-15`). AUTH's replies do not come through here: they + /// are [`HandlerContext::send_auth_ok`]'s, and an `AUTH` is not an event. pub fn send_ok( &self, event_id: nostream_core::EventId, accepted: bool, message: &str, params: Option, + ) { + if accepted { + self.metrics.event_accepted(); + } else { + self.metrics.event_rejected(message); + } + + self.sink.send(&RelayMessage::Ok(CommandResult { + event_id, + accepted, + message: message.to_owned(), + params, + })); + } + + /// The AUTH handler's `["OK", , , ]`: the identical frame + /// [`HandlerContext::send_ok`] queues, touching no counter. + /// + /// AUTH's three replies — its `true` and its two `invalid: …` refusals — are counted in + /// neither the accepted nor the rejected family (ADR 0021, decision 4). + pub fn send_auth_ok( + &self, + event_id: nostream_core::EventId, + accepted: bool, + message: &str, + params: Option, ) { self.sink.send(&RelayMessage::Ok(CommandResult { event_id, diff --git a/crates/nostream-relay/src/handlers/subscribe.rs b/crates/nostream-relay/src/handlers/subscribe.rs index fb8f27ac9..c910db164 100644 --- a/crates/nostream-relay/src/handlers/subscribe.rs +++ b/crates/nostream-relay/src/handlers/subscribe.rs @@ -45,21 +45,24 @@ const INVITE_REQUEST_KIND: Kind = Kind(28_935); /// the next frame. The continuation starts at the invite mint and is spawned into the /// socket's handler set, where it interleaves with the frames that follow. pub fn begin(message: SubscribeMessage, context: &Arc) -> Option { - let (read, filters) = register(message, context)?; + let (read, filters, started_ms) = register(message, context)?; let context = Arc::clone(context); Some(Box::pin(async move { maybe_issue_invite_code(read.subscription_id(), &filters, &context).await; - fetch_and_send(read, &filters, &context).await; + fetch_and_send(read, &filters, started_ms, &context).await; })) } /// The prefix (`handleMessage`, `:51-69`): what the capture runs before its first `await`. +/// +/// The third value is the registration instant the EOSE sample is measured from, in the +/// handler's clock's milliseconds (ADR 0021, decision 4). fn register( message: SubscribeMessage, context: &HandlerContext, -) -> Option<(InFlightRead, Vec)> { +) -> Option<(InFlightRead, Vec, u64)> { let subscription_id = message.subscription_id; let search_enabled = context .settings @@ -95,8 +98,9 @@ fn register( // Registered before the mint's only `await`, so the read a `CLOSE` aborts exists by then. let read = context.connection.begin_read(&subscription_id); + let started_ms = context.now_ms(); - Some((read, filters)) + Some((read, filters, started_ms)) } /// NIP-43: kind 28935 is never published by a client and never stored. A REQ for it asks the @@ -248,7 +252,12 @@ async fn mint_invite_code( /// event (`auth`), or a single-filter subscription's `limit` decided the answer /// (`finish`/`more`). A read with neither cause keeps `["EOSE", ]`, which is what makes /// every recorded session's EOSE byte-identical to the capture's. -async fn fetch_and_send(mut read: InFlightRead, filters: &[Filter], context: &HandlerContext) { +async fn fetch_and_send( + mut read: InFlightRead, + filters: &[Filter], + started_ms: u64, + context: &HandlerContext, +) { let subscription_id = read.subscription_id().to_owned(); // A cancellation set before the stream was opened (a `CLOSE` during the mint) ends the @@ -525,6 +534,13 @@ async fn fetch_and_send(mut read: InFlightRead, filters: &[Filter], context: &Ha } } + // Recorded before the frame is queued, so a client that has read its EOSE has already seen + // the sample. A read that ends above, through a cancellation or a sink refusal, sends no + // EOSE and records none. + context + .metrics + .observe_eose_millis(context.now_ms().saturating_sub(started_ms)); + context.sink.send(&RelayMessage::Eose(EoseMessage { subscription_id, hints, @@ -628,6 +644,7 @@ mod tests { use super::*; use crate::connection::Connection; + use crate::metrics::RelayMetrics; use crate::relay_key::RelayKeySource; use crate::sink::{FrameBudget, FrameSink, Refusal}; use crate::testing::{Fixture, settings}; @@ -671,6 +688,7 @@ mod tests { let connection = Arc::new(Connection::new( "127.0.0.1".to_owned(), Nip42Session::with_challenge("challenge", 0), + Arc::new(RelayMetrics::default()), )); let context = Arc::new(fixture.context( Arc::new(TestClock::new(1_700_000_000_000)), diff --git a/crates/nostream-relay/src/lib.rs b/crates/nostream-relay/src/lib.rs index ea17a4c6f..4c8a92132 100644 --- a/crates/nostream-relay/src/lib.rs +++ b/crates/nostream-relay/src/lib.rs @@ -16,6 +16,8 @@ //! - `src/@types/{message-handlers,subscription,clients}.ts` //! - `src/factories/{event-strategy-factory,message-handler-factory, //! websocket-adapter-factory,rate-limiter-factory}.ts` +//! - `src/telemetry/event-metrics.ts` and the event counters `src/utils/admin-metrics.ts` +//! reads (`metrics.rs`: the process-wide counters and their Prometheus text exposition) //! //! **Implemented here:** the transport (`transport.rs`: `tokio-tungstenite` 0.30, the //! settings-derived message limit, the close codes, the drain timeout), the per-socket state @@ -38,7 +40,9 @@ //! //! Phase 2+ areas this crate does not own: the HTTP surface (`nostream-admin`) and the probe //! family and NIP-66 monitor (`nostream-services`). The NIP-11 document's builder is this -//! crate's ([`nip11`]); nothing serves it yet (D1). +//! crate's ([`nip11`]); nothing serves it yet (D1). Nor does [`metrics`] own the admin consult's +//! SSE snapshot (`nostream-admin`) or the OTLP export (`nostreamd`): it keeps the counters and +//! renders them as text, and those two read or ship them elsewhere. //! //! The event acceptance gate this crate owns is the *policy*: the kind-specific tag rules, //! which `created_at` deltas the settings supply, and where the check runs. The pure @@ -53,6 +57,7 @@ pub mod error; pub mod handlers; pub mod hidden_content; pub mod limits; +pub mod metrics; pub mod nip11; pub mod relay; pub mod relay_key; diff --git a/crates/nostream-relay/src/metrics.rs b/crates/nostream-relay/src/metrics.rs new file mode 100644 index 000000000..89b5e2e87 --- /dev/null +++ b/crates/nostream-relay/src/metrics.rs @@ -0,0 +1,515 @@ +//! The process-wide relay counters, and the Prometheus text exposition they render. +//! +//! Mirrors `src/telemetry/event-metrics.ts` (per-kind receives and the accepted/rejected +//! verdicts) and the event counters `src/utils/admin-metrics.ts` reads, in the shape ADR 0021 +//! fixes: plain in-process atomics behind narrow accessors, the mechanism `connection_cap.rs` +//! and `sink.rs` already use for this class of work. +//! +//! **Counted here:** accepted connections, the events received per kind, the event handler's +//! verdicts, the live subscriptions, and the time from a `REQ` to its `EOSE`. **Not counted +//! here:** database query latency (no instrument exists; the daemon's stores are the +//! `unavailable` seams), process CPU and memory (no crate in the daemon reads them), and the +//! admin consult's SSE snapshot and OTLP export, which stay `nostream-admin`'s and +//! `nostreamd`'s. +//! +//! The labels are two closed vocabularies: the event kind as a decimal string, capped at +//! [`MAX_KIND_LABELS`] distinct kinds with an `other` overflow, and the rejection reason's +//! prefix, published as [`REJECT_LABELS`]. A reader that is handed a label outside either +//! vocabulary traps rather than answering zero, because a misspelt label is a defect at the +//! call site and a silent zero would hide it for the life of the process. + +use std::collections::BTreeMap; +use std::sync::Mutex; +use std::sync::atomic::{AtomicI64, AtomicU64, Ordering}; + +/// The most distinct event kinds tracked by `events_received`. A kind that is new when the map +/// is full counts under `kind="other"`, so an unauthenticated sender cannot grow the map +/// without bound; a kind already tracked keeps counting past the cap. +pub const MAX_KIND_LABELS: usize = 1024; + +/// The rejection reasons, in the order the exposition prints them. +/// +/// The first ten are the prefixes the tree puts before the `:` of an OK frame's message; the +/// bare message `event is expired` is `expired`, and anything unrecognised is `other`. +/// `duplicate` and `info` are only ever sent on **accepted** frames today, so their rejection +/// series never print: they stay reserved, so a future `send_ok(false, "duplicate: …")` lands in +/// a named label instead of `other`. +pub const REJECT_LABELS: [&str; 12] = [ + "invalid", + "blocked", + "rejected", + "rate-limited", + "pow", + "auth-required", + "restricted", + "duplicate", + "error", + "info", + "expired", + "other", +]; + +/// The EOSE histogram's boundaries, in integer milliseconds, with the label each prints. +pub const EOSE_BUCKET_MS: [(u64, &str); 6] = [ + (10, "0.01"), + (50, "0.05"), + (100, "0.1"), + (500, "0.5"), + (1000, "1"), + (5000, "5"), +]; + +const CONNECTIONS_ACTIVE: &str = "nostream_connections_active"; +const CONNECTIONS_ACTIVE_HELP: &str = "Current number of active WebSocket connections"; +const CONNECTIONS_TOTAL: &str = "nostream_connections_total"; +const CONNECTIONS_TOTAL_HELP: &str = "Total WebSocket connections since process start"; +const EVENTS_RECEIVED_TOTAL: &str = "nostream_events_received_total"; +const EVENTS_RECEIVED_TOTAL_HELP: &str = "Events received from clients"; +const EVENTS_ACCEPTED_TOTAL: &str = "nostream_events_accepted_total"; +const EVENTS_ACCEPTED_TOTAL_HELP: &str = "Events accepted by the event handler"; +const EVENTS_REJECTED_TOTAL: &str = "nostream_events_rejected_total"; +const EVENTS_REJECTED_TOTAL_HELP: &str = "Events rejected before storage"; +const SUBSCRIPTIONS_ACTIVE: &str = "nostream_subscriptions_active"; +const SUBSCRIPTIONS_ACTIVE_HELP: &str = "Current active REQ subscriptions"; +const EOSE_DURATION_SECONDS: &str = "nostream_eose_duration_seconds"; +const EOSE_DURATION_SECONDS_HELP: &str = "Time from REQ received to EOSE sent"; + +/// The process's counters: one value on [`Relay`](crate::relay::Relay), handed to every +/// connection task and to the scrape endpoint. +#[derive(Debug)] +pub struct RelayMetrics { + connections_total: AtomicU64, + events_received: Mutex>, + events_received_other: AtomicU64, + events_accepted: AtomicU64, + events_rejected: [AtomicU64; REJECT_LABELS.len()], + subscriptions_active: AtomicI64, + eose_buckets: [AtomicU64; EOSE_BUCKET_MS.len()], + eose_count: AtomicU64, + eose_sum_ms: AtomicU64, +} + +impl Default for RelayMetrics { + fn default() -> Self { + Self { + connections_total: AtomicU64::new(0), + events_received: Mutex::new(BTreeMap::new()), + events_received_other: AtomicU64::new(0), + events_accepted: AtomicU64::new(0), + events_rejected: std::array::from_fn(|_| AtomicU64::new(0)), + subscriptions_active: AtomicI64::new(0), + eose_buckets: std::array::from_fn(|_| AtomicU64::new(0)), + eose_count: AtomicU64::new(0), + eose_sum_ms: AtomicU64::new(0), + } + } +} + +impl RelayMetrics { + /// How many clients were registered since the process started. + pub fn connections_total(&self) -> u64 { + self.connections_total.load(Ordering::SeqCst) + } + + /// How many events of `kind` were received; `0` for a kind never observed. + pub fn events_received(&self, kind: u64) -> u64 { + self.events_received + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .get(&kind) + .copied() + .unwrap_or(0) + } + + /// How many events of a kind past [`MAX_KIND_LABELS`] were received. + pub fn event_received_other(&self) -> u64 { + self.events_received_other.load(Ordering::SeqCst) + } + + /// How many events the event handler accepted. + pub fn events_accepted(&self) -> u64 { + self.events_accepted.load(Ordering::SeqCst) + } + + /// How many events were rejected for `label`, one of [`REJECT_LABELS`]. + pub fn events_rejected(&self, label: &str) -> u64 { + self.events_rejected[reject_index(label)].load(Ordering::SeqCst) + } + + /// The live subscriptions, process-wide: the signed gauge. + pub fn subscriptions_active(&self) -> i64 { + self.subscriptions_active.load(Ordering::SeqCst) + } + + /// How many EOSE samples were recorded. + pub fn eose_count(&self) -> u64 { + self.eose_count.load(Ordering::SeqCst) + } + + /// The EOSE samples' sum, in seconds. + pub fn eose_sum_seconds(&self) -> f64 { + self.eose_sum_ms.load(Ordering::SeqCst) as f64 / 1000.0 + } + + /// The cumulative count of samples at or below one bucket boundary, or `_count` for + /// `"+Inf"`. Any other `le` is a defect at the reader and traps. + pub fn eose_bucket(&self, le: &str) -> u64 { + if le == "+Inf" { + return self.eose_count(); + } + + let index = EOSE_BUCKET_MS + .iter() + .position(|(_, label)| *label == le) + .unwrap_or(EOSE_BUCKET_MS.len()); + + assert!( + index < EOSE_BUCKET_MS.len(), + "`{le}` is not an EOSE bucket label" + ); + + self.eose_buckets[index].load(Ordering::SeqCst) + } + + /// Counts one registered client: `Relay::run_connection`, after `Connection::accept` + /// returned `Ok`, so a socket the cap, the attempt limiter or the upgrade refused never + /// counts. + pub fn connection_accepted(&self) { + self.connections_total.fetch_add(1, Ordering::SeqCst); + } + + /// Counts one received event against its kind, or the `other` overflow. + pub fn event_received(&self, kind: u64) { + let mut received = self + .events_received + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + + if let Some(count) = received.get_mut(&kind) { + *count += 1; + } else if received.len() < MAX_KIND_LABELS { + received.insert(kind, 1); + } else { + self.events_received_other.fetch_add(1, Ordering::SeqCst); + } + } + + /// Counts one event the event handler accepted. + pub fn event_accepted(&self) { + self.events_accepted.fetch_add(1, Ordering::SeqCst); + } + + /// Counts one event the event handler rejected, against its message's reason. + pub fn event_rejected(&self, message: &str) { + self.events_rejected[reject_index(reject_reason(message))].fetch_add(1, Ordering::SeqCst); + } + + /// Adds one to the live-subscription gauge: a `REQ` for an id that was not registered. + pub fn subscription_added(&self) { + self.subscriptions_active.fetch_add(1, Ordering::SeqCst); + } + + /// Removes `count` from the live-subscription gauge: a `CLOSE`, or a socket close. + pub fn subscriptions_removed(&self, count: i64) { + self.subscriptions_active.fetch_sub(count, Ordering::SeqCst); + } + + /// Records one EOSE sample: every bucket whose boundary is at or above `millis`, then the + /// count and the sum. + pub fn observe_eose_millis(&self, millis: u64) { + for (index, (boundary, _)) in EOSE_BUCKET_MS.iter().enumerate() { + if millis <= *boundary { + self.eose_buckets[index].fetch_add(1, Ordering::SeqCst); + } + } + + self.eose_count.fetch_add(1, Ordering::SeqCst); + self.eose_sum_ms.fetch_add(millis, Ordering::SeqCst); + } +} + +/// The label an OK frame's rejection message belongs to: its text before the first `:` when +/// that prefix is one of [`REJECT_LABELS`], `expired` for the bare `event is expired`, and +/// `other` for anything unrecognised. +pub fn reject_reason(message: &str) -> &'static str { + if message == "event is expired" { + return "expired"; + } + + let prefix = message.split(':').next().unwrap_or_default(); + + REJECT_LABELS + .iter() + .copied() + .find(|label| *label == prefix) + .unwrap_or("other") +} + +/// A label value as a Prometheus exposition quotes it: `\` → `\\`, `"` → `\"`, newline → +/// `\n`. +pub fn escape_label_value(value: &str) -> String { + let mut escaped = String::with_capacity(value.len()); + + for character in value.chars() { + match character { + '\\' => escaped.push_str("\\\\"), + '"' => escaped.push_str("\\\""), + '\n' => escaped.push_str("\\n"), + other => escaped.push(other), + } + } + + escaped +} + +/// The exposition body, in Prometheus text format 0.0.4. +/// +/// `connections_active` is `ConnectionCap::live_total()` read at scrape time; every other +/// number is the counters' own. The unlabeled families and the histogram always print, and a +/// labeled family prints only the values observed at least once — an absent series is +/// Prometheus's "no data", which is the honest rendering of "no rejection of this kind yet". +pub fn render(metrics: &RelayMetrics, connections_active: usize) -> String { + let mut families: Vec = Vec::with_capacity(7); + + let mut connections_active_family = + family(CONNECTIONS_ACTIVE, CONNECTIONS_ACTIVE_HELP, "gauge"); + connections_active_family.push_str(&format!("{CONNECTIONS_ACTIVE} {connections_active}\n")); + families.push(connections_active_family); + + let mut connections_total_family = family(CONNECTIONS_TOTAL, CONNECTIONS_TOTAL_HELP, "counter"); + connections_total_family.push_str(&format!( + "{CONNECTIONS_TOTAL} {}\n", + metrics.connections_total() + )); + families.push(connections_total_family); + + let mut received_family = family(EVENTS_RECEIVED_TOTAL, EVENTS_RECEIVED_TOTAL_HELP, "counter"); + { + let received = metrics + .events_received + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + + for (kind, count) in received.iter() { + received_family.push_str(&format!( + "{EVENTS_RECEIVED_TOTAL}{{kind=\"{}\"}} {count}\n", + escape_label_value(&kind.to_string()) + )); + } + } + let received_other = metrics.event_received_other(); + if received_other > 0 { + received_family.push_str(&format!( + "{EVENTS_RECEIVED_TOTAL}{{kind=\"other\"}} {received_other}\n" + )); + } + families.push(received_family); + + let mut accepted_family = family(EVENTS_ACCEPTED_TOTAL, EVENTS_ACCEPTED_TOTAL_HELP, "counter"); + accepted_family.push_str(&format!( + "{EVENTS_ACCEPTED_TOTAL} {}\n", + metrics.events_accepted() + )); + families.push(accepted_family); + + let mut rejected_family = family(EVENTS_REJECTED_TOTAL, EVENTS_REJECTED_TOTAL_HELP, "counter"); + for label in REJECT_LABELS { + let count = metrics.events_rejected(label); + + if count > 0 { + rejected_family.push_str(&format!( + "{EVENTS_REJECTED_TOTAL}{{reason=\"{}\"}} {count}\n", + escape_label_value(label) + )); + } + } + families.push(rejected_family); + + let mut subscriptions_active_family = + family(SUBSCRIPTIONS_ACTIVE, SUBSCRIPTIONS_ACTIVE_HELP, "gauge"); + subscriptions_active_family.push_str(&format!( + "{SUBSCRIPTIONS_ACTIVE} {}\n", + metrics.subscriptions_active() + )); + families.push(subscriptions_active_family); + + let mut eose_family = family( + EOSE_DURATION_SECONDS, + EOSE_DURATION_SECONDS_HELP, + "histogram", + ); + for (_, label) in EOSE_BUCKET_MS { + eose_family.push_str(&format!( + "{EOSE_DURATION_SECONDS}_bucket{{le=\"{}\"}} {}\n", + escape_label_value(label), + metrics.eose_bucket(label) + )); + } + eose_family.push_str(&format!( + "{EOSE_DURATION_SECONDS}_bucket{{le=\"+Inf\"}} {}\n", + metrics.eose_count() + )); + eose_family.push_str(&format!( + "{EOSE_DURATION_SECONDS}_sum {:.3}\n", + metrics.eose_sum_seconds() + )); + eose_family.push_str(&format!( + "{EOSE_DURATION_SECONDS}_count {}\n", + metrics.eose_count() + )); + families.push(eose_family); + + families.join("\n") +} + +/// One family's `# HELP` and `# TYPE` lines, which every family carries whether or not it has +/// a sample to print. +fn family(name: &str, help: &str, kind: &str) -> String { + format!("# HELP {name} {help}\n# TYPE {name} {kind}\n") +} + +/// `label`'s index in [`REJECT_LABELS`], or a trap. +/// +/// A label outside the constant is a defect at the reader, not a zero: answering `0` for +/// `"rate_limted"` would hide a misspelt series for the life of the process. +fn reject_index(label: &str) -> usize { + let index = REJECT_LABELS + .iter() + .position(|candidate| *candidate == label) + .unwrap_or(REJECT_LABELS.len()); + + assert!( + index < REJECT_LABELS.len(), + "`{label}` is not one of REJECT_LABELS" + ); + + index +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + + use super::*; + + /// R5's zero-state body, byte for byte. + const ZERO_STATE: &str = r#"# HELP nostream_connections_active Current number of active WebSocket connections +# TYPE nostream_connections_active gauge +nostream_connections_active 0 + +# HELP nostream_connections_total Total WebSocket connections since process start +# TYPE nostream_connections_total counter +nostream_connections_total 0 + +# HELP nostream_events_received_total Events received from clients +# TYPE nostream_events_received_total counter + +# HELP nostream_events_accepted_total Events accepted by the event handler +# TYPE nostream_events_accepted_total counter +nostream_events_accepted_total 0 + +# HELP nostream_events_rejected_total Events rejected before storage +# TYPE nostream_events_rejected_total counter + +# HELP nostream_subscriptions_active Current active REQ subscriptions +# TYPE nostream_subscriptions_active gauge +nostream_subscriptions_active 0 + +# HELP nostream_eose_duration_seconds Time from REQ received to EOSE sent +# TYPE nostream_eose_duration_seconds histogram +nostream_eose_duration_seconds_bucket{le="0.01"} 0 +nostream_eose_duration_seconds_bucket{le="0.05"} 0 +nostream_eose_duration_seconds_bucket{le="0.1"} 0 +nostream_eose_duration_seconds_bucket{le="0.5"} 0 +nostream_eose_duration_seconds_bucket{le="1"} 0 +nostream_eose_duration_seconds_bucket{le="5"} 0 +nostream_eose_duration_seconds_bucket{le="+Inf"} 0 +nostream_eose_duration_seconds_sum 0.000 +nostream_eose_duration_seconds_count 0 +"#; + + #[test] + fn reject_reason_answers_the_closed_vocabulary() { + assert_eq!(REJECT_LABELS.len(), 12); + + // One representative message per entry, in the constant's own order. + let representatives = [ + ("invalid: event id does not match", "invalid"), + ("blocked: pubkey not allowed", "blocked"), + ("rejected: event already exists", "rejected"), + ("rate-limited: slow down", "rate-limited"), + ("pow: difficulty 1<2", "pow"), + ( + "auth-required: authentication is required to publish events", + "auth-required", + ), + ("restricted: pubkey not admitted", "restricted"), + ("duplicate: event already exists", "duplicate"), + ("error: unable to process event", "error"), + ("info: welcome to the relay", "info"), + ("event is expired", "expired"), + ("something nobody named", "other"), + ]; + + let labels: Vec<&str> = representatives.iter().map(|(_, label)| *label).collect(); + assert_eq!(labels, REJECT_LABELS.to_vec()); + + for (message, label) in representatives { + assert_eq!(reject_reason(message), label, "{message}"); + } + + assert_eq!(reject_reason("invalid"), "invalid"); + assert_eq!(reject_reason(""), "other"); + assert_eq!(reject_reason("rate_limted: slow down"), "other"); + + // A reader handed a label outside the constant traps rather than answering zero. + let metrics = RelayMetrics::default(); + let trapped = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + metrics.events_rejected("typo") + })); + assert!(trapped.is_err(), "a label outside REJECT_LABELS must panic"); + } + + #[test] + fn escape_label_value_escapes_backslash_quote_and_newline() { + assert_eq!(escape_label_value("a\"b\\c\nd"), "a\\\"b\\\\c\\nd"); + assert_eq!(escape_label_value("plain"), "plain"); + } + + #[test] + fn kinds_past_the_cap_count_under_other() { + let metrics = RelayMetrics::default(); + + for kind in 0..=MAX_KIND_LABELS as u64 { + metrics.event_received(kind); + } + + assert_eq!(metrics.events_received(0), 1); + assert_eq!(metrics.events_received(MAX_KIND_LABELS as u64 - 1), 1); + assert_eq!(metrics.events_received(MAX_KIND_LABELS as u64), 0); + assert_eq!(metrics.event_received_other(), 1); + + // An already-tracked kind keeps counting past the cap. + metrics.event_received(0); + assert_eq!(metrics.events_received(0), 2); + assert_eq!(metrics.event_received_other(), 1); + + // 1024 numeric series plus the overflow, in ascending order. + let body = render(&metrics, 0); + let series: Vec<&str> = body + .lines() + .filter(|line| line.starts_with("nostream_events_received_total{kind=\"")) + .collect(); + assert_eq!(series.len(), MAX_KIND_LABELS + 1); + assert_eq!( + series[MAX_KIND_LABELS], + "nostream_events_received_total{kind=\"other\"} 1" + ); + assert_eq!(series[0], "nostream_events_received_total{kind=\"0\"} 2"); + } + + #[test] + fn the_zero_state_exposition_is_the_pinned_body() { + assert_eq!(render(&RelayMetrics::default(), 0), ZERO_STATE); + } +} diff --git a/crates/nostream-relay/src/relay.rs b/crates/nostream-relay/src/relay.rs index 004aba237..d9fc2d09c 100644 --- a/crates/nostream-relay/src/relay.rs +++ b/crates/nostream-relay/src/relay.rs @@ -33,6 +33,7 @@ use crate::dispatch::{HttpFallback, Protocol, classify_socket}; use crate::handlers::{self, HandlerContext, Stores}; use crate::hidden_content::{DEFAULT_REFRESH_INTERVAL, HiddenContentCache}; use crate::limits::RateLimits; +use crate::metrics::RelayMetrics; use crate::relay_key::RelayKeySource; use crate::sink::{FrameBudget, FrameSink, Refusal}; use crate::transport; @@ -148,6 +149,7 @@ pub struct Relay { pow: Arc>, frame_budget: Arc, connection_cap: Arc, + metrics: Arc, config: RelayConfig, } @@ -197,6 +199,7 @@ impl Relay { pow: Arc::new(Mutex::new(AdaptivePowState::default())), frame_budget, connection_cap, + metrics: Arc::new(RelayMetrics::default()), config, }) } @@ -226,6 +229,11 @@ impl Relay { &self.connection_cap } + /// The process-wide counters the scrape endpoint renders. + pub fn metrics(&self) -> &Arc { + &self.metrics + } + /// The context one socket's handlers run in. fn handler_context(&self, connection: Arc, sink: FrameSink) -> HandlerContext { HandlerContext { @@ -241,6 +249,7 @@ impl Relay { keys: Arc::clone(&self.keys), broadcast: self.hub.clone(), pow: Arc::clone(&self.pow), + metrics: Arc::clone(&self.metrics), } } @@ -422,6 +431,7 @@ impl Relay { settings: Arc::clone(&self.settings), random: Arc::clone(&self.random), sink: sink.clone(), + metrics: Arc::clone(&self.metrics), }; let connection = match Connection::accept(&transport, &connection_context) { @@ -432,6 +442,11 @@ impl Relay { } }; + // The one counter that moves after the frame it answers: the NIP-42 challenge is + // queued inside `Connection::accept`, and a socket the cap, the attempt limiter or the + // upgrade refused returns above without becoming a client (ADR 0021, decision 4). + self.metrics.connection_accepted(); + let context = Arc::new(self.handler_context(Arc::clone(&connection), sink.clone())); let mut hub = self.hub.subscribe(); diff --git a/crates/nostream-relay/src/testing.rs b/crates/nostream-relay/src/testing.rs index c05f30d3c..7561320ec 100644 --- a/crates/nostream-relay/src/testing.rs +++ b/crates/nostream-relay/src/testing.rs @@ -39,6 +39,7 @@ use crate::error::RelayError; use crate::handlers::{HandlerContext, Stores}; use crate::hidden_content::HiddenContentCache; use crate::limits::RateLimits; +use crate::metrics::RelayMetrics; use crate::relay_key::RelayKeySource; use crate::wot::{WotFuture, WotGraph}; @@ -1820,6 +1821,8 @@ pub struct Fixture { pub wot: Arc, pub hidden: Arc, pub hub: tokio::sync::broadcast::Sender>, + /// The counters this fixture's contexts move, for a unit test to read back. + pub metrics: Arc, } impl Fixture { @@ -1853,6 +1856,7 @@ impl Fixture { wot, hidden: HiddenContentCache::new(), hub, + metrics: Arc::new(RelayMetrics::default()), } } @@ -1920,6 +1924,7 @@ impl Fixture { pow: Arc::new(Mutex::new( nostream_core::adaptive_pow::AdaptivePowState::default(), )), + metrics: Arc::clone(&self.metrics), } } @@ -1928,6 +1933,7 @@ impl Fixture { let connection = Arc::new(Connection::new( "127.0.0.1".to_owned(), nostream_core::nip42::Nip42Session::with_challenge("challenge", 0), + Arc::clone(&self.metrics), )); self.context(clock, keys, connection, crate::sink::FrameSink::closed()) diff --git a/crates/nostream-relay/tests/connection.rs b/crates/nostream-relay/tests/connection.rs index d238a81b3..4b62f0289 100644 --- a/crates/nostream-relay/tests/connection.rs +++ b/crates/nostream-relay/tests/connection.rs @@ -33,6 +33,7 @@ fn connection() -> Arc { Arc::new(Connection::new( "127.0.0.1".to_owned(), nostream_core::nip42::Nip42Session::with_challenge("challenge", 0), + Arc::new(nostream_relay::metrics::RelayMetrics::default()), )) } @@ -415,6 +416,7 @@ async fn closing_the_socket_aborts_an_in_flight_read() { let connection = Arc::new(Connection::new( "127.0.0.1".to_owned(), nostream_core::nip42::Nip42Session::with_challenge("challenge", 0), + Arc::new(nostream_relay::metrics::RelayMetrics::default()), )); let context = Arc::new(fixture.context( Arc::new(TestClock::new(NOW_MS)), @@ -500,6 +502,7 @@ async fn restricted_read_with(authenticate_mid_read: bool) -> Vec { let connection = Arc::new(Connection::new( "127.0.0.1".to_owned(), nostream_core::nip42::Nip42Session::with_challenge("challenge", 3_600), + Arc::new(nostream_relay::metrics::RelayMetrics::default()), )); let context = Arc::new(fixture.context( Arc::new(TestClock::new(NOW_MS)), diff --git a/crates/nostream-relay/tests/handlers.rs b/crates/nostream-relay/tests/handlers.rs index 35b7fbb74..e4169238b 100644 --- a/crates/nostream-relay/tests/handlers.rs +++ b/crates/nostream-relay/tests/handlers.rs @@ -1688,6 +1688,7 @@ async fn a_close_during_the_invite_mint_leaves_the_event_but_not_the_read() { let connection = Arc::new(Connection::new( "127.0.0.1".to_owned(), nostream_core::nip42::Nip42Session::with_challenge("challenge", 0), + Arc::new(nostream_relay::metrics::RelayMetrics::default()), )); // The invite mint is behind the NIP-42 identity check (`subscribe.rs:167-190`), // so the test authenticates before it subscribes. diff --git a/crates/nostream-relay/tests/limits.rs b/crates/nostream-relay/tests/limits.rs index b6ed1eceb..eca60b120 100644 --- a/crates/nostream-relay/tests/limits.rs +++ b/crates/nostream-relay/tests/limits.rs @@ -976,6 +976,7 @@ async fn a_failing_event_limiter_limits_the_event_without_a_backoff() { let connection = Arc::new(nostream_relay::connection::Connection::new( "127.0.0.1".to_owned(), nostream_core::nip42::Nip42Session::with_challenge("challenge", 0), + Arc::new(nostream_relay::metrics::RelayMetrics::default()), )); let limits = Arc::new(RateLimits::with_limiter( Arc::new(FailingLimiter), diff --git a/crates/nostream-relay/tests/metrics.rs b/crates/nostream-relay/tests/metrics.rs new file mode 100644 index 000000000..495e7cd84 --- /dev/null +++ b/crates/nostream-relay/tests/metrics.rs @@ -0,0 +1,311 @@ +//! The relay's counters, driven by real frames through the harness (AC1–AC6). +//! +//! Each case reads its reply frame as the synchronisation point and then polls the counter +//! with a 2 s bound: every counter except `connections_total` moves before the frame it +//! answers is queued, but a scheduling delay must not be able to flake a case. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use common::{CLIENT_SECRET, NOW_SECS, Server, fast_config, relay_keys, signed_event}; +use nostream_core::Event; +use nostream_relay::metrics::REJECT_LABELS; +use nostream_relay::testing::{Fixture, settings}; + +/// The relay's own URL in the harness's settings. +const RELAY_URL: &str = "wss://relay.example.com"; + +async fn start(fixture: Fixture) -> Server { + Server::start_with(fixture, relay_keys(), fast_config()).await +} + +/// The event frame a client sends for one signed event. +fn event_frame(event: &Event) -> String { + format!( + r#"["EVENT",{}]"#, + serde_json::to_string(event).expect("event json") + ) +} + +/// The AUTH frame a client sends for one signed kind-22242 event. +fn auth_frame(event: &Event) -> String { + format!( + r#"["AUTH",{}]"#, + serde_json::to_string(event).expect("event json") + ) +} + +/// Polls `condition` for at most two seconds, then fails the case. +async fn poll_until(mut condition: impl FnMut() -> bool) { + let deadline = Instant::now() + Duration::from_secs(2); + + while Instant::now() < deadline { + if condition() { + return; + } + + tokio::time::sleep(Duration::from_millis(10)).await; + } + + panic!("the condition did not hold within two seconds"); +} + +#[tokio::test] +async fn a_connect_and_disconnect_move_the_connection_counters() { + let server = start(Fixture::new(settings())).await; + let metrics = Arc::clone(server.relay.metrics()); + + assert_eq!(metrics.connections_total(), 0); + assert_eq!(server.relay.connection_cap().live_total(), 0); + + let (client, _challenge) = server.connect().await; + + // The NIP-42 challenge is queued inside `Connection::accept`, ahead of the counter's site, + // so this is the one pair a reply frame cannot order: poll both. + poll_until(|| { + metrics.connections_total() == 1 && server.relay.connection_cap().live_total() == 1 + }) + .await; + assert_eq!(metrics.connections_total(), 1); + assert_eq!(server.relay.connection_cap().live_total(), 1); + + drop(client); + + poll_until(|| server.relay.connection_cap().live_total() == 0).await; + assert_eq!( + metrics.connections_total(), + 1, + "a client that left still counted once" + ); +} + +#[tokio::test] +async fn an_event_counts_its_kind_once() { + let server = start(Fixture::new(settings())).await; + let metrics = Arc::clone(server.relay.metrics()); + let (mut client, _challenge) = server.connect().await; + + let first = signed_event(&CLIENT_SECRET, 1, vec![], "first", NOW_SECS); + let mut tampered = signed_event(&CLIENT_SECRET, 1, vec![], "second", NOW_SECS); + tampered.content = "tampered".to_owned(); + // A kind-7 event needs an `e` or `a` tag before the handler answers anything but a NOTICE. + let target = "0".repeat(64); + let reaction = signed_event( + &CLIENT_SECRET, + 7, + vec![vec!["e", target.as_str()]], + "+", + NOW_SECS, + ); + + for event in [&first, &tampered, &reaction] { + client.send(&event_frame(event)).await; + + // The counter moves before validation, so the OK reply is the synchronisation point + // whatever the verdict is. + let reply = client.expect_frame().await; + assert!( + reply.starts_with(r#"["OK",""#), + "an EVENT is answered with an OK: {reply}" + ); + } + + poll_until(|| metrics.events_received(1) == 2 && metrics.events_received(7) == 1).await; + assert_eq!(metrics.events_received(1), 2); + assert_eq!(metrics.events_received(7), 1); + assert_eq!(metrics.event_received_other(), 0); +} + +#[tokio::test] +async fn an_auth_reply_is_not_an_accepted_event() { + let server = start(Fixture::new(settings())).await; + let metrics = Arc::clone(server.relay.metrics()); + let (mut client, challenge) = server.connect().await; + + let auth = signed_event( + &CLIENT_SECRET, + 22_242, + vec![vec!["relay", RELAY_URL], vec!["challenge", &challenge]], + "", + NOW_SECS, + ); + + client.send(&auth_frame(&auth)).await; + let accepted = client.expect_frame().await; + assert_eq!( + accepted, + format!(r#"["OK","{}",true,""]"#, auth.id), + "send_auth_ok must not move the frame's bytes" + ); + + let stale = signed_event( + &CLIENT_SECRET, + 22_242, + vec![vec!["relay", RELAY_URL], vec!["challenge", &challenge]], + "", + NOW_SECS - 601, + ); + + client.send(&auth_frame(&stale)).await; + let refused = client.expect_frame().await; + assert_eq!( + refused, + format!( + r#"["OK","{}",false,"invalid: created_at is too far from the current time"]"#, + stale.id + ) + ); + + // Both replies are read, and the carve-out means no counter moves: there is nothing to + // wait for. + assert_eq!(metrics.events_accepted(), 0); + assert_eq!(metrics.events_rejected("invalid"), 0); + + for label in REJECT_LABELS { + assert_eq!(metrics.events_rejected(label), 0, "{label}"); + } + + // An EVENT is an event: its accepted verdict counts. + let note = signed_event(&CLIENT_SECRET, 1, vec![], "an event", NOW_SECS); + client.send(&event_frame(¬e)).await; + let reply = client.expect_frame().await; + assert_eq!(reply, format!(r#"["OK","{}",true,""]"#, note.id)); + + poll_until(|| metrics.events_accepted() == 1).await; + assert_eq!(metrics.events_accepted(), 1); + + for label in REJECT_LABELS { + assert_eq!(metrics.events_rejected(label), 0, "{label}"); + } +} + +#[tokio::test] +async fn a_rejection_counts_its_reason_label() { + let server = start(Fixture::new(settings())).await; + let metrics = Arc::clone(server.relay.metrics()); + let (mut client, _challenge) = server.connect().await; + + // An id that does not match the content. + let mut tampered = signed_event(&CLIENT_SECRET, 1, vec![], "tampered", NOW_SECS); + tampered.content = "tampered after signing".to_owned(); + + // An `expiration` tag in the past: the bare `event is expired` message. + let expired = signed_event( + &CLIENT_SECRET, + 1, + vec![vec!["expiration", "1000000000"]], + "", + NOW_SECS, + ); + + for event in [&tampered, &expired] { + client.send(&event_frame(event)).await; + + let reply = client.expect_frame().await; + assert!( + reply.contains(r#"false,"#), + "a refusal is an OK with false: {reply}" + ); + } + + poll_until(|| { + metrics.events_rejected("invalid") == 1 && metrics.events_rejected("expired") == 1 + }) + .await; + assert_eq!(metrics.events_rejected("invalid"), 1); + assert_eq!(metrics.events_rejected("expired"), 1); + + for label in REJECT_LABELS { + if matches!(label, "invalid" | "expired") { + continue; + } + + assert_eq!(metrics.events_rejected(label), 0, "{label}"); + } +} + +#[tokio::test] +async fn a_subscription_counts_once_and_leaves_once() { + let server = start(Fixture::new(settings())).await; + let metrics = Arc::clone(server.relay.metrics()); + let (mut client, _challenge) = server.connect().await; + + assert_eq!(metrics.subscriptions_active(), 0); + + client.send(r#"["REQ","a",{"kinds":[1]}]"#).await; + let frames = client.read_until_eose().await; + assert!( + frames + .last() + .is_some_and(|frame| frame.starts_with(r#"["EOSE","a""#)) + ); + assert_eq!(metrics.subscriptions_active(), 1); + + // A re-REQ under the same id replaces in place and must not add a second subscription. + // The filter differs because an identical one is refused as a duplicate + // (`subscribe.rs`'s `can_subscribe`), and this re-REQ has to reach `Connection::subscribe` + // for the gauge's `insert` to be exercised at all. + client.send(r#"["REQ","a",{"kinds":[1],"limit":5}]"#).await; + let frames = client.read_until_eose().await; + assert!( + frames + .last() + .is_some_and(|frame| frame.starts_with(r#"["EOSE","a""#)) + ); + assert_eq!(metrics.subscriptions_active(), 1); + + client.send(r#"["REQ","b",{"kinds":[1]}]"#).await; + client.read_until_eose().await; + assert_eq!(metrics.subscriptions_active(), 2); + + client.send(r#"["CLOSE","a"]"#).await; + poll_until(|| metrics.subscriptions_active() == 1).await; + assert_eq!(metrics.subscriptions_active(), 1); + + drop(client); + poll_until(|| metrics.subscriptions_active() == 0).await; + assert_eq!(metrics.subscriptions_active(), 0); +} + +#[tokio::test] +async fn an_eose_records_one_sample_and_an_abort_records_none() { + let server = start(Fixture::new(settings())).await; + let metrics = Arc::clone(server.relay.metrics()); + let (mut client, _challenge) = server.connect().await; + + // The tested clock is frozen, so the sample is zero milliseconds and lands in the first + // bucket. + client.send(r#"["REQ","a",{"kinds":[1]}]"#).await; + let frames = client.read_until_eose().await; + assert!( + frames + .last() + .is_some_and(|frame| frame.starts_with(r#"["EOSE","a""#)) + ); + + poll_until(|| metrics.eose_count() == 1).await; + assert_eq!(metrics.eose_count(), 1); + assert_eq!(metrics.eose_bucket("0.01"), 1); + assert_eq!(metrics.eose_bucket("+Inf"), 1); + assert_eq!(metrics.eose_sum_seconds(), 0.0); + + // An aborted read sends no EOSE, so it records no sample. + let fixture = Fixture::new(settings()); + // No permit is ever added: the stored read waits until the CLOSE aborts it. + let _gate = fixture.events.gate_reads(); + let aborted = start(fixture).await; + let aborted_metrics = Arc::clone(aborted.relay.metrics()); + let (mut aborted_client, _challenge) = aborted.connect().await; + + aborted_client + .send(r#"["REQ","blocked",{"kinds":[1]}]"#) + .await; + aborted_client.send(r#"["CLOSE","blocked"]"#).await; + + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!(aborted_metrics.eose_count(), 0); +} diff --git a/crates/nostream-relay/tests/strategies.rs b/crates/nostream-relay/tests/strategies.rs index d6c7cca4a..d4838999a 100644 --- a/crates/nostream-relay/tests/strategies.rs +++ b/crates/nostream-relay/tests/strategies.rs @@ -104,6 +104,7 @@ fn socket(fixture: &Fixture) -> (HandlerContext, mpsc::UnboundedReceiver let connection = Arc::new(Connection::new( "127.0.0.1".to_owned(), Nip42Session::with_challenge("challenge", 0), + Arc::new(nostream_relay::metrics::RelayMetrics::default()), )); (fixture.context(clock(), keys(), connection, sink), frames) From 4e88365ab68ef63a297397df126ad15eaf33b281 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sun, 29 Nov 2026 09:21:18 -0500 Subject: [PATCH 02/10] feat(admin): serve the counters at /metrics behind a bearer token --- .../src/controllers/get_prometheus_metrics.rs | 99 ++++++ crates/nostream-admin/src/controllers/mod.rs | 1 + crates/nostream-admin/src/lib.rs | 11 +- crates/nostream-admin/src/routes/mod.rs | 27 +- crates/nostream-admin/src/state.rs | 23 ++ crates/nostream-admin/tests/common/mod.rs | 6 +- .../tests/prometheus_metrics.rs | 295 ++++++++++++++++++ crates/nostream-mcp/tests/common/mod.rs | 1 + 8 files changed, 458 insertions(+), 5 deletions(-) create mode 100644 crates/nostream-admin/src/controllers/get_prometheus_metrics.rs create mode 100644 crates/nostream-admin/tests/prometheus_metrics.rs diff --git a/crates/nostream-admin/src/controllers/get_prometheus_metrics.rs b/crates/nostream-admin/src/controllers/get_prometheus_metrics.rs new file mode 100644 index 000000000..930a1ab61 --- /dev/null +++ b/crates/nostream-admin/src/controllers/get_prometheus_metrics.rs @@ -0,0 +1,99 @@ +//! `GET /metrics`: the relay's counters as Prometheus text format 0.0.4. +//! +//! Not the console's SSE stream (`get_metrics.rs`, at `/admin/metrics`): this handler +//! serves a scraper, is mounted outside the admin gate and reads no session cookie (ADR 0021, +//! decisions 1 and 2). Its one credential is the configured bearer token, compared in constant +//! time; the arms are decided in this order — no configured token, no `Authorization` header, +//! no `Bearer ` prefix, a mismatch — and every one of them answers the same `401`. + +use std::sync::Arc; + +use axum::extract::State; +use axum::http::{HeaderMap, StatusCode, header}; +use axum::response::{IntoResponse, Response}; + +use crate::controllers::with_admin_controller_request_handler::error_message; +use crate::state::PrometheusMetrics; + +/// The scheme the token rides in, exactly: the `Authorization` header's bytes after this +/// prefix are the presented token (ADR 0021, decision 2). +pub const BEARER_PREFIX: &str = "Bearer "; + +/// The Prometheus text format's own version string, which is what a scraper's parser reads. +const CONTENT_TYPE: &str = "text/plain; version=0.0.4; charset=utf-8"; + +/// Serves the exposition, or the tree's `401 {"error":"Unauthorized"}`. +pub async fn handle(State(metrics): State>, headers: HeaderMap) -> Response { + let Some(token) = metrics.token.as_deref() else { + return unauthorized(); + }; + + let Some(presented) = headers + .get(header::AUTHORIZATION) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.strip_prefix(BEARER_PREFIX)) + else { + return unauthorized(); + }; + + if !tokens_match(presented.as_bytes(), token) { + return unauthorized(); + } + + ( + StatusCode::OK, + [(header::CONTENT_TYPE, CONTENT_TYPE)], + nostream_relay::metrics::render(&metrics.counters, metrics.connections.live_total()), + ) + .into_response() +} + +/// The tree's unauthorized answer, byte for byte (`admin_auth_middleware.rs:62`). +fn unauthorized() -> Response { + error_message(StatusCode::UNAUTHORIZED, "Unauthorized") +} + +/// Whether `presented` is `configured`, in time that does not depend on where the first +/// difference is: one XOR-accumulated loop over the bytes. +/// +/// A length mismatch answers `false` early. That leaks the configured token's length to a +/// caller who can time the response, and nothing else: the bytes are never compared, so no +/// prefix of a guess can be distinguished from another. +fn tokens_match(presented: &[u8], configured: &[u8]) -> bool { + if presented.len() != configured.len() { + return false; + } + + let mut difference = 0u8; + + for (left, right) in presented.iter().zip(configured) { + difference |= left ^ right; + } + + difference == 0 +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used)] + + use super::*; + + #[test] + fn an_equal_token_matches() { + assert!(tokens_match(b"sekrit", b"sekrit")); + } + + #[test] + fn a_different_token_does_not_match() { + assert!(!tokens_match(b"sekret", b"sekrit")); + assert!(!tokens_match(b"xekrit", b"sekrit")); + } + + #[test] + fn a_length_mismatch_does_not_match() { + assert!(!tokens_match(b"sekri", b"sekrit")); + assert!(!tokens_match(b"sekritt", b"sekrit")); + assert!(!tokens_match(b"", b"sekrit")); + } +} diff --git a/crates/nostream-admin/src/controllers/mod.rs b/crates/nostream-admin/src/controllers/mod.rs index ff5779a9c..7b42ec61b 100644 --- a/crates/nostream-admin/src/controllers/mod.rs +++ b/crates/nostream-admin/src/controllers/mod.rs @@ -39,6 +39,7 @@ pub mod get_ops_nip05_verifications; pub mod get_ops_storage_counts; pub mod get_ops_workers; pub mod get_privacy; +pub mod get_prometheus_metrics; pub mod get_readyz; pub mod get_session; pub mod get_settings; diff --git a/crates/nostream-admin/src/lib.rs b/crates/nostream-admin/src/lib.rs index f4ad293b3..222ebc02f 100644 --- a/crates/nostream-admin/src/lib.rs +++ b/crates/nostream-admin/src/lib.rs @@ -23,6 +23,13 @@ //! daemon serves that router from the one listener it binds (D13): this crate never opens a //! socket. //! +//! **The scrape endpoint is the one route outside the gate.** `GET /metrics` +//! ([`METRICS_PATH`], ADR 0021, decision 1) serves the relay's counters as Prometheus text +//! format; it is mounted only when the composition root enabled it, and it is merged after the +//! admin router is `with_state`d, so `admin_enabled`, `content_security` and the admin limiter +//! do not apply to it. Its credential is the bearer token on +//! [`PrometheusMetrics`](state::PrometheusMetrics), never the session cookie. +//! //! **Deliberately not owned here** — a reader should be able to tell an omission from a gap: //! //! - the listening socket, the WebSocket upgrade and the drain — `nostreamd` and @@ -48,8 +55,8 @@ pub mod state; pub mod utils; pub use error::AdminError; -pub use routes::{ADMIN_ROUTES, AdminRoute, PREFIX_MIDDLEWARE, mount}; -pub use state::{AdminState, AdminStateConfig, GrafanaSettings, MaintenanceRun}; +pub use routes::{ADMIN_ROUTES, AdminRoute, METRICS_PATH, PREFIX_MIDDLEWARE, mount}; +pub use state::{AdminState, AdminStateConfig, GrafanaSettings, MaintenanceRun, PrometheusMetrics}; /// The CSP nonce the page's `