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
use crate::config::ValidationError;
use prometheus::Error as MetricsError;
#[cfg(doc)]
use crate::filters::{Filter, FilterFactory};
#[derive(Debug, PartialEq, thiserror::Error)]
pub enum Error {
#[error("filter `{}` not found", .0)]
NotFound(String),
#[error("filter `{}` requires configuration, but none provided", .0)]
MissingConfig(&'static str),
#[error("field `{}` is invalid, reason: {}", field, reason)]
FieldInvalid { field: String, reason: String },
#[error("Deserialization failed: {}", .0)]
DeserializeFailed(String),
#[error("Failed to initialize metrics: {}", .0)]
InitializeMetricsFailed(String),
#[error("Protobuf error: {}", .0)]
ConvertProtoConfig(ConvertProtoConfigError),
}
impl From<Error> for ValidationError {
fn from(error: Error) -> Self {
Self::FilterInvalid(error)
}
}
impl From<MetricsError> for Error {
fn from(error: MetricsError) -> Self {
Error::InitializeMetricsFailed(error.to_string())
}
}
#[derive(Debug, PartialEq, thiserror::Error)]
#[error(
"{}failed to convert protobuf config: {}",
self.field.as_ref().map(|f| format!("Field `{}` ", f)).unwrap_or_default(),
reason
)]
pub struct ConvertProtoConfigError {
reason: String,
field: Option<String>,
}
impl ConvertProtoConfigError {
pub fn new(reason: impl Into<String>, field: Option<String>) -> Self {
Self {
reason: reason.into(),
field,
}
}
}
#[macro_export]
macro_rules! enum_no_match_error {
(
field = $field:literal,
invalid_value = $invalid_value:ident,
enum_type = $enum_type:ty,
allowed_values = [ $( $allowed_value:tt ),+ ]
) => {
Err($crate::filters::error::ConvertProtoConfigError::new(
format!(
"invalid value `{}` provided: allowed values are {}",
$invalid_value,
vec![
$( (stringify!($allowed_value), <$enum_type>::$allowed_value as i32) ),+
]
.into_iter()
.map(|(a, b)| format!("{} => {}", a, b as i32))
.collect::<Vec<_>>()
.join(", ")
),
Some($field.into()),
))
};
}
#[macro_export]
macro_rules! map_proto_enum {
(
value = $value:expr,
field = $field:literal,
proto_enum_type = $proto_enum_type:ty,
target_enum_type = $target_enum_type:ty,
variants = [ $( $variant:tt ),+ ]
) => {
match $value {
$( v if v == <$proto_enum_type>::$variant as i32 => Ok(<$target_enum_type>::$variant) ),+,
invalid => $crate::enum_no_match_error!(
field = $field,
invalid_value = invalid,
enum_type = $proto_enum_type,
allowed_values = [ $( $variant ),+ ]
)
}
}
}