use std::sync::Arc;
use futures::StreamExt;
use tokio_util::sync::CancellationToken;
use super::*;
#[rstest::rstest]
#[case::half_close(true)]
#[case::buffered_request(false)]
#[tokio::test(start_paused = true)]
async fn a_terminator_keeps_its_whole_grace_before_being_abandoned(
#[case] close_peer_before_write: bool,
) {
const GRACE: Duration = Duration::from_secs(5);
const MARGIN: Duration = Duration::from_secs(1);
const BEFORE_DEADLINE: Duration = Duration::from_secs(4);
const PAST_DEADLINE: Duration = Duration::from_millis(1_001);
assert_eq!(
BEFORE_DEADLINE + MARGIN,
GRACE,
"the advances must bracket the deadline by one margin"
);
let log: EventLog = Arc::new(Mutex::new(Vec::new()));
let (mut actor, _handle) = build_actor().expect("the actor should build");
let peer_closed = CancellationToken::new();
actor.set_peer_closed(peer_closed.clone());
actor.set_peer_closed_grace(GRACE);
let mut sink = StalledSink {
log: Arc::clone(&log),
};
let stream: FrameStream<Envelope, ()> = futures::stream::empty().boxed();
let mut driving = std::pin::pin!(run_forward(
&mut sink,
&mut actor,
Response::Stream(stream),
&log
));
if close_peer_before_write {
peer_closed.cancel();
} else {
assert!(
futures::poll!(driving.as_mut()).is_pending(),
"the terminator write must stall while the peer is still observed"
);
peer_closed.cancel();
}
assert!(
futures::poll!(driving.as_mut()).is_pending(),
"an unobservable peer must not abandon the terminator immediately"
);
tokio::time::advance(BEFORE_DEADLINE).await;
assert!(
futures::poll!(driving.as_mut()).is_pending(),
"the terminator must keep the whole grace before it is abandoned"
);
tokio::time::advance(PAST_DEADLINE).await;
let outcome = tokio::time::timeout(Duration::from_millis(100), driving)
.await
.expect("the terminator must be abandoned once the grace has passed")
.expect("an abandoned terminator is not a transport error");
assert_eq!(
outcome,
Dispatch::Stop,
"an abandoned terminator must stop the loop before it serves another frame"
);
let observed = events(&log);
assert!(
!observed.contains(&"send"),
"the abandoned terminator must never reach the sink: {observed:?}"
);
assert!(
!observed.contains(&"command_end"),
"an abandoned terminator must not run the completion hook: {observed:?}"
);
}