Skip to main content

zaun_community_protocol/framing/
encode.rs

1//! Sender side of §5.1: envelope JSON text → transport text messages.
2
3use super::{FRAG_ID_CHARS, FRAGMENT_PREFIX, FragId, WHOLE_PREFIX};
4use crate::limits::{MAX_FRAGMENTS, MAX_FRAME};
5
6/// Bytes reserved for every fragment header: `zaun:1f:` + 11-char id + `:` + index (≤ 2
7/// digits) + `:` + count (≤ 2 digits) + `:` (nothing in it is escaped). Reserving the worst
8/// case for every fragment keeps the split a single greedy pass; at realistic budgets (≈ 13 100
9/// B for simplex-client, measured in `zaun-host`) it never changes the count enough to matter,
10/// since 32 fragments then carry far more than `max_frame`.
11const HEADER_RESERVE: usize = FRAGMENT_PREFIX.len() + FRAG_ID_CHARS + 3 + 2 * 2;
12
13/// The smallest accepted per-message budget: a fragment header plus one character at its
14/// largest escaped (six bytes, [`escaped_len`]).
15pub const MIN_BUDGET: usize = HEADER_RESERVE + 6;
16
17/// Why an envelope cannot be framed.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
19pub enum EncodeError {
20    /// The envelope JSON exceeds `max_frame` (§5.2).
21    #[error("envelope of {len} bytes exceeds max_frame {max}")]
22    TooLarge {
23        /// Envelope length in bytes.
24        len: usize,
25        /// The limit.
26        max: usize,
27    },
28    /// The envelope needs more than [`MAX_FRAGMENTS`] fragments at this budget (§5.2).
29    #[error("envelope needs more than {max} fragments")]
30    TooManyFragments {
31        /// The limit.
32        max: usize,
33    },
34    /// The budget cannot hold a fragment header plus one character.
35    #[error("per-message budget {budget} is below the minimum {min}")]
36    BudgetTooSmall {
37        /// The budget given.
38        budget: usize,
39        /// [`MIN_BUDGET`].
40        min: usize,
41    },
42}
43
44/// The transport messages of one frame, in sending order.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct EncodedFrame {
47    messages: Vec<String>,
48}
49
50impl EncodedFrame {
51    /// The text messages to send, in order.
52    #[must_use]
53    pub fn messages(&self) -> &[String] {
54        &self.messages
55    }
56
57    /// Consumes the frame into its messages.
58    #[must_use]
59    pub fn into_messages(self) -> Vec<String> {
60        self.messages
61    }
62
63    /// SMP messages this frame costs against the in-flight window (§10.5): one per message.
64    #[must_use]
65    pub fn smp_messages(&self) -> usize {
66        self.messages.len()
67    }
68
69    /// Whether the frame is a single whole message.
70    #[must_use]
71    pub fn is_whole(&self) -> bool {
72        self.messages.len() == 1
73    }
74}
75
76/// The bytes `text` takes written inside a JSON string, as a frame message travels in its
77/// application data (§5.1): `"` and `\` take two, the control characters JSON writes as
78/// `\b`, `\t`, `\n`, `\f`, `\r` two, every other control character six (`\u00XX`).
79#[must_use]
80pub fn escaped_len(text: &str) -> usize {
81    text.len()
82        + text
83            .bytes()
84            .map(|b| match b {
85                b'"' | b'\\' | 0x08 | 0x09 | 0x0a | 0x0c | 0x0d => 1,
86                0x00..=0x1f => 5,
87                _ => 0,
88            })
89            .sum::<usize>()
90}
91
92/// Frames the compact envelope JSON `json` (§5.1).
93///
94/// `budget` is the per-message budget of the **whole** message text, prefix and header
95/// included, measured as written inside a JSON string ([`escaped_len`]): each message is cut
96/// by what it really costs, so text with few quotes fills a message. The host derives the
97/// budget from `simplex_client::limits` (§5.1); this crate never depends on `simplex-client`.
98/// A frame that fits in one message is sent whole; otherwise it is split greedily at UTF-8
99/// character boundaries. `frag_id` is used only when fragmenting.
100///
101/// # Errors
102/// [`EncodeError`] when the envelope is larger than `max_frame`, needs more than 32 fragments,
103/// or the budget is below [`MIN_BUDGET`].
104pub fn encode(json: &str, budget: usize, frag_id: FragId) -> Result<EncodedFrame, EncodeError> {
105    if budget < MIN_BUDGET {
106        return Err(EncodeError::BudgetTooSmall {
107            budget,
108            min: MIN_BUDGET,
109        });
110    }
111    if json.len() > MAX_FRAME {
112        return Err(EncodeError::TooLarge {
113            len: json.len(),
114            max: MAX_FRAME,
115        });
116    }
117    if WHOLE_PREFIX.len() + escaped_len(json) <= budget {
118        return Ok(EncodedFrame {
119            messages: vec![format!("{WHOLE_PREFIX}{json}")],
120        });
121    }
122    let chunks = split(json, budget - HEADER_RESERVE)?;
123    let count = chunks.len();
124    let id = frag_id.to_b64();
125    let messages = chunks
126        .iter()
127        .enumerate()
128        .map(|(index, chunk)| format!("{FRAGMENT_PREFIX}{id}:{index}:{count}:{chunk}"))
129        .collect();
130    Ok(EncodedFrame { messages })
131}
132
133/// Greedy split into chunks of at most `cap` escaped bytes ([`escaped_len`]), at character
134/// boundaries; stops as soon as the fragment limit is exceeded so the work is bounded.
135fn split(json: &str, cap: usize) -> Result<Vec<&str>, EncodeError> {
136    let mut chunks = Vec::new();
137    let mut start = 0;
138    let mut cost = 0;
139    for (i, c) in json.char_indices() {
140        let mut buf = [0; 4];
141        // `cap` ≥ 6 (`MIN_BUDGET` − header), so one character always fits a fresh chunk.
142        let w = escaped_len(c.encode_utf8(&mut buf));
143        if cost + w > cap {
144            if chunks.len() == MAX_FRAGMENTS {
145                return Err(EncodeError::TooManyFragments { max: MAX_FRAGMENTS });
146            }
147            chunks.push(&json[start..i]);
148            start = i;
149            cost = 0;
150        }
151        cost += w;
152    }
153    if start < json.len() {
154        if chunks.len() == MAX_FRAGMENTS {
155            return Err(EncodeError::TooManyFragments { max: MAX_FRAGMENTS });
156        }
157        chunks.push(&json[start..]);
158    }
159    Ok(chunks)
160}