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/// The most characters of a request's `type` that [`request_type`] and
180/// [`rpc_request_type`] read: a client chooses it, up to a whole frame of
181/// it, and every type the protocol has is far shorter (C-12).
182pub const MAX_REQUEST_TYPE: usize = 64;
183
184/// The `type` of a request payload, even one this build cannot decode, so
185/// the server can name it in [`crate::Error::Unsupported`].
186pub fn request_type(envelope: &[u8]) -> Option<String> {
187    scan::text_at(envelope, &["request", "type"])
188}
189
190/// Extract a request tag from the mandatory RPC wrapper, including unknown tags.
191///
192/// The server names every request with this before it is authenticated, so
193/// it reads the frame only as far as the tag and keeps nothing of what it
194/// steps over (finding 50): decoding the frame whole cost about 50 times
195/// its size in heap.
196pub fn rpc_request_type(bytes: &[u8]) -> Option<String> {
197    scan::text_at(bytes, &["envelope", "request", "type"])
198}
199
200/// Reading one text value out of CBOR without decoding what is around it.
201mod scan {
202    use ciborium_ll::{Decoder, Header};
203
204    type Reader<'a> = Decoder<&'a [u8]>;
205
206    /// How deep arrays and maps that are stepped over may nest: ciborium's
207    /// own limit, so whatever the typed decode reads can be named.
208    const DEPTH: usize = 256;
209
210    /// The bytes read at a time from a text or byte string.
211    const CHUNK: usize = 64;
212
213    /// The text under `path`, a key in each of the nested maps in turn: at
214    /// most [`super::MAX_REQUEST_TYPE`] characters of it.
215    pub(super) fn text_at(bytes: &[u8], path: &[&str]) -> Option<String> {
216        let mut reader = Decoder::from(bytes);
217        for key in path {
218            enter(&mut reader, key)?;
219        }
220        match header(&mut reader)? {
221            Header::Text(len) => text(&mut reader, len, super::MAX_REQUEST_TYPE),
222            _ => None,
223        }
224    }
225
226    /// The next header that is not a tag: a tag only annotates the item
227    /// after it.
228    fn header(reader: &mut Reader<'_>) -> Option<Header> {
229        loop {
230            match reader.pull().ok()? {
231                Header::Tag(_) => continue,
232                header => return Some(header),
233            }
234        }
235    }
236
237    /// Read into the map that comes next, up to the value of `key` in it.
238    fn enter(reader: &mut Reader<'_>, key: &str) -> Option<()> {
239        let Header::Map(len) = header(reader)? else {
240            return None;
241        };
242        let mut left = len;
243        loop {
244            match &mut left {
245                Some(0) => return None,
246                Some(n) => *n -= 1,
247                None => {}
248            }
249            let found = match header(reader)? {
250                Header::Break if len.is_none() => return None,
251                // One character past the key is enough to tell it apart.
252                Header::Text(n) => text(reader, n, key.chars().count() + 1)?.as_str() == key,
253                other => {
254                    skip(reader, other, DEPTH)?;
255                    false
256                }
257            };
258            if found {
259                return Some(());
260            }
261            let value = header(reader)?;
262            skip(reader, value, DEPTH)?;
263        }
264    }
265
266    /// The first `max` characters of the text whose header was `len`; the
267    /// rest of it is read and dropped.
268    fn text(reader: &mut Reader<'_>, len: Option<usize>, max: usize) -> Option<String> {
269        let mut kept = String::new();
270        let mut count = 0;
271        let mut chunk = [0; CHUNK];
272        let mut segments = reader.text(len);
273        while let Some(mut segment) = segments.pull().ok()? {
274            while let Some(part) = segment.pull(&mut chunk).ok()? {
275                for c in part.chars().take(max - count) {
276                    kept.push(c);
277                    count += 1;
278                }
279            }
280        }
281        Some(kept)
282    }
283
284    /// Step over the item whose header was `header`, keeping none of it.
285    fn skip(reader: &mut Reader<'_>, header: Header, depth: usize) -> Option<()> {
286        let depth = depth.checked_sub(1)?;
287        match header {
288            Header::Text(len) => drop_text(reader, len),
289            Header::Bytes(len) => drop_bytes(reader, len),
290            Header::Array(len) => items(reader, len, depth),
291            Header::Map(Some(len)) => items(reader, Some(len.checked_mul(2)?), depth),
292            Header::Map(None) => items(reader, None, depth),
293            Header::Break => None,
294            // A number or a simple value is all header.
295            _ => Some(()),
296        }
297    }
298
299    /// Step over `len` items, or up to a break when `len` is `None`.
300    fn items(reader: &mut Reader<'_>, len: Option<usize>, depth: usize) -> Option<()> {
301        match len {
302            // Each item is at least a byte, so a claimed length past the
303            // frame ends at the frame's end.
304            Some(len) => {
305                for _ in 0..len {
306                    let item = header(reader)?;
307                    skip(reader, item, depth)?;
308                }
309            }
310            None => loop {
311                match header(reader)? {
312                    Header::Break => break,
313                    item => skip(reader, item, depth)?,
314                }
315            },
316        }
317        Some(())
318    }
319
320    // Kept out of `skip`, so a deep nest does not carry a buffer per level.
321    #[inline(never)]
322    fn drop_text(reader: &mut Reader<'_>, len: Option<usize>) -> Option<()> {
323        let mut chunk = [0; CHUNK];
324        let mut segments = reader.text(len);
325        while let Some(mut segment) = segments.pull().ok()? {
326            while segment.pull(&mut chunk).ok()?.is_some() {}
327        }
328        Some(())
329    }
330
331    #[inline(never)]
332    fn drop_bytes(reader: &mut Reader<'_>, len: Option<usize>) -> Option<()> {
333        let mut chunk = [0; CHUNK];
334        let mut segments = reader.bytes(len);
335        while let Some(mut segment) = segments.pull().ok()? {
336            while segment.pull(&mut chunk).ok()?.is_some() {}
337        }
338        Some(())
339    }
340}
341
342/// Write `value` as one frame. One over [`MAX_FRAME`] is refused before
343/// anything is written, so the writer can send something else instead.
344pub async fn write_frame<W, T>(writer: &mut W, value: &T) -> Result<(), CodecError>
345where
346    W: AsyncWrite + Unpin,
347    T: Serialize,
348{
349    let bytes = encode(value)?;
350    let len = u32::try_from(bytes.len())
351        .ok()
352        .filter(|&len| len <= MAX_FRAME)
353        .ok_or(CodecError::TooLarge {
354            len: bytes.len() as u64,
355        })?;
356    writer.write_all(&len.to_be_bytes()).await?;
357    writer.write_all(&bytes).await?;
358    Ok(())
359}
360
361/// Read one frame's payload, refusing an oversized one before reading it.
362pub async fn read_frame_bytes<R>(reader: &mut R) -> Result<Vec<u8>, CodecError>
363where
364    R: AsyncRead + Unpin,
365{
366    read_frame_bytes_within(reader, MAX_FRAME).await
367}
368
369/// As [`read_frame_bytes`], refusing a frame longer than `max` (at most
370/// [`MAX_FRAME`]) before anything is allocated for it.
371pub async fn read_frame_bytes_within<R>(reader: &mut R, max: u32) -> Result<Vec<u8>, CodecError>
372where
373    R: AsyncRead + Unpin,
374{
375    let len = reader.read_u32().await?;
376    if len > max.min(MAX_FRAME) {
377        return Err(CodecError::TooLarge { len: len.into() });
378    }
379    let mut bytes = vec![0; len as usize];
380    reader.read_exact(&mut bytes).await?;
381    Ok(bytes)
382}
383
384pub async fn read_frame<R, T>(reader: &mut R) -> Result<T, CodecError>
385where
386    R: AsyncRead + Unpin,
387    T: DeserializeOwned,
388{
389    decode(&read_frame_bytes(reader).await?)
390}
391
392/// As [`read_frame`], refusing a frame longer than `max`.
393pub async fn read_frame_within<R, T>(reader: &mut R, max: u32) -> Result<T, CodecError>
394where
395    R: AsyncRead + Unpin,
396    T: DeserializeOwned,
397{
398    decode(&read_frame_bytes_within(reader, max).await?)
399}