use std::{
error::Error,
future::Future,
io,
pin::Pin,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
task::{Context, Poll},
};
use futures::Sink;
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;
use super::{ResponseContext, response_pushes::run_handler_with_pushes};
use crate::{
app::{Envelope, codec_driver::FramePipeline},
connection::{ConnectionActor, ConnectionChannels, UntrackedActorInit},
hooks::{ConnectionContext, ProtocolHooks},
push::{PushConfigError, PushError, PushHandle, PushPolicy, PushPriority, PushQueues},
serializer::BincodeSerializer,
test_helpers::frame_codec::{TestCodec, TestFrame},
};
const MAX_FRAME_LENGTH: usize = 1024;
#[cfg(feature = "metrics")]
#[path = "response_pushes_tests/idle_grace.rs"]
mod idle_grace;
#[path = "response_pushes_tests/shutdown.rs"]
mod shutdown;
const HANDLER_RESPONSE: &str = "handler finished";
struct HandlerRig<S> {
actor: ConnectionActor<Envelope, (), TestFrame>,
handle: PushHandle<TestFrame>,
sink: S,
codec: TestCodec,
serializer: BincodeSerializer,
pipeline: FramePipeline<TestFrame>,
shutdown: CancellationToken,
}
impl<S> HandlerRig<S>
where
S: Sink<TestFrame, Error = io::Error> + Send + Unpin,
{
fn new(shutdown: CancellationToken, sink: S) -> Result<Self, PushConfigError> {
let (queues, handle) = PushQueues::<TestFrame>::builder()
.high_capacity(1)
.low_capacity(1)
.build()?;
let actor = ConnectionActor::new_untracked(UntrackedActorInit {
channels: ConnectionChannels::new(queues, handle.clone()),
response: None,
shutdown: shutdown.clone(),
hooks: ProtocolHooks::default(),
ctx: ConnectionContext::default(),
});
Ok(Self {
actor,
handle,
sink,
codec: TestCodec::new(MAX_FRAME_LENGTH),
serializer: BincodeSerializer,
pipeline: FramePipeline::new(None),
shutdown,
})
}
fn try_queue_push(&mut self) -> Result<(), PushError> {
self.handle.try_push(
queued_push(),
PushPriority::High,
PushPolicy::ReturnErrorIfFull,
)
}
const fn context(&mut self) -> ResponseContext<'_, BincodeSerializer, S, TestCodec> {
ResponseContext {
serializer: &self.serializer,
sink: &mut self.sink,
pipeline: &mut self.pipeline,
codec: &self.codec,
actor: &mut self.actor,
}
}
}
type BlockedRig = (HandlerRig<BlockingSink>, oneshot::Sender<()>);
type BlockedRigFixture = Result<BlockedRig, Box<dyn Error>>;
#[rstest::fixture]
fn blocked_rig() -> BlockedRigFixture {
let (release, blocked) = oneshot::channel();
let mut rig = HandlerRig::new(CancellationToken::new(), BlockingSink::new(blocked))?;
rig.try_queue_push()?;
Ok((rig, release))
}
fn queued_push() -> TestFrame {
TestFrame {
tag: 7,
payload: vec![7],
}
}
struct BlockingSink {
release: oneshot::Receiver<()>,
released: bool,
written: Vec<TestFrame>,
}
impl BlockingSink {
const fn new(release: oneshot::Receiver<()>) -> Self {
Self {
release,
released: false,
written: Vec::new(),
}
}
}
impl Sink<TestFrame> for BlockingSink {
type Error = io::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
if !self.released {
match Pin::new(&mut self.release).poll(cx) {
Poll::Ready(Ok(()) | Err(_)) => self.released = true,
Poll::Pending => return Poll::Pending,
}
}
Poll::Ready(Ok(()))
}
fn start_send(mut self: Pin<&mut Self>, item: TestFrame) -> Result<(), Self::Error> {
self.written.push(item);
Ok(())
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
}
struct DeferredHandler {
finished: Arc<AtomicBool>,
polls: usize,
}
impl DeferredHandler {
const fn new(finished: Arc<AtomicBool>) -> Self { Self { finished, polls: 0 } }
}
impl Future for DeferredHandler {
type Output = &'static str;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.polls += 1;
if self.polls < 2 {
cx.waker().wake_by_ref();
return Poll::Pending;
}
self.finished.store(true, Ordering::SeqCst);
Poll::Ready(HANDLER_RESPONSE)
}
}
#[rstest::rstest]
#[tokio::test]
async fn the_handler_keeps_running_while_a_push_write_waits(blocked_rig: BlockedRigFixture) {
let (mut rig, release) = blocked_rig.expect("the rig's queues build");
let finished = Arc::new(AtomicBool::new(false));
let call = DeferredHandler::new(Arc::clone(&finished));
let response = {
let mut ctx = rig.context();
let running = run_handler_with_pushes(&mut ctx, call);
tokio::pin!(running);
assert!(
futures::poll!(running.as_mut()).is_pending(),
"the write must still be waiting for the peer"
);
assert!(
finished.load(Ordering::SeqCst),
"the handler must be polled while the push write waits"
);
release
.send(())
.expect("the handler run still holds the release channel");
running.await.expect("the release lets the write finish")
};
assert_eq!(
response,
Some(HANDLER_RESPONSE),
"the response produced during the write must be returned"
);
assert_eq!(
rig.sink.written.len(),
1,
"the queued push must reach the transport"
);
assert_eq!(
rig.sink.written.first().map(|frame| frame.tag),
Some(7),
"the frame that reached the transport must be the queued push"
);
}
#[rstest::rstest]
#[tokio::test]
async fn an_abandoned_write_discards_the_finished_response(blocked_rig: BlockedRigFixture) {
let (mut rig, _release) = blocked_rig.expect("the rig's queues build");
let shutdown = rig.shutdown.clone();
let finished = Arc::new(AtomicBool::new(false));
let call = DeferredHandler::new(Arc::clone(&finished));
let response = {
let mut ctx = rig.context();
let running = run_handler_with_pushes(&mut ctx, call);
tokio::pin!(running);
assert!(
futures::poll!(running.as_mut()).is_pending(),
"the write must be pending before shutdown is requested"
);
shutdown.cancel();
running.await.expect("an abandoned write is not an error")
};
assert_eq!(
response, None,
"a response behind an abandoned write must not be returned"
);
assert!(
rig.sink.written.is_empty(),
"the abandoned write must not reach the transport"
);
}