servlet 1.0.0

A small application runtime with an explicit operational contract
Documentation
//! Response metadata is native; consuming bytes remains under the original lease.
use super::{ClientError, body::Body, observation::Observation, state::Lease};
use axum::{
    body::Bytes,
    http::{HeaderMap, StatusCode},
};
use tokio::time::{Instant, timeout_at};
use tracing::Instrument;

/// A response whose body owns capacity until EOF, failure, cancellation, or drop.
/// There is no detached body task. Retaining this value without polling or dropping
/// it retains capacity and may cause managed cleanup to time out.
pub struct Response {
    // Drop the native body before returning the managed operation permit.
    native: Option<Body>,
    lease: Option<Lease>,
    observation: Option<Observation>,
    status: StatusCode,
    headers: HeaderMap,
    deadline: Instant,
    progress: Instant,
    observed: usize,
    error: Option<ClientError>,
}
impl Response {
    pub(super) fn new(
        native: reqwest::Response,
        lease: Lease,
        deadline: Instant,
        mut observation: Observation,
        head: bool,
    ) -> Result<Self, ClientError> {
        let status = native.status();
        let mut headers = native.headers().clone();
        let native = match Body::new(
            native,
            &mut headers,
            lease.inner.config.gzip && !head && !matches!(status.as_u16(), 204 | 304),
            lease.inner.config.limits,
        ) {
            Ok(body) => body,
            Err(error) => {
                observation.failed(error);
                return Err(error);
            }
        };
        Ok(Self {
            status,
            headers,
            native: Some(native),
            lease: Some(lease),
            observation: Some(observation),
            deadline,
            progress: Instant::now(),
            observed: 0,
            error: None,
        })
    }
    /// Native HTTP status; non-success statuses are not retried or discarded.
    pub fn status(&self) -> StatusCode {
        self.status
    }
    /// Native response headers. They can contain secrets; Servlet does not log them.
    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }
    /// Read one native body chunk with cumulative byte, idle, and total bounds.
    /// Idle time includes caller pauses between chunks. Limits count delivered bytes;
    /// gzip-decoded bytes count when decoding is explicitly enabled.
    pub async fn chunk(&mut self) -> Result<Option<Bytes>, ClientError> {
        let span = self
            .observation
            .as_ref()
            .map(|observed| observed.span.clone())
            .unwrap_or_else(tracing::Span::none);
        self.read_chunk().instrument(span).await
    }
    async fn read_chunk(&mut self) -> Result<Option<Bytes>, ClientError> {
        if let Some(error) = self.error {
            return Err(error);
        }
        let Some(lease) = &self.lease else {
            return Ok(None);
        };
        let limits = lease.inner.config.limits;
        let cutoff = self.deadline.min(self.progress + limits.read_timeout);
        let expired = if cutoff == self.deadline {
            ClientError::Deadline
        } else {
            ClientError::ReadTimeout
        };
        let result = if lease.inner.closed.is_cancelled() {
            Err(ClientError::Closed)
        } else if Instant::now() >= cutoff {
            Err(expired)
        } else {
            tokio::select! {
                biased;
                () = lease.inner.closed.cancelled() => Err(ClientError::Closed),
                result = timeout_at(cutoff, self.native.as_mut().expect("leased response").chunk(limits.max_response_bytes - self.observed)) => {
                    if Instant::now() >= cutoff { Err(expired) }
                    else { result.map_err(|_| expired).and_then(|result| result) }
                }
            }
        };
        match result {
            Ok(Some(chunk)) => {
                if chunk.len() > limits.max_response_bytes - self.observed {
                    return self.fail(ClientError::ResponseTooLarge);
                }
                self.observed += chunk.len();
                if !chunk.is_empty() {
                    self.progress = Instant::now();
                }
                Ok(Some(chunk))
            }
            Ok(None) => {
                self.native.take();
                self.lease.take();
                if let Some(mut observed) = self.observation.take() {
                    observed.complete(self.status.as_u16());
                }
                Ok(None)
            }
            Err(error) => self.fail(error),
        }
    }
    /// Buffer the complete body, bounded by the configured response-byte allowance.
    pub async fn bytes(mut self) -> Result<Vec<u8>, ClientError> {
        let mut bytes = Vec::new();
        while let Some(chunk) = self.chunk().await? {
            bytes.extend_from_slice(&chunk);
        }
        Ok(bytes)
    }
    fn fail(&mut self, error: ClientError) -> Result<Option<Bytes>, ClientError> {
        self.native.take();
        self.lease.take();
        if let Some(mut observed) = self.observation.take() {
            observed.failed(error);
        }
        self.error = Some(error);
        Err(error)
    }
}