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};
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + Sync + 'a>>;
pub trait Middleware: Send + Sync {
fn handle<'a>(
&'a self,
request: Request,
next: Next<'a>,
) -> BoxFuture<'a, Result<Response, BoxError>>;
}
#[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())
}
}
pub struct Request(pub(crate) http::Request<crate::api::upload::RequestBody>);
impl Request {
#[must_use]
pub fn method(&self) -> &http::Method {
self.0.method()
}
#[must_use]
pub fn uri(&self) -> &http::Uri {
self.0.uri()
}
#[must_use]
pub fn headers(&self) -> &http::HeaderMap {
self.0.headers()
}
pub fn headers_mut(&mut self) -> &mut http::HeaderMap {
self.0.headers_mut()
}
}
enum Body {
Upstream(Incoming),
Buffered(Bytes),
}
pub struct Response {
status: http::StatusCode,
headers: http::HeaderMap,
body: Body,
}
impl Response {
#[must_use]
pub fn buffered(status: http::StatusCode, headers: http::HeaderMap, body: Bytes) -> Self {
Self {
status,
headers,
body: Body::Buffered(body),
}
}
#[must_use]
pub fn status(&self) -> http::StatusCode {
self.status
}
#[must_use]
pub fn headers(&self) -> &http::HeaderMap {
&self.headers
}
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))
}
pub(crate) fn into_events(self) -> (Option<Incoming>, Bytes) {
match self.body {
Body::Upstream(body) => (Some(body), Bytes::new()),
Body::Buffered(bytes) => (None, bytes),
}
}
}
#[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 }
}
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),
})
}),
}
}
}