oxihttp-core 0.1.1

OxiHTTP core types: error and http crate re-exports.
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
//! Error types for the OxiHTTP stack.

use std::sync::Arc;

use thiserror::Error;

/// Top-level error type for the OxiHTTP stack.
#[derive(Debug, Clone, Error)]
pub enum OxiHttpError {
    /// An invalid URI was provided.
    #[error("invalid URI: {0}")]
    InvalidUri(Arc<http::uri::InvalidUri>),

    /// An HTTP protocol error.
    #[error("HTTP error: {0}")]
    Http(Arc<http::Error>),

    /// A hyper transport error, captured as a string to avoid exposing hyper's types.
    #[error("hyper error: {0}")]
    Hyper(String),

    /// An I/O error.
    #[error("I/O error: {0}")]
    Io(Arc<std::io::Error>),

    /// An error reading or processing the response body.
    #[error("body error: {0}")]
    Body(String),

    /// A request or connect timeout expired.
    #[error("timeout: {0}")]
    Timeout(String),

    /// A redirect loop or limit was reached.
    #[error("redirect error: {0}")]
    Redirect(String),

    /// A TLS-specific error from oxitls.
    #[error("TLS error: {0}")]
    Tls(String),

    /// A DNS resolution failure.
    #[error("DNS error: {0}")]
    Dns(String),

    /// Connection pool exhaustion.
    #[error("connection pool error: {0}")]
    ConnectionPool(String),

    /// JSON serialization/deserialization error.
    #[error("JSON error: {0}")]
    Json(String),

    /// URL-encoded form error.
    #[error("form encoding error: {0}")]
    FormEncoding(String),

    /// An invalid header name or value.
    #[error("invalid header: {0}")]
    InvalidHeader(String),

    /// A server-specific error.
    #[error("server error: {0}")]
    Server(String),

    /// Route not found (404).
    #[error("route not found: {method} {path}")]
    RouteNotFound {
        /// The HTTP method of the request.
        method: String,
        /// The path that was not found.
        path: String,
    },

    /// Method not allowed (405).
    #[error("method not allowed: {method} {path}")]
    MethodNotAllowed {
        /// The HTTP method that is not allowed.
        method: String,
        /// The path where the method is not allowed.
        path: String,
    },

    /// An HTTP/3 / QUIC transport error (oxiquic-h3).
    #[error("HTTP/3 error: {0}")]
    H3(String),
}

impl From<http::uri::InvalidUri> for OxiHttpError {
    fn from(e: http::uri::InvalidUri) -> Self {
        OxiHttpError::InvalidUri(Arc::new(e))
    }
}

impl From<std::io::Error> for OxiHttpError {
    fn from(e: std::io::Error) -> Self {
        OxiHttpError::Io(Arc::new(e))
    }
}

impl From<http::Error> for OxiHttpError {
    fn from(e: http::Error) -> Self {
        OxiHttpError::Http(Arc::new(e))
    }
}

#[cfg(feature = "tls")]
impl From<oxitls_core::TlsError> for OxiHttpError {
    fn from(e: oxitls_core::TlsError) -> Self {
        OxiHttpError::Tls(e.to_string())
    }
}

impl OxiHttpError {
    /// Returns the HTTP status code associated with this error, if any.
    pub fn status_code(&self) -> Option<http::StatusCode> {
        match self {
            Self::RouteNotFound { .. } => Some(http::StatusCode::NOT_FOUND),
            Self::MethodNotAllowed { .. } => Some(http::StatusCode::METHOD_NOT_ALLOWED),
            Self::Timeout(_) => Some(http::StatusCode::REQUEST_TIMEOUT),
            _ => None,
        }
    }

    /// Returns `true` if this is a timeout error.
    pub fn is_timeout(&self) -> bool {
        matches!(self, Self::Timeout(_))
    }

    /// Returns `true` if this is a connection-related error.
    pub fn is_connect(&self) -> bool {
        matches!(self, Self::Dns(_) | Self::ConnectionPool(_) | Self::Tls(_))
    }

    /// Returns `true` if this is a body reading error.
    pub fn is_body(&self) -> bool {
        matches!(self, Self::Body(_))
    }

    /// Returns `true` if this is a redirect error.
    pub fn is_redirect(&self) -> bool {
        matches!(self, Self::Redirect(_))
    }
}

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

    #[test]
    fn test_oxi_http_error_is_clone() {
        let io_err = OxiHttpError::from(std::io::Error::new(std::io::ErrorKind::NotFound, "test"));
        let cloned = io_err.clone();
        assert_eq!(io_err.to_string(), cloned.to_string());

        let str_err = OxiHttpError::Body("test".to_string());
        let _ = str_err.clone();
    }
}

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

    // -------------------------------------------------------------------------
    // Display formatting tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_display_invalid_uri() {
        let raw_err: http::uri::InvalidUri = "not a valid uri!!!"
            .parse::<http::Uri>()
            .expect_err("should fail to parse");
        let err = OxiHttpError::from(raw_err);
        let msg = err.to_string();
        assert!(
            msg.contains("invalid URI"),
            "expected 'invalid URI' in '{msg}'"
        );
    }

    #[test]
    fn test_display_http_error() {
        let raw_err = http::Request::builder()
            .header("\n", "x")
            .body(())
            .expect_err("should fail with invalid header name");
        let err = OxiHttpError::from(raw_err);
        let msg = err.to_string();
        assert!(
            msg.contains("HTTP error"),
            "expected 'HTTP error' in '{msg}'"
        );
    }

    #[test]
    fn test_display_hyper_error() {
        let err = OxiHttpError::Hyper("connection reset".to_string());
        let msg = err.to_string();
        assert!(
            msg.contains("hyper error"),
            "expected 'hyper error' in '{msg}'"
        );
    }

    #[test]
    fn test_display_io_error() {
        let raw_err = std::io::Error::new(
            std::io::ErrorKind::ConnectionRefused,
            "connection refused test",
        );
        let err = OxiHttpError::from(raw_err);
        let msg = err.to_string();
        assert!(msg.contains("I/O error"), "expected 'I/O error' in '{msg}'");
    }

    #[test]
    fn test_display_body_error() {
        let err = OxiHttpError::Body("chunk too large".to_string());
        let msg = err.to_string();
        assert!(
            msg.contains("body error"),
            "expected 'body error' in '{msg}'"
        );
    }

    #[test]
    fn test_display_timeout() {
        let err = OxiHttpError::Timeout("request timed out".to_string());
        let msg = err.to_string();
        assert!(msg.contains("timeout"), "expected 'timeout' in '{msg}'");
    }

    #[test]
    fn test_display_redirect() {
        let err = OxiHttpError::Redirect("too many redirects".to_string());
        let msg = err.to_string();
        assert!(
            msg.contains("redirect error"),
            "expected 'redirect error' in '{msg}'"
        );
    }

    #[test]
    fn test_display_tls() {
        let err = OxiHttpError::Tls("certificate invalid".to_string());
        let msg = err.to_string();
        assert!(msg.contains("TLS error"), "expected 'TLS error' in '{msg}'");
    }

    #[test]
    fn test_display_dns() {
        let err = OxiHttpError::Dns("no such host".to_string());
        let msg = err.to_string();
        assert!(msg.contains("DNS error"), "expected 'DNS error' in '{msg}'");
    }

    #[test]
    fn test_display_connection_pool() {
        let err = OxiHttpError::ConnectionPool("pool exhausted".to_string());
        let msg = err.to_string();
        assert!(
            msg.contains("connection pool error"),
            "expected 'connection pool error' in '{msg}'"
        );
    }

    #[test]
    fn test_display_json() {
        let err = OxiHttpError::Json("unexpected token".to_string());
        let msg = err.to_string();
        assert!(
            msg.contains("JSON error"),
            "expected 'JSON error' in '{msg}'"
        );
    }

    #[test]
    fn test_display_route_not_found() {
        let err = OxiHttpError::RouteNotFound {
            method: "GET".to_string(),
            path: "/foo".to_string(),
        };
        let msg = err.to_string();
        assert!(
            msg.contains("route not found"),
            "expected 'route not found' in '{msg}'"
        );
        assert!(msg.contains("GET"), "expected 'GET' in '{msg}'");
        assert!(msg.contains("/foo"), "expected '/foo' in '{msg}'");
    }

    #[test]
    fn test_display_method_not_allowed() {
        let err = OxiHttpError::MethodNotAllowed {
            method: "DELETE".to_string(),
            path: "/bar".to_string(),
        };
        let msg = err.to_string();
        assert!(
            msg.contains("method not allowed"),
            "expected 'method not allowed' in '{msg}'"
        );
        assert!(msg.contains("DELETE"), "expected 'DELETE' in '{msg}'");
        assert!(msg.contains("/bar"), "expected '/bar' in '{msg}'");
    }

    // -------------------------------------------------------------------------
    // From conversion tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_from_invalid_uri() {
        let raw: http::uri::InvalidUri = "not a valid uri!!!"
            .parse::<http::Uri>()
            .expect_err("should fail");
        let result = OxiHttpError::from(raw);
        assert!(
            matches!(result, OxiHttpError::InvalidUri(_)),
            "expected InvalidUri variant"
        );
    }

    #[test]
    fn test_from_http_error() {
        let raw = http::Request::builder()
            .header("\n", "x")
            .body(())
            .expect_err("should fail with invalid header name");
        let result = OxiHttpError::from(raw);
        assert!(
            matches!(result, OxiHttpError::Http(_)),
            "expected Http variant"
        );
    }

    #[test]
    fn test_from_io_error() {
        let raw = std::io::Error::new(
            std::io::ErrorKind::ConnectionRefused,
            "test io error message",
        );
        let result = OxiHttpError::from(raw);
        assert!(matches!(result, OxiHttpError::Io(_)), "expected Io variant");
        assert!(
            result.to_string().contains("test io error message"),
            "Display should include the original io message"
        );
    }

    // -------------------------------------------------------------------------
    // status_code() tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_status_code_route_not_found() {
        let err = OxiHttpError::RouteNotFound {
            method: "GET".to_string(),
            path: "/missing".to_string(),
        };
        assert_eq!(err.status_code(), Some(http::StatusCode::NOT_FOUND));
    }

    #[test]
    fn test_status_code_method_not_allowed() {
        let err = OxiHttpError::MethodNotAllowed {
            method: "PUT".to_string(),
            path: "/resource".to_string(),
        };
        assert_eq!(
            err.status_code(),
            Some(http::StatusCode::METHOD_NOT_ALLOWED)
        );
    }

    #[test]
    fn test_status_code_timeout() {
        let err = OxiHttpError::Timeout("waited too long".to_string());
        assert_eq!(err.status_code(), Some(http::StatusCode::REQUEST_TIMEOUT));
    }

    #[test]
    fn test_status_code_body_is_none() {
        let err = OxiHttpError::Body("incomplete body".to_string());
        assert_eq!(err.status_code(), None);
    }

    // -------------------------------------------------------------------------
    // Predicate tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_is_timeout_true() {
        let err = OxiHttpError::Timeout("timed out".to_string());
        assert!(err.is_timeout());
    }

    #[test]
    fn test_is_timeout_false() {
        let err = OxiHttpError::Body("body error".to_string());
        assert!(!err.is_timeout());
    }

    #[test]
    fn test_is_connect_dns() {
        let err = OxiHttpError::Dns("nxdomain".to_string());
        assert!(err.is_connect());
    }

    #[test]
    fn test_is_connect_pool() {
        let err = OxiHttpError::ConnectionPool("exhausted".to_string());
        assert!(err.is_connect());
    }

    #[test]
    fn test_is_connect_tls() {
        let err = OxiHttpError::Tls("bad cert".to_string());
        assert!(err.is_connect());
    }

    #[test]
    fn test_is_connect_false() {
        let err = OxiHttpError::Timeout("timed out".to_string());
        assert!(!err.is_connect());
    }

    #[test]
    fn test_is_body_true() {
        let err = OxiHttpError::Body("truncated".to_string());
        assert!(err.is_body());
    }

    #[test]
    fn test_is_body_false() {
        let err = OxiHttpError::Json("bad json".to_string());
        assert!(!err.is_body());
    }

    #[test]
    fn test_is_redirect_true() {
        let err = OxiHttpError::Redirect("loop detected".to_string());
        assert!(err.is_redirect());
    }

    #[test]
    fn test_is_redirect_false() {
        let err = OxiHttpError::Timeout("timed out".to_string());
        assert!(!err.is_redirect());
    }
}