use std::{future::Future, io, pin::Pin, sync::Arc, time::Duration};
use tokio_util::sync::CancellationToken;
use super::{
ConnectionActor,
FrameSink,
ProgressSignal,
PushSink,
drain::ActorStep,
drive::ResponseOutcome,
event::Event,
grace::GraceTimer,
sink::next_progress,
state::ActorState,
};
use crate::{
app::Packet,
correlation::CorrelatableFrame,
metrics::ResponseCancellationReason,
push::FrameLike,
response::WireframeError,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum WriteBound {
Finished,
Stopped,
GraceExpired,
}
impl WriteBound {
#[must_use]
pub(crate) const fn is_finished(self) -> bool { matches!(self, Self::Finished) }
#[must_use]
pub(crate) const fn is_grace_expired(self) -> bool { matches!(self, Self::GraceExpired) }
}
pub(super) enum Output<F, P> {
Push(P),
Frame(F),
}
pub(crate) async fn write_before_bound<W, G>(
write: W,
shutdown: &CancellationToken,
grace: G,
) -> io::Result<WriteBound>
where
W: Future<Output = io::Result<()>>,
G: Future<Output = ()>,
{
tokio::pin!(write);
tokio::pin!(grace);
tokio::select! {
biased;
result = &mut write => result.map(|()| WriteBound::Finished),
() = shutdown.cancelled() => Ok(WriteBound::Stopped),
() = &mut grace => Ok(WriteBound::GraceExpired),
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum WriteOutcome {
Written,
Cancelled,
}
pub(super) struct WriteBounds<'a> {
shutdown: &'a CancellationToken,
peer_closed: &'a CancellationToken,
timer: Arc<dyn GraceTimer>,
grace: Duration,
}
#[derive(Clone, Copy, Debug)]
pub(super) enum WriteLimit {
Written,
Shutdown,
Grace,
}
impl<F, E, P> ConnectionActor<F, E, P>
where
F: FrameLike + CorrelatableFrame + Packet,
E: std::fmt::Debug,
P: FrameLike,
{
pub(super) async fn dispatch_and_write<S>(
&mut self,
event: Event<F, E, P>,
state: &mut ActorState,
sink: &mut S,
) -> Result<Option<ResponseOutcome>, WireframeError<E>>
where
S: FrameSink<F> + PushSink<P> + Send,
{
let mut frames = Vec::new();
let mut pushes = Vec::new();
let mut step = ActorStep {
state,
out: &mut frames,
pushes: &mut pushes,
};
self.dispatch_event(event, &mut step)?;
if self.flush_or_cancel(pushes, frames, sink).await? == WriteOutcome::Cancelled {
return Ok(Some(ResponseOutcome::Cancelled));
}
self.run_deferred_command_end();
Ok(None)
}
pub(super) async fn flush_or_cancel<S>(
&mut self,
pushes: Vec<P>,
frames: Vec<F>,
sink: &mut S,
) -> Result<WriteOutcome, WireframeError<E>>
where
S: FrameSink<F> + PushSink<P> + Send,
{
let output = pushes
.into_iter()
.map(Output::Push)
.chain(frames.into_iter().map(Output::Frame));
for item in output {
if self.write_output(item, sink).await? == WriteOutcome::Cancelled {
return Ok(WriteOutcome::Cancelled);
}
}
Ok(WriteOutcome::Written)
}
async fn write_output<S>(
&mut self,
item: Output<F, P>,
sink: &mut S,
) -> Result<WriteOutcome, WireframeError<E>>
where
S: FrameSink<F> + PushSink<P> + Send,
{
let progress = sink.progress();
match item {
Output::Push(push) => {
self.write_one(sink.send_push(push), progress.as_deref())
.await
}
Output::Frame(frame) => {
self.write_one(sink.send_frame(frame), progress.as_deref())
.await
}
}
}
async fn write_one<Writing>(
&mut self,
writing: Writing,
progress: Option<&ProgressSignal>,
) -> Result<WriteOutcome, WireframeError<E>>
where
Writing: Future<Output = io::Result<()>>,
{
self.write_frame_bounded(writing, progress)
.await
.map_err(WireframeError::Io)
}
pub(crate) async fn write_frame_bounded<Err, Fut>(
&mut self,
writing: Fut,
progress: Option<&ProgressSignal>,
) -> Result<WriteOutcome, Err>
where
Fut: Future<Output = Result<(), Err>>,
{
let limit = {
let bounds = self.write_bounds();
write_bounded(writing, &bounds, progress).await?
};
Ok(self.record_write_limit(limit))
}
pub(super) fn record_write_limit(&mut self, limit: WriteLimit) -> WriteOutcome {
match limit {
WriteLimit::Written => WriteOutcome::Written,
WriteLimit::Shutdown => {
ResponseCancellationReason::Shutdown.record();
WriteOutcome::Cancelled
}
WriteLimit::Grace => {
self.cancel_stalled_response();
WriteOutcome::Cancelled
}
}
}
pub(super) fn write_bounds(&self) -> WriteBounds<'_> {
WriteBounds {
shutdown: &self.shutdown,
peer_closed: &self.peer_closed,
timer: Arc::clone(&self.grace_timer),
grace: self.peer_closed_grace,
}
}
}
async fn write_bounded<Err>(
writing: impl Future<Output = Result<(), Err>>,
bounds: &WriteBounds<'_>,
progress: Option<&ProgressSignal>,
) -> Result<WriteLimit, Err> {
tokio::pin!(writing);
tokio::select! {
biased;
result = &mut writing => {
result?;
Ok(WriteLimit::Written)
}
() = bounds.shutdown.cancelled() => Ok(WriteLimit::Shutdown),
() = bounds.peer_closed.cancelled() => {
write_within_grace(writing.as_mut(), bounds, progress).await
}
}
}
pub(super) async fn write_within_grace<Err>(
mut writing: Pin<&mut impl Future<Output = Result<(), Err>>>,
bounds: &WriteBounds<'_>,
progress: Option<&ProgressSignal>,
) -> Result<WriteLimit, Err> {
loop {
tokio::select! {
biased;
result = &mut writing => {
result?;
return Ok(WriteLimit::Written);
}
() = bounds.shutdown.cancelled() => return Ok(WriteLimit::Shutdown),
() = next_progress(progress) => {
}
() = bounds.timer.elapse(bounds.grace) => return Ok(WriteLimit::Grace),
}
}
}