grippo 0.1.1

Parse, match and scrub data at scale.
Documentation
use std::borrow::Cow;

use super::{Json, Line, Miss, Record, Typed};

/// A path read in full: the typed value and its text, or the miss.
fn read<'a, R: Record<'a>>(record: R, path: &str) -> Result<(Typed<'a>, Cow<'a, str>), Miss> {
    let keys: Vec<&str> = path.split('/').collect();
    let at = record.find(&keys)?;
    Ok((record.typed(at)?, record.text(at)?))
}

fn string(s: &str) -> Typed<'_> {
    Typed::Str(Cow::Borrowed(s))
}

#[test]
fn json_reads_each_type_and_names_each_miss() {
    let json = Json::new(
        br#" {"s":"a\"b","n":-3,"u":18446744073709551615,"d":1.50,"t":true,"z":null,
             "l":[1,2],"m":{"k":{"x":"v"}}}"#,
    );
    let cases: &[(&str, Result<(Typed<'_>, &str), Miss>)] = &[
        ("s", Ok((Typed::Str("a\"b".into()), "a\"b"))),
        ("n", Ok((Typed::Int(-3), "-3"))),
        ("u", Ok((Typed::Uint(u64::MAX), "18446744073709551615"))),
        ("d", Ok((Typed::Double(1.5), "1.50"))),
        ("t", Ok((Typed::Bool(true), "true"))),
        ("z", Ok((Typed::Null, "null"))),
        ("l", Ok((Typed::List, "[1,2]"))),
        ("m/k/x", Ok((string("v"), "v"))),
        ("m/k", Ok((Typed::Map, r#"{"x":"v"}"#))),
        ("nope", Err(Miss::MissingRoot)),
        ("m/nope", Err(Miss::MissingField)),
        ("m/k/nope/deeper", Err(Miss::MissingField)),
        ("s/x", Err(Miss::WrongParentType)),
        ("l/0", Err(Miss::WrongParentType)),
        ("", Err(Miss::MissingRoot)),
    ];
    for (path, want) in cases {
        let got = read(json, path);
        let want = want.clone().map(|(t, text)| (t, Cow::Borrowed(text)));
        assert_eq!(got, want, "{path}");
    }
    for bytes in [&b"[1]"[..], &b""[..], &br#""x""#[..], &b"  7"[..]] {
        assert_eq!(
            Json::new(bytes).find(&["a"]),
            Err(Miss::MissingRoot),
            "{bytes:?}"
        );
    }
    for bytes in [&br#"{"bad":}"#[..], &br#"{"bad":"\x"}"#[..]] {
        assert_eq!(
            read(Json::new(bytes), "bad"),
            Err(Miss::Malformed),
            "{bytes:?}"
        );
    }
    let m = json.find(&["m"]).expect("m is there");
    let x = json.find_below(m, &["k", "x"]).expect("below m");
    assert_eq!(json.typed(x), Ok(string("v")));
    assert_eq!(json.find_below(m, &[] as &[&str]), Ok(m));
}

#[test]
fn a_line_is_one_string_field() {
    let line = Line::new(b"link up on port 3");
    let named = Line::named(b"x", "raw");
    let cases: &[(Line<'_>, &str, Result<(Typed<'_>, &str), Miss>)] = &[
        (
            line,
            "message",
            Ok((string("link up on port 3"), "link up on port 3")),
        ),
        (line, "msg", Err(Miss::MissingRoot)),
        (line, "message/x", Err(Miss::WrongParentType)),
        (line, "", Err(Miss::MissingRoot)),
        (named, "raw", Ok((string("x"), "x"))),
        (named, "message", Err(Miss::MissingRoot)),
        (Line::new(b"\xff"), "message", Err(Miss::Malformed)),
        (Line::new(b""), "message", Ok((string(""), ""))),
    ];
    for (record, path, want) in cases {
        let want = want.clone().map(|(t, text)| (t, Cow::Borrowed(text)));
        assert_eq!(read(*record, path), want, "{path}");
    }
}

#[cfg(feature = "parse")]
#[test]
fn fields_read_as_a_nested_record_by_dotted_name() {
    use crate::parse::{FieldSink, FieldValue, Fields, Hint};

    let mut fields = Fields::new();
    let rows: &[(&str, &[u8], Hint)] = &[
        ("host", b"fw01", Hint::Text),
        ("syslog.pri", b"134", Hint::Int),
        ("syslog.big", b"18446744073709551615", Hint::Int),
        ("syslog.ratio", b"0.5", Hint::Float),
        ("syslog.ok", b"true", Hint::Bool),
        ("syslog.odd", b"yes", Hint::Bool),
        ("syslog.port", b"n/a", Hint::Int),
        ("cef.src", b"10.0.0.1", Hint::Ip),
        ("cef.ext", br#"{"a":{"b":7},"s":"q\"x"}"#, Hint::Json),
        ("tag", b"a", Hint::Text),
        ("tag", b"b", Hint::Text),
        ("bad", b"\xff", Hint::Text),
        ("a.b.c", b"deep", Hint::Text),
        ("a.b.d", b"1", Hint::Int),
    ];
    for (name, bytes, hint) in rows {
        fields.field(name, FieldValue::borrowed(bytes, *hint));
    }
    let record = &fields;
    let cases: &[(&str, Result<(Typed<'_>, &str), Miss>)] = &[
        ("host", Ok((string("fw01"), "fw01"))),
        ("syslog/pri", Ok((Typed::Int(134), "134"))),
        (
            "syslog/big",
            Ok((Typed::Uint(u64::MAX), "18446744073709551615")),
        ),
        ("syslog/ratio", Ok((Typed::Double(0.5), "0.5"))),
        ("syslog/ok", Ok((Typed::Bool(true), "true"))),
        ("syslog/odd", Ok((string("yes"), "yes"))),
        ("syslog/port", Ok((string("n/a"), "n/a"))),
        ("cef/src", Ok((string("10.0.0.1"), "10.0.0.1"))),
        ("cef/ext/a/b", Ok((Typed::Int(7), "7"))),
        ("cef/ext/s", Ok((Typed::Str("q\"x".into()), "q\"x"))),
        ("cef/ext/a", Ok((Typed::Map, r#"{"b":7}"#))),
        ("tag", Ok((Typed::List, r#"["a","b"]"#))),
        ("a", Ok((Typed::Map, r#"{"b":{"c":"deep","d":1}}"#))),
        ("a/b/c", Ok((string("deep"), "deep"))),
        ("nope", Err(Miss::MissingRoot)),
        ("syslog/nope", Err(Miss::MissingField)),
        ("a/b/nope", Err(Miss::MissingField)),
        ("cef/ext/nope", Err(Miss::MissingField)),
        ("host/x", Err(Miss::WrongParentType)),
        ("tag/x", Err(Miss::WrongParentType)),
        ("cef/ext/a/b/c", Err(Miss::WrongParentType)),
        ("syslog.pri", Err(Miss::MissingRoot)),
        ("bad", Err(Miss::Malformed)),
        ("", Err(Miss::MissingRoot)),
    ];
    for (path, want) in cases {
        let want = want.clone().map(|(t, text)| (t, Cow::Borrowed(text)));
        assert_eq!(read(record, path), want, "{path}");
    }
    // A key holding a dot is one key, which no name split at its dots matches.
    assert_eq!(record.find(&["a", "b.c"]), Err(Miss::MissingField));
    let a = record.find(&["a"]).expect("a is there");
    let b = record.find_below(a, &["b"]).expect("a.b is there");
    let d = record.find_below(b, &["d"]).expect("a.b.d is there");
    assert_eq!(record.typed(d), Ok(Typed::Int(1)));
    assert_eq!(record.find_below(b, &["nope"]), Err(Miss::MissingField));
    assert_eq!((&Fields::new()).find(&["x"]).err(), Some(Miss::MissingRoot));
}

#[cfg(feature = "parse")]
#[test]
fn a_name_is_read_before_longer_names_below_it() {
    use crate::parse::{FieldSink, FieldValue, Fields, Hint};

    let mut fields = Fields::new();
    fields.field("a.b", FieldValue::borrowed(b"below", Hint::Text));
    fields.field("a", FieldValue::borrowed(b"top", Hint::Text));
    let record = &fields;
    assert_eq!(read(record, "a").map(|(t, _)| t), Ok(string("top")));
    assert_eq!(read(record, "a/b").map(|(t, _)| t), Ok(string("below")));
}

/// Every node a walk gives: depth, key, kind and the value's text, or the miss.
fn walked<'a, R: super::Walk<'a>>(
    record: R,
) -> Result<Vec<(usize, Option<String>, super::Kind, String)>, Miss> {
    let mut nodes = Vec::new();
    record.walk(|n| nodes.push(n))?;
    nodes
        .into_iter()
        .map(|n| {
            let text = String::from_utf8_lossy(&record.bytes(n.at)?).into_owned();
            Ok((n.depth, n.key.map(Cow::into_owned), n.kind, text))
        })
        .collect()
}

#[test]
fn a_json_walk_gives_every_value_in_document_order() {
    use super::Kind::{Bool, List, Map, Null, Number, Str};

    let node = |depth, key: Option<&str>, kind, text: &str| {
        (depth, key.map(str::to_owned), kind, text.to_owned())
    };
    let cases: &[(&[u8], Vec<_>)] = &[
        (
            br#" {"a":-1.5e3,"b":{"c":"x\"y","d":[true,null]},"e":[],"fg":{}} "#,
            vec![
                node(0, Some("a"), Number, "-1.5e3"),
                node(0, Some("b"), Map, r#"{"c":"x\"y","d":[true,null]}"#),
                node(1, Some("c"), Str, "x\"y"),
                node(1, Some("d"), List, "[true,null]"),
                node(2, None, Bool, "true"),
                node(2, None, Null, "null"),
                node(0, Some("e"), List, "[]"),
                node(0, Some("fg"), Map, "{}"),
            ],
        ),
        (
            br#"[1, {"k" : 0}]"#,
            vec![
                node(0, None, List, r#"[1, {"k" : 0}]"#),
                node(1, None, Number, "1"),
                node(1, None, Map, r#"{"k" : 0}"#),
                node(2, Some("k"), Number, "0"),
            ],
        ),
        (b"\t7\n", vec![node(0, None, Number, "7")]),
        (br#""s""#, vec![node(0, None, Str, "s")]),
        (b"{}", vec![]),
    ];
    for (bytes, want) in cases {
        assert_eq!(walked(Json::new(bytes)).as_ref(), Ok(want), "{bytes:?}");
    }
    let malformed: &[&[u8]] = &[
        b"",
        b"   ",
        br#"{"a":}"#,
        br#"{"a":1,}"#,
        b"[1,]",
        b"[,1]",
        b"[1 2]",
        br#"{"a" 1}"#,
        b"{1:2}",
        br#"{"a":1}}"#,
        br#"{"a":1} x"#,
        b"[",
        b"01",
        b"1.",
        b"1e",
        b"-",
        b"+1",
        b"tru",
        b"nul",
        br#""\x""#,
        br#""\u12""#,
        b"\"tab\there\"",
        br#""open"#,
        b"\xff",
        br#"{"\q":1}"#,
    ];
    for bytes in malformed {
        let mut calls = 0;
        let got = super::Walk::walk(Json::new(bytes), |_| calls += 1);
        assert_eq!((got, calls), (Err(Miss::Malformed), 0), "{bytes:?}");
    }
}

#[test]
fn a_json_record_is_rebuilt_with_strings_spliced_in() {
    let bytes = br#"{"a": 1, "b": {"c": [2, "x"]}, "d": "\u00e9"}"#;
    let json = Json::new(bytes);
    let mut ats = Vec::new();
    super::Walk::walk(json, |n| ats.push(n.at)).expect("walks");
    let mut out = Vec::new();
    // The number, the list as a whole, and the escaped string.
    let edits = [(ats[0], &b"T\"1"[..]), (ats[2], b"L"), (ats[5], b"\xffd")];
    json.splice_strings(&edits, &mut out).expect("splices");
    let want = r#"{"a": "T\"1", "b": {"c": "L"}, "d": "?d"}"#.replace('?', "\u{fffd}");
    assert_eq!(String::from_utf8(out).expect("utf-8"), want);
    let mut out = b"kept".to_vec();
    let backwards = [(ats[5], &b""[..]), (ats[0], b"")];
    assert_eq!(
        json.splice_strings(&backwards, &mut out),
        Err(Miss::Malformed)
    );
    let foreign = [("elsewhere", &b""[..])];
    assert_eq!(
        json.splice_strings(&foreign, &mut out),
        Err(Miss::Malformed)
    );
    assert_eq!(out, b"kept");
}

#[test]
fn a_line_walks_as_its_one_field() {
    use super::Kind::Str;

    let want = vec![(0, Some("raw".to_owned()), Str, "\u{fffd}x".to_owned())];
    assert_eq!(walked(Line::named(b"\xffx", "raw")), Ok(want));
}

#[cfg(feature = "parse")]
#[test]
fn a_fields_walk_reaches_every_field() {
    use super::Kind::{List, Map, Number, Str};
    use crate::parse::{FieldSink, FieldValue, Fields, Hint};

    let mut fields = Fields::new();
    let rows: &[(&str, &[u8], Hint)] = &[
        ("host", b"fw01", Hint::Text),
        ("syslog.pri", b"134", Hint::Int),
        ("tag", b"a", Hint::Text),
        ("tag", b"b", Hint::Text),
        ("cef.ext", br#" {"a":{"b":7}} "#, Hint::Json),
        ("a.b", b"below", Hint::Text),
        ("a", b"top", Hint::Text),
        ("j", b"{", Hint::Json),
        ("port", b"n/a", Hint::Int),
        ("x..y", b"z", Hint::Text),
        ("bad", b"\xff", Hint::Text),
    ];
    for (name, bytes, hint) in rows {
        fields.field(name, FieldValue::borrowed(bytes, *hint));
    }
    let node =
        |depth, key: &str, kind, text: &str| (depth, Some(key.to_owned()), kind, text.to_owned());
    let item = |text: &str| (1, None, Str, text.to_owned());
    let want = vec![
        node(0, "host", Str, "fw01"),
        node(0, "syslog", Map, r#"{"pri":134}"#),
        node(1, "pri", Number, "134"),
        node(0, "tag", List, r#"["a","b"]"#),
        item("a"),
        item("b"),
        node(0, "cef", Map, r#"{"ext": {"a":{"b":7}} }"#),
        node(1, "ext", Map, r#"{"a":{"b":7}}"#),
        node(2, "a", Map, r#"{"b":7}"#),
        node(3, "b", Number, "7"),
        // A name that is a path, then the longer names below it.
        node(0, "a", Str, "top"),
        node(0, "a", Map, r#"{"b":"below"}"#),
        node(1, "b", Str, "below"),
        // JSON that doesn't parse is its text.
        node(0, "j", Str, "{"),
        node(0, "port", Str, "n/a"),
        node(0, "x", Map, r#"{"":{"y":"z"}}"#),
        node(1, "", Map, r#"{"y":"z"}"#),
        node(2, "y", Str, "z"),
        // A field's bytes as they are.
        node(0, "bad", Str, "\u{fffd}"),
    ];
    assert_eq!(walked(&fields), Ok(want));

    let mut deep = Fields::new();
    deep.field(&"a.".repeat(65), FieldValue::borrowed(b"x", Hint::Text));
    assert_eq!(walked(&deep), Err(Miss::Malformed));
}