objectiveai_db_proxy/
frame.rs1use axum::body::Bytes;
31
32pub const TAG_OPEN: u8 = 0;
33pub const TAG_DATA: u8 = 1;
34pub const TAG_CLOSE: u8 = 2;
35
36pub 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 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
72pub 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 #[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}