Skip to main content

icedwright_protocol/
frame.rs

1//! Framing: a 4-byte little-endian payload length, a 1-byte kind, then the payload.
2
3use std::borrow::Cow;
4
5use serde::{Deserialize, Serialize};
6
7use crate::error::ProtocolError;
8
9/// Bytes before the payload.
10pub const HEADER_LEN: usize = 5;
11
12/// The largest payload either end accepts.
13pub const MAX_FRAME_BYTES: u64 = 64 * 1024 * 1024;
14
15/// What a frame's payload holds.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum FrameKind {
18    /// A JSON message.
19    Json,
20    /// The attachment announced by the JSON frame before it.
21    Binary,
22}
23
24impl FrameKind {
25    const fn byte(self) -> u8 {
26        match self {
27            FrameKind::Json => 0,
28            FrameKind::Binary => 1,
29        }
30    }
31
32    fn from_byte(byte: u8) -> Result<Self, ProtocolError> {
33        match byte {
34            0 => Ok(FrameKind::Json),
35            1 => Ok(FrameKind::Binary),
36            other => Err(ProtocolError::Malformed(format!(
37                "unknown frame kind {other}"
38            ))),
39        }
40    }
41}
42
43/// The attachment a JSON frame announces; the binary frame follows it immediately.
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45pub struct Attachment {
46    /// The binary payload's length.
47    pub bytes: u64,
48    /// Its media type, such as `image/x-rgba`.
49    pub media: Cow<'static, str>,
50}
51
52/// One frame.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct WireFrame {
55    /// What the payload holds.
56    pub kind: FrameKind,
57    /// The payload.
58    pub payload: Vec<u8>,
59}
60
61impl WireFrame {
62    /// A JSON frame.
63    #[must_use]
64    pub fn json(payload: Vec<u8>) -> Self {
65        Self {
66            kind: FrameKind::Json,
67            payload,
68        }
69    }
70
71    /// A binary frame.
72    #[must_use]
73    pub fn binary(payload: Vec<u8>) -> Self {
74        Self {
75            kind: FrameKind::Binary,
76            payload,
77        }
78    }
79
80    /// The frame as bytes, header first.
81    pub fn encode(&self) -> Result<Vec<u8>, ProtocolError> {
82        let length = u64::try_from(self.payload.len()).unwrap_or(u64::MAX);
83        let header_length = u32::try_from(length)
84            .ok()
85            .filter(|_| length <= MAX_FRAME_BYTES)
86            .ok_or(ProtocolError::FrameTooLarge(length))?;
87        let mut bytes = Vec::with_capacity(HEADER_LEN + self.payload.len());
88        bytes.extend_from_slice(&header_length.to_le_bytes());
89        bytes.push(self.kind.byte());
90        bytes.extend_from_slice(&self.payload);
91        Ok(bytes)
92    }
93
94    /// Reads a header: the kind and the payload length that follows it.
95    pub fn decode_header(header: [u8; HEADER_LEN]) -> Result<(FrameKind, usize), ProtocolError> {
96        let [a, b, c, d, kind] = header;
97        let length = u32::from_le_bytes([a, b, c, d]);
98        if u64::from(length) > MAX_FRAME_BYTES {
99            return Err(ProtocolError::FrameTooLarge(u64::from(length)));
100        }
101        let length =
102            usize::try_from(length).map_err(|_| ProtocolError::FrameTooLarge(u64::from(length)))?;
103        Ok((FrameKind::from_byte(kind)?, length))
104    }
105
106    /// Reads one frame from the front of `bytes`, returning it and how many bytes it took,
107    /// or `None` when `bytes` ends before the frame does.
108    pub fn decode(bytes: &[u8]) -> Result<Option<(WireFrame, usize)>, ProtocolError> {
109        let Some((header, rest)) = bytes.split_first_chunk::<HEADER_LEN>() else {
110            return Ok(None);
111        };
112        let (kind, length) = Self::decode_header(*header)?;
113        let Some(payload) = rest.get(..length) else {
114            return Ok(None);
115        };
116        let frame = WireFrame {
117            kind,
118            payload: payload.to_vec(),
119        };
120        Ok(Some((frame, HEADER_LEN + length)))
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127
128    #[test]
129    fn frames_round_trip() -> Result<(), ProtocolError> {
130        for frame in [
131            WireFrame::json(br#"{"id":1}"#.to_vec()),
132            WireFrame::binary(vec![0, 1, 2, 255]),
133            WireFrame::json(Vec::new()),
134        ] {
135            let bytes = frame.encode()?;
136            assert_eq!(bytes.len(), HEADER_LEN + frame.payload.len());
137            assert_eq!(WireFrame::decode(&bytes)?, Some((frame, bytes.len())));
138        }
139        Ok(())
140    }
141
142    #[test]
143    fn a_json_frame_with_its_attachment_decodes_in_order() -> Result<(), ProtocolError> {
144        let announce =
145            WireFrame::json(br#"{"attachment":{"bytes":3,"media":"image/x-rgba"}}"#.to_vec());
146        let attachment = WireFrame::binary(vec![9, 8, 7]);
147        let mut stream = announce.encode()?;
148        stream.extend(attachment.encode()?);
149        let Some((first, used)) = WireFrame::decode(&stream)? else {
150            panic!("first frame incomplete");
151        };
152        assert_eq!(first, announce);
153        assert_eq!(
154            WireFrame::decode(&stream[used..])?.map(|f| f.0),
155            Some(attachment)
156        );
157        Ok(())
158    }
159
160    #[test]
161    fn truncated_frames_wait_for_more() -> Result<(), ProtocolError> {
162        let bytes = WireFrame::json(b"hello".to_vec()).encode()?;
163        for end in 0..bytes.len() {
164            assert_eq!(WireFrame::decode(&bytes[..end])?, None, "{end}");
165        }
166        Ok(())
167    }
168
169    #[test]
170    fn oversized_and_unknown_frames_are_refused() {
171        let too_long = u32::try_from(MAX_FRAME_BYTES + 1).unwrap_or(u32::MAX);
172        let [a, b, c, d] = too_long.to_le_bytes();
173        assert_eq!(
174            WireFrame::decode_header([a, b, c, d, 0]),
175            Err(ProtocolError::FrameTooLarge(MAX_FRAME_BYTES + 1))
176        );
177        assert!(matches!(
178            WireFrame::decode_header([0, 0, 0, 0, 7]),
179            Err(ProtocolError::Malformed(_))
180        ));
181    }
182
183    #[test]
184    fn attachments_serialise_as_the_plan_shows() -> Result<(), serde_json::Error> {
185        let attachment = Attachment {
186            bytes: 4,
187            media: Cow::Borrowed("image/x-rgba"),
188        };
189        assert_eq!(
190            serde_json::to_string(&attachment)?,
191            r#"{"bytes":4,"media":"image/x-rgba"}"#
192        );
193        Ok(())
194    }
195}