reverse_proxy_service/
future.rs

1use crate::rewrite::PathRewriter;
2use crate::Error;
3
4use http::uri::{Authority, Scheme};
5use http::Error as HttpError;
6use http::{Request, Response};
7
8use hyper::body::{Body, HttpBody};
9use hyper::client::{connect::Connect, Client, ResponseFuture};
10
11use std::convert::Infallible;
12use std::future::Future;
13use std::pin::Pin;
14use std::task::{Context, Poll};
15
16type BoxErr = Box<dyn std::error::Error + Send + Sync>;
17
18pub struct RevProxyFuture {
19    inner: Result<ResponseFuture, Option<HttpError>>,
20}
21
22impl RevProxyFuture {
23    pub(crate) fn new<C, B, Pr>(
24        client: &Client<C, B>,
25        mut req: Request<B>,
26        scheme: &Scheme,
27        authority: &Authority,
28        path: &mut Pr,
29    ) -> Self
30    where
31        C: Connect + Clone + Send + Sync + 'static,
32        B: HttpBody + Send + 'static,
33        B::Data: Send,
34        B::Error: Into<BoxErr>,
35        Pr: PathRewriter,
36    {
37        let inner = path
38            .rewrite_uri(&mut req, scheme, authority)
39            .map(|_| client.request(req))
40            .map_err(Some);
41        Self { inner }
42    }
43}
44
45impl Future for RevProxyFuture {
46    type Output = Result<Result<Response<Body>, Error>, Infallible>;
47
48    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
49        match &mut self.inner {
50            Ok(fut) => match Future::poll(Pin::new(fut), cx) {
51                Poll::Ready(res) => Poll::Ready(Ok(res.map_err(Error::RequestFailed))),
52                Poll::Pending => Poll::Pending,
53            },
54            Err(e) => match e.take() {
55                Some(e) => Poll::Ready(Ok(Err(Error::InvalidUri(e)))),
56                None => unreachable!("RevProxyFuture::poll() is called after ready"),
57            },
58        }
59    }
60}