qubit-http 0.9.0

General-purpose HTTP infrastructure for Rust with unified client semantics, secure logging, and built-in SSE decoding
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
/*******************************************************************************
 *
 *    Copyright (c) 2025 - 2026 Haixing Hu.
 *
 *    SPDX-License-Identifier: Apache-2.0
 *
 *    Licensed under the Apache License, Version 2.0.
 *
 ******************************************************************************/
//! Unified [`HttpError`] type.

use std::error::Error;
use std::fmt;
use std::time::Duration;

use http::{
    Method,
    StatusCode,
};
use thiserror::Error;
use url::Url;

use super::RetryHint;
use crate::sanitize::SanitizedDebugger;
use crate::LogSanitizePolicy;
use qubit_error::BoxError;

use super::HttpErrorKind;

/// Unified HTTP error type.
#[derive(Error)]
#[error("{message}")]
pub struct HttpError {
    /// Error category.
    pub kind: HttpErrorKind,
    /// Optional HTTP method.
    pub method: Option<Method>,
    /// Optional request URL.
    pub url: Option<Url>,
    /// Optional response status code.
    pub status: Option<StatusCode>,
    /// Human-readable message.
    pub message: String,
    /// Optional preview of non-success response body.
    pub response_body_preview: Option<String>,
    /// Optional `Retry-After` duration parsed from a non-success response.
    pub retry_after: Option<Duration>,
    /// Optional source error.
    #[source]
    pub source: Option<BoxError>,
    /// Policy used when rendering this error with [`Debug`](fmt::Debug).
    pub log_sanitize_policy: Box<LogSanitizePolicy>,
}

impl fmt::Debug for HttpError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let debugger = SanitizedDebugger::new(&self.log_sanitize_policy);
        let url = debugger.optional_url(self.url.as_ref());
        let message = debugger.diagnostic_text(&self.message);
        let response_body_preview_len = self.response_body_preview.as_ref().map(String::len);
        formatter
            .debug_struct("HttpError")
            .field("kind", &self.kind)
            .field("method", &self.method)
            .field("url", &url)
            .field("status", &self.status)
            .field("message", &message)
            .field("response_body_preview_len", &response_body_preview_len)
            .field("retry_after", &self.retry_after)
            .field("source_present", &self.source.is_some())
            .finish()
    }
}

impl HttpError {
    /// Creates an error with kind and message; other fields are unset until chained.
    ///
    /// # Parameters
    /// - `kind`: Classification for retry logic and handling.
    /// - `message`: Human-readable description.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn new(kind: HttpErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            method: None,
            url: None,
            status: None,
            message: message.into(),
            response_body_preview: None,
            retry_after: None,
            source: None,
            log_sanitize_policy: Box::new(LogSanitizePolicy::default()),
        }
    }

    /// Attaches the HTTP method for diagnostics.
    ///
    /// # Parameters
    /// - `method`: Request method associated with the failure.
    ///
    /// # Returns
    /// `self` for chaining.
    pub fn with_method(mut self, method: &Method) -> Self {
        self.method = Some(method.clone());
        self
    }

    /// Attaches the request URL for diagnostics.
    ///
    /// # Parameters
    /// - `url`: Request URL associated with the failure.
    ///
    /// # Returns
    /// `self` for chaining.
    pub fn with_url(mut self, url: &Url) -> Self {
        self.url = Some(url.clone());
        self
    }

    /// Attaches an HTTP status code (e.g. for [`HttpErrorKind::Status`]).
    ///
    /// # Parameters
    /// - `status`: Response status code.
    ///
    /// # Returns
    /// `self` for chaining.
    pub fn with_status(mut self, status: StatusCode) -> Self {
        self.status = Some(status);
        self
    }

    /// Wraps an underlying error as the [`HttpError::source`] chain.
    ///
    /// # Parameters
    /// - `source`: Root cause (`Send + Sync + 'static`).
    ///
    /// # Returns
    /// `self` for chaining.
    pub fn with_source<E>(mut self, source: E) -> Self
    where
        E: Error + Send + Sync + 'static,
    {
        self.source = Some(Box::new(source));
        self
    }

    /// Attaches a preview of the non-success response body.
    ///
    /// # Parameters
    /// - `preview`: Truncated or summarized response body text.
    ///
    /// # Returns
    /// `self` for chaining.
    pub fn with_response_body_preview(mut self, preview: impl Into<String>) -> Self {
        self.response_body_preview = Some(preview.into());
        self
    }

    /// Attaches parsed `Retry-After` duration from a non-success response.
    ///
    /// # Parameters
    /// - `retry_after`: Parsed retry delay.
    ///
    /// # Returns
    /// `self` for chaining.
    pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
        self.retry_after = Some(retry_after);
        self
    }

    /// Attaches the log sanitization policy used by [`Debug`](fmt::Debug).
    ///
    /// # Parameters
    /// - `policy`: Policy whose custom sensitive names should be honored.
    ///
    /// # Returns
    /// `self` for chaining.
    pub fn with_log_sanitize_policy(mut self, policy: LogSanitizePolicy) -> Self {
        self.log_sanitize_policy = Box::new(policy);
        self
    }

    /// Builds [`HttpErrorKind::InvalidUrl`].
    ///
    /// # Parameters
    /// - `message`: Why the URL is invalid or cannot be resolved.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn invalid_url(message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::InvalidUrl, message)
    }

    /// Builds [`HttpErrorKind::BuildClient`] (e.g. reqwest builder failure).
    ///
    /// # Parameters
    /// - `message`: Build failure description.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn build_client(message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::BuildClient, message)
    }

    /// Builds [`HttpErrorKind::ProxyConfig`].
    ///
    /// # Parameters
    /// - `message`: Invalid proxy settings explanation.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn proxy_config(message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::ProxyConfig, message)
    }

    /// Builds [`HttpErrorKind::ConnectTimeout`].
    ///
    /// # Parameters
    /// - `message`: Timeout context.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn connect_timeout(message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::ConnectTimeout, message)
    }

    /// Builds [`HttpErrorKind::ReadTimeout`].
    ///
    /// # Parameters
    /// - `message`: Timeout context.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn read_timeout(message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::ReadTimeout, message)
    }

    /// Builds [`HttpErrorKind::WriteTimeout`].
    ///
    /// # Parameters
    /// - `message`: Timeout context.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn write_timeout(message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::WriteTimeout, message)
    }

    /// Builds [`HttpErrorKind::RequestTimeout`].
    ///
    /// # Parameters
    /// - `message`: Timeout context for the whole request deadline.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn request_timeout(message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::RequestTimeout, message)
    }

    /// Builds [`HttpErrorKind::Transport`].
    ///
    /// # Parameters
    /// - `message`: Low-level I/O or network failure description.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn transport(message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::Transport, message)
    }

    /// Builds [`HttpErrorKind::Status`] with the given status pre-filled.
    ///
    /// # Parameters
    /// - `status`: HTTP status from the response.
    /// - `message`: Additional context.
    ///
    /// # Returns
    /// New [`HttpError`] with [`HttpError::status`] set.
    pub fn status(status: StatusCode, message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::Status, message).with_status(status)
    }

    /// Builds [`HttpErrorKind::Decode`] (body or payload decoding).
    ///
    /// # Parameters
    /// - `message`: Decode failure description.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn decode(message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::Decode, message)
    }

    /// Builds [`HttpErrorKind::SseProtocol`] (framing, UTF-8, SSE line rules).
    ///
    /// # Parameters
    /// - `message`: Protocol violation description.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn sse_protocol(message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::SseProtocol, message)
    }

    /// Builds [`HttpErrorKind::SseDecode`] (e.g. JSON in SSE data).
    ///
    /// # Parameters
    /// - `message`: Payload decode failure description.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn sse_decode(message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::SseDecode, message)
    }

    /// Builds [`HttpErrorKind::Cancelled`].
    ///
    /// # Parameters
    /// - `message`: Why the operation was cancelled.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn cancelled(message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::Cancelled, message)
    }

    /// Builds [`HttpErrorKind::RetryAttemptTimeout`].
    ///
    /// # Parameters
    /// - `message`: Attempt timeout context from the retry layer.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn retry_attempt_timeout(message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::RetryAttemptTimeout, message)
    }

    /// Builds [`HttpErrorKind::RetryMaxElapsedExceeded`].
    ///
    /// # Parameters
    /// - `message`: Max elapsed / budget context from the retry layer.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn retry_max_elapsed_exceeded(message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::RetryMaxElapsedExceeded, message)
    }

    /// Builds [`HttpErrorKind::RetryAborted`].
    ///
    /// # Parameters
    /// - `message`: Why the retry policy aborted further attempts.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn retry_aborted(message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::RetryAborted, message)
    }

    /// Builds [`HttpErrorKind::Other`].
    ///
    /// # Parameters
    /// - `message`: Catch-all description.
    ///
    /// # Returns
    /// New [`HttpError`].
    pub fn other(message: impl Into<String>) -> Self {
        Self::new(HttpErrorKind::Other, message)
    }

    /// Classifies this error for retry policies ([`RetryHint`]).
    ///
    /// # Returns
    /// [`RetryHint::Retryable`] for timeouts, transport errors, and some HTTP statuses; otherwise non-retryable.
    pub fn retry_hint(&self) -> RetryHint {
        match self.kind {
            HttpErrorKind::ConnectTimeout
            | HttpErrorKind::ReadTimeout
            | HttpErrorKind::WriteTimeout
            | HttpErrorKind::RequestTimeout
            | HttpErrorKind::Transport => RetryHint::Retryable,
            HttpErrorKind::Status => {
                if let Some(status) = self.status {
                    if status == StatusCode::TOO_MANY_REQUESTS || status.is_server_error() {
                        RetryHint::Retryable
                    } else {
                        RetryHint::NonRetryable
                    }
                } else {
                    RetryHint::NonRetryable
                }
            }
            _ => RetryHint::NonRetryable,
        }
    }
}

impl From<std::io::Error> for HttpError {
    /// Maps [`std::io::Error`] to [`HttpError::transport`] with the I/O error as source.
    ///
    /// # Parameters
    /// - `error`: Underlying I/O error.
    ///
    /// # Returns
    /// Wrapped [`HttpError`].
    fn from(error: std::io::Error) -> Self {
        Self::transport(error.to_string()).with_source(error)
    }
}

impl From<reqwest::Error> for HttpError {
    /// Maps [`reqwest::Error`] to [`HttpErrorKind::BuildClient`] with chained source.
    ///
    /// # Parameters
    /// - `error`: Reqwest error to wrap.
    ///
    /// # Returns
    /// Wrapped [`HttpError`].
    fn from(error: reqwest::Error) -> Self {
        let error = error.without_url();
        Self::build_client(format!("Failed to build reqwest client: {}", error)).with_source(error)
    }
}