1use async_trait::async_trait;
7use camel_language_api::{Body, Exchange, ExpressionErrorClass, Value};
8use camel_language_api::{Expression, Language, LanguageError, Predicate};
9use jsonpath_rust::parser::model::JpQuery;
10use jsonpath_rust::parser::parse_json_path;
11use jsonpath_rust::query::js_path_process;
12use serde_json::Value as JsonValue;
13#[cfg(test)]
14thread_local! {
15 static COMPILE_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
16}
17
18const DEFAULT_MAX_DEPTH: usize = 64;
20
21const DEFAULT_MAX_INPUT_BYTES: usize = 16 * 1024 * 1024; #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
29pub enum JsonPathPredicateMode {
30 #[default]
34 Strict,
35 Matches,
41}
42
43#[derive(Debug, Clone)]
45pub struct JsonPathConfig {
46 pub max_input_bytes: Option<usize>,
49 pub max_depth: Option<usize>,
52 pub predicate_mode: JsonPathPredicateMode,
55}
56
57impl JsonPathConfig {
58 fn effective_max_depth(&self) -> usize {
60 self.max_depth.unwrap_or(DEFAULT_MAX_DEPTH)
61 }
62}
63
64impl Default for JsonPathConfig {
65 fn default() -> Self {
66 Self {
67 max_input_bytes: Some(DEFAULT_MAX_INPUT_BYTES),
68 max_depth: None,
69 predicate_mode: JsonPathPredicateMode::default(),
70 }
71 }
72}
73
74pub struct JsonPathLanguage {
76 config: JsonPathConfig,
77}
78
79impl JsonPathLanguage {
80 pub fn new() -> Self {
82 Self {
83 config: JsonPathConfig::default(),
84 }
85 }
86
87 pub fn with_config(config: JsonPathConfig) -> Self {
89 Self { config }
90 }
91}
92
93impl Default for JsonPathLanguage {
94 fn default() -> Self {
95 Self::new()
96 }
97}
98
99struct JsonPathExpression {
100 query: JpQuery,
101 config: JsonPathConfig,
102}
103
104struct JsonPathPredicate {
105 query: JpQuery,
106 config: JsonPathConfig,
107}
108
109fn check_depth(value: &JsonValue, max_depth: usize) -> Result<(), LanguageError> {
111 fn recurse(value: &JsonValue, max_depth: usize, current: usize) -> Result<(), LanguageError> {
112 if current > max_depth {
113 return Err(LanguageError::EvalError(format!(
114 "JSON nesting depth {current} exceeds limit of {max_depth}"
115 )));
116 }
117 match value {
118 JsonValue::Object(map) => {
119 for v in map.values() {
120 recurse(v, max_depth, current + 1)?;
121 }
122 Ok(())
123 }
124 JsonValue::Array(arr) => {
125 for v in arr {
126 recurse(v, max_depth, current + 1)?;
127 }
128 Ok(())
129 }
130 _ => Ok(()),
131 }
132 }
133 recurse(value, max_depth, 0)
134}
135
136fn extract_json(exchange: &Exchange, config: &JsonPathConfig) -> Result<JsonValue, LanguageError> {
142 let max_depth = config.effective_max_depth();
143
144 match &exchange.input.body {
145 Body::Json(v) => {
146 check_depth(v, max_depth)?;
148 Ok(v.clone())
149 }
150 Body::Text(s) => {
151 if let Some(limit) = config.max_input_bytes
153 && s.len() > limit
154 {
155 return Err(LanguageError::EvalError(format!(
156 "input size {} bytes exceeds limit of {limit} bytes",
157 s.len()
158 )));
159 }
160 let value: JsonValue =
163 serde_json::from_str(s).map_err(|_| LanguageError::EvalFailure {
164 class: ExpressionErrorClass::Conversion,
165 position: None,
166 detail: Some("body is not valid JSON".to_string()),
167 })?;
168 check_depth(&value, max_depth)?;
169 Ok(value)
170 }
171 other => other
172 .clone()
173 .try_into_json()
174 .map_err(|e| {
175 LanguageError::EvalError(format!("body is not JSON and cannot be coerced: {e}"))
176 })
177 .and_then(|b| match b {
178 Body::Json(v) => {
179 check_depth(&v, max_depth)?;
180 Ok(v)
181 }
182 _ => Err(LanguageError::EvalError(
183 "body coercion did not produce JSON".into(),
184 )),
185 }),
186 }
187}
188
189fn run_query_all(query: &JpQuery, json: &JsonValue) -> Result<Vec<JsonValue>, LanguageError> {
191 let results = js_path_process(query, json)
192 .map_err(|e| LanguageError::EvalError(format!("jsonpath query '{query}' failed: {e}")))?;
193 Ok(results.into_iter().map(|r| r.val.clone()).collect())
194}
195
196fn run_query(query: &JpQuery, json: &JsonValue) -> Result<JsonValue, LanguageError> {
200 let values = run_query_all(query, json)?;
201 Ok(match values.as_slice() {
202 [] => JsonValue::Null,
203 [one] => one.clone(),
204 _ => JsonValue::Array(values),
205 })
206}
207
208#[async_trait]
209impl Expression for JsonPathExpression {
210 async fn evaluate(&self, exchange: &Exchange) -> Result<Value, LanguageError> {
215 let json = extract_json(exchange, &self.config)?;
216 run_query(&self.query, &json)
217 }
218}
219
220#[async_trait]
221impl Predicate for JsonPathPredicate {
222 async fn matches(&self, exchange: &Exchange) -> Result<bool, LanguageError> {
223 let json = extract_json(exchange, &self.config)?;
224 match self.config.predicate_mode {
225 JsonPathPredicateMode::Matches => {
226 let values = run_query_all(&self.query, &json)?;
231 Ok(match values.as_slice() {
232 [] => false,
233 [JsonValue::Bool(b)] => *b,
234 _ => true,
235 })
236 }
237 JsonPathPredicateMode::Strict => {
238 let result = run_query(&self.query, &json)?;
239 match &result {
244 JsonValue::Bool(b) => Ok(*b),
245 other => Err(LanguageError::TypeMismatch {
246 expected: "bool".to_string(),
247 actual: json_type_name(other).to_string(),
248 position: None,
249 }),
250 }
251 }
252 }
253 }
254}
255
256fn json_type_name(value: &JsonValue) -> &'static str {
259 match value {
260 JsonValue::Null => "null",
261 JsonValue::Bool(_) => "bool",
262 JsonValue::Number(_) => "number",
263 JsonValue::String(_) => "string",
264 JsonValue::Array(_) => "array",
265 JsonValue::Object(_) => "object",
266 }
267}
268
269impl Language for JsonPathLanguage {
270 fn name(&self) -> &'static str {
271 "jsonpath"
272 }
273
274 fn create_expression(&self, script: &str) -> Result<Box<dyn Expression>, LanguageError> {
275 if !script.starts_with('$') {
276 return Err(LanguageError::ParseError {
277 expr: script.to_string(),
278 reason: "JsonPath expression must start with '$'".into(),
279 });
280 }
281 let parsed = parse_json_path(script).map_err(|e| LanguageError::ParseError {
282 expr: script.to_string(),
283 reason: e.to_string(),
284 })?;
285 #[cfg(test)]
286 {
287 COMPILE_COUNT.with(|c| c.set(c.get() + 1));
288 }
289 Ok(Box::new(JsonPathExpression {
290 query: parsed,
291 config: self.config.clone(),
292 }))
293 }
294
295 fn create_predicate(&self, script: &str) -> Result<Box<dyn Predicate>, LanguageError> {
296 if !script.starts_with('$') {
297 return Err(LanguageError::ParseError {
298 expr: script.to_string(),
299 reason: "JsonPath expression must start with '$'".into(),
300 });
301 }
302 let parsed = parse_json_path(script).map_err(|e| LanguageError::ParseError {
303 expr: script.to_string(),
304 reason: e.to_string(),
305 })?;
306 #[cfg(test)]
307 {
308 COMPILE_COUNT.with(|c| c.set(c.get() + 1));
309 }
310 Ok(Box::new(JsonPathPredicate {
311 query: parsed,
312 config: self.config.clone(),
313 }))
314 }
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320 use camel_language_api::Message;
321
322 async fn exchange_with_json(json: &str) -> Exchange {
323 let value: JsonValue = serde_json::from_str(json).unwrap();
324 Exchange::new(Message::new(Body::Json(value)))
325 }
326
327 async fn exchange_with_text_body(text: &str) -> Exchange {
328 Exchange::new(Message::new(Body::Text(text.to_string())))
329 }
330
331 async fn empty_exchange() -> Exchange {
332 Exchange::new(Message::default())
333 }
334
335 async fn default_lang() -> JsonPathLanguage {
336 JsonPathLanguage::new()
337 }
338
339 #[tokio::test]
340 async fn expression_simple_path() {
341 let lang = default_lang().await;
342 let expr = lang.create_expression("$.store.name").unwrap();
343 let ex = exchange_with_json(r#"{"store":{"name":"books"}}"#).await;
344 let result = expr.evaluate(&ex).await.unwrap();
345 assert_eq!(result, JsonValue::String("books".to_string()));
346 }
347
348 #[tokio::test]
349 async fn expression_nested_path() {
350 let lang = default_lang().await;
351 let expr = lang.create_expression("$.a.b.c").unwrap();
352 let ex = exchange_with_json(r#"{"a":{"b":{"c":42}}}"#).await;
353 let result = expr.evaluate(&ex).await.unwrap();
354 assert_eq!(result, JsonValue::Number(42.into()));
355 }
356
357 #[tokio::test]
358 async fn expression_array_index() {
359 let lang = default_lang().await;
360 let expr = lang.create_expression("$.items[0]").unwrap();
361 let ex = exchange_with_json(r#"{"items":["a","b","c"]}"#).await;
362 let result = expr.evaluate(&ex).await.unwrap();
363 assert_eq!(result, JsonValue::String("a".to_string()));
364 }
365
366 #[tokio::test]
367 async fn expression_wildcard() {
368 let lang = default_lang().await;
369 let expr = lang.create_expression("$.items[*].name").unwrap();
370 let ex = exchange_with_json(r#"{"items":[{"name":"a"},{"name":"b"}]}"#).await;
371 let result = expr.evaluate(&ex).await.unwrap();
372 assert_eq!(
373 result,
374 JsonValue::Array(vec![
375 JsonValue::String("a".to_string()),
376 JsonValue::String("b".to_string())
377 ])
378 );
379 }
380
381 #[tokio::test]
382 async fn expression_root_path() {
383 let lang = default_lang().await;
384 let expr = lang.create_expression("$").unwrap();
385 let ex = exchange_with_json(r#"{"x":1}"#).await;
386 let result = expr.evaluate(&ex).await.unwrap();
387 assert_eq!(result["x"], JsonValue::Number(1.into()));
388 }
389
390 #[tokio::test]
391 async fn expression_text_body_with_valid_json() {
392 let lang = default_lang().await;
393 let expr = lang.create_expression("$.name").unwrap();
394 let ex = exchange_with_text_body(r#"{"name":"test"}"#).await;
395 let result = expr.evaluate(&ex).await.unwrap();
396 assert_eq!(result, JsonValue::String("test".to_string()));
397 }
398
399 #[tokio::test]
400 async fn jsonpath_reads_body_not_headers() {
401 let lang = default_lang().await;
402 let expr = lang.create_expression("$.header").unwrap();
403 let body: JsonValue = serde_json::from_str(r#"{"header":"from-body"}"#).unwrap();
404 let mut message = Message::new(Body::Json(body));
405 message.set_header("header", Value::String("from-header".to_string()));
406 let ex = Exchange::new(message);
407 let result = expr.evaluate(&ex).await.unwrap();
408 assert_eq!(result, JsonValue::String("from-body".to_string()));
409 }
410
411 #[tokio::test]
412 async fn jsonpath_has_no_header_reader() {
413 let lang = default_lang().await;
414 match lang.create_expression("has_header('x')") {
415 Err(LanguageError::ParseError { .. }) => {}
416 Ok(_) => panic!("expected ParseError for has_header('x')"),
417 Err(other) => panic!("expected ParseError, got {other:?}"),
418 }
419 }
420
421 #[tokio::test]
422 async fn expression_empty_body_is_error() {
423 let lang = default_lang().await;
424 let expr = lang.create_expression("$.x").unwrap();
425 let ex = empty_exchange().await;
426 let result = expr.evaluate(&ex).await;
427 assert!(result.is_err());
428 }
429
430 #[tokio::test]
431 async fn expression_invalid_jsonpath_syntax() {
432 let lang = default_lang().await;
433 let result = lang.create_expression("$[invalid");
434 let err = match result {
435 Err(e) => e,
436 Ok(_) => panic!("expected ParseError"),
437 };
438 match err {
439 LanguageError::ParseError { expr, reason } => {
440 assert!(!expr.is_empty());
441 assert!(!reason.is_empty());
442 }
443 other => panic!("expected ParseError, got {other:?}"),
444 }
445 }
446
447 #[tokio::test]
450 async fn expression_without_dollar_prefix_is_rejected() {
451 let lang = default_lang().await;
452 let result = lang.create_expression("store.name");
453 assert!(result.is_err(), "expected error for missing $ prefix");
454 let err = match result {
455 Err(e) => e,
456 Ok(_) => panic!("expected ParseError"),
457 };
458 match err {
459 LanguageError::ParseError { expr, reason } => {
460 assert_eq!(expr, "store.name");
461 assert!(
462 reason.contains("'$'"),
463 "reason should mention '$', got: {reason}"
464 );
465 }
466 other => panic!("expected ParseError, got {other:?}"),
467 }
468 }
469
470 #[tokio::test]
471 async fn predicate_without_dollar_prefix_is_rejected() {
472 let lang = default_lang().await;
473 let result = lang.create_predicate("store.name");
474 assert!(result.is_err(), "expected error for missing $ prefix");
475 let err = match result {
476 Err(e) => e,
477 Ok(_) => panic!("expected ParseError"),
478 };
479 match err {
480 LanguageError::ParseError { reason, .. } => {
481 assert!(
482 reason.contains("'$'"),
483 "reason should mention '$', got: {reason}"
484 );
485 }
486 other => panic!("expected ParseError, got {other:?}"),
487 }
488 }
489
490 #[tokio::test]
493 async fn expression_deeply_nested_path() {
494 let lang = default_lang().await;
495 let expr = lang.create_expression("$.a.b.c.d").unwrap();
496 let ex = exchange_with_json(r#"{"a":{"b":{"c":{"d":"deep"}}}}"#).await;
497 let result = expr.evaluate(&ex).await.unwrap();
498 assert_eq!(result, JsonValue::String("deep".to_string()));
499 }
500
501 #[tokio::test]
502 async fn expression_array_index_nested() {
503 let lang = default_lang().await;
504 let expr = lang.create_expression("$.data.items[1].name").unwrap();
505 let ex = exchange_with_json(
506 r#"{"data":{"items":[{"name":"first"},{"name":"second"},{"name":"third"}]}}"#,
507 )
508 .await;
509 let result = expr.evaluate(&ex).await.unwrap();
510 assert_eq!(result, JsonValue::String("second".to_string()));
511 }
512
513 #[tokio::test]
514 async fn jsonpath_predicate_non_bool_is_type_mismatch() {
515 let lang = default_lang().await;
519 for (json_body, actual) in [
520 (r#"{"val":"false"}"#, "string"),
521 (r#"{"val":"x"}"#, "string"),
522 (r#"{"val":0}"#, "number"),
523 (r#"{"val":1}"#, "number"),
524 (r#"{"val":[]}"#, "array"),
525 (r#"{"val":{}}"#, "object"),
526 (r#"{"other":1}"#, "null"),
527 ] {
528 let pred = lang.create_predicate("$.val").unwrap();
529 let ex = exchange_with_json(json_body).await;
530 match pred.matches(&ex).await {
531 Err(LanguageError::TypeMismatch {
532 expected,
533 actual: got,
534 position: None,
535 }) => {
536 assert_eq!(expected, "bool");
537 assert_eq!(got, actual, "body {json_body}");
538 }
539 other => panic!("expected TypeMismatch for {json_body}, got: {other:?}"),
540 }
541 }
542
543 let pred = lang.create_predicate("$.active").unwrap();
545 assert!(
546 pred.matches(&exchange_with_json(r#"{"active":true}"#).await)
547 .await
548 .unwrap()
549 );
550 let pred = lang.create_predicate("$.active").unwrap();
551 assert!(
552 !pred
553 .matches(&exchange_with_json(r#"{"active":false}"#).await)
554 .await
555 .unwrap()
556 );
557 }
558
559 #[tokio::test]
560 async fn jsonpath_invalid_body_error_is_conversion_class_no_snippet() {
561 let lang = default_lang().await;
562 let expr = lang.create_expression("$.key").unwrap();
563 let mut ex = Exchange::new(Message::default());
564 ex.input.body = Body::Text("SECRETVAL not json".to_string());
565 let err = expr.evaluate(&ex).await.expect_err("must fail");
566 match &err {
567 LanguageError::EvalFailure {
568 class: ExpressionErrorClass::Conversion,
569 position: None,
570 detail: Some(detail),
571 } => {
572 assert_eq!(detail, "body is not valid JSON");
573 }
574 other => panic!("expected Conversion EvalFailure, got: {other:?}"),
575 }
576 assert!(!err.to_string().contains("SECRETVAL"), "body leaked: {err}");
577 }
578
579 #[tokio::test]
582 async fn oversized_input_is_rejected() {
583 let config = JsonPathConfig {
584 max_input_bytes: Some(100),
585 ..Default::default()
586 };
587 let lang = JsonPathLanguage::with_config(config);
588 let expr = lang.create_expression("$.key").unwrap();
589 let big_value = "x".repeat(200);
591 let big_json = format!(r#"{{"key":"{}"}}"#, big_value);
592 assert!(big_json.len() > 100);
593 let ex = exchange_with_text_body(&big_json).await;
594 let result = expr.evaluate(&ex).await;
595 assert!(
596 result.is_err(),
597 "expected error for oversized input, got {result:?}"
598 );
599 }
600
601 #[tokio::test]
602 async fn input_under_limit_is_accepted() {
603 let config = JsonPathConfig {
604 max_input_bytes: Some(1024),
605 ..Default::default()
606 };
607 let lang = JsonPathLanguage::with_config(config);
608 let expr = lang.create_expression("$.key").unwrap();
609 let ex = exchange_with_text_body(r#"{"key":"value"}"#).await;
610 let result = expr.evaluate(&ex).await;
611 assert!(
612 result.is_ok(),
613 "expected success for input under limit, got {result:?}"
614 );
615 }
616
617 #[tokio::test]
618 async fn deeply_nested_input_is_rejected() {
619 let config = JsonPathConfig {
620 max_depth: Some(5),
621 ..Default::default()
622 };
623 let lang = JsonPathLanguage::with_config(config);
624 let expr = lang.create_expression("$.a").unwrap();
625 let mut json = "1".to_string();
627 for _ in 0..10 {
628 json = format!(r#"{{"a":{json}}}"#);
629 }
630 let ex = exchange_with_text_body(&json).await;
631 let result = expr.evaluate(&ex).await;
632 assert!(
633 result.is_err(),
634 "expected error for deeply nested input, got {result:?}"
635 );
636 }
637
638 #[tokio::test]
639 async fn nesting_within_depth_limit_is_accepted() {
640 let config = JsonPathConfig {
641 max_depth: Some(10),
642 ..Default::default()
643 };
644 let lang = JsonPathLanguage::with_config(config);
645 let expr = lang.create_expression("$.a").unwrap();
646 let mut json = "1".to_string();
648 for _ in 0..5 {
649 json = format!(r#"{{"a":{json}}}"#);
650 }
651 let ex = exchange_with_text_body(&json).await;
652 let result = expr.evaluate(&ex).await;
653 assert!(
654 result.is_ok(),
655 "expected success for nesting within limit, got {result:?}"
656 );
657 }
658
659 #[tokio::test]
660 async fn default_config_has_safe_defaults() {
661 let config = JsonPathConfig::default();
663 assert_eq!(config.max_input_bytes, Some(16 * 1024 * 1024));
664 assert_eq!(config.max_depth, None);
666 }
667
668 #[tokio::test]
669 async fn default_config_rejects_oversized_text_body() {
670 let lang = JsonPathLanguage::new(); let expr = lang.create_expression("$.key").unwrap();
673 let big_value = "x".repeat(16 * 1024 * 1024 + 10);
674 let big_json = format!(r#"{{"key":"{}"}}"#, big_value);
675 let ex = exchange_with_text_body(&big_json).await;
676 let result = expr.evaluate(&ex).await;
677 assert!(
678 result.is_err(),
679 "default config must reject oversized input, got {result:?}"
680 );
681 }
682
683 #[tokio::test]
684 async fn oversized_input_also_rejected_for_predicate() {
685 let config = JsonPathConfig {
686 max_input_bytes: Some(100),
687 ..Default::default()
688 };
689 let lang = JsonPathLanguage::with_config(config);
690 let pred = lang.create_predicate("$.key").unwrap();
691 let big_value = "x".repeat(200);
692 let big_json = format!(r#"{{"key":"{}"}}"#, big_value);
693 let ex = exchange_with_text_body(&big_json).await;
694 let result = pred.matches(&ex).await;
695 assert!(
696 result.is_err(),
697 "expected error for oversized input in predicate, got {result:?}"
698 );
699 }
700
701 #[tokio::test]
702 async fn deeply_nested_input_rejected_for_predicate() {
703 let config = JsonPathConfig {
704 max_depth: Some(3),
705 ..Default::default()
706 };
707 let lang = JsonPathLanguage::with_config(config);
708 let pred = lang.create_predicate("$.a").unwrap();
709 let mut json = "1".to_string();
710 for _ in 0..5 {
711 json = format!(r#"{{"a":{json}}}"#);
712 }
713 let ex = exchange_with_text_body(&json).await;
714 let result = pred.matches(&ex).await;
715 assert!(
716 result.is_err(),
717 "expected error for deeply nested input in predicate, got {result:?}"
718 );
719 }
720
721 #[tokio::test]
722 async fn body_json_no_input_size_check_but_depth_checked() {
723 let config = JsonPathConfig {
726 max_input_bytes: Some(10), max_depth: Some(3),
728 predicate_mode: JsonPathPredicateMode::Strict,
729 };
730 let lang = JsonPathLanguage::with_config(config);
731 let expr = lang.create_expression("$.a").unwrap();
732 let mut json_str = "1".to_string();
734 for _ in 0..5 {
735 json_str = format!(r#"{{"a":{json_str}}}"#);
736 }
737 let ex = exchange_with_json(&json_str).await;
738 let result = expr.evaluate(&ex).await;
739 assert!(
740 result.is_err(),
741 "expected depth error for pre-parsed JSON, got {result:?}"
742 );
743 }
744
745 #[test]
751 fn compile_once_types_are_send_sync() {
752 fn assert_send_sync<T: Send + Sync>() {}
753 assert_send_sync::<JsonPathExpression>();
754 assert_send_sync::<JsonPathPredicate>();
755 assert_send_sync::<JpQuery>();
756 }
757
758 #[tokio::test]
767 async fn compilation_happens_only_once_for_expression() {
768 let before = COMPILE_COUNT.with(std::cell::Cell::get);
769 let lang = JsonPathLanguage::new();
770 let expr = lang.create_expression("$.foo.bar").unwrap();
771 let after_create = COMPILE_COUNT.with(std::cell::Cell::get);
772 assert_eq!(
773 after_create,
774 before + 1,
775 "create_expression must compile exactly once"
776 );
777
778 for _ in 0..50 {
780 let ex = exchange_with_json(r#"{"foo":{"bar":"baz"}}"#).await;
781 let result = expr.evaluate(&ex).await.unwrap();
782 assert_eq!(result, JsonValue::String("baz".to_string()));
783 }
784 assert_eq!(
785 COMPILE_COUNT.with(std::cell::Cell::get),
786 after_create,
787 "evaluate must NOT trigger re-compilation"
788 );
789 }
790
791 #[tokio::test]
792 async fn compilation_happens_only_once_for_predicate() {
793 let before = COMPILE_COUNT.with(std::cell::Cell::get);
794 let lang = JsonPathLanguage::new();
795 let pred = lang.create_predicate("$.active").unwrap();
796 let after_create = COMPILE_COUNT.with(std::cell::Cell::get);
797 assert_eq!(
798 after_create,
799 before + 1,
800 "create_predicate must compile exactly once"
801 );
802
803 for _ in 0..50 {
804 let ex = exchange_with_json(r#"{"active":true}"#).await;
805 assert!(pred.matches(&ex).await.unwrap());
806 }
807 assert_eq!(
808 COMPILE_COUNT.with(std::cell::Cell::get),
809 after_create,
810 "matches must NOT trigger re-compilation"
811 );
812 }
813
814 fn matches_mode_lang() -> JsonPathLanguage {
815 JsonPathLanguage::with_config(JsonPathConfig {
816 predicate_mode: JsonPathPredicateMode::Matches,
817 ..JsonPathConfig::default()
818 })
819 }
820
821 #[tokio::test]
822 async fn matches_mode_cardinality_table() {
823 let lang = matches_mode_lang();
829 let table = [
830 (
832 r#"{"items":[{"price":20},{"price":5}]}"#,
833 "$.items[?@.price>10]",
834 true,
835 ),
836 (r#"{"items":[{"price":20}]}"#, "$.items[?@.price>10]", true),
837 (r#"{"items":[{"price":5}]}"#, "$.items[?@.price>10]", false),
838 (r#"{"items":[1,2]}"#, "$.missing", false),
839 (r#"{"val":{}}"#, "$.val", true),
840 (r#"{"val":[]}"#, "$.val", true),
841 (r#"{"val":""}"#, "$.val", true),
842 (r#"{"val":"false"}"#, "$.val", true),
843 (r#"{"val":0}"#, "$.val", true),
844 (r#"{"val":null}"#, "$.val", true),
845 (r#"{"val":true}"#, "$.val", true),
846 (r#"{"val":false}"#, "$.val", false),
847 ];
848 for (body, query, expected) in table {
849 let pred = lang.create_predicate(query).unwrap();
850 let ex = exchange_with_json(body).await;
851 let got = pred.matches(&ex).await.unwrap_or_else(|e| {
852 panic!("matches mode must not error for {query} on {body}: {e:?}")
853 });
854 assert_eq!(got, expected, "query {query} on {body}");
855 }
856 }
857
858 #[tokio::test]
859 async fn strict_stays_default_and_repro_cases_remain_type_errors() {
860 let lang = default_lang().await;
863 let ex = exchange_with_json(r#"{"items":[{"price":20},{"price":5}]}"#).await;
864 let pred = lang.create_predicate("$.items[?@.price>10]").unwrap();
865 match pred.matches(&ex).await {
866 Err(LanguageError::TypeMismatch {
867 actual,
868 position: None,
869 ..
870 }) => {
871 assert_eq!(actual, "object");
874 }
875 other => panic!("strict default must stay a type error, got: {other:?}"),
876 }
877 let pred = lang.create_predicate("$.missing").unwrap();
878 match pred.matches(&ex).await {
879 Err(LanguageError::TypeMismatch {
880 actual,
881 position: None,
882 ..
883 }) => {
884 assert_eq!(actual, "null");
885 }
886 other => panic!("strict default must stay a type error, got: {other:?}"),
887 }
888 }
889
890 #[tokio::test]
891 async fn matches_mode_evaluation_failure_stays_typed_error() {
892 let lang = matches_mode_lang();
896 let pred = lang.create_predicate("$.val").unwrap();
897 let ex = exchange_with_text_body("not json at all").await;
898 assert!(
899 pred.matches(&ex).await.is_err(),
900 "evaluation failure must not coerce to false"
901 );
902 }
903}