1use std::fmt;
18use std::sync::Arc;
19
20use serde::{Deserialize, Serialize};
21
22use crate::pool::{Selector, VariablePool};
23use crate::template::Template;
24use crate::value::Value;
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
29pub enum Operator {
30 #[serde(rename = "contains")]
31 Contains,
32 #[serde(rename = "not contains")]
33 NotContains,
34 #[serde(rename = "start with", alias = "starts with", alias = "start_with", alias = "starts_with")]
35 StartWith,
36 #[serde(rename = "end with", alias = "ends with", alias = "end_with", alias = "ends_with")]
37 EndWith,
38 #[serde(rename = "is")]
39 Is,
40 #[serde(rename = "is not", alias = "is_not")]
41 IsNot,
42 #[serde(rename = "empty")]
43 Empty,
44 #[serde(rename = "not empty", alias = "not_empty")]
45 NotEmpty,
46 #[serde(rename = "in")]
47 In,
48 #[serde(rename = "not in", alias = "not_in")]
49 NotIn,
50 #[serde(rename = "all of", alias = "all_of")]
51 AllOf,
52 #[serde(rename = "=", alias = "==", alias = "eq")]
53 Eq,
54 #[serde(rename = "≠", alias = "!=", alias = "ne")]
55 Ne,
56 #[serde(rename = ">", alias = "gt")]
57 Gt,
58 #[serde(rename = "<", alias = "lt")]
59 Lt,
60 #[serde(rename = "≥", alias = ">=", alias = "ge")]
61 Ge,
62 #[serde(rename = "≤", alias = "<=", alias = "le")]
63 Le,
64 #[serde(rename = "null", alias = "is null")]
65 Null,
66 #[serde(rename = "not null", alias = "is not null", alias = "not_null")]
67 NotNull,
68 #[serde(rename = "exists")]
69 Exists,
70 #[serde(rename = "not exists", alias = "not_exists")]
71 NotExists,
72}
73
74impl Operator {
75 pub fn as_str(self) -> &'static str {
77 match self {
78 Operator::Contains => "contains",
79 Operator::NotContains => "not contains",
80 Operator::StartWith => "start with",
81 Operator::EndWith => "end with",
82 Operator::Is => "is",
83 Operator::IsNot => "is not",
84 Operator::Empty => "empty",
85 Operator::NotEmpty => "not empty",
86 Operator::In => "in",
87 Operator::NotIn => "not in",
88 Operator::AllOf => "all of",
89 Operator::Eq => "=",
90 Operator::Ne => "≠",
91 Operator::Gt => ">",
92 Operator::Lt => "<",
93 Operator::Ge => "≥",
94 Operator::Le => "≤",
95 Operator::Null => "null",
96 Operator::NotNull => "not null",
97 Operator::Exists => "exists",
98 Operator::NotExists => "not exists",
99 }
100 }
101
102 pub fn is_unary(self) -> bool {
104 matches!(
105 self,
106 Operator::Empty
107 | Operator::NotEmpty
108 | Operator::Null
109 | Operator::NotNull
110 | Operator::Exists
111 | Operator::NotExists
112 )
113 }
114}
115
116impl fmt::Display for Operator {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 f.write_str(self.as_str())
119 }
120}
121
122#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
124#[serde(rename_all = "lowercase")]
125pub enum LogicalOperator {
126 #[default]
127 And,
128 Or,
129}
130
131#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
133#[error("operator `{operator}` cannot be applied to {actual} (expected value: {expected})")]
134pub struct ConditionError {
135 pub operator: &'static str,
136 pub actual: &'static str,
137 pub expected: String,
138}
139
140#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
142pub struct Condition {
143 pub variable_selector: Selector,
144 pub comparison_operator: Operator,
145 #[serde(default)]
147 pub value: serde_json::Value,
148 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub sub_variable_condition: Option<SubConditionGroup>,
151}
152
153impl Condition {
154 pub fn selectors(&self) -> Vec<Selector> {
157 let mut out = vec![self.variable_selector.clone()];
158 expected_selectors(&self.value, &mut out);
159 if let Some(group) = &self.sub_variable_condition {
160 for c in &group.conditions {
161 expected_selectors(&c.value, &mut out);
162 }
163 }
164 out
165 }
166}
167
168pub(crate) fn expected_selectors(raw: &serde_json::Value, out: &mut Vec<Selector>) {
170 match raw {
171 serde_json::Value::String(s) if s.contains("{{#") => out.extend(Template::parse(s).selectors().cloned()),
172 serde_json::Value::Array(items) => {
173 for item in items {
174 expected_selectors(item, out);
175 }
176 }
177 _ => {}
178 }
179}
180
181#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
183pub struct SubConditionGroup {
184 #[serde(default)]
185 pub logical_operator: LogicalOperator,
186 #[serde(default)]
187 pub conditions: Vec<KeyCondition>,
188}
189
190#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
193pub struct KeyCondition {
194 #[serde(default)]
195 pub key: String,
196 pub comparison_operator: Operator,
197 #[serde(default)]
198 pub value: serde_json::Value,
199}
200
201#[derive(Clone, Debug, PartialEq, Serialize)]
203pub struct ConditionTrace {
204 pub selector: String,
205 pub operator: Operator,
206 pub actual: Value,
207 pub expected: Value,
208 pub result: bool,
209}
210
211impl ConditionTrace {
212 pub fn to_value(&self) -> Value {
214 Value::object([
215 ("selector", Value::from(self.selector.as_str())),
216 ("operator", Value::from(self.operator.as_str())),
217 ("actual", self.actual.clone()),
218 ("expected", self.expected.clone()),
219 ("result", Value::Bool(self.result)),
220 ])
221 }
222}
223
224pub(crate) fn resolve_expected(raw: &serde_json::Value, pool: &VariablePool) -> Value {
227 match raw {
228 serde_json::Value::String(s) => {
229 if s.contains("{{#") {
230 Template::parse(s).resolve(pool)
231 } else {
232 Value::from(s.as_str())
233 }
234 }
235 serde_json::Value::Array(items) => Value::array(items.iter().map(|i| resolve_expected(i, pool))),
236 other => Value::from_json(other.clone()),
237 }
238}
239
240pub fn evaluate(condition: &Condition, pool: &VariablePool) -> Result<bool, ConditionError> {
242 evaluate_traced(condition, pool).map(|t| t.result)
243}
244
245pub fn evaluate_traced(condition: &Condition, pool: &VariablePool) -> Result<ConditionTrace, ConditionError> {
247 let actual = pool.get_or_null(&condition.variable_selector);
248 let op = condition.comparison_operator;
249 let (expected, result) = match &condition.sub_variable_condition {
250 Some(group) if is_file_like(&actual) && !op.is_unary() => {
251 (Value::Null, evaluate_file_group(op, &actual, group, pool)?)
252 }
253 _ => {
254 let expected = if op.is_unary() { Value::Null } else { resolve_expected(&condition.value, pool) };
255 let result = compare(op, &actual, &expected)?;
256 (expected, result)
257 }
258 };
259 Ok(ConditionTrace { selector: condition.variable_selector.to_string(), operator: op, actual, expected, result })
260}
261
262pub fn evaluate_group(
265 conditions: &[Condition],
266 logical: LogicalOperator,
267 pool: &VariablePool,
268) -> Result<(bool, Vec<ConditionTrace>), ConditionError> {
269 if conditions.is_empty() {
270 return Ok((false, Vec::new()));
271 }
272 let mut traces = Vec::with_capacity(conditions.len());
273 for condition in conditions {
274 let trace = evaluate_traced(condition, pool)?;
275 let result = trace.result;
276 traces.push(trace);
277 match logical {
278 LogicalOperator::And if !result => return Ok((false, traces)),
279 LogicalOperator::Or if result => return Ok((true, traces)),
280 _ => {}
281 }
282 }
283 Ok((logical == LogicalOperator::And, traces))
284}
285
286fn is_file_like(v: &Value) -> bool {
287 match v {
288 Value::File(_) => true,
289 Value::Array(items) => !items.is_empty() && items.iter().all(|i| matches!(i, Value::File(_))),
290 _ => false,
291 }
292}
293
294fn evaluate_file_group(
295 op: Operator,
296 actual: &Value,
297 group: &SubConditionGroup,
298 pool: &VariablePool,
299) -> Result<bool, ConditionError> {
300 let files: Vec<&Value> = match actual {
301 Value::Array(items) => items.iter().collect(),
302 single => vec![single],
303 };
304 let mut matches = Vec::with_capacity(files.len());
305 for file in files {
306 matches.push(key_group_matches(file, &group.conditions, group.logical_operator, pool)?);
307 }
308 Ok(match op {
309 Operator::NotContains | Operator::NotIn | Operator::IsNot | Operator::Ne => !matches.iter().any(|m| *m),
310 Operator::AllOf => !matches.is_empty() && matches.iter().all(|m| *m),
311 _ => matches.iter().any(|m| *m),
312 })
313}
314
315pub(crate) fn key_group_matches(
317 item: &Value,
318 conditions: &[KeyCondition],
319 logical: LogicalOperator,
320 pool: &VariablePool,
321) -> Result<bool, ConditionError> {
322 if conditions.is_empty() {
323 return Ok(true);
324 }
325 for c in conditions {
326 let r = key_condition_matches(item, c, pool)?;
327 match logical {
328 LogicalOperator::And if !r => return Ok(false),
329 LogicalOperator::Or if r => return Ok(true),
330 _ => {}
331 }
332 }
333 Ok(logical == LogicalOperator::And)
334}
335
336pub(crate) fn key_condition_matches(
338 item: &Value,
339 c: &KeyCondition,
340 pool: &VariablePool,
341) -> Result<bool, ConditionError> {
342 let actual = item_attribute(item, &c.key);
343 let expected = if c.comparison_operator.is_unary() { Value::Null } else { resolve_expected(&c.value, pool) };
344 compare(c.comparison_operator, &actual, &expected)
345}
346
347pub(crate) fn item_attribute(item: &Value, key: &str) -> Value {
350 if key.is_empty() {
351 return item.clone();
352 }
353 match item {
354 Value::File(f) => f.attribute(key).unwrap_or(Value::Null),
355 other => {
356 let parts: Vec<&str> = key.split('.').collect();
357 other.get_path(&parts).unwrap_or(Value::Null)
358 }
359 }
360}
361
362pub(crate) fn compare(op: Operator, actual: &Value, expected: &Value) -> Result<bool, ConditionError> {
364 let err = || ConditionError { operator: op.as_str(), actual: actual.type_name(), expected: expected.to_text() };
365 Ok(match op {
366 Operator::Null | Operator::NotExists => actual.is_null(),
367 Operator::NotNull | Operator::Exists => !actual.is_null(),
368 Operator::Empty => actual.is_empty(),
369 Operator::NotEmpty => !actual.is_empty(),
370 Operator::Contains => contains(actual, expected).ok_or_else(err)?,
371 Operator::NotContains => !contains(actual, expected).ok_or_else(err)?,
372 Operator::StartWith => match text_of(actual) {
373 None if actual.is_null() => false,
374 None => return Err(err()),
375 Some(s) => s.starts_with(&expected.to_text_exposed()),
376 },
377 Operator::EndWith => match text_of(actual) {
378 None if actual.is_null() => false,
379 None => return Err(err()),
380 Some(s) => s.ends_with(&expected.to_text_exposed()),
381 },
382 Operator::Is | Operator::Eq => !actual.is_null() && loose_eq(actual, expected),
383 Operator::IsNot | Operator::Ne => actual.is_null() || !loose_eq(actual, expected),
384 Operator::Gt | Operator::Lt | Operator::Ge | Operator::Le => {
385 if actual.is_null() {
386 return Ok(false);
387 }
388 let a = number_of(actual).ok_or_else(err)?;
389 let Some(e) = number_of(expected) else {
390 return Err(err());
391 };
392 match op {
393 Operator::Gt => a > e,
394 Operator::Lt => a < e,
395 Operator::Ge => a >= e,
396 _ => a <= e,
397 }
398 }
399 Operator::In => is_in(actual, expected),
400 Operator::NotIn => !is_in(actual, expected),
401 Operator::AllOf => {
402 if actual.is_null() {
403 return Ok(false);
404 }
405 let wanted = as_list(expected);
406 let mut all = true;
407 for w in &wanted {
408 if !contains(actual, w).ok_or_else(err)? {
409 all = false;
410 break;
411 }
412 }
413 all
414 }
415 })
416}
417
418fn contains(actual: &Value, expected: &Value) -> Option<bool> {
421 match actual {
422 Value::Null => Some(false),
423 Value::String(s) | Value::Secret(s) => Some(s.contains(expected.to_text_exposed().as_str())),
424 Value::Array(items) => Some(items.iter().any(|i| loose_eq(i, expected))),
425 Value::Object(map) => Some(map.contains_key(expected.to_text_exposed().as_str())),
426 _ => None,
427 }
428}
429
430fn is_in(actual: &Value, expected: &Value) -> bool {
431 if actual.is_null() {
432 return false;
433 }
434 as_list(expected).iter().any(|e| loose_eq(actual, e))
435}
436
437fn as_list(expected: &Value) -> Vec<Value> {
440 match expected {
441 Value::Array(items) => items.iter().cloned().collect(),
442 Value::String(s) => {
443 let trimmed = s.trim();
444 if trimmed.starts_with('[') {
445 if let Ok(serde_json::Value::Array(items)) = serde_json::from_str::<serde_json::Value>(trimmed) {
446 return items.into_iter().map(Value::from_json).collect();
447 }
448 }
449 trimmed.split(',').map(|p| Value::from(p.trim())).filter(|v| !v.is_empty()).collect()
450 }
451 Value::Null => Vec::new(),
452 other => vec![other.clone()],
453 }
454}
455
456fn text_of(v: &Value) -> Option<Arc<str>> {
457 match v {
458 Value::String(s) | Value::Secret(s) => Some(s.clone()),
459 _ => None,
460 }
461}
462
463pub(crate) fn number_of(v: &Value) -> Option<f64> {
465 match v {
466 Value::Int(_) | Value::Float(_) => v.as_f64(),
467 Value::String(s) => s.trim().parse::<f64>().ok(),
468 _ => None,
469 }
470}
471
472fn bool_of(v: &Value) -> Option<bool> {
473 match v {
474 Value::Bool(b) => Some(*b),
475 Value::String(s) => match s.trim().to_ascii_lowercase().as_str() {
476 "true" | "1" | "yes" => Some(true),
477 "false" | "0" | "no" => Some(false),
478 _ => None,
479 },
480 Value::Int(1) => Some(true),
481 Value::Int(0) => Some(false),
482 _ => None,
483 }
484}
485
486pub(crate) fn loose_eq(a: &Value, b: &Value) -> bool {
489 match (a, b) {
490 (Value::Null, Value::Null) => true,
491 (Value::Null, _) | (_, Value::Null) => false,
492 (Value::Bool(x), other) | (other, Value::Bool(x)) => bool_of(other) == Some(*x),
493 (Value::Int(_) | Value::Float(_), _) | (_, Value::Int(_) | Value::Float(_)) => {
494 match (number_of(a), number_of(b)) {
495 (Some(x), Some(y)) => x == y,
496 _ => false,
497 }
498 }
499 (Value::String(x) | Value::Secret(x), Value::String(y) | Value::Secret(y)) => x == y,
500 (Value::Array(_) | Value::Object(_) | Value::File(_), _)
501 | (_, Value::Array(_) | Value::Object(_) | Value::File(_)) => a == b,
502 }
503}
504
505#[cfg(test)]
506mod tests {
507 use super::*;
508 use serde_json::json;
509
510 fn pool() -> VariablePool {
511 let mut p = VariablePool::new();
512 p.insert("n", "s", Value::from("hello world"));
513 p.insert("n", "i", Value::Int(3));
514 p.insert("n", "f", Value::Float(2.5));
515 p.insert("n", "b", Value::Bool(true));
516 p.insert("n", "arr", Value::from_json(json!(["a", "b", 1])));
517 p.insert("n", "empty", Value::from(""));
518 p.insert("n", "ref", Value::from("world"));
519 p
520 }
521
522 fn cond(sel: &str, op: &str, value: serde_json::Value) -> Condition {
523 serde_json::from_value(json!({
524 "variable_selector": sel.split('.').collect::<Vec<_>>(),
525 "comparison_operator": op,
526 "value": value,
527 }))
528 .unwrap()
529 }
530
531 fn eval(sel: &str, op: &str, value: serde_json::Value) -> bool {
532 evaluate(&cond(sel, op, value), &pool()).unwrap()
533 }
534
535 #[test]
536 fn string_operators() {
537 assert!(eval("n.s", "contains", json!("lo w")));
538 assert!(!eval("n.s", "not contains", json!("lo w")));
539 assert!(eval("n.s", "start with", json!("hell")));
540 assert!(eval("n.s", "starts with", json!("hell")));
541 assert!(eval("n.s", "end with", json!("world")));
542 assert!(eval("n.s", "is", json!("hello world")));
543 assert!(eval("n.s", "is not", json!("x")));
544 assert!(eval("n.empty", "empty", json!(null)));
545 assert!(eval("n.s", "not empty", json!(null)));
546 }
547
548 #[test]
549 fn template_in_expected_value() {
550 assert!(eval("n.s", "end with", json!("{{#n.ref#}}")));
551 }
552
553 #[test]
554 fn numeric_no_truncation() {
555 assert!(!eval("n.i", "=", json!("3.9")));
556 assert!(eval("n.i", "=", json!("3")));
557 assert!(eval("n.i", "==", json!(3.0)));
558 assert!(eval("n.f", ">", json!(2)));
559 assert!(eval("n.f", "≤", json!("2.5")));
560 assert!(eval("n.i", ">=", json!(3)));
561 assert!(eval("n.i", "≠", json!(4)));
562 }
563
564 #[test]
565 fn missing_variable_is_null() {
566 assert!(eval("n.missing", "not exists", json!(null)));
567 assert!(eval("n.missing", "null", json!(null)));
568 assert!(eval("n.missing", "empty", json!(null)));
569 assert!(!eval("n.missing", "exists", json!(null)));
570 assert!(!eval("n.missing", ">", json!(1)));
571 assert!(!eval("n.missing", "contains", json!("x")));
572 assert!(eval("n.missing", "not contains", json!("x")));
573 assert!(!eval("n.missing", "=", json!(1)));
574 assert!(eval("n.missing", "≠", json!(1)));
575 }
576
577 #[test]
578 fn booleans() {
579 assert!(eval("n.b", "is", json!("true")));
580 assert!(eval("n.b", "=", json!(true)));
581 assert!(!eval("n.b", "is", json!("false")));
582 }
583
584 #[test]
585 fn arrays_and_membership() {
586 assert!(eval("n.arr", "contains", json!("a")));
587 assert!(eval("n.arr", "contains", json!("1")));
588 assert!(eval("n.arr", "all of", json!(["a", "b"])));
589 assert!(!eval("n.arr", "all of", json!(["a", "z"])));
590 assert!(eval("n.i", "in", json!(["1", "3"])));
591 assert!(eval("n.s", "not in", json!(["hello"])));
592 assert!(!eval("n.ref", "in", json!("hello world")));
594 assert!(eval("n.ref", "in", json!("hello, world")));
595 }
596
597 #[test]
598 fn type_errors_are_reported() {
599 assert!(evaluate(&cond("n.i", "start with", json!("3")), &pool()).is_err());
600 assert!(evaluate(&cond("n.s", ">", json!(1)), &pool()).is_err());
601 }
602
603 #[test]
604 fn group_short_circuit_and_trace() {
605 let conds = vec![cond("n.i", "=", json!(4)), cond("n.s", "contains", json!("hello"))];
606 let (r, t) = evaluate_group(&conds, LogicalOperator::And, &pool()).unwrap();
607 assert!(!r);
608 assert_eq!(t.len(), 1);
609 let (r, t) = evaluate_group(&conds, LogicalOperator::Or, &pool()).unwrap();
610 assert!(r);
611 assert_eq!(t.len(), 2);
612 assert!(!evaluate_group(&[], LogicalOperator::And, &pool()).unwrap().0);
613 }
614
615 #[test]
616 fn file_sub_conditions_respect_outer_operator() {
617 let mut p = VariablePool::new();
618 let files = json!([
619 {"$file": true, "name": "a.png", "kind": "image", "extension": ".png"},
620 {"$file": true, "name": "b.pdf", "kind": "document", "extension": ".pdf"}
621 ]);
622 p.insert("n", "files", Value::from_json_trusted(files));
623 let mk = |op: &str, ext: &str| -> Condition {
624 serde_json::from_value(json!({
625 "variable_selector": ["n", "files"],
626 "comparison_operator": op,
627 "sub_variable_condition": {"logical_operator": "and", "conditions": [
628 {"key": "extension", "comparison_operator": "is", "value": ext}
629 ]}
630 }))
631 .unwrap()
632 };
633 assert!(evaluate(&mk("contains", ".png"), &p).unwrap());
634 assert!(!evaluate(&mk("not contains", ".png"), &p).unwrap());
635 assert!(evaluate(&mk("not contains", ".doc"), &p).unwrap());
636 assert!(!evaluate(&mk("all of", ".png"), &p).unwrap());
637 }
638
639 #[test]
640 fn operator_wire_names_roundtrip() {
641 for op in ["contains", "≠", "≥", "≤", "start with", "not exists", "all of"] {
642 let parsed: Operator = serde_json::from_value(json!(op)).unwrap();
643 assert_eq!(parsed.as_str(), op);
644 }
645 }
646}