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
use std::{fmt, io, io::Write, str::Utf8Error, string::FromUtf8Error};
use http::{header, uri::InvalidUri, StatusCode};
pub use crate::channel::Canceled;
pub use http::Error as HttpError;
use crate::http::body::Body;
use crate::http::response::Response;
use crate::util::{BytesMut, Either};
pub trait ResponseError: fmt::Display + fmt::Debug {
fn error_response(&self) -> Response {
let mut resp = Response::new(StatusCode::INTERNAL_SERVER_ERROR);
let mut buf = BytesMut::new();
let _ = write!(crate::http::helpers::Writer(&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<'a, T: ResponseError> ResponseError for &'a 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 {
error!("Internal Server Error: {:?}", err);
} else {
debug!("Error in response: {:?}", err);
}
resp
}
}
impl ResponseError for HttpError {}
impl ResponseError for io::Error {}
impl ResponseError for serde_json::error::Error {}
#[derive(Debug, Display, From)]
pub enum ParseError {
#[display(fmt = "Invalid Method specified")]
Method,
#[display(fmt = "Uri error: {}", _0)]
Uri(InvalidUri),
#[display(fmt = "Invalid HTTP version specified")]
Version,
#[display(fmt = "Invalid Header provided")]
Header,
#[display(fmt = "Message head is too large")]
TooLarge,
#[display(fmt = "Message is incomplete")]
Incomplete,
#[display(fmt = "Invalid Status provided")]
Status,
#[allow(dead_code)]
#[display(fmt = "Timeout during parse")]
Timeout,
InvalidInput(&'static str),
#[display(fmt = "UTF8 error: {}", _0)]
Utf8(Utf8Error),
}
impl std::error::Error for ParseError {}
impl From<FromUtf8Error> for ParseError {
fn from(err: FromUtf8Error) -> ParseError {
ParseError::Utf8(err.utf8_error())
}
}
impl From<httparse::Error> for ParseError {
fn from(err: httparse::Error) -> ParseError {
match err {
httparse::Error::HeaderName
| httparse::Error::HeaderValue
| httparse::Error::NewLine
| httparse::Error::Token => ParseError::Header,
httparse::Error::Status => ParseError::Status,
httparse::Error::TooManyHeaders => ParseError::TooLarge,
httparse::Error::Version => ParseError::Version,
}
}
}
#[derive(Display, Debug, From)]
pub enum PayloadError {
#[display(
fmt = "A payload reached EOF, but is not complete. With error: {:?}",
_0
)]
Incomplete(Option<io::Error>),
#[display(fmt = "Cannot decode content-encoding.")]
EncodingCorrupted,
#[display(fmt = "A payload reached size limit.")]
Overflow,
#[display(fmt = "A payload length is unknown.")]
UnknownLength,
#[display(fmt = "{}", _0)]
Http2Payload(h2::Error),
Parse(ParseError),
#[display(fmt = "{}", _0)]
Io(io::Error),
}
impl std::error::Error for PayloadError {}
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(Debug, Display, From)]
pub enum DispatchError {
Service(Box<dyn ResponseError>),
#[from(ignore)]
Upgrade(Box<dyn std::error::Error>),
#[display(fmt = "Disconnected: {:?}", _0)]
PeerGone(Option<io::Error>),
#[display(fmt = "Parse error: {}", _0)]
Parse(ParseError),
#[display(fmt = "Encode error: {}", _0)]
#[from(ignore)]
Encode(io::Error),
#[display(fmt = "{}", _0)]
H2(h2::Error),
#[display(fmt = "The first request did not complete within the specified timeout")]
SlowRequestTimeout,
#[display(fmt = "Connection shutdown timeout")]
DisconnectTimeout,
#[display(fmt = "Task is completed but request's payload is not consumed")]
PayloadIsNotConsumed,
#[display(fmt = "Malformed request")]
MalformedRequest,
#[display(fmt = "Response body processing error: {}", _0)]
ResponsePayload(Box<dyn std::error::Error>),
#[display(fmt = "Internal error")]
InternalError,
#[display(fmt = "Unknown error")]
Unknown,
}
impl std::error::Error for DispatchError {}
impl From<io::Error> for DispatchError {
fn from(err: io::Error) -> Self {
DispatchError::PeerGone(Some(err))
}
}
#[derive(PartialEq, Debug, Display)]
pub enum ContentTypeError {
#[display(fmt = "Cannot parse content type")]
ParseError,
#[display(fmt = "Unknown content encoding")]
UnknownEncoding,
#[display(fmt = "Unexpected Content-Type")]
Unexpected,
#[display(fmt = "Content-Type is expected")]
Expected,
}
#[derive(Debug, Display)]
pub enum BlockingError<E: fmt::Debug> {
#[display(fmt = "{:?}", _0)]
Error(E),
#[display(fmt = "Thread pool is gone")]
Canceled,
}
impl<E: fmt::Debug> std::error::Error for BlockingError<E> {}
impl From<crate::rt::JoinError> for PayloadError {
fn from(_: crate::rt::JoinError) -> Self {
PayloadError::Io(io::Error::new(
io::ErrorKind::Other,
"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::Other,
"Operation is canceled",
)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use http::{Error as HttpError, StatusCode};
use std::io;
#[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::new(io::ErrorKind::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::new(io::ErrorKind::Other, "ParseError").into();
assert!(format!("{}", err).contains("ParseError"));
let err: PayloadError = BlockingError::Canceled.into();
assert!(format!("{}", err).contains("Operation is canceled"));
let err: PayloadError =
BlockingError::Error(io::Error::new(io::ErrorKind::Other, "ParseError")).into();
assert!(format!("{}", err).contains("ParseError"));
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 ParseError::from($from) {
e @ $error => {
assert!(format!("{}", e).len() >= 5);
}
e => unreachable!("{:?}", e),
}
};
}
#[test]
fn test_from() {
from!(httparse::Error::HeaderName => ParseError::Header);
from!(httparse::Error::HeaderName => ParseError::Header);
from!(httparse::Error::HeaderValue => ParseError::Header);
from!(httparse::Error::NewLine => ParseError::Header);
from!(httparse::Error::Status => ParseError::Status);
from!(httparse::Error::Token => ParseError::Header);
from!(httparse::Error::TooManyHeaders => ParseError::TooLarge);
from!(httparse::Error::Version => ParseError::Version);
}
}