Merge branch 'worktree-agent-a7f3054a31bded07b'
Browse files at this commit4 changed files +348 -70
- src/ai/api.rs +22 -2
- src/ai/server.rs +175 -68
- src/lib.rs +1 -0
- tests/ai_bridge.rs +150 -0
src/ai/api.rsmodified+22 -2
| @@ -18,12 +18,21 @@ use crate::constant::AI_API_ALLOWLIST; | |||
| 18 | /// field, so a `?` here means the caller built the request wrong and the | 18 | /// field, so a `?` here means the caller built the request wrong and the |
| 19 | /// request is refused rather than silently matched on its prefix. | 19 | /// request is refused rather than silently matched on its prefix. |
| 20 | pub fn path_allowed(path: &str) -> bool { | 20 | pub fn path_allowed(path: &str) -> bool { |
| 21 | + route_template(path).is_some() | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +/// The allowlist pattern this path matched — the route *template* | ||
| 25 | +/// (`/notes/{id}`), never the concrete path, which carries record ids. This is | ||
| 26 | +/// what the bridge puts on a span or a metric label; see [`crate::telemetry`] | ||
| 27 | +/// for why the concrete path may never leave the process. | ||
| 28 | +pub fn route_template(path: &str) -> Option<&'static str> { | ||
| 21 | if !path.starts_with('/') || path.contains('?') { | 29 | if !path.starts_with('/') || path.contains('?') { |
| 22 | - return false; | 30 | + return None; |
| 23 | } | 31 | } |
| 24 | AI_API_ALLOWLIST | 32 | AI_API_ALLOWLIST |
| 25 | .iter() | 33 | .iter() |
| 26 | - .any(|pattern| pattern_matches(pattern, path)) | 34 | + .copied() |
| 35 | + .find(|pattern| pattern_matches(pattern, path)) | ||
| 27 | } | 36 | } |
| 28 | 37 | ||
| 29 | /// One `/`-separated pattern against one path. A literal segment must be | 38 | /// One `/`-separated pattern against one path. A literal segment must be |
| @@ -96,6 +105,17 @@ mod tests { | |||
| 96 | assert!(!path_allowed("/users//profile")); | 105 | assert!(!path_allowed("/users//profile")); |
| 97 | } | 106 | } |
| 98 | 107 | ||
| 108 | + #[test] | ||
| 109 | + fn the_template_is_the_pattern_not_the_path() { | ||
| 110 | + assert_eq!(route_template("/notes/note123"), Some("/notes/{id}")); | ||
| 111 | + assert_eq!(route_template("/auth/me"), Some("/auth/me")); | ||
| 112 | + assert_eq!( | ||
| 113 | + route_template("/users/user456/profile"), | ||
| 114 | + Some("/users/{id}/profile") | ||
| 115 | + ); | ||
| 116 | + assert_eq!(route_template("/users"), None); | ||
| 117 | + } | ||
| 118 | + | ||
| 99 | #[test] | 119 | #[test] |
| 100 | fn query_string_is_refused() { | 120 | fn query_string_is_refused() { |
| 101 | assert!(!path_allowed("/notes?limit=10")); | 121 | assert!(!path_allowed("/notes?limit=10")); |
src/ai/server.rsmodified+175 -68
| @@ -6,10 +6,12 @@ | |||
| 6 | 6 | ||
| 7 | use std::net::SocketAddr; | 7 | use std::net::SocketAddr; |
| 8 | use std::sync::{Arc, OnceLock}; | 8 | use std::sync::{Arc, OnceLock}; |
| 9 | -use std::time::Duration; | 9 | +use std::time::{Duration, Instant}; |
| 10 | 10 | ||
| 11 | +use opentelemetry::KeyValue; | ||
| 11 | use serde_json::Value; | 12 | use serde_json::Value; |
| 12 | use tower::ServiceExt; | 13 | use tower::ServiceExt; |
| 14 | +use tracing::Instrument; | ||
| 13 | use ulid::Ulid; | 15 | use ulid::Ulid; |
| 14 | 16 | ||
| 15 | use crate::ai::error::AiError; | 17 | use crate::ai::error::AiError; |
| @@ -31,6 +33,7 @@ use crate::domain::user::{User, UserId}; | |||
| 31 | use crate::error::AppError; | 33 | use crate::error::AppError; |
| 32 | use crate::module::Module; | 34 | use crate::module::Module; |
| 33 | use crate::state::DbHealth; | 35 | use crate::state::DbHealth; |
| 36 | +use crate::telemetry::Metrics; | ||
| 34 | use crate::tenant::{Slug, Tenants}; | 37 | use crate::tenant::{Slug, Tenants}; |
| 35 | use crate::web::blob_path; | 38 | use crate::web::blob_path; |
| 36 | use crate::web::courses::can_view_course; | 39 | use crate::web::courses::can_view_course; |
| @@ -118,6 +121,34 @@ struct Inner { | |||
| 118 | token: String, | 121 | token: String, |
| 119 | request_timeout: Duration, | 122 | request_timeout: Duration, |
| 120 | endpoint: quinn::Endpoint, | 123 | endpoint: quinn::Endpoint, |
| 124 | + /// Filled by [`AiBridge::arm_api`], for the same reason `api` is: the | ||
| 125 | + /// process's instruments are built with the router, after the listener is | ||
| 126 | + /// bound. | ||
| 127 | + metrics: OnceLock<Metrics>, | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +impl Inner { | ||
| 131 | + /// The instruments to record into. A service that dials in during the boot | ||
| 132 | + /// window gets the noop set, which — with no OTLP endpoint configured — is | ||
| 133 | + /// exactly what the armed one is anyway. | ||
| 134 | + fn metrics(&self) -> &Metrics { | ||
| 135 | + self.metrics.get_or_init(Metrics::noop) | ||
| 136 | + } | ||
| 137 | + | ||
| 138 | + /// How many services are connected right now, as the gauge sees it. | ||
| 139 | + fn record_worker_count(&self) { | ||
| 140 | + self.metrics() | ||
| 141 | + .ai_workers | ||
| 142 | + .record(self.registry.snapshot().len() as u64, &[]); | ||
| 143 | + } | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +/// Count one refused handshake. `reason` comes from a fixed vocabulary — | ||
| 147 | +/// never a message — so the metric's label cardinality stays bounded. | ||
| 148 | +fn handshake_failed(metrics: &Metrics, reason: &'static str) { | ||
| 149 | + metrics | ||
| 150 | + .ai_handshake_failures_total | ||
| 151 | + .add(1, &[KeyValue::new("reason", reason)]); | ||
| 121 | } | 152 | } |
| 122 | 153 | ||
| 123 | /// Handle to a running bridge. Cheap to clone; every clone shares one listener | 154 | /// Handle to a running bridge. Cheap to clone; every clone shares one listener |
| @@ -158,6 +189,7 @@ impl AiBridge { | |||
| 158 | token: config.token, | 189 | token: config.token, |
| 159 | request_timeout: config.request_timeout, | 190 | request_timeout: config.request_timeout, |
| 160 | endpoint, | 191 | endpoint, |
| 192 | + metrics: OnceLock::new(), | ||
| 161 | }); | 193 | }); |
| 162 | tracing::info!( | 194 | tracing::info!( |
| 163 | "AI bridge listening on {bound} (protocol {AI_PROTOCOL}, cert sha256 {fingerprint})" | 195 | "AI bridge listening on {bound} (protocol {AI_PROTOCOL}, cert sha256 {fingerprint})" |
| @@ -239,49 +271,82 @@ impl AiBridge { | |||
| 239 | payload, | 271 | payload, |
| 240 | }; | 272 | }; |
| 241 | 273 | ||
| 242 | - let call = async { | 274 | + // The span names the capability, the worker, the school slug and this |
| 243 | - let (mut send, mut recv) = | 275 | + // call's own id — never the payload, which is the user's own text. |
| 244 | - lease.conn().open_bi().await.map_err(|e| { | 276 | + let span = tracing::info_span!( |
| 277 | + "ai.request", | ||
| 278 | + "ai.capability" = capability, | ||
| 279 | + "ai.worker.id" = %lease.worker().id, | ||
| 280 | + school = school.as_str(), | ||
| 281 | + "ai.request.id" = %id, | ||
| 282 | + otel.status_code = tracing::field::Empty, | ||
| 283 | + ); | ||
| 284 | + let metrics = self.inner.metrics(); | ||
| 285 | + let attrs = [KeyValue::new("capability", capability.to_string())]; | ||
| 286 | + metrics.ai_requests_inflight.add(1, &attrs); | ||
| 287 | + let started = Instant::now(); | ||
| 288 | + | ||
| 289 | + let outcome = async { | ||
| 290 | + let call = async { | ||
| 291 | + let (mut send, mut recv) = lease.conn().open_bi().await.map_err(|e| { | ||
| 245 | AiError::Transport(format!("could not open a request stream: {e}")) | 292 | AiError::Transport(format!("could not open a request stream: {e}")) |
| 246 | })?; | 293 | })?; |
| 247 | - write_frame(&mut send, &request).await?; | 294 | + write_frame(&mut send, &request).await?; |
| 248 | - // FIN tells the service the request is complete — it can start work | 295 | + // FIN tells the service the request is complete — it can start |
| 249 | - // without waiting to see whether more bytes follow. | 296 | + // work without waiting to see whether more bytes follow. |
| 250 | - send.finish() | 297 | + send.finish().map_err(|e| { |
| 251 | - .map_err(|e| AiError::Transport(format!("could not finish the request: {e}")))?; | 298 | + AiError::Transport(format!("could not finish the request: {e}")) |
| 252 | - let response: Response = read_frame(&mut recv).await?; | 299 | + })?; |
| 253 | - Ok::<_, AiError>(response) | 300 | + let response: Response = read_frame(&mut recv).await?; |
| 254 | - }; | 301 | + Ok::<_, AiError>(response) |
| 302 | + }; | ||
| 255 | 303 | ||
| 256 | - let response = match tokio::time::timeout(timeout, call).await { | 304 | + let response = match tokio::time::timeout(timeout, call).await { |
| 257 | - Err(_) => { | 305 | + Err(_) => { |
| 258 | - tracing::warn!( | 306 | + metrics.ai_request_timeouts_total.add(1, &attrs); |
| 259 | - "AI request {id} for `{capability}` timed out after {deadline_ms}ms on worker {}", | 307 | + tracing::warn!( |
| 260 | - lease.worker().id | 308 | + "ai.request.id" = %id, |
| 261 | - ); | 309 | + capability, |
| 262 | - return Err(AiError::Timeout(deadline_ms)); | 310 | + "ai.worker.id" = %lease.worker().id, |
| 263 | - } | 311 | + deadline_ms, |
| 264 | - Ok(result) => result?, | 312 | + "AI request timed out" |
| 265 | - }; | 313 | + ); |
| 314 | + return Err(AiError::Timeout(deadline_ms)); | ||
| 315 | + } | ||
| 316 | + Ok(result) => result?, | ||
| 317 | + }; | ||
| 266 | 318 | ||
| 267 | - match response { | 319 | + match response { |
| 268 | - Response::Ok { | 320 | + Response::Ok { |
| 269 | - id: got, payload, .. | 321 | + id: got, payload, .. |
| 270 | - } if got == id => Ok(payload), | 322 | + } if got == id => Ok(payload), |
| 271 | - Response::Err { | 323 | + Response::Err { |
| 272 | - id: got, | 324 | + id: got, |
| 273 | - code, | 325 | + code, |
| 274 | - message, | 326 | + message, |
| 275 | - .. | 327 | + .. |
| 276 | - } if got == id => Err(AiError::Remote { code, message }), | 328 | + } if got == id => Err(AiError::Remote { code, message }), |
| 277 | - // A mismatched id means the service is not tracking which stream it | 329 | + // A mismatched id means the service is not tracking which |
| 278 | - // is on. Nothing here depends on the id for correlation, but the | 330 | + // stream it is on. Nothing here depends on the id for |
| 279 | - // answer's *content* now belongs to some other request, so it must | 331 | + // correlation, but the answer's *content* now belongs to some |
| 280 | - // not be handed back as this one's result. | 332 | + // other request, so it must not be handed back as this one's |
| 281 | - Response::Ok { id: got, .. } | Response::Err { id: got, .. } => { | 333 | + // result. |
| 282 | - Err(AiError::IdMismatch { expected: id, got }) | 334 | + Response::Ok { id: got, .. } | Response::Err { id: got, .. } => { |
| 335 | + Err(AiError::IdMismatch { expected: id, got }) | ||
| 336 | + } | ||
| 283 | } | 337 | } |
| 284 | } | 338 | } |
| 339 | + .instrument(span.clone()) | ||
| 340 | + .await; | ||
| 341 | + | ||
| 342 | + metrics.ai_requests_inflight.add(-1, &attrs); | ||
| 343 | + metrics | ||
| 344 | + .ai_request_duration | ||
| 345 | + .record(started.elapsed().as_secs_f64(), &attrs); | ||
| 346 | + if outcome.is_err() { | ||
| 347 | + span.record("otel.status_code", "ERROR"); | ||
| 348 | + } | ||
| 349 | + outcome | ||
| 285 | } | 350 | } |
| 286 | 351 | ||
| 287 | /// Hand the api-read path the router it dispatches into. | 352 | /// Hand the api-read path the router it dispatches into. |
| @@ -296,7 +361,11 @@ impl AiBridge { | |||
| 296 | tenants: Tenants, | 361 | tenants: Tenants, |
| 297 | db_up: DbHealth, | 362 | db_up: DbHealth, |
| 298 | files_path: std::path::PathBuf, | 363 | files_path: std::path::PathBuf, |
| 364 | + metrics: Metrics, | ||
| 299 | ) { | 365 | ) { |
| 366 | + // Not warned about on a second call: the instruments are the same | ||
| 367 | + // process-global ones either way, so re-arming changes nothing. | ||
| 368 | + let _ = self.inner.metrics.set(metrics); | ||
| 300 | if self | 369 | if self |
| 301 | .inner | 370 | .inner |
| 302 | .api | 371 | .api |
| @@ -323,10 +392,12 @@ async fn accept_loop(inner: Arc<Inner>) { | |||
| 323 | while let Some(incoming) = inner.endpoint.accept().await { | 392 | while let Some(incoming) = inner.endpoint.accept().await { |
| 324 | let inner = Arc::clone(&inner); | 393 | let inner = Arc::clone(&inner); |
| 325 | tokio::spawn(async move { | 394 | tokio::spawn(async move { |
| 326 | - let remote = incoming.remote_address(); | ||
| 327 | match incoming.await { | 395 | match incoming.await { |
| 328 | - Ok(conn) => serve_connection(inner, conn, remote).await, | 396 | + Ok(conn) => serve_connection(inner, conn).await, |
| 329 | - Err(e) => tracing::warn!("AI service handshake from {remote} failed: {e}"), | 397 | + Err(e) => { |
| 398 | + handshake_failed(inner.metrics(), "transport"); | ||
| 399 | + tracing::warn!(error = %e, "an AI service's QUIC handshake failed"); | ||
| 400 | + } | ||
| 330 | } | 401 | } |
| 331 | }); | 402 | }); |
| 332 | } | 403 | } |
| @@ -335,10 +406,10 @@ async fn accept_loop(inner: Arc<Inner>) { | |||
| 335 | 406 | ||
| 336 | /// Run one service connection: handshake, register, wait for it to die, | 407 | /// Run one service connection: handshake, register, wait for it to die, |
| 337 | /// deregister. | 408 | /// deregister. |
| 338 | -async fn serve_connection(inner: Arc<Inner>, conn: quinn::Connection, remote: SocketAddr) { | 409 | +async fn serve_connection(inner: Arc<Inner>, conn: quinn::Connection) { |
| 339 | let handshake = tokio::time::timeout( | 410 | let handshake = tokio::time::timeout( |
| 340 | Duration::from_secs(AI_HANDSHAKE_TIMEOUT_SECS), | 411 | Duration::from_secs(AI_HANDSHAKE_TIMEOUT_SECS), |
| 341 | - register(&inner, &conn, remote), | 412 | + register(&inner, &conn), |
| 342 | ) | 413 | ) |
| 343 | .await; | 414 | .await; |
| 344 | 415 | ||
| @@ -346,7 +417,8 @@ async fn serve_connection(inner: Arc<Inner>, conn: quinn::Connection, remote: So | |||
| 346 | Ok(Ok(registered)) => registered, | 417 | Ok(Ok(registered)) => registered, |
| 347 | Ok(Err(())) => return, | 418 | Ok(Err(())) => return, |
| 348 | Err(_) => { | 419 | Err(_) => { |
| 349 | - tracing::warn!("AI service at {remote} did not complete its handshake in time"); | 420 | + handshake_failed(inner.metrics(), "timeout"); |
| 421 | + tracing::warn!("an AI service did not complete its handshake in time"); | ||
| 350 | conn.close(2u32.into(), b"handshake timeout"); | 422 | conn.close(2u32.into(), b"handshake timeout"); |
| 351 | return; | 423 | return; |
| 352 | } | 424 | } |
| @@ -373,7 +445,13 @@ async fn serve_connection(inner: Arc<Inner>, conn: quinn::Connection, remote: So | |||
| 373 | } | 445 | } |
| 374 | }; | 446 | }; |
| 375 | inner.registry.remove(&worker_id); | 447 | inner.registry.remove(&worker_id); |
| 376 | - tracing::info!("AI service `{service}` ({worker_id}) at {remote} disconnected: {reason}"); | 448 | + inner.record_worker_count(); |
| 449 | + tracing::info!( | ||
| 450 | + "worker.id" = %worker_id, | ||
| 451 | + service = %service, | ||
| 452 | + reason = %reason, | ||
| 453 | + "AI service disconnected" | ||
| 454 | + ); | ||
| 377 | } | 455 | } |
| 378 | 456 | ||
| 379 | /// Answer one client-initiated stream. Two shapes ride this path and are told | 457 | /// Answer one client-initiated stream. Two shapes ride this path and are told |
| @@ -675,7 +753,7 @@ async fn read_api( | |||
| 675 | "unavailable", | 753 | "unavailable", |
| 676 | "the api is not serving yet — retry".to_string(), | 754 | "the api is not serving yet — retry".to_string(), |
| 677 | ))?; | 755 | ))?; |
| 678 | - dispatch_api(api, request).await | 756 | + dispatch_api(api, inner.metrics(), request).await |
| 679 | } | 757 | } |
| 680 | 758 | ||
| 681 | /// The half of [`read_api`] that needs only the armed handle: liveness, | 759 | /// The half of [`read_api`] that needs only the armed handle: liveness, |
| @@ -684,6 +762,7 @@ async fn read_api( | |||
| 684 | /// endpoint (see this module's tests). | 762 | /// endpoint (see this module's tests). |
| 685 | async fn dispatch_api( | 763 | async fn dispatch_api( |
| 686 | api: &ApiHandle, | 764 | api: &ApiHandle, |
| 765 | + metrics: &Metrics, | ||
| 687 | request: ApiRequest, | 766 | request: ApiRequest, |
| 688 | ) -> Result<ApiResponse, (&'static str, String)> { | 767 | ) -> Result<ApiResponse, (&'static str, String)> { |
| 689 | let ApiRequest { | 768 | let ApiRequest { |
| @@ -741,12 +820,32 @@ async fn dispatch_api( | |||
| 741 | modules: tenant.modules, | 820 | modules: tenant.modules, |
| 742 | }); | 821 | }); |
| 743 | 822 | ||
| 823 | + // This dispatch skips every layer, so it also skips the request span and | ||
| 824 | + // the request metrics the HTTP edge records — they are recorded here | ||
| 825 | + // instead, off the route *template* the allowlist matched. The concrete | ||
| 826 | + // path holds record ids and never reaches a span or a label. | ||
| 827 | + let route = crate::ai::api::route_template(&path).unwrap_or("unmatched"); | ||
| 828 | + let otel_name = format!("GET {route}"); | ||
| 829 | + let span = tracing::info_span!( | ||
| 830 | + "http.request", | ||
| 831 | + otel.name = %otel_name, | ||
| 832 | + "http.request.method" = "GET", | ||
| 833 | + "http.route" = route, | ||
| 834 | + school = school.as_str(), | ||
| 835 | + "ai.origin" = true, | ||
| 836 | + "http.response.status_code" = tracing::field::Empty, | ||
| 837 | + ); | ||
| 838 | + metrics.request_started("GET"); | ||
| 839 | + let started = Instant::now(); | ||
| 840 | + | ||
| 744 | let response = tokio::time::timeout( | 841 | let response = tokio::time::timeout( |
| 745 | Duration::from_secs(REQUEST_TIMEOUT_SECS), | 842 | Duration::from_secs(REQUEST_TIMEOUT_SECS), |
| 746 | api.router.clone().oneshot(dispatched), | 843 | api.router.clone().oneshot(dispatched), |
| 747 | ) | 844 | ) |
| 845 | + .instrument(span.clone()) | ||
| 748 | .await | 846 | .await |
| 749 | .map_err(|_| { | 847 | .map_err(|_| { |
| 848 | + metrics.request_finished("GET", route, 504, Some(&school), started.elapsed()); | ||
| 750 | ( | 849 | ( |
| 751 | "unavailable", | 850 | "unavailable", |
| 752 | format!("`{target}` did not answer within {REQUEST_TIMEOUT_SECS}s"), | 851 | format!("`{target}` did not answer within {REQUEST_TIMEOUT_SECS}s"), |
| @@ -755,6 +854,10 @@ async fn dispatch_api( | |||
| 755 | .expect("an axum router is infallible"); | 854 | .expect("an axum router is infallible"); |
| 756 | 855 | ||
| 757 | let status = response.status().as_u16(); | 856 | let status = response.status().as_u16(); |
| 857 | + // Recorded as soon as the router has answered: what follows is bridge | ||
| 858 | + // framing, not the HTTP request the caller made. | ||
| 859 | + metrics.request_finished("GET", route, status, Some(&school), started.elapsed()); | ||
| 860 | + span.record("http.response.status_code", i64::from(status)); | ||
| 758 | let body = axum::body::to_bytes(response.into_body(), AI_MAX_FRAME_BYTES) | 861 | let body = axum::body::to_bytes(response.into_body(), AI_MAX_FRAME_BYTES) |
| 759 | .await | 862 | .await |
| 760 | .map_err(|e| { | 863 | .map_err(|e| { |
| @@ -837,12 +940,12 @@ type Control = (quinn::SendStream, quinn::RecvStream); | |||
| 837 | async fn register( | 940 | async fn register( |
| 838 | inner: &Inner, | 941 | inner: &Inner, |
| 839 | conn: &quinn::Connection, | 942 | conn: &quinn::Connection, |
| 840 | - remote: SocketAddr, | ||
| 841 | ) -> Result<(String, String, Control), ()> { | 943 | ) -> Result<(String, String, Control), ()> { |
| 842 | let (mut send, mut recv) = match conn.accept_bi().await { | 944 | let (mut send, mut recv) = match conn.accept_bi().await { |
| 843 | Ok(streams) => streams, | 945 | Ok(streams) => streams, |
| 844 | Err(e) => { | 946 | Err(e) => { |
| 845 | - tracing::warn!("AI service at {remote} opened no control stream: {e}"); | 947 | + handshake_failed(inner.metrics(), "no_control_stream"); |
| 948 | + tracing::warn!(error = %e, "an AI service opened no control stream"); | ||
| 846 | return Err(()); | 949 | return Err(()); |
| 847 | } | 950 | } |
| 848 | }; | 951 | }; |
| @@ -850,7 +953,8 @@ async fn register( | |||
| 850 | let hello: Hello = match read_frame(&mut recv).await { | 953 | let hello: Hello = match read_frame(&mut recv).await { |
| 851 | Ok(hello) => hello, | 954 | Ok(hello) => hello, |
| 852 | Err(e) => { | 955 | Err(e) => { |
| 853 | - tracing::warn!("AI service at {remote} sent an unreadable Hello: {e}"); | 956 | + handshake_failed(inner.metrics(), "malformed_hello"); |
| 957 | + tracing::warn!(error = %e, "an AI service sent an unreadable Hello"); | ||
| 854 | refuse(&mut send, conn, RejectCode::Malformed, &e.to_string()).await; | 958 | refuse(&mut send, conn, RejectCode::Malformed, &e.to_string()).await; |
| 855 | return Err(()); | 959 | return Err(()); |
| 856 | } | 960 | } |
| @@ -861,25 +965,27 @@ async fn register( | |||
| 861 | "this backend speaks {AI_PROTOCOL}, the service announced {}", | 965 | "this backend speaks {AI_PROTOCOL}, the service announced {}", |
| 862 | hello.protocol | 966 | hello.protocol |
| 863 | ); | 967 | ); |
| 864 | - tracing::warn!( | 968 | + handshake_failed(inner.metrics(), "bad_version"); |
| 865 | - "AI service `{}` at {remote} rejected: {message}", | 969 | + tracing::warn!(service = %hello.service, reason = "bad_version", "AI service rejected: {message}"); |
| 866 | - hello.service | ||
| 867 | - ); | ||
| 868 | refuse(&mut send, conn, RejectCode::UnsupportedProtocol, &message).await; | 970 | refuse(&mut send, conn, RejectCode::UnsupportedProtocol, &message).await; |
| 869 | return Err(()); | 971 | return Err(()); |
| 870 | } | 972 | } |
| 871 | if !constant_time_eq(hello.token.as_bytes(), inner.token.as_bytes()) { | 973 | if !constant_time_eq(hello.token.as_bytes(), inner.token.as_bytes()) { |
| 974 | + handshake_failed(inner.metrics(), "bad_token"); | ||
| 872 | tracing::warn!( | 975 | tracing::warn!( |
| 873 | - "AI service `{}` at {remote} rejected: bad shared token", | 976 | + service = %hello.service, |
| 874 | - hello.service | 977 | + reason = "bad_token", |
| 978 | + "AI service rejected: bad shared token" | ||
| 875 | ); | 979 | ); |
| 876 | refuse(&mut send, conn, RejectCode::Unauthorized, "invalid token").await; | 980 | refuse(&mut send, conn, RejectCode::Unauthorized, "invalid token").await; |
| 877 | return Err(()); | 981 | return Err(()); |
| 878 | } | 982 | } |
| 879 | if hello.capabilities.is_empty() { | 983 | if hello.capabilities.is_empty() { |
| 984 | + handshake_failed(inner.metrics(), "bad_capabilities"); | ||
| 880 | tracing::warn!( | 985 | tracing::warn!( |
| 881 | - "AI service `{}` at {remote} rejected: declared no capabilities", | 986 | + service = %hello.service, |
| 882 | - hello.service | 987 | + reason = "bad_capabilities", |
| 988 | + "AI service rejected: declared no capabilities" | ||
| 883 | ); | 989 | ); |
| 884 | refuse( | 990 | refuse( |
| 885 | &mut send, | 991 | &mut send, |
| @@ -898,10 +1004,8 @@ async fn register( | |||
| 898 | protocol: AI_PROTOCOL.to_string(), | 1004 | protocol: AI_PROTOCOL.to_string(), |
| 899 | }; | 1005 | }; |
| 900 | if let Err(e) = write_frame(&mut send, &greeting).await { | 1006 | if let Err(e) = write_frame(&mut send, &greeting).await { |
| 901 | - tracing::warn!( | 1007 | + handshake_failed(inner.metrics(), "welcome_failed"); |
| 902 | - "could not welcome AI service `{}` at {remote}: {e}", | 1008 | + tracing::warn!(service = %hello.service, error = %e, "could not welcome an AI service"); |
| 903 | - hello.service | ||
| 904 | - ); | ||
| 905 | return Err(()); | 1009 | return Err(()); |
| 906 | } | 1010 | } |
| 907 | 1011 | ||
| @@ -914,10 +1018,13 @@ async fn register( | |||
| 914 | max_concurrent, | 1018 | max_concurrent, |
| 915 | conn.clone(), | 1019 | conn.clone(), |
| 916 | ); | 1020 | ); |
| 1021 | + inner.record_worker_count(); | ||
| 917 | tracing::info!( | 1022 | tracing::info!( |
| 918 | - "AI service `{}` ({worker_id}) at {remote} registered: {:?}, max_concurrent {max_concurrent}", | 1023 | + "worker.id" = %worker_id, |
| 919 | - hello.service, | 1024 | + service = %hello.service, |
| 920 | - hello.capabilities | 1025 | + capabilities = hello.capabilities.len(), |
| 1026 | + max_concurrent, | ||
| 1027 | + "AI service registered" | ||
| 921 | ); | 1028 | ); |
| 922 | Ok((worker_id, hello.service, (send, recv))) | 1029 | Ok((worker_id, hello.service, (send, recv))) |
| 923 | } | 1030 | } |
| @@ -957,7 +1064,7 @@ mod tests { | |||
| 957 | use axum::routing::get; | 1064 | use axum::routing::get; |
| 958 | 1065 | ||
| 959 | use super::{ | 1066 | use super::{ |
| 960 | - AI_MAX_FRAME_BYTES, ApiHandle, ApiRequest, ApiResponse, constant_time_eq, | 1067 | + AI_MAX_FRAME_BYTES, ApiHandle, ApiRequest, ApiResponse, Metrics, constant_time_eq, |
| 961 | refuse_before_dispatch, | 1068 | refuse_before_dispatch, |
| 962 | }; | 1069 | }; |
| 963 | use crate::ai::protocol::read_frame; | 1070 | use crate::ai::protocol::read_frame; |
| @@ -1005,7 +1112,7 @@ mod tests { | |||
| 1005 | let router = axum::Router::new().route("/notes", get(|| async { "plain text" })); | 1112 | let router = axum::Router::new().route("/notes", get(|| async { "plain text" })); |
| 1006 | let api = armed(router).await; | 1113 | let api = armed(router).await; |
| 1007 | assert_eq!( | 1114 | assert_eq!( |
| 1008 | - refused(super::dispatch_api(&api, read_of("/notes")).await), | 1115 | + refused(super::dispatch_api(&api, &Metrics::noop(), read_of("/notes")).await), |
| 1009 | "not_json" | 1116 | "not_json" |
| 1010 | ); | 1117 | ); |
| 1011 | } | 1118 | } |
| @@ -1019,7 +1126,7 @@ mod tests { | |||
| 1019 | get(|| async { axum::http::StatusCode::NO_CONTENT }), | 1126 | get(|| async { axum::http::StatusCode::NO_CONTENT }), |
| 1020 | ); | 1127 | ); |
| 1021 | let api = armed(router).await; | 1128 | let api = armed(router).await; |
| 1022 | - match super::dispatch_api(&api, read_of("/notes")).await { | 1129 | + match super::dispatch_api(&api, &Metrics::noop(), read_of("/notes")).await { |
| 1023 | Ok(ApiResponse::Ok { status, body, .. }) => { | 1130 | Ok(ApiResponse::Ok { status, body, .. }) => { |
| 1024 | assert_eq!(status, 204); | 1131 | assert_eq!(status, 204); |
| 1025 | assert_eq!(body, serde_json::Value::Null); | 1132 | assert_eq!(body, serde_json::Value::Null); |
| @@ -1038,7 +1145,7 @@ mod tests { | |||
| 1038 | ); | 1145 | ); |
| 1039 | let api = armed(router).await; | 1146 | let api = armed(router).await; |
| 1040 | assert_eq!( | 1147 | assert_eq!( |
| 1041 | - refused(super::dispatch_api(&api, read_of("/notes")).await), | 1148 | + refused(super::dispatch_api(&api, &Metrics::noop(), read_of("/notes")).await), |
| 1042 | "too_large" | 1149 | "too_large" |
| 1043 | ); | 1150 | ); |
| 1044 | } | 1151 | } |
src/lib.rsmodified+1 -0
| @@ -247,6 +247,7 @@ pub fn build_router(state: AppState) -> Router { | |||
| 247 | state.tenants.clone(), | 247 | state.tenants.clone(), |
| 248 | state.db_up.clone(), | 248 | state.db_up.clone(), |
| 249 | state.files_path.clone(), | 249 | state.files_path.clone(), |
| 250 | + metrics.clone(), | ||
| 250 | ); | 251 | ); |
| 251 | } | 252 | } |
| 252 | 253 | ||
tests/ai_bridge.rsmodified+150 -0
| @@ -2590,3 +2590,153 @@ async fn a_blob_read_is_refused_module_disabled_when_the_school_has_no_chatbot() | |||
| 2590 | ); | 2590 | ); |
| 2591 | assert!(bytes == uploaded, "the bytes differ from what was uploaded"); | 2591 | assert!(bytes == uploaded, "the bytes differ from what was uploaded"); |
| 2592 | } | 2592 | } |
| 2593 | + | ||
| 2594 | +// ------------------------------------------------------------- telemetry -- | ||
| 2595 | + | ||
| 2596 | +/// Attribute keys telemetry may never leave the process with — the list | ||
| 2597 | +/// `tests/telemetry.rs` fixes for the HTTP edge, applied to the bridge's own | ||
| 2598 | +/// spans. A prompt, a message or a user id showing up here is the failure this | ||
| 2599 | +/// guards against. | ||
| 2600 | +const FORBIDDEN: &[&str] = &[ | ||
| 2601 | + "url.path", | ||
| 2602 | + "url.full", | ||
| 2603 | + "url.query", | ||
| 2604 | + "client.address", | ||
| 2605 | + "network.peer.address", | ||
| 2606 | + "user_agent.original", | ||
| 2607 | + "user.id", | ||
| 2608 | + "user.name", | ||
| 2609 | + "enduser.id", | ||
| 2610 | + "cookie", | ||
| 2611 | + "http.request.body", | ||
| 2612 | + "http.response.body", | ||
| 2613 | +]; | ||
| 2614 | + | ||
| 2615 | +/// The bridge's own observability, asserted end to end over real QUIC: one | ||
| 2616 | +/// dispatched request must produce an `ai.request` span naming the capability | ||
| 2617 | +/// and nothing about the caller, and one refused handshake must reach the | ||
| 2618 | +/// failure counter under a stable `reason`. | ||
| 2619 | +/// | ||
| 2620 | +/// The only test in this binary that installs a subscriber — `tracing`'s | ||
| 2621 | +/// global default can be set once per process — so both assertions live in it | ||
| 2622 | +/// rather than in a test each. Everything is filtered by a capability no other | ||
| 2623 | +/// test uses, since the other tests keep dispatching into the same exporters. | ||
| 2624 | +#[tokio::test] | ||
| 2625 | +async fn a_dispatch_is_traced_by_capability_and_a_refused_handshake_is_counted() { | ||
| 2626 | + use opentelemetry::trace::TracerProvider as _; | ||
| 2627 | + use opentelemetry_sdk::metrics::data::{AggregatedMetrics, MetricData}; | ||
| 2628 | + use opentelemetry_sdk::metrics::{InMemoryMetricExporter, PeriodicReader, SdkMeterProvider}; | ||
| 2629 | + use opentelemetry_sdk::trace::{InMemorySpanExporter, SdkTracerProvider}; | ||
| 2630 | + use tracing_subscriber::layer::SubscriberExt; | ||
| 2631 | + use tracing_subscriber::util::SubscriberInitExt; | ||
| 2632 | + | ||
| 2633 | + let span_exporter = InMemorySpanExporter::default(); | ||
| 2634 | + let tracer_provider = SdkTracerProvider::builder() | ||
| 2635 | + .with_simple_exporter(span_exporter.clone()) | ||
| 2636 | + .build(); | ||
| 2637 | + let metric_exporter = InMemoryMetricExporter::default(); | ||
| 2638 | + let meter_provider = SdkMeterProvider::builder() | ||
| 2639 | + .with_reader(PeriodicReader::builder(metric_exporter.clone()).build()) | ||
| 2640 | + .build(); | ||
| 2641 | + // Installed before the bridge exists: its instruments are taken from | ||
| 2642 | + // whatever meter provider is global when it first records. | ||
| 2643 | + opentelemetry::global::set_meter_provider(meter_provider.clone()); | ||
| 2644 | + tracing_subscriber::registry() | ||
| 2645 | + .with(tracing_opentelemetry::layer().with_tracer(tracer_provider.tracer("test"))) | ||
| 2646 | + .init(); | ||
| 2647 | + | ||
| 2648 | + let bridge = bridge().await; | ||
| 2649 | + let _service = connect_service( | ||
| 2650 | + &bridge, | ||
| 2651 | + hello("probe", &["telemetry.probe"]), | ||
| 2652 | + Behaviour::Echo, | ||
| 2653 | + ) | ||
| 2654 | + .await; | ||
| 2655 | + await_workers(&bridge, 1).await; | ||
| 2656 | + bridge | ||
| 2657 | + .dispatch(&demo(), "telemetry.probe", json!({ "image": "abc" })) | ||
| 2658 | + .await | ||
| 2659 | + .expect("the service answered"); | ||
| 2660 | + | ||
| 2661 | + // A refusal on its own connection, for the handshake counter. | ||
| 2662 | + let mut wrong = hello("probe", &["telemetry.probe"]); | ||
| 2663 | + wrong.token = "not-the-token".into(); | ||
| 2664 | + let (_endpoint, _conn, _send, _recv, greeting) = shake_hands(&bridge, wrong).await; | ||
| 2665 | + assert!( | ||
| 2666 | + matches!(greeting, Greeting::Rejected { .. }), | ||
| 2667 | + "{greeting:?}" | ||
| 2668 | + ); | ||
| 2669 | + | ||
| 2670 | + tracer_provider.force_flush().expect("flush spans"); | ||
| 2671 | + let spans = span_exporter.get_finished_spans().expect("exported spans"); | ||
| 2672 | + let attrs_of = |span: &opentelemetry_sdk::trace::SpanData| -> Vec<(String, String)> { | ||
| 2673 | + span.attributes | ||
| 2674 | + .iter() | ||
| 2675 | + .map(|kv| (kv.key.to_string(), kv.value.to_string())) | ||
| 2676 | + .collect() | ||
| 2677 | + }; | ||
| 2678 | + let request = spans | ||
| 2679 | + .iter() | ||
| 2680 | + .find(|s| { | ||
| 2681 | + s.name == "ai.request" | ||
| 2682 | + && attrs_of(s) | ||
| 2683 | + .contains(&("ai.capability".to_string(), "telemetry.probe".to_string())) | ||
| 2684 | + }) | ||
| 2685 | + .unwrap_or_else(|| { | ||
| 2686 | + panic!( | ||
| 2687 | + "no ai.request span named the probe capability: {:?}", | ||
| 2688 | + spans.iter().map(|s| s.name.to_string()).collect::<Vec<_>>() | ||
| 2689 | + ) | ||
| 2690 | + }); | ||
| 2691 | + let attrs = attrs_of(request); | ||
| 2692 | + assert!( | ||
| 2693 | + attrs.contains(&("school".to_string(), DEMO_SLUG.to_string())), | ||
| 2694 | + "the span names the school slug: {attrs:?}" | ||
| 2695 | + ); | ||
| 2696 | + assert!( | ||
| 2697 | + attrs | ||
| 2698 | + .iter() | ||
| 2699 | + .any(|(k, v)| k == "ai.worker.id" && !v.is_empty()), | ||
| 2700 | + "{attrs:?}" | ||
| 2701 | + ); | ||
| 2702 | + assert!( | ||
| 2703 | + attrs | ||
| 2704 | + .iter() | ||
| 2705 | + .any(|(k, v)| k == "ai.request.id" && !v.is_empty()), | ||
| 2706 | + "{attrs:?}" | ||
| 2707 | + ); | ||
| 2708 | + for span in &spans { | ||
| 2709 | + for (key, _) in attrs_of(span) { | ||
| 2710 | + assert!( | ||
| 2711 | + !FORBIDDEN.contains(&key.as_str()), | ||
| 2712 | + "span {:?} carries {key:?}, which may never leave this process", | ||
| 2713 | + span.name | ||
| 2714 | + ); | ||
| 2715 | + } | ||
| 2716 | + } | ||
| 2717 | + | ||
| 2718 | + meter_provider.force_flush().expect("flush metrics"); | ||
| 2719 | + let mut refused = 0u64; | ||
| 2720 | + for resource in metric_exporter.get_finished_metrics().expect("metrics") { | ||
| 2721 | + for scope in resource.scope_metrics() { | ||
| 2722 | + for metric in scope.metrics() { | ||
| 2723 | + if metric.name() != "ai_handshake_failures_total" { | ||
| 2724 | + continue; | ||
| 2725 | + } | ||
| 2726 | + if let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data() { | ||
| 2727 | + for point in sum.data_points() { | ||
| 2728 | + if point.attributes().any(|kv| { | ||
| 2729 | + kv.key.as_str() == "reason" && kv.value.to_string() == "bad_token" | ||
| 2730 | + }) { | ||
| 2731 | + refused += point.value(); | ||
| 2732 | + } | ||
| 2733 | + } | ||
| 2734 | + } | ||
| 2735 | + } | ||
| 2736 | + } | ||
| 2737 | + } | ||
| 2738 | + assert!( | ||
| 2739 | + refused >= 1, | ||
| 2740 | + "the refused handshake must be counted under reason=bad_token" | ||
| 2741 | + ); | ||
| 2742 | +} | ||