forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

server.rs1536 lines, 58.4 KiBHistoryRawDownload
1//! The QUIC listener AI services dial into, and the request path out to them.
2//!
3//! See [`super::protocol`] for the wire shape. The backend listens rather than
4//! dials so a service can sit behind NAT, restart without the backend needing
5//! to know its address, and scale out by opening a second connection.
6
7use std::net::SocketAddr;
8use std::sync::{Arc, OnceLock};
9use std::time::{Duration, Instant};
10
11use opentelemetry::KeyValue;
12use serde_json::Value;
13use tower::ServiceExt;
14use tracing::Instrument;
15
16use crate::ai::error::AiError;
17use 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};
22use crate::ai::registry::{AiRegistry, WorkerSnapshot, clamp_concurrency};
23use crate::ai::tls;
24use 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};
28use crate::database::Database;
29
30use crate::domain::course_note_file::CourseNoteFileId;
31use crate::domain::monotonic_id::next_uuid;
32use crate::domain::user::{User, UserId};
33use crate::error::AppError;
34use crate::module::Module;
35use crate::state::AppState;
36use crate::telemetry::Metrics;
37use crate::service::course::can_view_course;
38use crate::tenant::{ResolvedTenant, SchoolId, Tenants};
39use crate::web::blob_path;
40use crate::web::extractor::AiPrincipal;
41use crate::web::tenant_state::{TenantExt, school_files_path};
42
43/// What the bridge needs to come up.
44#[derive(Clone, Debug)]
45pub struct BridgeConfig {
46 /// UDP address to listen on (`AI_QUIC_ADDR`).
47 pub addr: SocketAddr,
48 /// Shared secret every service must present (`AI_SHARED_TOKEN`).
49 pub token: String,
50 /// PEM paths; both absent means a self-signed certificate is generated.
51 pub cert_path: Option<String>,
52 pub key_path: Option<String>,
53 /// How long one dispatch may take (`AI_REQUEST_TIMEOUT_SECS`).
54 pub request_timeout: Duration,
55}
56
57/// What an api read needs to be answered: the router to dispatch into and
58/// the registry every school is resolved through.
59///
60/// Deployment-wide, not per-school: `hab/2` frames name their own school, so
61/// one bridge (and one AI fleet) serves every school here.
62struct ApiHandle {
63 router: axum::Router,
64 tenants: Tenants,
65 /// Where uploaded blobs live — the deployment root; a school's own
66 /// directory is [`school_files_path`] of it.
67 files_path: std::path::PathBuf,
68}
69
70impl ApiHandle {
71 /// Resolve the school a frame named, or the refusal the service gets.
72 ///
73 /// A value that is not a hyphenated uuid is `unknown_school`, not
74 /// `malformed`: `malformed` stays the frame-shape error. `unknown_school`
75 /// means the deployment has no such customer, and `school_suspended`
76 /// means it has one that is switched off.
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 /// One school's blob directory.
104 fn files_dir(&self, id: &SchoolId) -> std::path::PathBuf {
105 school_files_path(&self.files_path, id)
106 }
107}
108
109struct Inner {
110 registry: AiRegistry,
111 /// Armed once per process by [`crate::build_router`] (see
112 /// [`AiBridge::arm_api`]). A `OnceLock` because the router is built after the
113 /// listener is bound and never replaced afterwards: writing it costs one
114 /// store at boot and reading it is lock-free on every api read.
115 api: OnceLock<ApiHandle>,
116 /// The leaf certificate this listener presents, kept so it can be shown to
117 /// an operator (or pinned by an in-process client) without re-reading the
118 /// PEM off disk.
119 certificate: rustls::pki_types::CertificateDer<'static>,
120 token: String,
121 request_timeout: Duration,
122 endpoint: quinn::Endpoint,
123 /// Filled by [`AiBridge::arm_api`], for the same reason `api` is: the
124 /// process's instruments are built with the router, after the listener is
125 /// bound.
126 metrics: OnceLock<Metrics>,
127 /// Root [`AppState`] with `ai` cleared, armed by [`AiBridge::arm_api`].
128 /// A `rag.index` registration replays the course-note index through it.
129 /// `ai` stays `None` here so this lock does not cycle back into the
130 /// bridge that holds it; the replay fills the bridge in on a clone.
131 replay: OnceLock<AppState>,
132}
133
134impl Inner {
135 /// The instruments to record into. A service that dials in during the boot
136 /// window gets the noop set, which — with no OTLP endpoint configured — is
137 /// exactly what the armed one is anyway.
138 fn metrics(&self) -> &Metrics {
139 self.metrics.get_or_init(Metrics::noop)
140 }
141
142 /// How many services are connected right now, as the gauge sees it.
143 fn record_worker_count(&self) {
144 self.metrics()
145 .ai_workers
146 .record(self.registry.snapshot().len() as u64, &[]);
147 }
148}
149
150/// Count one refused handshake. `reason` comes from a fixed vocabulary —
151/// never a message — so the metric's label cardinality stays bounded.
152fn handshake_failed(metrics: &Metrics, reason: &'static str) {
153 metrics
154 .ai_handshake_failures_total
155 .add(1, &[KeyValue::new("reason", reason)]);
156}
157
158/// Handle to a running bridge. Cheap to clone; every clone shares one listener
159/// and one registry.
160#[derive(Clone)]
161pub struct AiBridge {
162 inner: Arc<Inner>,
163}
164
165impl AiBridge {
166 /// Bind the listener and start accepting services in the background.
167 ///
168 /// Returns as soon as the socket is bound — services are expected to dial
169 /// in on their own schedule, so the backend never waits for one. A request
170 /// issued before any service connects fails with [`AiError::NoWorker`]
171 /// rather than blocking, which is what keeps an AI feature's outage
172 /// confined to that feature.
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 /// The address actually bound. Differs from the configured one when port 0
207 /// was requested (as the tests do).
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 /// The listener's leaf certificate, DER-encoded. A service pins this (or
216 /// its [`AiBridge::certificate_fingerprint`]) instead of installing a CA.
217 pub fn certificate(&self) -> rustls::pki_types::CertificateDer<'static> {
218 self.inner.certificate.clone()
219 }
220
221 /// SHA-256 of [`AiBridge::certificate`], hex — the value logged at boot.
222 pub fn certificate_fingerprint(&self) -> String {
223 tls::fingerprint(&self.inner.certificate)
224 }
225
226 /// Every connected service, for logs and a future health endpoint.
227 pub fn workers(&self) -> Vec<WorkerSnapshot> {
228 self.inner.registry.snapshot()
229 }
230
231 /// Is anything connected that can serve `capability`?
232 ///
233 /// This registry owns the sockets, so it is the whole truth about what the
234 /// backend can answer. Racy in the harmless direction — a worker can vanish
235 /// between the check and the dispatch — so it never guards a write.
236 pub fn has_capability(&self, capability: &str) -> bool {
237 self.inner.registry.has_capability(capability)
238 }
239
240 /// Send one request to a service and await its answer.
241 ///
242 /// Each call takes a fresh QUIC bidirectional stream, so concurrent calls
243 /// over the same connection neither block nor interleave: the stream *is*
244 /// the correlation, and a slow one cannot stall a fast one.
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 /// [`AiBridge::dispatch`] with a per-call deadline, for capabilities whose
256 /// cost is nothing like the default (a quick classification vs. a long
257 /// generation).
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 // The lease is taken before the timeout starts and released when this
266 // function returns by any path, so an abandoned request frees the
267 // worker's slot rather than leaking it.
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 // The span names the capability, the worker, the school uuid and this
280 // call's own id — never the payload, which is the user's own text.
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 // FIN tells the service the request is complete — it can start
301 // work without waiting to see whether more bytes follow.
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 // A mismatched id means the service is not tracking which
335 // stream it is on. Nothing here depends on the id for
336 // correlation, but the answer's *content* now belongs to some
337 // other request, so it must not be handed back as this one's
338 // result.
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 // A worker that answers `unknown_capability` for a name it advertised
348 // in its own `Hello` has contradicted its handshake. That claim is the
349 // only reason this dispatch was routed here, and the only reason the
350 // caller's door answered `202` instead of "nothing is connected", so it
351 // is withdrawn: `has_capability` stops seeing it and the next door call
352 // refuses instead of queuing work nobody will do. A reconnect restores
353 // it (every fresh `Hello` inserts a worker with its declared list).
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 /// Hand the api-read path the router it dispatches into.
376 ///
377 /// Called once by [`crate::build_router`] with the *pre-layer* service, so
378 /// a synthetic QUIC request skips the per-IP limiter, CORS and `ETag` (see
379 /// the comment there). A second call keeps the first router: the process
380 /// only ever builds one.
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 // Not warned about on a second call: the instruments are the same
390 // process-global ones either way, so re-arming changes nothing.
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 // `ai` cleared: storing the caller's state as-is would cycle
405 // AppState -> bridge -> this lock -> AppState, and the replay fills
406 // the bridge back in on a clone. A worker that registered in the
407 // boot window, before this arm, already missed its own kick.
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 /// Stop listening and close every service connection.
418 pub fn close(&self) {
419 self.inner.endpoint.close(0u32.into(), b"shutting down");
420 }
421}
422
423/// Does this refusal code mean the worker contradicted a claim it made in its
424/// own `Hello` — it advertised the capability and then answered that this name
425/// is not one it implements?
426///
427/// Only `unknown_capability` does. The protocol's refusal vocabulary names no
428/// sibling for "no operation by this name": its one example of a service-defined
429/// code (`unsupported_image`) is a verdict about *this request's payload*, and
430/// the other codes a service may answer — `invalid_payload`, `unavailable`,
431/// `timed_out`, `internal`, `capacity` — are the same kind of thing. Those must
432/// leave the claim standing so a busy, restarting or overloaded service keeps
433/// getting the next request; only a permanent "this name is not mine" licenses
434/// a withdrawal (see [`Registry::withdraw`]).
435fn contradicts_its_own_claim(code: &str) -> bool {
436 code == "unknown_capability"
437}
438
439/// Accept connections until the endpoint closes. One task per service.
440async 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/// Run one service connection: handshake, register, wait for it to die,
457/// deregister.
458async 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 // The welcome is already on the wire. Spawned, not awaited: walking
476 // every school's notes must not hold the handshake, and a registration
477 // that does not offer `rag.index` does not enter.
478 if crate::ai::rag::should_replay_index(&capabilities) {
479 spawn_index_replay_if_armed(&inner);
480 }
481
482 // The control stream is held open (`_control`) for the connection's life.
483 // Nothing more is read on it: its closure, not a heartbeat frame, is how a
484 // service says goodbye, and the QUIC idle timeout covers the case where it
485 // dies without saying anything.
486 //
487 // Every *further* client-initiated stream is one api read or one blob
488 // read. A service that opens none behaves exactly as it did before this
489 // loop existed.
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 // The connection is going away; `closed()` has the real reason.
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/// Answer one client-initiated stream. Two shapes ride this path and are told
513/// apart by the field each requires: an [`ApiRequest`] has `path`, a
514/// [`BlobRequest`] has `file`. The api read is tried first, so every frame that
515/// parsed as one before still does, byte for byte.
516async fn serve_client_stream(
517 inner: Arc<Inner>,
518 mut send: quinn::SendStream,
519 mut recv: quinn::RecvStream,
520) {
521 // Decoded as a `Value` first only so a frame that is JSON but not an
522 // `ApiRequest` still gets its `id` echoed back — that id is what the
523 // service correlates its own logs by.
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 // Echoed verbatim on a refusal, before it is known to be a school at all:
537 // it is how the service tells which of its in-flight reads was refused.
538 let school = string_field(&raw, "school");
539 // Routed on the shape's required field rather than by parsing one and
540 // falling back to the other: that fallback cloned the whole `Value` on
541 // every api read. `path` still wins when a frame carries both.
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 // The third client-initiated shape: a call of a capability the *backend*
561 // serves (ZEKA's storage surface). Routed on `capability`, which neither
562 // of the shapes above carries.
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 // The fourth client-initiated shape: an artifact's bytes coming *in* (the
580 // podcast service's finished mp3). Routed on `upload`, the marker neither
581 // of the shapes above carries; the `size` raw bytes follow the frame on
582 // this same stream.
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 // Neither shape. Reported as the api-read refusal it has always been —
597 // `path` is the field a frame this far off most likely meant to carry.
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/// One string field of a raw frame, or the empty string. Used for the fields a
605/// refusal echoes back before the frame has been proved to be anything.
606fn 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/// Answer one blob read: the [`BlobResponse`] header frame, then — on `Ok` —
614/// exactly `size` raw bytes copied straight off disk, then FIN.
615///
616/// The bytes are streamed rather than buffered: a course-note attachment can
617/// be the school's whole `max_file_bytes`, and this path exists precisely
618/// because such a thing does not fit a frame.
619async 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 // The header already promised `size` bytes, so a short body
628 // would read as a silently truncated file. Reset instead: the
629 // service sees a broken stream and can ask again.
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/// Copy the blob to the stream, one 64 KiB chunk at a time, giving each write
651/// [`AI_BLOB_WRITE_STALL_SECS`] to make progress.
652///
653/// The deadline is per write, not over the transfer: a service that reads
654/// slowly keeps getting fresh time, while one that opens the stream and never
655/// reads blocks on the QUIC stream window and is cut loose instead of parking
656/// this task and the open file for the connection's life.
657async 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/// Serve one artifact upload: validate the frame, store exactly `size` bytes
682/// under the school's blob root, stamp the job's row, and answer one
683/// [`BlobUploadResponse`] frame. Nothing follows the answer — the artifact
684/// travels one way only.
685///
686/// A refusal answers the frame and resets the read side: the service may still
687/// be writing its bytes, and none of them will be stored, so letting the
688/// stream drain would only spend the sender's bandwidth on a file that is
689/// already refused.
690async 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 // The bytes that would have followed are not wanted; tell the
707 // sender so its write stops rather than filling a stream nobody
708 // reads.
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/// The body of an upload: resolve the school, check the job, stream exactly
720/// `size` bytes into a temp file under the school's own blob root, rename it
721/// into place, and stamp the row. `Err` is the refusal `(code, message)`.
722///
723/// The order is the point: metadata and the job's existence are checked before
724/// a byte is read (a refusal must not cost the sender the whole file), and the
725/// bytes are complete on disk — renamed, not half-written — before the row
726/// names them. A row write that finds the job gone deletes the file it just
727/// stored rather than leaving an orphan.
728async 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 // This stream bypasses the router, so it also bypasses the route_layer the
746 // module gate is — the entitlement is checked here by hand instead. The
747 // podcast nest is the `chatbot` module's, exactly as it is over HTTP.
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/// One upload refusal frame. The school is echoed as the caller spelled it.
763fn 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/// Resolve, authorize and open one blob. `Err` is the refusal that becomes a
778/// [`BlobResponse::Err`] code.
779///
780/// Scope is course-note attachments and nothing else: the id is looked up in
781/// `course_note_file` alone, so a personal note's file id reads as `not_found`
782/// rather than reaching another table's row. Authorization is the very guard
783/// `download_file` applies over HTTP — [`can_view_course`] on the note's own
784/// course — so the bridge widens who may ask, never what may be read.
785async 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 // This stream bypasses the router, so it also bypasses the route_layer the
796 // module gate is — the entitlement is checked here by hand instead.
797 // `chatbot` too: a school that did not buy the `ai` package sends no data
798 // to an AI service, and these bytes are the largest thing it would send.
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 // The row exists but its blob does not: server-side damage (a lost volume
842 // path), exactly as `download_file` reads it — not the service's `404`.
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 // The header's `size` is what will actually be copied, so it is taken from
854 // the file on disk rather than the row's column: a service reading exactly
855 // `size` bytes must never over- or under-read.
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/// Who a client-initiated read runs as.
874///
875/// Loaded live out of the *school's own* database — never the control one and
876/// never trusted from the frame: a service holding a stale id must not act as a
877/// user who has since been deleted or demoted, nor as a same-named user of
878/// another school. With nobody named the principal is the synthetic `ai` role.
879async 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 // Both the bare key (`abc`, as a REST path spells it) and the record form
887 // (`user:abc`) are accepted.
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/// The bridge-level refusal this request earns *before* anything is dispatched,
896/// in the order the contract pins: the method first, then the allowlist. A
897/// refused path is never handed to the router at all.
898fn 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/// Validate, dispatch into the router, and turn its answer into a frame.
918///
919/// `Err` is a bridge-level refusal (code, message). Anything the router itself
920/// answered — `401`, `403`, `404` included — comes back as
921/// [`ApiResponse::Ok`] carrying that status: the service asked and the API
922/// replied, which is not a transport failure.
923async 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 // Armed by `build_router`, which runs after the listener binds: a service
932 // that dials in inside that boot window is told to retry, never panicked on.
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/// The half of [`read_api`] that needs only the armed handle: principal,
941/// dispatch, and framing the router's answer. Split out from the listener so
942/// the refusal codes it owns can be exercised without a QUIC endpoint (see
943/// this module's tests).
944async 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 // The school comes off the frame, so this is where a service naming a
959 // stranger's school (or a suspended school's) is stopped — before a row of
960 // anyone's data is read.
961 let tenant = api.school(&school).await?;
962 let db = tenant.db.clone();
963 // The role itself is re-read again by the extractor on the dispatched
964 // request; see [`principal`] for why it is never taken from the frame.
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 // An extension cannot be set from outside the process, which is what makes
982 // this principal unforgeable over HTTP (see [`AiPrincipal`]).
983 dispatched.extensions_mut().insert(AiPrincipal(user));
984 // The dispatched request carries no cookie, so the school is handed over
985 // in the extension the shadow `State` reads first.
986 // Carries the school's entitlements too, so the router's module gate
987 // refuses a disabled nest on this path exactly as it does over HTTP.
988 dispatched.extensions_mut().insert(TenantExt {
989 id: tenant.id,
990 db,
991 modules: tenant.modules,
992 });
993
994 // This dispatch skips every layer, so it also skips the request span and
995 // the request metrics the HTTP edge records — they are recorded here
996 // instead, off the route *template* the allowlist matched. The concrete
997 // path holds record ids and never reaches a span or a label.
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 // Recorded as soon as the router has answered: what follows is bridge
1029 // framing, not the HTTP request the caller made.
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 // `204`s and empty error bodies are a real answer, not a parse failure.
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
1060fn 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/// Write one answer frame and finish the stream.
1070///
1071/// An `Ok` too big to frame is downgraded to a `too_large` refusal rather than
1072/// dropped: a service that got no frame at all would wait out its own deadline
1073/// to learn nothing.
1074async 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/// Frame one answer, downgrading an oversize `Ok` as above. [`write_frame`]
1082/// checks the size *before* it writes a byte, so the refusal never follows a
1083/// half-written frame. Generic over the writer so the downgrade can be asserted
1084/// against a buffer.
1085async 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/// Run one capability the backend serves, and frame its answer.
1107///
1108/// The school is resolved the same way an api read's is — through the same
1109/// registry, with the same three refusals — because it decides *which
1110/// database* the operation runs against; a deployment-scoped capability
1111/// (the school directory) resolves none, and is the only one that may.
1112/// The work is bounded by the bridge's own request deadline: past it the
1113/// service gets `timed_out` and decides for itself whether to retry, which is
1114/// the honest answer, since the statement may well have landed.
1115async fn serve_capability(inner: &Inner, request: CapabilityRequest) -> CapabilityResponse {
1116 // The backend-served families walk one composed table
1117 // ([`crate::ai::capability`]): ZEKA's storage surface and the podcast
1118 // job's state reports. The scope decides whether the frame's school is
1119 // resolved below — it is, for every family today.
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/// One refusal frame, with the school echoed as the caller spelled it.
1176fn 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
1190async 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/// Frame one capability answer, downgrading an oversize `Ok` exactly as
1198/// [`write_answer`] does for an api read: an answer too big to frame becomes a
1199/// `too_large` refusal rather than silence, since a caller that got no frame
1200/// at all would wait out its own deadline to learn nothing.
1201async 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/// Read the `Hello`, decide, answer, and register on success.
1224///
1225/// `Err(())` means the connection was refused and already closed — the caller
1226/// has nothing left to clean up.
1227type Control = (quinn::SendStream, quinn::RecvStream);
1228async 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 // Registered only after the welcome is on the wire: a service that never
1301 // learns it was accepted must not start receiving requests.
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/// Send a rejection the service can act on, then close. Best-effort: a peer
1321/// that has already vanished simply gets closed.
1322async 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 // Give the frame a moment to leave before the connection close overtakes
1335 // it, so the service reports the real reason instead of a bare reset.
1336 let _ = tokio::time::timeout(Duration::from_millis(200), send.stopped()).await;
1337 conn.close(1u32.into(), message.as_bytes());
1338}
1339
1340/// Re-index course notes with files, off the handshake path.
1341///
1342/// No-op when [`AiBridge::arm_api`] has not stored the root state yet. A
1343/// worker that dials in during that window is covered by the arm-time kick,
1344/// once the state exists and the worker is already in the registry.
1345fn 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/// Compare two secrets without leaking their common prefix length through
1359/// timing. Length difference is not secret (and cannot be hidden here), but
1360/// the byte comparison must not short-circuit.
1361fn 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/// One dispatched-and-unanswered AI request, counted for as long as it lives.
1369///
1370/// `AiBridge::send`'s future is dropped whenever its caller goes away (an HTTP
1371/// client disconnecting, an outer timeout), and a decrement written after the
1372/// `.await` is skipped on exactly those paths — leaking the gauge upwards for
1373/// the process's whole life. `Drop` covers every exit.
1374struct InFlight<'a> {
1375 metrics: &'a Metrics,
1376 attrs: &'a [KeyValue],
1377}
1378
1379impl<'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
1386impl Drop for InFlight<'_> {
1387 fn drop(&mut self) {
1388 self.metrics.ai_requests_inflight.add(-1, self.attrs);
1389 }
1390}
1391
1392#[cfg(test)]
1393mod 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 /// An armed handle serving `router`. The database is never touched by these
1404 /// reads (nobody is named, so the principal is synthetic), but the handle
1405 /// carries one exactly as the live path does.
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 /// A read of `/notes` as the service itself.
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 /// The refusal code, or a panic naming the answer that was not one.
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 // No allowlisted route answers text today, so this stands in for the
1437 // day one does: the service is told the body was unreadable rather
1438 // than handed a frame whose `body` field silently became a string.
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 // The other side of the same branch: a `204` has nothing to parse and
1450 // must not read as `not_json`.
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 // The read-side cap: the body is drained with a limit, so an answer
1468 // that cannot fit a frame is refused instead of being buffered whole.
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 // The write-side cap: a body that passed the read limit can still
1483 // overflow once it is wrapped in its frame. The service must get a
1484 // refusal it can log, never silence it waits out — and, because the
1485 // size is checked before any byte is written, nothing of the oversize
1486 // frame may precede it on the stream.
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 // An absent method means GET, which is the whole api the bridge offers.
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 // Order is pinned: the method is judged before the path, so a write
1524 // attempt reads as a write attempt whatever it was aimed at.
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}