camel-language-simple 0.5.8

Simple Language for rust-camel YAML DSL
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
mod evaluator;
mod parser;

use camel_language_api::{Exchange, Expression, Language, LanguageError, Predicate, Value};

pub struct SimpleLanguage;

struct SimpleExpression(parser::Expr);
struct SimplePredicate(parser::Expr);

impl Expression for SimpleExpression {
    fn evaluate(&self, exchange: &Exchange) -> Result<Value, LanguageError> {
        evaluator::evaluate(&self.0, exchange)
    }
}

impl Predicate for SimplePredicate {
    fn matches(&self, exchange: &Exchange) -> Result<bool, LanguageError> {
        let val = evaluator::evaluate(&self.0, exchange)?;
        Ok(match &val {
            Value::Bool(b) => *b,
            Value::Null => false,
            _ => true,
        })
    }
}

impl Language for SimpleLanguage {
    fn name(&self) -> &'static str {
        "simple"
    }

    fn create_expression(&self, script: &str) -> Result<Box<dyn Expression>, LanguageError> {
        let ast = parser::parse(script)?;
        Ok(Box::new(SimpleExpression(ast)))
    }

    fn create_predicate(&self, script: &str) -> Result<Box<dyn Predicate>, LanguageError> {
        let ast = parser::parse(script)?;
        Ok(Box::new(SimplePredicate(ast)))
    }
}

#[cfg(test)]
mod tests {
    use super::SimpleLanguage;
    use camel_language_api::Language;
    use camel_language_api::{Exchange, Message, Value};

    fn exchange_with_header(key: &str, val: &str) -> Exchange {
        let mut msg = Message::default();
        msg.set_header(key, Value::String(val.to_string()));
        Exchange::new(msg)
    }

    fn exchange_with_body(body: &str) -> Exchange {
        Exchange::new(Message::new(body))
    }

    #[test]
    fn test_header_equals_string() {
        let lang = SimpleLanguage;
        let pred = lang.create_predicate("${header.type} == 'order'").unwrap();
        let ex = exchange_with_header("type", "order");
        assert!(pred.matches(&ex).unwrap());
    }

    #[test]
    fn test_header_not_equals() {
        let lang = SimpleLanguage;
        let pred = lang.create_predicate("${header.type} != 'order'").unwrap();
        let ex = exchange_with_header("type", "invoice");
        assert!(pred.matches(&ex).unwrap());
    }

    #[test]
    fn test_body_contains() {
        let lang = SimpleLanguage;
        let pred = lang.create_predicate("${body} contains 'hello'").unwrap();
        let ex = exchange_with_body("say hello world");
        assert!(pred.matches(&ex).unwrap());
    }

    #[test]
    fn test_header_null_check() {
        let lang = SimpleLanguage;
        let pred = lang.create_predicate("${header.missing} == null").unwrap();
        let ex = exchange_with_body("anything");
        assert!(pred.matches(&ex).unwrap());
    }

    #[test]
    fn test_header_not_null() {
        let lang = SimpleLanguage;
        let pred = lang.create_predicate("${header.type} != null").unwrap();
        let ex = exchange_with_header("type", "order");
        assert!(pred.matches(&ex).unwrap());
    }

    #[test]
    fn test_expression_header_value() {
        let lang = SimpleLanguage;
        let expr = lang.create_expression("${header.type}").unwrap();
        let ex = exchange_with_header("type", "order");
        let val = expr.evaluate(&ex).unwrap();
        assert_eq!(val, Value::String("order".to_string()));
    }

    #[test]
    fn test_expression_body() {
        let lang = SimpleLanguage;
        let expr = lang.create_expression("${body}").unwrap();
        let ex = exchange_with_body("hello");
        let val = expr.evaluate(&ex).unwrap();
        assert_eq!(val, Value::String("hello".to_string()));
    }

    #[test]
    fn test_numeric_comparison() {
        let lang = SimpleLanguage;
        let pred = lang.create_predicate("${header.age} > 18").unwrap();
        let mut ex = Exchange::new(Message::default());
        ex.input.set_header("age", Value::Number(25.into()));
        assert!(pred.matches(&ex).unwrap());
    }

    // --- Edge case tests ---

    #[test]
    fn test_empty_body() {
        let lang = SimpleLanguage;
        let expr = lang.create_expression("${body}").unwrap();
        let ex = Exchange::new(Message::default());
        let val = expr.evaluate(&ex).unwrap();
        assert_eq!(val, Value::String("".to_string()));
    }

    #[test]
    fn test_parse_error_unrecognized_token() {
        // A pure `${...}` token that doesn't match any known form is a parse error.
        // For example `${unknown}` is not a valid Simple expression.
        let lang = SimpleLanguage;
        let result = lang.create_expression("${unknown}");
        assert!(result.is_err(), "unknown token should be a parse error");
    }

    #[test]
    fn test_empty_header_key_is_parse_error() {
        let lang = SimpleLanguage;
        let result = lang.create_expression("${header.}");
        let err = result.err().expect("should be a parse error");
        let err = format!("{err}");
        assert!(
            err.contains("empty"),
            "error should mention empty key, got: {err}"
        );
    }

    #[test]
    fn test_empty_exchange_property_key_is_parse_error() {
        let lang = SimpleLanguage;
        let result = lang.create_expression("${exchangeProperty.}");
        let err = result.err().expect("should be a parse error");
        let err = format!("{err}");
        assert!(
            err.contains("empty"),
            "error should mention empty key, got: {err}"
        );
    }

    #[test]
    fn test_missing_header_returns_null() {
        let lang = SimpleLanguage;
        let expr = lang.create_expression("${header.nonexistent}").unwrap();
        let ex = exchange_with_body("anything");
        let val = expr.evaluate(&ex).unwrap();
        assert_eq!(val, Value::Null);
    }

    #[test]
    fn test_exchange_property_expression() {
        let lang = SimpleLanguage;
        let expr = lang
            .create_expression("${exchangeProperty.myProp}")
            .unwrap();
        let mut ex = exchange_with_body("test");
        ex.set_property("myProp".to_string(), Value::String("propVal".to_string()));
        let val = expr.evaluate(&ex).unwrap();
        assert_eq!(val, Value::String("propVal".to_string()));
    }

    #[test]
    fn test_missing_property_returns_null() {
        let lang = SimpleLanguage;
        let expr = lang
            .create_expression("${exchangeProperty.missing}")
            .unwrap();
        let ex = exchange_with_body("test");
        let val = expr.evaluate(&ex).unwrap();
        assert_eq!(val, Value::Null);
    }

    #[test]
    fn test_string_literal_expression() {
        let lang = SimpleLanguage;
        let expr = lang.create_expression("'hello'").unwrap();
        let ex = exchange_with_body("test");
        let val = expr.evaluate(&ex).unwrap();
        assert_eq!(val, Value::String("hello".to_string()));
    }

    #[test]
    fn test_null_expression() {
        let lang = SimpleLanguage;
        let expr = lang.create_expression("null").unwrap();
        let ex = exchange_with_body("test");
        let val = expr.evaluate(&ex).unwrap();
        assert_eq!(val, Value::Null);
    }

    #[test]
    fn test_predicate_null_is_false() {
        let lang = SimpleLanguage;
        let pred = lang.create_predicate("${header.missing}").unwrap();
        let ex = exchange_with_body("test");
        assert!(!pred.matches(&ex).unwrap());
    }

    #[test]
    fn test_predicate_non_null_is_true() {
        let lang = SimpleLanguage;
        let pred = lang.create_predicate("${header.type}").unwrap();
        let ex = exchange_with_header("type", "order");
        assert!(pred.matches(&ex).unwrap());
    }

    #[test]
    fn test_contains_not_found() {
        let lang = SimpleLanguage;
        let pred = lang.create_predicate("${body} contains 'xyz'").unwrap();
        let ex = exchange_with_body("hello world");
        assert!(!pred.matches(&ex).unwrap());
    }

    #[test]
    fn test_less_than_or_equal() {
        let lang = SimpleLanguage;
        let pred = lang.create_predicate("${header.age} <= 18").unwrap();
        let mut ex = Exchange::new(Message::default());
        ex.input.set_header("age", Value::Number(18.into()));
        assert!(pred.matches(&ex).unwrap());
    }

    // --- Mixed interpolation tests ---

    #[test]
    fn test_interpolated_text_with_header() {
        // "Exchange #${header.CamelTimerCounter}" → "Exchange #42"
        let lang = SimpleLanguage;
        let expr = lang
            .create_expression("Exchange #${header.CamelTimerCounter}")
            .unwrap();
        let ex = exchange_with_header("CamelTimerCounter", "42");
        let val = expr.evaluate(&ex).unwrap();
        assert_eq!(val, Value::String("Exchange #42".to_string()));
    }

    #[test]
    fn test_interpolated_text_with_body() {
        // "Got ${body}" → "Got hello"
        let lang = SimpleLanguage;
        let expr = lang.create_expression("Got ${body}").unwrap();
        let ex = exchange_with_body("hello");
        let val = expr.evaluate(&ex).unwrap();
        assert_eq!(val, Value::String("Got hello".to_string()));
    }

    #[test]
    fn test_interpolated_multiple_expressions() {
        // "Transformed: ${body} (source=${header.source})" → real values
        let lang = SimpleLanguage;
        let expr = lang
            .create_expression("Transformed: ${body} (source=${header.source})")
            .unwrap();
        let mut msg = Message::new("data");
        msg.set_header("source", Value::String("kafka".to_string()));
        let ex = Exchange::new(msg);
        let val = expr.evaluate(&ex).unwrap();
        assert_eq!(
            val,
            Value::String("Transformed: data (source=kafka)".to_string())
        );
    }

    #[test]
    fn test_interpolated_missing_header_becomes_empty() {
        // Missing header in interpolated string yields empty string for that slot
        let lang = SimpleLanguage;
        let expr = lang
            .create_expression("prefix-${header.missing}-suffix")
            .unwrap();
        let ex = exchange_with_body("x");
        let val = expr.evaluate(&ex).unwrap();
        assert_eq!(val, Value::String("prefix--suffix".to_string()));
    }

    #[test]
    fn test_interpolated_text_only_no_expressions() {
        // Plain text with no ${...} — treated as a literal (no interpolation needed,
        // but must still work without error)
        let lang = SimpleLanguage;
        let expr = lang.create_expression("Hello World").unwrap();
        let ex = exchange_with_body("x");
        let val = expr.evaluate(&ex).unwrap();
        assert_eq!(val, Value::String("Hello World".to_string()));
    }

    #[test]
    fn test_interpolated_unclosed_brace_treated_as_literal() {
        // An unclosed `${` has no matching `}` — the remainder is treated as
        // plain literal text rather than causing a parse error.
        let lang = SimpleLanguage;
        let expr = lang.create_expression("Got ${body").unwrap();
        let ex = exchange_with_body("hello");
        let val = expr.evaluate(&ex).unwrap();
        assert_eq!(val, Value::String("Got ${body".to_string()));
    }

    #[test]
    fn test_operator_inside_string_literal_not_split() {
        // The string literal 'a>=b' contains '>=' but must NOT be parsed as a
        // BinOp split — the whole thing is a StringLit atom.
        let lang = SimpleLanguage;
        let result = lang.create_expression("'a>=b'");
        let val = result
            .unwrap()
            .evaluate(&Exchange::new(Message::default()))
            .unwrap();
        assert_eq!(
            val,
            Value::String("a>=b".to_string()),
            "string literal 'a>=b' should be parsed as a plain string, not split on >="
        );
    }

    #[test]
    fn test_header_eq_string_literal_containing_operator() {
        // ${header.x} == 'a>=b' — the operator inside the RHS string must not
        // cause the parser to split the LHS at the wrong position.
        let lang = SimpleLanguage;
        let pred = lang.create_predicate("${header.x} == 'a>=b'").unwrap();
        let ex = exchange_with_header("x", "a>=b");
        assert!(
            pred.matches(&ex).unwrap(),
            "predicate should match when header equals 'a>=b'"
        );
    }
}

#[cfg(test)]
mod body_field_parser_tests {
    use crate::parser::{Expr, PathSegment, parse};

    #[test]
    fn parse_body_field_simple_key() {
        let expr = parse("${body.name}").unwrap();
        assert_eq!(
            expr,
            Expr::BodyField(vec![PathSegment::Key("name".to_string())])
        );
    }

    #[test]
    fn parse_body_field_nested() {
        let expr = parse("${body.user.city}").unwrap();
        assert_eq!(
            expr,
            Expr::BodyField(vec![
                PathSegment::Key("user".to_string()),
                PathSegment::Key("city".to_string()),
            ])
        );
    }

    #[test]
    fn parse_body_field_array_index() {
        let expr = parse("${body.items.0}").unwrap();
        assert_eq!(
            expr,
            Expr::BodyField(vec![
                PathSegment::Key("items".to_string()),
                PathSegment::Index(0),
            ])
        );
    }

    #[test]
    fn parse_body_field_array_nested() {
        let expr = parse("${body.users.0.name}").unwrap();
        assert_eq!(
            expr,
            Expr::BodyField(vec![
                PathSegment::Key("users".to_string()),
                PathSegment::Index(0),
                PathSegment::Key("name".to_string()),
            ])
        );
    }

    #[test]
    fn parse_body_field_empty_segment_error() {
        let result = parse("${body.}");
        assert!(result.is_err());
    }

    #[test]
    fn parse_body_field_exact_still_works() {
        // Regression: ${body} must still produce Expr::Body, not BodyField
        let expr = parse("${body}").unwrap();
        assert_eq!(expr, Expr::Body);
    }

    #[test]
    fn parse_body_field_double_dots_error() {
        // ${body..name} has an empty segment between the two dots
        let result = parse("${body..name}");
        assert!(result.is_err());
    }

    #[test]
    fn parse_body_field_index_only() {
        // ${body.0} — single index segment (e.g. body is a JSON array)
        let expr = parse("${body.0}").unwrap();
        assert_eq!(expr, Expr::BodyField(vec![PathSegment::Index(0)]));
    }

    #[test]
    fn parse_body_field_leading_zero_is_key() {
        // ${body.01} — leading zero means it's a string key, not an array index
        let expr = parse("${body.01}").unwrap();
        assert_eq!(
            expr,
            Expr::BodyField(vec![PathSegment::Key("01".to_string())])
        );
    }
}

#[cfg(test)]
mod body_field_eval_tests {
    use crate::SimpleLanguage;
    use camel_language_api::Language;
    use camel_language_api::{Body, Exchange, Value};
    use serde_json::json;

    fn eval(expr_str: &str, body: Body) -> Value {
        let mut ex = Exchange::default();
        ex.input.body = body;
        let lang = SimpleLanguage;
        lang.create_expression(expr_str)
            .unwrap()
            .evaluate(&ex)
            .unwrap()
    }

    #[test]
    fn body_field_simple_key() {
        let result = eval("${body.name}", Body::Json(json!({"name": "Alice"})));
        assert_eq!(result, json!("Alice"));
    }

    #[test]
    fn body_field_number_value() {
        let result = eval("${body.age}", Body::Json(json!({"age": 30})));
        assert_eq!(result, json!(30));
    }

    #[test]
    fn body_field_bool_value() {
        let result = eval("${body.active}", Body::Json(json!({"active": true})));
        assert_eq!(result, json!(true));
    }

    #[test]
    fn body_field_nested() {
        let result = eval(
            "${body.user.city}",
            Body::Json(json!({"user": {"city": "Madrid"}})),
        );
        assert_eq!(result, json!("Madrid"));
    }

    #[test]
    fn body_field_array_index() {
        let result = eval("${body.items.0}", Body::Json(json!({"items": ["a", "b"]})));
        assert_eq!(result, json!("a"));
    }

    #[test]
    fn body_field_array_nested() {
        let result = eval(
            "${body.users.0.name}",
            Body::Json(json!({"users": [{"name": "Bob"}]})),
        );
        assert_eq!(result, json!("Bob"));
    }

    #[test]
    fn body_field_missing_key_returns_null() {
        let result = eval("${body.missing}", Body::Json(json!({"name": "Alice"})));
        assert_eq!(result, Value::Null);
    }

    #[test]
    fn body_field_missing_nested_returns_null() {
        let result = eval("${body.a.b.c}", Body::Json(json!({"a": {"x": 1}})));
        assert_eq!(result, Value::Null);
    }

    #[test]
    fn body_field_out_of_bounds_index_returns_null() {
        let result = eval("${body.items.5}", Body::Json(json!({"items": ["a"]})));
        assert_eq!(result, Value::Null);
    }

    #[test]
    fn body_field_non_json_body_returns_null() {
        let result = eval(
            "${body.name}",
            Body::Text(r#"{"name":"Alice"}"#.to_string()),
        );
        assert_eq!(result, Value::Null);
    }

    #[test]
    fn body_field_empty_body_returns_null() {
        let result = eval("${body.name}", Body::Empty);
        assert_eq!(result, Value::Null);
    }

    #[test]
    fn body_field_in_interpolation() {
        let result = eval("Hello ${body.name}!", Body::Json(json!({"name": "Alice"})));
        assert_eq!(result, json!("Hello Alice!"));
    }

    #[test]
    fn body_field_in_predicate_true() {
        let lang = SimpleLanguage;
        let mut ex = Exchange::default();
        ex.input.body = Body::Json(json!({"status": "active"}));
        let result = lang
            .create_expression("${body.status} == 'active'")
            .unwrap()
            .evaluate(&ex)
            .unwrap();
        assert_eq!(result, Value::Bool(true));
    }

    #[test]
    fn body_field_in_predicate_false() {
        let lang = SimpleLanguage;
        let mut ex = Exchange::default();
        ex.input.body = Body::Json(json!({"status": "inactive"}));
        let result = lang
            .create_expression("${body.status} == 'active'")
            .unwrap()
            .evaluate(&ex)
            .unwrap();
        assert_eq!(result, Value::Bool(false));
    }

    #[test]
    fn body_field_bytes_body_returns_null() {
        // Note: Using Body::Text here instead of Body::Bytes since bytes crate
        // is not available in test context. Both should behave the same for JSON field access.
        let result = eval(
            "${body.name}",
            Body::Text(r#"{"name":"Alice"}"#.to_string()),
        );
        assert_eq!(result, Value::Null);
    }

    #[test]
    fn body_field_json_null_value_returns_null() {
        // key exists but its value is JSON null → returns Value::Null
        let result = eval(
            "${body.name}",
            Body::Json(serde_json::json!({"name": null})),
        );
        assert_eq!(result, Value::Null);
    }

    #[test]
    fn body_field_numeric_predicate() {
        // JSON number 42.0 compares equal to the parsed number 42 from the
        // Simple Language expression, because both resolve to the same f64.
        let lang = SimpleLanguage;
        let mut ex = Exchange::default();
        ex.input.body = Body::Json(json!({"score": 42.0}));
        let result = lang
            .create_expression("${body.score} == 42")
            .unwrap()
            .evaluate(&ex)
            .unwrap();
        assert_eq!(result, Value::Bool(true));
    }

    #[test]
    fn body_bytes_utf8_returns_string() {
        // Body::Bytes with valid UTF-8 content should be readable via ${body}
        let lang = SimpleLanguage;
        let mut ex = Exchange::default();
        ex.input.body = Body::from(b"hello from bytes".to_vec());
        let val = lang
            .create_expression("${body}")
            .unwrap()
            .evaluate(&ex)
            .unwrap();
        assert_eq!(val, Value::String("hello from bytes".to_string()));
    }

    #[test]
    fn body_json_returns_serialized_string() {
        // Body::Json should be serialized to a JSON string when accessed via ${body}
        let lang = SimpleLanguage;
        let mut ex = Exchange::default();
        ex.input.body = Body::Json(json!({"msg": "world"}));
        let val = lang
            .create_expression("${body}")
            .unwrap()
            .evaluate(&ex)
            .unwrap();
        // The result should be the JSON serialization, not empty
        let s = match val {
            Value::String(s) => s,
            other => panic!("expected String, got {other:?}"),
        };
        assert!(!s.is_empty(), "${{body}} on Body::Json should not be empty");
        let parsed: serde_json::Value = serde_json::from_str(&s).unwrap();
        assert_eq!(parsed["msg"], "world");
    }

    #[test]
    fn body_bytes_in_interpolation() {
        // Body::Bytes should work in interpolated expressions like "Received: ${body}"
        let lang = SimpleLanguage;
        let mut ex = Exchange::default();
        ex.input.body = Body::from(b"ping".to_vec());
        let val = lang
            .create_expression("Received: ${body}")
            .unwrap()
            .evaluate(&ex)
            .unwrap();
        assert_eq!(val, Value::String("Received: ping".to_string()));
    }
}