reductstore 1.19.8

ReductStore is a time series database designed specifically for storing and managing large amounts of blob data.
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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
// Copyright 2021-2026 ReductSoftware UG
// Licensed under the Apache License, Version 2.0

use crate::storage::query::condition::computed_reference::ComputedReference;
use crate::storage::query::condition::constant::Constant;
use crate::storage::query::condition::operators::aggregation::{EachN, EachT, Gate, Limit};
use crate::storage::query::condition::operators::arithmetic::{
    Abs, Add, Div, DivNum, Mult, Rem, Sub,
};
use crate::storage::query::condition::operators::comparison::{Eq, Gt, Gte, Lt, Lte, Ne};
use crate::storage::query::condition::operators::date::{
    Day, Hour, Minute, Month, Second, Weekday, Year,
};
use crate::storage::query::condition::operators::logical::{AllOf, AnyOf, In, Nin, NoneOf, OneOf};
use crate::storage::query::condition::operators::misc::{Cast, Exists, Ref, Timestamp};
use crate::storage::query::condition::operators::string::{Contains, EndsWith, StartsWith};
use crate::storage::query::condition::reference::Reference;
use crate::storage::query::condition::value::{parse_duration, Value};
use crate::storage::query::condition::{Boxed, BoxedNode};
use reduct_base::error::ReductError;
use reduct_base::unprocessable_entity;
use serde_json::{Map, Number, Value as JsonValue};
use std::collections::HashMap;

/// Parses a JSON object into a condition tree.
pub(crate) struct Parser {}

pub(crate) type Directives = HashMap<String, Vec<Value>>;
static DIRECTIVES: [&str; 10] = [
    "#ctx_before",
    "#ctx_after",
    "#select_labels",
    "#ext",
    // query execution directives
    "#batch_size",
    "#batch_records",
    "#batch_metadata_size",
    "#batch_timeout",
    "#record_timeout",
    "#io_timeout",
];

impl Parser {
    /// Parses a JSON object into a condition tree.
    ///
    /// # Arguments
    ///
    /// * `json` - A JSON value representing the condition.
    ///
    /// # Returns
    ///
    /// A boxed node representing the condition tree.
    /// The root node is a `StagedAllOf` that aggregates all expressions
    pub fn parse(&self, mut json: JsonValue) -> Result<(BoxedNode, Directives), ReductError> {
        // parse directives if any
        let directives = Self::parse_directives(&mut json)?;
        let expressions = Self::parse_recursively(&json)?;
        Ok((AllOf::boxed(expressions)?, directives))
    }

    fn parse_directives(json: &mut JsonValue) -> Result<Directives, ReductError> {
        let mut directives = Directives::new();
        let mut keys_to_remove = vec![];
        for (key, value) in json.as_object().unwrap_or(&Map::new()).iter() {
            if key.starts_with("#") {
                if !DIRECTIVES.contains(&key.as_str()) {
                    return Err(unprocessable_entity!(
                        "Directive '{}' is not supported",
                        key
                    ));
                }

                let parse_primitive = |v: &JsonValue| -> Value {
                    match v {
                        JsonValue::Bool(value) => Value::Bool(*value),
                        JsonValue::Number(value) => {
                            if value.is_i64() || value.is_u64() {
                                Value::Int(value.as_i64().unwrap())
                            } else {
                                Value::Float(value.as_f64().unwrap())
                            }
                        }
                        JsonValue::String(value) => {
                            if let Ok(duration) = parse_duration(value) {
                                duration
                            } else {
                                Value::String(value.to_string())
                            }
                        }
                        _ => panic!("Unsupported directive value type: {}", v), // panic because it's programming error
                    }
                };

                let mut parsed_values = vec![];

                if value.is_null() {
                    return Err(unprocessable_entity!("Directive '{}' cannot be null", key));
                } else if value.is_object() {
                    // store the object as a string
                    parsed_values.push(Value::String(value.to_string()));
                } else if value.is_array() {
                    for item in value.as_array().unwrap() {
                        parsed_values.push(parse_primitive(item));
                    }
                } else {
                    parsed_values.push(parse_primitive(value))
                }
                directives.insert(key.to_string(), parsed_values);
                keys_to_remove.push(key.to_string());
            }
        }

        // Remove directives from the original JSON object
        for key in keys_to_remove {
            json.as_object_mut().unwrap().shift_remove(&key);
        }
        Ok(directives)
    }

    fn parse_recursively(json: &JsonValue) -> Result<Vec<BoxedNode>, ReductError> {
        match json {
            JsonValue::Object(map) => Self::parse_object(map),
            JsonValue::Bool(value) => Self::parse_bool(value),
            JsonValue::Number(value) => Self::parse_number(value),
            JsonValue::String(value) => Self::parse_literal(value),
            JsonValue::Array(_) => Err(unprocessable_entity!(
                "Array type is not supported: {}",
                json
            )),
            JsonValue::Null => Err(unprocessable_entity!(
                "Null type is not supported: {}",
                json
            )),
        }
    }

    fn parse_object(map: &Map<String, serde_json::Value>) -> Result<Vec<BoxedNode>, ReductError> {
        let mut expressions = vec![];
        for (key, value) in map.iter() {
            if let JsonValue::Array(operand_list) = value {
                // Parse array notation e.g. {"$and": [true, true]}
                expressions.push(Self::parse_array_syntax(key, operand_list)?);
            } else if let JsonValue::Object(operator_right_operand) = value {
                // Parse object notation e.g. {"&label": {"$and": true}}
                expressions.push(Self::parse_object_syntax(key, operator_right_operand)?);
            } else {
                // For unary operators, we need to parse the value
                let operands = Self::parse_recursively(value)?;
                let operator = Self::parse_operator(key, operands)?;
                expressions.push(operator);
            }
        }

        // We use AND operator to aggregate results from all expressions
        Ok(expressions)
    }

    fn parse_bool(value: &bool) -> Result<Vec<BoxedNode>, ReductError> {
        Ok(vec![Constant::boxed(Value::Bool(*value))])
    }

    fn parse_number(value: &Number) -> Result<Vec<BoxedNode>, ReductError> {
        if value.is_i64() || value.is_u64() {
            Ok(vec![Constant::boxed(Value::Int(value.as_i64().unwrap()))])
        } else {
            Ok(vec![Constant::boxed(Value::Float(value.as_f64().unwrap()))])
        }
    }

    fn parse_literal(value: &str) -> Result<Vec<BoxedNode>, ReductError> {
        if value.starts_with("&") {
            Ok(vec![Reference::boxed(value[1..].to_string())])
        } else if value.starts_with("@") {
            Ok(vec![ComputedReference::boxed(value[1..].to_string())])
        } else if let Some(value) = value.strip_prefix("$$") {
            Ok(vec![Constant::boxed(Value::String(format!("${value}")))])
        } else if value.starts_with("$") {
            match Self::parse_operator(value, vec![]) {
                Ok(operator) => Ok(vec![operator]),
                Err(_) => Err(unprocessable_entity!(
                    "Unknown '$' literal '{}'; use '$$' to escape a string value",
                    value
                )),
            }
        } else if let Ok(duration) = parse_duration(value) {
            Ok(vec![Constant::boxed(duration)])
        } else {
            Ok(vec![Constant::boxed(Value::String(value.to_string()))])
        }
    }

    fn parse_array_syntax(
        operator: &str,
        json_operands: &Vec<JsonValue>,
    ) -> Result<BoxedNode, ReductError> {
        let mut operands = vec![];
        for operand in json_operands {
            operands.extend(Self::parse_recursively(operand)?);
        }
        Self::parse_operator(operator, operands)
    }

    fn parse_object_syntax(
        left_operand: &str,
        op_right_operand: &Map<String, JsonValue>,
    ) -> Result<BoxedNode, ReductError> {
        let mut left_operand =
            Self::parse_recursively(&JsonValue::String(left_operand.to_string()))?;
        if op_right_operand.len() != 1 {
            return Err(unprocessable_entity!(
                "Object notation must have exactly one operator"
            ));
        }

        let (operator, operand) = op_right_operand.iter().next().unwrap();
        let right_operand = Self::parse_recursively(operand)?;
        left_operand.extend(right_operand);
        Self::parse_operator(operator, left_operand)
    }

    fn parse_operator(operator: &str, operands: Vec<BoxedNode>) -> Result<BoxedNode, ReductError> {
        if !operator.starts_with("$") {
            return Err(unprocessable_entity!(
                "Operator '{}' must start with '$'",
                operator
            ));
        }

        match operator {
            // Aggregation operators
            "$each_n" => EachN::boxed(operands),
            "$each_t" => EachT::boxed(operands),
            "$gate" => Gate::boxed(operands),
            "$limit" => Limit::boxed(operands),
            // Arithmetic operators
            "$add" => Add::boxed(operands),
            "$sub" => Sub::boxed(operands),
            "$mult" => Mult::boxed(operands),
            "$div" => Div::boxed(operands),
            "$div_num" => DivNum::boxed(operands),
            "$rem" => Rem::boxed(operands),
            "$abs" => Abs::boxed(operands),

            // Logical operators
            "$and" | "$all_of" => AllOf::boxed(operands),
            "$or" | "$any_of" => AnyOf::boxed(operands),
            "$not" | "$none_of" => NoneOf::boxed(operands),
            "$xor" | "$one_of" => OneOf::boxed(operands),
            "$in" => In::boxed(operands),
            "$nin" => Nin::boxed(operands),

            // Comparison operators
            "$eq" => Eq::boxed(operands),
            "$gt" => Gt::boxed(operands),
            "$gte" => Gte::boxed(operands),
            "$lt" => Lt::boxed(operands),
            "$lte" => Lte::boxed(operands),
            "$ne" => Ne::boxed(operands),

            // Date operators
            "$second" => Second::boxed(operands),
            "$minute" => Minute::boxed(operands),
            "$hour" => Hour::boxed(operands),
            "$day" => Day::boxed(operands),
            "$month" => Month::boxed(operands),
            "$year" => Year::boxed(operands),
            "$weekday" => Weekday::boxed(operands),

            // String operators
            "$contains" => Contains::boxed(operands),
            "$starts_with" => StartsWith::boxed(operands),
            "$ends_with" => EndsWith::boxed(operands),

            // Misc
            "$exists" | "$has" => Exists::boxed(operands),
            "$cast" => Cast::boxed(operands),
            "$ref" => Ref::boxed(operands),
            "$timestamp" | "$id" => Timestamp::boxed(operands),

            _ => Err(unprocessable_entity!(
                "Operator '{}' not supported",
                operator
            )),
        }
    }
}

impl Parser {
    pub fn new() -> Self {
        Self {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::query::condition::Context;
    use rstest::{fixture, rstest};
    use serde_json::json;
    use std::collections::HashMap;

    #[rstest]
    fn test_parser_array_syntax(parser: Parser, context: Context) {
        let json = json!({
        "$and": [true, {"$gt": [20, 10]}]
        });
        let (mut node, _) = parser.parse(json).unwrap();
        assert!(node.apply(&context).unwrap().as_bool().unwrap());
    }

    #[rstest]
    fn test_parser_object_syntax(parser: Parser) {
        let json = json!({
            "&label": {"$gt": 10}
        });
        let (mut node, _) = parser.parse(json).unwrap();
        let context = Context::new(0, HashMap::from_iter(vec![("label", "20")]), HashMap::new());
        assert!(node.apply(&context).unwrap().as_bool().unwrap());
    }

    #[rstest]
    fn test_parse_int(parser: Parser, context: Context) {
        let json = json!({
            "$and": [1, -2]
        });
        let (mut node, _) = parser.parse(json).unwrap();
        assert!(node.apply(&context).unwrap().as_bool().unwrap());
    }

    #[rstest]
    fn test_parse_float(parser: Parser, context: Context) {
        let json = json!({
            "$and": [1.1, -2.2]
        });
        let (mut node, _) = parser.parse(json).unwrap();
        assert!(node.apply(&context).unwrap().as_bool().unwrap());
    }

    #[rstest]
    fn test_parse_string(parser: Parser, context: Context) {
        let json = json!({
            "$and": ["a","b"]
        });
        let (mut node, _) = parser.parse(json).unwrap();
        assert!(node.apply(&context).unwrap().as_bool().unwrap());
    }

    #[rstest]
    fn test_parse_escaped_dollar_string_literal(parser: Parser, context: Context) {
        let json = json!({
            "$eq": ["$$plugin", "$$plugin"]
        });
        let (mut node, _) = parser.parse(json).unwrap();
        assert!(node.apply(&context).unwrap().as_bool().unwrap());
    }

    #[rstest]
    fn test_parse_computed_reference_literal(parser: Parser) {
        let json = json!({
            "$eq": ["@value", 10]
        });
        let (mut node, _) = parser.parse(json).unwrap();
        let mut context = Context::default();
        context.computed_labels.insert("value", "10");
        assert!(node.apply(&context).unwrap().as_bool().unwrap());
    }

    #[rstest]
    fn test_parse_object_syntax_with_escaped_dollar_string_literal(
        parser: Parser,
        context: Context,
    ) {
        let json = json!({
            "&label": {"$eq": "$$x"}
        });
        let (mut node, _) = parser.parse(json).unwrap();
        assert!(!node.apply(&context).unwrap().as_bool().unwrap());
    }

    #[rstest]
    fn test_parse_in_operator_with_escaped_dollar_string_literal(parser: Parser, context: Context) {
        let json = json!({
            "$in": ["&label", "$$x"]
        });
        let (mut node, _) = parser.parse(json).unwrap();
        assert!(!node.apply(&context).unwrap().as_bool().unwrap());
    }

    #[rstest]
    fn test_parse_unknown_dollar_key_is_rejected(parser: Parser) {
        let json = json!({
            "$plugin": {"$eq": "value"}
        });
        let result = parser.parse(json);
        assert_eq!(
            result.err().unwrap().to_string(),
            "[UnprocessableEntity] Unknown '$' literal '$plugin'; use '$$' to escape a string value"
        );
    }

    #[rstest]
    fn test_parse_unknown_dollar_string_literal_is_rejected(parser: Parser) {
        let json = json!({
            "$eq": ["$plugin", "$plugin"]
        });
        let result = parser.parse(json);
        assert_eq!(
            result.err().unwrap().to_string(),
            "[UnprocessableEntity] Unknown '$' literal '$plugin'; use '$$' to escape a string value"
        );
    }

    #[rstest]
    fn test_parse_object_syntax_with_escaped_dollar_key_literal(parser: Parser) {
        let json = json!({
            "$$plugin": {"$eq": "$$plugin"}
        });
        let (mut node, _) = parser.parse(json).unwrap();
        assert!(node.apply(&Context::default()).unwrap().as_bool().unwrap());
    }

    #[rstest]
    fn test_parse_duration(parser: Parser, context: Context) {
        let json = json!({
            "$eq": ["1h", 3600_000_000u64]
        });
        let (mut node, _) = parser.parse(json).unwrap();
        assert!(node.apply(&context).unwrap().as_bool().unwrap());
    }

    #[rstest]
    fn test_parser_multiline(parser: Parser) {
        let json = json!({
            "$and": [
                {"&label": {"$and": true}},
                true
            ]
        }        );

        let (mut node, _) = parser.parse(json).unwrap();
        let context = Context::new(
            0,
            HashMap::from_iter(vec![("label", "true")]),
            HashMap::new(),
        );
        assert!(node.apply(&context).unwrap().as_bool().unwrap());
    }

    #[rstest]
    fn test_parse_nullary_operator(parser: Parser, context: Context) {
        let json = json!({
            "$add": [
                "$timestamp",
                1
            ]
        });
        let (mut node, _) = parser.parse(json).unwrap();
        assert_eq!(node.apply(&context).unwrap(), Value::Int(1));
    }

    #[rstest]
    fn test_parse_unary_operator(parser: Parser, context: Context) {
        let json = json!({
        "$limit": 100
        });
        let (mut node, _) = parser.parse(json).unwrap();
        assert_eq!(node.apply(&context).unwrap(), Value::Int(1));
    }

    #[rstest]
    fn test_parser_invalid_operator(parser: Parser) {
        let json = json!( {
            "$xx": [true, true]
        });
        let result = parser.parse(json);
        assert_eq!(
            result.err().unwrap().to_string(),
            "[UnprocessableEntity] Operator '$xx' not supported"
        );
    }

    #[rstest]
    fn test_parser_invalid_object_notation(parser: Parser) {
        let json = json!({
                "&ref": {
                    "$and": true,
                    "x": "y"
                }
            }        );
        let result = parser.parse(json);
        assert_eq!(
            result.err().unwrap().to_string(),
            "[UnprocessableEntity] Object notation must have exactly one operator"
        );
    }

    #[rstest]
    fn test_parser_invalid_array_type(parser: Parser) {
        let json = json!({
            "&label": {
                "$in": [10, 20]
            }
        });
        let result = parser.parse(json);
        assert_eq!(
            result.err().unwrap().to_string(),
            "[UnprocessableEntity] Array type is not supported: [10,20]"
        );
    }

    #[rstest]
    fn test_parser_invalid_null(parser: Parser) {
        let json = json!({
            "&ref": {
                "$and": null
            }
        });
        let result = parser.parse(json);
        assert_eq!(
            result.err().unwrap().to_string(),
            "[UnprocessableEntity] Null type is not supported: null"
        );
    }

    #[rstest]
    fn test_parser_invalid_operator_without_dollar(parser: Parser) {
        let json = json!({
            "and": [true, true]
        });
        let result = parser.parse(json);
        assert_eq!(
            result.err().unwrap().to_string(),
            "[UnprocessableEntity] Operator 'and' must start with '$'"
        );
    }

    mod parse_directives {
        use super::*;
        use rstest::rstest;
        use serde::Serialize;

        #[rstest]
        fn test_parse_directives(parser: Parser) {
            let json = json!({
                "#ctx_before": "1h",
                "#ctx_after": "2h",
                "#select_labels": ["label1", "label2"]
            });
            let (_, directives) = parser.parse(json).unwrap();
            assert_eq!(directives.len(), 3);
            assert_eq!(
                directives["#ctx_before"],
                vec![Value::Duration(3600_000_000)]
            );
            assert_eq!(
                directives["#ctx_after"],
                vec![Value::Duration(7200_000_000)]
            );
            assert_eq!(
                directives["#select_labels"],
                vec![
                    Value::String("label1".to_string()),
                    Value::String("label2".to_string())
                ]
            );
        }

        #[rstest]
        #[case(true, Value::Bool(true))]
        #[case(123, Value::Int(123))]
        #[case(123.45, Value::Float(123.45))]
        #[case("test", Value::String("test".to_string()))]
        fn test_parse_directives_primitive_values<T: Serialize>(
            parser: Parser,
            #[case] value: T,
            #[case] expected: Value,
        ) {
            let json = json!({
                "#ctx_before": value,
            });
            let (_, directives) = parser.parse(json).unwrap();
            assert_eq!(directives["#ctx_before"], vec![expected]);
        }

        #[rstest]
        fn test_parse_array_directives(parser: Parser) {
            let json = json!({
                "#select_labels": ["label1", "label2"]
            });
            let (_, directives) = parser.parse(json).unwrap();
            assert_eq!(
                directives["#select_labels"],
                vec![
                    Value::String("label1".to_string()),
                    Value::String("label2".to_string())
                ]
            );
        }

        #[rstest]
        fn test_parse_invalid_directive(parser: Parser) {
            let json = json!({
                "#invalid_directive": "value"
            });
            let result = parser.parse(json);
            assert_eq!(
                result.err().unwrap().to_string(),
                "[UnprocessableEntity] Directive '#invalid_directive' is not supported"
            );
        }

        #[rstest]
        fn test_parse_object_directive(parser: Parser) {
            let json = json!({
                "#ext": {"key": "value"}
            });
            let (_, directives) = parser.parse(json).unwrap();
            assert_eq!(
                directives.get("#ext").unwrap(),
                &vec![Value::String(r#"{"key":"value"}"#.to_string())]
            );
        }

        #[rstest]
        fn test_parse_null_directive(parser: Parser) {
            let json = json!({
                "#ctx_before": null
            });

            let result = parser.parse(json);
            assert_eq!(
                result.err().unwrap().to_string(),
                "[UnprocessableEntity] Directive '#ctx_before' cannot be null"
            );
        }
    }

    mod parse_operators {
        use super::*;
        use crate::storage::query::condition::Node;

        #[rstest]
        // Aggregation operators
        #[case("$each_n", "[1]", Value::Bool(true))]
        #[case("$each_t", "[1]", Value::Bool(false))]
        #[case("$gate", "[\"10s\", true]", Value::Bool(true))]
        #[case("$limit", "[1]", Value::Bool(true))]
        // Arithmetic operators
        #[case("$add", "[1, 2.0]", Value::Float(3.0))]
        #[case("$sub", "[1, 2]", Value::Int(-1))]
        #[case("$mult", "[2, 3]", Value::Int(6))]
        #[case("$div", "[3, 2]", Value::Float(1.5))]
        #[case("$div_num", "[3, 2]", Value::Int(1))]
        #[case("$rem", "[-10, 6]", Value::Int(-4))]
        #[case("$abs", "[-10]", Value::Int(10))]
        // Logical operators
        #[case("$and", "[true, false]", Value::Bool(false))]
        #[case("$all_of", "[true, false]", Value::Bool(false))]
        #[case("$or", "[true, false]", Value::Bool(true))]
        #[case("$any_of", "[true, false]", Value::Bool(true))]
        #[case("$not", "[true]", Value::Bool(false))]
        #[case("$none_of", "[true, true]", Value::Bool(false))]
        #[case("$xor", "[true, true]", Value::Bool(false))]
        #[case("$one_of", "[true, true]", Value::Bool(false))]
        #[case("$in", "[\"a\", \"a\", \"b\"]", Value::Bool(true))]
        #[case("$nin", "[\"a\", \"a\", \"b\"]", Value::Bool(false))]
        // Comparison operators
        #[case("$eq", "[10, 10]", Value::Bool(true))]
        #[case("$gt", "[20, 10]", Value::Bool(true))]
        #[case("$gte", "[20, 10]", Value::Bool(true))]
        #[case("$lt", "[20, 10]", Value::Bool(false))]
        #[case("$lte", "[20, 10]", Value::Bool(false))]
        #[case("$ne", "[-10, 10]", Value::Bool(true))]
        // Date operators
        #[case("$second", "[1704067200123456]", Value::Int(0))]
        #[case("$second", "[1704067200123456, \"Europe/Berlin\"]", Value::Int(0))]
        #[case("$minute", "[1704067200123456]", Value::Int(0))]
        #[case("$minute", "[1704067200123456, \"Europe/Berlin\"]", Value::Int(0))]
        #[case("$hour", "[1704067200123456]", Value::Int(0))]
        #[case("$hour", "[1704067200123456, \"Europe/Berlin\"]", Value::Int(1))]
        #[case("$day", "[1704067200123456]", Value::Int(1))]
        #[case("$day", "[1704067200123456, \"America/New_York\"]", Value::Int(31))]
        #[case("$month", "[1704067200123456]", Value::Int(1))]
        #[case("$month", "[1704067200123456, \"America/New_York\"]", Value::Int(12))]
        #[case("$year", "[1704067200123456]", Value::Int(2024))]
        #[case("$year", "[1704067200123456, \"America/New_York\"]", Value::Int(2023))]
        #[case("$weekday", "[1704067200123456]", Value::Int(0))]
        #[case("$weekday", "[1704067200123456, \"America/New_York\"]", Value::Int(6))]
        // String operators
        #[case("$contains", "[\"abc\", \"b\"]", Value::Bool(true))]
        #[case("$starts_with", "[\"abc\", \"ab\"]", Value::Bool(true))]
        #[case("$ends_with", "[\"abc\", \"bc\"]", Value::Bool(true))]
        // Misc
        #[case("$exists", "[\"label\"]", Value::Bool(true))]
        #[case("$has", "[\"label\"]", Value::Bool(true))]
        #[case("$cast", "[10.0, \"int\"]", Value::Int(10))]
        #[case("$ref", "[\"label\"]", Value::Int(10))]
        #[case("$timestamp", "[]", Value::Int(0))]
        #[case("$id", "[]", Value::Int(0))]
        fn test_parse_operator(
            parser: Parser,
            context: Context,
            #[case] operator: &str,
            #[case] operands: &str,
            #[case] expected: Value,
        ) {
            let json = serde_json::from_str(&format!(
                r#"{{"$eq":[{}, {{"{}": {} }}] }}"#,
                expected.to_string(),
                operator,
                operands
            ))
            .unwrap();
            let (mut node, _) = parser.parse(json).unwrap();
            assert!(
                node.apply(&context).unwrap().as_bool().unwrap(),
                "{}",
                node.print()
            );
        }

        #[rstest]
        #[case("$second")]
        #[case("$minute")]
        #[case("$hour")]
        #[case("$day")]
        #[case("$month")]
        #[case("$year")]
        #[case("$weekday")]
        fn test_parse_date_operator_invalid_operands(parser: Parser, #[case] operator: &str) {
            let json = serde_json::from_str(&format!(r#"{{"{}": []}}"#, operator)).unwrap();
            let result = parser.parse(json);
            assert_eq!(
                result.err().unwrap().to_string(),
                format!(
                    "[UnprocessableEntity] {} requires one or two operands",
                    operator
                )
            );
        }

        #[rstest]
        fn test_print_date_operators() {
            assert!(Day::new(vec![]).print().contains("Day"));
            assert!(Hour::new(vec![]).print().contains("Hour"));
            assert!(Minute::new(vec![]).print().contains("Minute"));
            assert!(Month::new(vec![]).print().contains("Month"));
            assert!(Second::new(vec![]).print().contains("Second"));
            assert!(Weekday::new(vec![]).print().contains("Weekday"));
            assert!(Year::new(vec![]).print().contains("Year"));
        }
    }

    #[fixture]
    fn parser() -> Parser {
        Parser::new()
    }

    #[fixture]
    fn context() -> Context<'static> {
        let mut context = Context::default();
        context.labels.insert("label", "10");
        context
    }
}