Skip to main content

zaun_community_protocol/framing/
reassembly.rs

1//! Bounded fragment reassembly, one per connection (§5.2).
2//!
3//! Memory is bounded by construction: at most [`MAX_OPEN_REASSEMBLIES`] open reassemblies,
4//! each holding at most `max_frame` bytes of chunks in at most [`MAX_FRAGMENTS`] slots.
5
6use super::{FragId, Fragment};
7use crate::limits::{FRAGMENT_TIMEOUT_MS, MAX_FRAGMENTS, MAX_FRAME, MAX_OPEN_REASSEMBLIES};
8
9/// Why a reassembly (or a fragment that would start one) was discarded. A discard produces no
10/// response; the sender's retry repairs it (§5.2, §7.3).
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum DiscardReason {
13    /// The same index arrived again with different content.
14    ConflictingChunk,
15    /// The same `frag_id` arrived with a different `count`.
16    ConflictingCount,
17    /// `count` exceeds [`MAX_FRAGMENTS`].
18    TooManyFragments,
19    /// The chunks received exceed `max_frame` bytes.
20    TooLarge,
21    /// A hand-built [`Fragment`] with `count < 2` or `index ≥ count` ([`super::classify`] never
22    /// yields one); it is dropped without touching any reassembly.
23    InvalidFragment,
24}
25
26/// The result of pushing one fragment.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum Pushed {
29    /// The frame is complete: the envelope JSON text, to be parsed as an envelope.
30    Complete(String),
31    /// Stored; more fragments are needed.
32    Pending,
33    /// An identical repeat of a stored fragment; ignored.
34    Duplicate,
35    /// The fragment's whole reassembly was discarded.
36    Discarded(DiscardReason),
37}
38
39#[derive(Debug)]
40struct Open {
41    id: FragId,
42    started_ms: u64,
43    count: usize,
44    chunks: Vec<Option<String>>,
45    received: usize,
46    bytes: usize,
47}
48
49/// Per-connection reassembly state machine (§5.2).
50#[derive(Debug)]
51pub struct Reassembler {
52    /// Open reassemblies in order of their first fragment's arrival (oldest first).
53    open: Vec<Open>,
54    max_frame: usize,
55}
56
57impl Default for Reassembler {
58    fn default() -> Self {
59        Self::new()
60    }
61}
62
63impl Reassembler {
64    /// A reassembler with the protocol's `max_frame` ([`MAX_FRAME`]).
65    #[must_use]
66    pub fn new() -> Self {
67        Self::with_max_frame(MAX_FRAME)
68    }
69
70    /// A reassembler with a stricter host `max_frame` (§12); never above [`MAX_FRAME`].
71    #[must_use]
72    pub fn with_max_frame(max_frame: usize) -> Self {
73        Self {
74            open: Vec::with_capacity(MAX_OPEN_REASSEMBLIES),
75            max_frame: max_frame.min(MAX_FRAME),
76        }
77    }
78
79    /// Discards reassemblies whose first fragment arrived more than 60 s before `now_ms`
80    /// (exactly 60 s is still accepted). Returns how many were discarded.
81    pub fn expire(&mut self, now_ms: u64) -> usize {
82        let before = self.open.len();
83        self.open
84            .retain(|o| now_ms.saturating_sub(o.started_ms) <= FRAGMENT_TIMEOUT_MS);
85        before - self.open.len()
86    }
87
88    /// Pushes one fragment received at `now_ms`. Expired reassemblies are discarded first.
89    pub fn push(&mut self, fragment: Fragment<'_>, now_ms: u64) -> Pushed {
90        if fragment.count < 2 || fragment.index >= fragment.count {
91            return Pushed::Discarded(DiscardReason::InvalidFragment);
92        }
93        self.expire(now_ms);
94        let position = self.open.iter().position(|o| o.id == fragment.frag_id);
95        if fragment.count > MAX_FRAGMENTS {
96            return self.discard(position, DiscardReason::TooManyFragments);
97        }
98        let Some(i) = position else {
99            return self.start(fragment, now_ms);
100        };
101        let open = &mut self.open[i];
102        if open.count != fragment.count {
103            return self.discard(position, DiscardReason::ConflictingCount);
104        }
105        match &open.chunks[fragment.index] {
106            Some(stored) if stored == fragment.chunk => return Pushed::Duplicate,
107            Some(_) => return self.discard(position, DiscardReason::ConflictingChunk),
108            None => {}
109        }
110        if open.bytes + fragment.chunk.len() > self.max_frame {
111            return self.discard(position, DiscardReason::TooLarge);
112        }
113        open.bytes += fragment.chunk.len();
114        open.received += 1;
115        open.chunks[fragment.index] = Some(fragment.chunk.to_owned());
116        if open.received < open.count {
117            return Pushed::Pending;
118        }
119        let done = self.open.remove(i);
120        Pushed::Complete(done.chunks.into_iter().flatten().collect())
121    }
122
123    /// Number of open reassemblies (≤ [`MAX_OPEN_REASSEMBLIES`]).
124    #[must_use]
125    pub fn open_count(&self) -> usize {
126        self.open.len()
127    }
128
129    /// Chunk bytes currently buffered (≤ `MAX_OPEN_REASSEMBLIES × max_frame`).
130    #[must_use]
131    pub fn buffered_bytes(&self) -> usize {
132        self.open.iter().map(|o| o.bytes).sum()
133    }
134
135    fn start(&mut self, fragment: Fragment<'_>, now_ms: u64) -> Pushed {
136        if fragment.chunk.len() > self.max_frame {
137            return Pushed::Discarded(DiscardReason::TooLarge);
138        }
139        if self.open.len() == MAX_OPEN_REASSEMBLIES {
140            // A fifth reassembly discards the oldest (§5.2).
141            self.open.remove(0);
142        }
143        let mut chunks = vec![None; fragment.count];
144        chunks[fragment.index] = Some(fragment.chunk.to_owned());
145        self.open.push(Open {
146            id: fragment.frag_id,
147            started_ms: now_ms,
148            count: fragment.count,
149            chunks,
150            received: 1,
151            bytes: fragment.chunk.len(),
152        });
153        Pushed::Pending
154    }
155
156    fn discard(&mut self, position: Option<usize>, reason: DiscardReason) -> Pushed {
157        if let Some(i) = position {
158            self.open.remove(i);
159        }
160        Pushed::Discarded(reason)
161    }
162}