Skip to main content

basecamp_sdk/http/
mod.rs

1//! The HTTP layer the client sends on, and the seam for replacing it.
2//!
3//! Everything the SDK sends goes out through one [`HttpClient`]. The one it ships,
4//! [`ReqwestClient`], is what [`crate::ClientBuilder::build`] uses when nothing else is
5//! supplied; an application that already has an HTTP stack implements the trait and hands
6//! it to [`crate::ClientBuilder::http_client`].
7//!
8//! The request and response types are the `http` crate's, re-exported here so a caller
9//! needs no dependency of its own to name a [`Method`] or read a [`StatusCode`].
10
11use std::pin::Pin;
12
13use async_trait::async_trait;
14use bytes::{Bytes, BytesMut};
15use futures_util::{Stream, StreamExt, stream};
16
17use crate::error::Error;
18
19pub use ::http::header::{self, HeaderMap, HeaderName, HeaderValue};
20pub use ::http::{Method, Request, Response, StatusCode, Version};
21
22#[cfg(feature = "reqwest")]
23mod reqwest;
24#[cfg(feature = "reqwest")]
25#[cfg_attr(docsrs, doc(cfg(feature = "reqwest")))]
26pub use self::reqwest::ReqwestClient;
27
28/// Sends one HTTP request and answers with the response, its body still unread.
29///
30/// An implementation **must not follow redirects**: SPEC §13 has the SDK handle every
31/// redirect itself, so the download flow can read a `Location` and keep credentials on the
32/// API origin. Timeouts belong to the implementation, since the SDK cannot interrupt a
33/// transport it does not know; the operation deadline of
34/// [`crate::ClientBuilder::operation_deadline`] bounds the whole call from above.
35///
36/// A failure to get an answer at all — no connection, a timeout, a broken stream — is
37/// [`Error::network`]; a response with any status is `Ok`.
38#[async_trait]
39pub trait HttpClient: Send + Sync {
40    /// Sends the request.
41    async fn send(&self, request: Request<Bytes>) -> Result<Response<Body>, Error>;
42}
43
44#[async_trait]
45impl<H: HttpClient + ?Sized> HttpClient for std::sync::Arc<H> {
46    async fn send(&self, request: Request<Bytes>) -> Result<Response<Body>, Error> {
47        (**self).send(request).await
48    }
49}
50
51/// A response body as it arrives, read once.
52///
53/// An implementation builds one with [`Body::from_stream`], passing along the length the
54/// transport knows so a body declared past the caller's cap is refused before a byte of it
55/// is read. The SDK reads it with [`Body::chunk`] or [`Body::collect`].
56pub struct Body {
57    stream: Pin<Box<dyn Stream<Item = Result<Bytes, Error>> + Send>>,
58    content_length: Option<u64>,
59}
60
61impl Body {
62    /// A body over a stream of chunks.
63    pub fn from_stream(
64        stream: impl Stream<Item = Result<Bytes, Error>> + Send + 'static,
65        content_length: Option<u64>,
66    ) -> Body {
67        Body {
68            stream: Box::pin(stream),
69            content_length,
70        }
71    }
72
73    /// No body at all.
74    pub fn empty() -> Body {
75        Body::from(Bytes::new())
76    }
77
78    /// What the transport declared the body's length to be, when it declared one.
79    pub fn content_length(&self) -> Option<u64> {
80        self.content_length
81    }
82
83    /// The next piece of the body, or `None` once it has all arrived.
84    pub async fn chunk(&mut self) -> Result<Option<Bytes>, Error> {
85        self.stream.next().await.transpose()
86    }
87
88    /// Reads the body whole, up to `limit` bytes, and answers `too_large` on the first byte
89    /// past. A body exactly at the limit reads whole; one declared past it never starts.
90    pub async fn collect(
91        mut self,
92        limit: usize,
93        too_large: impl Fn() -> Error,
94    ) -> Result<Bytes, Error> {
95        if self
96            .content_length
97            .is_some_and(|length| length > limit as u64)
98        {
99            return Err(too_large());
100        }
101        let mut body = BytesMut::new();
102        while let Some(chunk) = self.chunk().await? {
103            if body.len() + chunk.len() > limit {
104                return Err(too_large());
105            }
106            body.extend_from_slice(&chunk);
107        }
108        Ok(body.freeze())
109    }
110}
111
112impl From<Bytes> for Body {
113    fn from(bytes: Bytes) -> Body {
114        let content_length = Some(bytes.len() as u64);
115        Body::from_stream(stream::once(async move { Ok(bytes) }), content_length)
116    }
117}
118
119impl From<Vec<u8>> for Body {
120    fn from(bytes: Vec<u8>) -> Body {
121        Body::from(Bytes::from(bytes))
122    }
123}
124
125impl From<&'static str> for Body {
126    fn from(text: &'static str) -> Body {
127        Body::from(Bytes::from_static(text.as_bytes()))
128    }
129}
130
131impl std::fmt::Debug for Body {
132    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133        f.debug_struct("Body")
134            .field("content_length", &self.content_length)
135            .finish_non_exhaustive()
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    fn too_large() -> Error {
144        Error::usage("too large")
145    }
146
147    #[tokio::test]
148    async fn collects_a_body_up_to_the_limit() {
149        let body = Body::from(Bytes::from_static(b"hello"));
150        assert_eq!(body.content_length(), Some(5));
151        assert_eq!(body.collect(5, too_large).await.unwrap(), "hello");
152    }
153
154    #[tokio::test]
155    async fn refuses_a_body_declared_past_the_limit_before_reading_it() {
156        let body = Body::from_stream(
157            stream::once(async { panic!("the body should never be read") }),
158            Some(6),
159        );
160        assert_eq!(
161            body.collect(5, too_large).await.unwrap_err().message(),
162            "too large"
163        );
164    }
165
166    #[tokio::test]
167    async fn refuses_an_undeclared_body_on_the_first_byte_past_the_limit() {
168        let chunks = stream::iter([
169            Ok(Bytes::from_static(b"hel")),
170            Ok(Bytes::from_static(b"lo!")),
171        ]);
172        let body = Body::from_stream(chunks, None);
173        assert_eq!(
174            body.collect(5, too_large).await.unwrap_err().message(),
175            "too large"
176        );
177    }
178}