use std::convert::Infallible;
use std::future::Future;
use std::net::{IpAddr, SocketAddr};
use std::pin::Pin;
use http::request::Parts;
use http::{Request, Response};
use hyper::body::Incoming;
use serde::Serialize;
use fetchlet::AppHandle;
use crate::{Error, FetchletService};
type ResponseFuture =
Pin<Box<dyn Future<Output = Result<Response<fetchlet::Body>, Infallible>> + Send>>;
#[derive(Clone, Copy, Debug)]
pub struct PeerAddr(pub SocketAddr);
pub fn peer_addr(parts: &Parts) -> Option<IpAddr> {
parts
.extensions
.get::<PeerAddr>()
.map(|PeerAddr(address)| address.ip())
}
#[derive(Clone)]
pub struct HyperService {
inner: FetchletService,
}
impl HyperService {
pub fn new(app: AppHandle, public_origin: &str) -> Result<Self, Error> {
let inner = FetchletService::new(app, public_origin)?.client_address(peer_addr);
Ok(Self { inner })
}
pub fn connection(&self, peer: SocketAddr) -> HyperConnection {
HyperConnection {
inner: self.inner.clone(),
peer: Some(PeerAddr(peer)),
}
}
pub fn context<C, F>(self, context: F) -> Self
where
C: Serialize,
F: Fn(&Parts) -> C + Send + Sync + 'static,
{
self.map(|inner| inner.context(context))
}
pub fn trusted_context(
self,
context: impl Fn(&Parts) -> fetchlet::Context + Send + Sync + 'static,
) -> Self {
self.map(|inner| inner.trusted_context(context))
}
pub fn on_error(self, callback: impl Fn(&Error) + Send + Sync + 'static) -> Self {
self.map(|inner| inner.on_error(callback))
}
pub fn stream_request_bodies(self) -> Self {
self.map(FetchletService::stream_request_bodies)
}
pub fn into_inner(self) -> FetchletService {
self.inner
}
fn map(self, change: impl FnOnce(FetchletService) -> FetchletService) -> Self {
Self {
inner: change(self.inner),
}
}
}
impl hyper::service::Service<Request<Incoming>> for HyperService {
type Response = Response<fetchlet::Body>;
type Error = Infallible;
type Future = ResponseFuture;
fn call(&self, request: Request<Incoming>) -> Self::Future {
respond(self.inner.clone(), request)
}
}
#[derive(Clone)]
pub struct HyperConnection {
inner: FetchletService,
peer: Option<PeerAddr>,
}
impl hyper::service::Service<Request<Incoming>> for HyperConnection {
type Response = Response<fetchlet::Body>;
type Error = Infallible;
type Future = ResponseFuture;
fn call(&self, mut request: Request<Incoming>) -> Self::Future {
if let Some(peer) = self.peer {
request.extensions_mut().insert(peer);
}
respond(self.inner.clone(), request)
}
}
fn respond(service: FetchletService, request: Request<Incoming>) -> ResponseFuture {
Box::pin(async move {
Ok(match service.fetch(request).await {
Ok(response) => response,
Err(error) => service.error_response(&error),
})
})
}