use std::{
collections::{HashMap, hash_map::Entry},
num::NonZeroUsize,
time::{Duration, Instant},
};
use super::{
ContinuationFrameHeader,
MessageKey,
budget::{AggregateBudgets, ContinuationLimits, check_aggregate_budgets, check_size_limit},
error::{MessageAssemblyError, MessageSeriesError, MessageSeriesStatus},
partial::PartialAssembly,
streaming::{StreamingAssembly, StreamingAssemblyId},
types::{AssembledMessage, FirstFrameInput},
validation,
};
#[derive(Debug)]
pub struct MessageAssemblyState {
pub(super) max_message_size: NonZeroUsize,
pub(super) timeout: Duration,
pub(super) assemblies: HashMap<MessageKey, PartialAssembly>,
pub(super) streaming_assemblies: HashMap<MessageKey, StreamingAssembly>,
pub(super) streaming_generation: u64,
pub(super) deferred_streaming_evictions: Vec<StreamingAssemblyId>,
budgets: AggregateBudgets,
}
impl MessageAssemblyState {
#[must_use]
pub fn new(max_message_size: NonZeroUsize, timeout: Duration) -> Self {
Self::with_budgets(max_message_size, timeout, None, None)
}
#[must_use]
pub fn with_budgets(
max_message_size: NonZeroUsize,
timeout: Duration,
connection_budget: Option<NonZeroUsize>,
in_flight_budget: Option<NonZeroUsize>,
) -> Self {
Self {
max_message_size,
timeout,
assemblies: HashMap::new(),
streaming_assemblies: HashMap::new(),
streaming_generation: 0,
deferred_streaming_evictions: Vec::new(),
budgets: AggregateBudgets {
connection: connection_budget,
in_flight: in_flight_budget,
},
}
}
pub fn accept_first_frame(
&mut self,
input: FirstFrameInput<'_>,
) -> Result<Option<AssembledMessage>, MessageAssemblyError> {
self.accept_first_frame_at(input, Instant::now())
}
pub fn accept_first_frame_at(
&mut self,
input: FirstFrameInput<'_>,
now: Instant,
) -> Result<Option<AssembledMessage>, MessageAssemblyError> {
self.purge_deferring_streaming(now);
let key = input.header.message_key;
if self.assemblies.contains_key(&key) || self.streaming_assemblies.contains_key(&key) {
return Err(MessageAssemblyError::DuplicateFirstFrame { key });
}
validation::validate_first_frame(input.header, input.body.len())?;
let counted_body_len = input
.header
.total_body_len
.unwrap_or(0)
.max(input.body.len());
check_size_limit(
self.max_message_size,
key,
input.metadata.len(),
counted_body_len,
)?;
if input.header.is_last {
return Ok(Some(AssembledMessage::new(
key,
input.routing,
input.metadata,
input.body.to_vec(),
)));
}
if self.budgets.is_enabled() {
let incoming_bytes = input.body.len().saturating_add(input.metadata.len());
check_aggregate_budgets(
key,
self.total_buffered_bytes(),
incoming_bytes,
&self.budgets,
)?;
}
let partial = PartialAssembly::from_first_frame(input, now);
self.assemblies.insert(key, partial);
Ok(None)
}
pub fn accept_continuation_frame(
&mut self,
header: &ContinuationFrameHeader,
body: &[u8],
) -> Result<Option<AssembledMessage>, MessageAssemblyError> {
self.accept_continuation_frame_at(header, body, Instant::now())
}
const fn is_unrecoverable_continuity_error(error: &MessageSeriesError) -> bool {
matches!(
error,
MessageSeriesError::KeyMismatch { .. }
| MessageSeriesError::SequenceOverflow { .. }
| MessageSeriesError::MissingFirstFrame { .. }
| MessageSeriesError::MissingSequence { .. }
| MessageSeriesError::ContinuationBodyLengthMismatch { .. }
)
}
pub fn accept_continuation_frame_at(
&mut self,
header: &ContinuationFrameHeader,
body: &[u8],
now: Instant,
) -> Result<Option<AssembledMessage>, MessageAssemblyError> {
self.purge_deferring_streaming(now);
let key = header.message_key;
if header.body_len != body.len() {
return Err(MessageAssemblyError::Series(
MessageSeriesError::ContinuationBodyLengthMismatch {
key,
header_len: header.body_len,
actual_len: body.len(),
},
));
}
let limits = ContinuationLimits {
max_message_size: self.max_message_size,
budgets: self.budgets,
};
let buffered_total = if limits.budgets.is_enabled() {
self.total_buffered_bytes()
} else {
0
};
let Entry::Occupied(mut entry) = self.assemblies.entry(key) else {
return Err(MessageAssemblyError::Series(
MessageSeriesError::MissingFirstFrame { key },
));
};
let status = match entry.get_mut().accept_continuation(header) {
Ok(s) => s,
Err(e) => {
if Self::is_unrecoverable_continuity_error(&e) {
entry.remove();
}
return Err(MessageAssemblyError::Series(e));
}
};
let partial = entry.get_mut();
if let Err(e) = partial.admit_continuation(body.len(), buffered_total, limits) {
entry.remove();
return Err(e);
}
partial.push_body(body);
let MessageSeriesStatus::Complete = status else {
return Ok(None);
};
entry.remove().into_message()
}
pub fn purge_expired(&mut self) -> Vec<MessageKey> { self.purge_expired_at(Instant::now()) }
pub fn purge_expired_at(&mut self, now: Instant) -> Vec<MessageKey> {
let purged = self.purge_expired_detailed_at(now);
self.deferred_streaming_evictions
.extend_from_slice(purged.streaming());
purged.buffered().to_vec()
}
#[must_use]
pub fn total_buffered_bytes(&self) -> usize {
self.assemblies
.values()
.map(PartialAssembly::buffered_bytes)
.sum()
}
#[must_use]
pub fn buffered_count(&self) -> usize { self.assemblies.len() }
}