Skip to main content

basecamp_sdk/http/
reqwest.rs

1use std::time::Duration;
2
3use async_trait::async_trait;
4use bytes::Bytes;
5use futures_util::stream;
6use reqwest::redirect::Policy;
7
8use crate::config::DEFAULT_TIMEOUT;
9use crate::error::Error;
10use crate::http::{Body, HttpClient, Request, Response};
11
12/// The [`HttpClient`] the SDK ships, over [`reqwest`]. This is what a client gets when
13/// nothing else is supplied.
14///
15/// It never follows a redirect, whatever it was built from: the SDK does that itself.
16#[derive(Debug, Clone)]
17pub struct ReqwestClient {
18    http: reqwest::Client,
19}
20
21impl ReqwestClient {
22    /// A client with the SDK's default per-attempt timeout.
23    pub fn new() -> Result<ReqwestClient, Error> {
24        ReqwestClient::with_timeout(DEFAULT_TIMEOUT)
25    }
26
27    /// A client that gives an answer `timeout` to arrive.
28    pub fn with_timeout(timeout: Duration) -> Result<ReqwestClient, Error> {
29        ReqwestClient::from_builder(reqwest::Client::builder().timeout(timeout))
30    }
31
32    /// A client built from settings of the caller's own — a proxy, a root certificate, a
33    /// timeout. Two settings the builder carries are replaced, because each would act
34    /// beneath the SDK where it cannot see: redirects are never followed (the SDK follows
35    /// its own) and reqwest's own retries are off (SPEC §7's attempt budget counts every
36    /// request).
37    ///
38    /// Default headers are the caller's and cannot be taken back: reqwest adds them to
39    /// every request that lacks the header, including a download's second hop, which must
40    /// go out bare. A builder carrying a default `Authorization` or `Cookie` would send it
41    /// to the storage host, so give it none — the SDK sets every header it needs per
42    /// request.
43    pub fn from_builder(builder: reqwest::ClientBuilder) -> Result<ReqwestClient, Error> {
44        let http = builder
45            .redirect(Policy::none())
46            .retry(reqwest::retry::never())
47            .build()
48            .map_err(|error| Error::usage(format!("HTTP client: {error}")))?;
49        Ok(ReqwestClient { http })
50    }
51}
52
53#[async_trait]
54impl HttpClient for ReqwestClient {
55    async fn send(&self, request: Request<Bytes>) -> Result<Response<Body>, Error> {
56        let request = reqwest::Request::try_from(request).map_err(classify)?;
57        let answered = self.http.execute(request).await.map_err(classify)?;
58
59        let status = answered.status();
60        let version = answered.version();
61        let headers = answered.headers().clone();
62        let content_length = answered.content_length();
63
64        let mut response = Response::new(Body::from_stream(chunks(answered), content_length));
65        *response.status_mut() = status;
66        *response.version_mut() = version;
67        *response.headers_mut() = headers;
68        Ok(response)
69    }
70}
71
72fn chunks(response: reqwest::Response) -> impl stream::Stream<Item = Result<Bytes, Error>> + Send {
73    stream::try_unfold(response, |mut response| async move {
74        match response.chunk().await {
75            Ok(Some(chunk)) => Ok(Some((chunk, response))),
76            Ok(None) => Ok(None),
77            Err(error) => Err(classify(error)),
78        }
79    })
80}
81
82/// A transport failure as the SDK's network error, less the URL reqwest writes into its
83/// own message: the failure ends up in hints and logs, and a signed URL carries its
84/// credential in the query (SPEC §9).
85fn classify(error: reqwest::Error) -> Error {
86    let error = error.without_url();
87    if error.is_timeout() {
88        Error::network_timeout(error)
89    } else {
90        Error::network(error)
91    }
92}