Skip to main content

rig_core/driver/
http_transport.rs

1//! The HTTP transport: any [`HttpClientExt`] sends [`Encoded`] requests and
2//! delivers their replies as [`WireFrame`]s. It owns every HTTP concern:
3//! headers, framing, status and content-type checks, and request ids.
4
5use bytes::Bytes;
6use futures::StreamExt;
7
8use super::{Exchange, Opened, Opening, Transport};
9use crate::error::ProviderError;
10use crate::http_client::framing::{Framer, Framing};
11use crate::http_client::{self, HttpClientExt};
12use crate::wasm_compat::{WasmCompatSend, WasmCompatSync};
13use crate::wire::{Body, Encoded, Mode, Wire, WireFrame};
14
15impl<W, H> Transport<W> for H
16where
17    W: Wire<Payload = Encoded, Frame = WireFrame>,
18    H: HttpClientExt + Clone + WasmCompatSend + WasmCompatSync + 'static,
19{
20    fn send(&self, payload: Encoded, exchange: Exchange) -> Opening<WireFrame> {
21        let Encoded {
22            mut request,
23            framing,
24            request_id_header,
25            relaxed_content_type,
26        } = payload;
27        let Exchange { mode, extensions } = exchange;
28        request.extensions_mut().extend(extensions);
29        // A whole reply has nothing to stream: it is read as a unary one is,
30        // so its document is a fact of the reply in both modes.
31        let streamed = framing.framer().filter(|_| mode == Mode::Streaming);
32        if streamed.is_some() && matches!(request.body(), Body::Multipart(_)) {
33            return Opening::failed(ProviderError::request(
34                "a multipart request cannot open a streamed reply",
35            ));
36        }
37        accept_header(&mut request, framing);
38        let exchange = HttpExchange {
39            framing,
40            request_id_header,
41            relaxed_content_type,
42            path: request.uri().path().to_owned(),
43        };
44        let http = self.clone();
45        Opening::new(async move {
46            Ok(match streamed {
47                Some(framer) => match byte_request(request) {
48                    Ok(request) => exchange.streaming(&http, request, framer).await,
49                    Err(error) => Opened::failed(error),
50                },
51                None => exchange.unary(&http, request).await,
52            })
53        })
54    }
55}
56
57/// What one request's exchange needs besides the client.
58struct HttpExchange {
59    framing: Framing,
60    request_id_header: Option<&'static str>,
61    relaxed_content_type: bool,
62    path: String,
63}
64
65impl HttpExchange {
66    fn failed(self, error: ProviderError, request_id: Option<String>) -> Opened<WireFrame> {
67        Opened::failed(error)
68            .with_request_id(request_id)
69            .with_route(self.path)
70    }
71
72    /// Send a buffered request and frame its whole body.
73    async fn unary<H: HttpClientExt>(
74        self,
75        http: &H,
76        request: http::Request<Body>,
77    ) -> Opened<WireFrame> {
78        let sent = match send(http, request, self.request_id_header).await {
79            Ok(sent) => sent,
80            Err(error) => return self.failed(error, None),
81        };
82        // The status said success, but an SSE framer over a body that is not
83        // an event stream yields no frames at all, which would fold to a
84        // contentless success. The reply the provider actually sent is the
85        // error.
86        if let Some(rejected) =
87            wrong_content_type(&sent.headers, self.framing, self.relaxed_content_type)
88        {
89            let error = ProviderError::from_transport_error(rejected)
90                .with_provider_status(Some(sent.status))
91                .with_provider_request_id(sent.provider_request_id.clone())
92                .with_response_headers(Some(sent.headers.clone()));
93            return self.failed(error, sent.provider_request_id);
94        }
95        // Frame the reply the way a stream is framed: a wire whose unary
96        // reply is an event stream would otherwise hand its decoder a
97        // document it cannot parse.
98        let document = serde_json::from_slice(&sent.body).ok();
99        let frames = self.framing.split(&sent.body);
100        let frames = futures::stream::iter(frames.into_iter().map(Ok));
101        Opened {
102            document,
103            ..Opened::new(frames)
104                .with_request_id(sent.provider_request_id)
105                .with_http(sent.status, sent.headers)
106                .with_route(self.path)
107        }
108    }
109
110    /// Open a streamed reply and frame its body as it arrives.
111    async fn streaming<H: HttpClientExt>(
112        self,
113        http: &H,
114        request: http::Request<Bytes>,
115        mut framer: Framer,
116    ) -> Opened<WireFrame> {
117        let response = match http.send_streaming(request).await {
118            // Custom transports may return rejected responses directly; preserve
119            // their status, headers, and bounded body in the error.
120            Ok(response) if !response.status().is_success() => Err(reject_response(response).await),
121            Ok(response) => {
122                match wrong_content_type(
123                    response.headers(),
124                    self.framing,
125                    self.relaxed_content_type,
126                ) {
127                    Some(error) => Err(error),
128                    None => Ok(response),
129                }
130            }
131            other => other,
132        };
133        let response = match response {
134            Ok(response) => response,
135            Err(error) => {
136                let request_id = error
137                    .non_success_headers()
138                    .and_then(|headers| request_id_from(headers, self.request_id_header));
139                let error = ProviderError::from_transport_error(error)
140                    .with_provider_request_id(request_id.clone());
141                return self.failed(error, request_id);
142            }
143        };
144        let request_id = request_id_from(response.headers(), self.request_id_header);
145        let status = response.status();
146        let headers = response.headers().clone();
147        let mut body = response.into_body();
148        let frames = async_stream::stream! {
149            while let Some(chunk) = body.next().await {
150                let chunk = match chunk {
151                    Ok(chunk) => chunk,
152                    Err(error) => {
153                        yield Err(ProviderError::from_transport_error(error));
154                        return;
155                    }
156                };
157                for frame in framer.push(&chunk) {
158                    let frame = match frame {
159                        Ok(frame) => frame,
160                        Err(refused) => {
161                            let why = format!("the reply sent a frame of {refused}");
162                            yield Err(ProviderError::Response(why));
163                            return;
164                        }
165                    };
166                    yield Ok(frame);
167                }
168            }
169            if let Some(frame) = framer.finish() {
170                yield Ok(frame);
171            }
172        };
173        Opened::new(frames)
174            .with_request_id(request_id)
175            .with_http(status, headers)
176            .with_route(self.path)
177    }
178}
179
180/// What one send learned about its reply.
181struct Sent {
182    status: http::StatusCode,
183    headers: http::HeaderMap,
184    body: Bytes,
185    provider_request_id: Option<String>,
186}
187
188/// Sends a buffered request, preserving non-success response details and IDs.
189async fn send<H>(
190    http: &H,
191    request: http::Request<Body>,
192    request_id_header: Option<&'static str>,
193) -> Result<Sent, ProviderError>
194where
195    H: HttpClientExt,
196{
197    let (parts, body) = request.into_parts();
198    let response = match body {
199        Body::Bytes(bytes) => {
200            http.send(http::Request::from_parts(parts, bytes.into()))
201                .await
202        }
203        Body::Multipart(form) => {
204            http.send_multipart(http::Request::from_parts(parts, form))
205                .await
206        }
207    };
208    let response = match response {
209        Ok(response) => response,
210        // A transport that reports the non-success reply as an error: the
211        // reply is the provider's, so it funnels to a preserved provider
212        // response with the id read off its headers and the headers
213        // themselves; a response-less failure stays a transport error.
214        Err(error) => {
215            let request_id = error
216                .non_success_headers()
217                .and_then(|headers| request_id_from(headers, request_id_header));
218            return Err(
219                ProviderError::from_transport_error(error).with_provider_request_id(request_id)
220            );
221        }
222    };
223
224    // Take the reply apart before awaiting the body: the headers are then
225    // owned, so preserving them onto an error costs no clone and every
226    // error path below can afford them.
227    let (parts, body) = response.into_parts();
228    let status = parts.status;
229    let provider_request_id = request_id_from(&parts.headers, request_id_header);
230    let body = body.await.map_err(ProviderError::from_transport_error)?;
231
232    if !status.is_success() {
233        return Err(
234            ProviderError::from_http_response(status, String::from_utf8_lossy(&body))
235                .with_provider_request_id(provider_request_id)
236                .with_response_headers(Some(parts.headers)),
237        );
238    }
239    Ok(Sent {
240        status,
241        headers: parts.headers,
242        body,
243        provider_request_id,
244    })
245}
246
247/// The provider's transport request id, when it names such a header and the
248/// reply carries a non-empty value.
249pub(crate) fn request_id_from(headers: &http::HeaderMap, header: Option<&str>) -> Option<String> {
250    header.and_then(|header| {
251        headers
252            .get(header)
253            .and_then(|value| value.to_str().ok())
254            .filter(|value| !value.is_empty())
255            .map(str::to_string)
256    })
257}
258
259/// Defaults byte-body requests to `application/json`, including bodyless GETs.
260/// Preserves an explicitly supplied content type.
261fn content_type(request: &mut http::Request<Body>) {
262    if matches!(request.body(), Body::Bytes(_)) {
263        request
264            .headers_mut()
265            .entry(http::header::CONTENT_TYPE)
266            .or_insert(http::HeaderValue::from_static("application/json"));
267    }
268}
269
270/// Add `Accept: text/event-stream` to an SSE request, without overriding an
271/// `Accept` the wire set itself.
272fn accept_header(request: &mut http::Request<Body>, framing: Framing) {
273    content_type(request);
274    if framing == Framing::Sse {
275        request
276            .headers_mut()
277            .entry("Accept")
278            .or_insert(http::HeaderValue::from_static("text/event-stream"));
279    }
280}
281
282/// Whether a reply's content type is not the event stream an SSE wire asked
283/// for: the framer would silently produce no frames, which reads as
284/// truncation rather than as the wrong endpoint. A reply that names no
285/// content type at all is accepted only by a wire that opted in.
286///
287/// The one predicate both paths ask, so a unary reply and a streamed one
288/// cannot disagree about what the provider sent.
289fn wrong_content_type(
290    headers: &http::HeaderMap,
291    framing: Framing,
292    relaxed: bool,
293) -> Option<http_client::Error> {
294    if framing != Framing::Sse {
295        return None;
296    }
297    let Some(content_type) = headers.get(&http::header::CONTENT_TYPE) else {
298        return (!relaxed)
299            .then(|| http_client::Error::InvalidContentType(http::HeaderValue::from_static("")));
300    };
301    let event_stream = content_type
302        .to_str()
303        .ok()
304        .and_then(|value| value.parse::<mime::Mime>().ok())
305        .is_some_and(|mime_type| {
306            matches!(
307                (mime_type.type_(), mime_type.subtype()),
308                (mime::TEXT, mime::EVENT_STREAM)
309            )
310        });
311    (!event_stream).then(|| http_client::Error::InvalidContentType(content_type.clone()))
312}
313
314/// A request whose body is bytes. Multipart replies are never streamed.
315fn byte_request(request: http::Request<Body>) -> Result<http::Request<Bytes>, ProviderError> {
316    let (parts, body) = request.into_parts();
317    match body {
318        Body::Bytes(bytes) => Ok(http::Request::from_parts(parts, bytes.into())),
319        Body::Multipart(_) => Err(ProviderError::request(
320            "a multipart request cannot open a streamed reply",
321        )),
322    }
323}
324
325/// Bytes of a rejected reply's body kept on the error; a reply longer than
326/// this is cut there.
327const REJECTED_BODY_LIMIT: usize = 1 << 20;
328
329/// Chunks read off a rejected reply before giving up on it, so a transport
330/// that keeps yielding empty chunks cannot hold the opener.
331const REJECTED_CHUNK_LIMIT: usize = 4096;
332
333/// Turn a reply the driver will not stream (any status but 200, a 204
334/// included: a status is a status) into the non-success error, reading the
335/// body to its end (bounded in bytes and chunks) so the provider's payload
336/// and the transport's headers ride on the error.
337async fn reject_response(
338    response: http::Response<crate::http_client::BoxedStream>,
339) -> http_client::Error {
340    let status = response.status();
341    let headers = response.headers().clone();
342    let mut body = response.into_body();
343    let mut bytes: Vec<u8> = Vec::new();
344    let mut chunks = 0usize;
345    while let Some(chunk) = body.next().await {
346        chunks += 1;
347        if let Ok(chunk) = chunk {
348            let room = REJECTED_BODY_LIMIT.saturating_sub(bytes.len());
349            bytes.extend_from_slice(chunk.get(..chunk.len().min(room)).unwrap_or_default());
350        }
351        if bytes.len() >= REJECTED_BODY_LIMIT || chunks >= REJECTED_CHUNK_LIMIT {
352            break;
353        }
354    }
355    http_client::Error::InvalidStatusCodeWithDetails {
356        status,
357        body: String::from_utf8_lossy(&bytes).into_owned(),
358        headers,
359    }
360}