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.
//! API calls: requests sent when awaited, with access to the raw response.
use std::{
    fmt,
    future::Future,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
};

use http::{HeaderMap, StatusCode};

use crate::{
    error::Error,
    request::{Request, ResponseBody},
    Configuration,
};

pub(crate) type Decode<T> = fn(ResponseBody) -> Result<T, Error>;
type Sending<T> = Pin<Box<dyn Future<Output = Result<ApiResponse<T>, Error>> + Send + Sync>>;

enum State<T> {
    Ready {
        request: Box<Request>,
        cfg: Arc<Configuration>,
        decode: Decode<T>,
        stream: bool,
    },
    Sending(Sending<T>),
    Done,
}

/// One API request, sent when awaited: `client.items().list(None).await?`.
///
/// It is a `Future` of the decoded body, and [`with_response`](Self::with_response) also gives
/// the status and headers.
#[must_use = "a call does nothing until it is awaited"]
pub struct Call<T> {
    state: State<T>,
}

impl<T: Send + 'static> Call<T> {
    pub(crate) fn new(
        request: Request,
        cfg: Arc<Configuration>,
        decode: Decode<T>,
        stream: bool,
    ) -> Self {
        let request = Box::new(request);
        Self {
            state: State::Ready {
                request,
                cfg,
                decode,
                stream,
            },
        }
    }

    /// Sends the request, resolving to the status and headers of the response along with
    /// its decoded body.
    ///
    /// # Errors
    ///
    /// Fails like awaiting the call does.
    pub async fn with_response(mut self) -> Result<ApiResponse<T>, Error> {
        std::future::poll_fn(|cx| self.poll_response(cx)).await
    }

    fn poll_response(&mut self, cx: &mut Context<'_>) -> Poll<Result<ApiResponse<T>, Error>> {
        self.state = match std::mem::replace(&mut self.state, State::Done) {
            State::Ready {
                request,
                cfg,
                decode,
                stream,
            } => State::Sending(Box::pin(async move {
                let response = request.send(&cfg, stream).await?;
                Ok(ApiResponse {
                    status: response.status,
                    headers: response.headers,
                    data: decode(response.body)?,
                })
            })),
            state => state,
        };
        let State::Sending(sending) = &mut self.state else {
            panic!("`Call` polled after completion");
        };
        let result = std::task::ready!(sending.as_mut().poll(cx));
        self.state = State::Done;
        Poll::Ready(result)
    }
}

impl<T: Send + 'static> Future for Call<T> {
    type Output = Result<T, Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut()
            .poll_response(cx)
            .map_ok(ApiResponse::into_data)
    }
}

impl<T> fmt::Debug for Call<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Call").finish_non_exhaustive()
    }
}

/// A successful response: its status, headers and decoded body.
#[derive(Clone, Debug)]
pub struct ApiResponse<T> {
    status: StatusCode,
    headers: HeaderMap,
    data: T,
}

impl<T> ApiResponse<T> {
    /// The HTTP status.
    #[must_use]
    pub fn status(&self) -> StatusCode {
        self.status
    }

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

    /// The `x-request-id` (or `request-id`) header, to quote when reporting an issue.
    #[must_use]
    pub fn request_id(&self) -> Option<&str> {
        ["x-request-id", "request-id"]
            .iter()
            .find_map(|name| self.headers.get(*name)?.to_str().ok())
    }

    /// The decoded body.
    #[must_use]
    pub fn data(&self) -> &T {
        &self.data
    }

    /// The decoded body, dropping the status and headers.
    #[must_use]
    pub fn into_data(self) -> T {
        self.data
    }

    /// The status, headers and decoded body.
    #[must_use]
    pub fn into_parts(self) -> (StatusCode, HeaderMap, T) {
        (self.status, self.headers, self.data)
    }

    pub(crate) fn map<U>(self, f: impl FnOnce(T) -> U) -> ApiResponse<U> {
        ApiResponse {
            status: self.status,
            headers: self.headers,
            data: f(self.data),
        }
    }
}