diff --git a/src/main.rs b/src/main.rs index f0133ee..5d6df58 100644 --- a/src/main.rs +++ b/src/main.rs @@ -82,26 +82,52 @@ fn keepalive(db: Database, health: DbHealth) { interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); let ping_timeout = std::time::Duration::from_secs(hezarfen_backend::constant::DB_PING_TIMEOUT_SECS); + let metrics = hezarfen_backend::telemetry::Metrics::global(); + // The transitions are what an operator is paged about; a line per tick + // would bury them. `None` until the first verdict, so that one always + // announces itself. + let mut was_up: Option = None; + let mut down_since: Option = None; loop { interval.tick().await; // corner-cut: an abandoned ping stays queued in the SDK and replays // when the socket heals, so a long outage lands a burst of no-op // `RETURN 1`s on recovery. Harmless; probe over a raw TCP dial // instead if that burst ever shows up in a profile. - match tokio::time::timeout(ping_timeout, db.query("RETURN 1")).await { + let started = tokio::time::Instant::now(); + let outcome = tokio::time::timeout(ping_timeout, db.query("RETURN 1")).await; + let elapsed = started.elapsed(); + metrics.db_ping_duration.record(elapsed.as_secs_f64(), &[]); + let up = match &outcome { Ok(Ok(_)) => { - health.set(true); tracing::debug!("database keepalive ping ok"); + true } Ok(Err(err)) => { - health.set(false); tracing::debug!("database keepalive ping failed: {err}"); + false } Err(_) => { - health.set(false); tracing::debug!("database keepalive ping timed out"); + false } + }; + health.set(up); + metrics.db_up.record(u64::from(up), &[]); + match (was_up, up) { + (Some(true) | None, false) => { + down_since = Some(started); + tracing::warn!("database is down: the keepalive ping did not answer"); + } + (Some(false), true) => { + let outage_secs = down_since + .take() + .map_or(0.0, |since| since.elapsed().as_secs_f64()); + tracing::warn!(outage_secs, "database is back"); + } + _ => {} } + was_up = Some(up); } }); } diff --git a/src/rate_limit.rs b/src/rate_limit.rs index cd19885..46826f4 100644 --- a/src/rate_limit.rs +++ b/src/rate_limit.rs @@ -80,7 +80,7 @@ use std::collections::HashMap; use std::hash::Hash; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, OnceLock}; use std::time::Duration; use axum::extract::{ConnectInfo, Request}; @@ -100,6 +100,7 @@ use crate::database::Database; use crate::domain::timestamp::Timestamp; use crate::error::AppError; use crate::state::DbHealth; +use crate::telemetry::Metrics; /// Per-IP rate-limit knobs, sourced from the environment (see `.env.example`) and /// carried in [`crate::state::AppState`]. A `0` limit disables that tier. @@ -136,6 +137,12 @@ pub struct RateLimiter { /// Only meaningful for the IP tiers; the keyed tiers never look at it. trust_proxy: bool, buckets: Arc>>, + /// What this tier is called in telemetry (`api`, `auth`, `chatbot`, + /// `builder`). Named by [`RateLimiter::share`], which is where the tier's + /// name already lives — the constructors take a number and nothing else, + /// and every tier the router builds is shared. Shared with the clones, so + /// the middleware's clone sees the name too. + tier: Arc>, /// The single bucket every client shares once the map is saturated and no /// eviction is allowed (see the module docs). Local only: it is keyless, so /// it is never synced to the shared table. @@ -191,6 +198,21 @@ impl Bucket { } impl RateLimiter { + /// This tier's telemetry name, or `unnamed` for a limiter nobody shared + /// (tests build those; the router shares every tier it wires). + fn tier(&self) -> &'static str { + self.tier.get().copied().unwrap_or("unnamed") + } + + /// One refusal, counted for the operator. Deliberately *only* a counter: + /// a log line per rejection is a flood amplifier, and the only fields + /// worth having (who, from where) are the ones telemetry may not carry. + fn count_rejection(&self) { + Metrics::global() + .rate_limit_rejections_total + .add(1, &[opentelemetry::KeyValue::new("tier", self.tier())]); + } + /// Requests allowed per window, `0` meaning the tier is off. Read by /// `GET /limits` so a client learns its own budget instead of discovering /// it by getting a `429`. @@ -223,7 +245,7 @@ impl UserRateLimiter { /// once the user is over the cap. The handler-side twin of [`RateLimiter::enforce`]. pub fn enforce_user(&self, user_id: &str) -> Result<(), AppError> { self.check(user_id.to_string()).map_err(|retry_after_secs| { - tracing::warn!(%user_id, retry_after_secs, "per-user rate limit exceeded"); + tracing::warn!(retry_after_secs, "per-user rate limit exceeded"); AppError::TooManyRequests { retry_after_secs } }) } @@ -243,7 +265,7 @@ impl RateLimiter { match self.check(ip) { Ok(()) => Ok(next.run(req).await), Err(retry_after_secs) => { - tracing::warn!(%ip, retry_after_secs, "rate limit exceeded"); + tracing::warn!(retry_after_secs, "rate limit exceeded"); Err(AppError::TooManyRequests { retry_after_secs }) } } @@ -258,6 +280,7 @@ impl RateLimiter { window: Duration::from_secs(60), trust_proxy, buckets: Arc::new(Mutex::new(HashMap::new())), + tier: Arc::new(OnceLock::new()), overflow: Arc::new(Mutex::new(Bucket::opened_at(Instant::now()))), } } @@ -278,9 +301,16 @@ impl RateLimiter { Err((remaining.as_secs_f64().ceil() as u64).max(1)) } + /// [`RateLimiter::check_key`], counting whatever it refuses. Every tier's + /// rejections pass through here — both `enforce` paths and the overflow + /// budget — so the counter cannot miss one. + fn check(&self, key: K) -> Result<(), u64> { + self.check_key(key).inspect_err(|_| self.count_rejection()) + } + /// Count one request from `key`. `Err` carries the whole seconds (rounded /// up, at least 1) until the window resets — the `Retry-After` value. - fn check(&self, key: K) -> Result<(), u64> { + fn check_key(&self, key: K) -> Result<(), u64> { if self.max == 0 { return Ok(()); } @@ -426,6 +456,9 @@ where db_up: DbHealth, pinned: Option, ) { + // Before the early return: a disabled tier still wants its name, so a + // limiter turned on later reports under it. + let _ = self.tier.set(tier); if self.max == 0 { // The tier is off: `check` records nothing, so there is nothing to // share and no reason to hold a task or a table row. @@ -533,7 +566,7 @@ async fn sync_once( let mut response = match with_deadline(query).await { Ok(response) => response, Err(err) => { - tracing::warn!(%err, "rate-limit sync failed; counting locally until it recovers"); + tracing::warn!(%err, tier, "rate-limit sync failed; counting locally until it recovers"); return; } }; diff --git a/src/telemetry.rs b/src/telemetry.rs index 34c0fcb..d82fc9d 100644 --- a/src/telemetry.rs +++ b/src/telemetry.rs @@ -164,7 +164,13 @@ impl Metrics { /// Declare every instrument against the global meter provider — the noop /// one unless [`init`] installed an OTLP pipeline first. pub fn new() -> Self { - let meter = global::meter(SCOPE); + Self::from_meter(global::meter(SCOPE)) + } + + /// The same instruments against a caller-supplied meter. Exists for tests + /// that want to read their own recordings back without claiming the + /// process-global meter provider, which the whole test binary shares. + pub fn from_meter(meter: opentelemetry::metrics::Meter) -> Self { Self { http_server_request_duration: meter .f64_histogram("http.server.request.duration") @@ -235,14 +241,17 @@ impl Metrics { Self::new() } - /// The process's instruments, for the few call sites that have no - /// `AppState` to read them from — [`crate::error::AppError::into_response`] - /// (axum hands it nothing) and the panic hook (which runs outside any - /// request). [`init`] publishes the real handle here; before that, and in - /// tests, this builds a noop one against the noop meter provider, so - /// recording is always safe. + /// The process's instruments, for the call sites that exist before (or + /// outside) [`crate::state::AppState`] — the rate limiter, built while the + /// state is still being assembled, the keepalive task and the tenant cache. + /// + /// [`init`] publishes the handle it built; before that (every test suite, + /// which never calls `init`) each call declares instruments against + /// whatever meter provider is installed, so a test that installs its own + /// provider first still sees what these call sites record. Only reached on + /// a rejection or a cache change, never per request. pub fn global() -> Self { - GLOBAL.get_or_init(Self::new).clone() + GLOBAL.get().cloned().unwrap_or_else(Self::new) } /// Count one request in; the returned guard value must be handed back to diff --git a/src/tenant.rs b/src/tenant.rs index 6232d7c..5410a6d 100644 --- a/src/tenant.rs +++ b/src/tenant.rs @@ -34,6 +34,7 @@ use crate::domain::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ValidationError}; use crate::module::ModuleSet; +use crate::telemetry::Metrics; use crate::web::tenant_state::ResolvedTenant; pub(crate) const SCHOOL_TABLE: &str = "school"; @@ -538,10 +539,14 @@ impl Tenants { } fn forget(&self, slug: &Slug) { - self.cache - .write() - .expect("tenant cache lock") - .remove(slug.as_str()); + let (removed, size) = { + let mut cache = self.cache.write().expect("tenant cache lock"); + (cache.remove(slug.as_str()).is_some(), cache.len()) + }; + if removed { + tracing::info!(school = %slug, "tenant connection evicted"); + Self::report_size(size); + } } /// The cached handle, or a freshly dialled one. @@ -562,13 +567,21 @@ impl Tenants { } // Losing the race here is harmless — both handles are equivalent — but // the winner is kept so two requests never diverge onto two sessions. - Ok(self - .cache - .write() - .expect("tenant cache lock") - .entry(slug.as_str().to_string()) - .or_insert(db) - .clone()) + let (db, size) = { + let mut cache = self.cache.write().expect("tenant cache lock"); + let db = cache.entry(slug.as_str().to_string()).or_insert(db).clone(); + (db, cache.len()) + }; + tracing::info!(school = %slug, "tenant connection opened"); + Self::report_size(size); + Ok(db) + } + + /// Publish how many schools the cache holds. Called after every insert and + /// every eviction, which are the only two things that move it — a gauge + /// sampled anywhere else would report a number nobody can act on. + fn report_size(size: usize) { + Metrics::global().tenant_cache_size.record(size as u64, &[]); } /// One new connection, pinned to `slug`'s database for its lifetime. diff --git a/src/web/board_ws.rs b/src/web/board_ws.rs index 90b6c90..4e5d38a 100644 --- a/src/web/board_ws.rs +++ b/src/web/board_ws.rs @@ -149,6 +149,7 @@ async fn room(mut socket: WebSocket, st: AppState, slug: Slug, board: BoardId, u // lands between a replay's read and this subscribe would otherwise be lost // outright, whereas one delivered twice is deduplicated by its id at the // client (which a resync forces anyway). + let _connected = room::Connected::open(&st.metrics, "board", slug.as_str(), board.key()); let mut feed = st.board_hub.subscribe(&slug, board.key()); // The ids this socket drew, in the order they were published. The hub has // no idea who is listening, so the room filters its own strokes back out diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index b6f21c3..e426f19 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -171,6 +171,9 @@ async fn room( ) { let exam_id = exam.get_id().clone(); let attempt_id = attempt.get_id().clone(); + // The exam, not the attempt: an attempt names one student, and telemetry + // never names a person. + let _connected = room::Connected::open(&st.metrics, "exam_room", slug.as_str(), exam_id.key()); // Join critical section: this socket counts as presence in the sitting's // room until it closes, and joining clears the walk-out marker — one // atomic step under PRESENCE_LOCK, so a dying socket's teardown either diff --git a/src/web/room.rs b/src/web/room.rs index 15415d6..5d484f7 100644 --- a/src/web/room.rs +++ b/src/web/room.rs @@ -29,18 +29,52 @@ use axum::extract::ws::{Message, Utf8Bytes, WebSocket}; use serde_json::{Value, json}; use crate::error::AppError; +use crate::telemetry::Metrics; -/// Errors that end a room: the peer went away, or the room reached a terminal -/// state and its closing frame was sent. -pub(crate) struct RoomClosed; +/// Counts one open socket for as long as it lives. +/// +/// A room has several ways out — a break out of the `select!`, an early +/// return, a panic — and a decrement written at any one of them is a leaked +/// gauge at the others, drifting upwards for the process's whole life. `Drop` +/// is the only placement that covers every exit, so the guard is created at +/// the top of a room loop and nothing else touches the counter. +pub(crate) struct Connected { + metrics: Metrics, + kind: &'static str, + school: String, + id: String, +} -/// Send one JSON frame. A failed send means the peer is gone, which ends the -/// room — every caller propagates it with `?`. -pub(crate) async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> { - socket - .send(Message::Text(frame.to_string().into())) - .await - .map_err(|_| RoomClosed) +impl Connected { + /// `kind` is the room's telemetry name (`exam_room`, `board`), `id` a + /// **resource** id — the exam, the board — and never the person on the + /// socket, which telemetry may not carry. + pub(crate) fn open(metrics: &Metrics, kind: &'static str, school: &str, id: &str) -> Self { + metrics + .ws_connections + .add(1, &[opentelemetry::KeyValue::new("kind", kind)]); + tracing::info!(kind, school, id, "websocket opened"); + Self { + metrics: metrics.clone(), + kind, + school: school.to_string(), + id: id.to_string(), + } + } +} + +impl Drop for Connected { + fn drop(&mut self) { + self.metrics + .ws_connections + .add(-1, &[opentelemetry::KeyValue::new("kind", self.kind)]); + tracing::info!( + kind = self.kind, + school = self.school, + id = self.id, + "websocket closed" + ); + } } /// The best-effort closing handshake a room ends with — a bare TCP teardown @@ -110,3 +144,72 @@ pub(crate) fn public_message(err: &AppError, room: &str) -> String { } } } + +/// Errors that end a room: the peer went away, or the room reached a terminal +/// state and its closing frame was sent. +pub(crate) struct RoomClosed; + +/// Send one JSON frame. A failed send means the peer is gone, which ends the +/// room — every caller propagates it with `?`. +pub(crate) async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> { + socket + .send(Message::Text(frame.to_string().into())) + .await + .map_err(|_| RoomClosed) +} + +#[cfg(test)] +mod tests { + use opentelemetry::metrics::MeterProvider as _; + use opentelemetry_sdk::metrics::data::{AggregatedMetrics, MetricData}; + use opentelemetry_sdk::metrics::{InMemoryMetricExporter, PeriodicReader, SdkMeterProvider}; + + use super::Connected; + use crate::telemetry::Metrics; + + /// The guard is the whole reason the gauge balances: every exit from a + /// room drops it, including the ones that never reach the loop's end. Read + /// back through a meter of this test's own, so the assertion is about what + /// was really recorded and no other test in this binary can perturb it. + #[test] + fn every_open_socket_is_counted_out_again() { + let exporter = InMemoryMetricExporter::default(); + let provider = SdkMeterProvider::builder() + .with_reader(PeriodicReader::builder(exporter.clone()).build()) + .build(); + let metrics = Metrics::from_meter(provider.meter("test")); + + let guard = Connected::open(&metrics, "exam_room", "demo", "exam_abc"); + drop(guard); + provider.force_flush().expect("flush"); + + let mut sum_value = None; + for rm in exporter.get_finished_metrics().expect("metrics") { + for scope in rm.scope_metrics() { + for metric in scope.metrics() { + if metric.name() != "ws_connections" { + continue; + } + let AggregatedMetrics::I64(MetricData::Sum(sum)) = metric.data() else { + panic!("an up-down counter must export as an i64 sum"); + }; + for point in sum.data_points() { + assert!( + point + .attributes() + .any(|kv| kv.key.as_str() == "kind" + && kv.value.as_str() == "exam_room"), + "the only series here is the exam room's" + ); + sum_value = Some(point.value()); + } + } + } + } + assert_eq!( + sum_value, + Some(0), + "a socket opened and dropped leaves the gauge where it started" + ); + } +} diff --git a/tests/rate_limit.rs b/tests/rate_limit.rs index b65eec0..7bb2db8 100644 --- a/tests/rate_limit.rs +++ b/tests/rate_limit.rs @@ -715,3 +715,62 @@ async fn every_route_enforces_the_shipped_limit_plus_one() { ); } } + +/// A refusal is not only a status: an operator watching a tier needs the +/// count. Installs a real meter provider, drives the api tier to its `429` and +/// reads the counter back out of an in-memory exporter. +/// +/// It shares the process with the rest of this binary, so the assertion is "at +/// least one, tagged api" rather than an exact total — another test refusing +/// concurrently is data on the same series. +#[tokio::test] +async fn a_rejection_is_counted_under_its_tier() { + use opentelemetry_sdk::metrics::data::{AggregatedMetrics, MetricData}; + use opentelemetry_sdk::metrics::{InMemoryMetricExporter, PeriodicReader, SdkMeterProvider}; + + let exporter = InMemoryMetricExporter::default(); + let provider = SdkMeterProvider::builder() + .with_reader(PeriodicReader::builder(exporter.clone()).build()) + .build(); + opentelemetry::global::set_meter_provider(provider.clone()); + + let app = app_with(RateLimitConfig { + auth_per_minute: 0, + api_per_minute: 2, + trust_proxy: true, + }) + .await; + for _ in 0..2 { + let (status, _, _) = send_as(&app, "9.9.9.9", "GET", "/health", None).await; + assert_eq!(status, StatusCode::OK); + } + let (status, _, _) = send_as(&app, "9.9.9.9", "GET", "/health", None).await; + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS, "the tier is spent"); + + provider.force_flush().expect("flush"); + let mut api_rejections = 0u64; + for rm in exporter.get_finished_metrics().expect("exported metrics") { + for scope in rm.scope_metrics() { + for metric in scope.metrics() { + if metric.name() != "rate_limit_rejections_total" { + continue; + } + let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data() else { + panic!("a counter must export as a u64 sum"); + }; + for point in sum.data_points() { + if point + .attributes() + .any(|kv| kv.key.as_str() == "tier" && kv.value.as_str() == "api") + { + api_rejections = api_rejections.max(point.value()); + } + } + } + } + } + assert!( + api_rejections >= 1, + "the 429 must show up on rate_limit_rejections_total{{tier=\"api\"}}" + ); +}