servlet 1.2.0

A small application runtime with an explicit operational contract
Documentation
//! Native multi-member gzip decoding over bounded wire input, without detached work.
use super::{ClientError, ClientLimits};
use async_compression::tokio::bufread::GzipDecoder;
use axum::{body::Bytes, http::HeaderMap};
use futures_util::StreamExt;
use std::io;
use tokio::io::{AsyncRead, AsyncReadExt};
use tokio_util::io::StreamReader;

pub(super) enum Body {
    Native {
        response: reqwest::Response,
        consumed: usize,
        limit: usize,
    },
    Gzip(Box<dyn AsyncRead + Unpin + Send>),
}
impl Body {
    pub(super) fn new(
        response: reqwest::Response,
        headers: &mut HeaderMap,
        gzip: bool,
        limits: ClientLimits,
    ) -> Result<Self, ClientError> {
        let mut encodings = headers.get_all("content-encoding").iter();
        let encoding = encodings.next();
        let multiple = encodings.next().is_some();
        let encoded = gzip && encoding.is_some();
        let gzip_encoding =
            encoding.is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"gzip"));
        if encoded && (multiple || !gzip_encoding) {
            if multiple
                || !encoding.is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"identity"))
            {
                return Err(ClientError::Transport);
            }
        } else if encoded {
            return Ok(Self::decoded(response, headers, limits));
        }
        Ok(Self::Native {
            response,
            consumed: 0,
            limit: limits.max_response_wire_bytes,
        })
    }
    fn decoded(response: reqwest::Response, headers: &mut HeaderMap, limits: ClientLimits) -> Self {
        headers.remove("content-encoding");
        headers.remove("content-length");
        let input = response.bytes_stream().scan(0usize, move |used, result| {
            let result = result
                .map_err(ClientError::transport)
                .and_then(|bytes| {
                    if bytes.len() > limits.max_response_wire_bytes - *used {
                        return Err(ClientError::ResponseTooLarge);
                    }
                    *used += bytes.len();
                    Ok(bytes)
                })
                .map_err(io::Error::other);
            std::future::ready(Some(result))
        });
        let mut decoder = GzipDecoder::new(StreamReader::new(Box::pin(input)));
        decoder.multiple_members(true);
        Self::Gzip(Box::new(decoder))
    }
    pub(super) async fn chunk(&mut self, remaining: usize) -> Result<Option<Bytes>, ClientError> {
        match self {
            Self::Native {
                response,
                consumed,
                limit,
            } => {
                let chunk = response.chunk().await.map_err(ClientError::transport)?;
                if let Some(bytes) = &chunk {
                    if bytes.len() > *limit - *consumed {
                        return Err(ClientError::ResponseTooLarge);
                    }
                    *consumed += bytes.len();
                }
                Ok(chunk)
            }
            Self::Gzip(reader) => {
                // Ask for at most one byte beyond the remaining decoded allowance;
                // Response rejects that byte before exposing/appending the chunk.
                let mut buffer = [0u8; 8192];
                let allowance = buffer.len().min(remaining + 1);
                let read = reader
                    .read(&mut buffer[..allowance])
                    .await
                    .map_err(|error| {
                        error
                            .get_ref()
                            .and_then(|cause| cause.downcast_ref::<ClientError>())
                            .copied()
                            .unwrap_or(ClientError::Transport)
                    })?;
                Ok((read != 0).then(|| Bytes::copy_from_slice(&buffer[..read])))
            }
        }
    }
}