1use std::any::Any;
13use std::fmt;
14use std::sync::Arc;
15
16use bytes::Bytes;
17use http::{Request, Response};
18
19use super::middleware::{Exchange, HttpMiddleware};
20use super::{HttpClientExt, LazyBody, MultipartForm, Result, StreamingResponse};
21use crate::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
22
23pub(crate) trait ErasedHttpClient: WasmCompatSend + WasmCompatSync {
26 fn send_boxed(
27 &self,
28 req: Request<Bytes>,
29 ) -> WasmBoxedFuture<'static, Result<Response<LazyBody>>>;
30
31 fn send_multipart_boxed(
32 &self,
33 req: Request<MultipartForm>,
34 ) -> WasmBoxedFuture<'static, Result<Response<LazyBody>>>;
35
36 fn send_streaming_boxed(
39 &self,
40 req: Request<Bytes>,
41 ) -> WasmBoxedFuture<'_, Result<StreamingResponse>>;
42}
43
44impl<H> ErasedHttpClient for H
45where
46 H: HttpClientExt + 'static,
47{
48 fn send_boxed(
49 &self,
50 req: Request<Bytes>,
51 ) -> WasmBoxedFuture<'static, Result<Response<LazyBody>>> {
52 Box::pin(self.send(req))
53 }
54
55 fn send_multipart_boxed(
56 &self,
57 req: Request<MultipartForm>,
58 ) -> WasmBoxedFuture<'static, Result<Response<LazyBody>>> {
59 Box::pin(self.send_multipart(req))
60 }
61
62 fn send_streaming_boxed(
63 &self,
64 req: Request<Bytes>,
65 ) -> WasmBoxedFuture<'_, Result<StreamingResponse>> {
66 Box::pin(self.send_streaming(req))
67 }
68}
69
70#[derive(Clone)]
82pub struct DynHttpClient {
83 inner: Arc<dyn ErasedHttpClient>,
84 middleware: Vec<Arc<dyn HttpMiddleware>>,
87}
88
89impl DynHttpClient {
90 pub fn new<H>(http: H) -> Self
93 where
94 H: HttpClientExt + 'static,
95 {
96 if let Some(already) = (&http as &dyn Any).downcast_ref::<DynHttpClient>() {
97 return already.clone();
98 }
99 Self {
100 inner: Arc::new(http),
101 middleware: Vec::new(),
102 }
103 }
104
105 pub fn with_middleware<M>(mut self, middleware: M) -> Self
111 where
112 M: HttpMiddleware + 'static,
113 {
114 self.middleware.push(Arc::new(middleware));
115 self
116 }
117
118 pub fn ptr_eq(&self, other: &Self) -> bool {
123 Arc::ptr_eq(&self.inner, &other.inner)
124 }
125
126 async fn apply_request_middleware(
129 &self,
130 parts: &mut http::request::Parts,
131 body: Bytes,
132 ) -> Result<Bytes> {
133 self.apply_header_middleware(parts).await?;
134 let exchange = Exchange {
135 method: &parts.method,
136 uri: &parts.uri,
137 extensions: &parts.extensions,
138 };
139 let mut body = body;
140 for mw in &self.middleware {
141 body = mw
142 .before_request_body(exchange, &parts.headers, body)
143 .await?;
144 }
145 Ok(body)
146 }
147
148 async fn apply_header_middleware(&self, parts: &mut http::request::Parts) -> Result<()> {
151 for mw in &self.middleware {
152 let exchange = Exchange {
153 method: &parts.method,
154 uri: &parts.uri,
155 extensions: &parts.extensions,
156 };
157 mw.before_request_headers(exchange, &mut parts.headers)
158 .await?;
159 }
160 Ok(())
161 }
162
163 async fn observe<T, B, F>(
169 &self,
170 parts: http::request::Parts,
171 body: T,
172 send: impl FnOnce(Request<T>) -> F,
173 ) -> Result<Response<B>>
174 where
175 F: Future<Output = Result<Response<B>>>,
176 {
177 let (method, uri, extensions) = (
178 parts.method.clone(),
179 parts.uri.clone(),
180 parts.extensions.clone(),
181 );
182 let exchange = Exchange {
183 method: &method,
184 uri: &uri,
185 extensions: &extensions,
186 };
187 let error = match send(Request::from_parts(parts, body)).await {
188 Ok(response) => {
189 for mw in &self.middleware {
190 mw.after_response(exchange, response.status(), response.headers())
191 .await?;
192 }
193 return Ok(response);
194 }
195 Err(error) => error,
196 };
197 if let (Some(status), Some(headers)) =
198 (error.non_success_status(), error.non_success_headers())
199 {
200 for mw in &self.middleware {
201 if mw.after_response(exchange, status, headers).await.is_err() {
202 break;
203 }
204 }
205 }
206 Err(error)
207 }
208}
209
210impl fmt::Debug for DynHttpClient {
211 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212 f.write_str("DynHttpClient")
213 }
214}
215
216impl HttpClientExt for DynHttpClient {
217 fn send(
218 &self,
219 req: Request<Bytes>,
220 ) -> impl Future<Output = Result<Response<LazyBody>>> + WasmCompatSend + 'static {
221 let this = self.clone();
222 let (mut parts, body) = req.into_parts();
223 async move {
224 let body = this.apply_request_middleware(&mut parts, body).await?;
225 this.observe(parts, body, |request| this.inner.send_boxed(request))
226 .await
227 }
228 }
229
230 fn send_multipart(
231 &self,
232 req: Request<MultipartForm>,
233 ) -> impl Future<Output = Result<Response<LazyBody>>> + WasmCompatSend + 'static {
234 let this = self.clone();
235 let (mut parts, body) = req.into_parts();
236 async move {
237 this.apply_header_middleware(&mut parts).await?;
238 this.observe(parts, body, |request| {
239 this.inner.send_multipart_boxed(request)
240 })
241 .await
242 }
243 }
244
245 fn send_streaming(
246 &self,
247 req: Request<Bytes>,
248 ) -> impl Future<Output = Result<StreamingResponse>> + WasmCompatSend {
249 let (mut parts, body) = req.into_parts();
250 async move {
251 let body = self.apply_request_middleware(&mut parts, body).await?;
252 self.observe(parts, body, |request| {
253 self.inner.send_streaming_boxed(request)
254 })
255 .await
256 }
257 }
258}
259
260#[cfg(test)]
261mod tests;