servlet 1.0.0

A small application runtime with an explicit operational contract
Documentation
//! Socket write-idle enforcement even when Hyper stops polling a response body.

use axum::body::{Body, Bytes};
use http_body::{Body as HttpBody, Frame, SizeHint};
use std::{
    future::Future,
    io,
    pin::Pin,
    task::{Context, Poll},
    time::Duration,
};
use tokio::{
    io::{AsyncRead, AsyncWrite, ReadBuf},
    sync::watch,
    time::{Instant, Sleep, sleep},
};

#[derive(Clone, Copy, Default)]
pub(super) enum TransferState {
    #[default]
    Idle,
    Producing(Instant),
    // The body is finished, but Hyper can still have headers or frames to write.
    Buffered(Instant),
}

impl TransferState {
    pub(super) fn deadline(self) -> Option<Instant> {
        match self {
            Self::Idle => None,
            Self::Producing(deadline) | Self::Buffered(deadline) => Some(deadline),
        }
    }

    pub(super) fn is_buffered(self) -> bool {
        matches!(self, Self::Buffered(_))
    }
}

pub(super) struct TransferBody {
    inner: Body,
    transfer: watch::Sender<TransferState>,
}

impl TransferBody {
    pub(super) fn new(
        inner: Body,
        deadline: Instant,
        transfer: watch::Sender<TransferState>,
    ) -> Self {
        transfer.send_modify(|state| {
            debug_assert!(matches!(state, TransferState::Idle));
            *state = TransferState::Producing(deadline);
        });
        Self { inner, transfer }
    }
}

impl HttpBody for TransferBody {
    type Data = Bytes;
    type Error = axum::Error;

    fn poll_frame(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Bytes>, Self::Error>>> {
        Pin::new(&mut self.inner).poll_frame(cx)
    }

    fn is_end_stream(&self) -> bool {
        self.inner.is_end_stream()
    }

    fn size_hint(&self) -> SizeHint {
        self.inner.size_hint()
    }
}

impl Drop for TransferBody {
    fn drop(&mut self) {
        // Hyper no longer needs the body, even if the response forbids a body.
        // Its headers and frames can still be buffered until the next flush.
        self.transfer.send_modify(|state| {
            let TransferState::Producing(deadline) = *state else {
                unreachable!("response body must own the current transfer");
            };
            *state = TransferState::Buffered(deadline);
        });
    }
}

pub(super) struct Transport<T> {
    inner: T,
    outcome: crate::telemetry::OutcomeSlot,
    transfer: watch::Sender<TransferState>,
    timeout: Duration,
    blocked: bool,
    timer: Pin<Box<Sleep>>,
}
impl<T> Transport<T> {
    pub(super) fn new(
        inner: T,
        timeout: Duration,
        outcome: crate::telemetry::OutcomeSlot,
        transfer: watch::Sender<TransferState>,
    ) -> Self {
        Self {
            inner,
            outcome,
            transfer,
            timeout,
            blocked: false,
            timer: Box::pin(sleep(timeout)),
        }
    }
    fn record_error(&self, error: &io::Error) {
        if error.kind() == io::ErrorKind::TimedOut {
            crate::telemetry::mark_current(&self.outcome, crate::telemetry::Outcome::TimedOut);
        } else {
            crate::telemetry::fail_current(
                &self.outcome,
                crate::telemetry::ExchangeFailure::Transport,
            );
        }
    }

    fn record_write_error<R>(&self, result: &Poll<io::Result<R>>) {
        // Buffered bytes can belong to a previous exchange whose outcome has
        // already been recorded. Don't attribute their failure to a later one.
        if let Poll::Ready(Err(error)) = result
            && !self.transfer.borrow().is_buffered()
        {
            self.record_error(error);
        }
    }
    fn observe<R>(
        &mut self,
        cx: &mut Context<'_>,
        result: Poll<io::Result<R>>,
    ) -> Poll<io::Result<R>> {
        if result.is_ready() {
            self.blocked = false;
            self.record_write_error(&result);
            return result;
        }
        if !self.blocked {
            self.blocked = true;
            self.timer.as_mut().reset(Instant::now() + self.timeout);
        }
        if self.timer.as_mut().poll(cx).is_ready() {
            let result = Poll::Ready(Err(io::Error::new(
                io::ErrorKind::TimedOut,
                "socket write idle timeout",
            )));
            self.record_write_error(&result);
            result
        } else {
            Poll::Pending
        }
    }
}
impl<T: AsyncRead + Unpin> AsyncRead for Transport<T> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        let result = Pin::new(&mut self.inner).poll_read(cx, buf);
        if let Poll::Ready(Err(error)) = &result {
            self.record_error(error);
        }
        result
    }
}
impl<T: AsyncWrite + Unpin> AsyncWrite for Transport<T> {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        let result = Pin::new(&mut self.inner).poll_write(cx, buf);
        self.observe(cx, result)
    }
    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let result = Pin::new(&mut self.inner).poll_flush(cx);
        if matches!(result, Poll::Ready(Ok(()))) {
            self.transfer.send_if_modified(|state| {
                if !state.is_buffered() {
                    return false;
                }
                *state = TransferState::Idle;
                true
            });
        }
        self.observe(cx, result)
    }
    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let result = Pin::new(&mut self.inner).poll_shutdown(cx);
        self.observe(cx, result)
    }
}

#[cfg(all(test, feature = "otel"))]
#[path = "transport_test.rs"]
mod transport_test;