Merge branch 'worktree-agent-a441ea882ae84cd92'
Browse files at this commit8 changed files +285 -38
- src/main.rs +30 -4
- src/rate_limit.rs +38 -5
- src/telemetry.rs +17 -8
- 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 | 82 | interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); |
| 83 | 83 | let ping_timeout = |
| 84 | 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 | 91 | loop { |
| 86 | 92 | interval.tick().await; |
| 87 | 93 | // corner-cut: an abandoned ping stays queued in the SDK and replays |
| 88 | 94 | // when the socket heals, so a long outage lands a burst of no-op |
| 89 | 95 | // `RETURN 1`s on recovery. Harmless; probe over a raw TCP dial |
| 90 | 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 | 102 | Ok(Ok(_)) => { |
| 93 | - health.set(true); | |
| 94 | 103 | tracing::debug!("database keepalive ping ok"); |
| 104 | + true | |
| 95 | 105 | } |
| 96 | 106 | Ok(Err(err)) => { |
| 97 | - health.set(false); | |
| 98 | 107 | tracing::debug!("database keepalive ping failed: {err}"); |
| 108 | + false | |
| 99 | 109 | } |
| 100 | 110 | Err(_) => { |
| 101 | - health.set(false); | |
| 102 | 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 | 80 | use std::collections::HashMap; |
| 81 | 81 | use std::hash::Hash; |
| 82 | 82 | use std::net::{IpAddr, Ipv4Addr, SocketAddr}; |
| 83 | -use std::sync::{Arc, Mutex}; | |
| 83 | +use std::sync::{Arc, Mutex, OnceLock}; | |
| 84 | 84 | use std::time::Duration; |
| 85 | 85 | |
| 86 | 86 | use axum::extract::{ConnectInfo, Request}; |
| @@ -100,6 +100,7 @@ use crate::database::Database; | ||
| 100 | 100 | use crate::domain::timestamp::Timestamp; |
| 101 | 101 | use crate::error::AppError; |
| 102 | 102 | use crate::state::DbHealth; |
| 103 | +use crate::telemetry::Metrics; | |
| 103 | 104 | |
| 104 | 105 | /// Per-IP rate-limit knobs, sourced from the environment (see `.env.example`) and |
| 105 | 106 | /// carried in [`crate::state::AppState`]. A `0` limit disables that tier. |
| @@ -136,6 +137,12 @@ pub struct RateLimiter<K = IpAddr> { | ||
| 136 | 137 | /// Only meaningful for the IP tiers; the keyed tiers never look at it. |
| 137 | 138 | trust_proxy: bool, |
| 138 | 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 | 146 | /// The single bucket every client shares once the map is saturated and no |
| 140 | 147 | /// eviction is allowed (see the module docs). Local only: it is keyless, so |
| 141 | 148 | /// it is never synced to the shared table. |
| @@ -191,6 +198,21 @@ impl Bucket { | ||
| 191 | 198 | } |
| 192 | 199 | |
| 193 | 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 | 216 | /// Requests allowed per window, `0` meaning the tier is off. Read by |
| 195 | 217 | /// `GET /limits` so a client learns its own budget instead of discovering |
| 196 | 218 | /// it by getting a `429`. |
| @@ -223,7 +245,7 @@ impl UserRateLimiter { | ||
| 223 | 245 | /// once the user is over the cap. The handler-side twin of [`RateLimiter::enforce`]. |
| 224 | 246 | pub fn enforce_user(&self, user_id: &str) -> Result<(), AppError> { |
| 225 | 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 | 249 | AppError::TooManyRequests { retry_after_secs } |
| 228 | 250 | }) |
| 229 | 251 | } |
| @@ -243,7 +265,7 @@ impl RateLimiter<IpAddr> { | ||
| 243 | 265 | match self.check(ip) { |
| 244 | 266 | Ok(()) => Ok(next.run(req).await), |
| 245 | 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 | 269 | Err(AppError::TooManyRequests { retry_after_secs }) |
| 248 | 270 | } |
| 249 | 271 | } |
| @@ -258,6 +280,7 @@ impl<K: Eq + Hash> RateLimiter<K> { | ||
| 258 | 280 | window: Duration::from_secs(60), |
| 259 | 281 | trust_proxy, |
| 260 | 282 | buckets: Arc::new(Mutex::new(HashMap::new())), |
| 283 | + tier: Arc::new(OnceLock::new()), | |
| 261 | 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 | 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 | 311 | /// Count one request from `key`. `Err` carries the whole seconds (rounded |
| 282 | 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 | 314 | if self.max == 0 { |
| 285 | 315 | return Ok(()); |
| 286 | 316 | } |
| @@ -426,6 +456,9 @@ where | ||
| 426 | 456 | db_up: DbHealth, |
| 427 | 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 | 462 | if self.max == 0 { |
| 430 | 463 | // The tier is off: `check` records nothing, so there is nothing to |
| 431 | 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 | 566 | let mut response = match with_deadline(query).await { |
| 534 | 567 | Ok(response) => response, |
| 535 | 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 | 570 | return; |
| 538 | 571 | } |
| 539 | 572 | }; |
src/telemetry.rsmodified+17 -8
| @@ -164,7 +164,13 @@ impl Metrics { | ||
| 164 | 164 | /// Declare every instrument against the global meter provider — the noop |
| 165 | 165 | /// one unless [`init`] installed an OTLP pipeline first. |
| 166 | 166 | pub fn new() -> Self { |
| 167 | - 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 { | |
| 168 | 174 | Self { |
| 169 | 175 | http_server_request_duration: meter |
| 170 | 176 | .f64_histogram("http.server.request.duration") |
| @@ -235,14 +241,17 @@ impl Metrics { | ||
| 235 | 241 | Self::new() |
| 236 | 242 | } |
| 237 | 243 | |
| 238 | - /// The process's instruments, for the few call sites that have no | |
| 239 | - /// `AppState` to read them from — [`crate::error::AppError::into_response`] | |
| 240 | - /// (axum hands it nothing) and the panic hook (which runs outside any | |
| 241 | - /// request). [`init`] publishes the real handle here; before that, and in | |
| 242 | - /// tests, this builds a noop one against the noop meter provider, so | |
| 243 | - /// recording is always safe. | |
| 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. | |
| 244 | 253 | pub fn global() -> Self { |
| 245 | - GLOBAL.get_or_init(Self::new).clone() | |
| 254 | + GLOBAL.get().cloned().unwrap_or_else(Self::new) | |
| 246 | 255 | } |
| 247 | 256 | |
| 248 | 257 | /// Count one request in; the returned guard value must be handed back to |
src/tenant.rsmodified+24 -11
| @@ -34,6 +34,7 @@ use crate::domain::page::PagedList; | ||
| 34 | 34 | use crate::domain::timestamp::Timestamp; |
| 35 | 35 | use crate::error::{AppError, ValidationError}; |
| 36 | 36 | use crate::module::ModuleSet; |
| 37 | +use crate::telemetry::Metrics; | |
| 37 | 38 | use crate::web::tenant_state::ResolvedTenant; |
| 38 | 39 | |
| 39 | 40 | pub(crate) const SCHOOL_TABLE: &str = "school"; |
| @@ -538,10 +539,14 @@ impl Tenants { | ||
| 538 | 539 | } |
| 539 | 540 | |
| 540 | 541 | fn forget(&self, slug: &Slug) { |
| 541 | - self.cache | |
| 542 | - .write() | |
| 543 | - .expect("tenant cache lock") | |
| 544 | - .remove(slug.as_str()); | |
| 542 | + let (removed, size) = { | |
| 543 | + let mut cache = self.cache.write().expect("tenant cache lock"); | |
| 544 | + (cache.remove(slug.as_str()).is_some(), cache.len()) | |
| 545 | + }; | |
| 546 | + if removed { | |
| 547 | + tracing::info!(school = %slug, "tenant connection evicted"); | |
| 548 | + Self::report_size(size); | |
| 549 | + } | |
| 545 | 550 | } |
| 546 | 551 | |
| 547 | 552 | /// The cached handle, or a freshly dialled one. |
| @@ -562,13 +567,21 @@ impl Tenants { | ||
| 562 | 567 | } |
| 563 | 568 | // Losing the race here is harmless — both handles are equivalent — but |
| 564 | 569 | // the winner is kept so two requests never diverge onto two sessions. |
| 565 | - Ok(self | |
| 566 | - .cache | |
| 567 | - .write() | |
| 568 | - .expect("tenant cache lock") | |
| 569 | - .entry(slug.as_str().to_string()) | |
| 570 | - .or_insert(db) | |
| 571 | - .clone()) | |
| 570 | + let (db, size) = { | |
| 571 | + let mut cache = self.cache.write().expect("tenant cache lock"); | |
| 572 | + let db = cache.entry(slug.as_str().to_string()).or_insert(db).clone(); | |
| 573 | + (db, cache.len()) | |
| 574 | + }; | |
| 575 | + tracing::info!(school = %slug, "tenant connection opened"); | |
| 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 | 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 | 149 | // lands between a replay's read and this subscribe would otherwise be lost |
| 150 | 150 | // outright, whereas one delivered twice is deduplicated by its id at the |
| 151 | 151 | // client (which a resync forces anyway). |
| 152 | + let _connected = room::Connected::open(&st.metrics, "board", slug.as_str(), board.key()); | |
| 152 | 153 | let mut feed = st.board_hub.subscribe(&slug, board.key()); |
| 153 | 154 | // The ids this socket drew, in the order they were published. The hub has |
| 154 | 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 | 172 | let exam_id = exam.get_id().clone(); |
| 173 | 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 | 177 | // Join critical section: this socket counts as presence in the sitting's |
| 175 | 178 | // room until it closes, and joining clears the walk-out marker — one |
| 176 | 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 | 29 | use serde_json::{Value, json}; |
| 30 | 30 | |
| 31 | 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 | -/// state and its closing frame was sent. | |
| 35 | -pub(crate) struct RoomClosed; | |
| 34 | +/// Counts one open socket for as long as it lives. | |
| 35 | +/// | |
| 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 | |
| 38 | -/// room — every caller propagates it with `?`. | |
| 39 | -pub(crate) async fn send(socket: &mut WebSocket, frame: Value) -> Result<(), RoomClosed> { | |
| 40 | - socket | |
| 41 | - .send(Message::Text(frame.to_string().into())) | |
| 42 | - .await | |
| 43 | - .map_err(|_| RoomClosed) | |
| 48 | +impl Connected { | |
| 49 | + /// `kind` is the room's telemetry name (`exam_room`, `board`), `id` a | |
| 50 | + /// **resource** id — the exam, the board — and never the person on the | |
| 51 | + /// socket, which telemetry may not carry. | |
| 52 | + pub(crate) fn open(metrics: &Metrics, kind: &'static str, school: &str, id: &str) -> Self { | |
| 53 | + metrics | |
| 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 | 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 | +} |