http_extensions 0.4.1

Shared HTTP types and extension traits for clients and servers.
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use std::borrow::Cow;
use std::time::Duration;

use http::StatusCode;
use http::header::{InvalidHeaderValue, MaxSizeReached};
use http::method::InvalidMethod;
use http::status::InvalidStatusCode;
use http::uri::{InvalidUri, InvalidUriParts};
use ohno::{ErrorLabel, Labeled};
use recoverable::{Recovery, RecoveryInfo};
use thread_aware::ThreadAware;
use thread_aware::affinity::Affinity;

use crate::HttpRequest;
use crate::error_labels::{
    LABEL_BODY_SIZE_LIMIT_REACHED, LABEL_BODY_TIMEOUT, LABEL_HEADER_VALUE_INVALID, LABEL_HTTP_ERROR, LABEL_IO, LABEL_METHOD_INVALID,
    LABEL_RESPONSE_TIMEOUT, LABEL_RESPONSE_UNSUCCESSFUL, LABEL_STATUS_CODE_INVALID, LABEL_UNAVAILABLE, LABEL_URI_INVALID, LABEL_VALIDATION,
};
use crate::http_utils::SyncHolder;

/// A convenient type alias for results in this crate.
pub type Result<T> = std::result::Result<T, HttpError>;

/// A unified HTTP error type.
///
/// Combines various HTTP-related errors into a single type with useful features:
///
/// - Captures backtraces automatically
/// - Tells you if an error is temporary (transient) or permanent
/// - Works with `http` crate errors out of the box
/// - Carries an [`ErrorLabel`] for metrics and logging (see its docs for
///   cardinality requirements)
///
/// # Examples
///
/// ```
/// # use http_extensions::HttpError;
/// # use recoverable::{Recovery, RecoveryKind};
///
/// fn check_error(error: HttpError) {
///     // See if we can retry
///     if error.recovery().kind() == RecoveryKind::Retry {
///         println!("temporary error, let's retry");
///     }
/// }
/// # check_error(HttpError::unavailable("test"));
/// ```
///
/// # Error Interoperability
///
/// Works with many error types through `From` implementations, so you can use
/// the `?` operator with them. Also tells you if errors can be recovered from.
///
/// ## Standard Library Errors
///
/// - [`std::io::Error`] - Auto-classified as retry, unavailable, or never based on error kind
/// - [`std::convert::Infallible`] - Handled for pattern matching completeness
///
/// ## Works with `http` crate
///
/// Converts from these error types automatically:
///
/// - `http::Error` - General HTTP errors
/// - `http::uri::InvalidUri` and `http::uri::InvalidUriParts` - Bad URIs
/// - `http::header::InvalidHeaderValue` - Invalid headers
/// - `http::method::InvalidMethod` - Invalid HTTP methods
/// - `http::status::InvalidStatusCode` - Invalid status codes
/// - `http::header::MaxSizeReached` - Headers too large
///
/// ```
/// # use http_extensions::HttpError;
///
/// let uri_error = "invalid uri".parse::<http::Uri>().unwrap_err();
/// let error = HttpError::from(uri_error);
///
/// assert!(error.to_string().starts_with("invalid uri character"));
/// ```
///
/// ## Works with `templated_uri` crate
///
/// - `templated_uri::UriError` - Invalid URI template parameters
///
/// ## Custom Errors
///
/// Custom errors can be wrapped using [`HttpError::other()`]:
///
/// ```
/// # use http_extensions::{HttpError};
/// # use recoverable::RecoveryInfo;
/// # use std::fmt;
/// # #[derive(Debug)]
/// # struct CustomError;
/// # impl std::error::Error for CustomError {}
/// # impl fmt::Display for CustomError {
/// #    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
/// #        write!(f, "custom error")
/// #    }
/// # }
///
/// let custom_error = CustomError;
/// let http_error = HttpError::other(custom_error, RecoveryInfo::never(), "custom");
/// ```
#[ohno::error]
#[from(
    http::Error(label: LABEL_HTTP_ERROR, recovery: RecoveryInfo::never()),
    InvalidUriParts(label: LABEL_URI_INVALID, recovery: RecoveryInfo::never()),
    InvalidUri(label: LABEL_URI_INVALID, recovery: RecoveryInfo::never()),
    InvalidHeaderValue(label: LABEL_HEADER_VALUE_INVALID, recovery: RecoveryInfo::never()),
    InvalidMethod(label: LABEL_METHOD_INVALID, recovery: RecoveryInfo::never()),
    InvalidStatusCode(label: LABEL_STATUS_CODE_INVALID, recovery: RecoveryInfo::never()),
    MaxSizeReached(label: LABEL_BODY_SIZE_LIMIT_REACHED, recovery: RecoveryInfo::never()),
    std::io::Error(label: LABEL_IO, recovery: RecoveryInfo::from(error.kind())),
    templated_uri::UriError(label: error.label().clone(), recovery: RecoveryInfo::never())
)]
pub struct HttpError {
    label: ErrorLabel,
    recovery: RecoveryInfo,
    // NOTE: Boxed to keep the size of HttpError small and wrapped
    // in SyncHolder to make HttpError Sync even if HttpRequest is not Sync.
    request: Option<SyncHolder<Box<HttpRequest>>>,
}

impl ThreadAware for HttpError {
    fn relocate(&mut self, _source: Option<Affinity>, _destination: Affinity) {
        // no thread-local state to relocate
    }
}

impl HttpError {
    /// Wraps any error type into an [`HttpError`] with the given `recovery`
    /// strategy and a `label` for metrics and logging.
    ///
    /// The `label` accepts anything that implements `Into<ErrorLabel>`.
    /// See [`ErrorLabel`] docs for cardinality requirements.
    pub fn other(error: impl Into<Box<dyn std::error::Error + Send + Sync>>, recovery: RecoveryInfo, label: impl Into<ErrorLabel>) -> Self {
        Self::caused_by(label, recovery, None, error)
    }

    /// Wraps an error that implements [`Recovery`] into an [`HttpError`],
    /// extracting recovery information automatically via [`Recovery::recovery()`].
    ///
    /// The `label` accepts anything that implements `Into<ErrorLabel>`.
    /// See [`ErrorLabel`] docs for cardinality requirements.
    pub fn other_with_recovery<E>(error: E, label: impl Into<ErrorLabel>) -> Self
    where
        E: std::error::Error + Send + Sync + Recovery + 'static,
    {
        let recovery = error.recovery();

        Self::other(error, recovery, label)
    }

    /// Creates an error from an unsuccessful HTTP status `code` with the given
    /// `recovery` strategy.
    #[must_use]
    pub fn invalid_status_code(code: StatusCode, recovery: RecoveryInfo) -> Self {
        Self::other(
            format!("the response was not successful, status code: {}", code.as_u16()),
            recovery,
            LABEL_RESPONSE_UNSUCCESSFUL,
        )
    }

    /// Creates a validation error.
    ///
    /// This is a convenience method to create a validation error with a standard message format.
    /// The error is classified as non-retryable.
    #[must_use]
    pub fn validation(msg: impl Into<Cow<'static, str>>) -> Self {
        Self::other(msg.into(), RecoveryInfo::never(), LABEL_VALIDATION)
    }

    /// Like [`validation`](Self::validation) but with a custom label for finer-grained telemetry.
    #[must_use]
    pub(crate) fn validation_with_label(msg: impl Into<Cow<'static, str>>, label: impl Into<ErrorLabel>) -> Self {
        Self::other(msg.into(), RecoveryInfo::never(), label)
    }

    /// Creates an error that indicates a service is currently unavailable.
    ///
    /// This indicates that the service is currently down, unreachable, or
    /// experiencing an increased rate of failures.
    ///
    /// # Examples
    ///
    /// Reject the execution and attach the request for possible retry later. A typical case for
    /// this is an open circuit breaker that rejects executions without consuming the request.
    ///
    /// ```
    /// # fn main() {
    /// # #[cfg(feature = "test-util")] {
    /// # use http_extensions::{HttpError, HttpRequest, HttpRequestBuilder};
    /// # let http_request = HttpRequestBuilder::new_fake()
    /// #     .get("https://example.com")
    /// #     .build()
    /// #     .unwrap();
    /// // attach the request
    /// let mut error = HttpError::unavailable("service is down").with_request(http_request);
    /// // later you can try to extract the request
    /// if let Some(request) = error.take_request() {
    ///     // execute the retry
    ///     execute_retry(request);
    /// }
    /// # fn execute_retry(http_request: HttpRequest) {}
    /// # }
    /// # }
    /// ```
    #[must_use]
    pub fn unavailable(msg: impl Into<Cow<'static, str>>) -> Self {
        Self::other(msg.into(), RecoveryInfo::unavailable(), LABEL_UNAVAILABLE)
    }

    /// Creates a timeout error with the specified duration.
    ///
    /// This is a convenience method to create a timeout error with a standard message format.
    /// The error is classified as retryable.
    #[must_use]
    pub fn timeout(duration: Duration) -> Self {
        Self::other(
            format!(
                "request timed out while receiving the response, timeout: {}ms",
                duration.as_millis()
            ),
            RecoveryInfo::retry(),
            LABEL_RESPONSE_TIMEOUT,
        )
    }

    /// Creates a timeout error for body data retrieval.
    ///
    /// Used when streaming body data is not fully received within the configured timeout.
    /// The error is classified as retryable.
    #[must_use]
    pub(crate) fn timeout_for_body(duration: Duration) -> Self {
        Self::other(
            format!("body data was not fully received, timeout: {}ms", duration.as_millis()),
            RecoveryInfo::retry(),
            LABEL_BODY_TIMEOUT,
        )
    }

    /// Attaches HTTP request to this error.
    ///
    /// Useful for rejected requests that you may want to retry later.
    #[must_use]
    pub fn with_request(mut self, request: HttpRequest) -> Self {
        self.request = Some(SyncHolder::new(Box::new(request)));
        self
    }

    /// Extracts the HTTP request from this error, if any.
    ///
    /// The request can be extracted only once. Further calls return `None`.
    /// The request can be attached to the error by using [`HttpError::with_request`]
    /// method.
    #[must_use]
    pub fn take_request(&mut self) -> Option<HttpRequest> {
        self.request.take().map(|holder| *holder.into_inner())
    }

    /// Resolves the error label for pre-defined set of errors.
    ///
    /// This method recognizes the following error types:
    /// - [`HttpError`]
    /// - [`JsonError`][crate::json::JsonError]
    /// - [`std::io::Error`]
    #[cfg(test)]
    pub(crate) fn resolve_error_label(error: &(dyn std::error::Error + 'static)) -> Option<ErrorLabel> {
        if let Some(err) = error.downcast_ref::<Self>() {
            return Some(err.label().clone());
        }

        if let Some(err) = error.downcast_ref::<crate::json::JsonError>() {
            return Some(err.label().clone());
        }

        if let Some(err) = error.downcast_ref::<std::io::Error>() {
            return Some(err.kind().into());
        }

        None
    }
}

impl Recovery for HttpError {
    fn recovery(&self) -> RecoveryInfo {
        self.recovery.clone()
    }
}

impl Labeled for HttpError {
    fn label(&self) -> &ErrorLabel {
        &self.label
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use std::fmt::{Debug, Display};

    use futures::executor::block_on;
    use ohno::ErrorExt;
    use recoverable::RecoveryKind;
    use serde::Deserialize;
    use thread_aware::affinity::pinned_affinities;

    use super::*;
    use crate::{FakeHandler, HttpRequestBuilder, HttpRequestBuilderExt, HttpResponseBuilder, JsonError};

    static_assertions::assert_impl_all!(HttpError: std::error::Error, Send, Sync, Display, Debug, ThreadAware);

    #[test]
    fn assert_size_small() {
        // Keep the size of HttpError small to avoid excessive stack usage.
        assert_eq!(size_of::<HttpError>(), 64);
    }

    #[test]
    fn validation_ok() {
        let error = HttpError::validation("my-validation");

        assert_eq!(error.message(), "my-validation");
        assert_eq!(error.label(), "validation");
        assert_eq!(error.recovery(), RecoveryInfo::never());
    }

    #[test]
    fn invalid_status_code_ok() {
        let error = HttpError::invalid_status_code(StatusCode::NOT_FOUND, RecoveryInfo::unknown());

        assert_eq!(error.message(), "the response was not successful, status code: 404");
        assert_eq!(error.label(), "response_unsuccessful");
        assert_eq!(error.recovery(), RecoveryInfo::unknown());
    }

    #[test]
    fn other_method_wraps_custom_errors() {
        let io_error = std::io::Error::other("custom error");
        let error = HttpError::other(io_error, RecoveryInfo::retry(), "custom");

        assert_eq!(error.message(), "custom error");
        assert_eq!(error.label(), "custom");
        assert_eq!(error.recovery(), RecoveryInfo::retry());
    }

    #[test]
    fn http_constructor() {
        let invalid_method = http::Method::from_bytes(b"INVALID METHOD").unwrap_err();
        let error = HttpError::from(invalid_method);
        assert_eq!(error.recovery(), RecoveryInfo::never());
        assert_eq!(error.label(), "method_invalid");
    }

    #[test]
    fn from_io() {
        let error = HttpError::from(std::io::Error::other("test"));
        assert_eq!(error.message(), "test");
        assert_eq!(error.recovery(), RecoveryInfo::never());
        assert_eq!(error.label(), "io");

        let error = HttpError::from(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "some message"));
        assert_eq!(error.recovery(), RecoveryInfo::retry());
        assert_eq!(error.label(), "io");
    }

    #[test]
    fn from_uri_errors() {
        let uri_error = "invalid uri with spaces".parse::<http::Uri>().unwrap_err();
        let error = HttpError::from(uri_error);
        assert_eq!(error.recovery(), RecoveryInfo::never());
        assert_eq!(error.label(), "uri_invalid");
    }

    #[test]
    fn from_uri_template_validation_error() {
        let validation_error = templated_uri::UriError::from("not a valid uri".parse::<http::Uri>().unwrap_err());
        let error = HttpError::from(validation_error);
        assert_eq!(error.recovery(), RecoveryInfo::never());
        assert_eq!(error.label(), "uri_invalid");
    }

    #[test]
    fn from_invalid_header_value() {
        let header_error = http::header::HeaderValue::from_bytes(&[0x00]).unwrap_err();
        let error = HttpError::from(header_error);
        assert_eq!(error.recovery(), RecoveryInfo::never());
        assert_eq!(error.label(), "header_value_invalid");
    }

    #[test]
    fn from_invalid_status_code() {
        let status_error = StatusCode::from_u16(9999).unwrap_err();
        let error = HttpError::from(status_error);
        assert_eq!(error.recovery(), RecoveryInfo::never());
        assert_eq!(error.label(), "status_code_invalid");
    }

    #[test]
    fn from_http_error() {
        let http_error = http::Request::builder().header("invalid\nheader", "value").body(()).unwrap_err();
        let error = HttpError::from(http_error);
        assert_eq!(error.recovery(), RecoveryInfo::never());
        assert_eq!(error.label(), "http_error");
    }

    #[test]
    fn assert_from() {
        static_assertions::assert_impl_all!(HttpError: From<http::Error>);
        static_assertions::assert_impl_all!(HttpError: From<InvalidUri>);
        static_assertions::assert_impl_all!(HttpError: From<InvalidUriParts>);
        static_assertions::assert_impl_all!(HttpError: From<InvalidHeaderValue>);
        static_assertions::assert_impl_all!(HttpError: From<InvalidMethod>);
        static_assertions::assert_impl_all!(HttpError: From<InvalidStatusCode>);
        static_assertions::assert_impl_all!(HttpError: From<MaxSizeReached>);
        static_assertions::assert_impl_all!(HttpError: From<templated_uri::UriError>);
        static_assertions::assert_impl_all!(HttpError: From<std::io::Error>);
    }

    #[test]
    fn assert_from_infallible() {
        static_assertions::assert_impl_all!(HttpError: From<std::convert::Infallible>);
    }

    #[test]
    fn timeout_error() {
        let duration = Duration::from_millis(1500);
        let timeout_error = HttpError::timeout(duration);

        assert_eq!(timeout_error.recovery(), RecoveryInfo::retry());
        assert_eq!(
            timeout_error.message(),
            "request timed out while receiving the response, timeout: 1500ms"
        );
        assert_eq!(timeout_error.label(), "response_timeout");
    }

    #[test]
    fn timeout_for_body_error() {
        let duration = Duration::from_millis(2500);
        let error = HttpError::timeout_for_body(duration);

        assert_eq!(error.recovery(), RecoveryInfo::retry());
        assert_eq!(error.message(), "body data was not fully received, timeout: 2500ms");
        assert_eq!(error.label(), "body_timeout");
    }

    #[test]
    fn unavailable_error() {
        let unavailable_error = HttpError::unavailable("service is down");

        assert_eq!(unavailable_error.recovery(), RecoveryInfo::unavailable());
        assert_eq!(unavailable_error.message(), "service is down");
        assert_eq!(unavailable_error.label(), "unavailable");
    }

    #[test]
    fn other_with_recovery() {
        let existing_error = HttpError::validation("base error");
        let error = HttpError::other_with_recovery(existing_error, "permission");

        assert!(error.message().contains("base error"));
        assert_eq!(error.label(), "permission");
        assert_eq!(error.recovery().kind(), RecoveryKind::Never);
    }

    #[test]
    fn rejected_request_ok() {
        let request = HttpRequestBuilder::new_fake().uri("https://dummy").build().unwrap();

        let mut error = HttpError::validation("rejection").with_request(request);

        assert_eq!(error.take_request().unwrap().uri().to_string(), "https://dummy/");

        // Later calls should return None
        assert!(error.take_request().is_none());
    }

    #[test]
    fn relocated_preserves_error() {
        let affinity = pinned_affinities(&[1])[0];
        let mut error = HttpError::validation("relocated test");

        error.relocate(None, affinity);

        assert_eq!(error.message(), "relocated test");
        assert_eq!(error.label(), "validation");
    }

    #[test]
    fn resolve_label() {
        // HttpError variant
        let http_err = HttpError::validation("bad input");
        assert_eq!(HttpError::resolve_error_label(&http_err).unwrap(), "validation");

        // JsonError variant
        let json_err = JsonError::deserialization(serde_json::Error::io(std::io::Error::other("bad json")));
        assert_eq!(HttpError::resolve_error_label(&json_err).unwrap(), "json_deserialization");

        // std::io::Error variant
        let io_err = std::io::Error::from(std::io::ErrorKind::ConnectionReset);
        assert_eq!(HttpError::resolve_error_label(&io_err).unwrap(), "connection_reset");

        // Unrecognized error returns None
        let unknown: Box<dyn std::error::Error + Send + Sync> = "unknown".into();
        assert!(HttpError::resolve_error_label(unknown.as_ref()).is_none());
    }

    #[test]
    fn error_chain() {
        #[derive(Debug, Deserialize)]
        struct Person;

        let handler = FakeHandler::from_sync_handler(|_| HttpResponseBuilder::new_fake().text("invalid json").build());

        let err = block_on(handler.request_builder().uri("https://dummy.com").fetch_json_owned::<Person>()).unwrap_err();

        let label = ErrorLabel::from_error_chain(&err, HttpError::resolve_error_label);
        assert_eq!(label, "json.json_deserialization");
    }
}