zaun_community_protocol/framing/parse.rs
1//! Receiver side of §5.1 and §5.3: classify one inbound transport text.
2
3use super::{FRAGMENT_PREFIX, FragId, PROTOCOL_PREFIX, WHOLE_PREFIX};
4
5/// Largest `count` the §5.1 syntax allows. Receivers additionally enforce the §5.2 limit
6/// ([`crate::limits::MAX_FRAGMENTS`]) in the [`super::Reassembler`].
7// The specification limits `count` to 32 (§5.1, §5.2). The parser accepts up to 64 so that an
8// over-limit fragment is classified as a fragment and discarded by the reassembler with
9// `TooManyFragments`, instead of being mistaken for non-protocol text.
10const SYNTAX_MAX_COUNT: usize = 64;
11
12/// One fragment message (§5.1), borrowing its chunk from the received text.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct Fragment<'a> {
15 /// The reassembly this fragment belongs to.
16 pub frag_id: FragId,
17 /// Position, `0 ≤ index < count`.
18 pub index: usize,
19 /// Number of fragments in the frame, `2 ≤ count ≤ 64` syntactically; over 32 is discarded.
20 pub count: usize,
21 /// A piece of the envelope JSON text (valid UTF-8 by construction).
22 pub chunk: &'a str,
23}
24
25/// What an inbound transport text is (§5.3).
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Inbound<'a> {
28 /// Does not start with `zaun:`: not a protocol message. Never parse it as a command; count
29 /// it against the command rate limit; on an unbound connection send one plain notice.
30 NotProtocol,
31 /// Starts with `zaun:` but the frame prefix is unknown (`zaun:2:` …): answer
32 /// `UNSUPPORTED_VERSION` when possible, otherwise ignore.
33 UnknownPrefix,
34 /// `zaun:1f:` with a malformed header (bad id, leading zeros, `index ≥ count`, …).
35 // SPEC: §5 does not say how to treat a malformed fragment header. Conservative: ignore it
36 // (no response, no reassembly touched), as for a discarded reassembly in §5.2.
37 MalformedFragment,
38 /// A whole envelope: its JSON text, to be parsed as an envelope.
39 Whole(&'a str),
40 /// A fragment, to be pushed into the connection's reassembler.
41 Fragment(Fragment<'a>),
42}
43
44/// Classifies one inbound text message. The `zaun:1f:` prefix is tested before `zaun:1:`
45/// (they differ at the 7th byte, so the order is only for clarity).
46#[must_use]
47pub fn classify(text: &str) -> Inbound<'_> {
48 if let Some(rest) = text.strip_prefix(FRAGMENT_PREFIX) {
49 return parse_fragment(rest).map_or(Inbound::MalformedFragment, Inbound::Fragment);
50 }
51 if let Some(json) = text.strip_prefix(WHOLE_PREFIX) {
52 return Inbound::Whole(json);
53 }
54 if text.starts_with(PROTOCOL_PREFIX) {
55 return Inbound::UnknownPrefix;
56 }
57 Inbound::NotProtocol
58}
59
60/// Parses `<frag_id>:<index>:<count>:<chunk>`; the chunk may itself contain `:`.
61fn parse_fragment(rest: &str) -> Option<Fragment<'_>> {
62 let mut parts = rest.splitn(4, ':');
63 let frag_id = FragId::from_b64(parts.next()?)?;
64 let index = decimal(parts.next()?)?;
65 let count = decimal(parts.next()?)?;
66 let chunk = parts.next()?;
67 let valid = (2..=SYNTAX_MAX_COUNT).contains(&count) && index < count;
68 valid.then_some(Fragment {
69 frag_id,
70 index,
71 count,
72 chunk,
73 })
74}
75
76/// A decimal without leading zeros (except `"0"`), at most two digits (the syntax maximum is
77/// 64), so parsing never overflows.
78fn decimal(text: &str) -> Option<usize> {
79 let canonical = (1..=2).contains(&text.len())
80 && text.bytes().all(|b| b.is_ascii_digit())
81 && (text == "0" || !text.starts_with('0'));
82 if canonical { text.parse().ok() } else { None }
83}