timvw_rust_runtime/
client.rs1use 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
12pub type HttpService = BoxCloneSyncService<http::Request<Body>, http::Response<Body>, BoxError>;
14
15#[derive(Clone)]
31pub struct Client {
32 service: HttpService,
33}
34
35impl Client {
36 #[cfg(feature = "reqwest")]
40 pub fn new() -> Self {
41 Self::from_reqwest(reqwest::Client::new())
42 }
43
44 #[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 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 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 pub fn service(&self) -> &HttpService {
97 &self.service
98 }
99
100 pub fn request(&self, method: Method, url: &str) -> RequestBuilder {
102 RequestBuilder::new(self.clone(), method, url)
103 }
104
105 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
117impl 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
138struct 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#[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}