Skip to main content

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