Skip to main content

objectiveai_db_proxy/
frame.rs

1//! The proxy↔host wire format.
2//!
3//! Defined HERE, and deliberately NOT in the SDK. The format is a
4//! private contract between two binaries; the laboratory host declares
5//! its own copy of it. Publishing it through the SDK would make every
6//! adjustment a breaking change for every SDK consumer, none of whom
7//! have any business speaking it.
8//!
9//! Every message on the socket is a WebSocket BINARY frame:
10//!
11//! ```text
12//! [tag: u8][id: u32 big-endian][payload…]
13//! ```
14//!
15//! | tag | frame   | payload | direction   |
16//! |-----|---------|---------|-------------|
17//! | 0   | `Open`  | none    | proxy → host |
18//! | 1   | `Data`  | bytes   | both        |
19//! | 2   | `Close` | none    | both        |
20//!
21//! There are no text frames: one uniform shape means neither end needs
22//! a second parser.
23//!
24//! Payloads are OPAQUE. pgwire is never parsed here, so TLS
25//! negotiation and every protocol extension cross untouched, and a
26//! Postgres message larger than one frame simply spans several — both
27//! ends reassemble from a byte stream, exactly as they would from a
28//! socket.
29
30use axum::body::Bytes;
31
32pub const TAG_OPEN: u8 = 0;
33pub const TAG_DATA: u8 = 1;
34pub const TAG_CLOSE: u8 = 2;
35
36/// `tag` + `id`. Five bytes, which is already noise beside a WebSocket
37/// frame's own 2–14 byte header — the reason `id` is a comfortable
38/// `u32` instead of a `u16` with wraparound bookkeeping.
39pub const HEADER_LEN: usize = 5;
40
41#[derive(Debug)]
42pub enum Frame {
43    Open { id: u32 },
44    Data { id: u32, payload: Bytes },
45    Close { id: u32 },
46}
47
48impl Frame {
49    /// Decode one binary message. `None` for anything malformed or
50    /// tagged unknown — a frame this build cannot read is not one it
51    /// can route, and the socket carries other streams that can.
52    ///
53    /// `Bytes` in, `Bytes` out: the payload is a view into the same
54    /// allocation the socket delivered, so demuxing costs no copy.
55    pub fn decode(bytes: Bytes) -> Option<Self> {
56        if bytes.len() < HEADER_LEN {
57            return None;
58        }
59        let id = u32::from_be_bytes([bytes[1], bytes[2], bytes[3], bytes[4]]);
60        match bytes[0] {
61            TAG_OPEN => Some(Frame::Open { id }),
62            TAG_DATA => Some(Frame::Data {
63                id,
64                payload: bytes.slice(HEADER_LEN..),
65            }),
66            TAG_CLOSE => Some(Frame::Close { id }),
67            _ => None,
68        }
69    }
70}
71
72/// Frame a freshly-read chunk. Takes a slice rather than `Frame::Data`
73/// because this is the hot path — going through the enum would buy an
74/// extra copy of every byte the database ever sends.
75pub fn encode_data(id: u32, payload: &[u8]) -> Bytes {
76    let mut out = Vec::with_capacity(HEADER_LEN + payload.len());
77    out.push(TAG_DATA);
78    out.extend_from_slice(&id.to_be_bytes());
79    out.extend_from_slice(payload);
80    Bytes::from(out)
81}
82
83pub fn encode_open(id: u32) -> Bytes {
84    encode_control(TAG_OPEN, id)
85}
86
87pub fn encode_close(id: u32) -> Bytes {
88    encode_control(TAG_CLOSE, id)
89}
90
91fn encode_control(tag: u8, id: u32) -> Bytes {
92    let mut out = [0u8; HEADER_LEN];
93    out[0] = tag;
94    out[1..].copy_from_slice(&id.to_be_bytes());
95    Bytes::copy_from_slice(&out)
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn control_frames_round_trip() {
104        assert!(matches!(
105            Frame::decode(encode_open(1)),
106            Some(Frame::Open { id: 1 })
107        ));
108        assert!(matches!(
109            Frame::decode(encode_close(u32::MAX)),
110            Some(Frame::Close { id: u32::MAX })
111        ));
112    }
113
114    #[test]
115    fn data_frames_round_trip() {
116        let bytes = encode_data(0x0102_0304, b"pgwire");
117        assert_eq!(bytes.len(), HEADER_LEN + 6);
118        match Frame::decode(bytes) {
119            Some(Frame::Data { id, payload }) => {
120                assert_eq!(id, 0x0102_0304);
121                assert_eq!(&payload[..], b"pgwire");
122            }
123            other => panic!("expected Data, got {other:?}"),
124        }
125    }
126
127    /// An empty `Data` payload is legal and distinct from `Close`: a
128    /// zero-length write is not an end of stream.
129    #[test]
130    fn empty_data_is_not_close() {
131        match Frame::decode(encode_data(7, b"")) {
132            Some(Frame::Data { id: 7, payload }) => assert!(payload.is_empty()),
133            other => panic!("expected empty Data, got {other:?}"),
134        }
135    }
136
137    #[test]
138    fn short_and_unknown_frames_are_rejected() {
139        assert!(Frame::decode(Bytes::from_static(&[TAG_DATA, 0, 0, 0])).is_none());
140        assert!(Frame::decode(Bytes::new()).is_none());
141        assert!(Frame::decode(Bytes::from_static(&[200, 0, 0, 0, 1])).is_none());
142    }
143}