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,
}
#[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,
},
}
}
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()
}
}
#[derive(Clone, Debug)]
pub struct ApiResponse<T> {
status: StatusCode,
headers: HeaderMap,
data: T,
}
impl<T> ApiResponse<T> {
#[must_use]
pub fn status(&self) -> StatusCode {
self.status
}
#[must_use]
pub fn headers(&self) -> &HeaderMap {
&self.headers
}
#[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())
}
#[must_use]
pub fn data(&self) -> &T {
&self.data
}
#[must_use]
pub fn into_data(self) -> T {
self.data
}
#[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),
}
}
}