Skip to main content

djs_rest/
transport.rs

1//! The HTTP transport under [`Rest`](crate::Rest) (D-396, D-404): what sends a request and
2//! waits.
3//!
4//! [`Rest`](crate::Rest) builds every request (route, headers, body, rate limits, retries)
5//! and hands it to a [`Transport`] to send. With the default `hyper` feature the transport is
6//! hyper with rustls, so nothing needs to be set. Elsewhere — on `wasm32-unknown-unknown`,
7//! such as Cloudflare Workers, which send HTTP with the platform's `fetch` — implement
8//! [`Transport`] and pass it to [`RestBuilder::transport`](crate::RestBuilder::transport).
9//!
10//! discord.js counterpart: the `makeRequest` option of `RESTOptions` (`@discordjs/rest`),
11//! which replaces `undici`'s `request`.
12
13use core::{fmt, future::Future, pin::Pin, time::Duration};
14use std::error::Error;
15
16use bytes::Bytes;
17
18// `std::time` has no clock on `wasm32-unknown-unknown`; `web-time` reads the JS host's (D-397).
19// Natively tokio's `Instant`, which tests can pause.
20#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
21pub(crate) use tokio::time::Instant;
22#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
23pub(crate) use web_time::Instant;
24
25/// A boxed, `Send` future: what the [`Transport`] methods return.
26pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
27
28/// Sends HTTP requests and waits for [`Rest`](crate::Rest) (D-404).
29///
30/// [`send`](Self::send) performs one request; [`Rest`](crate::Rest) does everything around
31/// it (authentication, rate limits, retries) and gives up on it after its
32/// [timeout](crate::RestBuilder::timeout), which it measures with [`sleep`](Self::sleep), as
33/// it does every rate-limit and retry wait. Both futures must be `Send`: on a
34/// single-threaded target whose futures are not (Cloudflare Workers' `fetch`), wrap them
35/// (for example in `worker::send::SendFuture`).
36///
37/// discord.js counterpart: the `makeRequest` option of `RESTOptions` (`@discordjs/rest`).
38///
39/// # Examples
40///
41/// A transport that answers every request with `204 No Content` (useful in tests):
42///
43/// ```
44/// use std::time::Duration;
45///
46/// use bytes::Bytes;
47/// use djs_rest::{Body, BoxFuture, Rest, Transport};
48///
49/// struct NoContent;
50///
51/// impl Transport for NoContent {
52///     fn send(
53///         &self,
54///         _request: http::Request<Body>,
55///     ) -> BoxFuture<'_, Result<http::Response<Bytes>, Box<dyn std::error::Error + Send + Sync>>>
56///     {
57///         Box::pin(async {
58///             Ok(http::Response::builder().status(204).body(Bytes::new())?)
59///         })
60///     }
61///
62///     fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()> {
63///         Box::pin(tokio::time::sleep(duration))
64///     }
65/// }
66///
67/// let rest = Rest::builder().token("my-token").transport(NoContent).build();
68/// # let _ = rest;
69/// ```
70pub trait Transport: Send + Sync + 'static {
71    /// Sends `request` and returns its response, with the whole body. A failure to get a
72    /// response (connection, TLS, …) is an error, which [`Rest`](crate::Rest) retries like a
73    /// server error; any HTTP status is a response.
74    ///
75    /// The request has its method, absolute URI, headers (with `Content-Type` when there is a
76    /// body) and [`Body`]; `Content-Length` is [`Body::len`].
77    ///
78    /// discord.js counterpart: `makeRequest`.
79    fn send(
80        &self,
81        request: http::Request<Body>,
82    ) -> BoxFuture<'_, Result<http::Response<Bytes>, Box<dyn Error + Send + Sync>>>;
83
84    /// Waits for `duration`: rate limits, retries and the request timeout.
85    ///
86    /// discord.js counterpart: none (Node's timers).
87    fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()>;
88}
89
90/// The body of a request a [`Transport`] sends: a sequence of byte chunks.
91///
92/// A JSON body is one chunk; a `multipart/form-data` body is its part headers and each file's
93/// data as is, so files are not copied to send them (D-087). Cloning is cheap (the chunks are
94/// reference counted).
95///
96/// discord.js counterpart: the `body` of `RequestInit` (`undici`).
97#[derive(Clone, Default, PartialEq, Eq)]
98pub struct Body {
99    chunks: Vec<Bytes>,
100}
101
102impl Body {
103    pub(crate) const fn new(chunks: Vec<Bytes>) -> Self {
104        Self { chunks }
105    }
106
107    /// Returns the chunks, in order (some may be empty).
108    #[must_use]
109    pub fn chunks(&self) -> &[Bytes] {
110        &self.chunks
111    }
112
113    /// Returns the length of the whole body, in bytes.
114    #[must_use]
115    pub fn len(&self) -> usize {
116        self.chunks.iter().map(Bytes::len).sum()
117    }
118
119    /// Returns whether the body is empty (a request without a body).
120    #[must_use]
121    pub fn is_empty(&self) -> bool {
122        self.chunks.iter().all(Bytes::is_empty)
123    }
124
125    /// Returns the whole body as one buffer: the chunk itself if there is one, else a copy
126    /// of them all.
127    #[must_use]
128    pub fn into_bytes(mut self) -> Bytes {
129        match self.chunks.len() {
130            0 => Bytes::new(),
131            1 => self.chunks.swap_remove(0),
132            _ => self.chunks.concat().into(),
133        }
134    }
135}
136
137impl fmt::Debug for Body {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        f.debug_struct("Body")
140            .field("chunks", &self.chunks.len())
141            .field("len", &self.len())
142            .finish()
143    }
144}
145
146/// Waits with `transport` until `deadline`, if it is ahead.
147pub(crate) async fn sleep_until(transport: &dyn Transport, deadline: Instant) {
148    let now = Instant::now();
149    if deadline > now {
150        transport.sleep(deadline - now).await;
151    }
152}
153
154/// The default transport: hyper with rustls (the `hyper` feature, D-405).
155#[cfg(feature = "hyper")]
156pub(crate) mod hyper {
157    use core::{
158        convert::Infallible,
159        pin::Pin,
160        task::{Context, Poll},
161        time::Duration,
162    };
163    use std::error::Error;
164
165    use bytes::Bytes;
166    use http_body_util::BodyExt;
167    use hyper::body::{Frame, SizeHint};
168    use hyper_rustls::HttpsConnector;
169    use hyper_util::{
170        client::legacy::{Client, connect::HttpConnector},
171        rt::{TokioExecutor, TokioTimer},
172    };
173
174    use super::{Body, BoxFuture, Transport};
175
176    /// hyper's pooled client over HTTPS (HTTP/2 or HTTP/1.1) or plain HTTP.
177    pub(crate) struct HyperTransport {
178        client: Client<HttpsConnector<HttpConnector>, HyperBody>,
179    }
180
181    impl HyperTransport {
182        pub(crate) fn new() -> Self {
183            let connector = hyper_rustls::HttpsConnectorBuilder::new()
184                .with_tls_config(crate::tls::client_config())
185                .https_or_http()
186                .enable_all_versions()
187                .build();
188            let client = Client::builder(TokioExecutor::new())
189                .timer(TokioTimer::new())
190                .pool_timer(TokioTimer::new())
191                .build(connector);
192            Self { client }
193        }
194    }
195
196    impl Transport for HyperTransport {
197        fn send(
198            &self,
199            request: http::Request<Body>,
200        ) -> BoxFuture<'_, Result<http::Response<Bytes>, Box<dyn Error + Send + Sync>>> {
201            let response = self.client.request(request.map(HyperBody::from));
202            Box::pin(async move {
203                let (parts, body) = response.await?.into_parts();
204                let body = body.collect().await?.to_bytes();
205                Ok(http::Response::from_parts(parts, body))
206            })
207        }
208
209        fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()> {
210            Box::pin(tokio::time::sleep(duration))
211        }
212    }
213
214    /// A [`Body`] for hyper: its chunks of known total length (so `Content-Length` is set).
215    #[derive(Debug)]
216    pub(crate) struct HyperBody {
217        chunks: std::vec::IntoIter<Bytes>,
218        remaining: u64,
219    }
220
221    impl From<Body> for HyperBody {
222        fn from(body: Body) -> Self {
223            Self {
224                remaining: body.len() as u64,
225                chunks: body.chunks.into_iter(),
226            }
227        }
228    }
229
230    impl hyper::body::Body for HyperBody {
231        type Data = Bytes;
232        type Error = Infallible;
233
234        fn poll_frame(
235            self: Pin<&mut Self>,
236            _cx: &mut Context<'_>,
237        ) -> Poll<Option<Result<Frame<Bytes>, Infallible>>> {
238            let this = self.get_mut();
239            let next = this.chunks.by_ref().find(|chunk| !chunk.is_empty());
240            if let Some(chunk) = &next {
241                this.remaining -= chunk.len() as u64;
242            }
243            Poll::Ready(next.map(|chunk| Ok(Frame::data(chunk))))
244        }
245
246        fn is_end_stream(&self) -> bool {
247            self.remaining == 0
248        }
249
250        fn size_hint(&self) -> SizeHint {
251            SizeHint::with_exact(self.remaining)
252        }
253    }
254
255    #[cfg(test)]
256    mod tests {
257        use hyper::body::Body as _;
258
259        use super::*;
260
261        #[tokio::test]
262        async fn sends_every_non_empty_chunk_with_the_exact_length() {
263            let body = Body::new(vec![
264                Bytes::from_static(b"ab"),
265                Bytes::new(),
266                Bytes::from_static(b"c"),
267            ]);
268            let mut body = HyperBody::from(body);
269            assert_eq!(body.size_hint().exact(), Some(3));
270            let mut frames = Vec::new();
271            while let Some(frame) = body.frame().await {
272                frames.push(frame.unwrap().into_data().unwrap());
273            }
274            assert_eq!(frames, [&b"ab"[..], b"c"]);
275            assert!(body.is_end_stream());
276        }
277    }
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283
284    #[test]
285    fn a_body_joins_its_chunks_only_when_needed() {
286        let one = Bytes::from_static(b"{}");
287        let body = Body::new(vec![one.clone()]);
288        assert_eq!(body.len(), 2);
289        assert!(!body.is_empty());
290        // One chunk is returned as is, without a copy.
291        assert_eq!(body.into_bytes().as_ptr(), one.as_ptr());
292
293        let body = Body::new(vec![
294            Bytes::from_static(b"ab"),
295            Bytes::new(),
296            Bytes::from_static(b"c"),
297        ]);
298        assert_eq!(body.chunks().len(), 3);
299        assert_eq!(body.len(), 3);
300        assert_eq!(body.into_bytes(), "abc");
301        assert!(Body::default().is_empty());
302        assert!(Body::new(vec![Bytes::new()]).is_empty());
303        assert_eq!(Body::default().into_bytes(), "");
304    }
305}