Skip to main content

rings_core/chunk/
reassembly.rs

1use std::collections::BTreeMap;
2use std::collections::HashMap;
3use std::collections::HashSet;
4use std::collections::VecDeque;
5
6use bytes::Bytes;
7use rings_transport::core::pool::ChannelLane;
8use uuid::Uuid;
9
10use super::progress::Progress;
11use super::progress::RateFloor;
12use super::Chunk;
13use super::ReassemblyLimits;
14use crate::consts::MAX_TTL_MS;
15use crate::consts::TS_OFFSET_TOLERANCE_MS;
16use crate::utils::get_epoch_ms;
17
18/// One message being reassembled: the chunks seen so far, keyed by position, and the charge
19/// its first chunk took for the whole message.
20pub(super) struct Pending<C> {
21    /// total number of chunks the message claims (from `chunk[1]`).
22    total: usize,
23    /// `d₀`, the data length of the first chunk, which no later chunk may exceed, so the
24    /// message's data never passes the `n·d₀` its first chunk was charged for.
25    first_len: usize,
26    /// received positions -> bytes. A `BTreeMap` dedups by position (first write wins) and keeps
27    /// the data ordered, so assembly is a single in-order concat.
28    pub(super) slots: BTreeMap<usize, Bytes>,
29    /// creation time / ttl of the first chunk seen, used for TTL eviction.
30    ts_ms: u128,
31    ttl_ms: u64,
32    /// This logical transmission already produced its one peer-attributable failure.
33    failure_charged: bool,
34    /// Every retained chunk was bound to an authenticated peer at ingress.
35    peer_attributable: bool,
36    /// The lane the first chunk arrived on, which every later chunk must share.
37    carrier: Option<ChannelLane>,
38    /// The charge the first chunk took for the whole message (load-bounds paper, Law 4): held
39    /// while the message is reassembled and handed on with it, released by drop.
40    charge: C,
41    /// The message's credit-time ledger, which its rate floor reads.
42    progress: Progress,
43}
44
45impl<C> Pending<C> {
46    /// The rate floor of this message under `limits`.
47    fn rate_floor(&self, limits: &ReassemblyLimits) -> RateFloor {
48        RateFloor {
49            rate: limits.rate_floor,
50            chunk: u64::try_from(self.first_len).unwrap_or(u64::MAX),
51            grace_chunks: limits.grace_chunks,
52        }
53    }
54
55    /// Whether the message is past its own expiry at `now`.
56    fn ttl_expired(&self, now: u128) -> bool {
57        self.ts_ms.saturating_add(u128::from(self.ttl_ms)) <= now
58    }
59
60    /// Complete iff every position has arrived. Each inserted position is unique (map key) and in
61    /// `0..total`, so `slots.len() == total` iff the present set is exactly `{0..total-1}`.
62    fn is_complete(&self) -> bool {
63        self.slots.len() == self.total
64    }
65
66    /// Whether `chunk`, carried on `carrier`, joins this in-flight message: it agrees on the
67    /// message's shape and provenance, is no longer than the first chunk, and fills a position
68    /// still free.
69    fn admits(&self, chunk: &Chunk, carrier: Option<ChannelLane>) -> Result<(), Rejected> {
70        let [position, total] = chunk.chunk;
71        if self.total != total {
72            return Err(Rejected::TotalMismatch);
73        }
74        // Chunks of one message share id+ts+ttl; a same-id chunk from a different transmission
75        // must not be merged in (it would skew expiry/tombstone behaviour).
76        if self.ts_ms != chunk.meta.ts_ms || self.ttl_ms != chunk.meta.ttl_ms {
77            return Err(Rejected::MetadataMismatch);
78        }
79        // A message's chunks travel one lane; one that changes lanes would take credit on a lane
80        // its content does not belong to.
81        if self.carrier != carrier {
82            return Err(Rejected::CarrierMismatch);
83        }
84        // The first chunk was charged for `n·d₀`; a longer chunk would pass that charge.
85        if chunk.data.len() > self.first_len {
86            return Err(Rejected::LongerThanFirst);
87        }
88        // First write per position wins; a duplicate position is a no-op, not an error.
89        match self.slots.get(&position) {
90            Some(existing) if existing == &chunk.data => Err(Rejected::DuplicatePosition),
91            Some(_) => Err(Rejected::ConflictingPosition),
92            None => Ok(()),
93        }
94    }
95}
96
97/// Stable identity of one logical transmission. A UUID may be reused after the
98/// prior transmission's TTL, so terminal evidence also includes its timestamp
99/// and TTL rather than blocking that UUID indefinitely.
100#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
101struct LogicalTransmission {
102    id: Uuid,
103    ts_ms: u128,
104    ttl_ms: u64,
105}
106
107impl LogicalTransmission {
108    const fn new(id: Uuid, ts_ms: u128, ttl_ms: u64) -> Self {
109        Self { id, ts_ms, ttl_ms }
110    }
111}
112
113/// Receiver side: **whole-message** reassembly for reliable data-channel `MessagePayload`
114/// fragments. Buffers a message's chunks keyed by id and yields the complete [`Bytes`] once every
115/// position has arrived (then forgets it).
116///
117/// Correct under duplicates / retransmits (first write per position wins *during* assembly),
118/// partial delivery (TTL eviction), and a message **fully retransmitted after it already
119/// completed**: a completed id is kept as a tombstone until it would expire, so a late re-send
120/// within the TTL window is dropped rather than re-assembled and delivered twice.
121///
122/// **One charge per message** (load-bounds paper, Law 4, #932). A message is opened only by its
123/// first chunk, `[0, n]` with data length `d₀`, and only when `(n − 1)·d₀` stays below
124/// [`ReassemblyLimits::max_message_bytes`]; the charge `C` that chunk brings (the receiver's
125/// mailbox reservation of `n·d₀`) is held with the message. Every later chunk is at most `d₀`
126/// long, so the message never outgrows that charge, and the charge a later chunk brings is
127/// dropped. The charge leaves with the completed message (`RetainedReassembly`), or is dropped
128/// when the message expires or the reassembler closes. The reassembler itself holds no budget
129/// and refuses nothing for capacity: its remaining caps (ids, slots, chunk length, message
130/// length) are validity bounds an honest sender never meets.
131///
132/// ```text
133/// chunk [0, n], d₀ ── new id, (n − 1)·d₀ < max ──▶ open(charge)        (Incomplete)
134/// chunk [i, n], dᵢ ── open, dᵢ ≤ d₀, slot free ───▶ insert; drop charge (Incomplete | Complete)
135/// chunk [i > 0, n] ── no open message ────────────▶ Rejected(Invalid | Replay)
136/// expiry, stall, close ───────────────────────────▶ drop(message, charge)
137/// ```
138///
139/// **Rate floor.** An open message also expires, attributably, once the bytes it received fall
140/// below the rate floor over the credit-time its sender held unused credit for, less one lane
141/// window of grace (`progress`; load-bounds paper, Def. 7 and Law 4). The caller reads that
142/// credit, per carrier, from its transport; a caller that reads none (`|_| 0`, as the plain API
143/// does) never advances the clock, and a message then expires at its TTL alone.
144pub struct MessageReassembler<C = ()> {
145    pub(super) pending: HashMap<Uuid, Pending<C>>,
146    /// Tombstones for ids that have already been delivered, each paired with its expiry
147    /// (`ts_ms + ttl_ms`). A chunk for one of these is dropped, so a post-completion retransmit of a
148    /// whole message is not re-assembled and delivered again. `VecDeque` for FIFO/TTL eviction, the
149    /// `HashSet` for an O(1) membership check; the two are kept in lockstep.
150    completed: VecDeque<(Uuid, u128)>,
151    pub(super) completed_ids: HashSet<Uuid>,
152    /// Failed or expired logical transmissions retained until a bounded local horizon. Once a
153    /// transmission has produced a terminal failure, later chunks with the same UUID, timestamp,
154    /// and TTL are replays rather than a second failure or a successful delivery. New failures are
155    /// fail-open (not attributed) while this bounded set is full, so hostile UUID rotation cannot
156    /// make memory unbounded.
157    failed: VecDeque<(LogicalTransmission, u128)>,
158    failed_ids: HashSet<LogicalTransmission>,
159    /// When invalid-terminal tracking saturates, new invalid arrivals fail open and untracked
160    /// already-scored expiries remain replays until this horizon. This prevents a retained expiry
161    /// from being charged again merely because an older tombstone drains first.
162    failure_tracking_saturated_until: u128,
163    /// The bounds enforced on every incoming chunk.
164    limits: ReassemblyLimits,
165}
166
167/// A completed message and the charge its first chunk took for it.
168pub(crate) struct RetainedReassembly<C> {
169    bytes: Bytes,
170    /// The charge, handed on with the message.
171    charge: C,
172    /// The lane every chunk of the message arrived on.
173    carrier: Option<ChannelLane>,
174}
175
176/// Result of applying one chunk to a reassembler.
177pub(crate) enum ReassemblyOutcome<C> {
178    /// The chunk was admitted but the message is not complete yet.
179    Incomplete,
180    /// The chunk completed a message, which carries its charge.
181    Complete(RetainedReassembly<C>),
182    /// The chunk was rejected without mutating retained reassembly state.
183    Rejected(ReassemblyRejection),
184}
185
186/// Whether a rejected chunk is evidence about the remote peer: no rejection is for capacity.
187#[derive(Clone, Copy, Debug, Eq, PartialEq)]
188pub(crate) enum ReassemblyRejection {
189    /// The wire shape, timestamp, metadata, or size is remotely invalid.
190    Invalid,
191    /// The chunk is stale or repeats a position or a message already accepted.
192    Replay,
193}
194
195impl<C> RetainedReassembly<C> {
196    /// The lane every chunk of the message arrived on, for the receiver to check against the
197    /// lane its content belongs to.
198    pub(crate) const fn carrier(&self) -> Option<ChannelLane> {
199        self.carrier
200    }
201
202    /// The message's bytes and its charge.
203    pub(crate) fn into_parts(self) -> (Bytes, C) {
204        (self.bytes, self.charge)
205    }
206}
207
208impl<C> AsRef<[u8]> for RetainedReassembly<C> {
209    fn as_ref(&self) -> &[u8] {
210        &self.bytes
211    }
212}
213
214impl Default for MessageReassembler {
215    fn default() -> Self {
216        Self::with_limits(ReassemblyLimits::production())
217    }
218}
219
220impl MessageReassembler {
221    /// Empty reassembler with [`ReassemblyLimits::production`] bounds, holding no charge.
222    pub fn new() -> Self {
223        Self::default()
224    }
225
226    /// Accept one chunk. Returns the fully reassembled payload when this chunk completes its
227    /// message (which is then forgotten), otherwise `None`.
228    pub fn handle(&mut self, chunk: Chunk) -> Option<Bytes> {
229        self.handle_at(chunk, get_epoch_ms())
230    }
231
232    /// [`handle`](Self::handle) with the clock injected, so tests drive expiry/admission against a
233    /// controlled `now` through the real production path instead of poking internal state.
234    pub(super) fn handle_at(&mut self, chunk: Chunk, now: u128) -> Option<Bytes> {
235        match self
236            .handle_charged_at(chunk, (), (now, no_credit), true, None)
237            .0
238        {
239            ReassemblyOutcome::Complete(retained) => Some(retained.into_parts().0),
240            ReassemblyOutcome::Incomplete | ReassemblyOutcome::Rejected(_) => None,
241        }
242    }
243
244    /// Accept one chunk while preserving incomplete, complete, and rejected states.
245    #[cfg(test)]
246    pub(crate) fn handle_retained_outcome_at(
247        &mut self,
248        chunk: Chunk,
249        now: u128,
250    ) -> ReassemblyOutcome<()> {
251        self.handle_charged_at(chunk, (), (now, no_credit), true, None)
252            .0
253    }
254}
255
256impl<C> MessageReassembler<C> {
257    /// Empty reassembler enforcing the given `limits`, whose messages hold charges `C`. Tests
258    /// use this with small limits to exercise the admission rule without giant synthetic
259    /// payloads.
260    pub fn with_limits(limits: ReassemblyLimits) -> Self {
261        Self {
262            pending: HashMap::new(),
263            completed: VecDeque::new(),
264            completed_ids: HashSet::new(),
265            failed: VecDeque::new(),
266            failed_ids: HashSet::new(),
267            failure_tracking_saturated_until: 0,
268            // Clamp nonsensical caps so a caller cannot disable an invariant (e.g. a `0` cap).
269            limits: limits.normalized(),
270        }
271    }
272
273    /// Record `id` as delivered so a later full retransmit (within the TTL window) is suppressed,
274    /// dropping the oldest tombstone if the cap is reached. `expiry` is the message's `ts_ms +
275    /// ttl_ms` - after it, a retransmit is rejected by the expiry check anyway, so the tombstone
276    /// can go.
277    fn mark_completed(&mut self, id: Uuid, expiry: u128) {
278        if self.completed_ids.insert(id) {
279            self.completed.push_back((id, expiry));
280        }
281        while self.completed.len() > self.limits.max_completed_ids {
282            if let Some((old, _)) = self.completed.pop_front() {
283                self.completed_ids.remove(&old);
284            }
285        }
286    }
287
288    /// Number of messages currently being reassembled (incomplete).
289    pub fn pending_count(&self) -> usize {
290        self.pending.len()
291    }
292
293    /// Maximum reassembled message length in bytes configured on this reassembler.
294    pub(crate) const fn max_message_bytes(&self) -> usize {
295        self.limits.max_message_bytes
296    }
297
298    /// Drop messages whose TTL has elapsed, with their charges, and evict completed-id
299    /// tombstones that have likewise expired (a retransmit past its expiry is rejected anyway).
300    pub fn remove_expired(&mut self) {
301        let _ = self.remove_expired_at(get_epoch_ms());
302    }
303
304    /// Return whether any incomplete logical message is still retained.
305    pub(crate) fn has_pending(&self) -> bool {
306        !self.pending.is_empty()
307    }
308
309    /// Drop close-time state that cannot produce a future peer-attributable failure.
310    ///
311    /// No more chunks can arrive after the owning mailbox closes, so completed
312    /// and rejected-id tombstones have no purpose. Incomplete messages are
313    /// retained only when their original authenticated ingress can still yield
314    /// one failure at TTL; all other messages are dropped with their charges now.
315    pub(crate) fn prepare_for_close(&mut self) -> bool {
316        self.pending
317            .retain(|_, pending| pending.peer_attributable && !pending.failure_charged);
318        self.clear_terminal_history();
319        !self.pending.is_empty()
320    }
321
322    /// Drop every close-time message, with its charge, when no timer can deliver TTL cleanup.
323    pub(crate) fn discard_after_close_timer_failure(&mut self) {
324        self.pending.clear();
325        self.clear_terminal_history();
326    }
327
328    fn clear_terminal_history(&mut self) {
329        self.completed.clear();
330        self.completed_ids.clear();
331        self.failed.clear();
332        self.failed_ids.clear();
333        self.failure_tracking_saturated_until = 0;
334    }
335
336    /// [`remove_expired`](Self::remove_expired) with the clock injected (tests pass a controlled
337    /// `now` to drive the real eviction logic); returns how many expired messages are peer
338    /// evidence.
339    pub(crate) fn remove_expired_at(&mut self, now: u128) -> usize {
340        self.sweep_at(now, no_credit)
341    }
342
343    /// Sample every open message at `now`, its sender holding `credit(carrier)` unused, and drop
344    /// those past their TTL or below their rate floor, with their charges; returns how many of
345    /// them are peer evidence.
346    pub(crate) fn sweep_at(
347        &mut self,
348        now: u128,
349        credit: impl Fn(Option<ChannelLane>) -> u64,
350    ) -> usize {
351        self.evict_expired_terminal_history(now);
352        let mut expired_count = 0_usize;
353        let mut expired_transmissions = Vec::new();
354        let limits = self.limits;
355        self.pending.retain(|id, p| {
356            let floor = p.rate_floor(&limits);
357            p.progress.observe(now, credit(p.carrier), floor);
358            let alive = !p.ttl_expired(now) && !p.progress.stalled(floor);
359            if !alive {
360                expired_transmissions.push(LogicalTransmission::new(*id, p.ts_ms, p.ttl_ms));
361                if !p.failure_charged && p.peer_attributable {
362                    expired_count = expired_count.saturating_add(1);
363                }
364            }
365            alive
366        });
367        // Keep a bounded terminal witness after removing the pending buffer. This distinguishes a
368        // late chunk for an already-scored expiry from a first expired-on-arrival chunk, which is
369        // invalid evidence. At capacity `mark_failed_transmission` fails open for reputation by
370        // classifying the event as Replay without growing memory. Its saturation horizon keeps
371        // that classification stable if an older tombstone drains first; after the bounded
372        // horizon, exact-once history is intentionally forgotten with the tombstones.
373        for transmission in expired_transmissions {
374            if !self.mark_failed_transmission(transmission, now) {
375                // This expiry has already contributed to `expired_count`. Keep its untracked
376                // witness horizon alive even when a prior saturation interval was already active.
377                self.extend_failure_tracking_saturation(now);
378            }
379        }
380        expired_count
381    }
382
383    fn evict_expired_terminal_history(&mut self, now: u128) {
384        // Evict every expired tombstone, not just a leading run: completion order need not equal
385        // expiry order, so a `retain` is correct where front-popping would leave an out-of-order
386        // early-expiry entry behind a still-live front.
387        let completed_ids = &mut self.completed_ids;
388        self.completed.retain(|&(id, expiry)| {
389            let alive = expiry > now;
390            if !alive {
391                completed_ids.remove(&id);
392            }
393            alive
394        });
395        let failed_ids = &mut self.failed_ids;
396        self.failed.retain(|&(transmission, expiry)| {
397            let alive = expiry > now;
398            if !alive {
399                failed_ids.remove(&transmission);
400            }
401            alive
402        });
403    }
404
405    /// Forget a message (e.g. after it has been delivered), dropping its charge.
406    pub fn remove(&mut self, id: Uuid) {
407        self.pending.remove(&id);
408    }
409
410    /// Accept one chunk that brought `charge`, against the caller's clock, and also report how
411    /// many older incomplete logical messages expired before admission; the runtime adapter
412    /// records one peer failure per expired message.
413    ///
414    /// Imperative shell over a functional core: expire stale state, ask the pure `classify` for an
415    /// admission verdict, and apply it. Accepted data mutation stays in `admit`, which keeps
416    /// `charge` iff the chunk opens its message; the shell records only bounded terminal evidence
417    /// for rejected chunks, so one logical id cannot produce conflicting terminal outcomes.
418    pub(crate) fn handle_charged_at(
419        &mut self,
420        chunk: Chunk,
421        charge: C,
422        (now, credit): (u128, impl Fn(Option<ChannelLane>) -> u64),
423        peer_attributable: bool,
424        carrier: Option<ChannelLane>,
425    ) -> (ReassemblyOutcome<C>, usize) {
426        // Reclaim expired and stalled pending entries and tombstones first, before classify
427        // reads them, so invalid traffic still frees memory and an expired tombstone cannot
428        // suppress a fresh message that reuses its id after the TTL window.
429        let expired = self.sweep_at(now, &credit);
430        let outcome = match self.classify(&chunk, now, carrier) {
431            Ok(()) => self.admit(
432                chunk,
433                charge,
434                (now, credit(carrier)),
435                (peer_attributable, carrier),
436            ),
437            Err(reason) => {
438                tracing::debug!(?reason, id = ?chunk.meta.id, "reassembler dropped chunk");
439                let rejection = match reason.rejection() {
440                    ReassemblyRejection::Invalid if self.mark_logical_failure(&chunk, now) => {
441                        ReassemblyRejection::Invalid
442                    }
443                    ReassemblyRejection::Invalid | ReassemblyRejection::Replay => {
444                        ReassemblyRejection::Replay
445                    }
446                };
447                ReassemblyOutcome::Rejected(rejection)
448            }
449        };
450        (outcome, expired)
451    }
452
453    /// The pure admission rule: `(state, chunk, now) -> Ok(()) | Err(reason)`. Borrows `&self`,
454    /// mutates nothing, does no I/O; on failure a typed [`Rejected`] reason. The surrounding shell
455    /// may retain bounded failure evidence after this pure verdict.
456    fn classify(
457        &self,
458        chunk: &Chunk,
459        now: u128,
460        carrier: Option<ChannelLane>,
461    ) -> Result<(), Rejected> {
462        let meta = &chunk.meta;
463        let transmission = LogicalTransmission::new(meta.id, meta.ts_ms, meta.ttl_ms);
464        if self
465            .pending
466            .get(&meta.id)
467            .is_some_and(|pending| pending.failure_charged)
468            || self.failed_ids.contains(&transmission)
469        {
470            return Err(Rejected::AlreadyFailed);
471        }
472        if meta.ttl_ms > MAX_TTL_MS {
473            return Err(Rejected::TtlTooLarge);
474        }
475        // `saturating_sub` avoids the `u128` underflow a forged `ts_ms < TS_OFFSET_TOLERANCE_MS`
476        // would cause; `saturating_add` avoids overflow on a forged ttl.
477        if meta.ts_ms.saturating_sub(TS_OFFSET_TOLERANCE_MS) > now {
478            return Err(Rejected::FutureTimestamp);
479        }
480        // Reject an already-expired chunk up front, so a stale `total == 1` is never delivered.
481        if meta.ts_ms.saturating_add(meta.ttl_ms as u128) <= now {
482            return Err(Rejected::Expired);
483        }
484
485        let [position, total] = chunk.chunk;
486        // A real message has at least one chunk and every position in `0..total`.
487        if total == 0 || position >= total {
488            return Err(Rejected::Malformed);
489        }
490        // Cap the slot count: a forged `total` is refused before it can allocate a huge `BTreeMap`.
491        if total > self.limits.max_chunks_per_message {
492            return Err(Rejected::TooManyChunks);
493        }
494        // One chunk cannot exceed one data-channel message.
495        if chunk.data.len() > self.limits.max_chunk_data_len {
496            return Err(Rejected::ChunkTooLarge);
497        }
498        // Already delivered: drop a post-completion retransmit (expired tombstones were swept).
499        if self.completed_ids.contains(&meta.id) {
500            return Err(Rejected::AlreadyCompleted);
501        }
502        match self.pending.get(&meta.id) {
503            Some(pending) => pending.admits(chunk, carrier),
504            // Only the first chunk, which the receiver charged for the whole message, opens it;
505            // an honest sender sends a message's chunks in order on one lane.
506            None if position != 0 => Err(Rejected::MissingFirstChunk),
507            // An honest connection has at most one message open per lane.
508            None if self.pending.len() >= self.limits.max_pending_messages => {
509                Err(Rejected::PendingFull)
510            }
511            // `(n − 1)·d₀ < max`: an honest message of at most `max` bytes cut into chunks of
512            // `d₀` has `n = ⌈len / d₀⌉`, so its first `n − 1` chunks hold fewer than `max` bytes.
513            None if (total - 1).saturating_mul(chunk.data.len())
514                >= self.limits.max_message_bytes =>
515            {
516                Err(Rejected::PerMessageBytes)
517            }
518            None => Ok(()),
519        }
520    }
521
522    fn mark_logical_failure(&mut self, chunk: &Chunk, now: u128) -> bool {
523        let meta = &chunk.meta;
524        if let Some(pending) = self.pending.get_mut(&meta.id) {
525            if pending.failure_charged {
526                return false;
527            }
528            pending.failure_charged = true;
529            return true;
530        }
531
532        self.mark_failed_transmission(
533            LogicalTransmission::new(meta.id, meta.ts_ms, meta.ttl_ms),
534            now,
535        )
536    }
537
538    fn mark_failed_transmission(&mut self, transmission: LogicalTransmission, now: u128) -> bool {
539        if self.failed_ids.contains(&transmission) || self.failure_tracking_saturated_until > now {
540            return false;
541        }
542        if self.failed_ids.len() >= self.limits.max_completed_ids {
543            self.extend_failure_tracking_saturation(now);
544            return false;
545        }
546        // Invalid timestamps/TTLs must not pin terminal state longer than the protocol maximum.
547        // Using a local horizon also gives a well-defined reuse point for a malformed identity.
548        let expiry = now.saturating_add(MAX_TTL_MS as u128);
549        self.failed_ids.insert(transmission);
550        self.failed.push_back((transmission, expiry));
551        true
552    }
553
554    fn extend_failure_tracking_saturation(&mut self, now: u128) {
555        self.failure_tracking_saturated_until = self
556            .failure_tracking_saturated_until
557            .max(now.saturating_add(MAX_TTL_MS as u128));
558    }
559
560    /// The sole buffer mutation: insert a [`classify`]-approved `chunk`; a first chunk opens its
561    /// message with `charge`, any other drops it. If the chunk completes its message, take it
562    /// out, tombstone the id, and return the reassembled payload with its charge.
563    ///
564    /// [`classify`]: Self::classify
565    fn admit(
566        &mut self,
567        chunk: Chunk,
568        charge: C,
569        (now, credit): (u128, u64),
570        (peer_attributable, carrier): (bool, Option<ChannelLane>),
571    ) -> ReassemblyOutcome<C> {
572        let id = chunk.meta.id;
573        let [position, total] = chunk.chunk;
574        let received = u64::try_from(chunk.data.len()).unwrap_or(u64::MAX);
575        let mut pending = match self.pending.remove(&id) {
576            Some(mut pending) => {
577                let floor = pending.rate_floor(&self.limits);
578                pending.progress.observe(now, credit, floor);
579                pending.progress.receive(received);
580                pending
581            }
582            None => Pending {
583                total,
584                first_len: chunk.data.len(),
585                slots: BTreeMap::new(),
586                ts_ms: chunk.meta.ts_ms,
587                ttl_ms: chunk.meta.ttl_ms,
588                failure_charged: false,
589                peer_attributable,
590                carrier,
591                charge,
592                progress: Progress::open(now, credit, received),
593            },
594        };
595        pending.peer_attributable &= peer_attributable;
596        pending.slots.insert(position, chunk.data);
597
598        if !pending.is_complete() {
599            self.pending.insert(id, pending);
600            #[cfg(all(test, feature = "dummy", not(target_family = "wasm")))]
601            crate::simulation::observe_reassembly_pending(
602                self.pending.len(),
603                self.limits.max_pending_messages,
604            );
605            return ReassemblyOutcome::Incomplete;
606        }
607        let expiry = pending.ts_ms.saturating_add(pending.ttl_ms as u128);
608        // Tombstone the id until it would expire, so a later full retransmit is suppressed.
609        self.mark_completed(id, expiry);
610        ReassemblyOutcome::Complete(RetainedReassembly {
611            bytes: pending.slots.into_values().flatten().collect(),
612            charge: pending.charge,
613            carrier: pending.carrier,
614        })
615    }
616}
617
618/// Why a chunk was not admitted - a value, so [`MessageReassembler::classify`] stays a pure total
619/// function the shell can test and log uniformly, rather than scattering ad-hoc log strings.
620#[derive(Debug, Clone, Copy, PartialEq, Eq)]
621enum Rejected {
622    /// `ttl_ms` exceeds [`MAX_TTL_MS`].
623    TtlTooLarge,
624    /// Stamped further in the future than [`TS_OFFSET_TOLERANCE_MS`] allows.
625    FutureTimestamp,
626    /// Already past its `ts_ms + ttl_ms` expiry.
627    Expired,
628    /// `total == 0` or `position >= total`.
629    Malformed,
630    /// `total` exceeds [`ReassemblyLimits::max_chunks_per_message`].
631    TooManyChunks,
632    /// `data` exceeds [`ReassemblyLimits::max_chunk_data_len`].
633    ChunkTooLarge,
634    /// The message id is tombstoned (already delivered).
635    AlreadyCompleted,
636    /// This in-flight logical transmission already produced its failure outcome.
637    AlreadyFailed,
638    /// A later chunk of a message no first chunk opened.
639    MissingFirstChunk,
640    /// A new id, but [`ReassemblyLimits::max_pending_messages`] is already reached.
641    PendingFull,
642    /// `total` disagrees with the in-flight message's.
643    TotalMismatch,
644    /// `ts_ms`/`ttl_ms` disagree with the in-flight message's (a different transmission).
645    MetadataMismatch,
646    /// The chunk arrived on another lane than the in-flight message's first chunk.
647    CarrierMismatch,
648    /// The chunk is longer than its message's first chunk.
649    LongerThanFirst,
650    /// This position is already buffered (a duplicate/retransmit).
651    DuplicatePosition,
652    /// This position is buffered with different bytes.
653    ConflictingPosition,
654    /// The first chunk claims a message of [`ReassemblyLimits::max_message_bytes`] or more.
655    PerMessageBytes,
656}
657
658impl Rejected {
659    const fn rejection(self) -> ReassemblyRejection {
660        match self {
661            Self::AlreadyCompleted | Self::AlreadyFailed | Self::DuplicatePosition => {
662                ReassemblyRejection::Replay
663            }
664            Self::TtlTooLarge
665            | Self::FutureTimestamp
666            // An expired-on-arrival id has no retained expiry outcome. Treat it
667            // as invalid once; `mark_logical_failure` tombstones duplicate ids.
668            | Self::Expired
669            | Self::Malformed
670            | Self::TooManyChunks
671            | Self::ChunkTooLarge
672            | Self::MissingFirstChunk
673            | Self::PendingFull
674            | Self::TotalMismatch
675            | Self::MetadataMismatch
676            | Self::CarrierMismatch
677            | Self::LongerThanFirst
678            | Self::ConflictingPosition
679            | Self::PerMessageBytes => ReassemblyRejection::Invalid,
680        }
681    }
682}
683
684/// The credit reading of a caller that reads none: no sender ever holds unused credit, so the
685/// rate floor's clock never advances.
686const fn no_credit(_carrier: Option<ChannelLane>) -> u64 {
687    0
688}