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
//! Alert rule definitions and condition expressions
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Threshold comparison operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ThresholdOperator {
/// Value is greater than threshold.
GreaterThan,
/// Value is greater than or equal to threshold.
GreaterThanOrEqual,
/// Value is less than threshold.
LessThan,
/// Value is less than or equal to threshold.
LessThanOrEqual,
/// Value equals threshold.
Equal,
/// Value does not equal threshold.
NotEqual,
}
impl ThresholdOperator {
/// Evaluate the operator with two values.
#[must_use]
pub fn evaluate(&self, value: f64, threshold: f64) -> bool {
match self {
Self::GreaterThan => value > threshold,
Self::GreaterThanOrEqual => value >= threshold,
Self::LessThan => value < threshold,
Self::LessThanOrEqual => value <= threshold,
Self::Equal => (value - threshold).abs() < f64::EPSILON,
Self::NotEqual => (value - threshold).abs() >= f64::EPSILON,
}
}
}
/// Aggregation functions for metric queries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AggregationFunction {
/// Average of values.
Avg,
/// Sum of values.
Sum,
/// Minimum value.
Min,
/// Maximum value.
Max,
/// Count of values.
Count,
/// Rate of change.
Rate,
/// Percentile (e.g., 95th).
Percentile(u8),
}
/// Condition expression for alert rules.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ConditionExpression {
/// Simple threshold condition.
Threshold {
/// Metric name to query.
metric: String,
/// Comparison operator.
operator: ThresholdOperator,
/// Threshold value.
value: f64,
},
/// Threshold with aggregation over a time range.
AggregatedThreshold {
/// Metric name to query.
metric: String,
/// Aggregation function to apply.
aggregation: AggregationFunction,
/// Time window for aggregation in seconds.
window_seconds: u64,
/// Comparison operator.
operator: ThresholdOperator,
/// Threshold value.
value: f64,
},
/// Rate of change condition.
RateOfChange {
/// Metric name to query.
metric: String,
/// Time window for rate calculation in seconds.
window_seconds: u64,
/// Comparison operator for rate.
operator: ThresholdOperator,
/// Rate threshold (units per second).
rate_threshold: f64,
},
/// Absence of data condition.
Absent {
/// Metric name to check.
metric: String,
/// Time window to check for absence in seconds.
for_seconds: u64,
},
/// Logical AND of multiple conditions.
And(Vec<ConditionExpression>),
/// Logical OR of multiple conditions.
Or(Vec<ConditionExpression>),
/// Logical NOT of a condition.
Not(Box<ConditionExpression>),
/// Label-based condition.
LabelMatch {
/// Label name.
label: String,
/// Expected value (regex pattern).
pattern: String,
},
}
impl ConditionExpression {
/// Create a simple threshold condition.
pub fn threshold(metric: impl Into<String>, operator: ThresholdOperator, value: f64) -> Self {
Self::Threshold {
metric: metric.into(),
operator,
value,
}
}
/// Create an aggregated threshold condition.
pub fn aggregated_threshold(
metric: impl Into<String>,
aggregation: AggregationFunction,
window_seconds: u64,
operator: ThresholdOperator,
value: f64,
) -> Self {
Self::AggregatedThreshold {
metric: metric.into(),
aggregation,
window_seconds,
operator,
value,
}
}
/// Create an AND condition.
pub fn and(conditions: Vec<ConditionExpression>) -> Self {
Self::And(conditions)
}
/// Create an OR condition.
pub fn or(conditions: Vec<ConditionExpression>) -> Self {
Self::Or(conditions)
}
/// Create a NOT condition.
pub fn not(condition: ConditionExpression) -> Self {
Self::Not(Box::new(condition))
}
}
/// Complete alert rule definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertRuleDefinition {
/// Unique identifier for the rule.
pub id: String,
/// Human-readable name.
pub name: String,
/// Detailed description.
pub description: String,
/// Alert severity level.
pub level: super::AlertLevel,
/// Condition expression to evaluate.
pub condition: Option<ConditionExpression>,
/// Duration to wait before firing (pending period).
pub pending_duration: std::time::Duration,
/// Labels to attach to fired alerts.
pub labels: HashMap<String, String>,
/// Annotations for additional context.
pub annotations: HashMap<String, String>,
/// Grouping keys for alert aggregation.
pub group_by: Vec<String>,
/// Rule is enabled.
pub enabled: bool,
/// Evaluation interval in seconds.
pub eval_interval_seconds: u64,
/// Runbook URL for remediation steps.
pub runbook_url: Option<String>,
/// Dashboard URL for investigation.
pub dashboard_url: Option<String>,
}
impl AlertRuleDefinition {
/// Create a new alert rule with the given ID.
pub fn new(id: impl Into<String>) -> Self {
let id_str = id.into();
Self {
id: id_str.clone(),
name: id_str,
description: String::new(),
level: super::AlertLevel::default(),
condition: None,
pending_duration: std::time::Duration::from_secs(0),
labels: HashMap::new(),
annotations: HashMap::new(),
group_by: Vec::new(),
enabled: true,
eval_interval_seconds: 60,
runbook_url: None,
dashboard_url: None,
}
}
/// Set the rule name.
#[must_use]
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = name.into();
self
}
/// Set the description.
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = description.into();
self
}
/// Set the alert level.
#[must_use]
pub const fn with_severity(mut self, level: super::AlertLevel) -> Self {
self.level = level;
self
}
/// Set the condition expression.
#[must_use]
pub fn with_condition(mut self, condition: ConditionExpression) -> Self {
self.condition = Some(condition);
self
}
/// Set the pending duration.
#[must_use]
pub const fn with_pending_duration(mut self, duration: std::time::Duration) -> Self {
self.pending_duration = duration;
self
}
/// Add a label.
#[must_use]
pub fn with_label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.labels.insert(key.into(), value.into());
self
}
/// Add an annotation.
#[must_use]
pub fn with_annotation(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.annotations.insert(key.into(), value.into());
self
}
/// Set grouping keys.
#[must_use]
pub fn with_group_by(mut self, keys: Vec<String>) -> Self {
self.group_by = keys;
self
}
/// Set runbook URL.
#[must_use]
pub fn with_runbook_url(mut self, url: impl Into<String>) -> Self {
self.runbook_url = Some(url.into());
self
}
/// Set dashboard URL.
#[must_use]
pub fn with_dashboard_url(mut self, url: impl Into<String>) -> Self {
self.dashboard_url = Some(url.into());
self
}
/// Enable or disable the rule.
#[must_use]
pub const fn enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
}