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/// [`encode_limited`], with every map entry whose key is one of `keys`
62/// left out, at any depth: a reply with a field the connection did not
63/// agree to (`spoolframe:rating-sources`).
64///
65/// The value is encoded as usual, within `limit`. Only when the bytes
66/// hold one of `keys` (a CBOR text key is its bytes as they are, so a
67/// scan for them misses none, and a stray match only costs the slow
68/// path) are they read into CBOR's own tree, stripped and encoded again:
69/// that covers every shape without knowing any of them, and the tree is
70/// never larger than `limit` allows. A value without them is the very
71/// bytes [`encode_limited`] gives.
72pub fn encode_limited_without<T: Serialize>(
73    value: &T,
74    keys: &[&str],
75    limit: usize,
76) -> Result<Vec<u8>, CodecError> {
77    fn strip(value: &mut ciborium::Value, keys: &[&str]) {
78        match value {
79            ciborium::Value::Map(entries) => {
80                entries.retain(|(key, _)| !key.as_text().is_some_and(|k| keys.contains(&k)));
81                for (_, value) in entries {
82                    strip(value, keys);
83                }
84            }
85            ciborium::Value::Array(values) => {
86                for value in values {
87                    strip(value, keys);
88                }
89            }
90            ciborium::Value::Tag(_, value) => strip(value, keys),
91            _ => {}
92        }
93    }
94    let encoded = encode_limited(value, limit)?;
95    let holds = |key: &str| {
96        encoded
97            .windows(key.len())
98            .any(|window| window == key.as_bytes())
99    };
100    if !keys.iter().any(|key| holds(key)) {
101        return Ok(encoded);
102    }
103    let mut tree: ciborium::Value = decode(&encoded)?;
104    strip(&mut tree, keys);
105    encode_limited(&tree, limit)
106}
107
108/// RPC reply: total encoded length, followed by length-prefixed chunks.
109/// The complete message is checked before any bytes are written.
110pub async fn write_reply<W: AsyncWrite + Unpin, T: Serialize>(
111    writer: &mut W,
112    value: &T,
113) -> Result<(), CodecError> {
114    let encoded = encode_limited(value, MAX_REPLY)?;
115    write_encoded_reply(writer, &encoded).await
116}
117
118/// [`write_reply`] of a reply already encoded to at most [`MAX_REPLY`]:
119/// one encoded with [`encode_limited_without`].
120pub async fn write_encoded_reply<W: AsyncWrite + Unpin>(
121    writer: &mut W,
122    encoded: &[u8],
123) -> Result<(), CodecError> {
124    writer.write_u64(encoded.len() as u64).await?;
125    for chunk in encoded.chunks(MAX_FRAME as usize) {
126        writer.write_u32(chunk.len() as u32).await?;
127        writer.write_all(chunk).await?;
128    }
129    Ok(())
130}
131
132pub async fn read_reply<R: AsyncRead + Unpin, T: DeserializeOwned>(
133    reader: &mut R,
134) -> Result<T, CodecError> {
135    read_reply_within(reader, MAX_REPLY).await
136}
137
138/// As [`read_reply`], refusing a reply longer than `max` (at most
139/// [`MAX_REPLY`]) once its length is read, before any of it is held: what
140/// a request whose answer has a smaller bound of its own reads it with.
141pub async fn read_reply_within<R: AsyncRead + Unpin, T: DeserializeOwned>(
142    reader: &mut R,
143    max: usize,
144) -> Result<T, CodecError> {
145    let mut bytes = Vec::new();
146    read_reply_bytes(reader, &mut bytes, max).await?;
147    decode(&bytes)
148}
149
150/// A reply's bytes, at most `max` of them, read into `bytes`: kept by the
151/// caller so a test can see what was held for a reply that stalls.
152pub(crate) async fn read_reply_bytes<R: AsyncRead + Unpin>(
153    reader: &mut R,
154    bytes: &mut Vec<u8>,
155    max: usize,
156) -> Result<(), CodecError> {
157    let length = reader.read_u64().await?;
158    if length == 0 || length > max.min(MAX_REPLY) as u64 {
159        return Err(CodecError::TooLarge { len: length });
160    }
161    let length = length as usize;
162    while bytes.len() < length {
163        let chunk = reader.read_u32().await?;
164        if chunk == 0 || chunk > MAX_FRAME || chunk as usize > length - bytes.len() {
165            return Err(CodecError::Decode("invalid RPC reply chunk length".into()));
166        }
167        // Held as it arrives, a step at a time: a reply that announces
168        // 64 MiB and sends little holds little (review 2026-10-12).
169        let mut left = chunk as usize;
170        while left > 0 {
171            let offset = bytes.len();
172            let step = left.min(READ_STEP);
173            if bytes.capacity() - offset < step {
174                // Doubled as it fills, so the copies stay linear, and never
175                // past the announced length.
176                let grow = offset.max(READ_STEP).min(length - offset);
177                bytes
178                    .try_reserve_exact(grow)
179                    .map_err(|e| CodecError::Decode(e.to_string()))?;
180            }
181            bytes.resize(offset + step, 0);
182            reader.read_exact(&mut bytes[offset..]).await?;
183            left -= step;
184        }
185    }
186    Ok(())
187}
188
189/// The step [`read_reply`] reads a reply in, and the least its buffer
190/// grows by: it holds at most twice what arrived, or this much past it.
191const READ_STEP: usize = 64 << 10;
192
193#[derive(Debug, thiserror::Error)]
194pub enum CodecError {
195    #[error("stream error: {0}")]
196    Io(#[from] std::io::Error),
197    #[error("message of {len} bytes exceeds its size limit")]
198    TooLarge { len: u64 },
199    #[error("cannot encode: {0}")]
200    Encode(String),
201    #[error("cannot decode: {0}")]
202    Decode(String),
203}
204
205/// Encode `value` as one frame's payload.
206pub fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>, CodecError> {
207    let mut bytes = Vec::new();
208    ciborium::into_writer(value, &mut bytes).map_err(|e| CodecError::Encode(e.to_string()))?;
209    Ok(bytes)
210}
211
212/// How many bytes `value` encodes to, without keeping them: what a page's
213/// budget is measured against.
214pub fn encoded_len<T: Serialize>(value: &T) -> Result<usize, CodecError> {
215    struct Counting(usize);
216    impl std::io::Write for Counting {
217        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
218            self.0 += bytes.len();
219            Ok(bytes.len())
220        }
221        fn flush(&mut self) -> std::io::Result<()> {
222            Ok(())
223        }
224    }
225    let mut counted = Counting(0);
226    ciborium::into_writer(value, &mut counted).map_err(|e| CodecError::Encode(e.to_string()))?;
227    Ok(counted.0)
228}
229
230/// Decode one frame's payload.
231pub fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, CodecError> {
232    ciborium::from_reader(bytes).map_err(|e| CodecError::Decode(e.to_string()))
233}
234
235/// For tests: `value` comes back from a frame as it went in.
236#[cfg(test)]
237pub(crate) fn round_trip<T: Serialize + DeserializeOwned + PartialEq + std::fmt::Debug>(value: T) {
238    let bytes = encode(&value).unwrap();
239    assert_eq!(decode::<T>(&bytes).unwrap(), value);
240}
241
242/// The most characters of a request's `type` that [`request_type`] and
243/// [`rpc_request_type`] read: a client chooses it, up to a whole frame of
244/// it, and every type the protocol has is far shorter.
245pub const MAX_REQUEST_TYPE: usize = 64;
246
247/// The `type` of a request payload, even one this build cannot decode, so
248/// the server can name it in [`crate::Error::Unsupported`].
249pub fn request_type(envelope: &[u8]) -> Option<String> {
250    scan::text_at(envelope, &["request", "type"])
251}
252
253/// Extract a request tag from the mandatory RPC wrapper, including unknown tags.
254///
255/// The server names every request with this before it is authenticated, so
256/// it reads the frame only as far as the tag and keeps nothing of what it
257/// steps over: decoding the frame whole would cost about 50 times its
258/// size in heap.
259pub fn rpc_request_type(bytes: &[u8]) -> Option<String> {
260    scan::text_at(bytes, &["envelope", "request", "type"])
261}
262
263/// Reading one text value out of CBOR without decoding what is around it.
264mod scan {
265    use ciborium_ll::{Decoder, Header};
266
267    type Reader<'a> = Decoder<&'a [u8]>;
268
269    /// How deep arrays and maps that are stepped over may nest: ciborium's
270    /// own limit, so whatever the typed decode reads can be named.
271    const DEPTH: usize = 256;
272
273    /// The bytes read at a time from a text or byte string.
274    const CHUNK: usize = 64;
275
276    /// The text under `path`, a key in each of the nested maps in turn: at
277    /// most [`super::MAX_REQUEST_TYPE`] characters of it.
278    pub(super) fn text_at(bytes: &[u8], path: &[&str]) -> Option<String> {
279        let mut reader = Decoder::from(bytes);
280        for key in path {
281            enter(&mut reader, key)?;
282        }
283        match header(&mut reader)? {
284            Header::Text(len) => text(&mut reader, len, super::MAX_REQUEST_TYPE),
285            _ => None,
286        }
287    }
288
289    /// The next header that is not a tag: a tag only annotates the item
290    /// after it.
291    fn header(reader: &mut Reader<'_>) -> Option<Header> {
292        loop {
293            match reader.pull().ok()? {
294                Header::Tag(_) => continue,
295                header => return Some(header),
296            }
297        }
298    }
299
300    /// Read into the map that comes next, up to the value of `key` in it.
301    fn enter(reader: &mut Reader<'_>, key: &str) -> Option<()> {
302        let Header::Map(len) = header(reader)? else {
303            return None;
304        };
305        let mut left = len;
306        loop {
307            match &mut left {
308                Some(0) => return None,
309                Some(n) => *n -= 1,
310                None => {}
311            }
312            let found = match header(reader)? {
313                Header::Break if len.is_none() => return None,
314                // One character past the key is enough to tell it apart.
315                Header::Text(n) => text(reader, n, key.chars().count() + 1)?.as_str() == key,
316                other => {
317                    skip(reader, other, DEPTH)?;
318                    false
319                }
320            };
321            if found {
322                return Some(());
323            }
324            let value = header(reader)?;
325            skip(reader, value, DEPTH)?;
326        }
327    }
328
329    /// The first `max` characters of the text whose header was `len`; the
330    /// rest of it is read and dropped.
331    fn text(reader: &mut Reader<'_>, len: Option<usize>, max: usize) -> Option<String> {
332        let mut kept = String::new();
333        let mut count = 0;
334        let mut chunk = [0; CHUNK];
335        let mut segments = reader.text(len);
336        while let Some(mut segment) = segments.pull().ok()? {
337            while let Some(part) = segment.pull(&mut chunk).ok()? {
338                for c in part.chars().take(max - count) {
339                    kept.push(c);
340                    count += 1;
341                }
342            }
343        }
344        Some(kept)
345    }
346
347    /// Step over the item whose header was `header`, keeping none of it.
348    fn skip(reader: &mut Reader<'_>, header: Header, depth: usize) -> Option<()> {
349        let depth = depth.checked_sub(1)?;
350        match header {
351            Header::Text(len) => drop_text(reader, len),
352            Header::Bytes(len) => drop_bytes(reader, len),
353            Header::Array(len) => items(reader, len, depth),
354            Header::Map(Some(len)) => items(reader, Some(len.checked_mul(2)?), depth),
355            Header::Map(None) => items(reader, None, depth),
356            Header::Break => None,
357            // A number or a simple value is all header.
358            _ => Some(()),
359        }
360    }
361
362    /// Step over `len` items, or up to a break when `len` is `None`.
363    fn items(reader: &mut Reader<'_>, len: Option<usize>, depth: usize) -> Option<()> {
364        match len {
365            // Each item is at least a byte, so a claimed length past the
366            // frame ends at the frame's end.
367            Some(len) => {
368                for _ in 0..len {
369                    let item = header(reader)?;
370                    skip(reader, item, depth)?;
371                }
372            }
373            None => loop {
374                match header(reader)? {
375                    Header::Break => break,
376                    item => skip(reader, item, depth)?,
377                }
378            },
379        }
380        Some(())
381    }
382
383    // Kept out of `skip`, so a deep nest does not carry a buffer per level.
384    #[inline(never)]
385    fn drop_text(reader: &mut Reader<'_>, len: Option<usize>) -> Option<()> {
386        let mut chunk = [0; CHUNK];
387        let mut segments = reader.text(len);
388        while let Some(mut segment) = segments.pull().ok()? {
389            while segment.pull(&mut chunk).ok()?.is_some() {}
390        }
391        Some(())
392    }
393
394    #[inline(never)]
395    fn drop_bytes(reader: &mut Reader<'_>, len: Option<usize>) -> Option<()> {
396        let mut chunk = [0; CHUNK];
397        let mut segments = reader.bytes(len);
398        while let Some(mut segment) = segments.pull().ok()? {
399            while segment.pull(&mut chunk).ok()?.is_some() {}
400        }
401        Some(())
402    }
403}
404
405/// Write `value` as one frame. One over [`MAX_FRAME`] is refused before
406/// anything is written, so the writer can send something else instead.
407pub async fn write_frame<W, T>(writer: &mut W, value: &T) -> Result<(), CodecError>
408where
409    W: AsyncWrite + Unpin,
410    T: Serialize,
411{
412    let bytes = encode(value)?;
413    let len = u32::try_from(bytes.len())
414        .ok()
415        .filter(|&len| len <= MAX_FRAME)
416        .ok_or(CodecError::TooLarge {
417            len: bytes.len() as u64,
418        })?;
419    writer.write_all(&len.to_be_bytes()).await?;
420    writer.write_all(&bytes).await?;
421    Ok(())
422}
423
424/// Read one frame's payload, refusing an oversized one before reading it.
425pub async fn read_frame_bytes<R>(reader: &mut R) -> Result<Vec<u8>, CodecError>
426where
427    R: AsyncRead + Unpin,
428{
429    read_frame_bytes_within(reader, MAX_FRAME).await
430}
431
432/// As [`read_frame_bytes`], refusing a frame longer than `max` (at most
433/// [`MAX_FRAME`]) before anything is allocated for it.
434pub async fn read_frame_bytes_within<R>(reader: &mut R, max: u32) -> Result<Vec<u8>, CodecError>
435where
436    R: AsyncRead + Unpin,
437{
438    let len = reader.read_u32().await?;
439    if len > max.min(MAX_FRAME) {
440        return Err(CodecError::TooLarge { len: len.into() });
441    }
442    let mut bytes = vec![0; len as usize];
443    reader.read_exact(&mut bytes).await?;
444    Ok(bytes)
445}
446
447pub async fn read_frame<R, T>(reader: &mut R) -> Result<T, CodecError>
448where
449    R: AsyncRead + Unpin,
450    T: DeserializeOwned,
451{
452    decode(&read_frame_bytes(reader).await?)
453}
454
455/// As [`read_frame`], refusing a frame longer than `max`.
456pub async fn read_frame_within<R, T>(reader: &mut R, max: u32) -> Result<T, CodecError>
457where
458    R: AsyncRead + Unpin,
459    T: DeserializeOwned,
460{
461    decode(&read_frame_bytes_within(reader, max).await?)
462}