use std::time::Instant;
use super::{
ContinuationFrameHeader,
MessageAssemblyError,
MessageKey,
MessageSeriesError,
MessageSeriesStatus,
budget::check_size_limit,
series::MessageSeries,
types::{EnvelopeRouting, FirstFrameInput},
validation,
};
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct StreamingAssemblyId {
key: MessageKey,
generation: u64,
}
impl StreamingAssemblyId {
pub(super) const fn new(key: MessageKey, generation: u64) -> Self { Self { key, generation } }
#[must_use]
pub const fn key(&self) -> MessageKey { self.key }
#[must_use]
pub const fn generation(&self) -> u64 { self.generation }
}
#[derive(Debug)]
pub struct StreamingFirstFrame<'a> {
pub(super) key: MessageKey,
pub(super) assembly: Option<StreamingAssemblyId>,
pub(super) routing: EnvelopeRouting,
pub(super) metadata: Vec<u8>,
pub(super) chunk: &'a [u8],
pub(super) is_last: bool,
}
impl<'a> StreamingFirstFrame<'a> {
#[must_use]
pub const fn key(&self) -> MessageKey { self.key }
#[must_use]
pub const fn assembly_id(&self) -> Option<StreamingAssemblyId> { self.assembly }
#[must_use]
pub const fn routing(&self) -> EnvelopeRouting { self.routing }
#[must_use]
pub fn into_metadata(self) -> Vec<u8> { self.metadata }
#[must_use]
pub const fn chunk(&self) -> &'a [u8] { self.chunk }
#[must_use]
pub const fn is_last(&self) -> bool { self.is_last }
}
#[derive(Debug)]
pub enum StreamingContinuation<'a> {
Chunk {
key: MessageKey,
chunk: &'a [u8],
is_last: bool,
},
Discarded {
key: MessageKey,
},
}
impl StreamingContinuation<'_> {
#[must_use]
pub const fn key(&self) -> MessageKey {
match self {
Self::Chunk { key, .. } | Self::Discarded { key } => *key,
}
}
#[must_use]
pub const fn is_chunk(&self) -> bool { matches!(self, Self::Chunk { .. }) }
}
#[derive(Debug, thiserror::Error)]
#[error("{source}")]
pub struct StreamingFailure {
key: MessageKey,
source: MessageAssemblyError,
terminal: bool,
}
impl StreamingFailure {
pub(super) const fn new(key: MessageKey, source: MessageAssemblyError, terminal: bool) -> Self {
Self {
key,
source,
terminal,
}
}
#[must_use]
pub const fn key(&self) -> MessageKey { self.key }
#[must_use]
pub const fn is_terminal(&self) -> bool { self.terminal }
#[must_use]
pub const fn source_error(&self) -> &MessageAssemblyError { &self.source }
}
#[derive(Debug)]
pub(super) struct StreamingAssembly {
id: StreamingAssemblyId,
series: MessageSeries,
accumulated: usize,
metadata_len: usize,
pub(super) started_at: Instant,
discard: bool,
}
impl StreamingAssembly {
pub(super) const fn from_first_frame(
id: StreamingAssemblyId,
input: &FirstFrameInput<'_>,
chunk_len: usize,
started_at: Instant,
) -> Self {
Self {
id,
series: MessageSeries::from_first_frame(input.header),
accumulated: chunk_len,
metadata_len: input.metadata.len(),
started_at,
discard: false,
}
}
pub(super) const fn id(&self) -> StreamingAssemblyId { self.id }
pub(super) const fn is_complete(&self) -> bool { self.series.is_complete() }
pub(super) const fn begin_discard(&mut self) { self.discard = true; }
pub(super) fn accept_continuation<'a>(
&mut self,
header: &ContinuationFrameHeader,
body: &'a [u8],
max_message_size: std::num::NonZeroUsize,
) -> Result<Option<StreamingChunk<'a>>, StreamingFailure> {
let key = self.series.message_key();
let status = match self.series.accept_continuation(header) {
Ok(status) => status,
Err(error) => return Err(self.continuity_failure(error)),
};
let admitted = self.metadata_len.saturating_add(self.accumulated);
if let Err(error) = check_size_limit(max_message_size, key, admitted, body.len()) {
return Err(StreamingFailure::new(key, error, true));
}
if let Some(declared) = self.series.expected_total()
&& let Err(error) =
validation::validate_continuation(key, declared, self.accumulated, body.len())
{
return Err(StreamingFailure::new(key, error, true));
}
self.accumulated = self.accumulated.saturating_add(body.len());
let is_last = matches!(status, MessageSeriesStatus::Complete);
if is_last {
self.validate_completed_series(key)?;
}
if self.discard {
return Ok(None);
}
Ok(Some(StreamingChunk { body, is_last }))
}
fn validate_completed_series(&self, key: MessageKey) -> Result<(), StreamingFailure> {
let Some(declared) = self.series.expected_total() else {
return Ok(());
};
validation::validate_completion(key, declared, self.accumulated)
.map_err(|error| StreamingFailure::new(key, error, true))
}
const fn continuity_failure(&self, error: MessageSeriesError) -> StreamingFailure {
let key = self.series.message_key();
let terminal = !is_recoverable_continuity_error(&error);
StreamingFailure::new(key, MessageAssemblyError::Series(error), terminal)
}
}
#[derive(Debug)]
pub(super) struct StreamingChunk<'a> {
pub(super) body: &'a [u8],
pub(super) is_last: bool,
}
pub(super) const fn is_recoverable_continuity_error(error: &MessageSeriesError) -> bool {
matches!(
error,
MessageSeriesError::DuplicateFrame { .. } | MessageSeriesError::SequenceMismatch { .. }
)
}