use std::{collections::HashMap, time::Instant};
use bytes::{Bytes, BytesMut};
pub const MAX_FRAGMENTS: usize = u16::MAX as usize;
const MAX_FRAG_RECV: u16 = 1_024;
const MAX_CONCURRENT_ASSEMBLIES: usize = 64;
struct Assembly {
total: u16,
received: u16,
pieces: Vec<Option<Bytes>>,
started_at: Instant,
}
pub struct FragAssembler {
in_flight: HashMap<u32, Assembly>,
}
impl FragAssembler {
#[must_use]
pub fn new() -> Self {
Self {
in_flight: HashMap::new(),
}
}
#[must_use]
pub fn insert(
&mut self,
msg_id: u32,
frag_idx: u16,
frag_total: u16,
payload: Bytes,
) -> Option<Bytes> {
if frag_total == 0 || frag_total > MAX_FRAG_RECV {
tracing::warn!(
target: "zudp::frag",
msg_id, frag_total, max = MAX_FRAG_RECV,
"fragment total out of range — dropping"
);
return None;
}
if frag_idx >= frag_total {
return None;
}
let is_new = !self.in_flight.contains_key(&msg_id);
if is_new && self.in_flight.len() >= MAX_CONCURRENT_ASSEMBLIES {
tracing::warn!(
target: "zudp::frag",
msg_id, cap = MAX_CONCURRENT_ASSEMBLIES,
"concurrent assembly cap reached — dropping fragment"
);
return None;
}
let assembly = self.in_flight.entry(msg_id).or_insert_with(|| Assembly {
total: frag_total,
received: 0,
pieces: vec![None; frag_total as usize],
started_at: Instant::now(),
});
if assembly.pieces[frag_idx as usize]
.replace(payload)
.is_none()
{
assembly.received += 1;
}
if assembly.received < assembly.total {
return None;
}
let assembly = self.in_flight.remove(&msg_id)?;
let total_bytes: usize = assembly.pieces.iter().flatten().map(Bytes::len).sum();
let mut out = BytesMut::with_capacity(total_bytes);
for piece in assembly.pieces.into_iter().flatten() {
out.extend_from_slice(&piece);
}
Some(out.freeze())
}
pub fn prune(&mut self, max_age: std::time::Duration) {
let cutoff = Instant::now()
.checked_sub(max_age)
.unwrap_or(Instant::now());
self.in_flight.retain(|_, a| a.started_at > cutoff);
}
}
pub fn fragment(data: &Bytes, mtu: usize) -> Result<Vec<Bytes>, crate::Error> {
let total = data.len().div_ceil(mtu);
if total > MAX_FRAGMENTS {
return Err(crate::Error::MessageTooLarge {
got: total,
max: MAX_FRAGMENTS,
});
}
let chunks = (0..total)
.map(|i| data.slice(i * mtu..((i + 1) * mtu).min(data.len())))
.collect();
Ok(chunks)
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use bytes::Bytes;
use super::*;
#[test]
fn single_fragment_completes_immediately() {
let mut fa = FragAssembler::new();
let data = Bytes::from_static(b"hello");
let result = fa.insert(0, 0, 1, data.clone());
assert_eq!(result.unwrap(), data);
assert!(
fa.in_flight.is_empty(),
"completed assembly must be removed"
);
}
#[test]
fn out_of_order_fragments_reassemble_correctly() {
let mut fa = FragAssembler::new();
let a = Bytes::from_static(b"hello");
let b = Bytes::from_static(b" world");
assert!(fa.insert(1, 1, 2, b).is_none());
let result = fa.insert(1, 0, 2, a);
assert_eq!(result.unwrap(), Bytes::from_static(b"hello world"));
}
#[test]
fn fragment_bomb_above_max_rejected() {
let mut fa = FragAssembler::new();
let result = fa.insert(99, 0, MAX_FRAG_RECV + 1, Bytes::from_static(b"evil"));
assert!(
result.is_none(),
"frag_total > MAX_FRAG_RECV must be rejected"
);
assert!(
fa.in_flight.is_empty(),
"no slot should be allocated for rejected frames"
);
}
#[test]
fn fragment_zero_total_rejected() {
let mut fa = FragAssembler::new();
let result = fa.insert(0, 0, 0, Bytes::from_static(b"bad"));
assert!(result.is_none());
assert!(fa.in_flight.is_empty());
}
#[test]
fn frag_idx_out_of_bounds_rejected() {
let mut fa = FragAssembler::new();
let result = fa.insert(0, 3, 3, Bytes::from_static(b"bad"));
assert!(result.is_none());
}
#[test]
#[allow(clippy::cast_possible_truncation)]
fn concurrent_assembly_cap_enforced() {
let mut fa = FragAssembler::new();
for id in 0..(MAX_CONCURRENT_ASSEMBLIES as u32) {
let result = fa.insert(id, 0, 2, Bytes::from_static(b"x"));
assert!(
result.is_none(),
"incomplete assembly should not complete on frag 0"
);
}
assert_eq!(fa.in_flight.len(), MAX_CONCURRENT_ASSEMBLIES);
#[allow(clippy::cast_possible_truncation)]
let overflow_id = MAX_CONCURRENT_ASSEMBLIES as u32;
let result = fa.insert(overflow_id, 0, 2, Bytes::from_static(b"overflow"));
assert!(result.is_none(), "assembly beyond cap must be rejected");
assert_eq!(
fa.in_flight.len(),
MAX_CONCURRENT_ASSEMBLIES,
"cap must not be exceeded"
);
}
#[test]
fn duplicate_fragment_does_not_double_count() {
let mut fa = FragAssembler::new();
let piece = Bytes::from_static(b"chunk");
let _ = fa.insert(1, 0, 2, piece.clone());
let _ = fa.insert(1, 0, 2, piece.clone()); let asm = fa.in_flight.get(&1).expect("assembly should be in flight");
assert_eq!(
asm.received, 1,
"duplicate must not increment received count"
);
}
#[test]
fn prune_keeps_fresh_assemblies() {
let mut fa = FragAssembler::new();
let _ = fa.insert(0, 0, 2, Bytes::from_static(b"piece0"));
fa.prune(Duration::from_hours(1)); assert_eq!(fa.in_flight.len(), 1, "fresh assembly must survive prune");
}
#[test]
fn prune_removes_stale_assemblies() {
let mut fa = FragAssembler::new();
let _ = fa.insert(0, 0, 2, Bytes::from_static(b"piece0"));
std::thread::sleep(Duration::from_millis(5));
fa.prune(Duration::from_millis(1));
assert_eq!(
fa.in_flight.len(),
0,
"stale assembly must be removed by prune"
);
}
}