use std::{
convert::Infallible,
io,
pin::Pin,
sync::{Arc, Mutex, PoisonError},
task::{Context, Poll},
time::Duration,
};
use bytes::Bytes;
use futures::{Sink, StreamExt};
use tokio_util::sync::CancellationToken;
use super::{Dispatch, ResponseContext};
use crate::{
app::{Envelope, codec_driver::FramePipeline},
codec::LengthDelimitedFrameCodec,
connection::{ConnectionActor, ConnectionChannels, UntrackedActorInit},
hooks::{ConnectionContext, ProtocolHooks, WireframeProtocol},
middleware::{HandlerService, Service, ServiceRequest, ServiceResponse},
push::{PushConfigError, PushHandle, PushQueues},
response::{FrameStream, Response, WireframeError},
serializer::BincodeSerializer,
};
mod silent_reply;
mod terminator_grace;
type EventLog = Arc<Mutex<Vec<&'static str>>>;
fn record(log: &EventLog, event: &'static str) {
log.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(event);
}
fn events(log: &EventLog) -> Vec<&'static str> {
log.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
struct RecordingProtocol {
log: EventLog,
}
impl WireframeProtocol for RecordingProtocol {
type Frame = Bytes;
type ProtocolError = ();
fn stream_end_frame(&self, _ctx: &mut ConnectionContext) -> Option<Self::Frame> {
Some(Bytes::from_static(b"END"))
}
fn handle_error(&self, (): (), _ctx: &mut ConnectionContext) {
record(&self.log, "handle_error");
}
fn on_command_end(&self, _ctx: &mut ConnectionContext) { record(&self.log, "command_end"); }
}
struct RecordingSink {
log: EventLog,
fail: bool,
}
impl Sink<Bytes> for RecordingSink {
type Error = io::Error;
fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn start_send(self: Pin<&mut Self>, _item: Bytes) -> Result<(), Self::Error> {
if self.fail {
return Err(io::Error::other("sink refused the write"));
}
record(&self.log, "send");
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 StalledSink {
log: EventLog,
}
impl Sink<Bytes> for StalledSink {
type Error = io::Error;
fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
record(&self.log, "poll_ready");
Poll::Pending
}
fn start_send(self: Pin<&mut Self>, _item: Bytes) -> Result<(), Self::Error> {
record(&self.log, "send");
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 StreamService {
deferred: Arc<Mutex<Option<Response<Envelope, ()>>>>,
}
#[async_trait::async_trait]
impl Service for StreamService {
type Error = Infallible;
async fn call(&self, _req: ServiceRequest) -> Result<ServiceResponse, Self::Error> {
Ok(ServiceResponse::with_deferred(
Vec::new(),
None,
Arc::clone(&self.deferred),
))
}
}
type ActorFixture = (ConnectionActor<Envelope, (), Bytes>, PushHandle<Bytes>);
fn build_actor() -> Result<ActorFixture, PushConfigError> {
build_actor_with(CancellationToken::new())
}
fn build_actor_with(shutdown: CancellationToken) -> Result<ActorFixture, PushConfigError> {
let (queues, handle) = PushQueues::<Bytes>::builder()
.high_capacity(1)
.low_capacity(1)
.build()?;
let actor = ConnectionActor::new_untracked(UntrackedActorInit {
channels: ConnectionChannels::new(queues, handle.clone()),
response: None,
shutdown,
hooks: ProtocolHooks::default(),
ctx: ConnectionContext::default(),
});
Ok((actor, handle))
}
async fn forward(
response: Response<Envelope, ()>,
fail_sink: bool,
cancel_peer: bool,
) -> Result<(EventLog, io::Result<Dispatch>), PushConfigError> {
let log: EventLog = Arc::new(Mutex::new(Vec::new()));
let (mut actor, _handle) = build_actor()?;
if cancel_peer {
let peer_closed = CancellationToken::new();
peer_closed.cancel();
actor.set_peer_closed(peer_closed);
actor.set_peer_closed_grace(Duration::ZERO);
}
let mut sink = RecordingSink {
log: Arc::clone(&log),
fail: fail_sink,
};
let outcome = run_forward(&mut sink, &mut actor, response, &log).await;
Ok((log, outcome))
}
async fn run_forward<K>(
sink: &mut K,
actor: &mut ConnectionActor<Envelope, (), Bytes>,
response: Response<Envelope, ()>,
log: &EventLog,
) -> io::Result<Dispatch>
where
K: Sink<Bytes, Error = io::Error> + Unpin + Send,
{
let codec = LengthDelimitedFrameCodec::new(1024);
let serializer = BincodeSerializer;
let service = HandlerService::<Envelope>::from_service(
7,
StreamService {
deferred: Arc::new(Mutex::new(Some(response))),
},
);
let protocol: Arc<RecordingProtocol> = Arc::new(RecordingProtocol {
log: Arc::clone(log),
});
let mut pipeline: FramePipeline<Bytes> =
FramePipeline::with_hooks(None, ProtocolHooks::from_protocol(&protocol));
super::forward_response(
Envelope::new(7, Some(3), Vec::new()),
&service,
ResponseContext {
serializer: &serializer,
sink,
pipeline: &mut pipeline,
codec: &codec,
actor,
},
)
.await
}
#[tokio::test]
async fn completion_hook_runs_once_after_the_terminator_write() {
let stream: FrameStream<Envelope, ()> = futures::stream::empty().boxed();
let (log, outcome) = forward(Response::Stream(stream), false, false)
.await
.expect("the actor should build");
assert_eq!(
outcome.expect("a completed response is not an error"),
Dispatch::Continue,
"a completed response lets the loop dispatch the next frame"
);
assert_eq!(
events(&log),
vec!["send", "command_end"],
"the hook must run once, after the terminator reached the sink"
);
}
#[tokio::test]
async fn completion_hook_is_suppressed_when_the_terminator_write_fails() {
let stream: FrameStream<Envelope, ()> = futures::stream::empty().boxed();
let (log, outcome) = forward(Response::Stream(stream), true, false)
.await
.expect("the actor should build");
let error = outcome.expect_err("a refused write must fail the response");
assert!(
error.to_string().contains("sink refused the write"),
"the transport error must be propagated: {error}"
);
assert!(
events(&log).is_empty(),
"no hook may run when the terminator was never written"
);
}
#[tokio::test]
async fn protocol_error_stops_dispatch_without_a_terminator() {
let failed: FrameStream<Envelope, ()> = Box::pin(futures::stream::iter(vec![
Ok(Envelope::new(7, Some(3), vec![1])),
Err(WireframeError::Protocol(())),
]));
let (log, outcome) = forward(Response::Stream(failed), false, false)
.await
.expect("the actor should build");
assert_eq!(
outcome.expect("a protocol error is not a transport error"),
Dispatch::Stop,
"a failed stream must stop the loop before it serves another frame"
);
assert_eq!(
events(&log),
vec!["send", "handle_error", "command_end"],
"one frame is written, the error hook runs once, and no terminator follows"
);
}
#[tokio::test]
async fn shutdown_abandons_a_terminator_the_peer_never_accepts() {
let log: EventLog = Arc::new(Mutex::new(Vec::new()));
let shutdown = CancellationToken::new();
let (mut actor, _handle) = build_actor_with(shutdown.clone()).expect("the actor should build");
let mut sink = StalledSink {
log: Arc::clone(&log),
};
let stream: FrameStream<Envelope, ()> = futures::stream::empty().boxed();
let outcome = {
let mut driving = std::pin::pin!(run_forward(
&mut sink,
&mut actor,
Response::Stream(stream),
&log
));
assert!(
futures::poll!(driving.as_mut()).is_pending(),
"the terminator write must stall before shutdown is requested"
);
shutdown.cancel();
driving
.await
.expect("an abandoned terminator is not a transport error")
};
assert_eq!(
outcome,
Dispatch::Stop,
"a cancelled 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"),
"a cancelled terminator must not run the completion hook: {observed:?}"
);
}
#[tokio::test]
async fn completion_hook_is_suppressed_when_the_response_is_cancelled() {
let stalled: FrameStream<Envelope, ()> = Box::pin(futures::stream::pending::<
Result<Envelope, WireframeError<()>>,
>());
let (log, outcome) = forward(Response::Stream(stalled), false, true)
.await
.expect("the actor should build");
assert_eq!(
outcome.expect("a cancelled response is not an error"),
Dispatch::Stop,
"a cancelled stream must stop the loop before it serves another frame"
);
assert!(
events(&log).is_empty(),
"a cancelled response writes no terminator and runs no hook"
);
}