spoolframe-protocol 0.18.1

The spoolframe/client/1 wire protocol.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! Frames: a big-endian `u32` length, then that many bytes of CBOR.

use serde::Serialize;
use serde::de::DeserializeOwned;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};

/// The largest frame a peer accepts. Requests and replies are metadata; a
/// page of items is far smaller. The limit keeps a peer from making the
/// other allocate without bound.
pub const MAX_FRAME: u32 = 1 << 20;

/// RPC replies can span frames, but never exceed this aggregate budget.
pub const MAX_REPLY: usize = 64 << 20;

/// Encode without allocating past `limit`, including for an oversized value.
pub fn encode_limited<T: Serialize>(value: &T, limit: usize) -> Result<Vec<u8>, CodecError> {
    struct Bounded {
        bytes: Vec<u8>,
        limit: usize,
        exceeded: bool,
    }
    impl std::io::Write for Bounded {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            if bytes.len() > self.limit - self.bytes.len() {
                self.exceeded = true;
                return Err(std::io::Error::other("message limit"));
            }
            let needed = self.bytes.len() + bytes.len();
            if needed > self.bytes.capacity() {
                let capacity = needed
                    .max(self.bytes.capacity().saturating_mul(2))
                    .min(self.limit);
                self.bytes
                    .try_reserve_exact(capacity - self.bytes.len())
                    .map_err(std::io::Error::other)?;
            }
            self.bytes.extend_from_slice(bytes);
            Ok(bytes.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    let mut buffer = Bounded {
        bytes: Vec::new(),
        limit,
        exceeded: false,
    };
    ciborium::into_writer(value, &mut buffer).map_err(|error| {
        if buffer.exceeded {
            CodecError::TooLarge {
                len: limit as u64 + 1,
            }
        } else {
            CodecError::Encode(error.to_string())
        }
    })?;
    Ok(buffer.bytes)
}

/// [`encode_limited`], with every map entry whose key is one of `keys`
/// left out, at any depth: a reply with a field the connection did not
/// agree to (`spoolframe:rating-sources`).
///
/// The value is encoded as usual, within `limit`. Only when the bytes
/// hold one of `keys` (a CBOR text key is its bytes as they are, so a
/// scan for them misses none, and a stray match only costs the slow
/// path) are they read into CBOR's own tree, stripped and encoded again:
/// that covers every shape without knowing any of them, and the tree is
/// never larger than `limit` allows. A value without them is the very
/// bytes [`encode_limited`] gives.
pub fn encode_limited_without<T: Serialize>(
    value: &T,
    keys: &[&str],
    limit: usize,
) -> Result<Vec<u8>, CodecError> {
    fn strip(value: &mut ciborium::Value, keys: &[&str]) {
        match value {
            ciborium::Value::Map(entries) => {
                entries.retain(|(key, _)| !key.as_text().is_some_and(|k| keys.contains(&k)));
                for (_, value) in entries {
                    strip(value, keys);
                }
            }
            ciborium::Value::Array(values) => {
                for value in values {
                    strip(value, keys);
                }
            }
            ciborium::Value::Tag(_, value) => strip(value, keys),
            _ => {}
        }
    }
    let encoded = encode_limited(value, limit)?;
    let holds = |key: &str| {
        encoded
            .windows(key.len())
            .any(|window| window == key.as_bytes())
    };
    if !keys.iter().any(|key| holds(key)) {
        return Ok(encoded);
    }
    let mut tree: ciborium::Value = decode(&encoded)?;
    strip(&mut tree, keys);
    encode_limited(&tree, limit)
}

/// RPC reply: total encoded length, followed by length-prefixed chunks.
/// The complete message is checked before any bytes are written.
pub async fn write_reply<W: AsyncWrite + Unpin, T: Serialize>(
    writer: &mut W,
    value: &T,
) -> Result<(), CodecError> {
    let encoded = encode_limited(value, MAX_REPLY)?;
    write_encoded_reply(writer, &encoded).await
}

/// [`write_reply`] of a reply already encoded to at most [`MAX_REPLY`]:
/// one encoded with [`encode_limited_without`].
pub async fn write_encoded_reply<W: AsyncWrite + Unpin>(
    writer: &mut W,
    encoded: &[u8],
) -> Result<(), CodecError> {
    writer.write_u64(encoded.len() as u64).await?;
    for chunk in encoded.chunks(MAX_FRAME as usize) {
        writer.write_u32(chunk.len() as u32).await?;
        writer.write_all(chunk).await?;
    }
    Ok(())
}

pub async fn read_reply<R: AsyncRead + Unpin, T: DeserializeOwned>(
    reader: &mut R,
) -> Result<T, CodecError> {
    read_reply_within(reader, MAX_REPLY).await
}

/// As [`read_reply`], refusing a reply longer than `max` (at most
/// [`MAX_REPLY`]) once its length is read, before any of it is held: what
/// a request whose answer has a smaller bound of its own reads it with.
pub async fn read_reply_within<R: AsyncRead + Unpin, T: DeserializeOwned>(
    reader: &mut R,
    max: usize,
) -> Result<T, CodecError> {
    let mut bytes = Vec::new();
    read_reply_bytes(reader, &mut bytes, max).await?;
    decode(&bytes)
}

/// A reply's bytes, at most `max` of them, read into `bytes`: kept by the
/// caller so a test can see what was held for a reply that stalls.
pub(crate) async fn read_reply_bytes<R: AsyncRead + Unpin>(
    reader: &mut R,
    bytes: &mut Vec<u8>,
    max: usize,
) -> Result<(), CodecError> {
    let length = reader.read_u64().await?;
    if length == 0 || length > max.min(MAX_REPLY) as u64 {
        return Err(CodecError::TooLarge { len: length });
    }
    let length = length as usize;
    while bytes.len() < length {
        let chunk = reader.read_u32().await?;
        if chunk == 0 || chunk > MAX_FRAME || chunk as usize > length - bytes.len() {
            return Err(CodecError::Decode("invalid RPC reply chunk length".into()));
        }
        // Held as it arrives, a step at a time: a reply that announces
        // 64 MiB and sends little holds little (review 2026-10-12).
        let mut left = chunk as usize;
        while left > 0 {
            let offset = bytes.len();
            let step = left.min(READ_STEP);
            if bytes.capacity() - offset < step {
                // Doubled as it fills, so the copies stay linear, and never
                // past the announced length.
                let grow = offset.max(READ_STEP).min(length - offset);
                bytes
                    .try_reserve_exact(grow)
                    .map_err(|e| CodecError::Decode(e.to_string()))?;
            }
            bytes.resize(offset + step, 0);
            reader.read_exact(&mut bytes[offset..]).await?;
            left -= step;
        }
    }
    Ok(())
}

/// The step [`read_reply`] reads a reply in, and the least its buffer
/// grows by: it holds at most twice what arrived, or this much past it.
const READ_STEP: usize = 64 << 10;

#[derive(Debug, thiserror::Error)]
pub enum CodecError {
    #[error("stream error: {0}")]
    Io(#[from] std::io::Error),
    #[error("message of {len} bytes exceeds its size limit")]
    TooLarge { len: u64 },
    #[error("cannot encode: {0}")]
    Encode(String),
    #[error("cannot decode: {0}")]
    Decode(String),
}

/// Encode `value` as one frame's payload.
pub fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>, CodecError> {
    let mut bytes = Vec::new();
    ciborium::into_writer(value, &mut bytes).map_err(|e| CodecError::Encode(e.to_string()))?;
    Ok(bytes)
}

/// How many bytes `value` encodes to, without keeping them: what a page's
/// budget is measured against.
pub fn encoded_len<T: Serialize>(value: &T) -> Result<usize, CodecError> {
    struct Counting(usize);
    impl std::io::Write for Counting {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            self.0 += bytes.len();
            Ok(bytes.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    let mut counted = Counting(0);
    ciborium::into_writer(value, &mut counted).map_err(|e| CodecError::Encode(e.to_string()))?;
    Ok(counted.0)
}

/// Decode one frame's payload.
pub fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, CodecError> {
    ciborium::from_reader(bytes).map_err(|e| CodecError::Decode(e.to_string()))
}

/// For tests: `value` comes back from a frame as it went in.
#[cfg(test)]
pub(crate) fn round_trip<T: Serialize + DeserializeOwned + PartialEq + std::fmt::Debug>(value: T) {
    let bytes = encode(&value).unwrap();
    assert_eq!(decode::<T>(&bytes).unwrap(), value);
}

/// The most characters of a request's `type` that [`request_type`] and
/// [`rpc_request_type`] read: a client chooses it, up to a whole frame of
/// it, and every type the protocol has is far shorter.
pub const MAX_REQUEST_TYPE: usize = 64;

/// The `type` of a request payload, even one this build cannot decode, so
/// the server can name it in [`crate::Error::Unsupported`].
pub fn request_type(envelope: &[u8]) -> Option<String> {
    scan::text_at(envelope, &["request", "type"])
}

/// Extract a request tag from the mandatory RPC wrapper, including unknown tags.
///
/// The server names every request with this before it is authenticated, so
/// it reads the frame only as far as the tag and keeps nothing of what it
/// steps over: decoding the frame whole would cost about 50 times its
/// size in heap.
pub fn rpc_request_type(bytes: &[u8]) -> Option<String> {
    scan::text_at(bytes, &["envelope", "request", "type"])
}

/// Reading one text value out of CBOR without decoding what is around it.
mod scan {
    use ciborium_ll::{Decoder, Header};

    type Reader<'a> = Decoder<&'a [u8]>;

    /// How deep arrays and maps that are stepped over may nest: ciborium's
    /// own limit, so whatever the typed decode reads can be named.
    const DEPTH: usize = 256;

    /// The bytes read at a time from a text or byte string.
    const CHUNK: usize = 64;

    /// The text under `path`, a key in each of the nested maps in turn: at
    /// most [`super::MAX_REQUEST_TYPE`] characters of it.
    pub(super) fn text_at(bytes: &[u8], path: &[&str]) -> Option<String> {
        let mut reader = Decoder::from(bytes);
        for key in path {
            enter(&mut reader, key)?;
        }
        match header(&mut reader)? {
            Header::Text(len) => text(&mut reader, len, super::MAX_REQUEST_TYPE),
            _ => None,
        }
    }

    /// The next header that is not a tag: a tag only annotates the item
    /// after it.
    fn header(reader: &mut Reader<'_>) -> Option<Header> {
        loop {
            match reader.pull().ok()? {
                Header::Tag(_) => continue,
                header => return Some(header),
            }
        }
    }

    /// Read into the map that comes next, up to the value of `key` in it.
    fn enter(reader: &mut Reader<'_>, key: &str) -> Option<()> {
        let Header::Map(len) = header(reader)? else {
            return None;
        };
        let mut left = len;
        loop {
            match &mut left {
                Some(0) => return None,
                Some(n) => *n -= 1,
                None => {}
            }
            let found = match header(reader)? {
                Header::Break if len.is_none() => return None,
                // One character past the key is enough to tell it apart.
                Header::Text(n) => text(reader, n, key.chars().count() + 1)?.as_str() == key,
                other => {
                    skip(reader, other, DEPTH)?;
                    false
                }
            };
            if found {
                return Some(());
            }
            let value = header(reader)?;
            skip(reader, value, DEPTH)?;
        }
    }

    /// The first `max` characters of the text whose header was `len`; the
    /// rest of it is read and dropped.
    fn text(reader: &mut Reader<'_>, len: Option<usize>, max: usize) -> Option<String> {
        let mut kept = String::new();
        let mut count = 0;
        let mut chunk = [0; CHUNK];
        let mut segments = reader.text(len);
        while let Some(mut segment) = segments.pull().ok()? {
            while let Some(part) = segment.pull(&mut chunk).ok()? {
                for c in part.chars().take(max - count) {
                    kept.push(c);
                    count += 1;
                }
            }
        }
        Some(kept)
    }

    /// Step over the item whose header was `header`, keeping none of it.
    fn skip(reader: &mut Reader<'_>, header: Header, depth: usize) -> Option<()> {
        let depth = depth.checked_sub(1)?;
        match header {
            Header::Text(len) => drop_text(reader, len),
            Header::Bytes(len) => drop_bytes(reader, len),
            Header::Array(len) => items(reader, len, depth),
            Header::Map(Some(len)) => items(reader, Some(len.checked_mul(2)?), depth),
            Header::Map(None) => items(reader, None, depth),
            Header::Break => None,
            // A number or a simple value is all header.
            _ => Some(()),
        }
    }

    /// Step over `len` items, or up to a break when `len` is `None`.
    fn items(reader: &mut Reader<'_>, len: Option<usize>, depth: usize) -> Option<()> {
        match len {
            // Each item is at least a byte, so a claimed length past the
            // frame ends at the frame's end.
            Some(len) => {
                for _ in 0..len {
                    let item = header(reader)?;
                    skip(reader, item, depth)?;
                }
            }
            None => loop {
                match header(reader)? {
                    Header::Break => break,
                    item => skip(reader, item, depth)?,
                }
            },
        }
        Some(())
    }

    // Kept out of `skip`, so a deep nest does not carry a buffer per level.
    #[inline(never)]
    fn drop_text(reader: &mut Reader<'_>, len: Option<usize>) -> Option<()> {
        let mut chunk = [0; CHUNK];
        let mut segments = reader.text(len);
        while let Some(mut segment) = segments.pull().ok()? {
            while segment.pull(&mut chunk).ok()?.is_some() {}
        }
        Some(())
    }

    #[inline(never)]
    fn drop_bytes(reader: &mut Reader<'_>, len: Option<usize>) -> Option<()> {
        let mut chunk = [0; CHUNK];
        let mut segments = reader.bytes(len);
        while let Some(mut segment) = segments.pull().ok()? {
            while segment.pull(&mut chunk).ok()?.is_some() {}
        }
        Some(())
    }
}

/// Write `value` as one frame. One over [`MAX_FRAME`] is refused before
/// anything is written, so the writer can send something else instead.
pub async fn write_frame<W, T>(writer: &mut W, value: &T) -> Result<(), CodecError>
where
    W: AsyncWrite + Unpin,
    T: Serialize,
{
    let bytes = encode(value)?;
    let len = u32::try_from(bytes.len())
        .ok()
        .filter(|&len| len <= MAX_FRAME)
        .ok_or(CodecError::TooLarge {
            len: bytes.len() as u64,
        })?;
    writer.write_all(&len.to_be_bytes()).await?;
    writer.write_all(&bytes).await?;
    Ok(())
}

/// Read one frame's payload, refusing an oversized one before reading it.
pub async fn read_frame_bytes<R>(reader: &mut R) -> Result<Vec<u8>, CodecError>
where
    R: AsyncRead + Unpin,
{
    read_frame_bytes_within(reader, MAX_FRAME).await
}

/// As [`read_frame_bytes`], refusing a frame longer than `max` (at most
/// [`MAX_FRAME`]) before anything is allocated for it.
pub async fn read_frame_bytes_within<R>(reader: &mut R, max: u32) -> Result<Vec<u8>, CodecError>
where
    R: AsyncRead + Unpin,
{
    let len = reader.read_u32().await?;
    if len > max.min(MAX_FRAME) {
        return Err(CodecError::TooLarge { len: len.into() });
    }
    let mut bytes = vec![0; len as usize];
    reader.read_exact(&mut bytes).await?;
    Ok(bytes)
}

pub async fn read_frame<R, T>(reader: &mut R) -> Result<T, CodecError>
where
    R: AsyncRead + Unpin,
    T: DeserializeOwned,
{
    decode(&read_frame_bytes(reader).await?)
}

/// As [`read_frame`], refusing a frame longer than `max`.
pub async fn read_frame_within<R, T>(reader: &mut R, max: u32) -> Result<T, CodecError>
where
    R: AsyncRead + Unpin,
    T: DeserializeOwned,
{
    decode(&read_frame_bytes_within(reader, max).await?)
}