tez 0.0.3

A lightweight, ergonomic, and fast high-level HTTP client for Rust
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
use std::{convert::TryFrom, error::Error as StdError, sync::Arc, time::Duration};

use futures_util::Stream;
use http::{HeaderMap, HeaderName, HeaderValue, Method, Uri, Version, header::CONTENT_TYPE};
use serde::Serialize;
use url::Url;

use crate::{
    Body, Client, Error, Event, Multipart, Request, Response, Result, auth::Authentication,
    content::Content,
};

#[derive(Clone, Copy)]
enum TimeoutOverride {
    Set(Duration),
    Disabled,
}

pub(crate) fn resolve_timeout(
    request: &Request,
    client_timeout: Option<Duration>,
) -> Option<Duration> {
    match request.extensions().get::<TimeoutOverride>().copied() {
        Some(TimeoutOverride::Set(duration)) => Some(duration),
        Some(TimeoutOverride::Disabled) => None,
        None => client_timeout,
    }
}

/// A fluent builder for one request.
///
/// The builder owns the detached [`Request`] as it is assembled. It borrows its
/// client only for [`RequestBuilder::send`], which delegates to [`Client::send`].
pub struct RequestBuilder<'client> {
    client: &'client Client,
    request: Result<Request>,
    // Track who owns the content type so body helpers can remove only Tez
    // metadata and multipart boundaries cannot be replaced accidentally.
    content_type: ContentTypeState,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum ContentTypeState {
    Absent,
    Caller,
    Generated,
    Multipart,
}

impl<'client> RequestBuilder<'client> {
    pub(crate) fn new(client: &'client Client, method: Method, target: &str) -> Self {
        let request = parse_target(target).and_then(|uri| {
            http::Request::builder()
                .method(method)
                .uri(uri)
                .body(Body::empty())
                .map_err(Into::into)
        });
        Self {
            client,
            request,
            content_type: ContentTypeState::Absent,
        }
    }

    /// Replaces all values for a header name.
    ///
    /// The name and value use the standard HTTP conversions. Invalid input is
    /// reported when this builder is [`build`](Self::build) or
    /// [`send`](Self::send).
    #[must_use]
    pub fn header<K, V>(self, name: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        HeaderValue: TryFrom<V>,
    {
        self.apply(move |request, content_type| {
            let name = HeaderName::try_from(name)
                .map_err(|_| Error::request("request header name is invalid"))?;
            let value = HeaderValue::try_from(value)
                .map_err(|_| Error::request("request header value is invalid"))?;
            if name == CONTENT_TYPE {
                if *content_type == ContentTypeState::Multipart {
                    return Err(Error::request("multipart content type is managed by Tez"));
                }
                *content_type = ContentTypeState::Caller;
            }
            request.headers_mut().insert(name, value);
            Ok(())
        })
    }

    /// Appends a value without replacing existing values for the header name.
    ///
    /// Use this for headers whose repeated values are meaningful. Invalid input
    /// is reported when this builder is [`build`](Self::build) or
    /// [`send`](Self::send).
    #[must_use]
    pub fn append_header<K, V>(self, name: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        HeaderValue: TryFrom<V>,
    {
        self.apply(move |request, content_type| {
            let name = HeaderName::try_from(name)
                .map_err(|_| Error::request("request header name is invalid"))?;
            let value = HeaderValue::try_from(value)
                .map_err(|_| Error::request("request header value is invalid"))?;
            if name == CONTENT_TYPE {
                if *content_type == ContentTypeState::Multipart {
                    return Err(Error::request("multipart content type is managed by Tez"));
                }
                *content_type = ContentTypeState::Caller;
            }
            request.headers_mut().append(name, value);
            Ok(())
        })
    }

    /// Merges headers, replacing each name represented in `headers`.
    ///
    /// Repeated values in `headers` are preserved. Header names absent from
    /// `headers` are left unchanged.
    #[must_use]
    pub fn headers(self, headers: HeaderMap) -> Self {
        self.apply(move |request, content_type| {
            replace_headers(request.headers_mut(), headers, content_type)
        })
    }

    /// Sets authentication for this request.
    ///
    /// Authentication runs once when this request is sent, after its URL and
    /// headers are resolved and before the first network attempt. The
    /// implementation may inspect the complete request and replace the fields
    /// it owns. It overrides the client's default authentication.
    #[must_use]
    pub fn auth(self, authentication: impl Authentication + 'static) -> Self {
        self.apply(move |request, _| {
            request
                .extensions_mut()
                .insert::<Arc<dyn Authentication>>(Arc::new(authentication));
            Ok(())
        })
    }

    /// Appends URL-encoded query parameters to the target.
    ///
    /// Existing query parameters remain in place. Serialization failures are
    /// reported when this builder is [`build`](Self::build) or
    /// [`send`](Self::send).
    #[must_use]
    pub fn query<T>(self, query_params: &T) -> Self
    where
        T: Serialize + ?Sized,
    {
        self.apply(|request, _| {
            let query = serde_urlencoded::to_string(query_params)
                .map_err(|_| Error::request("request query could not be encoded"))?;
            if query.is_empty() {
                return Ok(());
            }
            let uri = append_query(request.uri(), &query)?;
            *request.uri_mut() = uri;
            Ok(())
        })
    }

    /// Sets the total deadline for this request.
    ///
    /// This overrides the client's default and covers connection, upload,
    /// redirects, response headers, and response body reads. Pass `None` to
    /// override a bounded client default with no deadline. Zero is retained as
    /// a request error and reported by [`Self::build`] or [`Self::send`].
    #[must_use]
    pub fn timeout(self, timeout: impl Into<Option<Duration>>) -> Self {
        self.apply(move |request, _| {
            match timeout.into() {
                Some(duration) if duration.is_zero() => {
                    return Err(Error::request("request timeout must be greater than zero"));
                }
                Some(duration) => request
                    .extensions_mut()
                    .insert(TimeoutOverride::Set(duration)),
                None => request.extensions_mut().insert(TimeoutOverride::Disabled),
            };
            Ok(())
        })
    }

    /// Sets the requested HTTP version.
    ///
    /// `HTTP/2` requires TLS ALPN or cleartext HTTP/2 prior knowledge in the
    /// client's connection policy. Other versions are normalized to the
    /// protocol selected for the connection.
    #[must_use]
    pub fn version(self, version: Version) -> Self {
        self.apply(move |request, _| {
            *request.version_mut() = version;
            Ok(())
        })
    }

    /// Adds typed request metadata for application layers.
    #[must_use]
    pub fn extension<T>(self, value: T) -> Self
    where
        T: Clone + Send + Sync + 'static,
    {
        self.apply(move |request, _| {
            request.extensions_mut().insert(value);
            Ok(())
        })
    }

    /// Replaces the request body without setting a content type.
    ///
    /// Accepts [`Body`], [`bytes::Bytes`], byte vectors, strings, and byte
    /// slices through [`Into`]. If Tez previously generated a content type with
    /// a content helper or [`Self::multipart`], it is removed.
    #[must_use]
    pub fn body(self, body: impl Into<Body>) -> Self {
        self.apply(move |request, content_type| {
            replace_body(request, body.into(), None, content_type);
            Ok(())
        })
    }

    /// Streams a one-shot request body from an asynchronous reader.
    #[must_use]
    pub fn reader<R>(self, reader: R) -> Self
    where
        R: futures_io::AsyncRead + Send + Unpin + 'static,
    {
        self.body(Body::reader(reader))
    }

    /// Streams a one-shot request body with an exact byte length.
    #[must_use]
    pub fn reader_with_length<R>(self, reader: R, length: u64) -> Self
    where
        R: futures_io::AsyncRead + Send + Unpin + 'static,
    {
        self.body(Body::reader_with_length(reader, length))
    }

    /// Streams a one-shot request body from byte chunks.
    ///
    /// Chunks are forwarded without copying and the source observes connection
    /// backpressure. This helper does not set a content type.
    #[must_use]
    pub fn stream<S, D, E>(self, stream: S) -> Self
    where
        S: Stream<Item = std::result::Result<D, E>> + Send + 'static,
        D: Into<bytes::Bytes>,
        E: StdError + Send + Sync + 'static,
    {
        self.body(Body::stream(stream))
    }

    /// Streams a one-shot request body with an exact encoded length.
    ///
    /// Ending before `length` is a body error. This helper does not set a
    /// content type.
    #[must_use]
    pub fn stream_with_length<S, D, E>(self, stream: S, length: u64) -> Self
    where
        S: Stream<Item = std::result::Result<D, E>> + Send + 'static,
        D: Into<bytes::Bytes>,
        E: StdError + Send + Sync + 'static,
    {
        self.body(Body::stream_with_length(stream, length))
    }

    /// Replaces the request body with UTF-8 text.
    ///
    /// Sets `Content-Type: text/plain; charset=utf-8` unless the request already
    /// has a caller-provided content type.
    #[must_use]
    pub fn text(self, text: impl Into<String>) -> Self {
        self.content(Content::text(text))
    }

    /// Replaces the request body with UTF-8 HTML.
    ///
    /// Sets `Content-Type: text/html; charset=utf-8` unless the request already
    /// has a caller-provided content type.
    #[must_use]
    pub fn html(self, html: impl Into<String>) -> Self {
        self.content(Content::html(html))
    }

    /// Serializes a value as a JSON request body.
    ///
    /// Sets `Content-Type: application/json` unless the request already has a
    /// caller-provided content type. Serialization failures are reported when
    /// this builder is [`build`](Self::build) or [`send`](Self::send).
    #[must_use]
    pub fn json<T>(self, value: &T) -> Self
    where
        T: Serialize + ?Sized,
    {
        self.apply(|request, content_type| {
            replace_content(request, Content::json(value)?, content_type);
            Ok(())
        })
    }

    /// Serializes a value as a URL-encoded form request body.
    ///
    /// Sets `Content-Type: application/x-www-form-urlencoded` unless the
    /// request already has a caller-provided content type. Serialization
    /// failures are reported when this builder is [`build`](Self::build) or
    /// [`send`](Self::send).
    #[must_use]
    pub fn form<T>(self, value: &T) -> Self
    where
        T: Serialize + ?Sized,
    {
        self.apply(|request, content_type| {
            replace_content(request, Content::form(value)?, content_type);
            Ok(())
        })
    }

    /// Streams values as newline-delimited JSON.
    ///
    /// Each source item is serialized only when the connection is ready for
    /// another body chunk. The request is one-shot and uses
    /// `application/x-ndjson` unless the caller already set a content type.
    #[must_use]
    pub fn ndjson<S, T, E>(self, stream: S) -> Self
    where
        S: Stream<Item = std::result::Result<T, E>> + Send + 'static,
        T: Serialize,
        E: StdError + Send + Sync + 'static,
    {
        let item_limit = self.client.inner.limits.stream_item_bytes();
        self.apply(move |request, content_type| {
            replace_body(
                request,
                crate::stream::ndjson_body(stream, item_limit),
                Some(crate::stream::NDJSON_CONTENT_TYPE),
                content_type,
            );
            Ok(())
        })
    }

    /// Streams values as one JSON array.
    ///
    /// Tez retains only one serialized value at a time and emits array
    /// punctuation between items. Use [`Self::json`] for one buffered value or
    /// [`Self::ndjson`] for independently framed records.
    #[must_use]
    pub fn json_array<S, T, E>(self, stream: S) -> Self
    where
        S: Stream<Item = std::result::Result<T, E>> + Send + 'static,
        T: Serialize,
        E: StdError + Send + Sync + 'static,
    {
        let item_limit = self.client.inner.limits.stream_item_bytes();
        self.apply(move |request, content_type| {
            replace_body(
                request,
                crate::stream::json_array_body(stream, item_limit),
                Some(crate::stream::JSON_CONTENT_TYPE),
                content_type,
            );
            Ok(())
        })
    }

    /// Streams server-sent events as an HTTP request body.
    ///
    /// Event data is framed lazily with backpressure. Invalid event names or
    /// identifiers are reported as body errors while the request is sent.
    #[must_use]
    pub fn sse<S, E>(self, stream: S) -> Self
    where
        S: Stream<Item = std::result::Result<Event, E>> + Send + 'static,
        E: StdError + Send + Sync + 'static,
    {
        let item_limit = self.client.inner.limits.stream_item_bytes();
        self.apply(move |request, content_type| {
            replace_body(
                request,
                crate::stream::sse_body(stream, item_limit),
                Some(crate::stream::SSE_CONTENT_TYPE),
                content_type,
            );
            Ok(())
        })
    }

    /// Replaces the request body with an owned multipart form.
    ///
    /// This sets the form's generated `Content-Type`, replacing an earlier
    /// value so its boundary always matches the encoded body. A later explicit
    /// content-type header is rejected. Forms made from buffered parts are
    /// replayable; a wrapped streaming [`crate::Part::body`] is streamed once.
    #[must_use]
    pub fn multipart(self, multipart: Multipart) -> Self {
        self.apply(move |request, content_type_state| {
            let (body, content_type) = multipart.into_body()?;
            replace_body(request, body, None, content_type_state);
            request.headers_mut().insert(CONTENT_TYPE, content_type);
            *content_type_state = ContentTypeState::Multipart;
            Ok(())
        })
    }

    /// Returns the detached standard HTTP request assembled by this builder.
    ///
    /// This performs no I/O. Root-leading targets remain paths until a
    /// [`Client`] sends the request through a client with a base URL.
    ///
    /// # Errors
    ///
    /// Returns the first request-construction error retained by the builder.
    pub fn build(self) -> Result<Request> {
        self.request
    }

    /// Sends the assembled request through the originating client.
    ///
    /// This is equivalent to [`Client::send`] on the result of [`Self::build`].
    ///
    /// # Errors
    ///
    /// Returns an error from request construction, authentication, transport,
    /// policy handling, or the total request deadline.
    pub async fn send(self) -> Result<Response> {
        let client = self.client;
        client.send(self.build()?).await
    }

    fn apply(
        mut self,
        operation: impl FnOnce(&mut Request, &mut ContentTypeState) -> Result<()>,
    ) -> Self {
        // Fluent methods keep a request-shaped API, so retain the first error
        // and return it from build/send.
        if let Ok(request) = &mut self.request
            && let Err(error) = operation(request, &mut self.content_type)
        {
            self.request = Err(error);
        }
        self
    }

    fn content(self, content: Content) -> Self {
        self.apply(move |request, content_type| {
            replace_content(request, content, content_type);
            Ok(())
        })
    }
}

fn replace_content(request: &mut Request, content: Content, content_type: &mut ContentTypeState) {
    let (body, media_type) = content.into_parts();
    replace_body(request, body, Some(media_type), content_type);
}

fn replace_headers(
    request_headers: &mut HeaderMap,
    headers: HeaderMap,
    content_type: &mut ContentTypeState,
) -> Result<()> {
    if headers.contains_key(CONTENT_TYPE) && *content_type == ContentTypeState::Multipart {
        return Err(Error::request("multipart content type is managed by Tez"));
    }
    for name in headers.keys() {
        request_headers.remove(name);
    }

    let mut previous = None;
    for (name, value) in headers {
        let name = name.or_else(|| previous.clone()).ok_or_else(|| {
            Error::request("request header map contains an invalid repeated value")
        })?;
        if name == CONTENT_TYPE {
            *content_type = ContentTypeState::Caller;
        }
        request_headers.append(name.clone(), value);
        previous = Some(name);
    }
    Ok(())
}

fn replace_body(
    request: &mut Request,
    body: Body,
    content_type: Option<&'static str>,
    content_type_state: &mut ContentTypeState,
) {
    if matches!(
        *content_type_state,
        ContentTypeState::Generated | ContentTypeState::Multipart
    ) {
        request.headers_mut().remove(CONTENT_TYPE);
    }
    *request.body_mut() = body;
    *content_type_state = if request.headers().contains_key(CONTENT_TYPE) {
        ContentTypeState::Caller
    } else {
        ContentTypeState::Absent
    };
    if request.headers().contains_key(CONTENT_TYPE) {
        return;
    }
    if let Some(content_type) = content_type {
        request
            .headers_mut()
            .insert(CONTENT_TYPE, HeaderValue::from_static(content_type));
        *content_type_state = ContentTypeState::Generated;
    }
}

fn append_query(uri: &Uri, query: &str) -> Result<Uri> {
    let separator = if uri.query().is_some() { '&' } else { '?' };
    parse_target(&format!("{uri}{separator}{query}"))
}

fn parse_target(target: &str) -> Result<Uri> {
    if target.is_empty() {
        return Err(Error::request("request target is required"));
    }
    if target.contains('#') {
        return Err(Error::request(
            "request URL fragments are not sent to servers",
        ));
    }
    if target.starts_with('/') {
        if target.starts_with("//") {
            return Err(Error::request("request path is invalid"));
        }
        return target
            .parse()
            .map_err(|_| Error::request("request path is invalid"));
    }

    // `http::Uri` accepts the common ASCII HTTP form without URL's heavier
    // normalization and IDNA machinery. Retain URL as the standards-aware
    // fallback for inputs such as Unicode host names.
    if let Ok(uri) = target.parse::<Uri>() {
        crate::client::validate_absolute_uri(&uri)?;
        return Ok(uri);
    }

    let url = Url::parse(target).map_err(|_| Error::request("request URL is invalid"))?;
    validate_absolute_url(&url)?;
    url.as_str()
        .parse()
        .map_err(|_| Error::request("request URL is invalid"))
}

pub(crate) fn validate_absolute_url(url: &Url) -> Result<()> {
    if !matches!(url.scheme(), "http" | "https")
        || url.host_str().is_none()
        || !url.username().is_empty()
        || url.password().is_some()
        || url.fragment().is_some()
    {
        return Err(Error::request("request URL is invalid"));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Serialize)]
    struct User<'a> {
        name: &'a str,
    }

    struct FailingValue;

    impl Serialize for FailingValue {
        fn serialize<S>(&self, _serializer: S) -> std::result::Result<S::Ok, S::Error>
        where
            S: serde::Serializer,
        {
            Err(serde::ser::Error::custom("deliberately not serializable"))
        }
    }

    #[test]
    fn accepts_only_unambiguous_targets() {
        let client = Client::new().unwrap();

        assert!(
            client
                .get("https://example.com/users?active=true")
                .build()
                .is_ok()
        );
        assert!(client.get("/users?active=true").build().is_ok());
        for target in [
            "users",
            "//example.com/users",
            "ftp://example.com/users",
            "https://user:secret@example.com/users",
            "https://example.com/users#profile",
        ] {
            let result = client.get(target).build();
            assert!(matches!(result, Err(error) if error.is_request()));
        }
    }

    #[test]
    fn request_builder_modifies_the_owned_request() {
        let client = Client::new().unwrap();
        let request = client
            .post("https://example.com/users")
            .header(CONTENT_TYPE, "application/custom")
            .json(&User { name: "Ada" })
            .append_header("x-mode", "first")
            .append_header("x-mode", "second")
            .header("x-mode", "replacement")
            .form(&[("ignored", "because body is replaced")])
            .body(Body::from("final"))
            .build()
            .unwrap();

        assert_eq!(request.method(), Method::POST);
        assert_eq!(
            request.headers().get(CONTENT_TYPE).unwrap(),
            "application/custom"
        );
        assert_eq!(request.headers().get_all("x-mode").iter().count(), 1);
        assert_eq!(request.headers().get("x-mode").unwrap(), "replacement");
    }

    #[test]
    fn generated_content_type_does_not_survive_a_raw_body() {
        let client = Client::new().unwrap();
        let request = client
            .post("https://example.com/users")
            .json(&User { name: "Ada" })
            .body("raw")
            .build()
            .unwrap();

        assert!(request.headers().get(CONTENT_TYPE).is_none());
    }

    #[test]
    fn header_map_replaces_only_the_names_it_contains() {
        let client = Client::new().unwrap();
        let mut headers = HeaderMap::new();
        headers.append("x-mode", HeaderValue::from_static("first"));
        headers.append("x-mode", HeaderValue::from_static("second"));
        let request = client
            .post("https://example.com/users")
            .header("x-mode", "old")
            .header("x-untouched", "value")
            .headers(headers)
            .text("tez")
            .build()
            .unwrap();

        assert_eq!(request.headers().get_all("x-mode").iter().count(), 2);
        assert_eq!(request.headers()["x-untouched"], "value");
        assert_eq!(request.headers()[CONTENT_TYPE], "text/plain; charset=utf-8");
    }

    #[test]
    fn query_appends_parameters_and_retains_the_first_error() {
        let client = Client::new().unwrap();
        let request = client
            .post("/users?existing=true")
            .query(&[("tag", "one"), ("tag", "two")])
            .json(&FailingValue)
            .header("not a valid header name", "value")
            .build();

        let Err(error) = request else {
            panic!("a failing JSON value unexpectedly built a request");
        };
        assert!(error.is_request());
        assert!(error.to_string().contains("JSON"));
    }

    #[test]
    fn zero_timeout_is_retained_without_echoing_the_request() {
        let client = Client::new().unwrap();
        let result = client
            .get("https://example.com/users?token=secret")
            .timeout(Duration::ZERO)
            .header("not a valid header name", "secret")
            .timeout(None)
            .build();
        let Err(error) = result else {
            panic!("a zero timeout unexpectedly built a request");
        };

        assert!(error.is_request());
        assert_eq!(
            error.to_string(),
            "request timeout must be greater than zero"
        );
        assert!(!format!("{error:?}").contains("secret"));
    }
}