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};
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 let inner = path
37 .rewrite_uri(&mut req, scheme, authority)
38 .map(|()| client.request(req))
39 .map_err(Some);
40 Self { inner }
41 }
42}
43
44impl Future for RevProxyFuture {
45 type Output = Result<Result<Response<Incoming>, ProxyError>, Infallible>;
46
47 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
48 match self.inner {
49 Ok(ref mut fut) => match Future::poll(Pin::new(fut), cx) {
50 Poll::Ready(res) => Poll::Ready(Ok(res.map_err(ProxyError::RequestFailed))),
51 Poll::Pending => Poll::Pending,
52 },
53 Err(ref mut e) => match e.take() {
54 Some(e) => Poll::Ready(Ok(Err(ProxyError::InvalidUri(e)))),
55 None => unreachable!("RevProxyFuture::poll() is called after ready"),
56 },
57 }
58 }
59}