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

use crate::components::connector::{ConnectError, ConnectErrorKind};
use crate::nakadi_types::Error;

#[derive(Debug)]
pub enum ConsumerAbort {
    UserInitiated,
    Error(ConsumerError),
}

impl ConsumerAbort {
    pub fn user_initiated() -> Self {
        Self::UserInitiated
    }

    pub fn error<E: Into<ConsumerError>>(err: E) -> Self {
        Self::Error(err.into())
    }

    pub fn is_error(&self) -> bool {
        match self {
            ConsumerAbort::UserInitiated => false,
            _ => true,
        }
    }

    pub fn is_user_abort(&self) -> bool {
        match self {
            ConsumerAbort::UserInitiated => true,
            _ => false,
        }
    }

    pub fn try_into_error(self) -> Result<ConsumerError, Self> {
        match self {
            ConsumerAbort::UserInitiated => Err(self),
            ConsumerAbort::Error(error) => Ok(error),
        }
    }

    pub fn maybe_as_consumer_error(&self) -> Option<&ConsumerError> {
        match self {
            ConsumerAbort::UserInitiated => None,
            ConsumerAbort::Error(ref error) => Some(error),
        }
    }
}

impl fmt::Display for ConsumerAbort {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConsumerAbort::UserInitiated => write!(f, "user initiated")?,
            ConsumerAbort::Error(ref error) => write!(f, "{}", error)?,
        }
        Ok(())
    }
}

impl StdError for ConsumerAbort {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            ConsumerAbort::UserInitiated => None,
            ConsumerAbort::Error(ref error) => error.source(),
        }
    }
}

impl<T> From<T> for ConsumerAbort
where
    T: Into<ConsumerError>,
{
    fn from(err: T) -> Self {
        Self::Error(err.into())
    }
}

impl From<ConnectError> for ConsumerAbort {
    fn from(err: ConnectError) -> Self {
        match err.kind() {
            ConnectErrorKind::Aborted => ConsumerAbort::user_initiated(),
            ConnectErrorKind::SubscriptionNotFound => ConsumerAbort::error(
                ConsumerError::new(ConsumerErrorKind::SubscriptionNotFound).with_source(err),
            ),
            ConnectErrorKind::AccessDenied => ConsumerAbort::error(
                ConsumerError::new(ConsumerErrorKind::AccessDenied).with_source(err),
            ),
            ConnectErrorKind::Unprocessable => ConsumerAbort::error(
                ConsumerError::new(ConsumerErrorKind::ConnectStream).with_source(err),
            ),
            ConnectErrorKind::BadRequest => ConsumerAbort::error(
                ConsumerError::new(ConsumerErrorKind::ConnectStream).with_source(err),
            ),
            ConnectErrorKind::Io => ConsumerAbort::error(
                ConsumerError::new(ConsumerErrorKind::ConnectStream).with_source(err),
            ),
            ConnectErrorKind::Other => ConsumerAbort::error(
                ConsumerError::new(ConsumerErrorKind::ConnectStream).with_source(err),
            ),
            ConnectErrorKind::Conflict => ConsumerAbort::error(
                ConsumerError::new(ConsumerErrorKind::ConnectStream).with_source(err),
            ),
            ConnectErrorKind::NakadiError => {
                ConsumerAbort::error(ConsumerError::new(ConsumerErrorKind::Other).with_source(err))
            }
        }
    }
}

/// Always leads to Nakadion shutting down
#[derive(Debug)]
pub struct ConsumerError {
    message: Option<String>,
    kind: ConsumerErrorKind,
    source: Option<Box<dyn StdError + Send + Sync + 'static>>,
}

impl ConsumerError {
    pub fn new(kind: ConsumerErrorKind) -> Self {
        Self {
            message: None,
            kind,
            source: None,
        }
    }

    pub fn internal() -> Self {
        Self::new(ConsumerErrorKind::Internal)
    }

    pub fn other() -> Self {
        Self::new(ConsumerErrorKind::Other)
    }

    pub fn connect_stream() -> Self {
        Self::new(ConsumerErrorKind::ConnectStream)
    }

    pub fn new_with_message<M: fmt::Display>(kind: ConsumerErrorKind, message: M) -> Self {
        Self {
            message: Some(message.to_string()),
            kind,
            source: None,
        }
    }

    pub fn with_message<T: fmt::Display>(mut self, message: T) -> Self {
        self.message = Some(message.to_string());
        self
    }

    pub fn with_source<E: StdError + Send + Sync + 'static>(mut self, source: E) -> Self {
        self.source = Some(Box::new(source));
        self
    }

    pub fn with_kind(mut self, kind: ConsumerErrorKind) -> Self {
        self.kind = kind;
        self
    }

    pub fn kind(&self) -> ConsumerErrorKind {
        self.kind
    }

    pub fn message(&self) -> Option<&str> {
        self.message.as_deref()
    }
}

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

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

impl From<ConsumerErrorKind> for ConsumerError {
    fn from(kind: ConsumerErrorKind) -> Self {
        Self::new(kind)
    }
}

impl From<nakadi_types::Error> for ConsumerError {
    fn from(err: nakadi_types::Error) -> Self {
        Self {
            message: Some(err.to_string()),
            kind: ConsumerErrorKind::Other,
            source: Some(Box::new(err)),
        }
    }
}

impl From<tokio::task::JoinError> for ConsumerError {
    fn from(err: tokio::task::JoinError) -> Self {
        Self {
            message: None,
            kind: ConsumerErrorKind::Internal,
            source: Some(Box::new(err)),
        }
    }
}

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

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConsumerErrorKind {
    SubscriptionNotFound,
    ConnectStream,
    AccessDenied,
    Internal,
    HandlerAbort,
    HandlerFactory,
    InvalidBatch,
    Other,
}

impl fmt::Display for ConsumerErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConsumerErrorKind::SubscriptionNotFound => write!(f, "subscription not found")?,
            ConsumerErrorKind::ConnectStream => write!(f, "connect to stream failed")?,
            ConsumerErrorKind::Internal => write!(f, "internal")?,
            ConsumerErrorKind::HandlerAbort => write!(f, "handler initiated")?,
            ConsumerErrorKind::HandlerFactory => write!(f, "handler factory")?,
            ConsumerErrorKind::InvalidBatch => write!(f, "invalid batch")?,
            ConsumerErrorKind::Other => write!(f, "other")?,
            _ => write!(f, "not categorized")?,
        }
        Ok(())
    }
}