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
use std::error::Error as StdError;
use std::fmt;

use http::StatusCode;
use http_api_problem::HttpApiProblem;

use crate::nakadi_types::{Error, FlowId};

/// An error type to get insights on why an HTTP request failed
#[derive(Debug)]
pub struct NakadiApiError {
    context: Option<String>,
    cause: Option<Box<dyn StdError + Send + Sync + 'static>>,
    kind: NakadiApiErrorKind,
    flow_id: Option<FlowId>,
}

impl NakadiApiError {
    /// Create an response based error from a `StatusCode` received
    /// from a server
    pub fn http<T: Into<StatusCode>>(status: T) -> Self {
        Self::create(status.into())
    }

    /// Create an io based error.
    pub fn io() -> Self {
        Self::create(NakadiApiErrorKind::Io)
    }

    /// Create an error for some other cause
    pub fn other() -> Self {
        Self::create(NakadiApiErrorKind::Other(None))
    }

    /// Create an error from an `HttpApiProblem`.
    ///
    /// Keep in mind that an `HttpApiProblem` can also be created
    /// from a `StatusCode` but in that case you should prefer
    /// `NakadiApiError::http`.
    ///
    /// This will also set the `HttpApiProblem` as the cause for this error.
    pub fn http_problem<T: Into<HttpApiProblem>>(prob: T) -> Self {
        let prob = prob.into();
        if let Some(status) = prob.status {
            Self::http(status)
        } else {
            Self::create(NakadiApiErrorKind::Other(None))
        }
        .caused_by(prob)
    }

    fn create<T: Into<NakadiApiErrorKind>>(kind: T) -> Self {
        Self {
            context: None,
            cause: None,
            kind: kind.into(),
            flow_id: None,
        }
    }

    /// Add a cause to this error
    pub fn caused_by<E>(mut self, err: E) -> Self
    where
        E: StdError + Send + Sync + 'static,
    {
        self.cause = Some(Box::new(err));
        self
    }

    /// Add  a message that adds context to the cause for this error.
    pub fn with_context<T: Into<String>>(mut self, context: T) -> Self {
        self.context = Some(context.into());
        self
    }

    /// Add a `FlowId` to this error
    pub fn with_flow_id<T: Into<FlowId>>(mut self, flow_id: T) -> Self {
        self.flow_id = Some(flow_id.into());
        self
    }

    pub fn with_maybe_flow_id(mut self, flow_id: Option<FlowId>) -> Self {
        self.flow_id = flow_id;
        self
    }

    /// Returns the `FlowId` associated with this error
    pub fn flow_id(&self) -> Option<&FlowId> {
        self.flow_id.as_ref()
    }

    /// Returns the `HttpApiProblem` associated with this error
    /// if the cause of this error was an `HttpApiProblem`
    ///
    /// If the cause was not an `HttpApiProblem` `None` is
    /// returned.
    pub fn problem(&self) -> Option<&HttpApiProblem> {
        if let Some(cause) = self.cause.as_ref() {
            cause.downcast_ref::<HttpApiProblem>()
        } else {
            None
        }
    }

    /// Try to turn this error into an `HttpApiProblem`.
    ///
    /// If the cause was not an `HttpApiProblem` `Self` is
    /// returned as an error.
    pub fn try_into_problem(mut self) -> Result<HttpApiProblem, Self> {
        if let Some(cause) = self.cause.take() {
            match cause.downcast::<HttpApiProblem>() {
                Ok(prob) => Ok(*prob),
                Err(the_box) => {
                    self.cause = Some(the_box);
                    Err(self)
                }
            }
        } else {
            Err(self)
        }
    }

    /// Get the `HttpStatusCode` for this error if there
    /// is a status code associated with this error
    pub fn status(&self) -> Option<StatusCode> {
        self.kind.status()
    }

    /// Returns true if there is a `StatusCode` and if it is a client error.
    pub fn is_client_error(&self) -> bool {
        match self.kind {
            NakadiApiErrorKind::ClientError(_) => true,
            _ => false,
        }
    }

    /// Returns true if there is a `StatusCode`
    /// and if it `StatusCode::FORBIDDEN` or `StatusCode::UNAUTHORIZED`.
    pub fn is_auth_error(&self) -> bool {
        match self.kind {
            NakadiApiErrorKind::ClientError(StatusCode::FORBIDDEN)
            | NakadiApiErrorKind::ClientError(StatusCode::UNAUTHORIZED) => true,
            _ => false,
        }
    }

    /// Returns true if there is a `StatusCode` and if it is a server error.
    pub fn is_server_error(&self) -> bool {
        match self.kind {
            NakadiApiErrorKind::ServerError(_) => true,
            _ => false,
        }
    }

    /// Returns true if the error was created with `NakadiApiError::other`.
    pub fn is_other_error(&self) -> bool {
        match self.kind {
            NakadiApiErrorKind::Other(_) => true,
            _ => false,
        }
    }

    /// Returns true if the error was created with `NakadiApiError::io`.
    pub fn is_io_error(&self) -> bool {
        match self.kind {
            NakadiApiErrorKind::Io => true,
            _ => false,
        }
    }
}

impl StdError for NakadiApiError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        self.cause.as_ref().map(|p| &**p as &dyn StdError)
    }
}

impl fmt::Display for NakadiApiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(context) = self.context.as_ref() {
            write!(f, "{}", context)?;
            if let Some(source) = self.source() {
                add_causes(source, f)?;
            } else {
                write!(f, " - {}", self.kind)?;
            }
        } else {
            write!(f, "{}", self.kind)?;
            if let Some(source) = self.source() {
                add_causes(source, f)?;
            }
        }

        Ok(())
    }
}

fn add_causes(err: &dyn StdError, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, " - Caused by: {}", err)?;
    if let Some(source) = err.source() {
        add_causes(source, f)?
    }
    Ok(())
}

impl From<NakadiApiErrorKind> for NakadiApiError {
    fn from(kind: NakadiApiErrorKind) -> Self {
        Self::create(kind)
    }
}

impl From<crate::components::IoError> for NakadiApiError {
    fn from(err: crate::components::IoError) -> Self {
        Self::io().with_context(err.into_string())
    }
}

impl From<http::header::InvalidHeaderValue> for NakadiApiError {
    fn from(err: http::header::InvalidHeaderValue) -> Self {
        NakadiApiError::other()
            .with_context("invalid header value")
            .caused_by(err)
    }
}

impl From<http::uri::InvalidUri> for NakadiApiError {
    fn from(err: http::uri::InvalidUri) -> Self {
        NakadiApiError::other()
            .with_context("invalid URI")
            .caused_by(err)
    }
}

impl From<tokio::time::Elapsed> for NakadiApiError {
    fn from(err: tokio::time::Elapsed) -> Self {
        NakadiApiError::io()
            .with_context("the operation timed out")
            .caused_by(err)
    }
}

impl From<crate::auth::TokenError> for NakadiApiError {
    fn from(err: crate::auth::TokenError) -> Self {
        NakadiApiError::other()
            .with_context("failed to get access token")
            .caused_by(err)
    }
}

impl From<crate::api::dispatch_http_request::RemoteCallError> for NakadiApiError {
    fn from(err: crate::api::dispatch_http_request::RemoteCallError) -> Self {
        let nakadi_err = if err.is_io() {
            NakadiApiError::io()
        } else {
            NakadiApiError::other()
        };

        let context = if let Some(msg) = err.message() {
            msg
        } else {
            "remote call error"
        };

        nakadi_err.with_context(context).caused_by(err)
    }
}

impl From<serde_json::Error> for NakadiApiError {
    fn from(err: serde_json::Error) -> Self {
        if err.is_io() {
            Self::io().with_context("JSON de-/serialization IO error")
        } else if err.is_eof() {
            Self::other().with_context("unexpected EOF in JSON deserialization")
        } else if err.is_syntax() {
            Self::other().with_context("invalid JSON syntax on deserialization")
        } else if err.is_data() {
            Self::other().with_context("unexpected JSON data type on deserialization")
        } else {
            Self::other().with_context("JSON de-/serialization error")
        }
        .caused_by(err)
    }
}

impl From<NakadiApiError> for Error {
    fn from(err: NakadiApiError) -> Self {
        Error::from_error(err)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NakadiApiErrorKind {
    ClientError(StatusCode),
    ServerError(StatusCode),
    Io,
    Other(Option<StatusCode>),
}

impl NakadiApiErrorKind {
    pub fn status(self) -> Option<StatusCode> {
        match self {
            NakadiApiErrorKind::ClientError(status) => Some(status),
            NakadiApiErrorKind::ServerError(status) => Some(status),
            NakadiApiErrorKind::Io => None,
            NakadiApiErrorKind::Other(status) => status,
        }
    }
}

impl fmt::Display for NakadiApiErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NakadiApiErrorKind::ClientError(status) => {
                write!(f, "{}", status)?;
            }
            NakadiApiErrorKind::ServerError(status) => {
                write!(f, "{}", status)?;
            }
            NakadiApiErrorKind::Io => {
                write!(f, "io error")?;
            }
            NakadiApiErrorKind::Other(Some(status)) => {
                write!(f, "{}", status)?;
            }
            NakadiApiErrorKind::Other(None) => {
                write!(f, "other error")?;
            }
        }

        Ok(())
    }
}

impl From<StatusCode> for NakadiApiErrorKind {
    fn from(status: StatusCode) -> Self {
        if status.is_client_error() {
            NakadiApiErrorKind::ClientError(status)
        } else if status.is_server_error() {
            NakadiApiErrorKind::ServerError(status)
        } else {
            NakadiApiErrorKind::Other(Some(status))
        }
    }
}