Skip to main content

timvw_rust_runtime/
client.rs

1use std::fmt;
2use std::future::Future;
3use std::pin::Pin;
4use std::sync::{Mutex, PoisonError};
5use std::task::{Context, Poll};
6
7use tower::util::BoxCloneSyncService;
8use tower::{Layer, Service, ServiceExt};
9
10use crate::{Body, BoxError, Error, Method, RequestBuilder, Response};
11
12/// The service a [`Client`] sends requests through, with its type erased.
13pub type HttpService = BoxCloneSyncService<http::Request<Body>, http::Response<Body>, BoxError>;
14
15/// Sends the requests of a generated client through a tower service.
16///
17/// [`Client::default`] sends with reqwest (feature `reqwest`) and retries transient failures (feature `retry`).
18/// [`Client::from_service`] takes any other service, as is, and [`Client::layer`] wraps the current one in a tower
19/// layer:
20///
21/// ```no_run
22/// # #[cfg(feature = "reqwest")]
23/// # fn demo() {
24/// use std::time::Duration;
25/// use timvw_rust_runtime::Client;
26///
27/// let client = Client::default().layer(tower::timeout::TimeoutLayer::new(Duration::from_secs(30)));
28/// # }
29/// ```
30#[derive(Clone)]
31pub struct Client {
32    service: HttpService,
33}
34
35impl Client {
36    /// A client that sends with a new `reqwest::Client`, retrying with [`RetryPolicy::default`] (feature `retry`).
37    ///
38    /// [`RetryPolicy::default`]: crate::retry::RetryPolicy
39    #[cfg(feature = "reqwest")]
40    pub fn new() -> Self {
41        Self::from_reqwest(reqwest::Client::new())
42    }
43
44    /// A client that sends with the given `reqwest::Client`, for example one with a proxy or a custom TLS setup, and
45    /// retries like [`Client::new`].
46    ///
47    /// For other retries, or none, start from the bare service instead:
48    /// `Client::from_service(ReqwestService::new(client))`, then add the layers you want.
49    #[cfg(feature = "reqwest")]
50    pub fn from_reqwest(client: reqwest::Client) -> Self {
51        let client = Self::from_service(crate::ReqwestService::new(client));
52        #[cfg(feature = "retry")]
53        let client = client.layer(crate::retry::RetryLayer::default());
54        client
55    }
56
57    /// A client that sends with any tower service from `http::Request<Body>` to `http::Response<B>`.
58    ///
59    /// The service must be `Clone` and `Send`, not `Sync`: services such as `ConcurrencyLimit` that cannot be shared
60    /// between threads are held behind a lock that is only taken to clone them.
61    pub fn from_service<S, B>(service: S) -> Self
62    where
63        S: Service<http::Request<Body>, Response = http::Response<B>> + Clone + Send + 'static,
64        S::Error: Into<BoxError>,
65        S::Future: Send + 'static,
66        B: http_body::Body + Send + Sync + 'static,
67        B::Data: Into<bytes::Bytes>,
68        B::Error: Into<BoxError>,
69    {
70        let service = service
71            .map_response(|response: http::Response<B>| response.map(Body::wrap))
72            .map_err(Into::into);
73        Self {
74            service: BoxCloneSyncService::new(SyncService(Mutex::new(service))),
75        }
76    }
77
78    /// Wraps the client's service in a tower layer: retries, timeouts, rate limits, tracing, ...
79    ///
80    /// Layers apply from the inside out: the last one added sees a request first.
81    pub fn layer<L, B>(self, layer: L) -> Self
82    where
83        L: Layer<HttpService>,
84        L::Service:
85            Service<http::Request<Body>, Response = http::Response<B>> + Clone + Send + 'static,
86        <L::Service as Service<http::Request<Body>>>::Error: Into<BoxError>,
87        <L::Service as Service<http::Request<Body>>>::Future: Send + 'static,
88        B: http_body::Body + Send + Sync + 'static,
89        B::Data: Into<bytes::Bytes>,
90        B::Error: Into<BoxError>,
91    {
92        Self::from_service(layer.layer(self.service))
93    }
94
95    /// The service requests go through.
96    pub fn service(&self) -> &HttpService {
97        &self.service
98    }
99
100    /// Starts a request to `url`.
101    pub fn request(&self, method: Method, url: &str) -> RequestBuilder {
102        RequestBuilder::new(self.clone(), method, url)
103    }
104
105    /// Sends a request.
106    pub async fn execute(&self, request: http::Request<Body>) -> Result<Response, Error> {
107        let response = self
108            .service
109            .clone()
110            .oneshot(request)
111            .await
112            .map_err(Error::request)?;
113        Ok(Response::from(response))
114    }
115}
116
117/// With feature `reqwest` [`Client::new`]: reqwest, with retries when feature `retry` is on; without it a client whose every request fails, to be
118/// replaced with [`Client::from_service`].
119impl Default for Client {
120    fn default() -> Self {
121        #[cfg(feature = "reqwest")]
122        {
123            Self::new()
124        }
125        #[cfg(not(feature = "reqwest"))]
126        {
127            Self::from_service(NoService)
128        }
129    }
130}
131
132impl fmt::Debug for Client {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        f.debug_struct("Client").finish_non_exhaustive()
135    }
136}
137
138/// Makes a `Clone + Send` service `Sync`. Every request clones the service, under the lock, and calls the clone, so
139/// the lock is never held across `poll_ready` or `call` on a shared value.
140struct SyncService<S>(Mutex<S>);
141
142impl<S: Clone> Clone for SyncService<S> {
143    fn clone(&self) -> Self {
144        let service = self
145            .0
146            .lock()
147            .unwrap_or_else(PoisonError::into_inner)
148            .clone();
149        Self(Mutex::new(service))
150    }
151}
152
153impl<S: Service<R>, R> Service<R> for SyncService<S> {
154    type Response = S::Response;
155    type Error = S::Error;
156    type Future = S::Future;
157
158    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
159        self.0
160            .get_mut()
161            .unwrap_or_else(PoisonError::into_inner)
162            .poll_ready(cx)
163    }
164
165    fn call(&mut self, request: R) -> Self::Future {
166        self.0
167            .get_mut()
168            .unwrap_or_else(PoisonError::into_inner)
169            .call(request)
170    }
171}
172
173/// The service of a client built without an HTTP client: every request fails.
174#[cfg_attr(feature = "reqwest", allow(dead_code))]
175#[derive(Clone, Copy, Debug)]
176struct NoService;
177
178impl Service<http::Request<Body>> for NoService {
179    type Response = http::Response<Body>;
180    type Error = BoxError;
181    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
182
183    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
184        Poll::Ready(Ok(()))
185    }
186
187    fn call(&mut self, _: http::Request<Body>) -> Self::Future {
188        Box::pin(async {
189            Err("no HTTP client: enable the `reqwest` feature of timvw-rust-runtime or set one with Client::from_service".into())
190        })
191    }
192}