Skip to main content

rig_http/http_client/
erased.rs

1//! Type-erased HTTP transport with optional middleware.
2//! Without middleware, requests and responses pass through unchanged.
3//!
4//! ```
5//! use rig_http::http_client::{DynHttpClient, HttpClientExt};
6//!
7//! fn erase(client: impl HttpClientExt + 'static) -> DynHttpClient {
8//!     DynHttpClient::new(client)
9//! }
10//! ```
11
12use 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
23/// Object-safe mirror of [`HttpClientExt`] with boxed futures. Private: the
24/// only way to reach it is through [`DynHttpClient`].
25pub(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    /// Borrows `self`: [`HttpClientExt::send_streaming`] does not promise a
37    /// `'static` future, so neither can its erasure.
38    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/// A type-erased, cheaply cloneable HTTP transport.
71///
72/// Clones share the transport and middleware instances but copy the middleware
73/// list. Erasing an already erased transport clones it without another layer.
74/// `Debug` prints only the type name to avoid exposing transport credentials.
75/// The transport is not serializable.
76///
77/// ```compile_fail
78/// fn assert_serialize<T: serde::Serialize>() {}
79/// assert_serialize::<rig_http::http_client::DynHttpClient>();
80/// ```
81#[derive(Clone)]
82pub struct DynHttpClient {
83    inner: Arc<dyn ErasedHttpClient>,
84    /// Transport-boundary middleware, applied in attachment order around
85    /// every request this handle sends. Cloned handles share the same stack.
86    middleware: Vec<Arc<dyn HttpMiddleware>>,
87}
88
89impl DynHttpClient {
90    /// Erase `http`. If `http` is already a `DynHttpClient`, this is a clone
91    /// (its attached middleware included).
92    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    /// Attach a transport-boundary [`HttpMiddleware`] to this handle.
106    ///
107    /// Hooks run in attachment order with the phases defined by [`HttpMiddleware`].
108    /// Existing clones keep their previous stack. The underlying transport stays
109    /// shared, so [`Self::ptr_eq`] is unaffected.
110    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    /// Whether two handles share the same underlying transport.
119    ///
120    /// Compares the transport only: handles that differ in attached
121    /// middleware but wrap the same transport still compare equal.
122    pub fn ptr_eq(&self, other: &Self) -> bool {
123        Arc::ptr_eq(&self.inner, &other.inner)
124    }
125
126    /// Run the request-side middleware phases: all header hooks in order,
127    /// then all body hooks in order (each seeing the final headers).
128    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    /// Run only the header hooks (the multipart path, which has no single
149    /// serialized body to hand to the body hooks).
150    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    /// Send `parts` and `body` through `send`, then run the response hooks
164    /// in attachment order on its reply: a response, or an error that kept
165    /// a non-success reply's status and headers. A hook's error fails a
166    /// response with that error; an error reply stops at a failing hook and
167    /// still fails with its own error.
168    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;