tez 0.0.0

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
use std::{convert::Infallible, error, fmt};

use url::Url;

use crate::redact::sanitize_url;

/// Stable classification for failures returned by `tez`.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ErrorKind {
    /// Request shape or header validation failed.
    Request,
    /// URL parsing, resolution, or policy validation failed.
    Url,
    /// The required asynchronous runtime is unavailable.
    Runtime,
    /// Name resolution failed.
    Dns,
    /// A connection could not be established.
    Connect,
    /// TLS configuration or negotiation failed.
    Tls,
    /// Proxy configuration or communication failed.
    Proxy,
    /// A request, connection, or body deadline expired.
    Timeout,
    /// Redirect processing failed.
    Redirect,
    /// Retry processing failed.
    Retry,
    /// Body input or output failed.
    BodyIo,
    /// A configured decoded-body limit was exceeded.
    BodyLimit,
    /// Response text, content coding, or structured decoding failed.
    Decoding,
    /// A transport failed without a more specific portable classification.
    Transport,
}

/// Structured redirect failure details.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RedirectError {
    /// A configured hop ceiling was reached before issuing another request.
    TooManyHops {
        /// The maximum number of followed hops.
        limit: u32,
        /// The number of hops already followed.
        followed: u32,
    },
    /// A previously visited method and URL pair would be repeated.
    Cycle {
        /// The number of hops followed before detecting the cycle.
        followed: u32,
    },
}

/// Structured retry failure details.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RetryError {
    /// Every configured attempt was consumed by retryable pre-header failures.
    Exhausted {
        /// Total attempts made, including the first.
        attempts: u8,
        /// Stable classification of the final attempt failure.
        last: ErrorKind,
    },
}

/// Opaque error returned by `tez` builders and clients.
///
/// Inspect [`Error::kind`] and the optional structured redirect/retry metadata.
/// Stored messages are deliberately transport-neutral. In particular, an
/// underlying backend error is never exposed as a source or downcast target.
#[derive(Clone)]
pub struct Error {
    kind: ErrorKind,
    message: String,
    redirect: Option<RedirectError>,
    retry: Option<RetryError>,
    sanitized_url: Option<String>,
}

/// Result type used by `tez`.
pub type Result<T> = std::result::Result<T, Error>;

impl Error {
    /// Creates a transport-neutral error with a fixed redacted message.
    ///
    /// This constructor is intended for custom [`crate::BodySource`]
    /// implementations.
    #[must_use]
    pub fn from_kind(kind: ErrorKind) -> Self {
        Self::new(kind, default_message(kind))
    }

    pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
        let message = message.into();
        Self::with_message(kind, format!("{}: {message}", KindDisplay(kind)))
    }

    fn with_message(kind: ErrorKind, message: String) -> Self {
        Self {
            kind,
            message,
            redirect: None,
            retry: None,
            sanitized_url: None,
        }
    }

    pub(crate) fn url(reason: &'static str) -> Self {
        Self::invalid_url(reason.to_owned())
    }

    pub(crate) fn invalid_request(reason: &'static str) -> Self {
        Self::with_message(ErrorKind::Request, format!("invalid request: {reason}"))
    }

    pub(crate) fn invalid_response(reason: &'static str) -> Self {
        Self::with_message(ErrorKind::Transport, format!("invalid response: {reason}"))
    }

    fn invalid_url(reason: String) -> Self {
        Self::with_message(ErrorKind::Url, format!("invalid URL: {reason}"))
    }

    fn invalid_header_name(reason: String) -> Self {
        Self::with_message(ErrorKind::Request, format!("invalid header name: {reason}"))
    }

    fn invalid_header_value(reason: String) -> Self {
        Self::with_message(
            ErrorKind::Request,
            format!("invalid header value: {reason}"),
        )
    }

    fn form(reason: String) -> Self {
        Self::with_message(ErrorKind::Request, format!("form error: {reason}"))
    }

    fn io(reason: String) -> Self {
        Self::with_message(ErrorKind::BodyIo, format!("body I/O error: {reason}"))
    }

    fn classified(
        kind: ErrorKind,
        message: impl Into<String>,
        redirect: Option<RedirectError>,
        retry: Option<RetryError>,
    ) -> Self {
        let mut error = Self::new(kind, message);
        error.redirect = redirect;
        error.retry = retry;
        error
    }

    /// Returns the stable failure classification.
    #[must_use]
    pub fn kind(&self) -> ErrorKind {
        self.kind
    }

    /// Returns structured redirect details when this is a redirect failure.
    #[must_use]
    pub fn redirect_error(&self) -> Option<RedirectError> {
        self.redirect
    }

    /// Returns structured retry details when configured attempts were exhausted.
    #[must_use]
    pub fn retry_error(&self) -> Option<RetryError> {
        self.retry
    }

    /// Returns a URL with userinfo, query, and fragment removed, when present.
    #[must_use]
    pub fn sanitized_url(&self) -> Option<&str> {
        self.sanitized_url.as_deref()
    }

    pub(crate) fn from_reqwest(error: reqwest::Error) -> Self {
        let mut source = error::Error::source(&error);
        while let Some(current) = source {
            if let Some(owned) = current.downcast_ref::<Self>() {
                return owned.clone();
            }
            source = current.source();
        }

        let kind = if error.is_timeout() {
            ErrorKind::Timeout
        } else if let Some(kind) = classify_backend_sources(&error) {
            kind
        } else if error.is_connect() {
            ErrorKind::Connect
        } else if error.is_builder() {
            ErrorKind::Request
        } else if error.is_decode() {
            ErrorKind::Decoding
        } else if error.is_body() {
            ErrorKind::BodyIo
        } else if error.is_redirect() {
            ErrorKind::Redirect
        } else {
            ErrorKind::Transport
        };

        let message = match kind {
            ErrorKind::Timeout => "request deadline exceeded",
            ErrorKind::Connect => "connection failed",
            ErrorKind::Dns => "DNS resolution failed",
            ErrorKind::Tls => "TLS negotiation failed",
            ErrorKind::Proxy => "proxy communication failed",
            ErrorKind::Request => "request could not be encoded",
            ErrorKind::Decoding => "response decoding failed",
            ErrorKind::BodyIo => "body stream failed",
            ErrorKind::Redirect => "redirect processing failed",
            _ => "request transport failed",
        };

        let mut classified = Self::new(kind, message);
        if let Some(url) = error.url() {
            classified.set_sanitized_url(url);
        }
        classified
    }

    pub(crate) fn proxy(_error: impl error::Error + Send + Sync + 'static) -> Self {
        Self::new(ErrorKind::Proxy, "proxy configuration is invalid")
    }

    pub(crate) fn body_limit(limit: usize) -> Self {
        Self::new(
            ErrorKind::BodyLimit,
            format!("decoded body exceeded the {limit}-byte limit"),
        )
    }

    pub(crate) fn timeout(message: &'static str) -> Self {
        Self::new(ErrorKind::Timeout, message)
    }

    pub(crate) fn redirect(error: RedirectError, url: &Url) -> Self {
        let message = match error {
            RedirectError::TooManyHops { .. } => "redirect hop limit exceeded",
            RedirectError::Cycle { .. } => "redirect cycle detected",
        };
        let mut result = Self::classified(ErrorKind::Redirect, message, Some(error), None);
        result.set_sanitized_url(url);
        result
    }

    pub(crate) fn retry_exhausted(attempts: u8, last_kind: ErrorKind, url: &Url) -> Self {
        let retry = RetryError::Exhausted {
            attempts,
            last: last_kind,
        };
        let mut result = Self::classified(
            ErrorKind::Retry,
            format!(
                "retry attempts exhausted after {attempts} attempts; last failure was {}",
                KindDisplay(last_kind)
            ),
            None,
            Some(retry),
        );
        result.set_sanitized_url(url);
        result
    }

    fn set_sanitized_url(&mut self, url: &Url) {
        self.sanitized_url = Some(sanitize_url(url));
    }
}

fn classify_backend_sources(error: &reqwest::Error) -> Option<ErrorKind> {
    let mut source = error::Error::source(error);
    while let Some(current) = source {
        if let Some(kind) = classify_typed_source(current) {
            return Some(kind);
        }
        source = current.source();
    }
    None
}

fn classify_typed_source(source: &(dyn error::Error + 'static)) -> Option<ErrorKind> {
    #[cfg(feature = "rustls")]
    if source.downcast_ref::<rustls::Error>().is_some() {
        return Some(ErrorKind::Tls);
    }

    // Hyper-rustls wraps its typed rustls failure in one or more `io::Error`
    // values. `io::Error::source` does not expose that inner value, so follow
    // the typed `get_ref` chain explicitly. Never infer TLS from an I/O kind:
    // DNS and connector failures can use the same broad `Other` kind.
    source
        .downcast_ref::<std::io::Error>()
        .and_then(std::io::Error::get_ref)
        .and_then(|inner| classify_typed_source(inner))
}

impl fmt::Debug for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Error")
            .field("kind", &self.kind())
            .field("message", &self.to_string())
            .field("redirect", &self.redirect_error())
            .field("retry", &self.retry_error())
            .field("sanitized_url", &self.sanitized_url())
            .finish()
    }
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)?;
        if let Some(url) = &self.sanitized_url {
            write!(formatter, " ({url})")?;
        }
        Ok(())
    }
}

impl error::Error for Error {}

impl From<url::ParseError> for Error {
    fn from(error: url::ParseError) -> Self {
        Self::invalid_url(error.to_string())
    }
}

impl From<http::header::InvalidHeaderName> for Error {
    fn from(error: http::header::InvalidHeaderName) -> Self {
        Self::invalid_header_name(error.to_string())
    }
}

impl From<http::header::InvalidHeaderValue> for Error {
    fn from(error: http::header::InvalidHeaderValue) -> Self {
        Self::invalid_header_value(error.to_string())
    }
}

impl From<Infallible> for Error {
    fn from(error: Infallible) -> Self {
        match error {}
    }
}

impl From<serde_urlencoded::ser::Error> for Error {
    fn from(_error: serde_urlencoded::ser::Error) -> Self {
        Self::form("form serialization failed".to_owned())
    }
}

impl From<std::io::Error> for Error {
    fn from(error: std::io::Error) -> Self {
        // Preserve the portable kind but not file names or backend details.
        Self::io(error.kind().to_string())
    }
}

struct KindDisplay(ErrorKind);

fn default_message(kind: ErrorKind) -> &'static str {
    match kind {
        ErrorKind::Request => "request failed",
        ErrorKind::Url => "URL processing failed",
        ErrorKind::Runtime => "asynchronous runtime is unavailable",
        ErrorKind::Dns => "DNS resolution failed",
        ErrorKind::Connect => "connection failed",
        ErrorKind::Tls => "TLS operation failed",
        ErrorKind::Proxy => "proxy operation failed",
        ErrorKind::Timeout => "operation timed out",
        ErrorKind::Redirect => "redirect processing failed",
        ErrorKind::Retry => "retry processing failed",
        ErrorKind::BodyIo => "body stream failed",
        ErrorKind::BodyLimit => "body limit exceeded",
        ErrorKind::Decoding => "response decoding failed",
        ErrorKind::Transport => "transport failed",
    }
}

impl fmt::Display for KindDisplay {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let value = match self.0 {
            ErrorKind::Request => "request error",
            ErrorKind::Url => "URL error",
            ErrorKind::Runtime => "runtime error",
            ErrorKind::Dns => "DNS error",
            ErrorKind::Connect => "connect error",
            ErrorKind::Tls => "TLS error",
            ErrorKind::Proxy => "proxy error",
            ErrorKind::Timeout => "timeout",
            ErrorKind::Redirect => "redirect error",
            ErrorKind::Retry => "retry error",
            ErrorKind::BodyIo => "body I/O error",
            ErrorKind::BodyLimit => "body limit error",
            ErrorKind::Decoding => "decoding error",
            ErrorKind::Transport => "transport error",
        };
        formatter.write_str(value)
    }
}

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

    #[test]
    fn it_errors_have_stable_classifications() {
        for kind in [
            ErrorKind::Request,
            ErrorKind::Url,
            ErrorKind::Runtime,
            ErrorKind::Dns,
            ErrorKind::Connect,
            ErrorKind::Tls,
            ErrorKind::Proxy,
            ErrorKind::Timeout,
            ErrorKind::Redirect,
            ErrorKind::Retry,
            ErrorKind::BodyIo,
            ErrorKind::BodyLimit,
            ErrorKind::Decoding,
            ErrorKind::Transport,
        ] {
            assert_eq!(Error::from_kind(kind).kind(), kind);
        }

        assert_eq!(
            Error::invalid_request("missing URL").kind(),
            ErrorKind::Request
        );
        assert_eq!(Error::body_limit(4).kind(), ErrorKind::BodyLimit);
        assert_eq!(Error::timeout("late").kind(), ErrorKind::Timeout);
    }

    #[test]
    fn it_error_urls_remove_userinfo_query_and_fragment() {
        let url = Url::parse("https://user:pass@example.com/path?token=secret#part").unwrap();
        let error = Error::redirect(RedirectError::Cycle { followed: 2 }, &url);
        let debug = format!("{error:?}");

        assert_eq!(error.sanitized_url(), Some("https://example.com/path"));
        assert!(!debug.contains("user"));
        assert!(!debug.contains("pass"));
        assert!(!debug.contains("secret"));
    }

    #[test]
    fn it_does_not_expose_internal_error_sources() {
        use std::error::Error as _;

        let error = Error::from_kind(ErrorKind::Transport);

        assert!(error.source().is_none());
        assert!(!format!("{error:?}").contains("reqwest"));
    }
}