fauxrest 0.0.5

A CLI tool for generating static JSON APIs from local data files
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
//! `$filter` directive support: the [`FilterOp`] comparison operators and
//! [`FilterCondition`](crate::filter::FilterCondition) evaluation used to
//! keep or drop items when materializing an endpoint.

use std::cmp::Ordering;
use std::fmt::Display;

use serde::Deserialize;
use serde_json::Value;

use crate::{Error, Result};

/// This operation targets the `$filter` directive.
/// All operations use `op` to process the value of `field` and the given `value`.
///
/// The ordering operators accept two numbers or two strings; strings compare
/// lexicographically, which is what sorts ISO-8601 dates correctly. Mixing
/// kinds is an error rather than a non-match.
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum FilterOp {
    /// `field` equals to `value`
    Eq,
    /// `field` not equals to `value`
    Neq,
    /// `field` is greater than `value`
    Gt,
    /// `field` is greater than or equals to `value`
    Gte,
    /// `field` is less than `value`
    Lt,
    /// `field` is less than or equals to `value`
    Lte,
    /// `field` contains `value`.
    Contains,
    /// `field` is exists or not (`value` should be `true` or `false`, `true` means exists)
    Exists,
    /// `field` is matched by `value`.
    RegEq,
    /// `field` is not matched by `value`.
    RegNeq,
}

impl Display for FilterOp {
    /// Formats this operator using its lowercase JSON name (e.g. `"eq"`,
    /// `"regeq"`), matching the strings used in `_config.json`.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FilterOp::Eq => write!(f, "eq"),
            FilterOp::Neq => write!(f, "neq"),
            FilterOp::Gt => write!(f, "gt"),
            FilterOp::Gte => write!(f, "gte"),
            FilterOp::Lt => write!(f, "lt"),
            FilterOp::Lte => write!(f, "lte"),
            FilterOp::Contains => write!(f, "contains"),
            FilterOp::Exists => write!(f, "exists"),
            FilterOp::RegEq => write!(f, "regeq"),
            FilterOp::RegNeq => write!(f, "regneq"),
        }
    }
}

/// A single `$filter` condition: `field <op> value`, evaluated against each
/// candidate item.
#[derive(Deserialize, Debug, Clone, PartialEq)]
pub struct FilterCondition {
    /// Name of the object field to read from each item.
    pub field: String,
    /// Comparison operator to apply.
    pub op: FilterOp,
    /// Right-hand side value to compare the field against.
    pub value: Value,
}

impl FilterCondition {
    /// Evaluates this condition against `item`, returning whether it
    /// matches.
    ///
    /// If `item` does not have `field`, the condition is considered
    /// unmatched for every operator except [`FilterOp::Exists`] (which
    /// checks for the field's presence) and [`FilterOp::RegNeq`] (which
    /// treats a missing field as not matching the pattern, i.e. `true`).
    ///
    /// # Errors
    ///
    /// Returns [`Error::FilterType`](crate::Error::FilterType) when the
    /// record's value and `value` hold JSON kinds this operator cannot
    /// compare — see [`check_type_mismatch`]. Also returns an error if
    /// [`FilterOp::RegEq`]/[`FilterOp::RegNeq`] is used with a non-string
    /// `value` or an invalid regex pattern.
    ///
    /// # Examples
    ///
    /// ```
    /// use fauxrest::filter::{FilterCondition, FilterOp};
    /// use serde_json::json;
    ///
    /// let cond = FilterCondition {
    ///     field: "status".to_string(),
    ///     op: FilterOp::Eq,
    ///     value: json!("active"),
    /// };
    /// let item = json!({ "status": "active" });
    /// assert!(cond.apply(&item).unwrap());
    /// ```
    pub fn apply(&self, item: &Value) -> Result<bool> {
        let target = item.get(&self.field);
        check_type_mismatch(&self.op, &self.field, target, &self.value)?;
        let result = match self.op {
            FilterOp::Eq => target.is_some_and(|t| t.eq(&self.value)),
            FilterOp::Neq => target.is_some_and(|t| t.ne(&self.value)),
            FilterOp::Gt => compare_ord(target, &self.value, Ordering::is_gt),
            FilterOp::Gte => compare_ord(target, &self.value, Ordering::is_ge),
            FilterOp::Lt => compare_ord(target, &self.value, Ordering::is_lt),
            FilterOp::Lte => compare_ord(target, &self.value, Ordering::is_le),
            FilterOp::Contains => contains_value(target, &self.value),
            FilterOp::Exists => {
                let expected = self.value.as_bool().unwrap_or(false);
                target.is_some() == expected
            }
            FilterOp::RegEq => regex_match(target, &self.value, true)?,
            FilterOp::RegNeq => regex_match(target, &self.value, false)?,
        };
        Ok(result)
    }
}

/// Implements the ordering operators (`gt`, `gte`, `lt`, `lte`): orders
/// `target` against `rhs` with [`scalar_ordering`] and asks `accept` whether
/// that ordering satisfies the operator. Returns `false` if `target` is absent
/// or the two cannot be ordered.
fn compare_ord<F>(target: Option<&Value>, rhs: &Value, accept: F) -> bool
where
    F: Fn(Ordering) -> bool,
{
    let Some(lhs) = target else {
        return false;
    };
    scalar_ordering(lhs, rhs).is_some_and(accept)
}

/// Orders two values of the same JSON kind: numbers numerically, strings
/// lexicographically by Unicode scalar value. Returns `None` when the kinds
/// differ, or for kinds that have no useful order (bool, null, array,
/// object).
///
/// Lexicographic order is what makes zero-padded, fixed-width formats such as
/// ISO-8601 dates (`"2026-10-16"`) sort correctly as strings. It is *not*
/// meaningful for free-form text like `"April 2023"`, so ordering such a field
/// gives an answer that is well-defined but not the one a reader would expect.
fn scalar_ordering(lhs: &Value, rhs: &Value) -> Option<Ordering> {
    match (lhs, rhs) {
        (Value::Number(_), Value::Number(_)) => lhs.as_f64()?.partial_cmp(&rhs.as_f64()?),
        (Value::String(lhs), Value::String(rhs)) => Some(lhs.as_str().cmp(rhs.as_str())),
        _ => None,
    }
}

/// Implements the `contains` operator: for a string `target`, checks for a
/// substring match against `rhs`; for an array `target`, checks whether any
/// element equals `rhs`. Returns `false` for any other target kind or if
/// `target` is absent.
fn contains_value(target: Option<&Value>, rhs: &Value) -> bool {
    let Some(target) = target else {
        return false;
    };
    match target {
        Value::String(s) => rhs
            .as_str()
            .map(|needle| s.contains(needle))
            .unwrap_or(false),
        Value::Array(arr) => arr.iter().any(|v| v == rhs),
        _ => false,
    }
}

/// Implements the `regeq`/`regneq` operators: compiles `rhs` as a regex and
/// matches it against `target` (which must be a string). `positive`
/// selects between `regeq` semantics (`true` = matched) and `regneq`
/// semantics (`true` = not matched). A missing or non-string `target` is
/// treated as "did not match".
fn regex_match(target: Option<&Value>, rhs: &Value, positive: bool) -> Result<bool> {
    let Some(value) = target.and_then(Value::as_str) else {
        return Ok(!positive);
    };
    let pattern = rhs
        .as_str()
        .ok_or_else(|| Error::Config("regex filter value must be a string".to_string()))?;
    let re = crate::compile_regex(pattern)
        .map_err(|e| Error::Config(format!("invalid regex '{}': {}", pattern, e)))?;
    let matched = re.is_match(value);
    Ok(if positive { matched } else { !matched })
}

/// Fails when `target` is present but its JSON kind is incompatible with
/// `right` for the given operator.
///
/// One field holding different kinds across records is a defect in the input
/// data, not something to reconcile here: no single interpretation keeps every
/// record, so continuing would publish an endpoint quietly missing whichever
/// half lost. Stopping costs one rerun instead.
///
/// Absent fields and nulls are exempt. A field that is a number in most
/// records and `null` in one is an unset value, not a conflicting type, and an
/// explicit `"value": null` in a condition is how a configuration asks whether
/// a field is unset.
fn check_type_mismatch(
    op: &FilterOp,
    field: &str,
    target: Option<&Value>,
    right: &Value,
) -> Result<()> {
    let Some(left) = target else {
        return Ok(());
    };
    if left.is_null() || right.is_null() || is_type_compatible(op, left, right) {
        return Ok(());
    }
    let (left_kind, right_kind) = (crate::value_kind(left), crate::value_kind(right));
    let detail = if left_kind == right_kind {
        format!("op '{op}' cannot compare two values of kind {left_kind}")
    } else {
        format!("the record holds {left_kind}, the condition compares against {right_kind}")
    };
    Err(Error::FilterType(format!("field '{field}': {detail}")))
}

/// Returns whether `lhs` and `rhs` have JSON kinds that make sense to
/// compare under `op` (e.g. both numeric or both strings for ordering
/// operators, both strings for regex operators). Operators without a specific
/// kind requirement (like `exists`) are always considered compatible.
///
/// This decides which comparisons [`check_type_mismatch`] rejects, so it has
/// to agree with what the operators actually support — failing a comparison
/// the evaluator handles correctly would reject valid data.
fn is_type_compatible(op: &FilterOp, lhs: &Value, rhs: &Value) -> bool {
    use FilterOp::*;
    match op {
        Eq | Neq => crate::value_kind(lhs) == crate::value_kind(rhs),
        Gt | Gte | Lt | Lte => {
            (lhs.is_number() && rhs.is_number()) || (lhs.is_string() && rhs.is_string())
        }
        Contains => match lhs {
            Value::String(_) => rhs.is_string(),
            Value::Array(_) => true,
            _ => false,
        },
        RegEq | RegNeq => lhs.is_string() && rhs.is_string(),
        _ => true,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn cond(field: &str, op: FilterOp, value: Value) -> FilterCondition {
        FilterCondition {
            field: field.to_string(),
            op,
            value,
        }
    }

    /// Strings order lexicographically, which is what makes ISO-8601 dates
    /// comparable. Before this worked, `gt`/`lt` matched nothing and
    /// `gte`/`lte` matched everything, because both operands collapsed to
    /// `0.0`.
    #[test]
    fn test_iso_dates_compare_as_strings() {
        let early = json!({ "from": "2018-04-01" });
        let late = json!({ "from": "2026-10-16" });
        let pivot = json!("2020-01-01");

        assert!(
            cond("from", FilterOp::Gt, pivot.clone())
                .apply(&late)
                .unwrap()
        );
        assert!(
            !cond("from", FilterOp::Gt, pivot.clone())
                .apply(&early)
                .unwrap()
        );
        assert!(
            cond("from", FilterOp::Lt, pivot.clone())
                .apply(&early)
                .unwrap()
        );
        assert!(
            !cond("from", FilterOp::Lt, pivot.clone())
                .apply(&late)
                .unwrap()
        );
    }

    /// The inclusive operators must distinguish equal from unequal rather than
    /// accepting everything.
    #[test]
    fn test_inclusive_operators_are_not_always_true() {
        let item = json!({ "from": "2020-01-01" });
        let same = json!("2020-01-01");
        let later = json!("2021-01-01");

        assert!(
            cond("from", FilterOp::Gte, same.clone())
                .apply(&item)
                .unwrap()
        );
        assert!(cond("from", FilterOp::Lte, same).apply(&item).unwrap());
        assert!(
            !cond("from", FilterOp::Gte, later.clone())
                .apply(&item)
                .unwrap()
        );
        assert!(cond("from", FilterOp::Lte, later).apply(&item).unwrap());
    }

    /// Numeric ordering is unchanged.
    #[test]
    fn test_numbers_still_compare_numerically() {
        let item = json!({ "age": 20 });
        assert!(cond("age", FilterOp::Gt, json!(18)).apply(&item).unwrap());
        assert!(!cond("age", FilterOp::Gt, json!(20)).apply(&item).unwrap());
        assert!(cond("age", FilterOp::Gte, json!(20)).apply(&item).unwrap());
        // Lexicographic order would call "20" less than "9"; numeric must not.
        assert!(cond("age", FilterOp::Gt, json!(9)).apply(&item).unwrap());
    }

    /// A record and a condition holding different kinds is the mixed-type
    /// input this rejects, and the message has to name both kinds so the
    /// offending record can be found.
    #[test]
    fn test_mismatched_kinds_are_rejected() {
        for (item, value) in [
            (json!({ "f": "2020" }), json!(2020)),
            (json!({ "f": 2020 }), json!("2020")),
        ] {
            for op in [FilterOp::Eq, FilterOp::Gt, FilterOp::Gte, FilterOp::Lte] {
                let err = cond("f", op.clone(), value.clone())
                    .apply(&item)
                    .expect_err("mixed kinds must be rejected");
                let message = err.to_string();
                assert!(
                    message.contains("'f'")
                        && message.contains("number")
                        && message.contains("string"),
                    "{:?} {} {:?} reported unhelpfully: {}",
                    item,
                    op,
                    value,
                    message
                );
            }
        }
    }

    /// Both sides sharing a kind the operator cannot order is equally
    /// unevaluable, and naming the operator is what makes it fixable.
    #[test]
    fn test_unorderable_kinds_are_rejected() {
        for (item, value) in [
            (json!({ "f": true }), json!(false)),
            (json!({ "f": [1, 2] }), json!([1])),
        ] {
            for op in [FilterOp::Gt, FilterOp::Gte, FilterOp::Lt, FilterOp::Lte] {
                let err = cond("f", op.clone(), value.clone())
                    .apply(&item)
                    .expect_err("unorderable kinds must be rejected");
                assert!(
                    err.to_string().contains(&op.to_string()),
                    "{:?} {} {:?} did not name the operator: {}",
                    item,
                    op,
                    value,
                    err
                );
            }
        }
    }

    /// An unset value is not a conflicting type. A field left `null` in one
    /// record out of many is ordinary data, and `"value": null` is how a
    /// condition asks whether a field is unset — neither may fail the run.
    #[test]
    fn test_null_operands_are_exempt() {
        for (item, value) in [
            (json!({ "f": null }), json!(null)),
            (json!({ "f": null }), json!(2020)),
            (json!({ "f": null }), json!("2020")),
            (json!({ "f": 2020 }), json!(null)),
            (json!({ "f": "2020" }), json!(null)),
        ] {
            for op in [FilterOp::Eq, FilterOp::Neq, FilterOp::Gt, FilterOp::Lte] {
                assert!(
                    cond("f", op.clone(), value.clone()).apply(&item).is_ok(),
                    "{:?} {} {:?} must not fail the run",
                    item,
                    op,
                    value
                );
            }
        }
    }

    /// A missing field never matches an ordering operator.
    #[test]
    fn test_absent_field_does_not_match() {
        let item = json!({ "other": "x" });
        assert!(!cond("f", FilterOp::Gte, json!("a")).apply(&item).unwrap());
    }

    /// Two strings are a supported comparison now, so they must not be
    /// reported as a type mismatch. Warning about a comparison the evaluator
    /// handles correctly would be noise.
    #[test]
    fn test_string_operands_are_not_a_type_mismatch() {
        for op in [FilterOp::Gt, FilterOp::Gte, FilterOp::Lt, FilterOp::Lte] {
            assert!(
                is_type_compatible(&op, &json!("2020-01-01"), &json!("2021-01-01")),
                "two strings should be compatible under {}",
                op
            );
            assert!(
                !is_type_compatible(&op, &json!("2020"), &json!(2020)),
                "mixed kinds should still be reported under {}",
                op
            );
        }
    }
}