servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! Completion means body production ended server-side, never peer acknowledgement.
use super::body::ExchangeBody;
use crate::{
    task::BoxError,
    telemetry::{Exchange, ExchangeFailure, Outcome},
};
use axum::{body::Bytes, http::StatusCode};
use http_body::{Body, Frame, SizeHint};
use std::{
    pin::Pin,
    task::{Context, Poll},
};

pub(super) struct ObservedBody {
    inner: ExchangeBody,
    observation: Exchange,
    completion: Outcome,
    span: tracing::Span,
}
impl ObservedBody {
    pub(super) fn new(inner: ExchangeBody, observation: Exchange, status: StatusCode) -> Self {
        let completion = if status.is_client_error() || status.is_server_error() {
            Outcome::Failed
        } else {
            Outcome::Completed
        };
        if inner.is_end_stream() {
            observation.mark(completion);
        }
        Self {
            inner,
            observation,
            completion,
            span: tracing::Span::current(),
        }
    }
}
impl Body for ObservedBody {
    type Data = Bytes;
    type Error = BoxError;
    fn poll_frame(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Bytes>, BoxError>>> {
        let this = self.get_mut();
        let _entered = this.span.enter();
        let result = Pin::new(&mut this.inner).poll_frame(cx);
        match &result {
            Poll::Ready(Some(Err(error))) => {
                let mut cause: Option<&(dyn std::error::Error + 'static)> = Some(error.as_ref());
                let mut outcome = Outcome::Failed;
                while let Some(error) = cause {
                    if error
                        .downcast_ref::<std::io::Error>()
                        .is_some_and(|error| error.kind() == std::io::ErrorKind::TimedOut)
                    {
                        outcome = Outcome::TimedOut;
                        break;
                    }
                    cause = error.source();
                }
                if outcome == Outcome::TimedOut {
                    this.observation.mark(outcome);
                } else {
                    this.observation.fail(ExchangeFailure::Body);
                }
            }
            Poll::Ready(None) => this.observation.mark(this.completion),
            Poll::Ready(Some(Ok(_))) if this.inner.is_end_stream() => {
                this.observation.mark(this.completion)
            }
            _ => {}
        }
        result
    }
    fn is_end_stream(&self) -> bool {
        self.inner.is_end_stream()
    }
    fn size_hint(&self) -> SizeHint {
        self.inner.size_hint()
    }
}

#[cfg(test)]
#[path = "observed_test.rs"]
mod observed_test;