use std::{future::Future, io, time::Duration};
use tokio_util::sync::CancellationToken;
use super::{ConnectionActor, ConnectionChannels, UntrackedActorInit, test_actor_with_shutdown};
use crate::{
app::Envelope,
connection::{FrameSink, PushSink, ResponseOutcome},
hooks::ProtocolHooks,
push::{PushError, PushHandle, PushQueues},
response::{FrameStream, Response},
};
struct RecordingSink {
shutdown: Option<CancellationToken>,
accepted: Vec<u8>,
}
impl RecordingSink {
fn accept(&mut self, frame: &Envelope) {
if let Some(byte) = frame.payload_bytes().first() {
self.accepted.push(*byte);
}
if let Some(shutdown) = self.shutdown.take() {
shutdown.cancel();
}
}
}
impl FrameSink<Envelope> for RecordingSink {
fn send_frame(&mut self, frame: Envelope) -> impl Future<Output = io::Result<()>> + Send {
self.accept(&frame);
std::future::ready(Ok(()))
}
}
impl PushSink<Envelope> for RecordingSink {
fn send_push(&mut self, frame: Envelope) -> impl Future<Output = io::Result<()>> + Send {
self.accept(&frame);
std::future::ready(Ok(()))
}
}
fn three_frame_response() -> Response<Envelope, ()> {
let frames = (1..=3)
.map(|number| Ok(Envelope::new(1, None, vec![number])))
.collect::<Vec<_>>();
let stream: FrameStream<Envelope, ()> = Box::pin(futures::stream::iter(frames));
Response::Stream(stream)
}
#[rstest::rstest]
#[case::drains_across_shutdown(false, 3, ResponseOutcome::Completed)]
#[case::abandons_on_shutdown(true, 1, ResponseOutcome::Cancelled)]
#[tokio::test]
async fn shutdown_either_drains_or_abandons_a_stream(
#[case] abandon_on_shutdown: bool,
#[case] expected_frames: usize,
#[case] expected_outcome: ResponseOutcome,
) {
let shutdown = CancellationToken::new();
let mut actor = test_actor_with_shutdown(shutdown.clone(), ProtocolHooks::default())
.expect("the actor should build");
actor.set_abandon_response_on_shutdown(abandon_on_shutdown);
let mut sink = RecordingSink {
shutdown: Some(shutdown),
accepted: Vec::new(),
};
let outcome = actor
.install_response(three_frame_response(), Some(7), &mut sink)
.await
.expect("a bounded response is not an error");
assert_eq!(outcome, expected_outcome);
assert_eq!(
sink.accepted.len(),
expected_frames,
"unexpected frames reached the sink: {:?}",
sink.accepted
);
}
fn stalled_response() -> Response<Envelope, ()> {
let stream: FrameStream<Envelope, ()> = Box::pin(futures::stream::pending());
Response::Stream(stream)
}
fn server_actor_with_pushes(
shutdown: &CancellationToken,
high_capacity: usize,
) -> (ConnectionActor<Envelope, ()>, PushHandle<Envelope>) {
let built = PushQueues::<Envelope>::builder()
.high_capacity(high_capacity)
.low_capacity(1)
.build();
let (queues, handle) = match built {
Ok(pair) => pair,
Err(error) => panic!("the push queues should build: {error:?}"),
};
let mut actor = ConnectionActor::new_untracked(UntrackedActorInit {
channels: ConnectionChannels::new(queues, handle.clone()),
response: None,
shutdown: shutdown.clone(),
hooks: ProtocolHooks::default(),
ctx: crate::hooks::ConnectionContext::default(),
});
actor.set_abandon_response_on_shutdown(false);
(actor, handle)
}
async fn drain_stalled_response_and_assert_lanes_closed(
actor: &mut ConnectionActor<Envelope, ()>,
sink: &mut RecordingSink,
handle: &PushHandle<Envelope>,
refused_byte: u8,
) {
let installed = actor
.install_response(stalled_response(), Some(1), sink)
.await;
let outcome = match installed {
Ok(outcome) => outcome,
Err(error) => panic!("a bounded response is not an error: {error:?}"),
};
assert_eq!(
outcome,
ResponseOutcome::Cancelled,
"the idle grace must end a stalled response"
);
assert_eq!(
handle
.push_high_priority(Envelope::new(1, None, vec![refused_byte]))
.await,
Err(PushError::Closed),
"a stopping connection must refuse a new push rather than queue it"
);
}
#[tokio::test(start_paused = true)]
async fn shutdown_that_starts_the_bounded_drain_drops_queued_pushes() {
let shutdown = CancellationToken::new();
let (mut actor, handle) = server_actor_with_pushes(&shutdown, 1);
let mut sink = RecordingSink {
shutdown: None,
accepted: Vec::new(),
};
handle
.push_high_priority(Envelope::new(1, None, vec![9]))
.await
.expect("the push is accepted before the stop");
shutdown.cancel();
drain_stalled_response_and_assert_lanes_closed(&mut actor, &mut sink, &handle, 10).await;
assert!(
!sink.accepted.contains(&9),
"a push queued when the stop arrived must be dropped, not flushed"
);
}
#[tokio::test(start_paused = true)]
async fn a_stop_during_a_peer_close_drain_discards_the_push_lanes() {
let shutdown = CancellationToken::new();
let (mut actor, handle) = server_actor_with_pushes(&shutdown, 2);
actor.set_peer_closed_grace(Duration::from_secs(5));
let peer_closed = CancellationToken::new();
actor.set_peer_closed(peer_closed.clone());
let mut sink = RecordingSink {
shutdown: Some(shutdown),
accepted: Vec::new(),
};
for byte in [9, 10] {
handle
.push_high_priority(Envelope::new(1, None, vec![byte]))
.await
.expect("the push is accepted before the stop");
}
peer_closed.cancel();
drain_stalled_response_and_assert_lanes_closed(&mut actor, &mut sink, &handle, 11).await;
assert_eq!(
sink.accepted.first(),
Some(&9),
"the push written before the stop was accepted must reach the sink"
);
assert!(
!sink.accepted.contains(&10),
"a push queued when the stop arrived must be dropped, not flushed"
);
}