use std::{future::Future, io, pin::Pin, time::Duration};
use futures::Sink;
use tokio::time::Instant;
use tokio_util::sync::CancellationToken;
use super::ResponseContext;
use crate::{
app::{PushWriteDiagnostics, codec_driver::ActorFrameSink},
codec::FrameCodec,
connection::{PendingPushes, PushSink},
metrics::PushWriteAbandonReason,
serializer::Serializer,
};
pub(super) async fn run_handler_with_pushes<Resp, S, K, F>(
ctx: &mut ResponseContext<'_, S, K, F>,
call: impl Future<Output = Resp>,
) -> io::Result<Option<Resp>>
where
S: Serializer + Send + Sync,
K: Sink<F::Frame, Error = io::Error> + Unpin + Send,
F: FrameCodec,
{
let shutdown = ctx.actor.shutdown_token();
let unobserved = ctx.actor.unobserved_token();
let bounds = PushWriteContext {
shutdown: &shutdown,
unobserved: &unobserved,
grace: ctx.actor.peer_closed_grace(),
diagnostics: push_diagnostics(ctx),
};
let mut flow = HandlerFlow {
lanes_open: ctx.actor.has_open_push_lanes(),
delivered_push: false,
};
let mut handler = HandlerRun {
call: std::pin::pin!(call),
finished: None,
};
loop {
match run_step(ctx, &mut handler, &mut flow, &bounds).await? {
LoopStep::Response(response) => return Ok(Some(response)),
LoopStep::Abandoned => return Ok(None),
LoopStep::Continue => flow.delivered_push = true,
}
}
}
struct HandlerFlow {
lanes_open: bool,
delivered_push: bool,
}
enum LoopStep<Resp> {
Response(Resp),
Abandoned,
Continue,
}
async fn run_step<Resp, S, K, F>(
ctx: &mut ResponseContext<'_, S, K, F>,
handler: &mut HandlerRun<'_, impl Future<Output = Resp>>,
flow: &mut HandlerFlow,
bounds: &PushWriteContext<'_>,
) -> io::Result<LoopStep<Resp>>
where
S: Serializer + Send + Sync,
K: Sink<F::Frame, Error = io::Error> + Unpin + Send,
F: FrameCodec,
{
let pending = match wait_for_batch(ctx, handler, flow, bounds).await {
LaneBatch::Response(response) => return Ok(LoopStep::Response(response)),
LaneBatch::Abandoned => return Ok(LoopStep::Abandoned),
LaneBatch::Frames(pending) => pending,
};
if write_batch(ctx, pending, handler, bounds).await? == PushWrite::Abandoned {
return Ok(LoopStep::Abandoned);
}
Ok(finished_step(handler))
}
fn finished_step<Resp>(handler: &mut HandlerRun<'_, impl Future<Output = Resp>>) -> LoopStep<Resp> {
handler
.finished
.take()
.map_or_else(|| LoopStep::Continue, LoopStep::Response)
}
enum LaneBatch<T, Resp> {
Frames(PendingPushes<T>),
Response(Resp),
Abandoned,
}
async fn wait_for_batch<Resp, S, K, F>(
ctx: &mut ResponseContext<'_, S, K, F>,
handler: &mut HandlerRun<'_, impl Future<Output = Resp>>,
flow: &mut HandlerFlow,
bounds: &PushWriteContext<'_>,
) -> LaneBatch<F::Frame, Resp>
where
S: Serializer + Send + Sync,
K: Sink<F::Frame, Error = io::Error> + Unpin + Send,
F: FrameCodec,
{
loop {
if !flow.lanes_open {
return LaneBatch::Response(handler.poll_while_running().await);
}
tokio::select! {
biased;
response = handler.poll_while_running() => return LaneBatch::Response(response),
() = bounds.shutdown.cancelled(), if flow.delivered_push => {
ctx.actor.discard_push_lanes();
flow.lanes_open = false;
return LaneBatch::Abandoned;
}
received = ctx.actor.next_pushes() => {
if let Some(frames) = received {
return LaneBatch::Frames(frames);
}
flow.lanes_open = false;
}
}
}
}
async fn write_batch<Resp, S, K, F>(
ctx: &mut ResponseContext<'_, S, K, F>,
pending: PendingPushes<F::Frame>,
handler: &mut HandlerRun<'_, impl Future<Output = Resp>>,
bounds: &PushWriteContext<'_>,
) -> io::Result<PushWrite>
where
S: Serializer + Send + Sync,
K: Sink<F::Frame, Error = io::Error> + Unpin + Send,
F: FrameCodec,
{
let terms = PushWriteContext {
diagnostics: push_diagnostics(ctx).with_priority(pending.priority),
..*bounds
};
for frame in pending.frames {
if write_push_watching(ctx, frame, handler, &terms).await? == PushWrite::Abandoned {
return Ok(PushWrite::Abandoned);
}
}
Ok(PushWrite::Written)
}
const fn push_diagnostics<S, K, F>(ctx: &ResponseContext<'_, S, K, F>) -> PushWriteDiagnostics
where
S: Serializer + Send + Sync,
K: Sink<F::Frame, Error = io::Error> + Unpin,
F: FrameCodec,
{
PushWriteDiagnostics::new(ctx.actor.connection_id(), ctx.actor.peer_addr())
}
struct HandlerRun<'a, Fut: Future> {
call: Pin<&'a mut Fut>,
finished: Option<Fut::Output>,
}
impl<Fut: Future> HandlerRun<'_, Fut> {
async fn poll_while_running(&mut self) -> Fut::Output {
if self.finished.is_some() {
return std::future::pending().await;
}
self.call.as_mut().await
}
}
#[derive(Clone, Copy)]
struct PushWriteContext<'a> {
shutdown: &'a CancellationToken,
unobserved: &'a CancellationToken,
grace: Duration,
diagnostics: PushWriteDiagnostics,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PushWrite {
Written,
Abandoned,
}
async fn write_push_watching<S, K, F, Fut>(
ctx: &mut ResponseContext<'_, S, K, F>,
frame: F::Frame,
handler: &mut HandlerRun<'_, Fut>,
terms: &PushWriteContext<'_>,
) -> io::Result<PushWrite>
where
S: Serializer + Send + Sync,
K: Sink<F::Frame, Error = io::Error> + Unpin + Send,
F: FrameCodec,
Fut: Future,
{
let started = Instant::now();
let writing = write_push(ctx, frame);
tokio::pin!(writing);
let deadline = grace_after_observation(terms.unobserved, terms.grace);
tokio::pin!(deadline);
loop {
let response = tokio::select! {
biased;
result = &mut writing => {
result?;
return Ok(PushWrite::Written);
}
response = handler.poll_while_running() => Some(response),
() = terms.shutdown.cancelled() => {
terms.diagnostics.record_abandonment(
PushWriteAbandonReason::Shutdown,
started.elapsed(),
);
return Ok(PushWrite::Abandoned);
}
() = &mut deadline => {
terms.diagnostics.record_abandonment(
PushWriteAbandonReason::IdleGraceExpired,
started.elapsed(),
);
return Ok(PushWrite::Abandoned);
}
};
if let Some(pending) = response {
handler.finished = Some(pending);
}
}
}
pub(super) async fn grace_after_observation(unobserved: &CancellationToken, grace: Duration) {
unobserved.cancelled().await;
tokio::time::sleep(grace).await;
}
async fn write_push<S, K, F>(
ctx: &mut ResponseContext<'_, S, K, F>,
frame: F::Frame,
) -> io::Result<()>
where
S: Serializer + Send + Sync,
K: Sink<F::Frame, Error = io::Error> + Unpin + Send,
F: FrameCodec,
{
let mut sink = ActorFrameSink::new(
ctx.serializer,
ctx.codec,
&mut *ctx.sink,
&mut *ctx.pipeline,
);
sink.send_push(frame).await
}