ntex 4.0.0-beta.15

Framework for composable network services
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
//! HTTP-related errors.
use std::{error, fmt, io, io::Write, string::FromUtf8Error};

use ntex_h2::{self as h2};
use ntex_http::{StatusCode, header};

// Re-export for convenience.
pub use crate::channel::Canceled;
pub use ntex_http::error::Error as HttpError;

use crate::error::Failure;
use crate::http::{body::Body, response::Response};
use crate::util::{BytesMut, Either, clone_io_error};

/// An error that can be converted into an HTTP [`Response`].
pub trait ResponseError: error::Error {
    /// Creates an HTTP response for this error.
    ///
    /// The default response has status `500 Internal Server Error`, a
    /// `text/plain; charset=utf-8` content type, and the error's
    /// [`Display`](fmt::Display) representation as its body. Implementations
    /// should override this method when that text is not suitable for clients.
    fn error_response(&self) -> Response {
        let mut resp = Response::new(StatusCode::INTERNAL_SERVER_ERROR);
        let mut buf = BytesMut::new();
        let _ = write!(&mut buf, "{self}");
        resp.headers_mut().insert(
            header::CONTENT_TYPE,
            header::HeaderValue::from_static("text/plain; charset=utf-8"),
        );
        resp.set_body(Body::from(buf))
    }
}

impl<T: ResponseError> ResponseError for &T {
    fn error_response(&self) -> Response {
        (*self).error_response()
    }
}

impl<T: ResponseError> From<T> for Response {
    fn from(err: T) -> Response {
        let resp = err.error_response();
        if resp.head().status == StatusCode::INTERNAL_SERVER_ERROR {
            log::error!("Internal Server Error: {err:?}");
        } else {
            log::debug!("Error in response: {err:?}");
        }
        resp
    }
}

/// Return `InternalServerError` for `HttpError`,
/// Response generation can return `HttpError`, so it is internal error
impl ResponseError for HttpError {}

/// Return `InternalServerError` for `io::Error`
impl ResponseError for io::Error {}

/// `InternalServerError` for `JsonError`
impl ResponseError for serde_json::error::Error {}

/// Errors that can occur while encoding HTTP streams.
#[derive(thiserror::Error, Clone, Debug)]
pub enum EncodeError {
    /// An invalid `HttpVersion`, such as `HTP/1.1`
    #[error("Unsupported HTTP version specified, {0:?}")]
    UnsupportedVersion(super::Version),

    /// The encoded stream ended before the message was complete.
    #[error("Unexpected end of bytes stream")]
    UnexpectedEof,

    /// A streaming request body has neither chunked coding nor `Content-Length`.
    #[error("Request body length is unknown")]
    UnknownLength,
}

/// Errors that can occur while parsing HTTP streams.
#[derive(thiserror::Error, Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum DecodeError {
    /// An invalid `Method`, such as `GE.T`.
    #[error("Invalid Method specified")]
    Method,
    /// An invalid `Uri`, such as `exam ple.domain`.
    #[error("Uri error")]
    Uri,
    /// An invalid `HttpVersion`, such as `HTP/1.1`
    #[error("Invalid HTTP version specified")]
    Version,
    /// An invalid `Header`.
    #[error("Invalid Header provided")]
    Header,
    /// The message contains more headers than the configured limit.
    #[error("Maximum number of headers are received")]
    MaxHeaders,
    /// A message head is too large to be reasonable.
    #[error("Message head is too large")]
    TooLarge(usize),
    /// A request or status line exceeds the configured limit.
    #[error("Request or status line is too long")]
    StartLineTooLong(usize),
    /// A request applies a transfer coding other than `chunked`.
    #[error("Unsupported transfer coding")]
    UnsupportedTransferCoding,
    /// A message reached EOF, but is not complete.
    #[error("Message is incomplete")]
    Incomplete,
    /// An invalid `Status`, such as `1337 ELITE`.
    #[error("Invalid Status provided")]
    Status,
    /// An `InvalidInput` occurred while trying to parse incoming stream.
    #[error("`InvalidInput` occurred while trying to parse incoming stream: {0}")]
    InvalidInput(&'static str),
    /// Parsing a field as string failed
    #[error("UTF8 error")]
    Utf8,
}

impl From<ntex_http::compat::InvalidUri> for DecodeError {
    fn from(_: ntex_http::compat::InvalidUri) -> DecodeError {
        DecodeError::Uri
    }
}

impl From<FromUtf8Error> for DecodeError {
    fn from(_: FromUtf8Error) -> DecodeError {
        DecodeError::Utf8
    }
}

impl From<httparse::Error> for DecodeError {
    fn from(err: httparse::Error) -> DecodeError {
        match err {
            httparse::Error::HeaderName
            | httparse::Error::HeaderValue
            | httparse::Error::NewLine
            | httparse::Error::Token => DecodeError::Header,
            httparse::Error::Status => DecodeError::Status,
            httparse::Error::TooManyHeaders => DecodeError::TooLarge(0),
            httparse::Error::Version => DecodeError::Version,
        }
    }
}

impl From<ntex_httparse::Error> for DecodeError {
    fn from(err: ntex_httparse::Error) -> DecodeError {
        match err {
            ntex_httparse::Error::HeaderName
            | ntex_httparse::Error::HeaderValue
            | ntex_httparse::Error::NewLine
            | ntex_httparse::Error::Token => DecodeError::Header,
            ntex_httparse::Error::Status => DecodeError::Status,
            ntex_httparse::Error::TooManyHeaders => DecodeError::TooLarge(0),
            ntex_httparse::Error::Version => DecodeError::Version,
        }
    }
}

#[derive(thiserror::Error, Debug)]
/// Errors that can occur while processing a payload.
pub enum PayloadError {
    /// A payload reached EOF, but is not complete.
    #[error("A payload reached EOF, but is not complete. With error: {0:?}")]
    Incomplete(#[source] Option<io::Error>),
    /// Content encoding stream corruption
    #[error("Cannot decode content-encoding.")]
    EncodingCorrupted,
    /// A payload reached size limit.
    #[error("A payload reached size limit.")]
    Overflow,
    /// A payload length is unknown.
    #[error("A payload length is unknown.")]
    UnknownLength,
    /// Http2 payload error
    #[error("")]
    Http2Payload(
        #[from]
        #[source]
        h2::StreamError,
    ),
    /// Decode error
    #[error("Decode error")]
    Decode(
        #[from]
        #[source]
        DecodeError,
    ),
    /// Io error
    #[error("{0}")]
    Io(
        #[from]
        #[source]
        io::Error,
    ),
}

impl Clone for PayloadError {
    fn clone(&self) -> PayloadError {
        match self {
            PayloadError::Incomplete(err) => {
                PayloadError::Incomplete(err.as_ref().map(clone_io_error))
            }
            PayloadError::EncodingCorrupted => PayloadError::EncodingCorrupted,
            PayloadError::Overflow => PayloadError::Overflow,
            PayloadError::UnknownLength => PayloadError::UnknownLength,
            PayloadError::Http2Payload(err) => PayloadError::Http2Payload(*err),
            PayloadError::Decode(err) => PayloadError::Decode(*err),
            PayloadError::Io(err) => PayloadError::Io(clone_io_error(err)),
        }
    }
}

impl From<Either<PayloadError, io::Error>> for PayloadError {
    fn from(err: Either<PayloadError, io::Error>) -> Self {
        match err {
            Either::Left(err) => err,
            Either::Right(err) => PayloadError::Io(err),
        }
    }
}

#[derive(thiserror::Error, Clone, Debug)]
/// Errors that can occur while dispatching HTTP requests.
pub enum DispatchError {
    /// Service error
    #[error("Service error {0}")]
    Service(Failure),

    /// Control service error
    #[error("Control service error")]
    Control(Failure),
}

#[derive(thiserror::Error, Clone, Debug)]
/// Errors that can occur while dispatching HTTP/2 requests.
pub enum H2Error {
    /// Too many consecutive empty non-final `DATA` frames
    #[error("Too many consecutive empty DATA frames")]
    EmptyDataFrames,
}

impl crate::error::ErrorDiagnostic for H2Error {
    fn signature(&self) -> &'static str {
        "ntex-http-h2error"
    }
}

/// Errors that can occur while parsing a `Content-Type` header.
#[derive(thiserror::Error, Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum ContentTypeError {
    /// Cannot parse content type
    #[error("Cannot parse content type")]
    ParseError,
    /// Unknown content encoding
    #[error("Unknown content encoding")]
    UnknownEncoding,
    /// Unexpected Content-Type
    #[error("Unexpected Content-Type")]
    Unexpected,
    /// Content-Type is expected
    #[error("Content-Type is expected")]
    Expected,
}

/// An error produced by a blocking operation.
#[derive(thiserror::Error, Debug)]
pub enum BlockingError<E: fmt::Debug> {
    /// The blocking operation returned an error.
    #[error("{0:?}")]
    Error(#[source] E),
    /// The thread pool stopped before completing the operation.
    #[error("Thread pool is gone")]
    Canceled,
}

impl From<crate::rt::JoinError> for PayloadError {
    fn from(_: crate::rt::JoinError) -> Self {
        PayloadError::Io(io::Error::new(
            io::ErrorKind::Interrupted,
            "Operation is canceled",
        ))
    }
}

impl From<crate::rt::BlockingError> for PayloadError {
    fn from(_: crate::rt::BlockingError) -> Self {
        PayloadError::Io(io::Error::new(
            io::ErrorKind::Interrupted,
            "Operation is canceled",
        ))
    }
}

impl From<BlockingError<io::Error>> for PayloadError {
    fn from(err: BlockingError<io::Error>) -> Self {
        match err {
            BlockingError::Error(e) => PayloadError::Io(e),
            BlockingError::Canceled => PayloadError::Io(io::Error::new(
                io::ErrorKind::Interrupted,
                "Operation is canceled",
            )),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ntex_http::Error as HttpError;

    #[test]
    fn test_into_response() {
        let err: HttpError = StatusCode::from_u16(10000).err().unwrap().into();
        let resp: Response = err.error_response();
        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn test_error_http_response() {
        let orig = io::Error::other("other");
        let resp: Response = orig.into();
        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn test_payload_error() {
        let err: PayloadError = io::Error::other("DecodeError").into();
        assert!(format!("{err}").contains("DecodeError"), "{err}");

        let err: PayloadError = BlockingError::Canceled.into();
        assert!(format!("{err}").contains("Operation is canceled"), "{err}");

        let err: PayloadError = BlockingError::Error(io::Error::other("DecodeError")).into();
        assert!(format!("{err}").contains("DecodeError"), "{err}");

        let err = PayloadError::Incomplete(None);
        assert_eq!(
            format!("{err}"),
            "A payload reached EOF, but is not complete. With error: None"
        );
    }

    macro_rules! from {
        ($from:expr => $error:pat) => {
            match DecodeError::from($from) {
                e @ $error => {
                    assert!(format!("{e}").len() >= 5);
                }
                e => unreachable!("{e:?}"),
            }
        };
    }

    #[test]
    fn test_from() {
        from!(httparse::Error::HeaderName => DecodeError::Header);
        from!(httparse::Error::HeaderName => DecodeError::Header);
        from!(httparse::Error::HeaderValue => DecodeError::Header);
        from!(httparse::Error::NewLine => DecodeError::Header);
        from!(httparse::Error::Status => DecodeError::Status);
        from!(httparse::Error::Token => DecodeError::Header);
        from!(httparse::Error::TooManyHeaders => DecodeError::TooLarge(0));
        from!(httparse::Error::Version => DecodeError::Version);
        from!(ntex_httparse::Error::HeaderName => DecodeError::Header);
        from!(ntex_httparse::Error::HeaderName => DecodeError::Header);
        from!(ntex_httparse::Error::HeaderValue => DecodeError::Header);
        from!(ntex_httparse::Error::NewLine => DecodeError::Header);
        from!(ntex_httparse::Error::Status => DecodeError::Status);
        from!(ntex_httparse::Error::Token => DecodeError::Header);
        from!(ntex_httparse::Error::TooManyHeaders => DecodeError::TooLarge(0));
        from!(ntex_httparse::Error::Version => DecodeError::Version);
    }

    #[test]
    fn test_decode_error_from() {
        let err = "a b".parse::<crate::http::Uri>().unwrap_err();
        assert!(matches!(DecodeError::from(err), DecodeError::Uri));
        let err = String::from_utf8(vec![0xff]).unwrap_err();
        assert!(matches!(DecodeError::from(err), DecodeError::Utf8));
    }

    #[test]
    fn test_payload_error_clone() {
        let errs = [
            PayloadError::Incomplete(None),
            PayloadError::Incomplete(Some(io::Error::other("inc"))),
            PayloadError::EncodingCorrupted,
            PayloadError::Overflow,
            PayloadError::UnknownLength,
            PayloadError::Http2Payload(ntex_h2::StreamError::Closed),
            PayloadError::Decode(DecodeError::Method),
            PayloadError::Io(io::Error::other("io")),
        ];
        for err in &errs {
            assert_eq!(err.to_string(), err.clone().to_string());
        }
    }

    #[test]
    fn test_payload_error_conversions() {
        let err = PayloadError::from(Either::<PayloadError, io::Error>::Left(
            PayloadError::Overflow,
        ));
        assert!(matches!(err, PayloadError::Overflow));
        let err = PayloadError::from(Either::<PayloadError, io::Error>::Right(io::Error::other(
            "right",
        )));
        assert!(matches!(err, PayloadError::Io(ref e) if e.to_string() == "right"));

        for err in [
            PayloadError::from(crate::rt::JoinError),
            PayloadError::from(crate::rt::BlockingError),
        ] {
            assert!(
                matches!(err, PayloadError::Io(ref e) if e.kind() == io::ErrorKind::Interrupted)
            );
        }
    }

    #[test]
    fn test_h2_error() {
        use crate::error::ErrorDiagnostic;

        let err = H2Error::EmptyDataFrames;
        assert_eq!(err.signature(), "ntex-http-h2error");
        assert_eq!(err.to_string(), "Too many consecutive empty DATA frames");
    }
}