Skip to main content

tower_proxy/
future.rs

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