use std::{future::Future, io, pin::Pin, sync::OnceLock};
use futures::{Stream, StreamExt};
use log::debug;
use tokio_util::sync::CancellationToken;
use super::super::frame_handling::Dispatch;
use crate::connection::UnobservedCause;
pub(super) struct PeerObservation<'a> {
pub(super) eof: &'a CancellationToken,
pub(super) unobserved: &'a CancellationToken,
pub(super) cause: &'a OnceLock<UnobservedCause>,
}
impl<'a> PeerObservation<'a> {
pub(super) const fn new(
eof: &'a CancellationToken,
unobserved: &'a CancellationToken,
cause: &'a OnceLock<UnobservedCause>,
) -> Self {
Self {
eof,
unobserved,
cause,
}
}
}
pub(super) async fn handle_watching_peer<H, R, F>(
handling: H,
reader: &mut R,
observation: PeerObservation<'_>,
pending_frame: &mut Option<F>,
) -> io::Result<Dispatch>
where
H: Future<Output = io::Result<Dispatch>>,
R: Stream<Item = io::Result<F>> + Unpin,
{
tokio::pin!(handling);
if pending_frame.is_some() {
return await_unobserved_peer(
handling.as_mut(),
observation.unobserved,
observation.cause,
UnobservedCause::BufferedRequest,
)
.await;
}
if observation.eof.is_cancelled() {
return await_unobserved_peer(
handling.as_mut(),
observation.unobserved,
observation.cause,
UnobservedCause::HalfClose,
)
.await;
}
tokio::select! {
biased;
result = &mut handling => result,
next = reader.next() => {
settle_read(next, pending_frame, handling.as_mut(), observation).await
}
}
}
async fn settle_read<H, F>(
next: Option<io::Result<F>>,
pending_frame: &mut Option<F>,
handling: Pin<&mut H>,
observation: PeerObservation<'_>,
) -> io::Result<Dispatch>
where
H: Future<Output = io::Result<Dispatch>>,
{
let PeerObservation {
eof,
unobserved,
cause,
} = observation;
match next {
Some(Ok(frame)) => {
*pending_frame = Some(frame);
await_unobserved_peer(
handling,
unobserved,
cause,
UnobservedCause::BufferedRequest,
)
.await
}
Some(Err(error)) => Err(error),
None => {
eof.cancel();
await_unobserved_peer(handling, unobserved, cause, UnobservedCause::HalfClose).await
}
}
}
async fn await_unobserved_peer<H>(
handling: Pin<&mut H>,
unobserved: &CancellationToken,
cause_cell: &OnceLock<UnobservedCause>,
cause: UnobservedCause,
) -> io::Result<Dispatch>
where
H: Future<Output = io::Result<Dispatch>>,
{
debug!(
"stopping peer observation after {}; the actor bounds the pending response",
cause.as_str()
);
cause_cell.set(cause).ok();
unobserved.cancel();
handling.await
}
#[cfg(test)]
#[path = "peer_watch_tests.rs"]
mod tests;