aviso-validators 0.4.1

Validation primitives used by aviso-server for identifier and payload checks.
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
// (C) Copyright 2024- ECMWF and individual contributors.
//
// This software is licensed under the terms of the Apache Licence Version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation nor
// does it submit to any jurisdiction.

//! Constraint parsing and evaluation helpers for identifier filters.
//!
//! These helpers are schema-agnostic and validate one constraint object at a time.

use anyhow::{Context, Result, bail};
use serde_json::Value;

#[derive(Debug, Clone, PartialEq)]
pub enum NumericConstraint<T> {
    Eq(T),
    In(Vec<T>),
    Gt(T),
    Gte(T),
    Lt(T),
    Lte(T),
    Between(T, T),
}

impl NumericConstraint<i64> {
    pub fn matches(&self, value: i64) -> bool {
        matches_numeric(self, value)
    }
}

impl NumericConstraint<f64> {
    pub fn matches(&self, value: f64) -> bool {
        if !value.is_finite() {
            return false;
        }
        // Exact comparison keeps replay/live filtering deterministic and avoids hidden
        // tolerance behavior when identifiers are canonicalized into topic tokens.
        matches_numeric(self, value)
    }
}

fn matches_numeric<T>(constraint: &NumericConstraint<T>, value: T) -> bool
where
    T: PartialOrd + PartialEq + Copy,
{
    match constraint {
        NumericConstraint::Eq(v) => value == *v,
        NumericConstraint::In(values) => values.contains(&value),
        NumericConstraint::Gt(v) => value > *v,
        NumericConstraint::Gte(v) => value >= *v,
        NumericConstraint::Lt(v) => value < *v,
        NumericConstraint::Lte(v) => value <= *v,
        NumericConstraint::Between(min, max) => value >= *min && value <= *max,
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum EnumConstraint {
    Eq(String),
    In(Vec<String>),
}

impl EnumConstraint {
    pub fn matches(&self, value: &str) -> bool {
        let canonical = value.to_lowercase();
        match self {
            EnumConstraint::Eq(v) => canonical == *v,
            EnumConstraint::In(values) => values.iter().any(|v| v == &canonical),
        }
    }
}

pub fn parse_int_constraint(
    field_name: &str,
    value: &Value,
    range: Option<&[i64; 2]>,
) -> Result<NumericConstraint<i64>> {
    let object = parse_constraint_object(field_name, value)?;
    let (operator, operand) = single_operator(field_name, object)?;

    let constraint = match operator {
        "eq" => NumericConstraint::Eq(parse_int_operand(field_name, operator, operand)?),
        "in" => NumericConstraint::In(parse_int_array_operand(field_name, operator, operand)?),
        "gt" => NumericConstraint::Gt(parse_int_operand(field_name, operator, operand)?),
        "gte" => NumericConstraint::Gte(parse_int_operand(field_name, operator, operand)?),
        "lt" => NumericConstraint::Lt(parse_int_operand(field_name, operator, operand)?),
        "lte" => NumericConstraint::Lte(parse_int_operand(field_name, operator, operand)?),
        "between" => {
            let (min, max) = parse_int_between_operand(field_name, operator, operand)?;
            NumericConstraint::Between(min, max)
        }
        _ => {
            bail!(
                "Field '{}' has invalid operator '{}'. Allowed: eq,in,gt,gte,lt,lte,between",
                field_name,
                operator
            )
        }
    };

    validate_int_constraint_against_range(field_name, &constraint, range)?;
    Ok(constraint)
}

pub fn parse_float_constraint(
    field_name: &str,
    value: &Value,
    range: Option<&[f64; 2]>,
) -> Result<NumericConstraint<f64>> {
    let object = parse_constraint_object(field_name, value)?;
    let (operator, operand) = single_operator(field_name, object)?;

    let constraint = match operator {
        "eq" => NumericConstraint::Eq(parse_float_operand(field_name, operator, operand)?),
        "in" => NumericConstraint::In(parse_float_array_operand(field_name, operator, operand)?),
        "gt" => NumericConstraint::Gt(parse_float_operand(field_name, operator, operand)?),
        "gte" => NumericConstraint::Gte(parse_float_operand(field_name, operator, operand)?),
        "lt" => NumericConstraint::Lt(parse_float_operand(field_name, operator, operand)?),
        "lte" => NumericConstraint::Lte(parse_float_operand(field_name, operator, operand)?),
        "between" => {
            let (min, max) = parse_float_between_operand(field_name, operator, operand)?;
            NumericConstraint::Between(min, max)
        }
        _ => {
            bail!(
                "Field '{}' has invalid operator '{}'. Allowed: eq,in,gt,gte,lt,lte,between",
                field_name,
                operator
            )
        }
    };

    validate_float_constraint_against_range(field_name, &constraint, range)?;
    Ok(constraint)
}

pub fn parse_enum_constraint(
    field_name: &str,
    value: &Value,
    allowed_values: &[String],
) -> Result<EnumConstraint> {
    let object = parse_constraint_object(field_name, value)?;
    let (operator, operand) = single_operator(field_name, object)?;
    let normalized_allowed: Vec<String> = allowed_values.iter().map(|v| v.to_lowercase()).collect();

    let constraint = match operator {
        "eq" => {
            let parsed = parse_enum_operand(field_name, operator, operand)?;
            validate_enum_value(field_name, &parsed, &normalized_allowed)?;
            EnumConstraint::Eq(parsed)
        }
        "in" => {
            let parsed = parse_enum_array_operand(field_name, operator, operand)?;
            for value in &parsed {
                validate_enum_value(field_name, value, &normalized_allowed)?;
            }
            EnumConstraint::In(parsed)
        }
        _ => {
            bail!(
                "Field '{}' has invalid operator '{}'. Allowed for enum constraints: eq,in",
                field_name,
                operator
            )
        }
    };

    Ok(constraint)
}

fn parse_constraint_object<'a>(
    field_name: &str,
    value: &'a Value,
) -> Result<&'a serde_json::Map<String, Value>> {
    value.as_object().ok_or_else(|| {
        anyhow::anyhow!(
            "Field '{}' constraint must be an object (for example {{\"gte\": 4}})",
            field_name
        )
    })
}

fn single_operator<'a>(
    field_name: &str,
    object: &'a serde_json::Map<String, Value>,
) -> Result<(&'a str, &'a Value)> {
    if object.len() != 1 {
        bail!(
            "Field '{}' constraint must contain exactly one operator",
            field_name
        );
    }
    let (operator, operand) = object
        .iter()
        .next()
        .context("constraint object unexpectedly empty")?;
    Ok((operator.as_str(), operand))
}

fn parse_int_operand(field_name: &str, operator: &str, value: &Value) -> Result<i64> {
    value.as_i64().ok_or_else(|| {
        anyhow::anyhow!(
            "Field '{}' operator '{}' expects integer value",
            field_name,
            operator
        )
    })
}

fn parse_int_array_operand(field_name: &str, operator: &str, value: &Value) -> Result<Vec<i64>> {
    let values = value.as_array().ok_or_else(|| {
        anyhow::anyhow!(
            "Field '{}' operator '{}' expects array of integers",
            field_name,
            operator
        )
    })?;
    if values.is_empty() {
        bail!(
            "Field '{}' operator '{}' must contain at least one value",
            field_name,
            operator
        );
    }
    values
        .iter()
        .map(|v| parse_int_operand(field_name, operator, v))
        .collect()
}

fn parse_int_between_operand(
    field_name: &str,
    operator: &str,
    value: &Value,
) -> Result<(i64, i64)> {
    let values = value.as_array().ok_or_else(|| {
        anyhow::anyhow!(
            "Field '{}' operator '{}' expects [min,max]",
            field_name,
            operator
        )
    })?;
    if values.len() != 2 {
        bail!(
            "Field '{}' operator '{}' expects exactly two values [min,max]",
            field_name,
            operator
        );
    }
    let min = parse_int_operand(field_name, operator, &values[0])?;
    let max = parse_int_operand(field_name, operator, &values[1])?;
    if min > max {
        bail!(
            "Field '{}' operator '{}' expects min <= max",
            field_name,
            operator
        );
    }
    Ok((min, max))
}

fn parse_float_operand(field_name: &str, operator: &str, value: &Value) -> Result<f64> {
    let parsed = value.as_f64().ok_or_else(|| {
        anyhow::anyhow!(
            "Field '{}' operator '{}' expects numeric value",
            field_name,
            operator
        )
    })?;

    if !parsed.is_finite() {
        bail!(
            "Field '{}' operator '{}' expects finite numeric value",
            field_name,
            operator
        );
    }

    Ok(parsed)
}

fn parse_float_array_operand(field_name: &str, operator: &str, value: &Value) -> Result<Vec<f64>> {
    let values = value.as_array().ok_or_else(|| {
        anyhow::anyhow!(
            "Field '{}' operator '{}' expects array of numbers",
            field_name,
            operator
        )
    })?;
    if values.is_empty() {
        bail!(
            "Field '{}' operator '{}' must contain at least one value",
            field_name,
            operator
        );
    }
    values
        .iter()
        .map(|v| parse_float_operand(field_name, operator, v))
        .collect()
}

fn parse_float_between_operand(
    field_name: &str,
    operator: &str,
    value: &Value,
) -> Result<(f64, f64)> {
    let values = value.as_array().ok_or_else(|| {
        anyhow::anyhow!(
            "Field '{}' operator '{}' expects [min,max]",
            field_name,
            operator
        )
    })?;
    if values.len() != 2 {
        bail!(
            "Field '{}' operator '{}' expects exactly two values [min,max]",
            field_name,
            operator
        );
    }
    let min = parse_float_operand(field_name, operator, &values[0])?;
    let max = parse_float_operand(field_name, operator, &values[1])?;
    if min > max {
        bail!(
            "Field '{}' operator '{}' expects min <= max",
            field_name,
            operator
        );
    }
    Ok((min, max))
}

fn parse_enum_operand(field_name: &str, operator: &str, value: &Value) -> Result<String> {
    value.as_str().map(|v| v.to_lowercase()).ok_or_else(|| {
        anyhow::anyhow!(
            "Field '{}' operator '{}' expects string value",
            field_name,
            operator
        )
    })
}

fn parse_enum_array_operand(
    field_name: &str,
    operator: &str,
    value: &Value,
) -> Result<Vec<String>> {
    let values = value.as_array().ok_or_else(|| {
        anyhow::anyhow!(
            "Field '{}' operator '{}' expects array of strings",
            field_name,
            operator
        )
    })?;
    if values.is_empty() {
        bail!(
            "Field '{}' operator '{}' must contain at least one value",
            field_name,
            operator
        );
    }
    values
        .iter()
        .map(|v| parse_enum_operand(field_name, operator, v))
        .collect()
}

fn validate_enum_value(field_name: &str, value: &str, allowed_values: &[String]) -> Result<()> {
    if !allowed_values.iter().any(|allowed| allowed == value) {
        bail!(
            "Field '{}' has invalid enum value '{}'. Allowed: [{}]",
            field_name,
            value,
            allowed_values.join(", ")
        );
    }
    Ok(())
}

fn validate_int_constraint_against_range(
    field_name: &str,
    constraint: &NumericConstraint<i64>,
    range: Option<&[i64; 2]>,
) -> Result<()> {
    let Some([min, max]) = range else {
        return Ok(());
    };

    validate_constraint_against_range(constraint, |value| {
        if value < *min || value > *max {
            bail!(
                "Field '{}' constraint value {} is outside allowed range [{}, {}]",
                field_name,
                value,
                min,
                max
            );
        }
        Ok(())
    })
}

fn validate_float_constraint_against_range(
    field_name: &str,
    constraint: &NumericConstraint<f64>,
    range: Option<&[f64; 2]>,
) -> Result<()> {
    let Some([min, max]) = range else {
        return Ok(());
    };

    // Float operands are validated as finite during parse_*_constraint.
    validate_constraint_against_range(constraint, |value| {
        if value < *min || value > *max {
            bail!(
                "Field '{}' constraint value {} is outside allowed range [{}, {}]",
                field_name,
                value,
                min,
                max
            );
        }
        Ok(())
    })
}

fn validate_constraint_against_range<T, F>(
    constraint: &NumericConstraint<T>,
    mut validate_operand: F,
) -> Result<()>
where
    T: Copy,
    F: FnMut(T) -> Result<()>,
{
    match constraint {
        NumericConstraint::Eq(v)
        | NumericConstraint::Gt(v)
        | NumericConstraint::Gte(v)
        | NumericConstraint::Lt(v)
        | NumericConstraint::Lte(v) => validate_operand(*v),
        NumericConstraint::In(values) => {
            for value in values {
                validate_operand(*value)?;
            }
            Ok(())
        }
        NumericConstraint::Between(from, to) => {
            validate_operand(*from)?;
            validate_operand(*to)
        }
    }
}

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

    #[test]
    fn int_constraint_parsing_and_matching_works() {
        let constraint = parse_int_constraint("severity", &json!({"gte": 4}), Some(&[1, 7]))
            .expect("constraint should parse");
        assert!(constraint.matches(4));
        assert!(constraint.matches(7));
        assert!(!constraint.matches(3));
    }

    #[test]
    fn int_constraint_rejects_unknown_operator() {
        let result = parse_int_constraint("severity", &json!({"ge": 4}), Some(&[1, 7]));
        assert!(result.is_err());
    }

    #[test]
    fn int_constraint_rejects_out_of_range_operand() {
        let result = parse_int_constraint("severity", &json!({"gte": 9}), Some(&[1, 7]));
        assert!(result.is_err());
    }

    #[test]
    fn int_between_requires_ordered_bounds() {
        let result = parse_int_constraint("severity", &json!({"between": [6, 2]}), Some(&[1, 7]));
        assert!(result.is_err());
    }

    #[test]
    fn enum_constraint_in_works_case_insensitive() {
        let constraint = parse_enum_constraint(
            "alert_level",
            &json!({"in": ["High", "Critical"]}),
            &[
                "low".to_string(),
                "high".to_string(),
                "critical".to_string(),
            ],
        )
        .expect("enum constraint should parse");
        assert!(constraint.matches("high"));
        assert!(constraint.matches("CRITICAL"));
        assert!(!constraint.matches("low"));
    }

    #[test]
    fn enum_constraint_rejects_invalid_members() {
        let result = parse_enum_constraint(
            "alert_level",
            &json!({"in": ["high", "urgent"]}),
            &[
                "low".to_string(),
                "high".to_string(),
                "critical".to_string(),
            ],
        );
        assert!(result.is_err());
    }

    #[test]
    fn float_constraint_parses_and_matches() {
        let constraint =
            parse_float_constraint("temperature", &json!({"between": [10.5, 20.5]}), None)
                .expect("float constraint should parse");
        assert!(constraint.matches(15.0));
        assert!(!constraint.matches(22.0));
    }

    #[test]
    fn float_eq_uses_exact_comparison() {
        let constraint =
            parse_float_constraint("temperature", &json!({"eq": 0.3}), None).expect("valid eq");
        assert!(constraint.matches(0.3));
        assert!(!constraint.matches(0.1 + 0.2));
    }

    #[test]
    fn float_in_uses_exact_comparison() {
        let constraint = parse_float_constraint("temperature", &json!({"in": [0.3, 1.5]}), None)
            .expect("valid in");
        assert!(constraint.matches(0.3));
        assert!(!constraint.matches(0.1 + 0.2));
    }

    #[test]
    fn float_between_is_inclusive() {
        let constraint =
            parse_float_constraint("temperature", &json!({"between": [10.5, 20.5]}), None)
                .expect("float between should parse");
        assert!(constraint.matches(10.5));
        assert!(constraint.matches(20.5));
        assert!(!constraint.matches(20.5000001));
    }

    #[test]
    fn float_constraint_rejects_non_finite_notification_values() {
        let constraint =
            parse_float_constraint("temperature", &json!({"gt": 3.0}), None).expect("valid gt");
        assert!(!constraint.matches(f64::NAN));
        assert!(!constraint.matches(f64::INFINITY));
        assert!(!constraint.matches(f64::NEG_INFINITY));
    }

    #[test]
    fn float_constraint_rejects_out_of_range_operand() {
        let result =
            parse_float_constraint("temperature", &json!({"gt": 21.0}), Some(&[10.0, 20.0]));
        assert!(result.is_err());
    }
}