use std::{
future::{self, Future},
io,
};
use bytes::Bytes;
use futures::{Sink, Stream};
use tokio_util::sync::CancellationToken;
use super::{
super::{
envelope::{Envelope, Packet},
recovery_codec::DecodedItem,
},
frames::{InboundFrames, NextFrame},
recovery::{RecoveryCoordinator, resolve_read_item},
stream_active::ActiveStream,
stream_dispatch::Connection,
stream_handles::LoopState,
stream_pushes::push_event,
stream_types::Event,
};
use crate::{
codec::FrameCodec,
connection::ConnectionActor,
frame::FrameMetadata,
message::{DecodeWith, EncodeWith},
serializer::Serializer,
};
impl<S, E, R, K, F> Connection<'_, S, E, R, K, F>
where
S: Serializer + FrameMetadata<Frame = Envelope> + Send + Sync,
E: Packet,
R: Stream<Item = io::Result<DecodedItem<F::Frame>>> + Unpin,
K: Sink<F::Frame, Error = io::Error> + Unpin + Send,
F: FrameCodec,
Envelope: DecodeWith<S> + EncodeWith<S>,
{
pub(super) async fn next_event(&mut self, state: &mut LoopState) -> Event<F::Frame> {
let read_timeout_ms = self.ctx.read_timeout_ms;
let shutdown = self.shutdown;
if std::mem::take(&mut state.serve_read_first) {
let probe = self.inbound.try_next(self.reader).await;
return match probe {
Ok(NextFrame::TimedOut) => self.await_event(state, read_timeout_ms).await,
Ok(next) => frame_event(next, self.inbound, &mut self.recovery, shutdown).await,
Err(error) => Event::Frame(Err(error)),
};
}
self.await_event(state, read_timeout_ms).await
}
async fn await_event(
&mut self,
state: &mut LoopState,
read_timeout_ms: u64,
) -> Event<F::Frame> {
let Connection {
reader,
inbound,
actor,
recovery,
..
} = self;
let shutdown = self.shutdown;
let push_lanes_open = actor.has_open_push_lanes();
let read = read_event(
inbound,
reader,
recovery,
ReadBounds::new(read_timeout_ms, shutdown),
);
race_event(actor, state.streams.active.as_mut(), push_lanes_open, read).await
}
pub(super) async fn read_frame(&mut self, read_timeout_ms: u64) -> Event<F::Frame> {
read_event(
&mut *self.inbound,
&mut *self.reader,
&mut self.recovery,
ReadBounds::new(read_timeout_ms, self.shutdown),
)
.await
}
}
#[derive(Clone, Copy)]
struct ReadBounds<'a> {
timeout_ms: u64,
shutdown: &'a CancellationToken,
}
impl<'a> ReadBounds<'a> {
const fn new(timeout_ms: u64, shutdown: &'a CancellationToken) -> Self {
Self {
timeout_ms,
shutdown,
}
}
}
async fn race_event<Fr, D>(
actor: &mut ConnectionActor<Envelope, (), Fr>,
active: Option<&mut ActiveStream>,
push_lanes_open: bool,
read: D,
) -> Event<Fr>
where
Fr: Send + 'static,
D: Future<Output = Event<Fr>>,
{
tokio::select! {
biased;
pushes = actor.next_pushes(), if push_lanes_open => push_event(pushes),
outcome = poll_live(active) => Event::Handler(outcome),
event = read => event,
}
}
async fn poll_live(active: Option<&mut ActiveStream>) -> Option<Bytes> {
match active {
Some(live) => live.poll_handler().await,
None => future::pending().await,
}
}
async fn read_event<R, Fr>(
inbound: &mut InboundFrames<DecodedItem<Fr>, Fr>,
reader: &mut R,
recovery: &mut RecoveryCoordinator<'_>,
bounds: ReadBounds<'_>,
) -> Event<Fr>
where
R: Stream<Item = io::Result<DecodedItem<Fr>>> + Unpin,
{
let next = inbound
.next_frame(reader, bounds.timeout_ms, bounds.shutdown)
.await;
match next {
Ok(ready) => frame_event(ready, inbound, recovery, bounds.shutdown).await,
Err(error) => Event::Frame(Err(error)),
}
}
async fn frame_event<T>(
next: NextFrame<DecodedItem<T>>,
inbound: &mut InboundFrames<DecodedItem<T>, T>,
recovery: &mut RecoveryCoordinator<'_>,
shutdown: &CancellationToken,
) -> Event<T> {
match next {
NextFrame::Ready(item) => {
match resolve_read_item(item, inbound, recovery, shutdown).await {
Ok(Some(frame)) => Event::Frame(Ok(Some(frame))),
Ok(None) => Event::Tick,
Err(error) => Event::Frame(Err(error)),
}
}
NextFrame::Closed if shutdown.is_cancelled() => Event::Shutdown,
NextFrame::Closed => Event::Frame(Ok(None)),
NextFrame::TimedOut => Event::Tick,
}
}