Skip to main content

spoolframe_protocol/
codec.rs

1//! Frames: a big-endian `u32` length, then that many bytes of CBOR.
2
3use serde::Serialize;
4use serde::de::DeserializeOwned;
5use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
6
7/// The largest frame a peer accepts. Requests and replies are metadata; a
8/// page of items is far smaller. The limit keeps a peer from making the
9/// other allocate without bound.
10pub const MAX_FRAME: u32 = 1 << 20;
11
12/// RPC replies can span frames, but never exceed this aggregate budget.
13pub const MAX_REPLY: usize = 64 << 20;
14
15/// Encode without allocating past `limit`, including for an oversized value.
16pub fn encode_limited<T: Serialize>(value: &T, limit: usize) -> Result<Vec<u8>, CodecError> {
17    struct Bounded {
18        bytes: Vec<u8>,
19        limit: usize,
20        exceeded: bool,
21    }
22    impl std::io::Write for Bounded {
23        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
24            if bytes.len() > self.limit - self.bytes.len() {
25                self.exceeded = true;
26                return Err(std::io::Error::other("message limit"));
27            }
28            let needed = self.bytes.len() + bytes.len();
29            if needed > self.bytes.capacity() {
30                let capacity = needed
31                    .max(self.bytes.capacity().saturating_mul(2))
32                    .min(self.limit);
33                self.bytes
34                    .try_reserve_exact(capacity - self.bytes.len())
35                    .map_err(std::io::Error::other)?;
36            }
37            self.bytes.extend_from_slice(bytes);
38            Ok(bytes.len())
39        }
40        fn flush(&mut self) -> std::io::Result<()> {
41            Ok(())
42        }
43    }
44    let mut buffer = Bounded {
45        bytes: Vec::new(),
46        limit,
47        exceeded: false,
48    };
49    ciborium::into_writer(value, &mut buffer).map_err(|error| {
50        if buffer.exceeded {
51            CodecError::TooLarge {
52                len: limit as u64 + 1,
53            }
54        } else {
55            CodecError::Encode(error.to_string())
56        }
57    })?;
58    Ok(buffer.bytes)
59}
60
61/// RPC reply: total encoded length, followed by length-prefixed chunks.
62/// The complete message is checked before any bytes are written.
63pub async fn write_reply<W: AsyncWrite + Unpin, T: Serialize>(
64    writer: &mut W,
65    value: &T,
66) -> Result<(), CodecError> {
67    let encoded = encode_limited(value, MAX_REPLY)?;
68    writer.write_u64(encoded.len() as u64).await?;
69    for chunk in encoded.chunks(MAX_FRAME as usize) {
70        writer.write_u32(chunk.len() as u32).await?;
71        writer.write_all(chunk).await?;
72    }
73    Ok(())
74}
75
76pub async fn read_reply<R: AsyncRead + Unpin, T: DeserializeOwned>(
77    reader: &mut R,
78) -> Result<T, CodecError> {
79    read_reply_within(reader, MAX_REPLY).await
80}
81
82/// As [`read_reply`], refusing a reply longer than `max` (at most
83/// [`MAX_REPLY`]) once its length is read, before any of it is held: what
84/// a request whose answer has a smaller bound of its own reads it with.
85pub async fn read_reply_within<R: AsyncRead + Unpin, T: DeserializeOwned>(
86    reader: &mut R,
87    max: usize,
88) -> Result<T, CodecError> {
89    let mut bytes = Vec::new();
90    read_reply_bytes(reader, &mut bytes, max).await?;
91    decode(&bytes)
92}
93
94/// A reply's bytes, at most `max` of them, read into `bytes`: kept by the
95/// caller so a test can see what was held for a reply that stalls.
96pub(crate) async fn read_reply_bytes<R: AsyncRead + Unpin>(
97    reader: &mut R,
98    bytes: &mut Vec<u8>,
99    max: usize,
100) -> Result<(), CodecError> {
101    let length = reader.read_u64().await?;
102    if length == 0 || length > max.min(MAX_REPLY) as u64 {
103        return Err(CodecError::TooLarge { len: length });
104    }
105    let length = length as usize;
106    while bytes.len() < length {
107        let chunk = reader.read_u32().await?;
108        if chunk == 0 || chunk > MAX_FRAME || chunk as usize > length - bytes.len() {
109            return Err(CodecError::Decode("invalid RPC reply chunk length".into()));
110        }
111        // Held as it arrives, a step at a time: a reply that announces
112        // 64 MiB and sends little holds little (review 2026-10-12).
113        let mut left = chunk as usize;
114        while left > 0 {
115            let offset = bytes.len();
116            let step = left.min(READ_STEP);
117            if bytes.capacity() - offset < step {
118                // Doubled as it fills, so the copies stay linear, and never
119                // past the announced length.
120                let grow = offset.max(READ_STEP).min(length - offset);
121                bytes
122                    .try_reserve_exact(grow)
123                    .map_err(|e| CodecError::Decode(e.to_string()))?;
124            }
125            bytes.resize(offset + step, 0);
126            reader.read_exact(&mut bytes[offset..]).await?;
127            left -= step;
128        }
129    }
130    Ok(())
131}
132
133/// The step [`read_reply`] reads a reply in, and the least its buffer
134/// grows by: it holds at most twice what arrived, or this much past it.
135const READ_STEP: usize = 64 << 10;
136
137#[derive(Debug, thiserror::Error)]
138pub enum CodecError {
139    #[error("stream error: {0}")]
140    Io(#[from] std::io::Error),
141    #[error("message of {len} bytes exceeds its size limit")]
142    TooLarge { len: u64 },
143    #[error("cannot encode: {0}")]
144    Encode(String),
145    #[error("cannot decode: {0}")]
146    Decode(String),
147}
148
149/// Encode `value` as one frame's payload.
150pub fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>, CodecError> {
151    let mut bytes = Vec::new();
152    ciborium::into_writer(value, &mut bytes).map_err(|e| CodecError::Encode(e.to_string()))?;
153    Ok(bytes)
154}
155
156/// How many bytes `value` encodes to, without keeping them: what a page's
157/// budget is measured against.
158pub fn encoded_len<T: Serialize>(value: &T) -> Result<usize, CodecError> {
159    struct Counting(usize);
160    impl std::io::Write for Counting {
161        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
162            self.0 += bytes.len();
163            Ok(bytes.len())
164        }
165        fn flush(&mut self) -> std::io::Result<()> {
166            Ok(())
167        }
168    }
169    let mut counted = Counting(0);
170    ciborium::into_writer(value, &mut counted).map_err(|e| CodecError::Encode(e.to_string()))?;
171    Ok(counted.0)
172}
173
174/// Decode one frame's payload.
175pub fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, CodecError> {
176    ciborium::from_reader(bytes).map_err(|e| CodecError::Decode(e.to_string()))
177}
178
179/// For tests: `value` comes back from a frame as it went in.
180#[cfg(test)]
181pub(crate) fn round_trip<T: Serialize + DeserializeOwned + PartialEq + std::fmt::Debug>(value: T) {
182    let bytes = encode(&value).unwrap();
183    assert_eq!(decode::<T>(&bytes).unwrap(), value);
184}
185
186/// The most characters of a request's `type` that [`request_type`] and
187/// [`rpc_request_type`] read: a client chooses it, up to a whole frame of
188/// it, and every type the protocol has is far shorter.
189pub const MAX_REQUEST_TYPE: usize = 64;
190
191/// The `type` of a request payload, even one this build cannot decode, so
192/// the server can name it in [`crate::Error::Unsupported`].
193pub fn request_type(envelope: &[u8]) -> Option<String> {
194    scan::text_at(envelope, &["request", "type"])
195}
196
197/// Extract a request tag from the mandatory RPC wrapper, including unknown tags.
198///
199/// The server names every request with this before it is authenticated, so
200/// it reads the frame only as far as the tag and keeps nothing of what it
201/// steps over: decoding the frame whole would cost about 50 times its
202/// size in heap.
203pub fn rpc_request_type(bytes: &[u8]) -> Option<String> {
204    scan::text_at(bytes, &["envelope", "request", "type"])
205}
206
207/// Reading one text value out of CBOR without decoding what is around it.
208mod scan {
209    use ciborium_ll::{Decoder, Header};
210
211    type Reader<'a> = Decoder<&'a [u8]>;
212
213    /// How deep arrays and maps that are stepped over may nest: ciborium's
214    /// own limit, so whatever the typed decode reads can be named.
215    const DEPTH: usize = 256;
216
217    /// The bytes read at a time from a text or byte string.
218    const CHUNK: usize = 64;
219
220    /// The text under `path`, a key in each of the nested maps in turn: at
221    /// most [`super::MAX_REQUEST_TYPE`] characters of it.
222    pub(super) fn text_at(bytes: &[u8], path: &[&str]) -> Option<String> {
223        let mut reader = Decoder::from(bytes);
224        for key in path {
225            enter(&mut reader, key)?;
226        }
227        match header(&mut reader)? {
228            Header::Text(len) => text(&mut reader, len, super::MAX_REQUEST_TYPE),
229            _ => None,
230        }
231    }
232
233    /// The next header that is not a tag: a tag only annotates the item
234    /// after it.
235    fn header(reader: &mut Reader<'_>) -> Option<Header> {
236        loop {
237            match reader.pull().ok()? {
238                Header::Tag(_) => continue,
239                header => return Some(header),
240            }
241        }
242    }
243
244    /// Read into the map that comes next, up to the value of `key` in it.
245    fn enter(reader: &mut Reader<'_>, key: &str) -> Option<()> {
246        let Header::Map(len) = header(reader)? else {
247            return None;
248        };
249        let mut left = len;
250        loop {
251            match &mut left {
252                Some(0) => return None,
253                Some(n) => *n -= 1,
254                None => {}
255            }
256            let found = match header(reader)? {
257                Header::Break if len.is_none() => return None,
258                // One character past the key is enough to tell it apart.
259                Header::Text(n) => text(reader, n, key.chars().count() + 1)?.as_str() == key,
260                other => {
261                    skip(reader, other, DEPTH)?;
262                    false
263                }
264            };
265            if found {
266                return Some(());
267            }
268            let value = header(reader)?;
269            skip(reader, value, DEPTH)?;
270        }
271    }
272
273    /// The first `max` characters of the text whose header was `len`; the
274    /// rest of it is read and dropped.
275    fn text(reader: &mut Reader<'_>, len: Option<usize>, max: usize) -> Option<String> {
276        let mut kept = String::new();
277        let mut count = 0;
278        let mut chunk = [0; CHUNK];
279        let mut segments = reader.text(len);
280        while let Some(mut segment) = segments.pull().ok()? {
281            while let Some(part) = segment.pull(&mut chunk).ok()? {
282                for c in part.chars().take(max - count) {
283                    kept.push(c);
284                    count += 1;
285                }
286            }
287        }
288        Some(kept)
289    }
290
291    /// Step over the item whose header was `header`, keeping none of it.
292    fn skip(reader: &mut Reader<'_>, header: Header, depth: usize) -> Option<()> {
293        let depth = depth.checked_sub(1)?;
294        match header {
295            Header::Text(len) => drop_text(reader, len),
296            Header::Bytes(len) => drop_bytes(reader, len),
297            Header::Array(len) => items(reader, len, depth),
298            Header::Map(Some(len)) => items(reader, Some(len.checked_mul(2)?), depth),
299            Header::Map(None) => items(reader, None, depth),
300            Header::Break => None,
301            // A number or a simple value is all header.
302            _ => Some(()),
303        }
304    }
305
306    /// Step over `len` items, or up to a break when `len` is `None`.
307    fn items(reader: &mut Reader<'_>, len: Option<usize>, depth: usize) -> Option<()> {
308        match len {
309            // Each item is at least a byte, so a claimed length past the
310            // frame ends at the frame's end.
311            Some(len) => {
312                for _ in 0..len {
313                    let item = header(reader)?;
314                    skip(reader, item, depth)?;
315                }
316            }
317            None => loop {
318                match header(reader)? {
319                    Header::Break => break,
320                    item => skip(reader, item, depth)?,
321                }
322            },
323        }
324        Some(())
325    }
326
327    // Kept out of `skip`, so a deep nest does not carry a buffer per level.
328    #[inline(never)]
329    fn drop_text(reader: &mut Reader<'_>, len: Option<usize>) -> Option<()> {
330        let mut chunk = [0; CHUNK];
331        let mut segments = reader.text(len);
332        while let Some(mut segment) = segments.pull().ok()? {
333            while segment.pull(&mut chunk).ok()?.is_some() {}
334        }
335        Some(())
336    }
337
338    #[inline(never)]
339    fn drop_bytes(reader: &mut Reader<'_>, len: Option<usize>) -> Option<()> {
340        let mut chunk = [0; CHUNK];
341        let mut segments = reader.bytes(len);
342        while let Some(mut segment) = segments.pull().ok()? {
343            while segment.pull(&mut chunk).ok()?.is_some() {}
344        }
345        Some(())
346    }
347}
348
349/// Write `value` as one frame. One over [`MAX_FRAME`] is refused before
350/// anything is written, so the writer can send something else instead.
351pub async fn write_frame<W, T>(writer: &mut W, value: &T) -> Result<(), CodecError>
352where
353    W: AsyncWrite + Unpin,
354    T: Serialize,
355{
356    let bytes = encode(value)?;
357    let len = u32::try_from(bytes.len())
358        .ok()
359        .filter(|&len| len <= MAX_FRAME)
360        .ok_or(CodecError::TooLarge {
361            len: bytes.len() as u64,
362        })?;
363    writer.write_all(&len.to_be_bytes()).await?;
364    writer.write_all(&bytes).await?;
365    Ok(())
366}
367
368/// Read one frame's payload, refusing an oversized one before reading it.
369pub async fn read_frame_bytes<R>(reader: &mut R) -> Result<Vec<u8>, CodecError>
370where
371    R: AsyncRead + Unpin,
372{
373    read_frame_bytes_within(reader, MAX_FRAME).await
374}
375
376/// As [`read_frame_bytes`], refusing a frame longer than `max` (at most
377/// [`MAX_FRAME`]) before anything is allocated for it.
378pub async fn read_frame_bytes_within<R>(reader: &mut R, max: u32) -> Result<Vec<u8>, CodecError>
379where
380    R: AsyncRead + Unpin,
381{
382    let len = reader.read_u32().await?;
383    if len > max.min(MAX_FRAME) {
384        return Err(CodecError::TooLarge { len: len.into() });
385    }
386    let mut bytes = vec![0; len as usize];
387    reader.read_exact(&mut bytes).await?;
388    Ok(bytes)
389}
390
391pub async fn read_frame<R, T>(reader: &mut R) -> Result<T, CodecError>
392where
393    R: AsyncRead + Unpin,
394    T: DeserializeOwned,
395{
396    decode(&read_frame_bytes(reader).await?)
397}
398
399/// As [`read_frame`], refusing a frame longer than `max`.
400pub async fn read_frame_within<R, T>(reader: &mut R, max: u32) -> Result<T, CodecError>
401where
402    R: AsyncRead + Unpin,
403    T: DeserializeOwned,
404{
405    decode(&read_frame_bytes_within(reader, max).await?)
406}