awc/
sender.rs

1use std::{
2    future::Future,
3    net,
4    pin::Pin,
5    rc::Rc,
6    task::{Context, Poll},
7    time::Duration,
8};
9
10use actix_http::{
11    body::{BodyStream, MessageBody},
12    error::HttpError,
13    header::{self, HeaderMap, HeaderName, TryIntoHeaderValue},
14    RequestHead, RequestHeadType,
15};
16use actix_rt::time::{sleep, Sleep};
17use bytes::Bytes;
18use derive_more::From;
19use futures_core::Stream;
20use serde::Serialize;
21
22#[cfg(feature = "__compress")]
23use actix_http::{encoding::Decoder, header::ContentEncoding, Payload};
24
25use crate::{
26    any_body::AnyBody,
27    client::ClientConfig,
28    error::{FreezeRequestError, InvalidUrl, SendRequestError},
29    BoxError, ClientResponse, ConnectRequest, ConnectResponse,
30};
31
32#[derive(Debug, From)]
33pub(crate) enum PrepForSendingError {
34    Url(InvalidUrl),
35    Http(HttpError),
36    Json(serde_json::Error),
37    Form(serde_urlencoded::ser::Error),
38}
39
40impl From<PrepForSendingError> for FreezeRequestError {
41    fn from(err: PrepForSendingError) -> FreezeRequestError {
42        match err {
43            PrepForSendingError::Url(err) => FreezeRequestError::Url(err),
44            PrepForSendingError::Http(err) => FreezeRequestError::Http(err),
45            PrepForSendingError::Json(err) => {
46                FreezeRequestError::Custom(Box::new(err), Box::new("json serialization error"))
47            }
48            PrepForSendingError::Form(err) => {
49                FreezeRequestError::Custom(Box::new(err), Box::new("form serialization error"))
50            }
51        }
52    }
53}
54
55impl From<PrepForSendingError> for SendRequestError {
56    fn from(err: PrepForSendingError) -> SendRequestError {
57        match err {
58            PrepForSendingError::Url(e) => SendRequestError::Url(e),
59            PrepForSendingError::Http(e) => SendRequestError::Http(e),
60            PrepForSendingError::Json(err) => {
61                SendRequestError::Custom(Box::new(err), Box::new("json serialization error"))
62            }
63            PrepForSendingError::Form(err) => {
64                SendRequestError::Custom(Box::new(err), Box::new("form serialization error"))
65            }
66        }
67    }
68}
69
70/// Future that sends request's payload and resolves to a server response.
71#[must_use = "futures do nothing unless polled"]
72pub enum SendClientRequest {
73    Fut(
74        Pin<Box<dyn Future<Output = Result<ConnectResponse, SendRequestError>>>>,
75        // FIXME: use a pinned Sleep instead of box.
76        Option<Pin<Box<Sleep>>>,
77        bool,
78    ),
79    Err(Option<SendRequestError>),
80}
81
82impl SendClientRequest {
83    pub(crate) fn new(
84        send: Pin<Box<dyn Future<Output = Result<ConnectResponse, SendRequestError>>>>,
85        response_decompress: bool,
86        timeout: Option<Duration>,
87    ) -> SendClientRequest {
88        let delay = timeout.map(|d| Box::pin(sleep(d)));
89        SendClientRequest::Fut(send, delay, response_decompress)
90    }
91}
92
93#[cfg(feature = "__compress")]
94impl Future for SendClientRequest {
95    type Output = Result<ClientResponse<Decoder<Payload>>, SendRequestError>;
96
97    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
98        let this = self.get_mut();
99
100        match this {
101            SendClientRequest::Fut(send, delay, response_decompress) => {
102                if let Some(delay) = delay {
103                    if delay.as_mut().poll(cx).is_ready() {
104                        return Poll::Ready(Err(SendRequestError::Timeout));
105                    }
106                }
107
108                let res = futures_core::ready!(send.as_mut().poll(cx)).map(|res| {
109                    res.into_client_response()._timeout(delay.take()).map_body(
110                        |head, payload| {
111                            if *response_decompress {
112                                Payload::Stream {
113                                    payload: Decoder::from_headers(payload, &head.headers),
114                                }
115                            } else {
116                                Payload::Stream {
117                                    payload: Decoder::new(payload, ContentEncoding::Identity),
118                                }
119                            }
120                        },
121                    )
122                });
123
124                Poll::Ready(res)
125            }
126            SendClientRequest::Err(ref mut e) => match e.take() {
127                Some(e) => Poll::Ready(Err(e)),
128                None => panic!("Attempting to call completed future"),
129            },
130        }
131    }
132}
133
134#[cfg(not(feature = "__compress"))]
135impl Future for SendClientRequest {
136    type Output = Result<ClientResponse, SendRequestError>;
137
138    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
139        let this = self.get_mut();
140        match this {
141            SendClientRequest::Fut(send, delay, _) => {
142                if let Some(delay) = delay {
143                    if delay.as_mut().poll(cx).is_ready() {
144                        return Poll::Ready(Err(SendRequestError::Timeout));
145                    }
146                }
147                send.as_mut()
148                    .poll(cx)
149                    .map_ok(|res| res.into_client_response()._timeout(delay.take()))
150            }
151            SendClientRequest::Err(ref mut e) => match e.take() {
152                Some(e) => Poll::Ready(Err(e)),
153                None => panic!("Attempting to call completed future"),
154            },
155        }
156    }
157}
158
159impl From<SendRequestError> for SendClientRequest {
160    fn from(e: SendRequestError) -> Self {
161        SendClientRequest::Err(Some(e))
162    }
163}
164
165impl From<HttpError> for SendClientRequest {
166    fn from(e: HttpError) -> Self {
167        SendClientRequest::Err(Some(e.into()))
168    }
169}
170
171impl From<PrepForSendingError> for SendClientRequest {
172    fn from(e: PrepForSendingError) -> Self {
173        SendClientRequest::Err(Some(e.into()))
174    }
175}
176
177#[derive(Debug)]
178pub(crate) enum RequestSender {
179    Owned(RequestHead),
180    Rc(Rc<RequestHead>, Option<HeaderMap>),
181}
182
183impl RequestSender {
184    pub(crate) fn send_body(
185        self,
186        addr: Option<net::SocketAddr>,
187        response_decompress: bool,
188        timeout: Option<Duration>,
189        config: &ClientConfig,
190        body: impl MessageBody + 'static,
191    ) -> SendClientRequest {
192        let req = match self {
193            RequestSender::Owned(head) => ConnectRequest::Client(
194                RequestHeadType::Owned(head),
195                AnyBody::from_message_body(body).into_boxed(),
196                addr,
197            ),
198            RequestSender::Rc(head, extra_headers) => ConnectRequest::Client(
199                RequestHeadType::Rc(head, extra_headers),
200                AnyBody::from_message_body(body).into_boxed(),
201                addr,
202            ),
203        };
204
205        let fut = config.connector.call(req);
206
207        SendClientRequest::new(fut, response_decompress, timeout.or(config.timeout))
208    }
209
210    pub(crate) fn send_json(
211        mut self,
212        addr: Option<net::SocketAddr>,
213        response_decompress: bool,
214        timeout: Option<Duration>,
215        config: &ClientConfig,
216        value: impl Serialize,
217    ) -> SendClientRequest {
218        let body = match serde_json::to_string(&value) {
219            Ok(body) => body,
220            Err(err) => return PrepForSendingError::Json(err).into(),
221        };
222
223        if let Err(e) = self.set_header_if_none(header::CONTENT_TYPE, "application/json") {
224            return e.into();
225        }
226
227        self.send_body(addr, response_decompress, timeout, config, body)
228    }
229
230    pub(crate) fn send_form(
231        mut self,
232        addr: Option<net::SocketAddr>,
233        response_decompress: bool,
234        timeout: Option<Duration>,
235        config: &ClientConfig,
236        value: impl Serialize,
237    ) -> SendClientRequest {
238        let body = match serde_urlencoded::to_string(value) {
239            Ok(body) => body,
240            Err(err) => return PrepForSendingError::Form(err).into(),
241        };
242
243        // set content-type
244        if let Err(err) =
245            self.set_header_if_none(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
246        {
247            return err.into();
248        }
249
250        self.send_body(addr, response_decompress, timeout, config, body)
251    }
252
253    pub(crate) fn send_stream<S, E>(
254        self,
255        addr: Option<net::SocketAddr>,
256        response_decompress: bool,
257        timeout: Option<Duration>,
258        config: &ClientConfig,
259        stream: S,
260    ) -> SendClientRequest
261    where
262        S: Stream<Item = Result<Bytes, E>> + 'static,
263        E: Into<BoxError> + 'static,
264    {
265        self.send_body(
266            addr,
267            response_decompress,
268            timeout,
269            config,
270            BodyStream::new(stream),
271        )
272    }
273
274    pub(crate) fn send(
275        self,
276        addr: Option<net::SocketAddr>,
277        response_decompress: bool,
278        timeout: Option<Duration>,
279        config: &ClientConfig,
280    ) -> SendClientRequest {
281        self.send_body(addr, response_decompress, timeout, config, ())
282    }
283
284    fn set_header_if_none<V>(&mut self, key: HeaderName, value: V) -> Result<(), HttpError>
285    where
286        V: TryIntoHeaderValue,
287    {
288        match self {
289            RequestSender::Owned(head) => {
290                if !head.headers.contains_key(&key) {
291                    match value.try_into_value() {
292                        Ok(value) => {
293                            head.headers.insert(key, value);
294                        }
295                        Err(e) => return Err(e.into()),
296                    }
297                }
298            }
299            RequestSender::Rc(head, extra_headers) => {
300                if !head.headers.contains_key(&key)
301                    && !extra_headers.iter().any(|h| h.contains_key(&key))
302                {
303                    match value.try_into_value() {
304                        Ok(v) => {
305                            let h = extra_headers.get_or_insert(HeaderMap::new());
306                            h.insert(key, v)
307                        }
308                        Err(e) => return Err(e.into()),
309                    };
310                }
311            }
312        }
313
314        Ok(())
315    }
316}