rig-reqwest 0.47.0

The bundled reqwest HTTP transport for Rig.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(
    test,
    allow(
        clippy::expect_used,
        clippy::indexing_slicing,
        clippy::panic,
        clippy::unwrap_used,
        clippy::unreachable
    )
)]
//! The bundled reqwest HTTP transport for Rig.
//!
//! [`ReqwestClient::default()`] is the process-wide client: built once on
//! first use and shared by every clone, so every provider client made with
//! it shares one connection pool. Construction never fails. On a host with
//! no CA certificates, the `rustls` build trusts the bundled Mozilla roots
//! instead. When reqwest still cannot build its client, every send reports
//! that build failure in-band.
//!
//! Native requests and bodies enter the captured Tokio context on each poll
//! ([`rig_http::runtime`]), using a lazy fallback when no runtime is current. Callers retain ownership;
//! dropping an operation cancels local work, not accepted remote work. Hosts
//! must keep their runtime driven with I/O and timers enabled until operations
//! finish. Missing drivers can panic; a stopped runtime causes I/O failure.
//!
//! ```no_run
//! use rig_reqwest::ReqwestClient;
//!
//! let shared = ReqwestClient::default();
//! let custom = ReqwestClient::from(rig_reqwest::reqwest::Client::new());
//! # let _ = (shared, custom);
//! ```

pub use reqwest;

/// A reqwest client implementing [`HttpClientExt`].
///
/// [`Default`] is the process-wide client, built once and shared by every
/// clone; `From<reqwest::Client>` wraps a configured client and keeps its
/// connection pool. Non-success responses retain at most 64 KiB of body bytes,
/// with a truncation marker only after observing excess data. Partial diagnostic
/// text survives body read failures; the client's timeout policy governs reads.
///
/// On native targets, [`Default`]'s client follows a redirect to another origin
/// (scheme, host or port) with only harmless headers, so no credential reaches
/// it. A browser follows redirects itself, so wasm lacks this protection, as do
/// a client from `From<reqwest::Client>` and a `ReqwestMiddlewareClient`, which
/// keep their own policy.
#[derive(Clone, Debug)]
pub struct ReqwestClient(Built);

/// The process-wide client, erased behind [`DynHttpClient`].
pub fn shared() -> DynHttpClient {
    DynHttpClient::new(ReqwestClient::default())
}

/// What building the client produced: the client, or why reqwest refused.
#[derive(Clone, Debug)]
enum Built {
    /// The process-wide client: on native targets, [`follow_redirects`]
    /// follows its redirects.
    Shared(Arc<reqwest::Client>),
    /// A caller's client, which keeps its own redirect policy.
    Client(Arc<reqwest::Client>),
    /// The shared client could not be built: every send reports this, so
    /// the failure surfaces where the first request is made rather than
    /// where the client was named.
    Failed(Arc<reqwest::Error>),
}

impl Default for ReqwestClient {
    /// The process-wide client, built on first use. It never panics: a
    /// client reqwest cannot build reports the build error on every send.
    fn default() -> Self {
        fn build() -> ReqwestClient {
            ReqwestClient(match build_shared(shared_builder) {
                Ok(client) => Built::Shared(Arc::new(client)),
                Err(error) => Built::Failed(Arc::new(error)),
            })
        }
        #[cfg(not(target_family = "wasm"))]
        {
            static SHARED: std::sync::LazyLock<ReqwestClient> = std::sync::LazyLock::new(build);
            SHARED.clone()
        }
        #[cfg(target_family = "wasm")]
        {
            thread_local! {
                static SHARED: ReqwestClient = build();
            }
            SHARED.with(Clone::clone)
        }
    }
}

impl ReqwestClient {
    /// The reqwest client, or `None` for the shared client when reqwest
    /// could not build it. On native targets, the shared client's is a second
    /// one: its redirects are reqwest's own, so it lacks this type's protection
    /// and does not share the pool.
    pub fn inner(&self) -> Option<&reqwest::Client> {
        match &self.0 {
            #[cfg(not(target_family = "wasm"))]
            Built::Shared(_) => {
                static FOLLOWING: std::sync::LazyLock<Option<reqwest::Client>> =
                    std::sync::LazyLock::new(|| build_shared(reqwest::Client::builder).ok());
                FOLLOWING.as_ref()
            }
            #[cfg(target_family = "wasm")]
            Built::Shared(client) => Some(client),
            Built::Client(client) => Some(client),
            Built::Failed(_) => None,
        }
    }

    /// Whether `self` and `other` are clones of one client.
    #[cfg(test)]
    fn same(&self, other: &Self) -> bool {
        match (&self.0, &other.0) {
            (Built::Shared(a), Built::Shared(b)) | (Built::Client(a), Built::Client(b)) => {
                Arc::ptr_eq(a, b)
            }
            (Built::Failed(a), Built::Failed(b)) => Arc::ptr_eq(a, b),
            _ => false,
        }
    }
}

/// The builder of the shared client. On native targets reqwest follows no
/// redirect, so that [`follow_redirects`] decides what each one carries.
fn shared_builder() -> reqwest::ClientBuilder {
    let builder = reqwest::Client::builder();
    #[cfg(not(target_family = "wasm"))]
    let builder = builder.redirect(reqwest::redirect::Policy::none());
    builder
}

/// A client from `builder`, falling back to the bundled roots when the system's
/// cannot be loaded.
fn build_shared(builder: fn() -> reqwest::ClientBuilder) -> reqwest::Result<reqwest::Client> {
    let built = builder().build();
    #[cfg(all(feature = "rustls", not(target_family = "wasm")))]
    let built = built.or_else(|error| with_bundled_roots(builder(), error));
    built
}

/// `builder` trusting only the bundled Mozilla roots, after the
/// default build failed with `error`. That build differs only in reading
/// the system's root store, which a host without CA certificates lacks.
/// Returns `error` when this build fails too.
#[cfg(all(feature = "rustls", not(target_family = "wasm")))]
fn with_bundled_roots(
    builder: reqwest::ClientBuilder,
    error: reqwest::Error,
) -> reqwest::Result<reqwest::Client> {
    let roots = webpki_root_certs::TLS_SERVER_ROOT_CERTS
        .iter()
        .filter_map(|der| reqwest::Certificate::from_der(der).ok());
    let Ok(client) = builder.tls_certs_only(roots).build() else {
        return Err(error);
    };
    tracing::warn!(
        "the system's CA certificates could not be loaded ({}), so rig trusts its bundled \
         Mozilla roots; install the system's CA certificates, or set SSL_CERT_FILE or \
         SSL_CERT_DIR, to trust those instead",
        Chain(&error)
    );
    Ok(client)
}

/// The error every send on an unbuilt client reports.
fn unbuilt(error: &Arc<reqwest::Error>) -> Error {
    Error::permanent(TransportBuildError(Arc::clone(error)))
}

impl From<reqwest::Client> for ReqwestClient {
    fn from(client: reqwest::Client) -> Self {
        Self(Built::Client(Arc::new(client)))
    }
}

use bytes::Bytes;
use rig_http::http_client::{
    BoxedStream, DynHttpClient, Error, HttpClientExt, LazyBody, MultipartForm, Request, Response,
    Result, StreamingResponse, multipart::PartContent, retryable_status,
};
use rig_http::wasm_compat::*;
use std::sync::Arc;

/// A transport build failure that displays the source chain and retains the
/// original reqwest error as its source.
#[derive(Debug)]
struct TransportBuildError(Arc<reqwest::Error>);

impl std::fmt::Display for TransportBuildError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "could not build the bundled reqwest transport: {}",
            Chain(&*self.0)
        )
    }
}

/// An error followed by each of its sources, separated by `: `.
struct Chain<'a>(&'a (dyn std::error::Error + 'static));

impl std::fmt::Display for Chain<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)?;
        std::iter::successors(self.0.source(), |cause| cause.source())
            .try_for_each(|cause| write!(f, ": {cause}"))
    }
}

impl std::error::Error for TransportBuildError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&*self.0)
    }
}

/// Classify a reqwest error, retaining it as the source. A request reqwest
/// could not build, a redirect it would not follow, and an error naming a
/// status [`retryable_status`] does not retry (from `error_for_status`) are
/// [`Error::Permanent`]; every other failure (connecting, a timeout, a body
/// cut short, a retried status) is [`Error::Transient`].
///
/// A non-success reply this transport reads itself goes through
/// [`non_success_body_error`] instead, which keeps its status, headers and
/// body.
pub fn from_reqwest(err: reqwest::Error) -> Error {
    if is_transient(&err) {
        Error::transient(err)
    } else {
        Error::permanent(err)
    }
}

/// Whether sending again may pass a request that failed with `err`, as
/// [`from_reqwest`] classifies it.
fn is_transient(err: &reqwest::Error) -> bool {
    match err.status() {
        Some(status) => retryable_status(Some(status.as_u16())),
        None => !(err.is_builder() || err.is_redirect()),
    }
}

/// The most of a non-success reply's body its error keeps.
const ERROR_BODY_LIMIT: usize = 64 * 1024;

/// Read at most 64 KiB of a failed response, retaining status and headers.
/// The client's timeout policy still governs body reads.
async fn non_success_status_error(response: reqwest::Response) -> Error {
    let status = response.status();
    let headers = response.headers().clone();
    non_success_body_error(status, headers, &mut Box::pin(response.bytes_stream())).await
}

/// The error a non-success reply becomes, read from its body's chunks: its
/// status and headers, and at most the first 64 KiB of the body decoded as
/// text by its charset, with a truncation marker when there was more. The
/// body is read until one byte past the limit or its first error; the bytes
/// read before an error are kept, and with none the error is the text. The
/// rest of `body` is left unread for the caller. Every transport that gives
/// providers rig-reqwest's errors builds them here, so the same reply gives
/// the same error whichever reads it.
pub async fn non_success_body_error<S, B, E>(
    status: http::StatusCode,
    headers: http::HeaderMap,
    body: &mut S,
) -> Error
where
    S: futures::Stream<Item = std::result::Result<B, E>> + Unpin,
    B: AsRef<[u8]>,
    E: std::fmt::Display,
{
    use futures::StreamExt;

    let mut bytes = Vec::new();
    let mut failure = None;
    while let Some(chunk) = body.next().await {
        match chunk {
            Ok(chunk) => {
                // One byte past the limit is enough to know the body was cut.
                let remaining = ERROR_BODY_LIMIT + 1 - bytes.len();
                bytes.extend(chunk.as_ref().iter().take(remaining));
                if bytes.len() > ERROR_BODY_LIMIT {
                    break;
                }
            }
            Err(error) => {
                failure = Some(error.to_string());
                break;
            }
        }
    }
    let kept = bytes.get(..ERROR_BODY_LIMIT).unwrap_or(&bytes);
    let mut text = if kept.is_empty() {
        failure
            .map(|failure| format!("failed to read error response body: {failure}"))
            .unwrap_or_default()
    } else {
        decode_error_body(kept.to_vec(), &headers).await
    };
    if bytes.len() > ERROR_BODY_LIMIT {
        text.push_str("\n[Response body truncated after 64 KiB]");
    }
    Error::non_success_with_details(status, headers, text)
}

/// Keep reqwest's charset decoding for the bounded, in-memory body.
#[cfg(not(target_family = "wasm"))]
async fn decode_error_body(bytes: Vec<u8>, headers: &http::HeaderMap) -> String {
    let mut response = http::Response::new(bytes);
    *response.headers_mut() = headers.clone();
    reqwest::Response::from(response)
        .text()
        .await
        .unwrap_or_else(|error| format!("failed to read error response body: {error}"))
}

#[cfg(target_family = "wasm")]
async fn decode_error_body(bytes: Vec<u8>, _headers: &http::HeaderMap) -> String {
    let bytes = bytes.strip_prefix(&[0xef, 0xbb, 0xbf]).unwrap_or(&bytes);
    String::from_utf8_lossy(bytes).into_owned()
}

/// Keep successful bodies lazy and owned by the response on every executor.
async fn into_response(mut response: reqwest::Response) -> Result<Response<LazyBody>> {
    if !response.status().is_success() {
        return Err(non_success_status_error(response).await);
    }

    let res = response_head(&mut response);
    let body = async { response.bytes().await.map_err(from_reqwest) };
    #[cfg(not(target_family = "wasm"))]
    let body = rig_http::runtime::bind(body)?;
    let body: LazyBody = Box::pin(body);
    res.body(body).map_err(Error::Protocol)
}

/// The status, headers (moved out) and, on native, HTTP version of `response`.
fn response_head(response: &mut reqwest::Response) -> http::response::Builder {
    #[cfg(not(target_family = "wasm"))]
    let mut res = Response::builder()
        .status(response.status())
        .version(response.version());

    #[cfg(target_family = "wasm")]
    let mut res = Response::builder().status(response.status());

    if let Some(hs) = res.headers_mut() {
        *hs = std::mem::take(response.headers_mut());
    }
    res
}

/// Convert an already-sent streaming response into the transport-agnostic
/// [`StreamingResponse`], rejecting non-success statuses with the
/// headers-preserving error. The body retains the request's reactor context.
async fn into_streaming_response(mut response: reqwest::Response) -> Result<StreamingResponse> {
    if !response.status().is_success() {
        return Err(non_success_status_error(response).await);
    }
    let res = response_head(&mut response);

    use futures::StreamExt;
    let stream = response
        .bytes_stream()
        .map(|chunk| chunk.map_err(from_reqwest));
    #[cfg(not(target_family = "wasm"))]
    let stream = rig_http::runtime::bind_stream(stream)?;
    let stream: BoxedStream = Box::pin(stream);
    res.body(stream).map_err(Error::Protocol)
}

/// A part's content type was not a MIME type reqwest would accept.
#[derive(Debug, thiserror::Error)]
#[error("multipart part {part:?} has an unusable content type {content_type:?}: {source}")]
struct InvalidPartContentType {
    part: String,
    content_type: String,
    source: reqwest::Error,
}

/// Render a [`MultipartForm`] as a `reqwest::multipart::Form`.
///
/// Returns an error when a binary part has a content type reqwest rejects.
pub fn multipart_form(value: MultipartForm) -> Result<reqwest::multipart::Form> {
    let mut form = reqwest::multipart::Form::new();

    for part in value.into_parts() {
        let (name, content, filename, content_type) = part.into_pieces();
        match content {
            PartContent::Text(text) => {
                form = form.text(name, text);
            }
            PartContent::Binary(bytes) => {
                // A `Bytes` body is the same reusable part `Part::bytes` makes, uncopied.
                let mut req_part = reqwest::multipart::Part::stream(bytes);
                if let Some(content_type) = content_type.as_ref() {
                    req_part = req_part.mime_str(content_type.as_ref()).map_err(|source| {
                        Error::permanent(InvalidPartContentType {
                            part: name.clone(),
                            content_type: content_type.as_ref().to_string(),
                            source,
                        })
                    })?;
                }

                if let Some(filename) = filename {
                    req_part = req_part.file_name(filename);
                }

                form = form.part(name, req_part);
            }
        }
    }

    Ok(form)
}

/// What a request carries: bytes, or a multipart form.
enum Payload {
    Bytes(Bytes),
    Form(reqwest::multipart::Form),
}

/// A reqwest client, plain or with middleware.
trait Execute: WasmCompatSend + WasmCompatSync {
    /// The send of `parts` with `payload`, or why it cannot be sent.
    fn execute(
        &self,
        parts: http::request::Parts,
        payload: Result<Payload>,
    ) -> Result<impl Future<Output = Result<reqwest::Response>> + WasmCompatSend + 'static>;
}

impl Execute for ReqwestClient {
    fn execute(
        &self,
        parts: http::request::Parts,
        payload: Result<Payload>,
    ) -> Result<impl Future<Output = Result<reqwest::Response>> + WasmCompatSend + 'static> {
        let client = match &self.0 {
            Built::Shared(client) | Built::Client(client) => client,
            Built::Failed(error) => return Err(unbuilt(error)),
        };
        #[cfg(not(target_family = "wasm"))]
        let follow = matches!(self.0, Built::Shared(_)).then(|| match &payload {
            Ok(Payload::Bytes(bytes)) => Some(bytes.clone()),
            _ => None,
        });
        let request = client
            .request(parts.method, parts.uri.to_string())
            .headers(parts.headers);
        let request = match payload? {
            Payload::Bytes(bytes) => request.body(bytes),
            Payload::Form(form) => request.multipart(form),
        };
        let request = request.build().map_err(from_reqwest)?;
        let client = Arc::clone(client);
        Ok(async move {
            #[cfg(not(target_family = "wasm"))]
            if let Some(body) = follow {
                return follow_redirects(client, request, body).await;
            }
            client.execute(request).await.map_err(from_reqwest)
        })
    }
}

/// The most redirects one request follows, reqwest's own limit.
#[cfg(not(target_family = "wasm"))]
const MAX_REDIRECTS: usize = 10;

/// Sends `request`, following its redirects by reqwest's rules, and returns the
/// first response it cannot follow: no redirect, no usable `Location`, a body it
/// cannot replay (`body` is `None` for a multipart form), or the limit reached.
///
/// Past a change of origin only allow-listed headers go on, for the rest of the
/// chain, so a key header rig has never heard of stays behind.
#[cfg(not(target_family = "wasm"))]
async fn follow_redirects(
    client: Arc<reqwest::Client>,
    request: reqwest::Request,
    mut body: Option<Bytes>,
) -> Result<reqwest::Response> {
    use http::header::{
        ACCEPT, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, RANGE, REFERER,
        TRANSFER_ENCODING, USER_AGENT,
    };
    use http::{HeaderValue, Method, StatusCode};

    let mut method = request.method().clone();
    let mut headers = request.headers().clone();
    let mut response = client.execute(request).await.map_err(from_reqwest)?;
    for _ in 0..MAX_REDIRECTS {
        let drop_body = match response.status() {
            StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND => method == Method::POST,
            StatusCode::SEE_OTHER => true,
            StatusCode::TEMPORARY_REDIRECT | StatusCode::PERMANENT_REDIRECT => false,
            _ => return Ok(response),
        };
        if drop_body {
            if method != Method::HEAD {
                method = Method::GET;
            }
            body = Some(Bytes::new());
            headers.remove(CONTENT_TYPE);
            headers.remove(CONTENT_LENGTH);
            headers.remove(CONTENT_ENCODING);
            headers.remove(TRANSFER_ENCODING);
        }
        let location = response.headers().get(LOCATION);
        let location = location.and_then(|location| location.to_str().ok());
        let previous = response.url();
        let (Some(mut url), Some(replay)) = (
            location.and_then(|location| previous.join(location).ok()),
            body.clone(),
        ) else {
            return Ok(response);
        };
        if url.origin() == previous.origin() {
            let mut referer = previous.clone();
            let _ = referer.set_username("");
            let _ = referer.set_password(None);
            referer.set_fragment(None);
            if let Ok(referer) = HeaderValue::from_str(referer.as_str()) {
                headers.insert(REFERER, referer);
            }
        } else {
            let kept = [ACCEPT, CONTENT_ENCODING, CONTENT_TYPE, RANGE, USER_AGENT];
            headers = headers
                .iter()
                .filter(|(name, _)| kept.contains(*name))
                .map(|(name, value)| (name.clone(), value.clone()))
                .collect();
        }
        // reqwest's builder would turn these into an `Authorization` header.
        let _ = url.set_username("");
        let _ = url.set_password(None);
        let request = client.request(method.clone(), url).headers(headers.clone());
        response = request.body(replay).send().await.map_err(from_reqwest)?;
    }
    Ok(response)
}

/// Sends `parts` with `payload` through `client` and reads the reply with
/// `convert`. The reactor is selected on first poll and kept through the
/// conversion.
fn send_with<C, T, F>(
    client: &C,
    parts: http::request::Parts,
    payload: Result<Payload>,
    convert: impl FnOnce(reqwest::Response) -> F + WasmCompatSend + 'static,
) -> impl Future<Output = Result<T>> + WasmCompatSend + 'static
where
    C: Execute,
    F: Future<Output = Result<T>> + WasmCompatSend,
{
    let sent = client.execute(parts, payload);
    async move {
        let sent = sent?;
        let operation = async move { convert(sent.await?).await };
        #[cfg(not(target_family = "wasm"))]
        let operation = rig_http::runtime::bind(operation)?;
        operation.await
    }
}

/// [`HttpClientExt`] for a client that implements [`Execute`].
macro_rules! http_client_ext {
    ($client:ty) => {
        impl HttpClientExt for $client {
            fn send(
                &self,
                req: Request<Bytes>,
            ) -> impl Future<Output = Result<Response<LazyBody>>> + WasmCompatSend + 'static {
                let (parts, body) = req.into_parts();
                send_with(self, parts, Ok(Payload::Bytes(body)), into_response)
            }

            fn send_multipart(
                &self,
                req: Request<MultipartForm>,
            ) -> impl Future<Output = Result<Response<LazyBody>>> + WasmCompatSend + 'static {
                let (parts, form) = req.into_parts();
                // Reject invalid MIME types locally rather than sending incomplete metadata.
                let payload = multipart_form(form).map(Payload::Form);
                send_with(self, parts, payload, into_response)
            }

            fn send_streaming(
                &self,
                req: Request<Bytes>,
            ) -> impl Future<Output = Result<StreamingResponse>> + WasmCompatSend {
                let (parts, body) = req.into_parts();
                let payload = Ok(Payload::Bytes(body));
                send_with(self, parts, payload, into_streaming_response)
            }
        }
    };
}
http_client_ext!(ReqwestClient);

#[cfg(any(
    feature = "reqwest-middleware-rustls",
    feature = "reqwest-middleware-native-tls"
))]
mod middleware;
#[cfg(any(
    feature = "reqwest-middleware-rustls",
    feature = "reqwest-middleware-native-tls"
))]
pub use middleware::ReqwestMiddlewareClient;

// Compile-time thread-safety contract: the transport handle is shared across
// threads by every host runtime.
#[cfg(not(target_family = "wasm"))]
const _: fn() = || {
    fn assert_send_sync_static<T: Send + Sync + 'static>() {}
    assert_send_sync_static::<ReqwestClient>();
};

#[cfg(test)]
mod tests;