forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

protocol.rs576 lines, 21.6 KiBHistoryRawDownload
1//! Wire format for the AI bridge ("hab/2" — hezarfen ai bridge).
2//!
3//! # Shape
4//!
5//! The backend is the QUIC **server**: AI services dial in, so a service can
6//! live behind NAT, restart freely, and scale by simply opening a second
7//! connection. Every service holds exactly one QUIC connection.
8//!
9//! On that connection:
10//!
11//! * The **control stream** is the first *client-initiated* bidirectional
12//! stream. The service writes one [`Hello`]; the backend answers one
13//! [`Greeting`] and then leaves the stream open forever. Its death is the
14//! deregistration signal — no heartbeat frame needed.
15//! * Each request is one *server-initiated* bidirectional stream: the backend
16//! opens it, writes one [`Request`], finishes its send side, and reads one
17//! [`Response`]. The stream is then closed.
18//!
19//! * Each **api read** goes the other way: the service opens a *client-initiated*
20//! bidirectional stream (any after the control one), writes one
21//! [`ApiRequest`], finishes its send side, and reads one [`ApiResponse`].
22//! That mirrors the REST API — the backend dispatches the path internally —
23//! so a service asks for school data instead of being handed it.
24//!
25//! * Each **blob read** goes the same way as an api read, on its own
26//! client-initiated bidirectional stream: the service writes one
27//! [`BlobRequest`], finishes its send side, and reads one [`BlobResponse`]
28//! header frame. On [`BlobResponse::Ok`] exactly `size` **raw** bytes follow
29//! the header — not a frame, so [`AI_MAX_FRAME_BYTES`] does not bound them —
30//! and then the stream is finished. That is how a service gets a course
31//! note's file bytes, which no JSON frame could carry.
32//!
33//! The two client-initiated request shapes are told apart by their required
34//! field: an [`ApiRequest`] has `path`, a [`BlobRequest`] has `file`.
35//!
36//! # School scoping
37//!
38//! Every request frame names its school by slug, and every answer echoes it:
39//! [`Request::school`], [`ApiRequest::school`], [`BlobRequest::school`] and
40//! their responses. The AI fleet is *shared* across the deployment — one
41//! service serves every school — so the school cannot be bound once at
42//! handshake time and [`Hello`] deliberately carries none: a service pinned to
43//! one school would have to be run once per customer. A frame without a
44//! `school` is `malformed`, an unknown slug is `unknown_school`, a suspended
45//! one `school_suspended`; there is no default and no fallback, because a read
46//! answered out of the wrong school's database is the one failure this field
47//! exists to make impossible.
48//!
49//! There is deliberately no correlation-id matching: QUIC stream IDs already
50//! multiplex concurrent requests over the one connection, independently
51//! flow-controlled, with no head-of-line blocking between them. [`Request::id`]
52//! is a trace id for logs on both sides, nothing more.
53//!
54//! # Framing
55//!
56//! `u32` big-endian byte length, then that many bytes of JSON. JSON (not a
57//! compact binary codec) because the AI services are expected to be written in
58//! whatever language suits the model, and a length-prefixed JSON frame is
59//! twenty lines in any of them.
60
61use serde::{Deserialize, Serialize};
62use serde_json::Value;
63use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
64
65use crate::constant::{AI_MAX_FRAME_BYTES, AI_PROTOCOL};
66
67/// Why a frame could not be read or written.
68#[derive(Debug, thiserror::Error)]
69pub enum FrameError {
70 #[error("stream ended before a complete frame arrived")]
71 Eof,
72 #[error("frame of {0} bytes exceeds the {AI_MAX_FRAME_BYTES}-byte limit")]
73 TooLarge(u32),
74 #[error("frame was not valid JSON for the expected message: {0}")]
75 Malformed(#[source] serde_json::Error),
76 #[error("stream i/o failed: {0}")]
77 Io(#[source] std::io::Error),
78}
79
80/// The service's opening frame on the control stream.
81///
82/// Carries **no** school on purpose: the fleet is shared, so one connection
83/// serves every school on the deployment and each frame names its own (see
84/// this module's "School scoping").
85#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
86pub struct Hello {
87 /// Must equal [`crate::constant::AI_PROTOCOL`]; anything else is rejected
88 /// rather than guessed at.
89 pub protocol: String,
90 /// Human-readable service name, for logs (`"ocr"`, `"grader"`).
91 pub service: String,
92 /// The capability strings this service will answer, e.g.
93 /// `["ocr.extract", "ocr.detect_lang"]`. Requests are routed by exact
94 /// match on one of these.
95 pub capabilities: Vec<String>,
96 /// Shared secret, compared against `AI_SHARED_TOKEN` in constant time.
97 pub token: String,
98 /// How many requests this worker will accept at once. Clamped to
99 /// `1..=`[`crate::constant::AI_MAX_CONCURRENT_PER_WORKER`]; absent means
100 /// the default.
101 #[serde(default)]
102 pub max_concurrent: Option<u32>,
103}
104
105/// The backend's answer on the control stream.
106#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
107#[serde(tag = "type", rename_all = "snake_case")]
108pub enum Greeting {
109 Welcome {
110 /// Server-assigned worker id, echoed in the backend's logs so a
111 /// service can correlate its own logs with ours.
112 worker_id: String,
113 protocol: String,
114 },
115 Rejected {
116 code: RejectCode,
117 message: String,
118 },
119}
120
121/// Why a handshake was refused. The service should not retry `Unauthorized`
122/// or `UnsupportedProtocol` without a config change.
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
124#[serde(rename_all = "snake_case")]
125pub enum RejectCode {
126 UnsupportedProtocol,
127 Unauthorized,
128 NoCapabilities,
129 Malformed,
130}
131
132/// One unit of work, written by the backend on a fresh server-initiated
133/// stream.
134#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
135pub struct Request {
136 /// Trace id (ULID). Not used for correlation — the stream does that.
137 pub id: String,
138 /// Slug of the school this work belongs to. Required — see this module's
139 /// "School scoping".
140 pub school: String,
141 /// Which capability from the worker's [`Hello::capabilities`] to invoke.
142 pub capability: String,
143 /// How long the backend will wait before abandoning the stream. The
144 /// service should stop work rather than answer late.
145 pub deadline_ms: u64,
146 /// Capability-specific body, opaque to the transport.
147 pub payload: Value,
148}
149
150/// The service's single answer frame. `Err` is a *handled* failure (bad input,
151/// model refused); a service that dies mid-request just drops the stream,
152/// which surfaces as a transport error instead.
153#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
154#[serde(tag = "status", rename_all = "snake_case")]
155pub enum Response {
156 Ok {
157 id: String,
158 /// Echo of [`Request::school`].
159 school: String,
160 payload: Value,
161 },
162 Err {
163 id: String,
164 /// Echo of [`Request::school`].
165 school: String,
166 /// Service-defined, stable, machine-readable (`"unsupported_image"`).
167 code: String,
168 message: String,
169 },
170}
171
172/// A read of the school's own API, written by the *service* on a fresh
173/// client-initiated stream.
174#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
175pub struct ApiRequest {
176 /// Trace id (ULID). Not used for correlation — the stream does that.
177 pub id: String,
178 /// Slug of the school to read. Required — see this module's "School
179 /// scoping"; the answer comes out of that school's own database.
180 pub school: String,
181 /// Path as the REST API spells it, e.g. `"/users/me"`. No host, no query.
182 pub path: String,
183 /// Query string without the leading `?`, e.g. `"limit=10&offset=0"`.
184 #[serde(default)]
185 pub query: Option<String>,
186 /// User id to execute as, for own-scoped endpoints. Absent means the
187 /// request runs as the service itself.
188 #[serde(default)]
189 pub on_behalf_of: Option<String>,
190 /// HTTP method. Absent means `GET`. Not validated here — the server
191 /// decides what it will dispatch.
192 #[serde(default)]
193 pub method: Option<String>,
194}
195
196/// The backend's single answer frame. `Err` is a bridge-level refusal (path not
197/// allowed, unknown user); an API call that ran and answered `404` is an `Ok`
198/// carrying that status, because the service asked and the API replied.
199#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
200#[serde(tag = "outcome", rename_all = "snake_case")]
201pub enum ApiResponse {
202 Ok {
203 id: String,
204 /// Echo of [`ApiRequest::school`].
205 school: String,
206 /// HTTP status the router produced.
207 status: u16,
208 body: Value,
209 },
210 Err {
211 id: String,
212 /// Echo of the school the frame named — as sent, even when it named no
213 /// school a slug could be made of, so a service can tell which of its
214 /// in-flight reads was refused.
215 school: String,
216 /// Bridge-defined, stable, machine-readable (`"path_not_allowed"`,
217 /// `"unknown_school"`, `"school_suspended"`).
218 code: String,
219 message: String,
220 },
221}
222
223/// A read of one course-note file's *bytes*, written by the *service* on a
224/// fresh client-initiated stream. Distinguished from an [`ApiRequest`] by its
225/// required `file` field.
226#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
227pub struct BlobRequest {
228 /// Trace id (ULID). Not used for correlation — the stream does that.
229 pub id: String,
230 /// Slug of the school the file belongs to. Required — see this module's
231 /// "School scoping"; the bytes come out of that school's blob directory.
232 pub school: String,
233 /// The `course_note_file` record key, as `GET /course-notes/{id}/files`
234 /// and the `rag.index` payload both publish it.
235 pub file: String,
236 /// User id to read as. Absent means the service itself, which can view no
237 /// course and so always earns `forbidden`.
238 #[serde(default)]
239 pub on_behalf_of: Option<String>,
240}
241
242/// The header frame that opens (or refuses) a blob stream. On `Ok` exactly
243/// `size` raw bytes follow it, then FIN; on `Err` the stream is finished with
244/// nothing after the frame.
245#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
246#[serde(tag = "status", rename_all = "snake_case")]
247pub enum BlobResponse {
248 Ok {
249 id: String,
250 /// Echo of [`BlobRequest::school`].
251 school: String,
252 name: String,
253 content_type: String,
254 /// Exactly how many raw bytes follow this frame.
255 size: u64,
256 },
257 Err {
258 id: String,
259 /// Echo of the school the frame named, as sent.
260 school: String,
261 /// Bridge-defined, stable, machine-readable (`"not_found"`).
262 code: String,
263 message: String,
264 },
265}
266
267/// Write one length-prefixed JSON frame.
268pub async fn write_frame<W, T>(w: &mut W, message: &T) -> Result<(), FrameError>
269where
270 W: AsyncWrite + Unpin,
271 T: Serialize,
272{
273 let body = serde_json::to_vec(message).map_err(FrameError::Malformed)?;
274 let len = u32::try_from(body.len()).map_err(|_| FrameError::TooLarge(u32::MAX))?;
275 if body.len() > AI_MAX_FRAME_BYTES {
276 return Err(FrameError::TooLarge(len));
277 }
278 w.write_all(&len.to_be_bytes())
279 .await
280 .map_err(FrameError::Io)?;
281 w.write_all(&body).await.map_err(FrameError::Io)?;
282 w.flush().await.map_err(FrameError::Io)?;
283 Ok(())
284}
285
286/// Read one length-prefixed JSON frame.
287///
288/// The length is checked *before* allocating, so a hostile or confused peer
289/// cannot make the backend reserve gigabytes by lying in four bytes.
290pub async fn read_frame<R, T>(r: &mut R) -> Result<T, FrameError>
291where
292 R: AsyncRead + Unpin,
293 T: for<'de> Deserialize<'de>,
294{
295 let mut header = [0u8; 4];
296 read_exact(r, &mut header).await?;
297 let len = u32::from_be_bytes(header);
298 if len as usize > AI_MAX_FRAME_BYTES {
299 return Err(FrameError::TooLarge(len));
300 }
301 let mut body = vec![0u8; len as usize];
302 read_exact(r, &mut body).await?;
303 serde_json::from_slice(&body).map_err(FrameError::Malformed)
304}
305
306/// `read_exact` that reports a clean peer FIN as [`FrameError::Eof`] rather
307/// than an opaque io error — a service closing its control stream is normal.
308async fn read_exact<R: AsyncRead + Unpin>(r: &mut R, buf: &mut [u8]) -> Result<(), FrameError> {
309 let mut filled = 0;
310 while filled < buf.len() {
311 match r.read(&mut buf[filled..]).await {
312 Ok(0) => return Err(FrameError::Eof),
313 Ok(n) => filled += n,
314 Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Err(FrameError::Eof),
315 Err(e) => return Err(FrameError::Io(e)),
316 }
317 }
318 Ok(())
319}
320
321/// Does this [`Hello`] speak our protocol version?
322pub fn protocol_matches(hello: &Hello) -> bool {
323 hello.protocol == AI_PROTOCOL
324}
325
326#[cfg(test)]
327mod tests {
328 use super::*;
329 use serde_json::json;
330
331 fn hello() -> Hello {
332 Hello {
333 protocol: AI_PROTOCOL.to_string(),
334 service: "ocr".into(),
335 capabilities: vec!["ocr.extract".into()],
336 token: "secret".into(),
337 max_concurrent: Some(4),
338 }
339 }
340
341 #[tokio::test]
342 async fn frames_round_trip_through_a_pipe() {
343 let (mut client, mut server) = tokio::io::duplex(64 * 1024);
344 let sent = hello();
345 write_frame(&mut client, &sent).await.unwrap();
346 let got: Hello = read_frame(&mut server).await.unwrap();
347 assert_eq!(got, sent);
348 }
349
350 #[tokio::test]
351 async fn back_to_back_frames_stay_aligned() {
352 // The length prefix, not the stream boundary, delimits a frame — two
353 // writes must read back as exactly two messages.
354 let (mut client, mut server) = tokio::io::duplex(64 * 1024);
355 let a = Response::Ok {
356 id: "a".into(),
357 school: "demo".into(),
358 payload: json!({ "n": 1 }),
359 };
360 let b = Response::Err {
361 id: "b".into(),
362 school: "demo".into(),
363 code: "bad_input".into(),
364 message: "nope".into(),
365 };
366 write_frame(&mut client, &a).await.unwrap();
367 write_frame(&mut client, &b).await.unwrap();
368 assert_eq!(read_frame::<_, Response>(&mut server).await.unwrap(), a);
369 assert_eq!(read_frame::<_, Response>(&mut server).await.unwrap(), b);
370 }
371
372 #[tokio::test]
373 async fn a_clean_close_reads_as_eof_not_an_io_error() {
374 let (client, mut server) = tokio::io::duplex(64);
375 drop(client);
376 let err = read_frame::<_, Hello>(&mut server).await.unwrap_err();
377 assert!(matches!(err, FrameError::Eof), "got {err:?}");
378 }
379
380 #[tokio::test]
381 async fn a_truncated_frame_is_eof_not_a_parse_of_partial_json() {
382 let (mut client, mut server) = tokio::io::duplex(64 * 1024);
383 client.write_all(&8u32.to_be_bytes()).await.unwrap();
384 client.write_all(b"{\"a\":").await.unwrap();
385 drop(client);
386 assert!(matches!(
387 read_frame::<_, Hello>(&mut server).await.unwrap_err(),
388 FrameError::Eof
389 ));
390 }
391
392 #[tokio::test]
393 async fn an_oversized_length_is_refused_before_allocating() {
394 let (mut client, mut server) = tokio::io::duplex(64 * 1024);
395 // Only the four-byte header is ever written: the reader must refuse on
396 // the header alone, without waiting for (or reserving) the body.
397 let claimed = AI_MAX_FRAME_BYTES as u32 + 1;
398 client.write_all(&claimed.to_be_bytes()).await.unwrap();
399 let err = read_frame::<_, Hello>(&mut server).await.unwrap_err();
400 assert!(
401 matches!(err, FrameError::TooLarge(n) if n == claimed),
402 "got {err:?}"
403 );
404 }
405
406 #[tokio::test]
407 async fn garbage_body_is_malformed_not_a_panic() {
408 let (mut client, mut server) = tokio::io::duplex(64 * 1024);
409 let body = b"not json at all";
410 client
411 .write_all(&(body.len() as u32).to_be_bytes())
412 .await
413 .unwrap();
414 client.write_all(body).await.unwrap();
415 assert!(matches!(
416 read_frame::<_, Hello>(&mut server).await.unwrap_err(),
417 FrameError::Malformed(_)
418 ));
419 }
420
421 #[tokio::test]
422 async fn greeting_and_response_tags_are_the_documented_wire_names() {
423 // Services in other languages match on these literals — a rename here
424 // silently breaks every one of them, so pin the encoding.
425 let welcome = serde_json::to_value(Greeting::Welcome {
426 worker_id: "w1".into(),
427 protocol: AI_PROTOCOL.into(),
428 })
429 .unwrap();
430 assert_eq!(welcome["type"], "welcome");
431 let rejected = serde_json::to_value(Greeting::Rejected {
432 code: RejectCode::Unauthorized,
433 message: "bad token".into(),
434 })
435 .unwrap();
436 assert_eq!(rejected["type"], "rejected");
437 assert_eq!(rejected["code"], "unauthorized");
438 let ok = serde_json::to_value(Response::Ok {
439 id: "1".into(),
440 school: "demo".into(),
441 payload: json!(null),
442 })
443 .unwrap();
444 assert_eq!(ok["status"], "ok");
445 }
446
447 #[tokio::test]
448 async fn api_frame_tags_are_the_documented_wire_names() {
449 // Same reason as above: other-language services match these literals.
450 // The tag is `outcome`, not `status` — `status` is the HTTP code.
451 let ok = serde_json::to_value(ApiResponse::Ok {
452 id: "1".into(),
453 school: "demo".into(),
454 status: 404,
455 body: json!(null),
456 })
457 .unwrap();
458 assert_eq!(ok["outcome"], "ok");
459 assert_eq!(ok["status"], 404);
460 let err = serde_json::to_value(ApiResponse::Err {
461 id: "1".into(),
462 school: "demo".into(),
463 code: "path_not_allowed".into(),
464 message: "nope".into(),
465 })
466 .unwrap();
467 assert_eq!(err["outcome"], "err");
468 assert_eq!(err["code"], "path_not_allowed");
469 }
470
471 #[tokio::test]
472 async fn an_api_request_needs_only_an_id_a_school_and_a_path() {
473 let bare: ApiRequest = serde_json::from_value(json!({
474 "id": "01J",
475 "school": "demo",
476 "path": "/users/me",
477 }))
478 .unwrap();
479 assert_eq!(bare.query, None);
480 assert_eq!(bare.on_behalf_of, None);
481 assert_eq!(bare.method, None);
482 // The school is required, not defaulted: a frame that names none has
483 // no school to fall back on and must not parse.
484 assert!(
485 serde_json::from_value::<ApiRequest>(json!({ "id": "01J", "path": "/users/me" }))
486 .is_err()
487 );
488
489 let full = ApiRequest {
490 id: "01J".into(),
491 school: "demo".into(),
492 path: "/notes".into(),
493 query: Some("limit=10".into()),
494 on_behalf_of: Some("user:abc".into()),
495 // Not validated at this layer — any string rides the wire.
496 method: Some("GET".into()),
497 };
498 let raw = serde_json::to_value(&full).unwrap();
499 assert_eq!(raw["school"], "demo");
500 assert_eq!(raw["path"], "/notes");
501 assert_eq!(raw["query"], "limit=10");
502 assert_eq!(raw["on_behalf_of"], "user:abc");
503 assert_eq!(raw["method"], "GET");
504 assert_eq!(serde_json::from_value::<ApiRequest>(raw).unwrap(), full);
505 }
506
507 #[tokio::test]
508 async fn blob_frame_tags_are_the_documented_wire_names() {
509 // Same reason as above: other-language services match these literals.
510 // The tag is `status` (as on `Response`), not `outcome` — a blob header
511 // carries no HTTP status for it to collide with.
512 let ok = serde_json::to_value(BlobResponse::Ok {
513 id: "1".into(),
514 school: "demo".into(),
515 name: "recap.pdf".into(),
516 content_type: "application/pdf".into(),
517 size: 204_800,
518 })
519 .unwrap();
520 assert_eq!(ok["status"], "ok");
521 assert_eq!(ok["size"], 204_800);
522 let err = serde_json::to_value(BlobResponse::Err {
523 id: "1".into(),
524 school: "demo".into(),
525 code: "not_found".into(),
526 message: "nope".into(),
527 })
528 .unwrap();
529 assert_eq!(err["status"], "err");
530 assert_eq!(err["code"], "not_found");
531
532 // `file` is what tells a blob request apart from an api read, so it is
533 // required; `on_behalf_of` is the only optional field.
534 let bare: BlobRequest = serde_json::from_value(json!({
535 "id": "01J", "school": "demo", "file": "01FILE",
536 }))
537 .unwrap();
538 assert_eq!(bare.on_behalf_of, None);
539 assert!(
540 serde_json::from_value::<BlobRequest>(json!({ "id": "01J", "school": "demo" }))
541 .is_err()
542 );
543 // The school is required here too.
544 assert!(
545 serde_json::from_value::<BlobRequest>(json!({ "id": "01J", "file": "01FILE" }))
546 .is_err()
547 );
548 // And the two shapes never parse as each other.
549 assert!(
550 serde_json::from_value::<ApiRequest>(json!({
551 "id": "01J", "school": "demo", "file": "01FILE",
552 }))
553 .is_err()
554 );
555 }
556
557 #[tokio::test]
558 async fn max_concurrent_is_optional_on_the_wire() {
559 let raw = json!({
560 "protocol": AI_PROTOCOL,
561 "service": "ocr",
562 "capabilities": ["ocr.extract"],
563 "token": "secret",
564 });
565 let hello: Hello = serde_json::from_value(raw).unwrap();
566 assert_eq!(hello.max_concurrent, None);
567 assert!(protocol_matches(&hello));
568 }
569
570 #[tokio::test]
571 async fn a_foreign_protocol_version_does_not_match() {
572 let mut h = hello();
573 h.protocol = "hab/99".into();
574 assert!(!protocol_matches(&h));
575 }
576}