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
use c3p0_common::error::C3p0Error;
use serde::Serialize;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use thiserror::Error;
use typescript_definitions::TypeScriptify;

pub struct ErrorCodes {}

impl ErrorCodes {
    pub const INACTIVE_USER: &'static str = "INACTIVE_USER";
    pub const INCOMPLETE_REQUEST: &'static str = "INCOMPLETE_REQUEST";
    pub const IO_ERROR: &'static str = "IO_ERROR";
    pub const JSON_PARSE_ERROR: &'static str = "JSON_PARSE_ERROR";
    pub const NOT_FOUND: &'static str = "NOT_FOUND";
    pub const NOT_PENDING_USER: &'static str = "NOT_PENDING_USER";
    pub const PARSE_ERROR: &'static str = "PARSE_ERROR";
    pub const WRONG_CREDENTIALS: &'static str = "WRONG_CREDENTIALS";
}

#[derive(Error, Debug)]
pub enum LightSpeedError {
    // JWT
    #[error("InvalidTokenError: [{message}]")]
    InvalidTokenError { message: String },
    #[error("ExpiredTokenError: [{message}]")]
    ExpiredTokenError { message: String },
    #[error("GenerateTokenError: [{message}]")]
    GenerateTokenError { message: String },
    #[error("MissingAuthTokenError")]
    MissingAuthTokenError,
    #[error("ParseAuthHeaderError: [{message}]")]
    ParseAuthHeaderError { message: String },

    // Module
    #[error("ModuleBuilderError: [{message}]")]
    ModuleBuilderError { message: String },
    #[error("ModuleStartError: [{message}]")]
    ModuleStartError { message: String },
    #[error("ConfigurationError: [{message}]")]
    ConfigurationError { message: String },

    // Auth
    #[error("UnauthenticatedError")]
    UnauthenticatedError,
    #[error("ForbiddenError [{message}]")]
    ForbiddenError { message: String },
    #[error("PasswordEncryptionError [{message}]")]
    PasswordEncryptionError { message: String },

    #[error("InternalServerError [{message}]")]
    InternalServerError { message: String },

    #[error("RepositoryError [{message}]")]
    RepositoryError { message: String },

    #[error("ValidationError [{details:?}]")]
    ValidationError { details: RootErrorDetails },

    #[error("BadRequest [{message}]")]
    BadRequest { message: String, code: &'static str },

    #[error("RequestConflict [{message}]")]
    RequestConflict { message: String, code: &'static str },

    #[error("ServiceUnavailable [{message}]")]
    ServiceUnavailable { message: String, code: &'static str },
}

#[derive(Default, Debug, Clone, PartialEq, Serialize, TypeScriptify)]
pub struct ErrorDetail {
    error: String,
    params: Vec<String>,
}

impl ErrorDetail {
    pub fn new<S: Into<String>>(error: S, params: Vec<String>) -> Self {
        ErrorDetail {
            error: error.into(),
            params,
        }
    }
}

impl From<String> for ErrorDetail {
    fn from(error: String) -> Self {
        ErrorDetail {
            error,
            params: vec![],
        }
    }
}

impl From<&str> for ErrorDetail {
    fn from(error: &str) -> Self {
        ErrorDetail {
            error: error.to_string(),
            params: vec![],
        }
    }
}

impl From<(&str, Vec<String>)> for ErrorDetail {
    fn from(error: (&str, Vec<String>)) -> Self {
        ErrorDetail {
            error: error.0.to_string(),
            params: error.1,
        }
    }
}

#[derive(Serialize, TypeScriptify)]
pub struct WebErrorDetails<'a> {
    pub code: u16,
    pub message: &'a Option<String>,
    pub details: Option<&'a HashMap<String, Vec<ErrorDetail>>>,
}

impl<'a> WebErrorDetails<'a> {
    pub fn from_message(code: u16, message: &'a Option<String>) -> Self {
        WebErrorDetails {
            code,
            message,
            details: None,
        }
    }

    pub fn from_error_details(code: u16, error_details: &'a RootErrorDetails) -> Self {
        WebErrorDetails {
            code,
            message: &error_details.message,
            details: Some(&error_details.details),
        }
    }
}

impl PartialEq<ErrorDetail> for &str {
    fn eq(&self, other: &ErrorDetail) -> bool {
        other.params.is_empty() && other.error.eq(self)
    }
}

impl PartialEq<ErrorDetail> for String {
    fn eq(&self, other: &ErrorDetail) -> bool {
        other.params.is_empty() && other.error.eq(self)
    }
}

impl From<C3p0Error> for LightSpeedError {
    fn from(err: C3p0Error) -> Self {
        LightSpeedError::RepositoryError {
            message: format!("{}", err),
        }
    }
}

pub type ErrorDetailsData = HashMap<String, Vec<ErrorDetail>>;

pub enum ErrorDetails<'a> {
    Root(RootErrorDetails),
    Scoped(ScopedErrorDetails<'a>),
}

impl<'a> Default for ErrorDetails<'a> {
    fn default() -> Self {
        ErrorDetails::Root(Default::default())
    }
}

impl<'a> ErrorDetails<'a> {
    pub fn add_detail<K: Into<String>, V: Into<ErrorDetail>>(&mut self, key: K, value: V) {
        match self {
            ErrorDetails::Root(node) => node.add_detail(key.into(), value.into()),
            ErrorDetails::Scoped(node) => node.add_detail(key.into(), value.into()),
        }
    }

    pub fn with_scope<S: Into<String>>(&mut self, scope: S) -> ErrorDetails<'_> {
        match self {
            ErrorDetails::Root(node) => ErrorDetails::Scoped(node.with_scope(scope.into())),
            ErrorDetails::Scoped(node) => ErrorDetails::Scoped(node.with_scope(scope.into())),
        }
    }

    pub fn details(&self) -> &ErrorDetailsData {
        match self {
            ErrorDetails::Root(node) => &node.details,
            ErrorDetails::Scoped(node) => &node.details.details,
        }
    }
}

#[derive(Debug)]
pub struct RootErrorDetails {
    pub message: Option<String>,
    pub details: HashMap<String, Vec<ErrorDetail>>,
}

impl Default for RootErrorDetails {
    fn default() -> Self {
        RootErrorDetails {
            message: None,
            details: HashMap::new(),
        }
    }
}

#[derive(Debug)]
pub struct ScopedErrorDetails<'a> {
    scope: String,
    details: &'a mut RootErrorDetails,
}

impl RootErrorDetails {
    fn add_detail(&mut self, key: String, value: ErrorDetail) {
        match self.details.entry(key) {
            Entry::Occupied(mut entry) => {
                entry.get_mut().push(value);
            }
            Entry::Vacant(entry) => {
                entry.insert(vec![value]);
            }
        }
    }

    fn with_scope(&mut self, scope: String) -> ScopedErrorDetails<'_> {
        ScopedErrorDetails {
            scope,
            details: self,
        }
    }
}

impl<'a> ScopedErrorDetails<'a> {
    fn add_detail(&mut self, key: String, value: ErrorDetail) {
        let scoped_key = format!("{}.{}", self.scope, key);
        self.details.add_detail(scoped_key, value)
    }

    fn with_scope(&mut self, scope: String) -> ScopedErrorDetails<'_> {
        ScopedErrorDetails {
            scope: format!("{}.{}", self.scope, scope),
            details: self.details,
        }
    }
}

impl From<serde_json::Error> for LightSpeedError {
    fn from(err: serde_json::Error) -> Self {
        LightSpeedError::BadRequest {
            message: format!("{}", err),
            code: ErrorCodes::JSON_PARSE_ERROR,
        }
    }
}

#[cfg(test)]
pub mod test {

    use super::*;

    #[test]
    pub fn error_details_should_add_entries() {
        let mut err = ErrorDetails::default();
        assert!(err.details().is_empty());

        err.add_detail("hello", "world_1");
        err.add_detail("hello", "world_2");
        err.add_detail("baby", "asta la vista");

        assert_eq!(2, err.details().len());
        assert_eq!(
            vec!["world_1".to_owned(), "world_2".to_owned()],
            err.details()["hello"]
        );
        assert_eq!(vec!["asta la vista".to_owned()], err.details()["baby"]);
    }

    #[test]
    pub fn error_details_should_have_scoped_children() {
        let mut root = ErrorDetails::default();

        root.add_detail("root", "world_1");

        {
            let mut child_one = root.with_scope("one");
            child_one.add_detail("A", "child one.A");
            child_one.add_detail("B", "child one.B");
            {
                let mut child_one_one = child_one.with_scope("inner");
                child_one_one.add_detail("A", "child one.inner.A");
            }
        }

        {
            let mut child_two = root.with_scope("two");
            child_two.add_detail("A", "child two.A");
        }

        use_validator(&mut root.with_scope("some"), "", "");
        use_validator(&mut root, "", "");
        use_validator(&mut root, "", "");

        assert_eq!(5, root.details().len());

        println!("{:?}", root.details());

        assert_eq!(
            ErrorDetail::new("world_1", vec![]),
            root.details()["root"][0]
        );
        assert_eq!(
            ErrorDetail::new("child one.A", vec![]),
            root.details()["one.A"][0]
        );
        assert_eq!(
            ErrorDetail::new("child one.B", vec![]),
            root.details()["one.B"][0]
        );
        assert_eq!(
            ErrorDetail::new("child one.inner.A", vec![]),
            root.details()["one.inner.A"][0]
        );
        assert_eq!(
            ErrorDetail::new("child two.A", vec![]),
            root.details()["two.A"][0]
        );
    }

    fn use_validator(_error_details: &mut ErrorDetails, _field_name: &str, _err: &str) {}
}