objectiveai_sdk/binary_frame.rs
1//! The binary wire frame: `[u32 BE header length][JSON header][raw
2//! payload bytes]`, all in ONE WebSocket binary message.
3//!
4//! Bulk payloads (laboratory-transfer chunks) never ride base64 inside
5//! JSON — the typed envelope a text frame would carry serializes
6//! UNCHANGED as the header (its `data` field is `#[serde(skip)]`), and
7//! the raw bytes follow out of band. Correlation is exactly the text
8//! frame's: the header holds the same ids. A receiver reads the
9//! length, parses the header with the same serde types it already
10//! uses, and attaches the remaining bytes to the chunk field.
11//!
12//! Std-only and transport-agnostic — both WebSocket hops (daemon ↔
13//! laboratory host, API ↔ daemon reverse channel) share it.
14
15/// One decoded-or-encoded wire frame: JSON text for every ordinary
16/// message, the binary sandwich for chunk-bearing ones.
17#[derive(Debug, Clone)]
18pub enum WireFrame {
19 Text(String),
20 Binary(Vec<u8>),
21}
22
23/// Build the binary sandwich. `header` is the frame's full JSON
24/// envelope (minus the payload bytes, which its serde representation
25/// skips); `payload` may be empty (chunk variants are ALWAYS binary,
26/// content notwithstanding — the framing is variant-keyed, never
27/// content-sniffed).
28pub fn encode(header: &str, payload: &[u8]) -> Vec<u8> {
29 let header = header.as_bytes();
30 let mut frame = Vec::with_capacity(4 + header.len() + payload.len());
31 frame.extend_from_slice(&(header.len() as u32).to_be_bytes());
32 frame.extend_from_slice(header);
33 frame.extend_from_slice(payload);
34 frame
35}
36
37/// Split a binary sandwich back into `(header JSON, payload bytes)`.
38/// `None` on anything malformed — a short frame, a header length past
39/// the end, or a non-UTF-8 header. Malformed frames are DROPPED by
40/// receivers (forward-compat posture, mirroring unknown text frames).
41pub fn decode(frame: &[u8]) -> Option<(&str, &[u8])> {
42 let len_bytes: [u8; 4] = frame.get(..4)?.try_into().ok()?;
43 let header_len = u32::from_be_bytes(len_bytes) as usize;
44 let header_end = 4usize.checked_add(header_len)?;
45 let header = std::str::from_utf8(frame.get(4..header_end)?).ok()?;
46 let payload = frame.get(header_end..)?;
47 Some((header, payload))
48}