1use crate::json::{obj, Json};
30use crate::types::{Errc, RcpError};
31
32pub const SCALAR_OPS: [&str; 6] = ["eq", "ne", "gt", "gte", "lt", "lte"];
34pub const ARRAY_OPS: [&str; 2] = ["in", "nin"];
36pub const UNARY_OPS: [&str; 1] = ["exists"];
38pub const STRING_OPS: [&str; 1] = ["contains"];
40
41const ORDERED_OPS: [&str; 4] = ["gt", "gte", "lt", "lte"];
42const ORDERED_TYPES: [&str; 3] = ["int", "float", "date"];
43
44fn is_known_op(op: &str) -> bool {
45 SCALAR_OPS.contains(&op)
46 || ARRAY_OPS.contains(&op)
47 || UNARY_OPS.contains(&op)
48 || STRING_OPS.contains(&op)
49}
50
51#[derive(Clone, Debug)]
56pub struct Filter(Json);
57
58impl Filter {
59 pub fn to_json(&self) -> Json {
61 self.0.clone()
62 }
63
64 pub fn and(self, other: Filter) -> Filter {
66 all([self, other])
67 }
68
69 pub fn or(self, other: Filter) -> Filter {
71 any([self, other])
72 }
73
74 pub fn negate(self) -> Filter {
76 Filter(obj(&[("not", self.0)]))
77 }
78}
79
80impl std::ops::Not for Filter {
81 type Output = Filter;
82 fn not(self) -> Filter {
83 self.negate()
84 }
85}
86
87impl std::ops::BitAnd for Filter {
88 type Output = Filter;
89 fn bitand(self, rhs: Filter) -> Filter {
90 self.and(rhs)
91 }
92}
93
94impl std::ops::BitOr for Filter {
95 type Output = Filter;
96 fn bitor(self, rhs: Filter) -> Filter {
97 self.or(rhs)
98 }
99}
100
101fn leaf(field: &str, op: &str, value: Json) -> Filter {
102 Filter(obj(&[
103 ("field", Json::from(field)),
104 ("op", Json::from(op)),
105 ("value", value),
106 ]))
107}
108
109pub fn eq(field: &str, value: impl Into<Json>) -> Filter {
111 leaf(field, "eq", value.into())
112}
113pub fn ne(field: &str, value: impl Into<Json>) -> Filter {
115 leaf(field, "ne", value.into())
116}
117pub fn gt(field: &str, value: impl Into<Json>) -> Filter {
119 leaf(field, "gt", value.into())
120}
121pub fn gte(field: &str, value: impl Into<Json>) -> Filter {
123 leaf(field, "gte", value.into())
124}
125pub fn lt(field: &str, value: impl Into<Json>) -> Filter {
127 leaf(field, "lt", value.into())
128}
129pub fn lte(field: &str, value: impl Into<Json>) -> Filter {
131 leaf(field, "lte", value.into())
132}
133
134pub fn in_(field: &str, values: impl IntoIterator<Item = Json>) -> Filter {
136 leaf(field, "in", Json::Array(values.into_iter().collect()))
137}
138pub fn nin(field: &str, values: impl IntoIterator<Item = Json>) -> Filter {
140 leaf(field, "nin", Json::Array(values.into_iter().collect()))
141}
142pub fn contains(field: &str, value: impl Into<Json>) -> Filter {
144 leaf(field, "contains", value.into())
145}
146pub fn exists(field: &str, present: bool) -> Filter {
148 leaf(field, "exists", Json::Bool(present))
149}
150
151pub fn all(clauses: impl IntoIterator<Item = Filter>) -> Filter {
153 combine("and", clauses)
154}
155pub fn any(clauses: impl IntoIterator<Item = Filter>) -> Filter {
157 combine("or", clauses)
158}
159pub fn not(clause: Filter) -> Filter {
161 clause.negate()
162}
163
164fn combine(kind: &str, clauses: impl IntoIterator<Item = Filter>) -> Filter {
165 let arr = Json::Array(clauses.into_iter().map(|c| c.0).collect());
166 Filter(obj(&[(kind, arr)]))
167}
168
169pub fn validate(
183 node: Option<&Json>,
184 fields: Option<&[(&str, &str)]>,
185 operators: Option<&[&str]>,
186 max_depth: i32,
187) -> Result<Option<Json>, RcpError> {
188 let node = match node {
189 None => return Ok(None),
190 Some(n) if n.is_null() => return Ok(None),
191 Some(Json::Object(o)) if o.is_empty() => return Ok(None),
192 Some(n) => n,
193 };
194 Ok(Some(validate_node(node, fields, operators, "filter", max_depth)?))
195}
196
197fn validate_node(
198 node: &Json,
199 fields: Option<&[(&str, &str)]>,
200 operators: Option<&[&str]>,
201 path: &str,
202 depth: i32,
203) -> Result<Json, RcpError> {
204 if depth < 0 {
205 return Err(bad(path, "filter nesting too deep"));
206 }
207 let obj_pairs = match node.as_object() {
208 Some(o) => o,
209 None => return Err(bad(path, "filter node must be an object")),
210 };
211
212 let has = |k: &str| obj_pairs.iter().any(|(kk, _)| kk == k);
213 let present: Vec<&str> = ["and", "or", "not"].into_iter().filter(|k| has(k)).collect();
214 let is_leaf = has("field") || has("op");
215 if present.len() > 1 {
216 return Err(bad(path, "filter node has multiple combinators"));
217 }
218 if !present.is_empty() && is_leaf {
219 return Err(bad(path, "filter node mixes a combinator with a leaf"));
220 }
221
222 if let Some(&comb) = present.first() {
223 if comb == "not" {
224 let child = node.get("not").unwrap();
225 let inner = validate_node(child, fields, operators, &format!("{path}.not"), depth - 1)?;
226 return Ok(obj(&[("not", inner)]));
227 }
228 let kids = match node.get(comb).and_then(|v| v.as_array()) {
229 Some(a) => a,
230 None => return Err(bad(&format!("{path}.{comb}"), "combinator must be an array")),
231 };
232 let mut out = Vec::with_capacity(kids.len());
233 for (i, c) in kids.iter().enumerate() {
234 out.push(validate_node(c, fields, operators, &format!("{path}.{comb}[{i}]"), depth - 1)?);
235 }
236 return Ok(obj(&[(comb, Json::Array(out))]));
237 }
238
239 if !is_leaf {
240 return Err(bad(path, "filter node is neither a combinator nor a leaf"));
241 }
242
243 let field = match node.get_str("field") {
245 Some(f) if !f.is_empty() => f,
246 _ => return Err(bad(path, "leaf requires a non-empty string 'field'")),
247 };
248 let op = match node.get_str("op") {
249 Some(o) => o,
250 None => return Err(bad(&format!("{path}.op"), "leaf requires a string 'op'")),
251 };
252 if !is_known_op(op) {
253 return Err(bad(&format!("{path}.op"), &format!("unknown operator '{op}'")));
254 }
255 if let Some(ops) = operators {
256 if !ops.contains(&op) {
257 return Err(bad(&format!("{path}.op"), &format!("operator '{op}' not advertised")));
258 }
259 }
260 let ftype = match fields {
261 Some(fs) => match fs.iter().find(|(n, _)| *n == field) {
262 Some((_, t)) => Some(*t),
263 None => return Err(bad(&format!("{path}.{field}"), &format!("field '{field}' not advertised"))),
264 },
265 None => None,
266 };
267
268 check_value(op, node, ftype, path)?;
269
270 let value = if UNARY_OPS.contains(&op) {
271 Json::Bool(node.get("value").and_then(|v| v.as_bool()).unwrap_or(true))
272 } else {
273 node.get("value").cloned().unwrap()
274 };
275 Ok(obj(&[
276 ("field", Json::from(field)),
277 ("op", Json::from(op)),
278 ("value", value),
279 ]))
280}
281
282fn check_value(op: &str, node: &Json, ftype: Option<&str>, path: &str) -> Result<(), RcpError> {
283 if UNARY_OPS.contains(&op) {
284 return Ok(());
285 }
286 let value = match node.get("value") {
287 Some(v) => v,
288 None => return Err(bad(&format!("{path}.value"), &format!("operator '{op}' requires a 'value'"))),
289 };
290 if ARRAY_OPS.contains(&op) {
291 match value.as_array() {
292 Some(a) if !a.is_empty() => {
293 if a.iter().any(|v| matches!(v, Json::Array(_) | Json::Object(_))) {
294 return Err(bad(&format!("{path}.value"), &format!("operator '{op}' array must hold scalars")));
295 }
296 }
297 _ => return Err(bad(&format!("{path}.value"), &format!("operator '{op}' requires a non-empty array"))),
298 }
299 } else if (SCALAR_OPS.contains(&op) || STRING_OPS.contains(&op))
300 && matches!(value, Json::Array(_) | Json::Object(_))
301 {
302 return Err(bad(&format!("{path}.value"), &format!("operator '{op}' requires a scalar value")));
303 }
304 if ORDERED_OPS.contains(&op) {
305 if let Some(t) = ftype {
306 if !t.is_empty() && !ORDERED_TYPES.contains(&t) {
307 return Err(bad(&format!("{path}.op"), &format!("operator '{op}' not valid on '{t}' field")));
308 }
309 }
310 }
311 Ok(())
312}
313
314fn bad(path: &str, message: &str) -> RcpError {
315 RcpError::with_data(
316 Errc::INVALID_PARAMS,
317 format!("{message} ({path})"),
318 obj(&[("field", Json::from(path))]),
319 )
320}
321
322#[cfg(test)]
323mod tests {
324 use super::*;
325
326 const FIELDS: [(&str, &str); 2] = [("year", "int"), ("lang", "keyword")];
327 const OPS: [&str; 8] = ["eq", "ne", "gt", "gte", "lt", "lte", "in", "nin"];
328
329 #[test]
330 fn builder_emits_spec_shape() {
331 let leaf = eq("lang", "fr").to_json();
332 assert_eq!(leaf.get_str("field"), Some("lang"));
333 assert_eq!(leaf.get_str("op"), Some("eq"));
334 assert_eq!(leaf.get("value").and_then(|v| v.as_str()), Some("fr"));
335
336 let tree = eq("lang", "en").and(gte("year", 2015i64)).to_json();
337 let arr = tree.get("and").and_then(|v| v.as_array()).unwrap();
338 assert_eq!(arr.len(), 2);
339 }
340
341 #[test]
342 fn validate_accepts_well_formed() {
343 let tree = all([eq("lang", "en"), gte("year", 2015i64)]).to_json();
344 let out = validate(Some(&tree), Some(&FIELDS), Some(&OPS), 32).unwrap();
345 assert!(out.is_some());
346 assert!(validate(None, Some(&FIELDS), None, 32).unwrap().is_none());
348 assert!(validate(Some(&Json::object()), Some(&FIELDS), None, 32).unwrap().is_none());
349 }
350
351 #[test]
352 fn validate_rejects_every_malformed_tree_with_32602() {
353 let cases = [
354 obj(&[("field", "author".into()), ("op", "eq".into()), ("value", "z".into())]),
355 obj(&[("field", "lang".into()), ("op", "equals".into()), ("value", "en".into())]),
356 obj(&[("and", "not-a-list".into())]),
357 obj(&[("field", "year".into()), ("op", "in".into()), ("value", Json::Int(2017))]),
358 obj(&[("or", Json::Array(vec![obj(&[("field", "lang".into())])]))]),
359 obj(&[("field", "lang".into()), ("op", "gt".into()), ("value", "en".into())]),
360 ];
361 for c in &cases {
362 let err = validate(Some(c), Some(&FIELDS), Some(&OPS), 32).unwrap_err();
363 assert_eq!(err.code, Errc::INVALID_PARAMS, "case: {}", c.dump());
364 assert!(err.data.as_ref().and_then(|d| d.get("field")).is_some());
365 }
366 }
367}