servlet 1.0.0

A small application runtime with an explicit operational contract
Documentation
//! A request receives one deadline before waiting for capacity.
use super::{ClientError, Response, observation::Observation, state::Inner};
use axum::http::HeaderMap;
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)
    }
    /// 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::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
    }
}