Skip to main content

zaun_community_protocol/
framing.rs

1//! Transport framing over SimpleX direct connections (specification §5).
2//!
3//! An envelope's compact JSON text travels as one *whole* frame message (`zaun:1:<json>`) or,
4//! when it does not fit the per-message budget, as 2–32 *fragment* messages
5//! (`zaun:1f:<frag_id>:<index>:<count>:<chunk>`). [`encode`] produces the messages,
6//! [`classify`] recognises an inbound text, and a [`Reassembler`] per connection joins
7//! fragments under the bounds of §5.2. Every message emitted costs one SMP message against
8//! the in-flight window (§10.5), so [`EncodedFrame::smp_messages`] is what flow control counts.
9//!
10//! Pure: no I/O, no clock (time is `now_ms`), no randomness (the caller supplies [`FragId`]).
11
12pub mod app_data;
13mod encode;
14mod parse;
15mod reassembly;
16
17use std::fmt;
18
19pub use encode::{EncodeError, EncodedFrame, MIN_BUDGET, encode, escaped_len};
20pub use parse::{Fragment, Inbound, classify};
21pub use reassembly::{DiscardReason, Pushed, Reassembler};
22
23use crate::b64;
24use crate::ids::{RngError, fill_random};
25
26/// Prefix of a whole-envelope message.
27pub const WHOLE_PREFIX: &str = "zaun:1:";
28/// Prefix of a fragment message.
29pub const FRAGMENT_PREFIX: &str = "zaun:1f:";
30/// Prefix shared by every protocol message; text without it is not a protocol message (§5.3).
31pub const PROTOCOL_PREFIX: &str = "zaun:";
32/// Length of an encoded [`FragId`] (8 bytes, base64url without padding).
33pub const FRAG_ID_CHARS: usize = 11;
34
35/// A fragment id: 8 random bytes, unique per sender per connection among open reassemblies.
36#[derive(Clone, Copy, PartialEq, Eq, Hash)]
37pub struct FragId([u8; 8]);
38
39impl FragId {
40    /// Wraps raw bytes (deterministic encoding, tests).
41    #[must_use]
42    pub const fn from_bytes(bytes: [u8; 8]) -> Self {
43        Self(bytes)
44    }
45
46    /// A fresh id from the OS CSPRNG.
47    ///
48    /// # Errors
49    /// [`RngError`] when the CSPRNG fails.
50    pub fn random() -> Result<Self, RngError> {
51        let mut bytes = [0u8; 8];
52        fill_random(&mut bytes)?;
53        Ok(Self(bytes))
54    }
55
56    /// The raw bytes.
57    #[must_use]
58    pub const fn as_bytes(&self) -> &[u8; 8] {
59        &self.0
60    }
61
62    /// Strict base64url of exactly [`FRAG_ID_CHARS`] characters.
63    #[must_use]
64    pub fn from_b64(text: &str) -> Option<Self> {
65        b64::decode_array(text).ok().map(Self)
66    }
67
68    /// Base64url without padding (11 characters).
69    #[must_use]
70    pub fn to_b64(&self) -> String {
71        b64::encode(&self.0)
72    }
73}
74
75impl fmt::Debug for FragId {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        write!(f, "FragId({})", self.to_b64())
78    }
79}