| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use std::net::SocketAddr; |
| 8 | use std::sync::{Arc, OnceLock}; |
| 9 | use std::time::{Duration, Instant}; |
| 10 | |
| 11 | use opentelemetry::KeyValue; |
| 12 | use serde_json::Value; |
| 13 | use tower::ServiceExt; |
| 14 | use tracing::Instrument; |
| 15 | |
| 16 | use crate::ai::error::AiError; |
| 17 | use crate::ai::protocol::{ |
| 18 | ApiRequest, ApiResponse, BlobRequest, BlobResponse, BlobUploadRequest, BlobUploadResponse, |
| 19 | CapabilityRequest, CapabilityResponse, FrameError, Greeting, Hello, RejectCode, Request, |
| 20 | Response, protocol_matches, read_frame, write_frame, |
| 21 | }; |
| 22 | use crate::ai::registry::{AiRegistry, WorkerSnapshot, clamp_concurrency}; |
| 23 | use crate::ai::tls; |
| 24 | use crate::constant::{ |
| 25 | AI_BLOB_WRITE_STALL_SECS, AI_HANDSHAKE_TIMEOUT_SECS, AI_MAX_FRAME_BYTES, AI_PROTOCOL, |
| 26 | AI_RAG_INDEX_CAPABILITY, REQUEST_TIMEOUT_SECS, |
| 27 | }; |
| 28 | use crate::database::Database; |
| 29 | |
| 30 | use crate::domain::course_note_file::CourseNoteFileId; |
| 31 | use crate::domain::monotonic_id::next_uuid; |
| 32 | use crate::domain::user::{User, UserId}; |
| 33 | use crate::error::AppError; |
| 34 | use crate::module::Module; |
| 35 | use crate::state::AppState; |
| 36 | use crate::telemetry::Metrics; |
| 37 | use crate::service::course::can_view_course; |
| 38 | use crate::tenant::{ResolvedTenant, SchoolId, Tenants}; |
| 39 | use crate::web::blob_path; |
| 40 | use crate::web::extractor::AiPrincipal; |
| 41 | use crate::web::tenant_state::{TenantExt, school_files_path}; |
| 42 | |
| 43 | |
| 44 | #[derive(Clone, Debug)] |
| 45 | pub struct BridgeConfig { |
| 46 | |
| 47 | pub addr: SocketAddr, |
| 48 | |
| 49 | pub token: String, |
| 50 | |
| 51 | pub cert_path: Option<String>, |
| 52 | pub key_path: Option<String>, |
| 53 | |
| 54 | pub request_timeout: Duration, |
| 55 | } |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | struct ApiHandle { |
| 63 | router: axum::Router, |
| 64 | tenants: Tenants, |
| 65 | |
| 66 | |
| 67 | files_path: std::path::PathBuf, |
| 68 | } |
| 69 | |
| 70 | impl ApiHandle { |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | async fn school(&self, school: &str) -> Result<ResolvedTenant, (&'static str, String)> { |
| 78 | let id = match SchoolId::try_parse(school) { |
| 79 | Ok(id) => id, |
| 80 | Err(_) => { |
| 81 | return Err(( |
| 82 | "unknown_school", |
| 83 | format!("this deployment serves no `{school}` school"), |
| 84 | )); |
| 85 | } |
| 86 | }; |
| 87 | self.tenants.resolve(&id).await.map_err(|err| match err { |
| 88 | AppError::Unauthorized => ( |
| 89 | "unknown_school", |
| 90 | format!("this deployment serves no `{id}` school"), |
| 91 | ), |
| 92 | AppError::Forbidden(_) => ( |
| 93 | "school_suspended", |
| 94 | format!("the `{id}` school is suspended"), |
| 95 | ), |
| 96 | other => ( |
| 97 | "unavailable", |
| 98 | format!("the `{id}` school is not reachable: {other}"), |
| 99 | ), |
| 100 | }) |
| 101 | } |
| 102 | |
| 103 | |
| 104 | fn files_dir(&self, id: &SchoolId) -> std::path::PathBuf { |
| 105 | school_files_path(&self.files_path, id) |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | struct Inner { |
| 110 | registry: AiRegistry, |
| 111 | |
| 112 | |
| 113 | |
| 114 | |
| 115 | api: OnceLock<ApiHandle>, |
| 116 | |
| 117 | |
| 118 | |
| 119 | certificate: rustls::pki_types::CertificateDer<'static>, |
| 120 | token: String, |
| 121 | request_timeout: Duration, |
| 122 | endpoint: quinn::Endpoint, |
| 123 | |
| 124 | |
| 125 | |
| 126 | metrics: OnceLock<Metrics>, |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | replay: OnceLock<AppState>, |
| 132 | } |
| 133 | |
| 134 | impl Inner { |
| 135 | |
| 136 | |
| 137 | |
| 138 | fn metrics(&self) -> &Metrics { |
| 139 | self.metrics.get_or_init(Metrics::noop) |
| 140 | } |
| 141 | |
| 142 | |
| 143 | fn record_worker_count(&self) { |
| 144 | self.metrics() |
| 145 | .ai_workers |
| 146 | .record(self.registry.snapshot().len() as u64, &[]); |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | |
| 151 | |
| 152 | fn handshake_failed(metrics: &Metrics, reason: &'static str) { |
| 153 | metrics |
| 154 | .ai_handshake_failures_total |
| 155 | .add(1, &[KeyValue::new("reason", reason)]); |
| 156 | } |
| 157 | |
| 158 | |
| 159 | |
| 160 | #[derive(Clone)] |
| 161 | pub struct AiBridge { |
| 162 | inner: Arc<Inner>, |
| 163 | } |
| 164 | |
| 165 | impl AiBridge { |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 173 | pub async fn bind(config: BridgeConfig) -> Result<Self, AiError> { |
| 174 | if config.token.trim().is_empty() { |
| 175 | return Err(AiError::Setup( |
| 176 | "AI_SHARED_TOKEN must be set when the AI bridge is enabled".into(), |
| 177 | )); |
| 178 | } |
| 179 | let bridge_tls = tls::build(config.cert_path.as_deref(), config.key_path.as_deref())?; |
| 180 | let fingerprint = tls::fingerprint(&bridge_tls.leaf); |
| 181 | let endpoint = |
| 182 | quinn::Endpoint::server(bridge_tls.server_config, config.addr).map_err(|e| { |
| 183 | AiError::Setup(format!("cannot bind the AI bridge to {}: {e}", config.addr)) |
| 184 | })?; |
| 185 | let bound = endpoint |
| 186 | .local_addr() |
| 187 | .map_err(|e| AiError::Setup(format!("bound socket has no address: {e}")))?; |
| 188 | |
| 189 | let inner = Arc::new(Inner { |
| 190 | registry: AiRegistry::default(), |
| 191 | api: OnceLock::new(), |
| 192 | certificate: bridge_tls.leaf.clone(), |
| 193 | token: config.token, |
| 194 | request_timeout: config.request_timeout, |
| 195 | endpoint, |
| 196 | metrics: OnceLock::new(), |
| 197 | replay: OnceLock::new(), |
| 198 | }); |
| 199 | tracing::info!( |
| 200 | "AI bridge listening on {bound} (protocol {AI_PROTOCOL}, cert sha256 {fingerprint})" |
| 201 | ); |
| 202 | tokio::spawn(accept_loop(Arc::clone(&inner))); |
| 203 | Ok(Self { inner }) |
| 204 | } |
| 205 | |
| 206 | |
| 207 | |
| 208 | pub fn local_addr(&self) -> Result<SocketAddr, AiError> { |
| 209 | self.inner |
| 210 | .endpoint |
| 211 | .local_addr() |
| 212 | .map_err(|e| AiError::Transport(e.to_string())) |
| 213 | } |
| 214 | |
| 215 | |
| 216 | |
| 217 | pub fn certificate(&self) -> rustls::pki_types::CertificateDer<'static> { |
| 218 | self.inner.certificate.clone() |
| 219 | } |
| 220 | |
| 221 | |
| 222 | pub fn certificate_fingerprint(&self) -> String { |
| 223 | tls::fingerprint(&self.inner.certificate) |
| 224 | } |
| 225 | |
| 226 | |
| 227 | pub fn workers(&self) -> Vec<WorkerSnapshot> { |
| 228 | self.inner.registry.snapshot() |
| 229 | } |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | pub fn has_capability(&self, capability: &str) -> bool { |
| 237 | self.inner.registry.has_capability(capability) |
| 238 | } |
| 239 | |
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 244 | |
| 245 | pub async fn dispatch( |
| 246 | &self, |
| 247 | school: &SchoolId, |
| 248 | capability: &str, |
| 249 | payload: Value, |
| 250 | ) -> Result<Value, AiError> { |
| 251 | self.dispatch_with_timeout(school, capability, payload, self.inner.request_timeout) |
| 252 | .await |
| 253 | } |
| 254 | |
| 255 | |
| 256 | |
| 257 | |
| 258 | pub async fn dispatch_with_timeout( |
| 259 | &self, |
| 260 | school: &SchoolId, |
| 261 | capability: &str, |
| 262 | payload: Value, |
| 263 | timeout: Duration, |
| 264 | ) -> Result<Value, AiError> { |
| 265 | |
| 266 | |
| 267 | |
| 268 | let lease = self.inner.registry.pick(capability)?; |
| 269 | let id = next_uuid().to_string(); |
| 270 | let deadline_ms = timeout.as_millis().min(u64::MAX as u128) as u64; |
| 271 | let request = Request { |
| 272 | id: id.clone(), |
| 273 | school: school.as_str().to_string(), |
| 274 | capability: capability.to_string(), |
| 275 | deadline_ms, |
| 276 | payload, |
| 277 | }; |
| 278 | |
| 279 | |
| 280 | |
| 281 | let span = tracing::info_span!( |
| 282 | "ai.request", |
| 283 | "ai.capability" = capability, |
| 284 | "ai.worker.id" = %lease.worker().id, |
| 285 | school = school.as_str(), |
| 286 | "ai.request.id" = %id, |
| 287 | otel.status_code = tracing::field::Empty, |
| 288 | ); |
| 289 | let metrics = self.inner.metrics(); |
| 290 | let attrs = [KeyValue::new("capability", capability.to_string())]; |
| 291 | let _in_flight = InFlight::started(metrics, &attrs); |
| 292 | let started = Instant::now(); |
| 293 | |
| 294 | let outcome = async { |
| 295 | let call = async { |
| 296 | let (mut send, mut recv) = lease.conn().open_bi().await.map_err(|e| { |
| 297 | AiError::Transport(format!("could not open a request stream: {e}")) |
| 298 | })?; |
| 299 | write_frame(&mut send, &request).await?; |
| 300 | |
| 301 | |
| 302 | send.finish().map_err(|e| { |
| 303 | AiError::Transport(format!("could not finish the request: {e}")) |
| 304 | })?; |
| 305 | let response: Response = read_frame(&mut recv).await?; |
| 306 | Ok::<_, AiError>(response) |
| 307 | }; |
| 308 | |
| 309 | let response = match tokio::time::timeout(timeout, call).await { |
| 310 | Err(_) => { |
| 311 | metrics.ai_request_timeouts_total.add(1, &attrs); |
| 312 | tracing::warn!( |
| 313 | "ai.request.id" = %id, |
| 314 | capability, |
| 315 | "ai.worker.id" = %lease.worker().id, |
| 316 | deadline_ms, |
| 317 | "AI request timed out" |
| 318 | ); |
| 319 | return Err(AiError::Timeout(deadline_ms)); |
| 320 | } |
| 321 | Ok(result) => result?, |
| 322 | }; |
| 323 | |
| 324 | match response { |
| 325 | Response::Ok { |
| 326 | id: got, payload, .. |
| 327 | } if got == id => Ok(payload), |
| 328 | Response::Err { |
| 329 | id: got, |
| 330 | code, |
| 331 | message, |
| 332 | .. |
| 333 | } if got == id => Err(AiError::Remote { code, message }), |
| 334 | |
| 335 | |
| 336 | |
| 337 | |
| 338 | |
| 339 | Response::Ok { id: got, .. } | Response::Err { id: got, .. } => { |
| 340 | Err(AiError::IdMismatch { expected: id, got }) |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | .instrument(span.clone()) |
| 345 | .await; |
| 346 | |
| 347 | |
| 348 | |
| 349 | |
| 350 | |
| 351 | |
| 352 | |
| 353 | |
| 354 | if let Err(AiError::Remote { code, .. }) = &outcome |
| 355 | && contradicts_its_own_claim(code) |
| 356 | { |
| 357 | self.inner.registry.withdraw(&lease.worker().id, capability); |
| 358 | tracing::warn!( |
| 359 | service = %lease.worker().service, |
| 360 | capability, |
| 361 | code = %code, |
| 362 | "AI service refused a capability it advertised; claim withdrawn until it reconnects" |
| 363 | ); |
| 364 | } |
| 365 | |
| 366 | metrics |
| 367 | .ai_request_duration |
| 368 | .record(started.elapsed().as_secs_f64(), &attrs); |
| 369 | if outcome.is_err() { |
| 370 | span.record("otel.status_code", "ERROR"); |
| 371 | } |
| 372 | outcome |
| 373 | } |
| 374 | |
| 375 | |
| 376 | |
| 377 | |
| 378 | |
| 379 | |
| 380 | |
| 381 | pub(crate) fn arm_api( |
| 382 | &self, |
| 383 | router: axum::Router, |
| 384 | tenants: Tenants, |
| 385 | files_path: std::path::PathBuf, |
| 386 | metrics: Metrics, |
| 387 | state: &AppState, |
| 388 | ) { |
| 389 | |
| 390 | |
| 391 | let _ = self.inner.metrics.set(metrics); |
| 392 | if self |
| 393 | .inner |
| 394 | .api |
| 395 | .set(ApiHandle { |
| 396 | router, |
| 397 | tenants, |
| 398 | files_path, |
| 399 | }) |
| 400 | .is_err() |
| 401 | { |
| 402 | tracing::warn!("the AI bridge api path was already armed — keeping the first router"); |
| 403 | } |
| 404 | |
| 405 | |
| 406 | |
| 407 | |
| 408 | let mut rooted = state.clone(); |
| 409 | rooted.ai = None; |
| 410 | if self.inner.replay.set(rooted).is_err() { |
| 411 | tracing::warn!("rag index replay was already armed — keeping the first state"); |
| 412 | } else if self.has_capability(AI_RAG_INDEX_CAPABILITY) { |
| 413 | spawn_index_replay_if_armed(&self.inner); |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | |
| 418 | pub fn close(&self) { |
| 419 | self.inner.endpoint.close(0u32.into(), b"shutting down"); |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | |
| 424 | |
| 425 | |
| 426 | |
| 427 | |
| 428 | |
| 429 | |
| 430 | |
| 431 | |
| 432 | |
| 433 | |
| 434 | |
| 435 | fn contradicts_its_own_claim(code: &str) -> bool { |
| 436 | code == "unknown_capability" |
| 437 | } |
| 438 | |
| 439 | |
| 440 | async fn accept_loop(inner: Arc<Inner>) { |
| 441 | while let Some(incoming) = inner.endpoint.accept().await { |
| 442 | let inner = Arc::clone(&inner); |
| 443 | tokio::spawn(async move { |
| 444 | match incoming.await { |
| 445 | Ok(conn) => serve_connection(inner, conn).await, |
| 446 | Err(e) => { |
| 447 | handshake_failed(inner.metrics(), "transport"); |
| 448 | tracing::warn!(error = %e, "an AI service's QUIC handshake failed"); |
| 449 | } |
| 450 | } |
| 451 | }); |
| 452 | } |
| 453 | tracing::info!("AI bridge listener stopped"); |
| 454 | } |
| 455 | |
| 456 | |
| 457 | |
| 458 | async fn serve_connection(inner: Arc<Inner>, conn: quinn::Connection) { |
| 459 | let handshake = tokio::time::timeout( |
| 460 | Duration::from_secs(AI_HANDSHAKE_TIMEOUT_SECS), |
| 461 | register(&inner, &conn), |
| 462 | ) |
| 463 | .await; |
| 464 | |
| 465 | let (worker_id, service, capabilities, _control) = match handshake { |
| 466 | Ok(Ok(registered)) => registered, |
| 467 | Ok(Err(())) => return, |
| 468 | Err(_) => { |
| 469 | handshake_failed(inner.metrics(), "timeout"); |
| 470 | tracing::warn!("an AI service did not complete its handshake in time"); |
| 471 | conn.close(2u32.into(), b"handshake timeout"); |
| 472 | return; |
| 473 | } |
| 474 | }; |
| 475 | |
| 476 | |
| 477 | |
| 478 | if crate::ai::rag::should_replay_index(&capabilities) { |
| 479 | spawn_index_replay_if_armed(&inner); |
| 480 | } |
| 481 | |
| 482 | |
| 483 | |
| 484 | |
| 485 | |
| 486 | |
| 487 | |
| 488 | |
| 489 | |
| 490 | let reason = loop { |
| 491 | tokio::select! { |
| 492 | reason = conn.closed() => break reason, |
| 493 | accepted = conn.accept_bi() => match accepted { |
| 494 | Ok((send, recv)) => { |
| 495 | tokio::spawn(serve_client_stream(Arc::clone(&inner), send, recv)); |
| 496 | } |
| 497 | |
| 498 | Err(_) => break conn.closed().await, |
| 499 | }, |
| 500 | } |
| 501 | }; |
| 502 | inner.registry.remove(&worker_id); |
| 503 | inner.record_worker_count(); |
| 504 | tracing::info!( |
| 505 | "worker.id" = %worker_id, |
| 506 | service = %service, |
| 507 | reason = %reason, |
| 508 | "AI service disconnected" |
| 509 | ); |
| 510 | } |
| 511 | |
| 512 | |
| 513 | |
| 514 | |
| 515 | |
| 516 | async fn serve_client_stream( |
| 517 | inner: Arc<Inner>, |
| 518 | mut send: quinn::SendStream, |
| 519 | mut recv: quinn::RecvStream, |
| 520 | ) { |
| 521 | |
| 522 | |
| 523 | |
| 524 | let raw: Value = match read_frame(&mut recv).await { |
| 525 | Ok(raw) => raw, |
| 526 | Err(e) => { |
| 527 | answer( |
| 528 | &mut send, |
| 529 | refusal(String::new(), String::new(), "malformed", e.to_string()), |
| 530 | ) |
| 531 | .await; |
| 532 | return; |
| 533 | } |
| 534 | }; |
| 535 | let id = string_field(&raw, "id"); |
| 536 | |
| 537 | |
| 538 | let school = string_field(&raw, "school"); |
| 539 | |
| 540 | |
| 541 | |
| 542 | if raw.get("path").is_some() { |
| 543 | let response = match serde_json::from_value::<ApiRequest>(raw) { |
| 544 | Ok(request) => match read_api(&inner, request).await { |
| 545 | Ok(response) => response, |
| 546 | Err((code, message)) => refusal(id, school, code, message), |
| 547 | }, |
| 548 | Err(e) => refusal(id, school, "malformed", e.to_string()), |
| 549 | }; |
| 550 | answer(&mut send, response).await; |
| 551 | return; |
| 552 | } |
| 553 | if raw.get("file").is_some() { |
| 554 | match serde_json::from_value::<BlobRequest>(raw) { |
| 555 | Ok(request) => serve_blob(&inner, &mut send, request).await, |
| 556 | Err(e) => answer(&mut send, refusal(id, school, "malformed", e.to_string())).await, |
| 557 | } |
| 558 | return; |
| 559 | } |
| 560 | |
| 561 | |
| 562 | |
| 563 | if raw.get("capability").is_some() { |
| 564 | match serde_json::from_value::<CapabilityRequest>(raw) { |
| 565 | Ok(request) => { |
| 566 | let response = serve_capability(&inner, request).await; |
| 567 | answer_capability(&mut send, response).await; |
| 568 | } |
| 569 | Err(e) => { |
| 570 | answer_capability( |
| 571 | &mut send, |
| 572 | capability_refusal(&id, &school, "malformed", e.to_string()), |
| 573 | ) |
| 574 | .await; |
| 575 | } |
| 576 | } |
| 577 | return; |
| 578 | } |
| 579 | |
| 580 | |
| 581 | |
| 582 | |
| 583 | if raw.get("upload").is_some() { |
| 584 | match serde_json::from_value::<BlobUploadRequest>(raw) { |
| 585 | Ok(request) => serve_upload(&inner, &mut send, recv, request).await, |
| 586 | Err(e) => { |
| 587 | let refused = upload_refusal(id, school, "malformed", e.to_string()); |
| 588 | if let Err(e) = write_frame(&mut send, &refused).await { |
| 589 | tracing::warn!("could not refuse an AI service's malformed upload: {e}"); |
| 590 | } |
| 591 | let _ = send.finish(); |
| 592 | } |
| 593 | } |
| 594 | return; |
| 595 | } |
| 596 | |
| 597 | |
| 598 | let api_err = serde_json::from_value::<ApiRequest>(raw) |
| 599 | .err() |
| 600 | .map_or_else(String::new, |e| e.to_string()); |
| 601 | answer(&mut send, refusal(id, school, "malformed", api_err)).await; |
| 602 | } |
| 603 | |
| 604 | |
| 605 | |
| 606 | fn string_field(raw: &Value, name: &str) -> String { |
| 607 | raw.get(name) |
| 608 | .and_then(Value::as_str) |
| 609 | .unwrap_or_default() |
| 610 | .to_string() |
| 611 | } |
| 612 | |
| 613 | |
| 614 | |
| 615 | |
| 616 | |
| 617 | |
| 618 | |
| 619 | async fn serve_blob(inner: &Inner, send: &mut quinn::SendStream, request: BlobRequest) { |
| 620 | let id = request.id.clone(); |
| 621 | let school = request.school.clone(); |
| 622 | match open_blob(inner, request).await { |
| 623 | Ok((header, mut file)) => { |
| 624 | if let Err(e) = write_frame(send, &header).await { |
| 625 | tracing::warn!("could not answer an AI service's blob read {id}: {e}"); |
| 626 | } else if let Err(e) = write_blob_body(&mut file, send).await { |
| 627 | |
| 628 | |
| 629 | |
| 630 | tracing::warn!("blob read {id} failed after its header: {e}"); |
| 631 | let _ = send.reset(1u32.into()); |
| 632 | return; |
| 633 | } |
| 634 | } |
| 635 | Err((code, message)) => { |
| 636 | let refused = BlobResponse::Err { |
| 637 | id, |
| 638 | school, |
| 639 | code: code.to_string(), |
| 640 | message, |
| 641 | }; |
| 642 | if let Err(e) = write_frame(send, &refused).await { |
| 643 | tracing::warn!("could not refuse an AI service's blob read: {e}"); |
| 644 | } |
| 645 | } |
| 646 | } |
| 647 | let _ = send.finish(); |
| 648 | } |
| 649 | |
| 650 | |
| 651 | |
| 652 | |
| 653 | |
| 654 | |
| 655 | |
| 656 | |
| 657 | async fn write_blob_body( |
| 658 | file: &mut tokio::fs::File, |
| 659 | send: &mut quinn::SendStream, |
| 660 | ) -> std::io::Result<()> { |
| 661 | let mut buf = [0u8; 64 * 1024]; |
| 662 | loop { |
| 663 | let n = tokio::io::AsyncReadExt::read(file, &mut buf).await?; |
| 664 | if n == 0 { |
| 665 | return Ok(()); |
| 666 | } |
| 667 | tokio::time::timeout( |
| 668 | Duration::from_secs(AI_BLOB_WRITE_STALL_SECS), |
| 669 | send.write_all(&buf[..n]), |
| 670 | ) |
| 671 | .await |
| 672 | .map_err(|_| { |
| 673 | std::io::Error::new( |
| 674 | std::io::ErrorKind::TimedOut, |
| 675 | format!("no progress for {AI_BLOB_WRITE_STALL_SECS}s"), |
| 676 | ) |
| 677 | })??; |
| 678 | } |
| 679 | } |
| 680 | |
| 681 | |
| 682 | |
| 683 | |
| 684 | |
| 685 | |
| 686 | |
| 687 | |
| 688 | |
| 689 | |
| 690 | async fn serve_upload( |
| 691 | inner: &Inner, |
| 692 | send: &mut quinn::SendStream, |
| 693 | mut recv: quinn::RecvStream, |
| 694 | request: BlobUploadRequest, |
| 695 | ) { |
| 696 | let id = request.id.clone(); |
| 697 | let school = request.school.clone(); |
| 698 | let response = match ingest_upload(inner, &request, &mut recv).await { |
| 699 | Ok((key, size)) => BlobUploadResponse::Ok { |
| 700 | id, |
| 701 | school, |
| 702 | key, |
| 703 | size, |
| 704 | }, |
| 705 | Err((code, message)) => { |
| 706 | |
| 707 | |
| 708 | |
| 709 | let _ = recv.stop(1u32.into()); |
| 710 | upload_refusal(request.id.clone(), request.school.clone(), code, message) |
| 711 | } |
| 712 | }; |
| 713 | if let Err(e) = write_frame(send, &response).await { |
| 714 | tracing::warn!("could not answer an AI service's blob upload {}: {e}", request.id); |
| 715 | } |
| 716 | let _ = send.finish(); |
| 717 | } |
| 718 | |
| 719 | |
| 720 | |
| 721 | |
| 722 | |
| 723 | |
| 724 | |
| 725 | |
| 726 | |
| 727 | |
| 728 | async fn ingest_upload( |
| 729 | inner: &Inner, |
| 730 | request: &BlobUploadRequest, |
| 731 | body: &mut quinn::RecvStream, |
| 732 | ) -> Result<(String, u64), (&'static str, String)> { |
| 733 | if !request.upload { |
| 734 | return Err(( |
| 735 | "malformed", |
| 736 | "`upload` must be true on a blob upload".to_string(), |
| 737 | )); |
| 738 | } |
| 739 | let api = inner.api.get().ok_or(( |
| 740 | "unavailable", |
| 741 | "the api is not serving yet — retry".to_string(), |
| 742 | ))?; |
| 743 | let tenant = api.school(&request.school).await?; |
| 744 | let (school, db) = (tenant.id, tenant.db); |
| 745 | |
| 746 | |
| 747 | |
| 748 | if !tenant.modules.contains(Module::Chatbot) { |
| 749 | return Err(( |
| 750 | "not_permitted", |
| 751 | format!("the `{school}` school has no `chatbot` module"), |
| 752 | )); |
| 753 | } |
| 754 | let refusal = crate::ai::podcast::refusal; |
| 755 | let root = api.files_dir(&school); |
| 756 | let (key, size) = crate::ai::podcast::ingest(&db, &root, request, body) |
| 757 | .await |
| 758 | .map_err(|r| refusal(&r))?; |
| 759 | Ok((key, size)) |
| 760 | } |
| 761 | |
| 762 | |
| 763 | fn upload_refusal( |
| 764 | id: String, |
| 765 | school: String, |
| 766 | code: &str, |
| 767 | message: String, |
| 768 | ) -> BlobUploadResponse { |
| 769 | BlobUploadResponse::Err { |
| 770 | id, |
| 771 | school, |
| 772 | code: code.to_string(), |
| 773 | message, |
| 774 | } |
| 775 | } |
| 776 | |
| 777 | |
| 778 | |
| 779 | |
| 780 | |
| 781 | |
| 782 | |
| 783 | |
| 784 | |
| 785 | async fn open_blob( |
| 786 | inner: &Inner, |
| 787 | request: BlobRequest, |
| 788 | ) -> Result<(BlobResponse, tokio::fs::File), (&'static str, String)> { |
| 789 | let api = inner.api.get().ok_or(( |
| 790 | "unavailable", |
| 791 | "the api is not serving yet — retry".to_string(), |
| 792 | ))?; |
| 793 | let tenant = api.school(&request.school).await?; |
| 794 | let (school, db) = (tenant.id, tenant.db); |
| 795 | |
| 796 | |
| 797 | |
| 798 | |
| 799 | for module in [Module::CourseNotes, Module::Chatbot] { |
| 800 | if !tenant.modules.contains(module) { |
| 801 | return Err(( |
| 802 | "module_disabled", |
| 803 | format!("the `{school}` school has no `{module}` module"), |
| 804 | )); |
| 805 | } |
| 806 | } |
| 807 | let user = principal(&db, request.on_behalf_of.as_deref()).await?; |
| 808 | |
| 809 | let missing = || { |
| 810 | ( |
| 811 | "not_found", |
| 812 | format!("no course note file `{}`", request.file), |
| 813 | ) |
| 814 | }; |
| 815 | let unavailable = |e: crate::error::AppError| ("unavailable", e.to_string()); |
| 816 | let file = crate::db::course_note_file::read(&db, &CourseNoteFileId::from_key(&request.file)) |
| 817 | .await |
| 818 | .map_err(unavailable)? |
| 819 | .ok_or_else(missing)?; |
| 820 | let note = crate::db::course_note::read(&db, file.get_course_note()) |
| 821 | .await |
| 822 | .map_err(unavailable)? |
| 823 | .ok_or_else(missing)?; |
| 824 | let course = crate::service::course::read(&db, note.get_course()) |
| 825 | .await |
| 826 | .map_err(unavailable)? |
| 827 | .ok_or_else(missing)?; |
| 828 | if !can_view_course(&course, &user, &db) |
| 829 | .await |
| 830 | .map_err(unavailable)? |
| 831 | { |
| 832 | return Err(( |
| 833 | "forbidden", |
| 834 | format!( |
| 835 | "`{}` may not view the course this file belongs to", |
| 836 | user.get_id().key() |
| 837 | ), |
| 838 | )); |
| 839 | } |
| 840 | |
| 841 | |
| 842 | |
| 843 | let path = blob_path(&api.files_dir(&school), &file.get_id().key()); |
| 844 | let handle = tokio::fs::File::open(&path).await.map_err(|e| { |
| 845 | ( |
| 846 | "unavailable", |
| 847 | format!( |
| 848 | "missing blob for course note file {}: {e}", |
| 849 | file.get_id().key() |
| 850 | ), |
| 851 | ) |
| 852 | })?; |
| 853 | |
| 854 | |
| 855 | |
| 856 | let size = handle |
| 857 | .metadata() |
| 858 | .await |
| 859 | .map_err(|e| ("unavailable", format!("could not stat the blob: {e}")))? |
| 860 | .len(); |
| 861 | Ok(( |
| 862 | BlobResponse::Ok { |
| 863 | id: request.id, |
| 864 | school: request.school, |
| 865 | name: file.get_name().as_str().to_string(), |
| 866 | content_type: file.get_content_type().as_str().to_string(), |
| 867 | size, |
| 868 | }, |
| 869 | handle, |
| 870 | )) |
| 871 | } |
| 872 | |
| 873 | |
| 874 | |
| 875 | |
| 876 | |
| 877 | |
| 878 | |
| 879 | async fn principal( |
| 880 | db: &Database, |
| 881 | on_behalf_of: Option<&str>, |
| 882 | ) -> Result<User, (&'static str, String)> { |
| 883 | let Some(who) = on_behalf_of else { |
| 884 | return Ok(User::ai_principal()); |
| 885 | }; |
| 886 | |
| 887 | |
| 888 | let key = who.strip_prefix("user:").unwrap_or(who); |
| 889 | crate::db::user::read(db, &UserId::from_key(key)) |
| 890 | .await |
| 891 | .map_err(|e| ("unavailable", format!("could not load `{who}`: {e}")))? |
| 892 | .ok_or_else(|| ("unknown_user", format!("no user `{who}`"))) |
| 893 | } |
| 894 | |
| 895 | |
| 896 | |
| 897 | |
| 898 | fn refuse_before_dispatch(method: Option<&str>, path: &str) -> Option<(&'static str, String)> { |
| 899 | match method { |
| 900 | None | Some("GET") => {} |
| 901 | Some(other) => { |
| 902 | return Some(( |
| 903 | "method_not_allowed", |
| 904 | format!("the api bridge reads only — `{other}` is never dispatched"), |
| 905 | )); |
| 906 | } |
| 907 | } |
| 908 | if !crate::ai::api::path_allowed(path) { |
| 909 | return Some(( |
| 910 | "path_not_allowed", |
| 911 | format!("`{path}` is not a path AI services may read"), |
| 912 | )); |
| 913 | } |
| 914 | None |
| 915 | } |
| 916 | |
| 917 | |
| 918 | |
| 919 | |
| 920 | |
| 921 | |
| 922 | |
| 923 | async fn read_api( |
| 924 | inner: &Inner, |
| 925 | request: ApiRequest, |
| 926 | ) -> Result<ApiResponse, (&'static str, String)> { |
| 927 | if let Some(refusal) = refuse_before_dispatch(request.method.as_deref(), &request.path) { |
| 928 | return Err(refusal); |
| 929 | } |
| 930 | |
| 931 | |
| 932 | |
| 933 | let api = inner.api.get().ok_or(( |
| 934 | "unavailable", |
| 935 | "the api is not serving yet — retry".to_string(), |
| 936 | ))?; |
| 937 | dispatch_api(api, inner.metrics(), request).await |
| 938 | } |
| 939 | |
| 940 | |
| 941 | |
| 942 | |
| 943 | |
| 944 | async fn dispatch_api( |
| 945 | api: &ApiHandle, |
| 946 | metrics: &Metrics, |
| 947 | request: ApiRequest, |
| 948 | ) -> Result<ApiResponse, (&'static str, String)> { |
| 949 | let ApiRequest { |
| 950 | id, |
| 951 | school, |
| 952 | path, |
| 953 | query, |
| 954 | on_behalf_of, |
| 955 | .. |
| 956 | } = request; |
| 957 | |
| 958 | |
| 959 | |
| 960 | |
| 961 | let tenant = api.school(&school).await?; |
| 962 | let db = tenant.db.clone(); |
| 963 | |
| 964 | |
| 965 | let user = principal(&db, on_behalf_of.as_deref()).await?; |
| 966 | |
| 967 | let target = match query.as_deref() { |
| 968 | Some(query) if !query.is_empty() => format!("{path}?{query}"), |
| 969 | _ => path.clone(), |
| 970 | }; |
| 971 | let mut dispatched = axum::http::Request::builder() |
| 972 | .method(axum::http::Method::GET) |
| 973 | .uri(&target) |
| 974 | .body(axum::body::Body::empty()) |
| 975 | .map_err(|e| { |
| 976 | ( |
| 977 | "malformed", |
| 978 | format!("`{target}` is not a request target: {e}"), |
| 979 | ) |
| 980 | })?; |
| 981 | |
| 982 | |
| 983 | dispatched.extensions_mut().insert(AiPrincipal(user)); |
| 984 | |
| 985 | |
| 986 | |
| 987 | |
| 988 | dispatched.extensions_mut().insert(TenantExt { |
| 989 | id: tenant.id, |
| 990 | db, |
| 991 | modules: tenant.modules, |
| 992 | }); |
| 993 | |
| 994 | |
| 995 | |
| 996 | |
| 997 | |
| 998 | let route = crate::ai::api::route_template(&path).unwrap_or("unmatched"); |
| 999 | let otel_name = format!("GET {route}"); |
| 1000 | let span = tracing::info_span!( |
| 1001 | "http.request", |
| 1002 | otel.name = %otel_name, |
| 1003 | "http.request.method" = "GET", |
| 1004 | "http.route" = route, |
| 1005 | school = school.as_str(), |
| 1006 | "ai.origin" = true, |
| 1007 | "http.response.status_code" = tracing::field::Empty, |
| 1008 | ); |
| 1009 | metrics.request_started("GET"); |
| 1010 | let started = Instant::now(); |
| 1011 | |
| 1012 | let response = tokio::time::timeout( |
| 1013 | Duration::from_secs(REQUEST_TIMEOUT_SECS), |
| 1014 | api.router.clone().oneshot(dispatched), |
| 1015 | ) |
| 1016 | .instrument(span.clone()) |
| 1017 | .await |
| 1018 | .map_err(|_| { |
| 1019 | metrics.request_finished("GET", route, 504, Some(&school), started.elapsed()); |
| 1020 | ( |
| 1021 | "unavailable", |
| 1022 | format!("`{target}` did not answer within {REQUEST_TIMEOUT_SECS}s"), |
| 1023 | ) |
| 1024 | })? |
| 1025 | .expect("an axum router is infallible"); |
| 1026 | |
| 1027 | let status = response.status().as_u16(); |
| 1028 | |
| 1029 | |
| 1030 | metrics.request_finished("GET", route, status, Some(&school), started.elapsed()); |
| 1031 | span.record("http.response.status_code", i64::from(status)); |
| 1032 | let body = axum::body::to_bytes(response.into_body(), AI_MAX_FRAME_BYTES) |
| 1033 | .await |
| 1034 | .map_err(|e| { |
| 1035 | ( |
| 1036 | "too_large", |
| 1037 | format!("the answer to `{target}` does not fit a frame: {e}"), |
| 1038 | ) |
| 1039 | })?; |
| 1040 | let body = if body.is_empty() { |
| 1041 | |
| 1042 | Value::Null |
| 1043 | } else { |
| 1044 | serde_json::from_slice(&body).map_err(|e| { |
| 1045 | ( |
| 1046 | "not_json", |
| 1047 | format!("`{target}` answered with a body that is not JSON: {e}"), |
| 1048 | ) |
| 1049 | })? |
| 1050 | }; |
| 1051 | |
| 1052 | Ok(ApiResponse::Ok { |
| 1053 | id, |
| 1054 | school, |
| 1055 | status, |
| 1056 | body, |
| 1057 | }) |
| 1058 | } |
| 1059 | |
| 1060 | fn refusal(id: String, school: String, code: &str, message: String) -> ApiResponse { |
| 1061 | ApiResponse::Err { |
| 1062 | id, |
| 1063 | school, |
| 1064 | code: code.to_string(), |
| 1065 | message, |
| 1066 | } |
| 1067 | } |
| 1068 | |
| 1069 | |
| 1070 | |
| 1071 | |
| 1072 | |
| 1073 | |
| 1074 | async fn answer(send: &mut quinn::SendStream, response: ApiResponse) { |
| 1075 | if let Err(e) = write_answer(send, &response).await { |
| 1076 | tracing::warn!("could not answer an AI service's api read: {e}"); |
| 1077 | } |
| 1078 | let _ = send.finish(); |
| 1079 | } |
| 1080 | |
| 1081 | |
| 1082 | |
| 1083 | |
| 1084 | |
| 1085 | async fn write_answer<W: tokio::io::AsyncWrite + Unpin>( |
| 1086 | w: &mut W, |
| 1087 | response: &ApiResponse, |
| 1088 | ) -> Result<(), FrameError> { |
| 1089 | let written = write_frame(w, response).await; |
| 1090 | if let (Err(FrameError::TooLarge(_)), ApiResponse::Ok { id, school, .. }) = (&written, response) |
| 1091 | { |
| 1092 | return write_frame( |
| 1093 | w, |
| 1094 | &refusal( |
| 1095 | id.clone(), |
| 1096 | school.clone(), |
| 1097 | "too_large", |
| 1098 | format!("the answer exceeds the {AI_MAX_FRAME_BYTES}-byte frame limit"), |
| 1099 | ), |
| 1100 | ) |
| 1101 | .await; |
| 1102 | } |
| 1103 | written |
| 1104 | } |
| 1105 | |
| 1106 | |
| 1107 | |
| 1108 | |
| 1109 | |
| 1110 | |
| 1111 | |
| 1112 | |
| 1113 | |
| 1114 | |
| 1115 | async fn serve_capability(inner: &Inner, request: CapabilityRequest) -> CapabilityResponse { |
| 1116 | |
| 1117 | |
| 1118 | |
| 1119 | |
| 1120 | use crate::ai::capability::{self, Scope}; |
| 1121 | |
| 1122 | let Some(api) = inner.api.get() else { |
| 1123 | return capability_refusal( |
| 1124 | &request.id, |
| 1125 | &request.school, |
| 1126 | "unavailable", |
| 1127 | "this process has no api surface to run capabilities against".to_string(), |
| 1128 | ); |
| 1129 | }; |
| 1130 | let tenant = match capability::scope_of(&request.capability) { |
| 1131 | Some(Scope::Deployment) => None, |
| 1132 | Some(Scope::School) => match api.school(&request.school).await { |
| 1133 | Ok(tenant) => Some(tenant), |
| 1134 | Err((code, message)) => { |
| 1135 | return capability_refusal(&request.id, &request.school, code, message); |
| 1136 | } |
| 1137 | }, |
| 1138 | None => { |
| 1139 | return capability_refusal( |
| 1140 | &request.id, |
| 1141 | &request.school, |
| 1142 | "unknown_capability", |
| 1143 | format!("the backend serves no `{}` operation", request.capability), |
| 1144 | ); |
| 1145 | } |
| 1146 | }; |
| 1147 | let control = api.tenants.control(); |
| 1148 | let call = capability::serve( |
| 1149 | &request.capability, |
| 1150 | tenant.as_ref(), |
| 1151 | control, |
| 1152 | &request.payload, |
| 1153 | ); |
| 1154 | match tokio::time::timeout(inner.request_timeout, call).await { |
| 1155 | Ok(Ok(payload)) => CapabilityResponse::Ok { |
| 1156 | id: request.id, |
| 1157 | school: request.school, |
| 1158 | payload, |
| 1159 | }, |
| 1160 | Ok(Err((code, message))) => { |
| 1161 | capability_refusal(&request.id, &request.school, code, message) |
| 1162 | } |
| 1163 | Err(_) => capability_refusal( |
| 1164 | &request.id, |
| 1165 | &request.school, |
| 1166 | "timed_out", |
| 1167 | format!( |
| 1168 | "the operation did not finish within {}s", |
| 1169 | inner.request_timeout.as_secs() |
| 1170 | ), |
| 1171 | ), |
| 1172 | } |
| 1173 | } |
| 1174 | |
| 1175 | |
| 1176 | fn capability_refusal( |
| 1177 | id: &str, |
| 1178 | school: &str, |
| 1179 | code: &str, |
| 1180 | message: String, |
| 1181 | ) -> CapabilityResponse { |
| 1182 | CapabilityResponse::Err { |
| 1183 | id: id.to_string(), |
| 1184 | school: school.to_string(), |
| 1185 | code: code.to_string(), |
| 1186 | message, |
| 1187 | } |
| 1188 | } |
| 1189 | |
| 1190 | async fn answer_capability(send: &mut quinn::SendStream, response: CapabilityResponse) { |
| 1191 | if let Err(e) = write_capability_answer(send, &response).await { |
| 1192 | tracing::warn!("could not answer an AI service's capability call: {e}"); |
| 1193 | } |
| 1194 | let _ = send.finish(); |
| 1195 | } |
| 1196 | |
| 1197 | |
| 1198 | |
| 1199 | |
| 1200 | |
| 1201 | async fn write_capability_answer<W: tokio::io::AsyncWrite + Unpin>( |
| 1202 | w: &mut W, |
| 1203 | response: &CapabilityResponse, |
| 1204 | ) -> Result<(), FrameError> { |
| 1205 | let written = write_frame(w, response).await; |
| 1206 | if let (Err(FrameError::TooLarge(_)), CapabilityResponse::Ok { id, school, .. }) = |
| 1207 | (&written, response) |
| 1208 | { |
| 1209 | return write_frame( |
| 1210 | w, |
| 1211 | &capability_refusal( |
| 1212 | id, |
| 1213 | school, |
| 1214 | "too_large", |
| 1215 | format!("the answer exceeds the {AI_MAX_FRAME_BYTES}-byte frame limit"), |
| 1216 | ), |
| 1217 | ) |
| 1218 | .await; |
| 1219 | } |
| 1220 | written |
| 1221 | } |
| 1222 | |
| 1223 | |
| 1224 | |
| 1225 | |
| 1226 | |
| 1227 | type Control = (quinn::SendStream, quinn::RecvStream); |
| 1228 | async fn register( |
| 1229 | inner: &Inner, |
| 1230 | conn: &quinn::Connection, |
| 1231 | ) -> Result<(String, String, Vec<String>, Control), ()> { |
| 1232 | let (mut send, mut recv) = match conn.accept_bi().await { |
| 1233 | Ok(streams) => streams, |
| 1234 | Err(e) => { |
| 1235 | handshake_failed(inner.metrics(), "no_control_stream"); |
| 1236 | tracing::warn!(error = %e, "an AI service opened no control stream"); |
| 1237 | return Err(()); |
| 1238 | } |
| 1239 | }; |
| 1240 | |
| 1241 | let hello: Hello = match read_frame(&mut recv).await { |
| 1242 | Ok(hello) => hello, |
| 1243 | Err(e) => { |
| 1244 | handshake_failed(inner.metrics(), "malformed_hello"); |
| 1245 | tracing::warn!(error = %e, "an AI service sent an unreadable Hello"); |
| 1246 | refuse(&mut send, conn, RejectCode::Malformed, &e.to_string()).await; |
| 1247 | return Err(()); |
| 1248 | } |
| 1249 | }; |
| 1250 | |
| 1251 | if !protocol_matches(&hello) { |
| 1252 | let message = format!( |
| 1253 | "this backend speaks {AI_PROTOCOL}, the service announced {}", |
| 1254 | hello.protocol |
| 1255 | ); |
| 1256 | handshake_failed(inner.metrics(), "bad_version"); |
| 1257 | tracing::warn!(service = %hello.service, reason = "bad_version", "AI service rejected: {message}"); |
| 1258 | refuse(&mut send, conn, RejectCode::UnsupportedProtocol, &message).await; |
| 1259 | return Err(()); |
| 1260 | } |
| 1261 | if !constant_time_eq(hello.token.as_bytes(), inner.token.as_bytes()) { |
| 1262 | handshake_failed(inner.metrics(), "bad_token"); |
| 1263 | tracing::warn!( |
| 1264 | service = %hello.service, |
| 1265 | reason = "bad_token", |
| 1266 | "AI service rejected: bad shared token" |
| 1267 | ); |
| 1268 | refuse(&mut send, conn, RejectCode::Unauthorized, "invalid token").await; |
| 1269 | return Err(()); |
| 1270 | } |
| 1271 | if hello.capabilities.is_empty() { |
| 1272 | handshake_failed(inner.metrics(), "bad_capabilities"); |
| 1273 | tracing::warn!( |
| 1274 | service = %hello.service, |
| 1275 | reason = "bad_capabilities", |
| 1276 | "AI service rejected: declared no capabilities" |
| 1277 | ); |
| 1278 | refuse( |
| 1279 | &mut send, |
| 1280 | conn, |
| 1281 | RejectCode::NoCapabilities, |
| 1282 | "declare at least one capability", |
| 1283 | ) |
| 1284 | .await; |
| 1285 | return Err(()); |
| 1286 | } |
| 1287 | |
| 1288 | let worker_id = next_uuid().to_string(); |
| 1289 | let max_concurrent = clamp_concurrency(hello.max_concurrent); |
| 1290 | let greeting = Greeting::Welcome { |
| 1291 | worker_id: worker_id.clone(), |
| 1292 | protocol: AI_PROTOCOL.to_string(), |
| 1293 | }; |
| 1294 | if let Err(e) = write_frame(&mut send, &greeting).await { |
| 1295 | handshake_failed(inner.metrics(), "welcome_failed"); |
| 1296 | tracing::warn!(service = %hello.service, error = %e, "could not welcome an AI service"); |
| 1297 | return Err(()); |
| 1298 | } |
| 1299 | |
| 1300 | |
| 1301 | |
| 1302 | inner.registry.insert( |
| 1303 | worker_id.clone(), |
| 1304 | hello.service.clone(), |
| 1305 | hello.capabilities.clone(), |
| 1306 | max_concurrent, |
| 1307 | conn.clone(), |
| 1308 | ); |
| 1309 | inner.record_worker_count(); |
| 1310 | tracing::info!( |
| 1311 | "worker.id" = %worker_id, |
| 1312 | service = %hello.service, |
| 1313 | capabilities = hello.capabilities.len(), |
| 1314 | max_concurrent, |
| 1315 | "AI service registered" |
| 1316 | ); |
| 1317 | Ok((worker_id, hello.service, hello.capabilities, (send, recv))) |
| 1318 | } |
| 1319 | |
| 1320 | |
| 1321 | |
| 1322 | async fn refuse( |
| 1323 | send: &mut quinn::SendStream, |
| 1324 | conn: &quinn::Connection, |
| 1325 | code: RejectCode, |
| 1326 | message: &str, |
| 1327 | ) { |
| 1328 | let greeting = Greeting::Rejected { |
| 1329 | code, |
| 1330 | message: message.to_string(), |
| 1331 | }; |
| 1332 | let _ = write_frame(send, &greeting).await; |
| 1333 | let _ = send.finish(); |
| 1334 | |
| 1335 | |
| 1336 | let _ = tokio::time::timeout(Duration::from_millis(200), send.stopped()).await; |
| 1337 | conn.close(1u32.into(), message.as_bytes()); |
| 1338 | } |
| 1339 | |
| 1340 | |
| 1341 | |
| 1342 | |
| 1343 | |
| 1344 | |
| 1345 | fn spawn_index_replay_if_armed(inner: &Arc<Inner>) { |
| 1346 | let Some(mut state) = inner.replay.get().cloned() else { |
| 1347 | tracing::warn!( |
| 1348 | "rag.index worker registered before replay state was armed; skipping index replay" |
| 1349 | ); |
| 1350 | return; |
| 1351 | }; |
| 1352 | state.ai = Some(AiBridge { |
| 1353 | inner: Arc::clone(inner), |
| 1354 | }); |
| 1355 | crate::ai::rag::spawn_index_replay(state); |
| 1356 | } |
| 1357 | |
| 1358 | |
| 1359 | |
| 1360 | |
| 1361 | fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { |
| 1362 | if a.len() != b.len() { |
| 1363 | return false; |
| 1364 | } |
| 1365 | a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 |
| 1366 | } |
| 1367 | |
| 1368 | |
| 1369 | |
| 1370 | |
| 1371 | |
| 1372 | |
| 1373 | |
| 1374 | struct InFlight<'a> { |
| 1375 | metrics: &'a Metrics, |
| 1376 | attrs: &'a [KeyValue], |
| 1377 | } |
| 1378 | |
| 1379 | impl<'a> InFlight<'a> { |
| 1380 | fn started(metrics: &'a Metrics, attrs: &'a [KeyValue]) -> Self { |
| 1381 | metrics.ai_requests_inflight.add(1, attrs); |
| 1382 | Self { metrics, attrs } |
| 1383 | } |
| 1384 | } |
| 1385 | |
| 1386 | impl Drop for InFlight<'_> { |
| 1387 | fn drop(&mut self) { |
| 1388 | self.metrics.ai_requests_inflight.add(-1, self.attrs); |
| 1389 | } |
| 1390 | } |
| 1391 | |
| 1392 | #[cfg(test)] |
| 1393 | mod tests { |
| 1394 | use axum::routing::get; |
| 1395 | |
| 1396 | use super::{ |
| 1397 | AI_MAX_FRAME_BYTES, ApiHandle, ApiRequest, ApiResponse, Metrics, constant_time_eq, |
| 1398 | refuse_before_dispatch, |
| 1399 | }; |
| 1400 | use crate::ai::protocol::read_frame; |
| 1401 | use crate::tenant::DEMO_SCHOOL_ID; |
| 1402 | |
| 1403 | |
| 1404 | |
| 1405 | |
| 1406 | async fn armed(router: axum::Router) -> ApiHandle { |
| 1407 | ApiHandle { |
| 1408 | router, |
| 1409 | tenants: crate::database::init_test_tenants().await, |
| 1410 | files_path: std::env::temp_dir(), |
| 1411 | } |
| 1412 | } |
| 1413 | |
| 1414 | |
| 1415 | fn read_of(path: &str) -> ApiRequest { |
| 1416 | ApiRequest { |
| 1417 | id: "trace-1".to_string(), |
| 1418 | school: DEMO_SCHOOL_ID.to_string(), |
| 1419 | path: path.to_string(), |
| 1420 | query: None, |
| 1421 | on_behalf_of: None, |
| 1422 | method: None, |
| 1423 | } |
| 1424 | } |
| 1425 | |
| 1426 | |
| 1427 | fn refused(answer: Result<ApiResponse, (&'static str, String)>) -> &'static str { |
| 1428 | match answer { |
| 1429 | Err((code, _)) => code, |
| 1430 | Ok(other) => panic!("expected a refusal, got {other:?}"), |
| 1431 | } |
| 1432 | } |
| 1433 | |
| 1434 | #[tokio::test] |
| 1435 | async fn a_body_that_is_not_json_is_refused_as_not_json() { |
| 1436 | |
| 1437 | |
| 1438 | |
| 1439 | let router = axum::Router::new().route("/notes", get(|| async { "plain text" })); |
| 1440 | let api = armed(router).await; |
| 1441 | assert_eq!( |
| 1442 | refused(super::dispatch_api(&api, &Metrics::noop(), read_of("/notes")).await), |
| 1443 | "not_json" |
| 1444 | ); |
| 1445 | } |
| 1446 | |
| 1447 | #[tokio::test] |
| 1448 | async fn an_empty_body_is_a_null_answer_not_a_parse_failure() { |
| 1449 | |
| 1450 | |
| 1451 | let router = axum::Router::new().route( |
| 1452 | "/notes", |
| 1453 | get(|| async { axum::http::StatusCode::NO_CONTENT }), |
| 1454 | ); |
| 1455 | let api = armed(router).await; |
| 1456 | match super::dispatch_api(&api, &Metrics::noop(), read_of("/notes")).await { |
| 1457 | Ok(ApiResponse::Ok { status, body, .. }) => { |
| 1458 | assert_eq!(status, 204); |
| 1459 | assert_eq!(body, serde_json::Value::Null); |
| 1460 | } |
| 1461 | other => panic!("an empty body is an Ok answer: {other:?}"), |
| 1462 | } |
| 1463 | } |
| 1464 | |
| 1465 | #[tokio::test] |
| 1466 | async fn a_router_answer_over_the_frame_cap_is_refused_as_too_large() { |
| 1467 | |
| 1468 | |
| 1469 | let router = axum::Router::new().route( |
| 1470 | "/notes", |
| 1471 | get(|| async { "x".repeat(AI_MAX_FRAME_BYTES + 1) }), |
| 1472 | ); |
| 1473 | let api = armed(router).await; |
| 1474 | assert_eq!( |
| 1475 | refused(super::dispatch_api(&api, &Metrics::noop(), read_of("/notes")).await), |
| 1476 | "too_large" |
| 1477 | ); |
| 1478 | } |
| 1479 | |
| 1480 | #[tokio::test] |
| 1481 | async fn an_oversize_ok_is_downgraded_to_a_too_large_refusal() { |
| 1482 | |
| 1483 | |
| 1484 | |
| 1485 | |
| 1486 | |
| 1487 | let big = ApiResponse::Ok { |
| 1488 | id: "trace-1".to_string(), |
| 1489 | school: DEMO_SCHOOL_ID.to_string(), |
| 1490 | status: 200, |
| 1491 | body: serde_json::Value::String("x".repeat(AI_MAX_FRAME_BYTES)), |
| 1492 | }; |
| 1493 | let mut wire = Vec::new(); |
| 1494 | super::write_answer(&mut wire, &big) |
| 1495 | .await |
| 1496 | .expect("the downgrade is written"); |
| 1497 | |
| 1498 | let mut rest = &wire[..]; |
| 1499 | match read_frame::<_, ApiResponse>(&mut rest).await { |
| 1500 | Ok(ApiResponse::Err { id, code, .. }) => { |
| 1501 | assert_eq!(code, "too_large"); |
| 1502 | assert_eq!(id, "trace-1", "the trace id survives the downgrade"); |
| 1503 | } |
| 1504 | other => panic!("expected a too_large refusal on the wire: {other:?}"), |
| 1505 | } |
| 1506 | assert!( |
| 1507 | rest.is_empty(), |
| 1508 | "{} bytes of the oversize frame were written before the refusal", |
| 1509 | rest.len() |
| 1510 | ); |
| 1511 | } |
| 1512 | |
| 1513 | #[test] |
| 1514 | fn only_a_get_on_an_allowlisted_path_is_ever_dispatched() { |
| 1515 | |
| 1516 | assert!(refuse_before_dispatch(None, "/notes").is_none()); |
| 1517 | assert!(refuse_before_dispatch(Some("GET"), "/notes").is_none()); |
| 1518 | |
| 1519 | let code = |method, path| refuse_before_dispatch(method, path).map(|(code, _)| code); |
| 1520 | assert_eq!(code(Some("DELETE"), "/notes"), Some("method_not_allowed")); |
| 1521 | assert_eq!(code(Some("get"), "/notes"), Some("method_not_allowed")); |
| 1522 | assert_eq!(code(None, "/users"), Some("path_not_allowed")); |
| 1523 | |
| 1524 | |
| 1525 | assert_eq!(code(Some("POST"), "/nope"), Some("method_not_allowed")); |
| 1526 | } |
| 1527 | |
| 1528 | #[tokio::test] |
| 1529 | async fn token_comparison_matches_only_exact_secrets() { |
| 1530 | assert!(constant_time_eq(b"secret", b"secret")); |
| 1531 | assert!(!constant_time_eq(b"secret", b"secreT")); |
| 1532 | assert!(!constant_time_eq(b"secret", b"secre")); |
| 1533 | assert!(!constant_time_eq(b"secret", b"secrets")); |
| 1534 | assert!(constant_time_eq(b"", b"")); |
| 1535 | } |
| 1536 | } |