use std::{
io,
pin::Pin,
task::{Context, Poll},
};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio_util::codec::Framed;
use super::*;
use crate::{
app::combined_codec::{ConnectionCodec, connection_codec},
connection::FrameSink,
};
struct FailingWriter {
writes_before_failure: usize,
attempts: usize,
}
impl FailingWriter {
const fn new(writes_before_failure: usize) -> Self {
Self {
writes_before_failure,
attempts: 0,
}
}
const fn attempts(&self) -> usize { self.attempts }
}
impl AsyncWrite for FailingWriter {
fn poll_write(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
let this = self.get_mut();
let attempt = this.attempts;
this.attempts += 1;
if attempt >= this.writes_before_failure {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::BrokenPipe,
"test writer loses the peer",
)));
}
Poll::Ready(Ok(buf.len()))
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
}
impl AsyncRead for FailingWriter {
fn poll_read(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
_buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
}
fn fragmenting_config() -> FragmentationConfig {
let message_cap = NonZeroUsize::new(256).expect("message cap must be non-zero");
FragmentationConfig::for_frame_budget(96, message_cap, Duration::from_secs(5))
.expect("frame budget must exceed fragmentation overhead")
}
fn multi_fragment_payload() -> Vec<u8> {
let payload_cap = fragmenting_config().fragment_payload_cap.get();
vec![7; payload_cap.saturating_add(16)]
}
fn fragmented_pipeline() -> FramePipeline<Bytes> {
let mut pipeline = FramePipeline::new(Some(fragmenting_config()));
pipeline
.process(Envelope::new(1, None, multi_fragment_payload()))
.expect("oversized envelope should fragment");
pipeline
}
fn failing_framed(codec: &TestCodec) -> Framed<FailingWriter, ConnectionCodec<TestCodec>> {
Framed::new(FailingWriter::new(1), connection_codec(codec))
}
#[tokio::test]
async fn flush_reports_a_failure_on_the_second_fragment() {
let mut pipeline = fragmented_pipeline();
let codec = TestCodec::default();
let mut framed = failing_framed(&codec);
let mut transport = OutboundTransport {
serializer: &BincodeSerializer,
codec: &codec,
sink: &mut framed,
};
let error = flush_pipeline_output(&mut transport, &mut pipeline)
.await
.expect_err("a failure on the second fragment must be reported");
assert!(
error.to_string().contains("test writer loses the peer"),
"the transport failure must be preserved, got: {error}"
);
assert_eq!(
framed.get_ref().attempts(),
2,
"the flush must stop at the failed write rather than retry"
);
assert!(
pipeline.drain_output().is_empty(),
"the remaining fragments must be discarded after the failed write"
);
}
#[tokio::test]
async fn send_frame_reports_a_failure_on_the_second_fragment() {
let mut pipeline: FramePipeline<Bytes> = FramePipeline::new(Some(fragmenting_config()));
let codec = TestCodec::default();
let mut framed = failing_framed(&codec);
let error = {
let mut sink = ActorFrameSink::new(&BincodeSerializer, &codec, &mut framed, &mut pipeline);
sink.send_frame(Envelope::new(1, None, multi_fragment_payload()))
.await
.expect_err("a failure on the second fragment must be reported")
};
assert!(
error.to_string().contains("test writer loses the peer"),
"the sink must propagate the transport failure, got: {error}"
);
assert_eq!(
framed.get_ref().attempts(),
2,
"the sink must stop at the failed write rather than retry"
);
assert!(
pipeline.drain_output().is_empty(),
"the sink must leave no fragments buffered for a later flush"
);
}