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
//! Error primitives.

use std::any::TypeId;
use std::error;
use std::fmt;
use std::fmt::{Debug, Display};
use std::io;

use failure;
use failure::Fail;
use futures::Poll;
use http::header::{HeaderMap, HeaderValue};
use http::{header, Response, StatusCode};
use hyper::body::Payload;
use serde::ser::{Serialize, SerializeMap, Serializer};

/// Trait representing error values from endpoints.
///
/// The types which implements this trait will be implicitly converted to an HTTP response
/// by the runtime.
pub trait HttpError: Debug + Display + Send + Sync + 'static {
    /// Return the HTTP status code associated with this error type.
    fn status_code(&self) -> StatusCode {
        StatusCode::INTERNAL_SERVER_ERROR
    }

    /// Append a set of header values to the header map.
    #[allow(unused_variables)]
    fn headers(&self, headers: &mut HeaderMap) {}

    #[allow(missing_docs)]
    fn cause(&self) -> Option<&dyn Fail> {
        None
    }

    #[doc(hidden)]
    fn __private_type_id__(&self) -> TypeId {
        TypeId::of::<Self>()
    }
}

impl HttpError for io::Error {
    fn status_code(&self) -> StatusCode {
        match self.kind() {
            io::ErrorKind::NotFound => StatusCode::NOT_FOUND,
            io::ErrorKind::PermissionDenied => StatusCode::FORBIDDEN,
            _ => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

impl HttpError for failure::Error {
    fn cause(&self) -> Option<&dyn Fail> {
        self.as_fail().cause()
    }
}

/// A type which holds a value of `HttpError` in a type-erased form.
#[derive(Debug)]
pub struct Error(Box<dyn HttpError>);

impl<E: HttpError> From<E> for Error {
    fn from(err: E) -> Self {
        Error(Box::new(err))
    }
}

impl AsRef<dyn HttpError> for Error {
    fn as_ref(&self) -> &dyn HttpError {
        &*self.0
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Display::fmt(&*self.0, f)
    }
}

impl Error {
    /// Returns `true` if the type of contained value is the same as `T`.
    pub fn is<T: HttpError>(&self) -> bool {
        self.0.__private_type_id__() == TypeId::of::<T>()
    }

    /// Attempts to downcast the boxed value to a conrete type by reference.
    pub fn downcast_ref<T: HttpError>(&self) -> Option<&T> {
        if self.is::<T>() {
            unsafe { Some(&*(&*self.0 as *const dyn HttpError as *const T)) }
        } else {
            None
        }
    }

    /// Attempts to downcast the boxed value to a conrete type by mutable reference.
    pub fn downcast_mut<T: HttpError>(&mut self) -> Option<&mut T> {
        if self.is::<T>() {
            unsafe { Some(&mut *(&mut *self.0 as *mut dyn HttpError as *mut T)) }
        } else {
            None
        }
    }

    /// Attempts to downcast the boxed value to a conrete type.
    pub fn downcast<T: HttpError>(self) -> Result<T> {
        if self.is::<T>() {
            unsafe {
                Ok(*Box::from_raw(
                    Box::into_raw(self.0) as *mut dyn HttpError as *mut T
                ))
            }
        } else {
            Err(self)
        }
    }

    /// Return the HTTP status code associated with contained value.
    pub fn status_code(&self) -> StatusCode {
        self.0.status_code()
    }

    /// Append a set of header values to the header map.
    pub fn headers(&self, headers: &mut HeaderMap) {
        self.0.headers(headers)
    }

    /// Returns a reference to the underlying cause of contained error value.
    pub fn cause(&self) -> Option<&dyn Fail> {
        self.0.cause()
    }

    pub(crate) fn into_response(self) -> Response<Error> {
        let mut response = Response::new(());
        *response.status_mut() = self.status_code();
        response.headers_mut().insert(
            header::CONTENT_TYPE,
            HeaderValue::from_static("text/plain; charset=utf-8"),
        );
        self.headers(response.headers_mut());
        response.map(|_| self)
    }

    pub(crate) fn into_payload(self) -> ErrorPayload {
        ErrorPayload {
            body: Some(self.to_string()),
            err: self,
        }
    }
}

impl Serialize for Error {
    fn serialize<S>(&self, ser: S) -> ::std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = ser.serialize_map(None)?;
        map.serialize_entry("code", &self.status_code().as_u16())?;
        map.serialize_entry("description", &self.to_string())?;
        // TODO: causes
        map.end()
    }
}

#[derive(Debug)]
pub(crate) struct ErrorPayload {
    body: Option<String>,
    err: Error,
}

impl ErrorPayload {
    pub(crate) fn into_inner(self) -> Error {
        self.err
    }
}

impl Payload for ErrorPayload {
    type Data = io::Cursor<String>;
    type Error = Never;

    fn poll_data(&mut self) -> Poll<Option<Self::Data>, Self::Error> {
        Ok(self.body.take().map(io::Cursor::new).into())
    }

    fn poll_trailers(&mut self) -> Poll<Option<HeaderMap>, Self::Error> {
        Ok(None.into())
    }

    fn is_end_stream(&self) -> bool {
        self.body.is_none()
    }

    fn content_length(&self) -> Option<u64> {
        self.body.as_ref().map(|body| body.len() as u64)
    }
}

/// A type alias of `Result<T, E>` whose error type is restricted to `Error`.
pub type Result<T> = ::std::result::Result<T, Error>;

// ==== Failure ====

#[derive(Debug)]
struct Failure<F: Fail>(F);

impl<F: Fail> Display for Failure<F> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Display::fmt(&self.0, f)
    }
}

impl<F: Fail> HttpError for Failure<F> {
    fn cause(&self) -> Option<&dyn Fail> {
        self.0.cause()
    }
}

#[allow(missing_docs)]
pub fn fail(err: impl Fail) -> Error {
    Failure(err).into()
}

// ==== err_msg ====

#[allow(missing_docs)]
pub fn bad_request(msg: impl Debug + Display + Send + Sync + 'static) -> Error {
    err_msg(StatusCode::BAD_REQUEST, msg)
}

#[allow(missing_docs)]
pub fn err_msg(status: StatusCode, msg: impl Debug + Display + Send + Sync + 'static) -> Error {
    ErrorMessage { status, msg }.into()
}

#[derive(Debug)]
struct ErrorMessage<D: fmt::Debug + fmt::Display + Send + 'static> {
    status: StatusCode,
    msg: D,
}

impl<D> fmt::Display for ErrorMessage<D>
where
    D: fmt::Debug + fmt::Display + Send + 'static,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.msg, f)
    }
}

impl<D> HttpError for ErrorMessage<D>
where
    D: fmt::Debug + fmt::Display + Send + Sync + 'static,
{
    fn status_code(&self) -> StatusCode {
        self.status
    }
}

// ==== Never ====

/// A type which has no possible values.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq)]
pub enum Never {}

impl Never {
    /// Consume itself and transform into an arbitrary type.
    ///
    /// NOTE: This function has never been actually called because the possible values don't exist.
    pub fn never_into<T>(self) -> T {
        match self {}
    }
}

impl fmt::Display for Never {
    fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {}
    }
}

impl error::Error for Never {
    fn description(&self) -> &str {
        match *self {}
    }

    fn cause(&self) -> Option<&dyn error::Error> {
        match *self {}
    }
}

impl HttpError for Never {}