mikros 0.3.0

An optionated crate to help building multi-purpose applications.
Documentation
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
mod macros;

use std::fmt::Formatter;
use std::sync::Arc;

use axum::response::{IntoResponse, Response};
use http::StatusCode;
use serde_derive::{Deserialize, Serialize};

use crate::logger::Logger;
use crate::service::context::Context;

#[derive(Deserialize, Serialize, Clone, Debug)]
pub(crate) enum Error {
    Internal(String),
    NotFound,
    InvalidArguments,
    PreconditionFailed(String),
    Rpc(String),
    Custom(String),
    PermissionDenied,
}

impl Error {
    pub(crate) fn description(&self) -> String {
        match self {
            Error::NotFound => "not found".to_string(),
            Error::InvalidArguments => "invalid arguments".to_string(),
            Error::PreconditionFailed(msg)
            | Error::Rpc(msg)
            | Error::Internal(msg)
            | Error::Custom(msg) => msg.to_string(),
            Error::PermissionDenied => "no permission to access the service".to_string(),
        }
    }

    fn kind(&self) -> String {
        match self {
            Error::Internal(_) => "InternalError".to_string(),
            Error::NotFound => "NotFoundError".to_string(),
            Error::InvalidArguments => "ValidationError".to_string(),
            Error::PreconditionFailed(_) => "ConditionError".to_string(),
            Error::Rpc(_) => "RPCError".to_string(),
            Error::Custom(_) => "CustomError".to_string(),
            Error::PermissionDenied => "PermissionError".to_string(),
        }
    }
}

// Library Result that should be used by public APIs to keep the standard error
// across all library and applications code.
pub type Result<T> = std::result::Result<T, ServiceError>;

// The error that a service must return for another service, either through an
// RPC call (between gRPC client-server communication) or as an HTTP response
// for clients.
#[derive(Deserialize, Serialize)]
pub struct ServiceError {
    // Fields that are always serialized
    code: i32,
    kind: String,

    // Fields that can be hidden.
    #[serde(skip_serializing_if = "Option::is_none")]
    message: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    service_name: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    attributes: Option<serde_json::Value>,

    #[serde(skip_serializing_if = "Option::is_none")]
    destination: Option<String>,

    #[serde(skip)]
    logger: Option<Arc<Logger>>,

    #[serde(skip)]
    concealable_attributes: Option<Vec<String>>,
}

impl ServiceError {
    fn new(ctx: Arc<Context>, error: Error) -> Self {
        Self {
            code: 0,
            kind: error.kind(),
            message: Some(error.description()),
            service_name: Some(ctx.service_name()),
            attributes: None,
            destination: None,
            logger: Self::get_logger(&ctx),
            concealable_attributes: ctx.envs.response_fields(),
        }
    }

    fn get_logger(ctx: &Arc<Context>) -> Option<Arc<Logger>> {
        let logger = ctx.definitions().log();

        if logger.display_errors.unwrap() {
            return Some(ctx.logger().clone());
        }

        None
    }

    /// Sets that the current error is related to an unexpected internal
    /// service behavior.
    pub fn internal(ctx: Arc<Context>, msg: &str) -> Self {
        Self::new(ctx, Error::Internal(msg.to_string()))
    }

    /// Sets that the current error is related to some data or resource not
    /// being found by the service.
    pub fn not_found(ctx: Arc<Context>) -> Self {
        Self::new(ctx, Error::NotFound)
    }

    /// Sets that the current error is related to an argument that didn't
    /// follow validation rules.
    pub fn invalid_arguments(ctx: Arc<Context>, _details: serde_json::Value) -> Self {
        Self::new(ctx, Error::InvalidArguments)
    }

    /// Sets that the current error is related to an internal condition which
    /// wasn't satisfied.
    pub fn precondition_failed(ctx: Arc<Context>, msg: &str) -> Self {
        Self::new(ctx, Error::PreconditionFailed(msg.to_string()))
    }

    /// Sets that the current error is related to a failed RPC call with
    /// another service.
    pub fn rpc(ctx: Arc<Context>, destination: &str, msg: &str) -> Self {
        let mut error = Self::new(ctx, Error::Rpc(msg.to_string()));

        error.destination = Some(destination.to_string());
        error
    }

    /// Lets a service set a custom error kind for its own error.
    pub fn custom(ctx: Arc<Context>, msg: &str) -> Self {
        Self::new(ctx, Error::Custom(msg.to_string()))
    }

    /// Sets that the current error is related to a client trying to access
    /// a resource without having permission to do so.
    pub fn permission_denied(ctx: Arc<Context>) -> Self {
        Self::new(ctx, Error::PermissionDenied)
    }

    /// Adds a code for the error so the client can map and identify their errors.
    pub fn with_code(mut self, code: i32) -> Self {
        self.code = code;
        self
    }

    /// Adds additional information into the error so they can be displayed for
    /// the client if desired.
    pub fn with_attributes(mut self, attributes: serde_json::Value) -> Self {
        self.attributes = Some(attributes);
        self
    }

    fn merge(a: &mut serde_json::Value, b: serde_json::Value) {
        match (a, b) {
            (a @ &mut serde_json::Value::Object(_), serde_json::Value::Object(b)) => {
                let a = a.as_object_mut().unwrap();
                for (k, v) in b {
                    Self::merge(a.entry(k).or_insert(serde_json::Value::Null), v);
                }
            }
            (a, b) => *a = b,
        }
    }

    fn serialize(&self) -> String {
        serde_json::to_string(self).unwrap_or("could not serialize the error message".to_string())
    }

    // Just a helper test function to add fields that should be hidden when
    // serialized. This way we don't need to set environment variable for this
    // operation inside the tests.
    #[cfg(test)]
    fn hide_field(mut self, field: &str) -> Self {
        let mut fields = self.concealable_attributes.unwrap_or(Vec::new());
        fields.push(field.to_string());
        self.concealable_attributes = Some(fields);
        self
    }

    // Translates an Error enum into a ServiceError object.
    pub(crate) fn from_error(ctx: Arc<Context>, error: Error) -> Self {
        Self::new(ctx, error)
    }
}

impl From<ServiceError> for tonic::Status {
    fn from(error: ServiceError) -> Self {
        // Should we log the message?
        if let Some(logger) = &error.logger {
            let mut error_attributes = serde_json::json!({
                "error.code": error.code,
                "error.kind": error.kind,
            });

            if let Some(defined_attributes) = &error.attributes {
                let mut defined_attributes = defined_attributes.clone();
                ServiceError::merge(&mut defined_attributes, error_attributes);
                error_attributes = defined_attributes;
            }

            let message = error.message.clone();
            logger.errorf(&message.unwrap(), error_attributes);
        }

        let mut error = error;

        // Hide fields according what as defined when the application started.
        // It's worth notice that from now on, we only have information that
        // was serialized.
        if let Some(attributes) = &error.concealable_attributes {
            for field in attributes {
                let field = field.to_lowercase();

                if field == "message" {
                    error.message = None;
                }

                if field == "service_name" {
                    error.service_name = None;
                }

                if field == "attributes" {
                    error.attributes = None;
                }

                if field == "destination" {
                    error.destination = None;
                }
            }
        }

        // Return our error always as an (gRPC) Unknown?
        let message = error.serialize();
        tonic::Status::unknown(message)
    }
}

impl From<tonic::Status> for ServiceError {
    fn from(status: tonic::Status) -> Self {
        let error: ServiceError = serde_json::from_str(status.message()).unwrap();
        error
    }
}

impl IntoResponse for ServiceError {
    fn into_response(self) -> Response {
        let code = match self.kind.as_str() {
            "NotFoundError" => StatusCode::NOT_FOUND,
            "ValidationError" => StatusCode::BAD_REQUEST,
            "ConditionError" => StatusCode::PRECONDITION_FAILED,
            "PermissionError" => StatusCode::FORBIDDEN,
            _ => StatusCode::INTERNAL_SERVER_ERROR,
        };

        (code, self.serialize()).into_response()
    }
}

impl std::error::Error for ServiceError {}

impl std::fmt::Display for ServiceError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.serialize())
    }
}

impl std::fmt::Debug for ServiceError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.serialize())
    }
}

// This is just a simple conversion for public APIs that deal with Error
// internally but must return a ServiceError for the client.
impl From<Error> for ServiceError {
    fn from(error: Error) -> Self {
        Self {
            code: 0,
            kind: error.kind(),
            message: Some(error.description()),
            service_name: None,
            attributes: None,
            destination: None,
            logger: None,
            concealable_attributes: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::definition::Definitions;
    use crate::env::Env;
    use crate::logger::builder::LoggerBuilder;

    fn assets_path() -> std::path::PathBuf {
        let mut p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        p.pop();
        p.push("resources/test");
        p
    }

    fn build_context() -> Arc<Context> {
        let filename = assets_path().join("definitions/service.toml.ok_custom_settings");
        let defs = Definitions::new(filename.to_str(), None).unwrap();
        let env = Env::load(&defs).unwrap();
        let logger = Arc::new(LoggerBuilder::new().build());

        Arc::new(Context::new(env, logger, defs, vec![]))
    }

    #[test]
    fn test_complete_service_error() {
        let ctx = build_context();
        let error = ServiceError::rpc(ctx.clone(), "http", "connection failed")
            .with_code(42)
            .with_attributes(serde_json::json!({
                "key": "value"
            }));

        assert_eq!(error.code, 42);
        assert_eq!(error.kind, "RPCError");
        assert_eq!(error.message.unwrap(), "connection failed");
        assert_eq!(error.service_name.unwrap(), "my-service");
        assert_eq!(
            error.attributes.unwrap(),
            serde_json::json!({
                "key": "value"
            })
        );

        assert_eq!(error.destination.unwrap(), "http");
    }

    #[test]
    fn test_service_error_without_message_field() {
        let ctx = build_context();
        let error = ServiceError::rpc(ctx.clone(), "http", "connection failed")
            .with_code(42)
            .with_attributes(serde_json::json!({
                "key": "value"
            }))
            .hide_field("message");

        let grpc_error: tonic::Status = error.into();
        let deserialized: ServiceError = grpc_error.into();

        assert_eq!(deserialized.code, 42);
        assert_eq!(deserialized.kind, "RPCError");
        assert_eq!(deserialized.message.is_none(), true);
        assert_eq!(deserialized.service_name.unwrap(), "my-service");
        assert_eq!(
            deserialized.attributes.unwrap(),
            serde_json::json!({
                "key": "value"
            })
        );

        assert_eq!(deserialized.destination.unwrap(), "http");
    }

    #[test]
    fn test_service_error_without_service_name_field() {
        let ctx = build_context();
        let error = ServiceError::rpc(ctx.clone(), "http", "connection failed")
            .with_code(42)
            .with_attributes(serde_json::json!({
                "key": "value"
            }))
            .hide_field("service_name");

        let grpc_error: tonic::Status = error.into();
        let deserialized: ServiceError = grpc_error.into();

        assert_eq!(deserialized.code, 42);
        assert_eq!(deserialized.kind, "RPCError");
        assert_eq!(deserialized.message.unwrap(), "connection failed");
        assert_eq!(deserialized.service_name.is_none(), true);
        assert_eq!(
            deserialized.attributes.unwrap(),
            serde_json::json!({
                "key": "value"
            })
        );

        assert_eq!(deserialized.destination.unwrap(), "http");
    }

    #[test]
    fn test_service_error_without_attributes_field() {
        let ctx = build_context();
        let error = ServiceError::rpc(ctx.clone(), "http", "connection failed")
            .with_code(42)
            .with_attributes(serde_json::json!({
                "key": "value"
            }))
            .hide_field("attributes");

        let grpc_error: tonic::Status = error.into();
        let deserialized: ServiceError = grpc_error.into();

        assert_eq!(deserialized.code, 42);
        assert_eq!(deserialized.kind, "RPCError");
        assert_eq!(deserialized.message.unwrap(), "connection failed");
        assert_eq!(deserialized.service_name.unwrap(), "my-service");
        assert_eq!(deserialized.attributes.is_none(), true);
        assert_eq!(deserialized.destination.unwrap(), "http");
    }

    #[test]
    fn test_service_error_without_destination_field() {
        let ctx = build_context();
        let error = ServiceError::rpc(ctx.clone(), "http", "connection failed")
            .with_code(42)
            .with_attributes(serde_json::json!({
                "key": "value"
            }))
            .hide_field("destination");

        let grpc_error: tonic::Status = error.into();
        let deserialized: ServiceError = grpc_error.into();

        assert_eq!(deserialized.code, 42);
        assert_eq!(deserialized.kind, "RPCError");
        assert_eq!(deserialized.message.unwrap(), "connection failed");
        assert_eq!(deserialized.service_name.unwrap(), "my-service");
        assert_eq!(
            deserialized.attributes.unwrap(),
            serde_json::json!({
                "key": "value"
            })
        );

        assert_eq!(deserialized.destination.is_none(), true);
    }

    #[test]
    fn test_service_error_without_all_fields() {
        let ctx = build_context();
        let error = ServiceError::rpc(ctx.clone(), "http", "connection failed")
            .with_code(42)
            .with_attributes(serde_json::json!({
                "key": "value"
            }))
            .hide_field("message")
            .hide_field("service_name")
            .hide_field("attributes")
            .hide_field("destination");

        let grpc_error: tonic::Status = error.into();
        let deserialized: ServiceError = grpc_error.into();

        assert_eq!(deserialized.code, 42);
        assert_eq!(deserialized.kind, "RPCError");
        assert_eq!(deserialized.message.is_none(), true);
        assert_eq!(deserialized.service_name.is_none(), true);
        assert_eq!(deserialized.attributes.is_none(), true);
        assert_eq!(deserialized.destination.is_none(), true);
    }

    #[test]
    fn test_create_all_service_error_kind() {
        let ctx = build_context();

        // Internal
        let internal = ServiceError::internal(ctx.clone(), "some internal error");
        assert_eq!(internal.kind, "InternalError".to_string());

        // NotFound
        let not_found = ServiceError::not_found(ctx.clone());
        assert_eq!(not_found.kind, "NotFoundError".to_string());

        // InvalidArguments
        let invalid_arguments = ServiceError::invalid_arguments(ctx.clone(), serde_json::json!({}));
        assert_eq!(invalid_arguments.kind, "ValidationError".to_string());

        // PreconditionFailed
        let precondition_failed =
            ServiceError::precondition_failed(ctx.clone(), "precondition failed");
        assert_eq!(precondition_failed.kind, "ConditionError".to_string());

        // RPC
        let rpc = ServiceError::rpc(ctx.clone(), "example-http", "connection failed");
        assert_eq!(rpc.kind, "RPCError".to_string());

        // Custom
        let custom = ServiceError::custom(ctx.clone(), "custom error");
        assert_eq!(custom.kind, "CustomError".to_string());

        // PermissionDenied
        let permission_denied = ServiceError::permission_denied(ctx.clone());
        assert_eq!(permission_denied.kind, "PermissionError".to_string());
    }
}