servlet 1.2.0

A small application runtime with an explicit operational contract
Documentation
//! A request receives one deadline before waiting for capacity.
use super::{
    ClientError, Response, encoding,
    observation::Observation,
    state::Inner,
    target::{MAX_HEADER_VALUE_BYTES, MAX_TARGET_BYTES},
};
use axum::http::HeaderMap;
use base64::{Engine, engine::general_purpose::STANDARD};
use serde::Serialize;
use std::sync::Arc;
use tokio::time::{Instant, timeout_at};
use tracing::Instrument;

/// Validated target and bounded explicit headers/body; no network work until send.
pub struct Request {
    inner: Arc<Inner>,
    url: url::Url,
    method: reqwest::Method,
    headers: HeaderMap,
    body: Option<Vec<u8>>,
}
impl Request {
    pub(super) fn new(
        inner: Arc<Inner>,
        method: reqwest::Method,
        path: &str,
    ) -> Result<Self, ClientError> {
        if !matches!(
            method,
            reqwest::Method::GET
                | reqwest::Method::HEAD
                | reqwest::Method::POST
                | reqwest::Method::PUT
                | reqwest::Method::PATCH
                | reqwest::Method::DELETE
                | reqwest::Method::OPTIONS
        ) {
            return Err(ClientError::Configuration);
        }
        let url = super::target::resolve(&inner.config.origin, path)?;
        let headers = inner.config.headers.clone();
        Ok(Self {
            inner,
            url,
            method,
            headers,
            body: None,
        })
    }
    /// Add/replace a sensitive header, sharing the configured 32-name/16-KiB cap.
    /// Routing, framing, proxy credentials, and trace-context headers are reserved.
    pub fn header(mut self, name: &str, value: &str) -> Result<Self, ClientError> {
        super::target::header(&mut self.headers, name, value)?;
        Ok(self)
    }
    /// Supply already-owned bytes, rejecting values above the request-byte cap.
    /// Allocation performed by the caller before this method remains caller-owned.
    pub fn body(mut self, body: Vec<u8>) -> Result<Self, ClientError> {
        if body.len() > self.inner.config.limits.max_request_bytes {
            return Err(ClientError::RequestTooLarge);
        }
        self.body = Some(body);
        Ok(self)
    }
    /// Serialize a JSON body within the request allowance and set its content type.
    pub fn json<T: Serialize + ?Sized>(self, value: &T) -> Result<Self, ClientError> {
        let body = encoding::json(value, self.inner.config.limits.max_request_bytes)?;
        self.header("content-type", "application/json")?.body(body)
    }

    /// Serialize a form body and set its content type. The encoded body must fit
    /// the request allowance. Structs, maps, and sequences of pairs are supported.
    pub fn form<T: Serialize + ?Sized>(self, fields: &T) -> Result<Self, ClientError> {
        let encoded = encoding::form(fields, self.inner.config.limits.max_request_bytes)?;
        self.body(encoded.into_bytes())?
            .header("content-type", "application/x-www-form-urlencoded")
    }

    /// Append URL-encoded query fields without changing the approved origin.
    /// The encoded path and query together must fit the 8 KiB target allowance.
    /// Structs, maps, and sequences of pairs are supported.
    pub fn query<T: Serialize + ?Sized>(mut self, fields: &T) -> Result<Self, ClientError> {
        let query = self.url.query().filter(|query| !query.is_empty());
        let reserved = self.url.path().len() + 1 + query.map_or(0, |query| query.len() + 1);
        let encoded =
            encoding::form(fields, MAX_TARGET_BYTES.saturating_sub(reserved)).map_err(|error| {
                match error {
                    ClientError::RequestTooLarge => ClientError::Destination,
                    other => other,
                }
            })?;
        if encoded.is_empty() {
            return Ok(self);
        }
        let query = match query {
            Some(query) => format!("{query}&{encoded}"),
            None => encoded,
        };
        self.url.set_query(Some(&query));
        Ok(self)
    }

    /// Set a sensitive Authorization header for HTTP Basic authentication.
    pub fn basic_auth(self, username: &str, password: Option<&str>) -> Result<Self, ClientError> {
        let password = password.unwrap_or_default();
        let max_input = (MAX_HEADER_VALUE_BYTES - "Basic ".len()) / 4 * 3;
        if username
            .len()
            .saturating_add(password.len())
            .saturating_add(1)
            > max_input
            || username.contains(':')
            || username
                .bytes()
                .chain(password.bytes())
                .any(|byte| byte.is_ascii_control())
        {
            return Err(ClientError::Configuration);
        }
        let encoded = STANDARD.encode(format!("{username}:{password}"));
        self.header("authorization", &format!("Basic {encoded}"))
    }

    /// Set a sensitive Authorization header for bearer authentication.
    pub fn bearer_auth(self, token: &str) -> Result<Self, ClientError> {
        if token.is_empty() || token.len() > MAX_HEADER_VALUE_BYTES - "Bearer ".len() {
            return Err(ClientError::Configuration);
        }
        self.header("authorization", &format!("Bearer {token}"))
    }

    /// Send within the earlier of the inherited cutoff and configured total limit.
    /// Capacity wait and subsequent response consumption use this same cutoff.
    /// No automatic retry or redirect is performed; HTTP error statuses are returned
    /// as ordinary responses. A timeout does not prove a remote write did not commit.
    /// The client span and metrics begin when this future is first polled and remain
    /// owned by the returned body. Request construction errors are not attempts.
    pub async fn send(self, inherited: Instant) -> Result<Response, ClientError> {
        let span = tracing::info_span!("http.client", client = %self.inner.name,
            "http.request.method" = %self.method, "otel.kind" = "client",
            "http.response.status_code" = tracing::field::Empty,
            outcome = tracing::field::Empty, "error.type" = tracing::field::Empty, "otel.status_code" = tracing::field::Empty);
        let entered = span.clone();
        async move {
            let mut observed = Observation::new(self.inner.metrics.clone(), span.clone());
            let deadline = inherited.min(Instant::now() + self.inner.config.limits.total_timeout);
            let (lease, transport) = match self.inner.acquire(deadline).await {
                Ok(acquired) => { observed.acquired(); acquired }
                Err(error) => { observed.failed(error); return Err(error); }
            };
            let head = self.method == reqwest::Method::HEAD;
            let mut request = reqwest::Request::new(self.method, self.url);
            *request.headers_mut() = self.headers;
            #[cfg(feature = "otel")]
            if self.inner.config.trace_context {
                crate::telemetry::inject_trace_context(request.headers_mut());
            }
            if self.inner.config.gzip && !request.headers().contains_key("accept-encoding")
                && !request.headers().contains_key("range") {
                request.headers_mut().insert("accept-encoding", axum::http::HeaderValue::from_static("gzip"));
            }
            *request.body_mut() = self.body.map(Into::into);
            let result = tokio::select! {
                biased;
                () = self.inner.closed.cancelled() => Err(ClientError::Closed),
                result = timeout_at(deadline, transport.execute(request)) => {
                    if Instant::now() >= deadline { Err(ClientError::Deadline) }
                    else { result.map_err(|_| ClientError::Deadline).and_then(|result| result.map_err(ClientError::request_transport)) }
                }
            };
            match result {
                Ok(response) => {
                    observed.received(response.status().as_u16());
                    Response::new(response, lease, deadline, observed, head)
                }
                Err(error) => { observed.failed(error); Err(error) }
            }
        }.instrument(entered).await
    }
}