use std::pin::Pin;
use log::warn;
use tokio::io::{self, AsyncRead, AsyncWrite, ReadHalf, WriteHalf};
use tokio_util::codec::{FramedRead, FramedWrite};
use super::super::{codec_driver::FramePipeline, recovery_codec::RecoveryDecoder};
use crate::codec::{EofError, FrameCodec, MAX_FRAME_LENGTH, clamp_frame_length, eof_condition};
pub(super) type TransportSink<W, F> =
Pin<Box<FramedWrite<WriteHalf<W>, <F as FrameCodec>::Encoder>>>;
pub(super) type TransportStream<W, F> =
Pin<Box<FramedRead<ReadHalf<W>, RecoveryDecoder<<F as FrameCodec>::Decoder>>>>;
#[derive(Clone, Copy, Debug)]
pub(super) struct TruncatedFrame<'a>(&'a [u8]);
impl<'a> TruncatedFrame<'a> {
pub(super) const fn as_bytes(&self) -> &'a [u8] { self.0 }
}
pub(super) fn truncated_frame<W, D>(reader: &FramedRead<ReadHalf<W>, D>) -> TruncatedFrame<'_>
where
W: AsyncRead + AsyncWrite + Unpin,
{
TruncatedFrame(reader.read_buffer().as_ref())
}
pub(super) fn report_truncation<W, F>(
reader: &FramedRead<ReadHalf<W>, RecoveryDecoder<<F as FrameCodec>::Decoder>>,
pipeline: &mut FramePipeline<F::Frame>,
error: &io::Error,
) where
F: FrameCodec,
W: AsyncRead + AsyncWrite + Unpin,
{
let partial = truncated_frame::<W, _>(reader);
match eof_condition(error) {
Some(eof @ (EofError::MidHeader { .. } | EofError::MidFrame { .. })) => {
tracing::debug!(
condition = ?eof,
partial_bytes = partial.as_bytes().len(),
"reporting a truncated frame to the protocol"
);
pipeline.on_eof(&eof, partial.as_bytes());
}
Some(EofError::CleanClose) | None => {}
}
}
pub(super) struct ConnectionFraming<W, F>
where
F: FrameCodec,
W: AsyncRead + AsyncWrite + Unpin,
{
pub(super) codec: F,
pub(super) sink: TransportSink<W, F>,
pub(super) stream: TransportStream<W, F>,
}
impl<W, F> ConnectionFraming<W, F>
where
F: FrameCodec,
W: AsyncRead + AsyncWrite + Unpin,
{
pub(super) fn split(self) -> (TransportSink<W, F>, TransportStream<W, F>, F) {
(self.sink, self.stream, self.codec)
}
}
pub(super) fn prepare_connection_framing<W, F>(stream: W, codec: &F) -> ConnectionFraming<W, F>
where
F: FrameCodec,
W: AsyncRead + AsyncWrite + Unpin,
{
let connection_codec = codec.clone();
let requested_frame_length = connection_codec.max_frame_length();
let max_frame_length = clamp_frame_length(requested_frame_length);
if requested_frame_length > MAX_FRAME_LENGTH {
warn!(
"codec max frame length exceeds guardrail; clamping to {MAX_FRAME_LENGTH} bytes \
(requested={requested_frame_length})"
);
}
let (read_half, write_half) = tokio::io::split(stream);
let framed_read = FramedRead::with_capacity(
read_half,
RecoveryDecoder::new(connection_codec.decoder()),
max_frame_length,
);
let sink = FramedWrite::new(write_half, connection_codec.encoder());
ConnectionFraming {
codec: connection_codec,
sink: Box::pin(sink),
stream: Box::pin(framed_read),
}
}