use std::{
marker::PhantomData,
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use futures::{Sink, SinkExt};
use log::warn;
use tokio::io;
use super::FramePipeline;
use crate::{
app::{Envelope, outbound_encoding::encode_message_frame},
codec::{CodecError, FrameCodec},
connection::{FrameSink, ProgressSignal, PushSink},
message::EncodeWith,
metrics::{AppResponseSendOutcome, Direction, inc_app_response_send, inc_frames},
serializer::Serializer,
};
pub(crate) struct OutboundTransport<'a, S, K, F>
where
F: FrameCodec,
{
pub(crate) serializer: &'a S,
pub(crate) codec: &'a F,
pub(crate) sink: &'a mut K,
}
pub(crate) async fn send_envelope<S, K, F>(
transport: &mut OutboundTransport<'_, S, K, F>,
envelope: &Envelope,
pipeline: &mut FramePipeline<F::Frame>,
) -> io::Result<()>
where
S: Serializer + Send + Sync,
K: Sink<F::Frame, Error = io::Error> + Unpin,
F: FrameCodec,
Envelope: EncodeWith<S>,
{
let mut encoded = encode_message_frame(transport.serializer, transport.codec, envelope)
.map_err(|e| {
let id = envelope.id;
let correlation_id = envelope.correlation_id;
warn!(
"failed to serialize outbound envelope: stage=serialize, \
category=serialization_failure, id={id}, correlation_id={correlation_id:?}, \
error={e:?}"
);
crate::metrics::inc_handler_errors();
inc_app_response_send(AppResponseSendOutcome::SerializationFailure);
io::Error::other(e)
})?;
pipeline.before_send_frame(&mut encoded.frame);
match transport.sink.send(encoded.frame).await {
Ok(()) => {
inc_app_response_send(AppResponseSendOutcome::Success);
Ok(())
}
Err(error) => {
let id = envelope.id;
let correlation_id = envelope.correlation_id;
let outcome = classify_send_error(&error);
warn!(
"failed to send outbound frame: stage=write, category={}, id={id}, \
correlation_id={correlation_id:?}, error={error:?}",
outcome.as_str()
);
crate::metrics::inc_handler_errors();
inc_app_response_send(outcome);
Err(io::Error::other(error))
}
}
}
fn classify_send_error(error: &io::Error) -> AppResponseSendOutcome {
let is_codec_rejection = error
.get_ref()
.and_then(|inner| inner.downcast_ref::<CodecError>())
.is_some_and(|codec_error| matches!(codec_error, CodecError::Framing(_)));
if is_codec_rejection {
AppResponseSendOutcome::CodecRejected
} else {
AppResponseSendOutcome::TransportFailure
}
}
pub(crate) async fn flush_pipeline_output<S, K, F>(
transport: &mut OutboundTransport<'_, S, K, F>,
pipeline: &mut FramePipeline<F::Frame>,
) -> io::Result<()>
where
S: Serializer + Send + Sync,
K: Sink<F::Frame, Error = io::Error> + Unpin,
F: FrameCodec,
Envelope: EncodeWith<S>,
{
let mut envelopes = pipeline.drain_output();
for envelope in envelopes.drain(..) {
send_envelope(transport, &envelope, pipeline).await?;
}
Ok(())
}
pub(crate) async fn send_native_frame<K, F>(
sink: &mut K,
pipeline: &mut FramePipeline<F::Frame>,
mut frame: F::Frame,
) -> io::Result<()>
where
K: Sink<F::Frame, Error = io::Error> + Unpin,
F: FrameCodec,
{
pipeline.before_send_frame(&mut frame);
match sink.send(frame).await {
Ok(()) => {
inc_frames(Direction::Outbound);
inc_app_response_send(AppResponseSendOutcome::Success);
Ok(())
}
Err(error) => {
let outcome = classify_send_error(&error);
warn!(
"failed to send protocol frame: stage=write, category={}, error={error:?}",
outcome.as_str()
);
crate::metrics::inc_handler_errors();
inc_app_response_send(outcome);
Err(io::Error::other(error))
}
}
}
pub(crate) struct ActorFrameSink<'a, S, K, F>
where
F: FrameCodec,
{
serializer: &'a S,
codec: &'a F,
sink: &'a mut K,
pipeline: &'a mut FramePipeline<F::Frame>,
progress: Arc<ProgressSignal>,
}
impl<'a, S, K, F> ActorFrameSink<'a, S, K, F>
where
F: FrameCodec,
{
pub(crate) fn new(
serializer: &'a S,
codec: &'a F,
sink: &'a mut K,
pipeline: &'a mut FramePipeline<F::Frame>,
) -> Self {
Self {
serializer,
codec,
sink,
pipeline,
progress: Arc::new(ProgressSignal::default()),
}
}
}
impl<S, K, F> FrameSink<Envelope> for ActorFrameSink<'_, S, K, F>
where
S: Serializer + Send + Sync,
K: Sink<F::Frame, Error = io::Error> + Unpin + Send,
F: FrameCodec,
Envelope: EncodeWith<S>,
{
async fn send_frame(&mut self, envelope: Envelope) -> io::Result<()> {
self.pipeline.process(envelope)?;
let mut transport = OutboundTransport {
serializer: self.serializer,
codec: self.codec,
sink: &mut ProgressSink::<K, F::Frame> {
inner: &mut *self.sink,
progress: &self.progress,
frame: PhantomData,
},
};
flush_pipeline_output(&mut transport, self.pipeline).await
}
fn progress(&self) -> Option<Arc<ProgressSignal>> { Some(Arc::clone(&self.progress)) }
}
struct ProgressSink<'a, K, F> {
inner: &'a mut K,
progress: &'a ProgressSignal,
frame: PhantomData<fn(F)>,
}
impl<K, F> Sink<F> for ProgressSink<'_, K, F>
where
K: Sink<F, Error = io::Error> + Unpin,
{
type Error = io::Error;
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut *self.get_mut().inner).poll_ready(cx)
}
fn start_send(self: Pin<&mut Self>, item: F) -> io::Result<()> {
Pin::new(&mut *self.get_mut().inner).start_send(item)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
let this = self.get_mut();
let polled = Pin::new(&mut *this.inner).poll_flush(cx);
if matches!(polled, Poll::Ready(Ok(()))) {
this.progress.report();
}
polled
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut *self.get_mut().inner).poll_close(cx)
}
}
impl<S, K, F> PushSink<F::Frame> for ActorFrameSink<'_, S, K, F>
where
S: Serializer + Send + Sync,
K: Sink<F::Frame, Error = io::Error> + Unpin + Send,
F: FrameCodec,
{
async fn send_push(&mut self, mut frame: F::Frame) -> io::Result<()> {
self.pipeline.before_send_frame(&mut frame);
self.sink.send(frame).await?;
inc_frames(Direction::Outbound);
Ok(())
}
}