use std::{future::Future, io, pin::Pin};
use futures::{
Sink,
Stream,
StreamExt,
future::{self, Either},
};
use tokio::time::{Instant, Sleep, sleep, sleep_until};
use tokio_util::sync::CancellationToken;
use super::{
super::PushWriteDiagnostics,
frames::InboundExpiry,
push_service::{PushBatch, PushTransport},
};
use crate::{
codec::FrameCodec,
connection::{PEER_CLOSED_RESPONSE_GRACE, write_before_bound},
metrics::PushWriteAbandonReason,
serializer::Serializer,
};
#[derive(Clone, Copy, Debug)]
pub(super) struct FrameWrite {
may_continue: bool,
peer_closed: bool,
}
impl FrameWrite {
const fn written(peer_closed: bool) -> Self {
Self {
may_continue: true,
peer_closed,
}
}
const fn stopped(peer_closed: bool) -> Self {
Self {
may_continue: false,
peer_closed,
}
}
pub(super) const fn may_continue(self) -> bool { self.may_continue }
pub(super) const fn peer_closed(self) -> bool { self.peer_closed }
}
pub(super) async fn write_frame<S, K, F, R, I>(
transport: &mut PushTransport<'_, S, K, F>,
frame: F::Frame,
batch: &mut PushBatch<'_, F, R, I>,
peer_closed: bool,
) -> io::Result<FrameWrite>
where
S: Serializer + Send + Sync,
K: Sink<F::Frame, Error = io::Error> + Unpin + Send,
F: FrameCodec,
R: Stream<Item = io::Result<I>> + Unpin,
{
let diagnostics = transport.diagnostics.with_priority(batch.priority);
let write = transport.write(frame);
tokio::pin!(write);
let mut closed = peer_closed;
if batch.pending_frame.is_none() && !closed {
let started = Instant::now();
let grace = sleep(PEER_CLOSED_RESPONSE_GRACE);
tokio::pin!(grace);
loop {
let purge = purge_wait(Some(batch.expiry.due()));
tokio::pin!(purge);
tokio::select! {
biased;
result = &mut write => {
result?;
return Ok(FrameWrite::written(closed));
}
() = batch.shutdown.cancelled() => {
diagnostics.record_abandonment(
PushWriteAbandonReason::Shutdown,
started.elapsed(),
);
return Ok(FrameWrite::stopped(closed));
}
() = &mut grace => {
diagnostics.record_abandonment(
PushWriteAbandonReason::IdleGraceExpired,
started.elapsed(),
);
return Ok(FrameWrite::stopped(closed));
}
next = batch.reader.next() => match next {
Some(Ok(next_frame)) => {
*batch.pending_frame = Some(next_frame);
break;
}
Some(Err(error)) => return Err(error),
None => {
batch.peer_eof.cancel();
closed = true;
break;
}
},
() = &mut purge => batch.expiry.expire_silence(),
}
}
}
Ok(
if finish_write_purging(write.as_mut(), batch, diagnostics).await? {
FrameWrite::written(closed)
} else {
FrameWrite::stopped(closed)
},
)
}
async fn finish_write_purging<W, F, R, I>(
write: Pin<&mut W>,
batch: &mut PushBatch<'_, F, R, I>,
diagnostics: PushWriteDiagnostics,
) -> io::Result<bool>
where
W: Future<Output = io::Result<()>>,
F: FrameCodec,
{
finish_write_with(write, batch.shutdown, diagnostics, Some(&mut batch.expiry)).await
}
pub(super) async fn finish_write<W>(
write: Pin<&mut W>,
shutdown: &CancellationToken,
diagnostics: PushWriteDiagnostics,
) -> io::Result<bool>
where
W: Future<Output = io::Result<()>>,
{
finish_write_with(write, shutdown, diagnostics, None).await
}
async fn finish_write_with<W>(
write: Pin<&mut W>,
shutdown: &CancellationToken,
diagnostics: PushWriteDiagnostics,
mut expiry: Option<&mut InboundExpiry<'_>>,
) -> io::Result<bool>
where
W: Future<Output = io::Result<()>>,
{
let started = Instant::now();
let bound = match expiry.as_mut() {
Some(state) => write_before_bound(write, shutdown, grace_with_purges(state)).await?,
None => write_before_bound(write, shutdown, sleep(PEER_CLOSED_RESPONSE_GRACE)).await?,
};
if bound.is_finished() {
return Ok(true);
}
let reason = if bound.is_grace_expired() {
PushWriteAbandonReason::IdleGraceExpired
} else {
PushWriteAbandonReason::Shutdown
};
diagnostics.record_abandonment(reason, started.elapsed());
Ok(false)
}
async fn grace_with_purges(expiry: &mut InboundExpiry<'_>) {
let grace = sleep(PEER_CLOSED_RESPONSE_GRACE);
tokio::pin!(grace);
loop {
let purge = purge_wait(Some(expiry.due()));
tokio::pin!(purge);
tokio::select! {
biased;
() = &mut grace => return,
() = &mut purge => expiry.expire_silence(),
}
}
}
fn purge_wait(deadline: Option<Instant>) -> Either<Sleep, future::Pending<()>> {
deadline.map_or_else(
|| Either::Right(future::pending()),
|at| Either::Left(sleep_until(at)),
)
}