rig_http/http_client/middleware.rs
1//! Transport-boundary middleware for [`DynHttpClient`](super::DynHttpClient).
2//! Attach hooks with [`with_middleware`](super::DynHttpClient::with_middleware).
3//!
4//! ```
5//! use rig_http::http_client::middleware::HttpMiddleware;
6//!
7//! struct PassThrough;
8//! impl HttpMiddleware for PassThrough {}
9//! ```
10
11use bytes::Bytes;
12use http::{HeaderMap, Method, StatusCode, Uri};
13
14use super::Result;
15use crate::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
16
17/// Transport-boundary hooks applied by
18/// [`DynHttpClient`](super::DynHttpClient) around every request.
19///
20/// Methods default to no-ops. All header hooks run in attachment order, then
21/// all body hooks run in that order with the final headers and preceding body
22/// replacements. Response hooks run in attachment order after transport returns,
23/// before streaming-body consumption. Multipart requests skip body hooks.
24///
25/// Any hook error fails the request; request-side errors abort before sending.
26/// Response hooks cannot modify responses. Hooks run on the request future and
27/// must not block.
28pub trait HttpMiddleware: WasmCompatSend + WasmCompatSync {
29 /// Mutate the outgoing request headers in place.
30 ///
31 /// Runs before [`before_request_body`](Self::before_request_body). An
32 /// error aborts the request before it is sent.
33 fn before_request_headers<'a>(
34 &'a self,
35 _method: &'a Method,
36 _uri: &'a Uri,
37 _headers: &'a mut HeaderMap,
38 ) -> WasmBoxedFuture<'a, Result<()>> {
39 Box::pin(async { Ok(()) })
40 }
41
42 /// Observe the serialized request body, returning the body to send.
43 ///
44 /// Return `body` unchanged to pass through, or a replacement to rewrite
45 /// the payload. `headers` reflects every middleware's header mutations.
46 /// Not invoked for multipart requests. An error aborts the request before
47 /// it is sent.
48 fn before_request_body<'a>(
49 &'a self,
50 _method: &'a Method,
51 _uri: &'a Uri,
52 _headers: &'a HeaderMap,
53 body: Bytes,
54 ) -> WasmBoxedFuture<'a, Result<Bytes>> {
55 Box::pin(async move { Ok(body) })
56 }
57
58 /// Observe the response status and headers as soon as they arrive.
59 ///
60 /// For streaming responses this runs before any of the body stream is
61 /// consumed. Observe-only: the response cannot be modified, but returning
62 /// an error fails the request with that error.
63 fn after_response<'a>(
64 &'a self,
65 _method: &'a Method,
66 _uri: &'a Uri,
67 _status: StatusCode,
68 _headers: &'a HeaderMap,
69 ) -> WasmBoxedFuture<'a, Result<()>> {
70 Box::pin(async { Ok(()) })
71 }
72}