meteroid-rs 0.31.4

Official Rust SDK for Meteroid, the open-source billing platform: subscriptions, invoicing, usage-based billing and webhooks.
Documentation
// this file is @generated by Perseid; edit the shared runtime template.
//! Request middleware: wraps every HTTP attempt to log, cache, sign or rewrite it.
use crate::connector::HttpClient;
use bytes::Bytes;
use http_body_util::BodyExt as _;
use hyper::body::Incoming;
use std::{fmt, future::Future, pin::Pin, sync::Arc};

/// Any error, as middleware and HTTP clients return them.
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
/// A boxed future, as middleware and HTTP clients return them.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + Sync + 'a>>;

/// Wraps each HTTP attempt, inside the retry loop. The first middleware registered is the
/// outermost. Call `next.run(request)` to continue, or return a response of your own.
pub trait Middleware: Send + Sync {
    /// Handles one attempt: `next.run(request)` sends it on.
    fn handle<'a>(
        &'a self,
        request: Request,
        next: Next<'a>,
    ) -> BoxFuture<'a, Result<Response, BoxError>>;
}

/// The middleware registered on a client, in order.
#[derive(Clone, Default)]
pub(crate) struct Middlewares(pub(crate) Vec<Arc<dyn Middleware>>);

impl Middlewares {
    pub(crate) fn push(&mut self, middleware: impl Middleware + 'static) {
        self.0.push(Arc::new(middleware));
    }
}

impl fmt::Debug for Middlewares {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Middlewares({})", self.0.len())
    }
}

/// An outgoing request. The body is not exposed.
pub struct Request(pub(crate) http::Request<crate::api::upload::RequestBody>);

impl Request {
    /// The HTTP method.
    #[must_use]
    pub fn method(&self) -> &http::Method {
        self.0.method()
    }
    /// The full URL, query included.
    #[must_use]
    pub fn uri(&self) -> &http::Uri {
        self.0.uri()
    }
    /// The headers, credentials included.
    #[must_use]
    pub fn headers(&self) -> &http::HeaderMap {
        self.0.headers()
    }

    /// The headers, to change before sending the request on.
    pub fn headers_mut(&mut self) -> &mut http::HeaderMap {
        self.0.headers_mut()
    }
}

enum Body {
    Upstream(Incoming),
    Buffered(Bytes),
}

/// A response from the server, or a buffered one built by a middleware.
pub struct Response {
    status: http::StatusCode,
    headers: http::HeaderMap,
    body: Body,
}

impl Response {
    /// A response served without contacting the server, e.g. from a cache. Only 2xx statuses
    /// keep their typed API error handling; pass other upstream responses through untouched.
    #[must_use]
    pub fn buffered(status: http::StatusCode, headers: http::HeaderMap, body: Bytes) -> Self {
        Self {
            status,
            headers,
            body: Body::Buffered(body),
        }
    }

    /// The HTTP status.
    #[must_use]
    pub fn status(&self) -> http::StatusCode {
        self.status
    }

    /// The response headers.
    #[must_use]
    pub fn headers(&self) -> &http::HeaderMap {
        &self.headers
    }

    /// Reads the whole body, e.g. to store it. Rebuild the response with [`Response::buffered`]
    /// to hand it back to the client.
    ///
    /// # Errors
    ///
    /// Fails when reading the body from the server does.
    pub async fn into_parts(self) -> Result<(http::StatusCode, http::HeaderMap, Bytes), BoxError> {
        let bytes = match self.body {
            Body::Buffered(bytes) => bytes,
            Body::Upstream(body) => body.collect().await?.to_bytes(),
        };
        Ok((self.status, self.headers, bytes))
    }

    /// The body left open from the server, or the bytes a middleware buffered.
    pub(crate) fn into_events(self) -> (Option<Incoming>, Bytes) {
        match self.body {
            Body::Upstream(body) => (Some(body), Bytes::new()),
            Body::Buffered(bytes) => (None, bytes),
        }
    }
}

/// The rest of the middleware chain, ending with the HTTP client.
#[derive(Clone, Copy)]
pub struct Next<'a> {
    middleware: &'a [Arc<dyn Middleware>],
    client: &'a dyn HttpClient,
}

impl<'a> Next<'a> {
    pub(crate) fn new(middleware: &'a [Arc<dyn Middleware>], client: &'a dyn HttpClient) -> Self {
        Self { middleware, client }
    }

    /// Sends `request` to the next middleware, or to the server after the last one.
    pub fn run(self, request: Request) -> BoxFuture<'a, Result<Response, BoxError>> {
        match self.middleware.split_first() {
            Some((first, rest)) => first.handle(
                request,
                Next {
                    middleware: rest,
                    client: self.client,
                },
            ),
            None => Box::pin(async move {
                let response = self.client.send(request.0).await?;
                let (parts, body) = response.into_parts();
                Ok(Response {
                    status: parts.status,
                    headers: parts.headers,
                    body: Body::Upstream(body),
                })
            }),
        }
    }
}