Skip to main content

podbox_protocol/
framing.rs

1use std::io::{self, Read, Write};
2
3use serde::Serialize;
4
5/// Write a length-prefixed JSON frame.
6pub fn write_frame<W: Write>(w: &mut W, msg: &impl Serialize) -> io::Result<()> {
7    let json = serde_json::to_vec(msg)?;
8    if json.len() > MAX_FRAME_SIZE {
9        return Err(io::Error::new(
10            io::ErrorKind::InvalidInput,
11            format!(
12                "frame too large: {} bytes (max {MAX_FRAME_SIZE})",
13                json.len()
14            ),
15        ));
16    }
17    let len = u32::try_from(json.len())
18        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "frame payload exceeds 4 GiB"))?
19        .to_be_bytes();
20    w.write_all(&len)?;
21    w.write_all(&json)?;
22    w.flush()?;
23    Ok(())
24}
25
26/// Maximum frame size: 16 MiB.
27const MAX_FRAME_SIZE: usize = 16 * 1024 * 1024;
28
29/// Read a length-prefixed JSON frame.
30pub fn read_frame<R: Read>(r: &mut R) -> io::Result<Option<Vec<u8>>> {
31    let mut len_buf = [0u8; 4];
32    match r.read_exact(&mut len_buf) {
33        Ok(()) => {}
34        Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
35        Err(e) => return Err(e),
36    }
37    let len = u32::from_be_bytes(len_buf) as usize;
38    if len > MAX_FRAME_SIZE {
39        return Err(io::Error::new(
40            io::ErrorKind::InvalidData,
41            format!("frame too large: {len} bytes (max {MAX_FRAME_SIZE})"),
42        ));
43    }
44    let mut buf = vec![0u8; len];
45    r.read_exact(&mut buf)?;
46    Ok(Some(buf))
47}
48
49/// Incremental frame reader that survives read timeouts.
50///
51/// [`read_frame`] uses `read_exact`, which discards bytes it already read when
52/// a timeout fires mid-frame. The stream is then misaligned: the next read
53/// parses payload bytes as a length prefix. `FrameReader` keeps the partial
54/// frame, so a timeout returns `WouldBlock`/`TimedOut` with nothing lost and
55/// the caller can retry, or give up once [`FrameReader::stalled_for`] is long.
56#[derive(Debug, Default)]
57pub struct FrameReader {
58    prefix: [u8; 4],
59    prefix_filled: usize,
60    body: Vec<u8>,
61    body_filled: usize,
62    body_len: Option<usize>,
63    /// When the first byte of the frame in progress arrived.
64    started: Option<std::time::Instant>,
65}
66
67/// What a [`FrameReader::read`] call produced.
68#[derive(Debug, PartialEq, Eq)]
69pub enum FrameRead {
70    /// A complete frame payload.
71    Frame(Vec<u8>),
72    /// The peer closed the stream at a frame boundary.
73    Eof,
74}
75
76impl FrameReader {
77    pub fn new() -> Self {
78        Self::default()
79    }
80
81    /// True when part of a frame has been read and the rest is still due.
82    pub fn in_progress(&self) -> bool {
83        self.started.is_some()
84    }
85
86    /// Time since the first byte of the frame in progress, if one is in progress.
87    pub fn stalled_for(&self) -> Option<std::time::Duration> {
88        self.started.map(|t| t.elapsed())
89    }
90
91    /// Read until one frame is complete. A timeout returns `Err` and keeps the
92    /// partial frame, so a later call resumes exactly where this one stopped.
93    pub fn read<R: Read>(&mut self, r: &mut R) -> io::Result<FrameRead> {
94        while self.prefix_filled < 4 {
95            let n = r.read(&mut self.prefix[self.prefix_filled..])?;
96            if n == 0 {
97                return if self.prefix_filled == 0 {
98                    Ok(FrameRead::Eof)
99                } else {
100                    Err(io::Error::from(io::ErrorKind::UnexpectedEof))
101                };
102            }
103            self.started.get_or_insert_with(std::time::Instant::now);
104            self.prefix_filled += n;
105        }
106        let len = match self.body_len {
107            Some(len) => len,
108            None => {
109                let len = u32::from_be_bytes(self.prefix) as usize;
110                if len > MAX_FRAME_SIZE {
111                    return Err(io::Error::new(
112                        io::ErrorKind::InvalidData,
113                        format!("frame too large: {len} bytes (max {MAX_FRAME_SIZE})"),
114                    ));
115                }
116                self.body = vec![0u8; len];
117                self.body_len = Some(len);
118                len
119            }
120        };
121        while self.body_filled < len {
122            let n = r.read(&mut self.body[self.body_filled..])?;
123            if n == 0 {
124                return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
125            }
126            self.body_filled += n;
127        }
128        let frame = std::mem::take(&mut self.body);
129        *self = Self::default();
130        Ok(FrameRead::Frame(frame))
131    }
132}