Skip to main content

rings_core/chunk/
framing.rs

1use bytes::Bytes;
2use serde::Deserialize;
3use serde::Serialize;
4
5use crate::consts::DEFAULT_TTL_MS;
6use crate::consts::MAX_CHUNK_ENVELOPE_OVERHEAD;
7use crate::consts::MIN_CHUNK_DATA;
8use crate::consts::TRANSPORT_CUSTOM_OVERHEAD;
9use crate::error::Error;
10use crate::error::Result;
11use crate::utils::get_epoch_ms;
12
13/// One chunk of a chunked message, as it travels on the wire.
14#[derive(Debug, Clone, Deserialize, Serialize)]
15pub struct Chunk {
16    /// `[position, total]` - this chunk's index and the number of chunks in the message.
17    pub chunk: [usize; 2],
18    /// chunk payload bytes
19    pub data: Bytes,
20    /// meta data of chunk
21    pub meta: ChunkMeta,
22}
23
24impl Chunk {
25    /// The chunks of one message, sender side: `bytes` cut into pieces of at most `chunk_size`
26    /// data bytes, tagged `[i, total]` and sharing one [`ChunkMeta`].
27    ///
28    /// ```text
29    ///   stream(bytes, k) = [Chunk{ chunk=[i, n], data=bytes[ik .. min((i+1)k, |bytes|)] } | i in 0..n]
30    ///   where n = ceil(|bytes| / k)
31    /// ```
32    ///
33    /// The chunks are yielded lazily and each `data` is a zero-copy [`Bytes::slice`] of the
34    /// input, so a sender frames and flushes one chunk at a time with bounded memory. `chunk_size`
35    /// comes from the connection's negotiated `max_message_size` minus the envelope reserve
36    /// ([`WireReserves::plan`] never yields an unusable size); it is clamped to at least 1 only so
37    /// a degenerate value still terminates. Empty input yields no chunks. Reassembly is the
38    /// receiver's job: see [`super::MessageReassembler`].
39    pub fn stream(bytes: Bytes, chunk_size: usize) -> impl Iterator<Item = Chunk> {
40        Self::stream_at(bytes, chunk_size, get_epoch_ms())
41    }
42
43    /// [`Self::stream`] stamped with the caller's epoch timestamp `now_ms`.
44    pub fn stream_at(bytes: Bytes, chunk_size: usize, now_ms: u128) -> impl Iterator<Item = Chunk> {
45        let chunk_size = chunk_size.max(1);
46        let total = bytes.len().div_ceil(chunk_size);
47        let meta = ChunkMeta::new_at(now_ms);
48        (0..total).map(move |i| {
49            let start = i * chunk_size;
50            let end = start.saturating_add(chunk_size).min(bytes.len());
51            Chunk {
52                meta,
53                chunk: [i, total],
54                data: bytes.slice(start..end),
55            }
56        })
57    }
58
59    /// Serialize chunk to the Rings wire encoding.
60    pub fn to_wire(&self) -> Result<Bytes> {
61        rings_codec::serialize(self)
62            .map(Bytes::from)
63            .map_err(Error::CodecSerialize)
64    }
65
66    /// Deserialize chunk from the Rings wire encoding.
67    pub fn from_wire(data: &[u8]) -> Result<Self> {
68        rings_codec::deserialize(data).map_err(Error::CodecDeserialize)
69    }
70}
71
72/// Meta data of a chunk
73#[derive(Debug, Copy, Clone, Deserialize, Serialize)]
74pub struct ChunkMeta {
75    /// uuid of msg
76    pub id: uuid::Uuid,
77    /// Created time
78    pub ts_ms: u128,
79    /// Time to live
80    pub ttl_ms: u64,
81}
82
83impl ChunkMeta {
84    /// Construct chunk metadata stamped at `ts_ms`.
85    pub fn new_at(ts_ms: u128) -> Self {
86        Self {
87            id: crate::utils::new_uuid(),
88            ts_ms,
89            ttl_ms: DEFAULT_TTL_MS,
90        }
91    }
92}
93
94impl Default for ChunkMeta {
95    fn default() -> Self {
96        Self::new_at(get_epoch_ms())
97    }
98}
99
100/// How one payload should be framed for a size-limited connection: sent whole, or split.
101///
102/// This is the *decision* only - a value, with no I/O - so the sender's effectful path
103/// (`do_send_payload`) is a thin shell that matches on it. Separating the rule from the act keeps
104/// the rule exhaustively testable in isolation (functional core / imperative shell).
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum Framing {
107    /// The payload is within the connection's limit; send it as a single message, unchanged.
108    Whole,
109    /// The payload exceeds the limit; split it into [`Chunk`]s of at most `chunk_size` data bytes
110    /// each (via [`Chunk::stream`]), each then re-wrapped in its own envelope.
111    Chunked {
112        /// Maximum data bytes per chunk.
113        chunk_size: usize,
114    },
115}
116
117/// The bytes the transport adds around a payload on the wire, per framing path. Bundled as a named
118/// value so the framing rule reads `reserves.plan(len, limit)` instead of a row of positional
119/// `usize`s, and so the production reserves live in exactly one place ([`WireReserves::PRODUCTION`]).
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub struct WireReserves {
122    /// Bytes added around a *whole* payload - the outer custom frame (`custom_frame_wire`).
123    pub whole: usize,
124    /// Bytes added around *each chunk's* data - its `MessagePayload` envelope **and** the outer
125    /// custom frame (`custom_frame_wire`).
126    pub chunk: usize,
127    /// Smallest per-chunk data payload worth producing; a limit that cannot fit `chunk +
128    /// min_chunk_data` is rejected rather than fragmented into near-empty chunks.
129    pub min_chunk_data: usize,
130}
131
132impl WireReserves {
133    /// The reserves used in production, derived from the transport/message ceilings.
134    pub const PRODUCTION: Self = Self {
135        whole: TRANSPORT_CUSTOM_OVERHEAD,
136        chunk: MAX_CHUNK_ENVELOPE_OVERHEAD + TRANSPORT_CUSTOM_OVERHEAD,
137        min_chunk_data: MIN_CHUNK_DATA,
138    };
139
140    /// Frame a `payload_len`-byte payload for a connection whose negotiated per-message limit is
141    /// `max_message_size`. The decision is taken against the *wire* bytes (payload + reserves), not
142    /// the bare payload, and is a pure total function:
143    ///
144    /// ```text
145    ///   plan : (len, limit) -> Whole                   if len + whole <= limit
146    ///                       -> Chunked(limit - chunk)  if limit >= chunk + min_chunk_data
147    ///                       -> None                    otherwise
148    /// ```
149    ///
150    /// `None` means the peer's limit is too small for even one useful chunk - a failure the caller
151    /// surfaces, never a flood of 1-byte chunks. When `Chunked { chunk_size }` is returned,
152    /// `min_chunk_data <= chunk_size` and `chunk_size + chunk <= limit`, so every wrapped chunk fits
153    /// and a payload yields at most `ceil(len / min_chunk_data)` chunks. Every sum is `checked`, so
154    /// the function is total over all `usize` inputs (no overflow/underflow).
155    pub fn plan(&self, payload_len: usize, max_message_size: usize) -> Option<Framing> {
156        let whole_fits = payload_len
157            .checked_add(self.whole)
158            .is_some_and(|wire| wire <= max_message_size);
159        if whole_fits {
160            return Some(Framing::Whole);
161        }
162        let min_viable = self.chunk.checked_add(self.min_chunk_data)?;
163        (max_message_size >= min_viable).then(|| Framing::Chunked {
164            chunk_size: max_message_size - self.chunk,
165        })
166    }
167}