Rate-limit, DB liveness, WebSocket and tenant-cache telemetry
Browse files at this commite87c2a26d334cf77ff466f3d678542876266d21bParent: 057a7fa- feat
- rate-limit, DB liveness, WebSocket and tenant-cache telemetry
8 changed files +300 -33
- src/main.rs +30 -4
- src/rate_limit.rs +38 -5
- src/telemetry.rs +32 -3
- src/tenant.rs +24 -11
- src/web/board_ws.rs +1 -0
- src/web/exam_ws.rs +3 -0
- src/web/room.rs +113 -10
- tests/rate_limit.rs +59 -0
src/main.rsmodified+30 -4
| @@ -82,26 +82,52 @@ fn keepalive(db: Database, health: DbHealth) { | |||
| 82 | interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); | 82 | interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); |
| 83 | let ping_timeout = | 83 | let ping_timeout = |
| 84 | std::time::Duration::from_secs(hezarfen_backend::constant::DB_PING_TIMEOUT_SECS); | 84 | std::time::Duration::from_secs(hezarfen_backend::constant::DB_PING_TIMEOUT_SECS); |
| 85 | + let metrics = hezarfen_backend::telemetry::Metrics::global(); | ||
| 86 | + // The transitions are what an operator is paged about; a line per tick | ||
| 87 | + // would bury them. `None` until the first verdict, so that one always | ||
| 88 | + // announces itself. | ||
| 89 | + let mut was_up: Option<bool> = None; | ||
| 90 | + let mut down_since: Option<tokio::time::Instant> = None; | ||
| 85 | loop { | 91 | loop { |
| 86 | interval.tick().await; | 92 | interval.tick().await; |
| 87 | // corner-cut: an abandoned ping stays queued in the SDK and replays | 93 | // corner-cut: an abandoned ping stays queued in the SDK and replays |
| 88 | // when the socket heals, so a long outage lands a burst of no-op | 94 | // when the socket heals, so a long outage lands a burst of no-op |
| 89 | // `RETURN 1`s on recovery. Harmless; probe over a raw TCP dial | 95 | // `RETURN 1`s on recovery. Harmless; probe over a raw TCP dial |
| 90 | // instead if that burst ever shows up in a profile. | 96 | // instead if that burst ever shows up in a profile. |
| 91 | - match tokio::time::timeout(ping_timeout, db.query("RETURN 1")).await { | 97 | + let started = tokio::time::Instant::now(); |
| 98 | + let outcome = tokio::time::timeout(ping_timeout, db.query("RETURN 1")).await; | ||
| 99 | + let elapsed = started.elapsed(); | ||
| 100 | + metrics.db_ping_duration.record(elapsed.as_secs_f64(), &[]); | ||
| 101 | + let up = match &outcome { | ||
| 92 | Ok(Ok(_)) => { | 102 | Ok(Ok(_)) => { |
| 93 | - health.set(true); | ||
| 94 | tracing::debug!("database keepalive ping ok"); | 103 | tracing::debug!("database keepalive ping ok"); |
| 104 | + true | ||
| 95 | } | 105 | } |
| 96 | Ok(Err(err)) => { | 106 | Ok(Err(err)) => { |
| 97 | - health.set(false); | ||
| 98 | tracing::debug!("database keepalive ping failed: {err}"); | 107 | tracing::debug!("database keepalive ping failed: {err}"); |
| 108 | + false | ||
| 99 | } | 109 | } |
| 100 | Err(_) => { | 110 | Err(_) => { |
| 101 | - health.set(false); | ||
| 102 | tracing::debug!("database keepalive ping timed out"); | 111 | tracing::debug!("database keepalive ping timed out"); |
| 112 | + false | ||
| 103 | } | 113 | } |
| 114 | + }; | ||
| 115 | + health.set(up); | ||
| 116 | + metrics.db_up.record(u64::from(up), &[]); | ||
| 117 | + match (was_up, up) { | ||
| 118 | + (Some(true) | None, false) => { | ||
| 119 | + down_since = Some(started); | ||
| 120 | + tracing::warn!("database is down: the keepalive ping did not answer"); | ||
| 121 | + } | ||
| 122 | + (Some(false), true) => { | ||
| 123 | + let outage_secs = down_since | ||
| 124 | + .take() | ||
| 125 | + .map_or(0.0, |since| since.elapsed().as_secs_f64()); | ||
| 126 | + tracing::warn!(outage_secs, "database is back"); | ||
| 127 | + } | ||
| 128 | + _ => {} | ||
| 104 | } | 129 | } |
| 130 | + was_up = Some(up); | ||
| 105 | } | 131 | } |
| 106 | }); | 132 | }); |
| 107 | } | 133 | } |
src/rate_limit.rsmodified+38 -5
| @@ -80,7 +80,7 @@ | |||
| 80 | use std::collections::HashMap; | 80 | use std::collections::HashMap; |
| 81 | use std::hash::Hash; | 81 | use std::hash::Hash; |
| 82 | use std::net::{IpAddr, Ipv4Addr, SocketAddr}; | 82 | use std::net::{IpAddr, Ipv4Addr, SocketAddr}; |
| 83 | -use std::sync::{Arc, Mutex}; | 83 | +use std::sync::{Arc, Mutex, OnceLock}; |
| 84 | use std::time::Duration; | 84 | use std::time::Duration; |
| 85 | 85 | ||
| 86 | use axum::extract::{ConnectInfo, Request}; | 86 | use axum::extract::{ConnectInfo, Request}; |
| @@ -100,6 +100,7 @@ use crate::database::Database; | |||
| 100 | use crate::domain::timestamp::Timestamp; | 100 | use crate::domain::timestamp::Timestamp; |
| 101 | use crate::error::AppError; | 101 | use crate::error::AppError; |
| 102 | use crate::state::DbHealth; | 102 | use crate::state::DbHealth; |
| 103 | +use crate::telemetry::Metrics; | ||
| 103 | 104 | ||
| 104 | /// Per-IP rate-limit knobs, sourced from the environment (see `.env.example`) and | 105 | /// Per-IP rate-limit knobs, sourced from the environment (see `.env.example`) and |
| 105 | /// carried in [`crate::state::AppState`]. A `0` limit disables that tier. | 106 | /// carried in [`crate::state::AppState`]. A `0` limit disables that tier. |
| @@ -136,6 +137,12 @@ pub struct RateLimiter<K = IpAddr> { | |||
| 136 | /// Only meaningful for the IP tiers; the keyed tiers never look at it. | 137 | /// Only meaningful for the IP tiers; the keyed tiers never look at it. |
| 137 | trust_proxy: bool, | 138 | trust_proxy: bool, |
| 138 | buckets: Arc<Mutex<HashMap<K, Bucket>>>, | 139 | buckets: Arc<Mutex<HashMap<K, Bucket>>>, |
| 140 | + /// What this tier is called in telemetry (`api`, `auth`, `chatbot`, | ||
| 141 | + /// `builder`). Named by [`RateLimiter::share`], which is where the tier's | ||
| 142 | + /// name already lives — the constructors take a number and nothing else, | ||
| 143 | + /// and every tier the router builds is shared. Shared with the clones, so | ||
| 144 | + /// the middleware's clone sees the name too. | ||
| 145 | + tier: Arc<OnceLock<&'static str>>, | ||
| 139 | /// The single bucket every client shares once the map is saturated and no | 146 | /// The single bucket every client shares once the map is saturated and no |
| 140 | /// eviction is allowed (see the module docs). Local only: it is keyless, so | 147 | /// eviction is allowed (see the module docs). Local only: it is keyless, so |
| 141 | /// it is never synced to the shared table. | 148 | /// it is never synced to the shared table. |
| @@ -191,6 +198,21 @@ impl Bucket { | |||
| 191 | } | 198 | } |
| 192 | 199 | ||
| 193 | impl<K> RateLimiter<K> { | 200 | impl<K> RateLimiter<K> { |
| 201 | + /// This tier's telemetry name, or `unnamed` for a limiter nobody shared | ||
| 202 | + /// (tests build those; the router shares every tier it wires). | ||
| 203 | + fn tier(&self) -> &'static str { | ||
| 204 | + self.tier.get().copied().unwrap_or("unnamed") | ||
| 205 | + } | ||
| 206 | + | ||
| 207 | + /// One refusal, counted for the operator. Deliberately *only* a counter: | ||
| 208 | + /// a log line per rejection is a flood amplifier, and the only fields | ||
| 209 | + /// worth having (who, from where) are the ones telemetry may not carry. | ||
| 210 | + fn count_rejection(&self) { | ||
| 211 | + Metrics::global() | ||
| 212 | + .rate_limit_rejections_total | ||
| 213 | + .add(1, &[opentelemetry::KeyValue::new("tier", self.tier())]); | ||
| 214 | + } | ||
| 215 | + | ||
| 194 | /// Requests allowed per window, `0` meaning the tier is off. Read by | 216 | /// Requests allowed per window, `0` meaning the tier is off. Read by |
| 195 | /// `GET /limits` so a client learns its own budget instead of discovering | 217 | /// `GET /limits` so a client learns its own budget instead of discovering |
| 196 | /// it by getting a `429`. | 218 | /// it by getting a `429`. |
| @@ -223,7 +245,7 @@ impl UserRateLimiter { | |||
| 223 | /// once the user is over the cap. The handler-side twin of [`RateLimiter::enforce`]. | 245 | /// once the user is over the cap. The handler-side twin of [`RateLimiter::enforce`]. |
| 224 | pub fn enforce_user(&self, user_id: &str) -> Result<(), AppError> { | 246 | pub fn enforce_user(&self, user_id: &str) -> Result<(), AppError> { |
| 225 | self.check(user_id.to_string()).map_err(|retry_after_secs| { | 247 | self.check(user_id.to_string()).map_err(|retry_after_secs| { |
| 226 | - tracing::warn!(%user_id, retry_after_secs, "per-user rate limit exceeded"); | 248 | + tracing::warn!(retry_after_secs, "per-user rate limit exceeded"); |
| 227 | AppError::TooManyRequests { retry_after_secs } | 249 | AppError::TooManyRequests { retry_after_secs } |
| 228 | }) | 250 | }) |
| 229 | } | 251 | } |
| @@ -243,7 +265,7 @@ impl RateLimiter<IpAddr> { | |||
| 243 | match self.check(ip) { | 265 | match self.check(ip) { |
| 244 | Ok(()) => Ok(next.run(req).await), | 266 | Ok(()) => Ok(next.run(req).await), |
| 245 | Err(retry_after_secs) => { | 267 | Err(retry_after_secs) => { |
| 246 | - tracing::warn!(%ip, retry_after_secs, "rate limit exceeded"); | 268 | + tracing::warn!(retry_after_secs, "rate limit exceeded"); |
| 247 | Err(AppError::TooManyRequests { retry_after_secs }) | 269 | Err(AppError::TooManyRequests { retry_after_secs }) |
| 248 | } | 270 | } |
| 249 | } | 271 | } |
| @@ -258,6 +280,7 @@ impl<K: Eq + Hash> RateLimiter<K> { | |||
| 258 | window: Duration::from_secs(60), | 280 | window: Duration::from_secs(60), |
| 259 | trust_proxy, | 281 | trust_proxy, |
| 260 | buckets: Arc::new(Mutex::new(HashMap::new())), | 282 | buckets: Arc::new(Mutex::new(HashMap::new())), |
| 283 | + tier: Arc::new(OnceLock::new()), | ||
| 261 | overflow: Arc::new(Mutex::new(Bucket::opened_at(Instant::now()))), | 284 | overflow: Arc::new(Mutex::new(Bucket::opened_at(Instant::now()))), |
| 262 | } | 285 | } |
| 263 | } | 286 | } |
| @@ -278,9 +301,16 @@ impl<K: Eq + Hash> RateLimiter<K> { | |||
| 278 | Err((remaining.as_secs_f64().ceil() as u64).max(1)) | 301 | Err((remaining.as_secs_f64().ceil() as u64).max(1)) |
| 279 | } | 302 | } |
| 280 | 303 | ||
| 304 | + /// [`RateLimiter::check_key`], counting whatever it refuses. Every tier's | ||
| 305 | + /// rejections pass through here — both `enforce` paths and the overflow | ||
| 306 | + /// budget — so the counter cannot miss one. | ||
| 307 | + fn check(&self, key: K) -> Result<(), u64> { | ||
| 308 | + self.check_key(key).inspect_err(|_| self.count_rejection()) | ||
| 309 | + } | ||
| 310 | + | ||
| 281 | /// Count one request from `key`. `Err` carries the whole seconds (rounded | 311 | /// Count one request from `key`. `Err` carries the whole seconds (rounded |
| 282 | /// up, at least 1) until the window resets — the `Retry-After` value. | 312 | /// up, at least 1) until the window resets — the `Retry-After` value. |
| 283 | - fn check(&self, key: K) -> Result<(), u64> { | 313 | + fn check_key(&self, key: K) -> Result<(), u64> { |
| 284 | if self.max == 0 { | 314 | if self.max == 0 { |
| 285 | return Ok(()); | 315 | return Ok(()); |
| 286 | } | 316 | } |
| @@ -426,6 +456,9 @@ where | |||
| 426 | db_up: DbHealth, | 456 | db_up: DbHealth, |
| 427 | pinned: Option<i64>, | 457 | pinned: Option<i64>, |
| 428 | ) { | 458 | ) { |
| 459 | + // Before the early return: a disabled tier still wants its name, so a | ||
| 460 | + // limiter turned on later reports under it. | ||
| 461 | + let _ = self.tier.set(tier); | ||
| 429 | if self.max == 0 { | 462 | if self.max == 0 { |
| 430 | // The tier is off: `check` records nothing, so there is nothing to | 463 | // The tier is off: `check` records nothing, so there is nothing to |
| 431 | // share and no reason to hold a task or a table row. | 464 | // share and no reason to hold a task or a table row. |
| @@ -533,7 +566,7 @@ async fn sync_once<K: Eq + Hash + Clone + std::fmt::Display>( | |||
| 533 | let mut response = match with_deadline(query).await { | 566 | let mut response = match with_deadline(query).await { |
| 534 | Ok(response) => response, | 567 | Ok(response) => response, |
| 535 | Err(err) => { | 568 | Err(err) => { |
| 536 | - tracing::warn!(%err, "rate-limit sync failed; counting locally until it recovers"); | 569 | + tracing::warn!(%err, tier, "rate-limit sync failed; counting locally until it recovers"); |
| 537 | return; | 570 | return; |
| 538 | } | 571 | } |
| 539 | }; | 572 | }; |
src/telemetry.rsmodified+32 -3
| @@ -119,6 +119,9 @@ const HTTP_DURATION_BUCKETS: &[f64] = &[ | |||
| 119 | 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10.0, | 119 | 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10.0, |
| 120 | ]; | 120 | ]; |
| 121 | 121 | ||
| 122 | +/// The handle [`init`] published, read by [`Metrics::global`]. | ||
| 123 | +static GLOBAL: OnceLock<Metrics> = OnceLock::new(); | ||
| 124 | + | ||
| 122 | /// Every instrument this process publishes, declared once at boot and cloned | 125 | /// Every instrument this process publishes, declared once at boot and cloned |
| 123 | /// into whatever needs them. With no OTLP endpoint configured the global meter | 126 | /// into whatever needs them. With no OTLP endpoint configured the global meter |
| 124 | /// provider is the SDK's noop, so each instrument is a cheap empty shell and | 127 | /// provider is the SDK's noop, so each instrument is a cheap empty shell and |
| @@ -161,7 +164,13 @@ impl Metrics { | |||
| 161 | /// Declare every instrument against the global meter provider — the noop | 164 | /// Declare every instrument against the global meter provider — the noop |
| 162 | /// one unless [`init`] installed an OTLP pipeline first. | 165 | /// one unless [`init`] installed an OTLP pipeline first. |
| 163 | pub fn new() -> Self { | 166 | pub fn new() -> Self { |
| 164 | - let meter = global::meter(SCOPE); | 167 | + Self::from_meter(global::meter(SCOPE)) |
| 168 | + } | ||
| 169 | + | ||
| 170 | + /// The same instruments against a caller-supplied meter. Exists for tests | ||
| 171 | + /// that want to read their own recordings back without claiming the | ||
| 172 | + /// process-global meter provider, which the whole test binary shares. | ||
| 173 | + pub fn from_meter(meter: opentelemetry::metrics::Meter) -> Self { | ||
| 165 | Self { | 174 | Self { |
| 166 | http_server_request_duration: meter | 175 | http_server_request_duration: meter |
| 167 | .f64_histogram("http.server.request.duration") | 176 | .f64_histogram("http.server.request.duration") |
| @@ -232,6 +241,19 @@ impl Metrics { | |||
| 232 | Self::new() | 241 | Self::new() |
| 233 | } | 242 | } |
| 234 | 243 | ||
| 244 | + /// The process's instruments, for the call sites that exist before (or | ||
| 245 | + /// outside) [`crate::state::AppState`] — the rate limiter, built while the | ||
| 246 | + /// state is still being assembled, the keepalive task and the tenant cache. | ||
| 247 | + /// | ||
| 248 | + /// [`init`] publishes the handle it built; before that (every test suite, | ||
| 249 | + /// which never calls `init`) each call declares instruments against | ||
| 250 | + /// whatever meter provider is installed, so a test that installs its own | ||
| 251 | + /// provider first still sees what these call sites record. Only reached on | ||
| 252 | + /// a rejection or a cache change, never per request. | ||
| 253 | + pub fn global() -> Self { | ||
| 254 | + GLOBAL.get().cloned().unwrap_or_else(Self::new) | ||
| 255 | + } | ||
| 256 | + | ||
| 235 | /// Count one request in; the returned guard value must be handed back to | 257 | /// Count one request in; the returned guard value must be handed back to |
| 236 | /// [`Metrics::request_finished`]. | 258 | /// [`Metrics::request_finished`]. |
| 237 | pub fn request_started(&self, method: &str) { | 259 | pub fn request_started(&self, method: &str) { |
| @@ -323,7 +345,7 @@ pub fn init(cfg: &TelemetryConfig) -> Result<(TelemetryGuard, Metrics), Telemetr | |||
| 323 | meter: None, | 345 | meter: None, |
| 324 | logger: None, | 346 | logger: None, |
| 325 | }, | 347 | }, |
| 326 | - Metrics::new(), | 348 | + publish(Metrics::new()), |
| 327 | )); | 349 | )); |
| 328 | }; | 350 | }; |
| 329 | 351 | ||
| @@ -371,10 +393,17 @@ pub fn init(cfg: &TelemetryConfig) -> Result<(TelemetryGuard, Metrics), Telemetr | |||
| 371 | meter: Some(meter_provider), | 393 | meter: Some(meter_provider), |
| 372 | logger: Some(logger_provider), | 394 | logger: Some(logger_provider), |
| 373 | }, | 395 | }, |
| 374 | - Metrics::new(), | 396 | + publish(Metrics::new()), |
| 375 | )) | 397 | )) |
| 376 | } | 398 | } |
| 377 | 399 | ||
| 400 | +/// Hand the freshly built instruments to [`Metrics::global`]. A second `init` | ||
| 401 | +/// (only tests do that) keeps the first set rather than swapping it mid-flight. | ||
| 402 | +fn publish(metrics: Metrics) -> Metrics { | ||
| 403 | + let _ = GLOBAL.set(metrics.clone()); | ||
| 404 | + metrics | ||
| 405 | +} | ||
| 406 | + | ||
| 378 | /// Which OTLP wire transport to use, from the standard | 407 | /// Which OTLP wire transport to use, from the standard |
| 379 | /// `OTEL_EXPORTER_OTLP_PROTOCOL`. Both are compiled in; the collector is | 408 | /// `OTEL_EXPORTER_OTLP_PROTOCOL`. Both are compiled in; the collector is |
| 380 | /// expected on localhost or a private network, so neither carries TLS. | 409 | /// expected on localhost or a private network, so neither carries TLS. |
src/tenant.rsmodified+24 -11
| @@ -34,6 +34,7 @@ use crate::domain::page::PagedList; | |||
| 34 | use crate::domain::timestamp::Timestamp; | 34 | use crate::domain::timestamp::Timestamp; |
| 35 | use crate::error::{AppError, ValidationError}; | 35 | use crate::error::{AppError, ValidationError}; |
| 36 | use crate::module::ModuleSet; | 36 | use crate::module::ModuleSet; |
| 37 | +use crate::telemetry::Metrics; | ||
| 37 | use crate::web::tenant_state::ResolvedTenant; | 38 | use crate::web::tenant_state::ResolvedTenant; |
| 38 | 39 | ||
| 39 | pub(crate) const SCHOOL_TABLE: &str = "school"; | 40 | pub(crate) const SCHOOL_TABLE: &str = "school"; |
| @@ -538,10 +539,14 @@ impl Tenants { | |||
| 538 | } | 539 | } |
| 539 | 540 | ||
| 540 | fn forget(&self, slug: &Slug) { | 541 | fn forget(&self, slug: &Slug) { |
| 541 | - self.cache | 542 | + let (removed, size) = { |
| 542 | - .write() | 543 | + let mut cache = self.cache.write().expect("tenant cache lock"); |
| 543 | - .expect("tenant cache lock") | 544 | + (cache.remove(slug.as_str()).is_some(), cache.len()) |
| 544 | - .remove(slug.as_str()); | 545 | + }; |
| 546 | + if removed { | ||
| 547 | + tracing::info!(school = %slug, "tenant connection evicted"); | ||
| 548 | + Self::report_size(size); | ||
| 549 | + } | ||
| 545 | } | 550 | } |
| 546 | 551 | ||
| 547 | /// The cached handle, or a freshly dialled one. | 552 | /// The cached handle, or a freshly dialled one. |
| @@ -562,13 +567,21 @@ impl Tenants { | |||
| 562 | } | 567 | } |
| 563 | // Losing the race here is harmless — both handles are equivalent — but | 568 | // Losing the race here is harmless — both handles are equivalent — but |
| 564 | // the winner is kept so two requests never diverge onto two sessions. | 569 | // the winner is kept so two requests never diverge onto two sessions. |
| 565 | - Ok(self | 570 | + let (db, size) = { |
| 566 | - .cache | 571 | + let mut cache = self.cache.write().expect("tenant cache lock"); |
| 567 | - .write() | 572 | + let db = cache.entry(slug.as_str().to_string()).or_insert(db).clone(); |
| 568 | - .expect("tenant cache lock") | 573 | + (db, cache.len()) |
| 569 | - .entry(slug.as_str().to_string()) | 574 | + }; |
| 570 | - .or_insert(db) | 575 | + tracing::info!(school = %slug, "tenant connection opened"); |
| 571 | - .clone()) | 576 | + Self::report_size(size); |
| 577 | + Ok(db) | ||
| 578 | + } | ||
| 579 | + | ||
| 580 | + /// Publish how many schools the cache holds. Called after every insert and | ||
| 581 | + /// every eviction, which are the only two things that move it — a gauge | ||
| 582 | + /// sampled anywhere else would report a number nobody can act on. | ||
| 583 | + fn report_size(size: usize) { | ||
| 584 | + Metrics::global().tenant_cache_size.record(size as u64, &[]); | ||
| 572 | } | 585 | } |
| 573 | 586 | ||
| 574 | /// One new connection, pinned to `slug`'s database for its lifetime. | 587 | /// One new connection, pinned to `slug`'s database for its lifetime. |
src/web/board_ws.rsmodified+1 -0
| @@ -149,6 +149,7 @@ async fn room(mut socket: WebSocket, st: AppState, slug: Slug, board: BoardId, u | |||
| 149 | // lands between a replay's read and this subscribe would otherwise be lost | 149 | // lands between a replay's read and this subscribe would otherwise be lost |
| 150 | // outright, whereas one delivered twice is deduplicated by its id at the | 150 | // outright, whereas one delivered twice is deduplicated by its id at the |
| 151 | // client (which a resync forces anyway). | 151 | // client (which a resync forces anyway). |
| 152 | + let _connected = room::Connected::open(&st.metrics, "board", slug.as_str(), board.key()); | ||
| 152 | let mut feed = st.board_hub.subscribe(&slug, board.key()); | 153 | let mut feed = st.board_hub.subscribe(&slug, board.key()); |
| 153 | // The ids this socket drew, in the order they were published. The hub has | 154 | // The ids this socket drew, in the order they were published. The hub has |
| 154 | // no idea who is listening, so the room filters its own strokes back out | 155 | // no idea who is listening, so the room filters its own strokes back out |
src/web/exam_ws.rsmodified+3 -0
| @@ -171,6 +171,9 @@ async fn room( | |||
| 171 | ) { | 171 | ) { |
| 172 | let exam_id = exam.get_id().clone(); | 172 | let exam_id = exam.get_id().clone(); |
| 173 | let attempt_id = attempt.get_id().clone(); | 173 | let attempt_id = attempt.get_id().clone(); |
| 174 | + // The exam, not the attempt: an attempt names one student, and telemetry | ||
| 175 | + // never names a person. | ||
| 176 | + let _connected = room::Connected::open(&st.metrics, "exam_room", slug.as_str(), exam_id.key()); | ||
| 174 | // Join critical section: this socket counts as presence in the sitting's | 177 | // Join critical section: this socket counts as presence in the sitting's |
| 175 | // room until it closes, and joining clears the walk-out marker — one | 178 | // room until it closes, and joining clears the walk-out marker — one |
| 176 | // atomic step under PRESENCE_LOCK, so a dying socket's teardown either | 179 | // atomic step under PRESENCE_LOCK, so a dying socket's teardown either |
src/web/room.rsmodified+113 -10
| @@ -29,18 +29,52 @@ use axum::extract::ws::{Message, Utf8Bytes, WebSocket}; | |||
| 29 | use serde_json::{Value, json}; | 29 | use serde_json::{Value, json}; |
| 30 | 30 | ||
| 31 | use crate::error::AppError; | 31 | use crate::error::AppError; |
| 32 | +use crate::telemetry::Metrics; | ||
| 32 | 33 | ||
| 33 | -/// Errors that end a room: the peer went away, or the room reached a terminal | 34 | +/// Counts one open socket for as long as it lives. |
| 34 | -/// state and its closing frame was sent. | 35 | +/// |
| 35 | -pub(crate) struct RoomClosed; | 36 | +/// A room has several ways out — a break out of the `select!`, an early |
| 37 | +/// return, a panic — and a decrement written at any one of them is a leaked | ||
| 38 | +/// gauge at the others, drifting upwards for the process's whole life. `Drop` | ||
| 39 | +/// is the only placement that covers every exit, so the guard is created at | ||
| 40 | +/// the top of a room loop and nothing else touches the counter. | ||
| 41 | +pub(crate) struct Connected { | ||
| 42 | + metrics: Metrics, | ||
| 43 | + kind: &'static str, | ||
| 44 | + school: String, | ||
| 45 | + id: String, | ||
| 46 | +} | ||
| 36 | 47 | ||
| 37 | -/// Send one JSON frame. A failed send means the peer is gone, which ends the | 48 | +impl Connected { |
| 38 | -/// room — every caller propagates it with `?`. | 49 | + /// `kind` is the room's telemetry name (`exam_room`, `board`), `id` a |
| 39 | -pub(crate) async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> { | 50 | + /// **resource** id — the exam, the board — and never the person on the |
| 40 | - socket | 51 | + /// socket, which telemetry may not carry. |
| 41 | - .send(Message::Text(frame.to_string().into())) | 52 | + pub(crate) fn open(metrics: &Metrics, kind: &'static str, school: &str, id: &str) -> Self { |
| 42 | - .await | 53 | + metrics |
| 43 | - .map_err(|_| RoomClosed) | 54 | + .ws_connections |
| 55 | + .add(1, &[opentelemetry::KeyValue::new("kind", kind)]); | ||
| 56 | + tracing::info!(kind, school, id, "websocket opened"); | ||
| 57 | + Self { | ||
| 58 | + metrics: metrics.clone(), | ||
| 59 | + kind, | ||
| 60 | + school: school.to_string(), | ||
| 61 | + id: id.to_string(), | ||
| 62 | + } | ||
| 63 | + } | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +impl Drop for Connected { | ||
| 67 | + fn drop(&mut self) { | ||
| 68 | + self.metrics | ||
| 69 | + .ws_connections | ||
| 70 | + .add(-1, &[opentelemetry::KeyValue::new("kind", self.kind)]); | ||
| 71 | + tracing::info!( | ||
| 72 | + kind = self.kind, | ||
| 73 | + school = self.school, | ||
| 74 | + id = self.id, | ||
| 75 | + "websocket closed" | ||
| 76 | + ); | ||
| 77 | + } | ||
| 44 | } | 78 | } |
| 45 | 79 | ||
| 46 | /// The best-effort closing handshake a room ends with — a bare TCP teardown | 80 | /// 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 { | |||
| 110 | } | 144 | } |
| 111 | } | 145 | } |
| 112 | } | 146 | } |
| 147 | + | ||
| 148 | +/// Errors that end a room: the peer went away, or the room reached a terminal | ||
| 149 | +/// state and its closing frame was sent. | ||
| 150 | +pub(crate) struct RoomClosed; | ||
| 151 | + | ||
| 152 | +/// Send one JSON frame. A failed send means the peer is gone, which ends the | ||
| 153 | +/// room — every caller propagates it with `?`. | ||
| 154 | +pub(crate) async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> { | ||
| 155 | + socket | ||
| 156 | + .send(Message::Text(frame.to_string().into())) | ||
| 157 | + .await | ||
| 158 | + .map_err(|_| RoomClosed) | ||
| 159 | +} | ||
| 160 | + | ||
| 161 | +#[cfg(test)] | ||
| 162 | +mod tests { | ||
| 163 | + use opentelemetry::metrics::MeterProvider as _; | ||
| 164 | + use opentelemetry_sdk::metrics::data::{AggregatedMetrics, MetricData}; | ||
| 165 | + use opentelemetry_sdk::metrics::{InMemoryMetricExporter, PeriodicReader, SdkMeterProvider}; | ||
| 166 | + | ||
| 167 | + use super::Connected; | ||
| 168 | + use crate::telemetry::Metrics; | ||
| 169 | + | ||
| 170 | + /// The guard is the whole reason the gauge balances: every exit from a | ||
| 171 | + /// room drops it, including the ones that never reach the loop's end. Read | ||
| 172 | + /// back through a meter of this test's own, so the assertion is about what | ||
| 173 | + /// was really recorded and no other test in this binary can perturb it. | ||
| 174 | + #[test] | ||
| 175 | + fn every_open_socket_is_counted_out_again() { | ||
| 176 | + let exporter = InMemoryMetricExporter::default(); | ||
| 177 | + let provider = SdkMeterProvider::builder() | ||
| 178 | + .with_reader(PeriodicReader::builder(exporter.clone()).build()) | ||
| 179 | + .build(); | ||
| 180 | + let metrics = Metrics::from_meter(provider.meter("test")); | ||
| 181 | + | ||
| 182 | + let guard = Connected::open(&metrics, "exam_room", "demo", "exam_abc"); | ||
| 183 | + drop(guard); | ||
| 184 | + provider.force_flush().expect("flush"); | ||
| 185 | + | ||
| 186 | + let mut sum_value = None; | ||
| 187 | + for rm in exporter.get_finished_metrics().expect("metrics") { | ||
| 188 | + for scope in rm.scope_metrics() { | ||
| 189 | + for metric in scope.metrics() { | ||
| 190 | + if metric.name() != "ws_connections" { | ||
| 191 | + continue; | ||
| 192 | + } | ||
| 193 | + let AggregatedMetrics::I64(MetricData::Sum(sum)) = metric.data() else { | ||
| 194 | + panic!("an up-down counter must export as an i64 sum"); | ||
| 195 | + }; | ||
| 196 | + for point in sum.data_points() { | ||
| 197 | + assert!( | ||
| 198 | + point | ||
| 199 | + .attributes() | ||
| 200 | + .any(|kv| kv.key.as_str() == "kind" | ||
| 201 | + && kv.value.as_str() == "exam_room"), | ||
| 202 | + "the only series here is the exam room's" | ||
| 203 | + ); | ||
| 204 | + sum_value = Some(point.value()); | ||
| 205 | + } | ||
| 206 | + } | ||
| 207 | + } | ||
| 208 | + } | ||
| 209 | + assert_eq!( | ||
| 210 | + sum_value, | ||
| 211 | + Some(0), | ||
| 212 | + "a socket opened and dropped leaves the gauge where it started" | ||
| 213 | + ); | ||
| 214 | + } | ||
| 215 | +} | ||
tests/rate_limit.rsmodified+59 -0
| @@ -715,3 +715,62 @@ async fn every_route_enforces_the_shipped_limit_plus_one() { | |||
| 715 | ); | 715 | ); |
| 716 | } | 716 | } |
| 717 | } | 717 | } |
| 718 | + | ||
| 719 | +/// A refusal is not only a status: an operator watching a tier needs the | ||
| 720 | +/// count. Installs a real meter provider, drives the api tier to its `429` and | ||
| 721 | +/// reads the counter back out of an in-memory exporter. | ||
| 722 | +/// | ||
| 723 | +/// It shares the process with the rest of this binary, so the assertion is "at | ||
| 724 | +/// least one, tagged api" rather than an exact total — another test refusing | ||
| 725 | +/// concurrently is data on the same series. | ||
| 726 | +#[tokio::test] | ||
| 727 | +async fn a_rejection_is_counted_under_its_tier() { | ||
| 728 | + use opentelemetry_sdk::metrics::data::{AggregatedMetrics, MetricData}; | ||
| 729 | + use opentelemetry_sdk::metrics::{InMemoryMetricExporter, PeriodicReader, SdkMeterProvider}; | ||
| 730 | + | ||
| 731 | + let exporter = InMemoryMetricExporter::default(); | ||
| 732 | + let provider = SdkMeterProvider::builder() | ||
| 733 | + .with_reader(PeriodicReader::builder(exporter.clone()).build()) | ||
| 734 | + .build(); | ||
| 735 | + opentelemetry::global::set_meter_provider(provider.clone()); | ||
| 736 | + | ||
| 737 | + let app = app_with(RateLimitConfig { | ||
| 738 | + auth_per_minute: 0, | ||
| 739 | + api_per_minute: 2, | ||
| 740 | + trust_proxy: true, | ||
| 741 | + }) | ||
| 742 | + .await; | ||
| 743 | + for _ in 0..2 { | ||
| 744 | + let (status, _, _) = send_as(&app, "9.9.9.9", "GET", "/health", None).await; | ||
| 745 | + assert_eq!(status, StatusCode::OK); | ||
| 746 | + } | ||
| 747 | + let (status, _, _) = send_as(&app, "9.9.9.9", "GET", "/health", None).await; | ||
| 748 | + assert_eq!(status, StatusCode::TOO_MANY_REQUESTS, "the tier is spent"); | ||
| 749 | + | ||
| 750 | + provider.force_flush().expect("flush"); | ||
| 751 | + let mut api_rejections = 0u64; | ||
| 752 | + for rm in exporter.get_finished_metrics().expect("exported metrics") { | ||
| 753 | + for scope in rm.scope_metrics() { | ||
| 754 | + for metric in scope.metrics() { | ||
| 755 | + if metric.name() != "rate_limit_rejections_total" { | ||
| 756 | + continue; | ||
| 757 | + } | ||
| 758 | + let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data() else { | ||
| 759 | + panic!("a counter must export as a u64 sum"); | ||
| 760 | + }; | ||
| 761 | + for point in sum.data_points() { | ||
| 762 | + if point | ||
| 763 | + .attributes() | ||
| 764 | + .any(|kv| kv.key.as_str() == "tier" && kv.value.as_str() == "api") | ||
| 765 | + { | ||
| 766 | + api_rejections = api_rejections.max(point.value()); | ||
| 767 | + } | ||
| 768 | + } | ||
| 769 | + } | ||
| 770 | + } | ||
| 771 | + } | ||
| 772 | + assert!( | ||
| 773 | + api_rejections >= 1, | ||
| 774 | + "the 429 must show up on rate_limit_rejections_total{{tier=\"api\"}}" | ||
| 775 | + ); | ||
| 776 | +} | ||