bomboni_request 0.3.0

Utilities for working with API requests. Part of Bomboni library.
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
use bomboni_proto::google::{
    protobuf::Any,
    rpc::{BadRequest, Code, Status, bad_request::FieldViolation},
};
use prost::{DecodeError, EncodeError};
use serde::{Deserialize, Serialize};
use std::{
    error::Error,
    fmt::{self, Display, Formatter},
};
use thiserror::Error;

use crate::query::error::QueryError;

#[derive(Error, Debug)]
#[cfg_attr(
    all(
        target_family = "wasm",
        not(any(target_os = "emscripten", target_os = "wasi")),
        feature = "wasm",
    ),
    derive(bomboni_wasm::Wasm),
    wasm(
        bomboni_wasm_crate = bomboni_wasm,
        into_wasm_abi,
        proxy { source = Status, try_from = RequestParse::parse },
    )
)]
/// Request error types.
pub enum RequestError {
    /// Invalid request with field violations.
    #[error("invalid `{name}` request")]
    BadRequest {
        /// Request name.
        name: String,
        /// Field violations.
        violations: Vec<PathError>,
    },
    /// Path-specific error.
    #[error(transparent)]
    Path(PathError),
    /// Generic error.
    #[error("{0}")]
    Generic(GenericErrorBox),
    /// Encode error.
    #[error("encode error: {0}")]
    Encode(#[from] EncodeError),
    /// Decode error.
    #[error("decode error: {0}")]
    Decode(#[from] DecodeError),
}

/// Request result type.
pub type RequestResult<T> = Result<T, RequestError>;

/// Error with path information.
#[derive(Debug)]
pub struct PathError {
    /// Error path.
    pub path: Vec<PathErrorStep>,
    /// Underlying error.
    pub error: GenericErrorBox,
}

/// Path error step.
#[derive(Debug, PartialEq, Eq)]
pub enum PathErrorStep {
    /// Field access.
    Field(String),
    /// Index access.
    Index(usize),
    /// Key access.
    Key(String),
}

/// Common error types.
#[derive(Error, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind")]
pub enum CommonError {
    /// Resource was not found.
    #[error("requested entity was not found")]
    ResourceNotFound,
    /// Unauthorized access.
    #[error("unauthorized")]
    Unauthorized,
    /// Required field is missing.
    #[error("no value provided for required field")]
    RequiredFieldMissing,
    /// Invalid name format.
    #[error("expected `{expected_format}`, but got `{name}`.")]
    InvalidName {
        /// Expected format.
        expected_format: String,
        /// Actual name.
        name: String,
    },
    /// Invalid name with alternative format.
    #[error(
        "expected either `{expected_format}` or `{alternative_expected_format}`, but got `{name}`"
    )]
    InvalidNameAlternative {
        /// Expected format.
        expected_format: String,
        /// Alternative expected format.
        alternative_expected_format: String,
        /// Actual name.
        name: String,
    },
    /// Invalid resource parent.
    #[error("expected resource parent `{expected}`, but got `{parent}`")]
    InvalidParent {
        /// Expected parent.
        expected: String,
        /// Actual parent.
        parent: String,
    },
    /// Invalid string format.
    #[error("expected a string in format `{expected}`")]
    InvalidStringFormat {
        /// Expected format.
        expected: String,
    },
    /// Invalid ID format.
    #[error("invalid ID format")]
    InvalidId,
    /// Duplicate ID.
    #[error("duplicate ID")]
    DuplicateId,
    /// Invalid display name format.
    #[error("invalid display name format")]
    InvalidDisplayName,
    /// Invalid date time format.
    #[error("invalid date time format")]
    InvalidDateTime,
    /// Invalid enum value.
    #[error("invalid enum value")]
    InvalidEnumValue,
    /// Unknown oneof variant.
    #[error("unknown oneof variant")]
    UnknownOneofVariant,
    /// Invalid numeric value.
    #[error("invalid numeric value")]
    InvalidNumericValue,
    /// Failed to convert value.
    #[error("failed to convert value")]
    FailedConvertValue,
    /// Numeric value out of range.
    #[error("out of range")]
    NumericOutOfRange,
    /// Duplicate value.
    #[error("duplicate value")]
    DuplicateValue,
    /// Resource already exists.
    #[error("already exists")]
    AlreadyExists,
    /// Resource not found.
    #[error("not found")]
    NotFound,
    /// Type mismatch.
    #[error("type mismatch")]
    TypeMismatch,
}

/// Generic error trait.
pub trait GenericError: Error {
    /// Returns the error as `Any` for downcasting.
    fn as_any(&self) -> &dyn std::any::Any;

    /// Returns the gRPC status code.
    fn code(&self) -> Code {
        Code::InvalidArgument
    }

    /// Returns the error details.
    fn details(&self) -> Vec<Any> {
        Vec::default()
    }
}

/// Boxed generic error.
pub type GenericErrorBox = Box<dyn GenericError + Send + Sync>;

impl RequestError {
    #[must_use]
    /// Creates a bad request error.
    pub fn bad_request<N, V, F, E>(name: N, violations: V) -> Self
    where
        N: Display,
        V: IntoIterator<Item = (F, E)>,
        F: Display,
        E: Into<GenericErrorBox>,
    {
        Self::BadRequest {
            name: name.to_string(),
            violations: violations
                .into_iter()
                .map(|(field, error)| PathError {
                    path: vec![PathErrorStep::Field(field.to_string())],
                    error: error.into(),
                })
                .collect(),
        }
    }

    #[must_use]
    /// Creates a generic error.
    pub fn generic<E: Into<GenericErrorBox>>(error: E) -> Self {
        Self::Generic(error.into())
    }

    #[must_use]
    /// Creates a path error.
    pub fn path<P, E>(path: P, error: E) -> Self
    where
        P: IntoIterator<Item = PathErrorStep>,
        E: Into<GenericErrorBox>,
    {
        Self::Path(PathError {
            path: path.into_iter().collect(),
            error: error.into(),
        })
    }

    #[must_use]
    /// Creates a field error.
    pub fn field<F, E>(field: F, error: E) -> Self
    where
        F: Display,
        E: Into<GenericErrorBox>,
    {
        Self::path([PathErrorStep::Field(field.to_string())], error)
    }

    #[must_use]
    /// Creates a field index error.
    pub fn field_index<F, E>(field: F, index: usize, error: E) -> Self
    where
        F: Display,
        E: Into<GenericErrorBox>,
    {
        Self::path(
            [
                PathErrorStep::Field(field.to_string()),
                PathErrorStep::Index(index),
            ],
            error,
        )
    }

    #[must_use]
    /// Creates a field key error.
    pub fn field_key<F, K, E>(field: F, key: K, error: E) -> Self
    where
        F: Display,
        K: Display,
        E: Into<GenericErrorBox>,
    {
        Self::path(
            [
                PathErrorStep::Field(field.to_string()),
                PathErrorStep::Key(key.to_string()),
            ],
            error,
        )
    }

    #[must_use]
    /// Creates a field parse error.
    pub fn field_parse<F, E>(field: F, error: E) -> Self
    where
        F: Display,
        E: Into<GenericErrorBox>,
    {
        Self::path(PathError::parse_path(field.to_string()), error)
    }

    #[must_use]
    /// Creates an index error.
    pub fn index<E>(index: usize, error: E) -> Self
    where
        E: Into<GenericErrorBox>,
    {
        Self::path([PathErrorStep::Index(index)], error)
    }

    #[must_use]
    /// Creates a key error.
    pub fn key<K, E>(key: K, error: E) -> Self
    where
        K: Display,
        E: Into<GenericErrorBox>,
    {
        Self::path([PathErrorStep::Key(key.to_string())], error)
    }

    #[must_use]
    /// Wraps the error with a path.
    ///
    /// # Panics
    ///
    /// Will panic if trying to wrap error path for error types that don't support path wrapping.
    pub fn wrap_path<P>(self, path: P) -> Self
    where
        P: IntoIterator<Item = PathErrorStep>,
    {
        let mut path: Vec<_> = path.into_iter().collect();
        match self {
            Self::Path(error) => PathError {
                path: {
                    path.extend(error.path);
                    path
                },
                error: error.error,
            }
            .into(),
            Self::Generic(error) => Self::path(path, error),
            err => panic!("cannot wrap error path `{path:?}` for: {err:?}"),
        }
    }

    #[must_use]
    /// Inserts a path at the specified index.
    ///
    /// # Panics
    ///
    /// Will panic if trying to insert error path for error types that don't support path insertion.
    pub fn insert_path<P>(self, path: P, index: usize) -> Self
    where
        P: IntoIterator<Item = PathErrorStep>,
    {
        let path: Vec<_> = path.into_iter().collect();
        match self {
            Self::Path(mut error) => PathError {
                path: {
                    let tail: Vec<_> = error.path.splice(index.., path).collect();
                    error.path.extend(tail);
                    error.path
                },
                error: error.error,
            }
            .into(),
            Self::Generic(error) => Self::path(path, error),
            err => panic!("cannot insert error path `{path:?}` for: {err:?}"),
        }
    }

    #[must_use]
    /// Wraps the error with a field.
    pub fn wrap_field<F: Display>(self, field: F) -> Self {
        self.wrap_path([PathErrorStep::Field(field.to_string())])
    }

    #[must_use]
    /// Wraps error with an index.
    pub fn wrap_index(self, index: usize) -> Self {
        self.wrap_path([PathErrorStep::Index(index)])
    }

    #[must_use]
    /// Wraps error with a key.
    pub fn wrap_key<K: Display>(self, key: K) -> Self {
        self.wrap_path([PathErrorStep::Key(key.to_string())])
    }

    #[must_use]
    /// Wraps error with a field and index.
    pub fn wrap_field_index<F>(self, field: F, index: usize) -> Self
    where
        F: Display,
    {
        self.wrap_path([
            PathErrorStep::Field(field.to_string()),
            PathErrorStep::Index(index),
        ])
    }

    #[must_use]
    /// Wraps error with a field and key.
    pub fn wrap_field_key<F, K>(self, field: F, key: K) -> Self
    where
        F: Display,
        K: Display,
    {
        self.wrap_path([
            PathErrorStep::Field(field.to_string()),
            PathErrorStep::Key(key.to_string()),
        ])
    }

    #[must_use]
    /// Wraps error for a request.
    pub fn wrap_request<N: Display>(self, name: N) -> Self {
        match self {
            Self::Path(error) => Self::bad_request(name, [(error.path_to_string(), error.error)]),
            Self::Generic(error) => {
                #[allow(clippy::option_if_let_else, trivial_casts)]
                if let Some(error) = error.as_any().downcast_ref::<QueryError>() {
                    #[allow(trivial_casts)]
                    Self::bad_request(
                        name,
                        [(
                            error.get_violating_field_name(),
                            Box::new(error.clone()) as GenericErrorBox,
                        )],
                    )
                } else {
                    Self::Generic(error)
                }
            }
            error => error,
        }
    }

    /// Returns the error code.
    pub fn code(&self) -> Code {
        match self {
            Self::Path(error) => error.code(),
            Self::Generic(error) => error.code(),
            Self::BadRequest { .. } | Self::Encode(_) | Self::Decode(_) => Code::InvalidArgument,
        }
    }

    /// Returns the error details.
    ///
    /// # Panics
    ///
    /// Will panic if unable to convert bad request details to protobuf Any type.
    pub fn details(&self) -> Vec<Any> {
        match self {
            Self::BadRequest { violations, .. } => vec![
                BadRequest {
                    field_violations: violations
                        .iter()
                        .map(|error| FieldViolation {
                            field: error.path_to_string(),
                            description: error.error.to_string(),
                        })
                        .collect(),
                }
                .try_into()
                .unwrap(),
            ],
            Self::Path(error) => error.details(),
            Self::Generic(error) => error.details(),
            _ => Vec::new(),
        }
    }
}

impl From<RequestError> for Status {
    fn from(err: RequestError) -> Self {
        Self::from(&err)
    }
}

impl From<&RequestError> for Status {
    fn from(err: &RequestError) -> Self {
        Self::new(err.code(), err.to_string(), err.details())
    }
}

#[cfg(feature = "tonic")]
impl From<RequestError> for tonic::Status {
    fn from(err: RequestError) -> Self {
        let status = Status::from(&err);
        status
            .try_into()
            .unwrap_or_else(|()| Self::internal("Failed to convert to tonic Status"))
    }
}

#[cfg(feature = "tonic")]
impl From<&RequestError> for tonic::Status {
    fn from(err: &RequestError) -> Self {
        let status = Status::from(err);
        status
            .try_into()
            .unwrap_or_else(|()| Self::internal("Failed to convert to tonic Status"))
    }
}

impl PathError {
    /// Returns the error code.
    pub fn code(&self) -> Code {
        self.error.code()
    }

    /// Returns the error details.
    pub fn details(&self) -> Vec<Any> {
        self.error.details()
    }

    /// Converts the path to a string representation.
    pub fn path_to_string(&self) -> String {
        use std::fmt::Write;
        let mut path = String::new();
        for (i, step) in self.path.iter().enumerate() {
            match step {
                PathErrorStep::Field(field) => {
                    if i == 0 {
                        path.push_str(field);
                    } else {
                        write!(path, ".{field}").unwrap();
                    }
                }
                PathErrorStep::Index(index) => write!(path, "[{index}]").unwrap(),
                PathErrorStep::Key(key) => write!(path, "{{{key}}}").unwrap(),
            }
        }
        path
    }

    /// Parses a path string into path error steps.
    ///
    /// # Panics
    ///
    /// Will panic if unable to parse index from path string format.
    pub fn parse_path<P: AsRef<str>>(path: P) -> Vec<PathErrorStep> {
        let parts: Vec<_> = path.as_ref().split('.').collect();
        let mut steps = Vec::with_capacity(parts.len());
        for part in parts {
            let part = part.trim();
            if let Some(index) = part.find('[') {
                let field = &part[..index];
                let index = part[index + 1..part.len() - 1].parse().unwrap();
                steps.push(PathErrorStep::Field(field.to_string()));
                steps.push(PathErrorStep::Index(index));
            } else if let Some(index) = part.find('{') {
                let key = &part[index + 1..part.len() - 1];
                steps.push(PathErrorStep::Key(key.to_string()));
            } else {
                steps.push(PathErrorStep::Field(part.to_string()));
            }
        }
        steps
    }
}

impl Error for PathError {}

impl From<PathError> for RequestError {
    fn from(err: PathError) -> Self {
        Self::Path(err)
    }
}

impl Display for PathError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "field `{}` error: `{}`",
            self.path_to_string(),
            self.error
        )
    }
}

impl Display for PathErrorStep {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Field(field) => write!(f, "{field}"),
            Self::Index(index) => write!(f, "[{index}]"),
            Self::Key(key) => write!(f, "{{{key}}}"),
        }
    }
}

impl GenericError for CommonError {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn code(&self) -> Code {
        match self {
            Self::ResourceNotFound | Self::NotFound => Code::NotFound,
            Self::AlreadyExists => Code::AlreadyExists,
            Self::Unauthorized => Code::PermissionDenied,
            _ => Code::InvalidArgument,
        }
    }
}

impl<T> From<T> for GenericErrorBox
where
    T: 'static + GenericError + Send + Sync,
{
    fn from(err: T) -> Self {
        Box::new(err)
    }
}

impl<T: 'static + GenericError + Send + Sync> From<T> for RequestError {
    fn from(err: T) -> Self {
        Self::Generic(Box::new(err))
    }
}

/// Extension trait for request errors.
pub trait RequestErrorExt {
    /// Wraps error with a field.
    fn wrap<F: Display>(self, field: F) -> RequestError;

    /// Wraps error with an index.
    fn wrap_index(self, index: usize) -> RequestError;

    /// Wraps error with a key.
    fn wrap_key<K: Display>(self, key: K) -> RequestError;

    /// Wraps error with a field and index.
    fn wrap_field_index<F: Display>(self, field: F, index: usize) -> RequestError;

    /// Wraps error with a field and key.
    fn wrap_field_key<F: Display, K: Display>(self, field: F, key: K) -> RequestError;

    /// Wraps error for a request.
    fn wrap_request<N: Display>(self, name: N) -> RequestError;
}

impl<T> RequestErrorExt for T
where
    T: 'static + GenericError + Send + Sync,
{
    fn wrap<F: Display>(self, field: F) -> RequestError {
        RequestError::generic(self).wrap_field(field)
    }

    fn wrap_index(self, index: usize) -> RequestError {
        RequestError::generic(self).wrap_index(index)
    }

    fn wrap_key<K: Display>(self, key: K) -> RequestError {
        RequestError::generic(self).wrap_key(key)
    }

    fn wrap_field_index<F: Display>(self, field: F, index: usize) -> RequestError {
        RequestError::generic(self).wrap_field_index(field, index)
    }

    fn wrap_field_key<F: Display, K: Display>(self, field: F, key: K) -> RequestError {
        RequestError::generic(self).wrap_field_key(field, key)
    }

    fn wrap_request<N: Display>(self, name: N) -> RequestError {
        RequestError::generic(self).wrap_request(name)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let err = RequestError::bad_request("Test", [("x", CommonError::InvalidId)]);
        assert_eq!(err.to_string(), "invalid `Test` request");
        assert_eq!(
            err.details().remove(0).to_msg::<BadRequest>().unwrap(),
            BadRequest {
                field_violations: vec![FieldViolation {
                    field: "x".into(),
                    description: "invalid ID format".into(),
                }]
            }
        );
    }

    #[test]
    fn query_error_metadata() {
        assert_eq!(
            serde_json::to_value(Status::from(
                RequestError::from(QueryError::InvalidPageSize).wrap_request("List"),
            ))
            .unwrap(),
            serde_json::from_str::<serde_json::Value>(
                r#"{
                "code": "INVALID_ARGUMENT",
                "message": "invalid `List` request",
                "details": [
                    {
                        "@type": "type.googleapis.com/google.rpc.BadRequest",
                        "fieldViolations": [
                            {
                                "field": "page_size",
                                "description": "page size specified is invalid"
                            }
                        ]
                    }
                ]
            }"#
            )
            .unwrap()
        );
    }

    #[test]
    fn field_paths() {
        assert_eq!(
            RequestError::generic(CommonError::NotFound)
                .wrap_field("value")
                .wrap_index(42)
                .wrap_field("root")
                .to_string(),
            "field `root[42].value` error: `not found`"
        );
        assert!(matches!(
            RequestError::generic(CommonError::NotFound)
                .wrap_index(42)
                .wrap_field("value")
                .wrap_request("Test"),
            RequestError::BadRequest { name, violations }
            if name == "Test" && violations.len() == 1
                && violations[0].to_string() == "field `value[42]` error: `not found`"
        ));
        assert!(matches!(
            CommonError::InvalidId.wrap("id").wrap_request("Test"),
            RequestError::BadRequest { name, violations }
            if name == "Test" && violations.len() == 1
                && violations[0].to_string() == "field `id` error: `invalid ID format`"
        ));
    }

    #[test]
    fn parse_error_field_path() {
        assert_eq!(
            PathError::parse_path("test.x.field[42].y.{key}.value"),
            vec![
                PathErrorStep::Field("test".into()),
                PathErrorStep::Field("x".into()),
                PathErrorStep::Field("field".into()),
                PathErrorStep::Index(42),
                PathErrorStep::Field("y".into()),
                PathErrorStep::Key("key".into()),
                PathErrorStep::Field("value".into()),
            ],
        );
    }
}