use std::io;
use bytes::Bytes;
use futures::stream;
use tokio_util::sync::CancellationToken;
use super::{
PushBatch,
READ_TIMEOUT_MS,
empty_inbound,
transport::{TransportRig, blocked_transport},
};
use crate::{
app::inbound_handler::{
frames::{InboundExpiry, buffered_assemblies, incomplete_inbound},
push_write::write_frame,
},
connection::PEER_CLOSED_RESPONSE_GRACE,
};
const STALLED_READ_TIMEOUT_MS: u64 = 1_000;
#[rstest::rstest]
#[tokio::test(start_paused = true)]
async fn a_stalled_push_write_purges_expired_inbound_state(
#[from(blocked_transport)] mut harness: TransportRig,
) {
use crate::push::PushPriority;
let shutdown = CancellationToken::new();
let peer_eof = CancellationToken::new();
let mut inbound = incomplete_inbound::<Bytes>();
let mut reader = stream::pending::<io::Result<Bytes>>();
let mut evicted = Vec::new();
let mut batch = PushBatch {
frames: Vec::new(),
priority: Some(PushPriority::High),
reader: &mut reader,
pending_frame: &mut inbound.pending,
expiry: InboundExpiry::new(
&mut inbound.message_assembly,
&mut inbound.read_deadline,
STALLED_READ_TIMEOUT_MS,
&mut evicted,
),
peer_eof: &peer_eof,
shutdown: &shutdown,
};
let written = tokio::time::timeout(
PEER_CLOSED_RESPONSE_GRACE * 2,
write_frame(
&mut harness.transport(),
Bytes::from_static(b"stalled"),
&mut batch,
true,
),
)
.await
.expect("the write must be bounded")
.expect("an idle-grace abandonment is not an error");
drop(batch);
assert!(
!written.may_continue(),
"the grace, not a purge, must end the stalled write"
);
assert!(
written.peer_closed(),
"the abandonment must keep the peer-closed state it was given"
);
assert_eq!(
buffered_assemblies(&inbound),
Some(0),
"the stalled write must not postpone the inbound expiry"
);
}
#[rstest::rstest]
#[tokio::test]
async fn a_shutdown_abandoned_fast_path_write_is_counted(
#[from(blocked_transport)] mut harness: TransportRig,
) {
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
use crate::{metrics::PUSH_WRITES_ABANDONED, push::PushPriority};
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let shutdown = CancellationToken::new();
shutdown.cancel();
let peer_eof = CancellationToken::new();
let mut inbound = empty_inbound();
let mut reader = stream::pending::<io::Result<Bytes>>();
let frame = Bytes::from_static(b"abandoned");
let mut evicted = Vec::new();
let mut batch = PushBatch {
frames: Vec::new(),
priority: Some(PushPriority::High),
reader: &mut reader,
pending_frame: &mut inbound.pending,
expiry: InboundExpiry::new(
&mut inbound.message_assembly,
&mut inbound.read_deadline,
READ_TIMEOUT_MS,
&mut evicted,
),
peer_eof: &peer_eof,
shutdown: &shutdown,
};
let outcome = {
let _recorder = ::metrics::set_default_local_recorder(&recorder);
write_frame(&mut harness.transport(), frame, &mut batch, false).await
}
.expect("a shutdown abandonment is not an error");
assert!(!outcome.may_continue(), "the connection must stop");
assert!(
!outcome.peer_closed(),
"the peer did not close its write half"
);
let samples = snapshotter.snapshot().into_vec();
let (key, _, _, value) = samples
.iter()
.find(|(key, ..)| key.key().name() == PUSH_WRITES_ABANDONED)
.expect("the shutdown abandonment must be counted");
assert!(
matches!(value, DebugValue::Counter(1)),
"the fast path must record exactly one abandonment"
);
assert!(
key.key().labels().count() == 1
&& key
.key()
.labels()
.any(|label| label.key() == "reason" && label.value() == "shutdown"),
"the counter keeps its single reason label and adds no priority label"
);
}
#[rstest::rstest]
#[tokio::test(start_paused = true)]
async fn a_blocked_write_to_a_silent_peer_is_bounded_by_the_grace(
#[from(blocked_transport)] mut harness: TransportRig,
) {
let shutdown = CancellationToken::new();
let peer_eof = CancellationToken::new();
let mut inbound = empty_inbound();
let mut reader = stream::pending::<io::Result<Bytes>>();
let mut evicted = Vec::new();
let mut batch = PushBatch {
frames: Vec::new(),
priority: None,
reader: &mut reader,
pending_frame: &mut inbound.pending,
expiry: InboundExpiry::new(
&mut inbound.message_assembly,
&mut inbound.read_deadline,
READ_TIMEOUT_MS,
&mut evicted,
),
peer_eof: &peer_eof,
shutdown: &shutdown,
};
let written = tokio::time::timeout(
PEER_CLOSED_RESPONSE_GRACE * 2,
write_frame(
&mut harness.transport(),
Bytes::from_static(b"stalled"),
&mut batch,
false,
),
)
.await
.expect("the write must be bounded")
.expect("an idle-grace abandonment is not an error");
drop(batch);
assert!(
!written.may_continue(),
"a frame abandoned under the grace must stop the connection"
);
assert!(
!written.peer_closed(),
"the silent peer never closed its write half"
);
assert!(
!peer_eof.is_cancelled(),
"a silent peer is not an EOF, so the connection-wide token stays open"
);
}
struct EofThenFail {
reported: bool,
}
impl futures::Stream for EofThenFail {
type Item = io::Result<Bytes>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
assert!(
!self.reported,
"the write must leave the observation loop once the peer reaches EOF"
);
self.reported = true;
std::task::Poll::Ready(None)
}
}
#[rstest::rstest]
#[tokio::test(start_paused = true)]
async fn a_write_that_sees_eof_leaves_the_observation_loop(
#[from(blocked_transport)] mut harness: TransportRig,
) {
let shutdown = CancellationToken::new();
let peer_eof = CancellationToken::new();
let mut inbound = empty_inbound();
let mut reader = EofThenFail { reported: false };
let mut evicted = Vec::new();
let mut batch = PushBatch {
frames: Vec::new(),
priority: None,
reader: &mut reader,
pending_frame: &mut inbound.pending,
expiry: InboundExpiry::new(
&mut inbound.message_assembly,
&mut inbound.read_deadline,
READ_TIMEOUT_MS,
&mut evicted,
),
peer_eof: &peer_eof,
shutdown: &shutdown,
};
let written = tokio::time::timeout(
PEER_CLOSED_RESPONSE_GRACE * 2,
write_frame(
&mut harness.transport(),
Bytes::from_static(b"stalled"),
&mut batch,
false,
),
)
.await
.expect("the write must be bounded after the peer reaches EOF")
.expect("an idle-grace abandonment is not an error");
drop(batch);
assert!(
peer_eof.is_cancelled(),
"the EOF must be recorded for the connection"
);
assert!(written.peer_closed(), "the peer closed its write half");
assert!(
!written.may_continue(),
"a write that never completed must stop the connection"
);
}