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

protocol.rs822 lines, 32.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//! * Each **capability call** also goes the service's way, on its own
34//! client-initiated bidirectional stream: the service writes one
35//! [`CapabilityRequest`], finishes its send side, and reads one
36//! [`CapabilityResponse`]. This is the reverse of the [`Request`]/
37//! [`Response`] pair above, and it exists for the same reason the api read
38//! does: capabilities live on both sides. The backend *dispatches*
39//! `chat.reply` and `insight.student` to a service; a service *calls*
40//! `insight.summary.upsert` and the rest of the backend's storage surface
41//! to have the backend write rows an AI service may not write itself.
42//!
43//! The three client-initiated request shapes are told apart by their
44//! required field: an [`ApiRequest`] has `path`, a [`BlobRequest`] has
45//! `file`, a [`CapabilityRequest`] has `capability`.
46//!
47//! * Each **blob upload** is the blob read's mirror image: the service writes
48//! one [`BlobUploadRequest`], then exactly `size` **raw** bytes — again not a
49//! frame — and finishes its send side; the backend stores them and answers
50//! one [`BlobUploadResponse`] header frame. That is how a service hands back
51//! an artifact it produced (today the podcast service's finished mp3), which
52//! no JSON frame could carry. Distinguished from a [`BlobRequest`] by its
53//! required `upload` marker and `job_id`.
54//!
55//! # Refusal codes
56//!
57//! [`ApiResponse::Err`], [`BlobResponse::Err`] and [`CapabilityResponse::Err`]
58//! all carry a `code`: a stable, machine-readable string a service branches
59//! on, never a message. The vocabulary, in one place:
60//!
61//! * `malformed` — the frame is not this shape (a missing or mistyped field).
62//! * `unknown_capability` — no operation this backend serves has that name.
63//! * `unknown_school` — the named id is not a school on this deployment.
64//! * `school_suspended` — it exists and is switched off; worth retrying later.
65//! * `not_permitted` — the school's own feature set refuses the operation.
66//! * `invalid_payload` — the payload does not fit the operation's contract
67//! (`message` names the field).
68//! * `too_many_rows` — a count bound was exceeded (`message` names it); the
69//! operation was refused whole, never applied in part.
70//! * `unavailable` — the school's database could not be reached.
71//! * `timed_out` — the operation outlived the bridge's deadline; whether it
72//! landed is unknown, so retrying is the caller's decision.
73//! * `internal` — the backend failed while doing the work.
74//! * `path_not_allowed`, `unknown_user`, `method_not_allowed` — api-read only.
75//!
76//! # School scoping
77//!
78//! Every request frame names its school by uuid, and every answer echoes it:
79//! [`Request::school`], [`ApiRequest::school`], [`BlobRequest::school`] and
80//! their responses. The AI fleet is *shared* across the deployment — one
81//! service serves every school — so the school cannot be bound once at
82//! handshake time and [`Hello`] deliberately carries none: a service pinned to
83//! one school would have to be run once per customer. A frame without a
84//! `school` is `malformed`, an unknown id is `unknown_school`, a suspended
85//! one `school_suspended`; there is no default and no fallback, because a read
86//! answered out of the wrong school's database is the one failure this field
87//! exists to make impossible.
88//!
89//! There is deliberately no correlation-id matching: QUIC stream IDs already
90//! multiplex concurrent requests over the one connection, independently
91//! flow-controlled, with no head-of-line blocking between them. [`Request::id`]
92//! is a trace id for logs on both sides, nothing more.
93//!
94//! # Framing
95//!
96//! `u32` big-endian byte length, then that many bytes of JSON. JSON (not a
97//! compact binary codec) because the AI services are expected to be written in
98//! whatever language suits the model, and a length-prefixed JSON frame is
99//! twenty lines in any of them.
100
101use serde::{Deserialize, Serialize};
102use serde_json::Value;
103use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
104
105use crate::constant::{AI_MAX_FRAME_BYTES, AI_PROTOCOL};
106
107/// Why a frame could not be read or written.
108#[derive(Debug, thiserror::Error)]
109pub enum FrameError {
110 #[error("stream ended before a complete frame arrived")]
111 Eof,
112 #[error("frame of {0} bytes exceeds the {AI_MAX_FRAME_BYTES}-byte limit")]
113 TooLarge(u32),
114 #[error("frame was not valid JSON for the expected message: {0}")]
115 Malformed(#[source] serde_json::Error),
116 #[error("stream i/o failed: {0}")]
117 Io(#[source] std::io::Error),
118}
119
120/// The service's opening frame on the control stream.
121///
122/// Carries **no** school on purpose: the fleet is shared, so one connection
123/// serves every school on the deployment and each frame names its own (see
124/// this module's "School scoping").
125#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
126pub struct Hello {
127 /// Must equal [`crate::constant::AI_PROTOCOL`]; anything else is rejected
128 /// rather than guessed at.
129 pub protocol: String,
130 /// Human-readable service name, for logs (`"ocr"`, `"grader"`).
131 pub service: String,
132 /// The capability strings this service will answer, e.g.
133 /// `["ocr.extract", "ocr.detect_lang"]`. Requests are routed by exact
134 /// match on one of these.
135 pub capabilities: Vec<String>,
136 /// Shared secret, compared against `AI_SHARED_TOKEN` in constant time.
137 pub token: String,
138 /// How many requests this worker will accept at once. Clamped to
139 /// `1..=`[`crate::constant::AI_MAX_CONCURRENT_PER_WORKER`]; absent means
140 /// the default.
141 #[serde(default)]
142 pub max_concurrent: Option<u32>,
143}
144
145/// The backend's answer on the control stream.
146#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
147#[serde(tag = "type", rename_all = "snake_case")]
148pub enum Greeting {
149 Welcome {
150 /// Server-assigned worker id, echoed in the backend's logs so a
151 /// service can correlate its own logs with ours.
152 worker_id: String,
153 protocol: String,
154 },
155 Rejected {
156 code: RejectCode,
157 message: String,
158 },
159}
160
161/// Why a handshake was refused. The service should not retry `Unauthorized`
162/// or `UnsupportedProtocol` without a config change.
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
164#[serde(rename_all = "snake_case")]
165pub enum RejectCode {
166 UnsupportedProtocol,
167 Unauthorized,
168 NoCapabilities,
169 Malformed,
170}
171
172/// One unit of work, written by the backend on a fresh server-initiated
173/// stream.
174#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
175pub struct Request {
176 /// Trace id (ULID). Not used for correlation — the stream does that.
177 pub id: String,
178 /// Uuid of the school this work belongs to (hyphenated form). Required —
179 /// see this module's
180 /// "School scoping".
181 pub school: String,
182 /// Which capability from the worker's [`Hello::capabilities`] to invoke.
183 pub capability: String,
184 /// How long the backend will wait before abandoning the stream. The
185 /// service should stop work rather than answer late.
186 pub deadline_ms: u64,
187 /// Capability-specific body, opaque to the transport.
188 pub payload: Value,
189}
190
191/// The service's single answer frame. `Err` is a *handled* failure (bad input,
192/// model refused); a service that dies mid-request just drops the stream,
193/// which surfaces as a transport error instead.
194#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
195#[serde(tag = "status", rename_all = "snake_case")]
196pub enum Response {
197 Ok {
198 id: String,
199 /// Echo of [`Request::school`].
200 school: String,
201 payload: Value,
202 },
203 Err {
204 id: String,
205 /// Echo of [`Request::school`].
206 school: String,
207 /// Service-defined, stable, machine-readable (`"unsupported_image"`).
208 code: String,
209 message: String,
210 },
211}
212
213/// A read of the school's own API, written by the *service* on a fresh
214/// client-initiated stream.
215#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
216pub struct ApiRequest {
217 /// Trace id (ULID). Not used for correlation — the stream does that.
218 pub id: String,
219 /// Uuid of the school to read (hyphenated form). Required — see this
220 /// module's "School
221 /// scoping"; the answer comes out of that school's own database.
222 pub school: String,
223 /// Path as the REST API spells it, e.g. `"/users/me"`. No host, no query.
224 pub path: String,
225 /// Query string without the leading `?`, e.g. `"limit=10&offset=0"`.
226 #[serde(default)]
227 pub query: Option<String>,
228 /// User id to execute as, for own-scoped endpoints. Absent means the
229 /// request runs as the service itself.
230 #[serde(default)]
231 pub on_behalf_of: Option<String>,
232 /// HTTP method. Absent means `GET`. Not validated here — the server
233 /// decides what it will dispatch.
234 #[serde(default)]
235 pub method: Option<String>,
236}
237
238/// The backend's single answer frame. `Err` is a bridge-level refusal (path not
239/// allowed, unknown user); an API call that ran and answered `404` is an `Ok`
240/// carrying that status, because the service asked and the API replied.
241#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
242#[serde(tag = "outcome", rename_all = "snake_case")]
243pub enum ApiResponse {
244 Ok {
245 id: String,
246 /// Echo of [`ApiRequest::school`].
247 school: String,
248 /// HTTP status the router produced.
249 status: u16,
250 body: Value,
251 },
252 Err {
253 id: String,
254 /// Echo of the school the frame named — as sent, even when it named no
255 /// school a uuid could be made of, so a service can tell which of its
256 /// in-flight reads was refused.
257 school: String,
258 /// Bridge-defined, stable, machine-readable (`"path_not_allowed"`,
259 /// `"unknown_school"`, `"school_suspended"`).
260 code: String,
261 message: String,
262 },
263}
264
265/// A read of one course-note file's *bytes*, written by the *service* on a
266/// fresh client-initiated stream. Distinguished from an [`ApiRequest`] by its
267/// required `file` field.
268#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
269pub struct BlobRequest {
270 /// Trace id (ULID). Not used for correlation — the stream does that.
271 pub id: String,
272 /// Uuid of the school the file belongs to (hyphenated form). Required —
273 /// see this module's
274 /// "School scoping"; the bytes come out of that school's blob directory.
275 pub school: String,
276 /// The `course_note_file` record key, as `GET /course-notes/{id}/files`
277 /// and the `rag.index` payload both publish it.
278 pub file: String,
279 /// User id to read as. Absent means the service itself, which can view no
280 /// course and so always earns `forbidden`.
281 #[serde(default)]
282 pub on_behalf_of: Option<String>,
283}
284
285/// The header frame that opens (or refuses) a blob stream. On `Ok` exactly
286/// `size` raw bytes follow it, then FIN; on `Err` the stream is finished with
287/// nothing after the frame.
288#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
289#[serde(tag = "status", rename_all = "snake_case")]
290pub enum BlobResponse {
291 Ok {
292 id: String,
293 /// Echo of [`BlobRequest::school`].
294 school: String,
295 name: String,
296 content_type: String,
297 /// Exactly how many raw bytes follow this frame.
298 size: u64,
299 },
300 Err {
301 id: String,
302 /// Echo of the school the frame named, as sent.
303 school: String,
304 /// Bridge-defined, stable, machine-readable (`"not_found"`).
305 code: String,
306 message: String,
307 },
308}
309
310/// A call of one capability the *backend* serves, written by the service on a
311/// fresh client-initiated stream. The mirror image of [`Request`], which the
312/// backend writes when it calls a capability the *service* serves.
313///
314/// Distinguished from an [`ApiRequest`] by its required `capability` field and
315/// from a [`BlobRequest`] by its required `school` and `payload`. There is no
316/// path and no method: an operation is named, never addressed — the backend's
317/// storage surface is a list of operations, and a frame that could name a
318/// table, a schema or a query would be the door this shape exists to not have.
319#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
320pub struct CapabilityRequest {
321 /// Trace id (ULID). Not used for correlation — the stream does that.
322 pub id: String,
323 /// Uuid of the school the call is scoped to (hyphenated form). Required,
324 /// exactly as on
325 /// every other frame — one capability is deployment-scoped
326 /// (`insight.schools.list`, whose answer *is* the school directory) and
327 /// sends the empty string there.
328 pub school: String,
329 /// The operation to run. Matched exactly against the backend's served
330 /// capabilities; anything else is `unknown_capability`.
331 pub capability: String,
332 /// Operation-specific body, opaque to the transport.
333 pub payload: Value,
334}
335
336/// The backend's single answer frame, mirroring [`Response`] field for field:
337/// `status` is the discriminator, and both variants echo the school the call
338/// named so a service can tell which of its in-flight calls was answered.
339///
340/// `Err` is a *handled* refusal (unknown capability, a payload that does not
341/// fit, the school's database unreachable). A service that dies mid-call just
342/// drops the stream, which surfaces as a transport error instead.
343#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
344#[serde(tag = "status", rename_all = "snake_case")]
345pub enum CapabilityResponse {
346 Ok {
347 /// Echo of [`CapabilityRequest::id`].
348 id: String,
349 /// Echo of [`CapabilityRequest::school`].
350 school: String,
351 payload: Value,
352 },
353 Err {
354 /// Echo of [`CapabilityRequest::id`].
355 id: String,
356 /// Echo of [`CapabilityRequest::school`], as sent.
357 school: String,
358 /// One of this module's documented refusal codes.
359 code: String,
360 message: String,
361 },
362}
363
364/// A write of one produced artifact's *bytes*, written by the *service* on a
365/// fresh client-initiated stream. The mirror image of [`BlobRequest`]: the
366/// service names what it is handing over, exactly `size` raw bytes follow this
367/// frame, and the backend stores them somewhere that belongs to the school —
368/// never to the service's own volume.
369///
370/// Distinguished from a [`BlobRequest`] (the read) by the required `upload`
371/// marker and its `job_id`: an upload is always *about* one backend-minted
372/// job, and the backend links the stored blob to that job's row.
373#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
374pub struct BlobUploadRequest {
375 /// Trace id (ULID). Not used for correlation — the stream does that.
376 pub id: String,
377 /// The shape marker. Must be `true`; any other value is `malformed`.
378 pub upload: bool,
379 /// Uuid of the school the artifact belongs to (hyphenated form). Required
380 /// — the bytes land
381 /// in that school's own blob directory, never anywhere else.
382 pub school: String,
383 /// The backend-minted podcast job the artifact belongs to.
384 pub job_id: String,
385 /// The artifact's display name (an episode's file name). Stored as
386 /// metadata; never used to build a path.
387 pub name: String,
388 /// The artifact's MIME type. Must be an `audio/*` type today.
389 pub content_type: String,
390 /// Exactly how many raw bytes follow this frame.
391 pub size: u64,
392 /// The episode's length, when the producer knows it. Metadata for the
393 /// read doors; `None` is allowed.
394 #[serde(default)]
395 pub duration_secs: Option<f64>,
396}
397
398/// The single answer frame an upload gets. There are no bytes after it: the
399/// artifact travels service → backend only, and `Ok.key` is the handle the
400/// read doors publish (`GET /podcast/jobs/{id}/audio` resolves it). A refusal
401/// carries nothing after the frame, and the backend resets the stream rather
402/// than reading a body it will not store.
403#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
404#[serde(tag = "status", rename_all = "snake_case")]
405pub enum BlobUploadResponse {
406 Ok {
407 /// Echo of [`BlobUploadRequest::id`].
408 id: String,
409 /// Echo of [`BlobUploadRequest::school`].
410 school: String,
411 /// The key the bytes were stored under, relative to the school's blob
412 /// root (`podcast/<job-id>.<ext>`).
413 key: String,
414 /// How many bytes were written — always the request's `size`.
415 size: u64,
416 },
417 Err {
418 /// Echo of [`BlobUploadRequest::id`].
419 id: String,
420 /// Echo of [`BlobUploadRequest::school`], as sent.
421 school: String,
422 /// This module's documented refusal codes, plus the operation's own
423 /// (`unknown_job`, `expired`, `audio_missing`, …) — flat and stable,
424 /// never nested.
425 code: String,
426 message: String,
427 },
428}
429
430/// Write one length-prefixed JSON frame.
431pub async fn write_frame<W, T>(w: &mut W, message: &T) -> Result<(), FrameError>
432where
433 W: AsyncWrite + Unpin,
434 T: Serialize,
435{
436 let body = serde_json::to_vec(message).map_err(FrameError::Malformed)?;
437 let len = u32::try_from(body.len()).map_err(|_| FrameError::TooLarge(u32::MAX))?;
438 if body.len() > AI_MAX_FRAME_BYTES {
439 return Err(FrameError::TooLarge(len));
440 }
441 w.write_all(&len.to_be_bytes())
442 .await
443 .map_err(FrameError::Io)?;
444 w.write_all(&body).await.map_err(FrameError::Io)?;
445 w.flush().await.map_err(FrameError::Io)?;
446 Ok(())
447}
448
449/// Read one length-prefixed JSON frame.
450///
451/// The length is checked *before* allocating, so a hostile or confused peer
452/// cannot make the backend reserve gigabytes by lying in four bytes.
453pub async fn read_frame<R, T>(r: &mut R) -> Result<T, FrameError>
454where
455 R: AsyncRead + Unpin,
456 T: for<'de> Deserialize<'de>,
457{
458 let mut header = [0u8; 4];
459 read_exact(r, &mut header).await?;
460 let len = u32::from_be_bytes(header);
461 if len as usize > AI_MAX_FRAME_BYTES {
462 return Err(FrameError::TooLarge(len));
463 }
464 let mut body = vec![0u8; len as usize];
465 read_exact(r, &mut body).await?;
466 serde_json::from_slice(&body).map_err(FrameError::Malformed)
467}
468
469/// `read_exact` that reports a clean peer FIN as [`FrameError::Eof`] rather
470/// than an opaque io error — a service closing its control stream is normal.
471async fn read_exact<R: AsyncRead + Unpin>(r: &mut R, buf: &mut [u8]) -> Result<(), FrameError> {
472 let mut filled = 0;
473 while filled < buf.len() {
474 match r.read(&mut buf[filled..]).await {
475 Ok(0) => return Err(FrameError::Eof),
476 Ok(n) => filled += n,
477 Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Err(FrameError::Eof),
478 Err(e) => return Err(FrameError::Io(e)),
479 }
480 }
481 Ok(())
482}
483
484/// Does this [`Hello`] speak our protocol version?
485pub fn protocol_matches(hello: &Hello) -> bool {
486 hello.protocol == AI_PROTOCOL
487}
488
489#[cfg(test)]
490mod tests {
491 use super::*;
492 use serde_json::json;
493
494 fn hello() -> Hello {
495 Hello {
496 protocol: AI_PROTOCOL.to_string(),
497 service: "ocr".into(),
498 capabilities: vec!["ocr.extract".into()],
499 token: "secret".into(),
500 max_concurrent: Some(4),
501 }
502 }
503
504 #[tokio::test]
505 async fn frames_round_trip_through_a_pipe() {
506 let (mut client, mut server) = tokio::io::duplex(64 * 1024);
507 let sent = hello();
508 write_frame(&mut client, &sent).await.unwrap();
509 let got: Hello = read_frame(&mut server).await.unwrap();
510 assert_eq!(got, sent);
511 }
512
513 #[tokio::test]
514 async fn back_to_back_frames_stay_aligned() {
515 // The length prefix, not the stream boundary, delimits a frame — two
516 // writes must read back as exactly two messages.
517 let (mut client, mut server) = tokio::io::duplex(64 * 1024);
518 let a = Response::Ok {
519 id: "a".into(),
520 school: "demo".into(),
521 payload: json!({ "n": 1 }),
522 };
523 let b = Response::Err {
524 id: "b".into(),
525 school: "demo".into(),
526 code: "bad_input".into(),
527 message: "nope".into(),
528 };
529 write_frame(&mut client, &a).await.unwrap();
530 write_frame(&mut client, &b).await.unwrap();
531 assert_eq!(read_frame::<_, Response>(&mut server).await.unwrap(), a);
532 assert_eq!(read_frame::<_, Response>(&mut server).await.unwrap(), b);
533 }
534
535 #[tokio::test]
536 async fn a_clean_close_reads_as_eof_not_an_io_error() {
537 let (client, mut server) = tokio::io::duplex(64);
538 drop(client);
539 let err = read_frame::<_, Hello>(&mut server).await.unwrap_err();
540 assert!(matches!(err, FrameError::Eof), "got {err:?}");
541 }
542
543 #[tokio::test]
544 async fn a_truncated_frame_is_eof_not_a_parse_of_partial_json() {
545 let (mut client, mut server) = tokio::io::duplex(64 * 1024);
546 client.write_all(&8u32.to_be_bytes()).await.unwrap();
547 client.write_all(b"{\"a\":").await.unwrap();
548 drop(client);
549 assert!(matches!(
550 read_frame::<_, Hello>(&mut server).await.unwrap_err(),
551 FrameError::Eof
552 ));
553 }
554
555 #[tokio::test]
556 async fn an_oversized_length_is_refused_before_allocating() {
557 let (mut client, mut server) = tokio::io::duplex(64 * 1024);
558 // Only the four-byte header is ever written: the reader must refuse on
559 // the header alone, without waiting for (or reserving) the body.
560 let claimed = AI_MAX_FRAME_BYTES as u32 + 1;
561 client.write_all(&claimed.to_be_bytes()).await.unwrap();
562 let err = read_frame::<_, Hello>(&mut server).await.unwrap_err();
563 assert!(
564 matches!(err, FrameError::TooLarge(n) if n == claimed),
565 "got {err:?}"
566 );
567 }
568
569 #[tokio::test]
570 async fn garbage_body_is_malformed_not_a_panic() {
571 let (mut client, mut server) = tokio::io::duplex(64 * 1024);
572 let body = b"not json at all";
573 client
574 .write_all(&(body.len() as u32).to_be_bytes())
575 .await
576 .unwrap();
577 client.write_all(body).await.unwrap();
578 assert!(matches!(
579 read_frame::<_, Hello>(&mut server).await.unwrap_err(),
580 FrameError::Malformed(_)
581 ));
582 }
583
584 #[tokio::test]
585 async fn greeting_and_response_tags_are_the_documented_wire_names() {
586 // Services in other languages match on these literals — a rename here
587 // silently breaks every one of them, so pin the encoding.
588 let welcome = serde_json::to_value(Greeting::Welcome {
589 worker_id: "w1".into(),
590 protocol: AI_PROTOCOL.into(),
591 })
592 .unwrap();
593 assert_eq!(welcome["type"], "welcome");
594 let rejected = serde_json::to_value(Greeting::Rejected {
595 code: RejectCode::Unauthorized,
596 message: "bad token".into(),
597 })
598 .unwrap();
599 assert_eq!(rejected["type"], "rejected");
600 assert_eq!(rejected["code"], "unauthorized");
601 let ok = serde_json::to_value(Response::Ok {
602 id: "1".into(),
603 school: "demo".into(),
604 payload: json!(null),
605 })
606 .unwrap();
607 assert_eq!(ok["status"], "ok");
608 }
609
610 #[tokio::test]
611 async fn api_frame_tags_are_the_documented_wire_names() {
612 // Same reason as above: other-language services match these literals.
613 // The tag is `outcome`, not `status` — `status` is the HTTP code.
614 let ok = serde_json::to_value(ApiResponse::Ok {
615 id: "1".into(),
616 school: "demo".into(),
617 status: 404,
618 body: json!(null),
619 })
620 .unwrap();
621 assert_eq!(ok["outcome"], "ok");
622 assert_eq!(ok["status"], 404);
623 let err = serde_json::to_value(ApiResponse::Err {
624 id: "1".into(),
625 school: "demo".into(),
626 code: "path_not_allowed".into(),
627 message: "nope".into(),
628 })
629 .unwrap();
630 assert_eq!(err["outcome"], "err");
631 assert_eq!(err["code"], "path_not_allowed");
632 }
633
634 #[tokio::test]
635 async fn capability_frame_tags_are_the_documented_wire_names() {
636 // The answer mirrors `Response` exactly — same `status` discriminator,
637 // same field names — so a service decodes both with one function.
638 // Pinned because other-language services match these literals.
639 let ok = serde_json::to_value(CapabilityResponse::Ok {
640 id: "1".into(),
641 school: "demo".into(),
642 payload: json!({ "written": 2 }),
643 })
644 .unwrap();
645 assert_eq!(ok["status"], "ok");
646 assert_eq!(ok["id"], "1");
647 assert_eq!(ok["school"], "demo");
648 assert_eq!(ok["payload"]["written"], 2);
649 let err = serde_json::to_value(CapabilityResponse::Err {
650 id: "1".into(),
651 school: "demo".into(),
652 code: "unknown_capability".into(),
653 message: "nope".into(),
654 })
655 .unwrap();
656 assert_eq!(err["status"], "err");
657 assert_eq!(err["code"], "unknown_capability");
658 assert_eq!(err["school"], "demo");
659 // A refusal carries no payload: there is no half-answer to read.
660 assert!(err.get("payload").is_none());
661 }
662
663 #[tokio::test]
664 async fn a_capability_request_needs_an_id_a_school_a_capability_and_a_payload() {
665 let call: CapabilityRequest = serde_json::from_value(json!({
666 "id": "01J",
667 "school": "demo",
668 "capability": "insight.summary.upsert",
669 "payload": { "rows": [] },
670 }))
671 .unwrap();
672 assert_eq!(call.capability, "insight.summary.upsert");
673 // Each of the three fields is required: a frame missing its
674 // capability names no operation to run, and a frame missing its
675 // school could only be answered out of a database nobody named.
676 for missing in ["id", "school", "capability", "payload"] {
677 let mut frame = json!({
678 "id": "01J",
679 "school": "demo",
680 "capability": "insight.pending.list",
681 "payload": {},
682 });
683 frame.as_object_mut().unwrap().remove(missing);
684 assert!(
685 serde_json::from_value::<CapabilityRequest>(frame).is_err(),
686 "a frame without `{missing}` must not parse"
687 );
688 }
689 }
690
691 #[tokio::test]
692 async fn the_client_initiated_shapes_do_not_parse_as_each_other() {
693 // Routing is by required field (`path` / `file` / `capability`), so
694 // this is the property that keeps a capability call from being
695 // mistaken for an api read — or for a blob read, which is what the
696 // frame would look like if `capability` were ever optional.
697 let call = json!({
698 "id": "01J",
699 "school": "demo",
700 "capability": "insight.pending.list",
701 "payload": {},
702 });
703 assert!(
704 serde_json::from_value::<CapabilityRequest>(call.clone()).is_ok(),
705 "the capability frame must parse as a capability call"
706 );
707 assert!(
708 serde_json::from_value::<ApiRequest>(call.clone()).is_err(),
709 "a capability call must not parse as an api read"
710 );
711 assert!(
712 serde_json::from_value::<BlobRequest>(call).is_err(),
713 "a capability call must not parse as a blob read"
714 );
715 }
716
717 #[tokio::test]
718 async fn an_api_request_needs_only_an_id_a_school_and_a_path() {
719 let bare: ApiRequest = serde_json::from_value(json!({
720 "id": "01J",
721 "school": "demo",
722 "path": "/users/me",
723 }))
724 .unwrap();
725 assert_eq!(bare.query, None);
726 assert_eq!(bare.on_behalf_of, None);
727 assert_eq!(bare.method, None);
728 // The school is required, not defaulted: a frame that names none has
729 // no school to fall back on and must not parse.
730 assert!(
731 serde_json::from_value::<ApiRequest>(json!({ "id": "01J", "path": "/users/me" }))
732 .is_err()
733 );
734
735 let full = ApiRequest {
736 id: "01J".into(),
737 school: "demo".into(),
738 path: "/notes".into(),
739 query: Some("limit=10".into()),
740 on_behalf_of: Some("user:abc".into()),
741 // Not validated at this layer — any string rides the wire.
742 method: Some("GET".into()),
743 };
744 let raw = serde_json::to_value(&full).unwrap();
745 assert_eq!(raw["school"], "demo");
746 assert_eq!(raw["path"], "/notes");
747 assert_eq!(raw["query"], "limit=10");
748 assert_eq!(raw["on_behalf_of"], "user:abc");
749 assert_eq!(raw["method"], "GET");
750 assert_eq!(serde_json::from_value::<ApiRequest>(raw).unwrap(), full);
751 }
752
753 #[tokio::test]
754 async fn blob_frame_tags_are_the_documented_wire_names() {
755 // Same reason as above: other-language services match these literals.
756 // The tag is `status` (as on `Response`), not `outcome` — a blob header
757 // carries no HTTP status for it to collide with.
758 let ok = serde_json::to_value(BlobResponse::Ok {
759 id: "1".into(),
760 school: "demo".into(),
761 name: "recap.pdf".into(),
762 content_type: "application/pdf".into(),
763 size: 204_800,
764 })
765 .unwrap();
766 assert_eq!(ok["status"], "ok");
767 assert_eq!(ok["size"], 204_800);
768 let err = serde_json::to_value(BlobResponse::Err {
769 id: "1".into(),
770 school: "demo".into(),
771 code: "not_found".into(),
772 message: "nope".into(),
773 })
774 .unwrap();
775 assert_eq!(err["status"], "err");
776 assert_eq!(err["code"], "not_found");
777
778 // `file` is what tells a blob request apart from an api read, so it is
779 // required; `on_behalf_of` is the only optional field.
780 let bare: BlobRequest = serde_json::from_value(json!({
781 "id": "01J", "school": "demo", "file": "01FILE",
782 }))
783 .unwrap();
784 assert_eq!(bare.on_behalf_of, None);
785 assert!(
786 serde_json::from_value::<BlobRequest>(json!({ "id": "01J", "school": "demo" }))
787 .is_err()
788 );
789 // The school is required here too.
790 assert!(
791 serde_json::from_value::<BlobRequest>(json!({ "id": "01J", "file": "01FILE" }))
792 .is_err()
793 );
794 // And the two shapes never parse as each other.
795 assert!(
796 serde_json::from_value::<ApiRequest>(json!({
797 "id": "01J", "school": "demo", "file": "01FILE",
798 }))
799 .is_err()
800 );
801 }
802
803 #[tokio::test]
804 async fn max_concurrent_is_optional_on_the_wire() {
805 let raw = json!({
806 "protocol": AI_PROTOCOL,
807 "service": "ocr",
808 "capabilities": ["ocr.extract"],
809 "token": "secret",
810 });
811 let hello: Hello = serde_json::from_value(raw).unwrap();
812 assert_eq!(hello.max_concurrent, None);
813 assert!(protocol_matches(&hello));
814 }
815
816 #[tokio::test]
817 async fn a_foreign_protocol_version_does_not_match() {
818 let mut h = hello();
819 h.protocol = "hab/99".into();
820 assert!(!protocol_matches(&h));
821 }
822}