use std::borrow::Cow;
use std::fmt;
use memchr::memchr2;
use serde::Deserialize;
use serde::de::{DeserializeSeed, Deserializer, Error, IgnoredAny, MapAccess, SeqAccess, Visitor};
#[cfg(any(feature = "parse-gelf", test))]
use serde_json::value::RawValue;
use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser, SinkMark};
use crate::path::key_part;
use crate::strmatch::{Signature, Specificity};
use crate::tier::MatcherTier;
const MAX_DEPTH: u8 = 64;
const NAME_FACTOR: usize = 16;
const NAME_FLOOR: usize = 1 << 20;
#[derive(Debug, Clone)]
pub struct Ndjson {
signature: Signature,
arrays: Arrays,
nulls: Nulls,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Arrays {
#[default]
Each,
Json,
JsonCompact,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Nulls {
#[default]
Skip,
Keep,
}
impl Default for Ndjson {
fn default() -> Self {
Self::new()
}
}
impl Ndjson {
#[must_use]
pub fn new() -> Self {
let signature = Signature::builder()
.anchored(["{"])
.specificity(Specificity::Generic)
.build()
.unwrap_or_else(|_| unreachable!("invariant: `{{` is a non-empty literal"));
Self {
signature,
arrays: Arrays::Each,
nulls: Nulls::Skip,
}
}
#[must_use]
pub const fn arrays(mut self, arrays: Arrays) -> Self {
self.arrays = arrays;
self
}
#[must_use]
pub const fn nulls(mut self, nulls: Nulls) -> Self {
self.nulls = nulls;
self
}
}
#[cfg(any(feature = "parse-gelf", test))]
#[derive(Deserialize)]
pub(super) struct Key<'a>(#[serde(borrow)] pub(super) Cow<'a, str>);
#[cfg(any(feature = "parse-gelf", test))]
pub(super) struct Entries<'a>(pub(super) Vec<(Key<'a>, &'a RawValue)>);
#[cfg(any(feature = "parse-gelf", test))]
impl<'de> Deserialize<'de> for Entries<'de> {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct Visit;
impl<'de> Visitor<'de> for Visit {
type Value = Entries<'de>;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a JSON object")
}
fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Self::Value, M::Error> {
let mut entries = Vec::with_capacity(map.size_hint().unwrap_or(8));
while let Some(entry) = map.next_entry()? {
entries.push(entry);
}
Ok(Entries(entries))
}
}
d.deserialize_map(Visit)
}
}
#[cfg(any(feature = "parse-gelf", test))]
pub(super) fn walk<'a>(
key: &str,
raw: &'a RawValue,
out: &mut dyn FieldSink<'a>,
) -> Result<(), serde_json::Error> {
walk_part(&key_part(Cow::Borrowed(key)), raw, out)
}
#[cfg(any(feature = "parse-gelf", test))]
fn walk_part<'a>(
key: &str,
raw: &'a RawValue,
out: &mut dyn FieldSink<'a>,
) -> Result<(), serde_json::Error> {
let text = raw.get();
match text.as_bytes().first() {
Some(b'{') => {
let Entries(entries) = serde_json::from_str(text)?;
out.push_prefix(key);
out.push_prefix(".");
for (k, v) in entries {
walk(&k.0, v, out)?;
}
out.pop_prefix();
out.pop_prefix();
}
Some(b'[') => {
let items: Vec<&RawValue> = serde_json::from_str(text)?;
for item in items {
walk_part(key, item, out)?;
}
}
Some(b'"') => {
let inner = &text[1..text.len() - 1];
let value = if inner.contains('\\') {
let decoded: String = serde_json::from_str(text)?;
FieldValue::owned(decoded.into_bytes(), Hint::Text)
} else {
FieldValue::borrowed(inner.as_bytes(), Hint::Text)
};
out.field(key, value);
}
Some(b'n') | None => {}
Some(b't' | b'f') => out.field(key, FieldValue::borrowed(text.as_bytes(), Hint::Bool)),
Some(_) => {
let hint = if text.contains(['.', 'e', 'E']) {
Hint::Float
} else {
Hint::Int
};
out.field(key, FieldValue::borrowed(text.as_bytes(), hint));
}
}
Ok(())
}
#[derive(Debug, Clone, Copy)]
enum Fail {
Depth,
Names,
Desync,
}
struct Cx<'s, 'de> {
out: &'s mut dyn FieldSink<'de>,
input: &'de [u8],
pos: usize,
fail: Option<Fail>,
mark: SinkMark,
prefix: usize,
names: usize,
budget: usize,
arrays: Arrays,
nulls: Nulls,
quiet: u8,
}
impl<'s, 'de> Cx<'s, 'de> {
fn new(input: &'de [u8], out: &'s mut dyn FieldSink<'de>, how: &Ndjson) -> Self {
let mark = out.mark();
Self {
out,
input,
pos: 0,
fail: None,
mark,
prefix: 0,
names: 0,
budget: NAME_FLOOR.max(input.len().saturating_mul(NAME_FACTOR)),
arrays: how.arrays,
nulls: how.nulls,
quiet: 0,
}
}
fn write<E: Error>(&mut self, key: &str, value: FieldValue<'de>) -> Result<(), E> {
if self.quiet > 0 {
return Ok(());
}
self.names += self.prefix + key.len();
if self.names > self.budget {
return Err(self.stop(Fail::Names));
}
self.out.field(key, value);
Ok(())
}
fn peek(&mut self) -> Option<u8> {
while matches!(self.input.get(self.pos), Some(b' ' | b'\t' | b'\n' | b'\r')) {
self.pos += 1;
}
self.input.get(self.pos).copied()
}
fn eat(&mut self, byte: u8) -> bool {
let found = self.peek() == Some(byte);
self.pos += usize::from(found);
found
}
fn escaped(&mut self) -> bool {
if self.peek() != Some(b'"') {
return false;
}
let mut i = self.pos + 1;
loop {
let Some(j) = self
.input
.get(i..)
.and_then(|rest| memchr2(b'"', b'\\', rest))
else {
return false;
};
if self.input[i + j] == b'"' {
self.pos = i + j + 1;
return true;
}
i += j + 2;
}
}
fn borrowed(&mut self, s: &str) -> bool {
if self.peek() != Some(b'"') {
return false;
}
let start = self.pos + 1;
let end = start + s.len();
let fits = self.input.get(end) == Some(&b'"')
&& (s.is_empty() || self.input[start..end].as_ptr() == s.as_ptr());
if fits {
self.pos = end + 1;
}
fits
}
fn number(&mut self) -> Option<(&'de [u8], Hint)> {
let start = self.pos;
let mut hint = Hint::Int;
loop {
match self.input.get(self.pos) {
Some(b'0'..=b'9' | b'+' | b'-') => {}
Some(b'.' | b'e' | b'E') => hint = Hint::Float,
Some(b' ' | b'\t' | b'\n' | b'\r' | b',' | b']' | b'}') | None => break,
Some(_) => return None,
}
self.pos += 1;
}
Some((&self.input[start..self.pos], hint))
}
fn literal(&mut self, text: &[u8]) -> Option<&'de [u8]> {
self.peek();
let found = self.input.get(self.pos..self.pos + text.len())?;
(found == text).then(|| {
self.pos += text.len();
found
})
}
#[cold]
fn stop<E: Error>(&mut self, why: Fail) -> E {
self.fail.get_or_insert(why);
E::custom("the record can't be read as fields")
}
fn finish(mut self, walked: Result<(), usize>) -> Result<(), ParseError> {
let offset = match (self.fail, walked) {
(Some(limit @ (Fail::Depth | Fail::Names)), _) => {
self.out.rollback(self.mark);
return Err(ParseError::Limit {
what: match limit {
Fail::Depth => "JSON nested deeper than 64 levels",
_ => "JSON field names longer in total than the record allows",
},
});
}
(None, Ok(())) if self.peek().is_none() => return Ok(()),
(None, Err(offset)) => offset,
(Some(Fail::Desync), _) | (None, Ok(())) => self.pos,
};
self.out.rollback(self.mark);
Err(ParseError::Malformed {
offset: offset.min(self.input.len()),
reason: "JSON that doesn't parse",
})
}
}
fn nested<'s, 'de, R>(
cx: &mut Cx<'s, 'de>,
key: &str,
body: impl FnOnce(&mut Cx<'s, 'de>) -> R,
) -> R {
if cx.quiet > 0 {
return body(cx);
}
cx.out.push_prefix(key);
cx.out.push_prefix(".");
cx.prefix += key.len() + 1;
let result = body(cx);
cx.prefix -= key.len() + 1;
cx.out.pop_prefix();
cx.out.pop_prefix();
result
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Lead {
Top,
Colon,
Element,
}
struct Val<'c, 's, 'de> {
cx: &'c mut Cx<'s, 'de>,
key: &'c str,
lead: Lead,
depth: u8,
}
impl<'de> DeserializeSeed<'de> for Val<'_, '_, 'de> {
type Value = ();
fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<(), D::Error> {
match self.lead {
Lead::Top => {}
Lead::Colon => {
if !self.cx.eat(b':') {
return Err(self.cx.stop(Fail::Desync));
}
}
Lead::Element => {
self.cx.eat(b',');
}
}
if !matches!(self.cx.peek(), Some(b'-' | b'0'..=b'9')) {
return d.deserialize_any(self);
}
IgnoredAny::deserialize(d)?;
let Some((text, hint)) = self.cx.number() else {
return Err(self.cx.stop(Fail::Desync));
};
self.cx.write(self.key, FieldValue::borrowed(text, hint))
}
}
impl<'s, 'de> Visitor<'de> for Val<'_, 's, 'de> {
type Value = ();
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a JSON value")
}
fn visit_borrowed_str<E: Error>(self, s: &'de str) -> Result<(), E> {
if !self.cx.borrowed(s) {
return Err(self.cx.stop(Fail::Desync));
}
let value = FieldValue::borrowed(s.as_bytes(), Hint::Text);
self.cx.write(self.key, value)
}
fn visit_str<E: Error>(self, s: &str) -> Result<(), E> {
if !self.cx.escaped() {
return Err(self.cx.stop(Fail::Desync));
}
let value = FieldValue::owned(s.as_bytes().to_vec(), Hint::Text);
self.cx.write(self.key, value)
}
fn visit_bool<E: Error>(self, v: bool) -> Result<(), E> {
let text: &[u8] = if v { b"true" } else { b"false" };
let Some(found) = self.cx.literal(text) else {
return Err(self.cx.stop(Fail::Desync));
};
self.cx
.write(self.key, FieldValue::borrowed(found, Hint::Bool))
}
fn visit_unit<E: Error>(self) -> Result<(), E> {
match self.cx.literal(b"null") {
Some(found) if self.cx.nulls == Nulls::Keep => self
.cx
.write(self.key, FieldValue::borrowed(found, Hint::Json)),
Some(_) => Ok(()),
None => Err(self.cx.stop(Fail::Desync)),
}
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
let Self {
cx,
key,
lead,
depth,
} = self;
if depth == MAX_DEPTH {
return Err(cx.stop(Fail::Depth));
}
if !cx.eat(b'{') {
return Err(cx.stop(Fail::Desync));
}
let mut entries = |cx: &mut Cx<'s, 'de>| -> Result<(), A::Error> {
while let Some(name) = map.next_key_seed(KeySeed { cx: &mut *cx })? {
let name = key_part(name);
map.next_value_seed(Val {
cx: &mut *cx,
key: &name,
lead: Lead::Colon,
depth: depth + 1,
})?;
}
Ok(())
};
if lead == Lead::Top {
entries(cx)?;
} else {
nested(cx, key, entries)?;
}
if cx.eat(b'}') {
Ok(())
} else {
Err(cx.stop(Fail::Desync))
}
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<(), A::Error> {
let Self { cx, key, depth, .. } = self;
if depth == MAX_DEPTH {
return Err(cx.stop(Fail::Depth));
}
let whole = cx.arrays != Arrays::Each && cx.quiet == 0;
let start = cx.peek().map(|_| cx.pos);
if !cx.eat(b'[') {
return Err(cx.stop(Fail::Desync));
}
cx.quiet += u8::from(whole);
let walked: Result<(), A::Error> = (|| {
while seq
.next_element_seed(Val {
cx: &mut *cx,
key,
lead: Lead::Element,
depth: depth + 1,
})?
.is_some()
{}
Ok(())
})();
cx.quiet -= u8::from(whole);
walked?;
if !cx.eat(b']') {
return Err(cx.stop(Fail::Desync));
}
match start {
Some(start) if whole => {
let text = &cx.input[start..cx.pos];
let value = if cx.arrays == Arrays::JsonCompact {
let Some(compact) = compact(text) else {
return Err(cx.stop(Fail::Desync));
};
FieldValue::owned(compact, Hint::Json)
} else {
FieldValue::borrowed(text, Hint::Json)
};
cx.write(key, value)
}
_ => Ok(()),
}
}
}
fn compact(text: &[u8]) -> Option<Vec<u8>> {
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
let value: serde_json::Value = sonic_rs::from_slice(text).ok()?;
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
let value: serde_json::Value = serde_json::from_slice(text).ok()?;
serde_json::to_vec(&value).ok()
}
struct KeySeed<'c, 's, 'de> {
cx: &'c mut Cx<'s, 'de>,
}
impl<'de> DeserializeSeed<'de> for KeySeed<'_, '_, 'de> {
type Value = Cow<'de, str>;
fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
self.cx.eat(b',');
d.deserialize_str(self)
}
}
impl<'de> Visitor<'de> for KeySeed<'_, '_, 'de> {
type Value = Cow<'de, str>;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("an object key")
}
fn visit_borrowed_str<E: Error>(self, s: &'de str) -> Result<Self::Value, E> {
if self.cx.borrowed(s) {
Ok(Cow::Borrowed(s))
} else {
Err(self.cx.stop(Fail::Desync))
}
}
fn visit_str<E: Error>(self, s: &str) -> Result<Self::Value, E> {
if self.cx.escaped() {
Ok(Cow::Owned(s.to_owned()))
} else {
Err(self.cx.stop(Fail::Desync))
}
}
}
const fn root<'c, 's, 'de>(cx: &'c mut Cx<'s, 'de>) -> Val<'c, 's, 'de> {
Val {
cx,
key: "",
lead: Lead::Top,
depth: 0,
}
}
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
fn parse_sonic<'a>(
record: &'a [u8],
out: &mut dyn FieldSink<'a>,
how: &Ndjson,
) -> Result<(), ParseError> {
let mut cx = Cx::new(record, out, how);
let mut de = sonic_rs::Deserializer::from_slice(record);
let walked = root(&mut cx)
.deserialize(&mut de)
.and_then(|()| de.end())
.map_err(|e| e.offset());
cx.finish(walked)
}
#[cfg(any(test, not(any(target_arch = "x86_64", target_arch = "aarch64"))))]
fn parse_serde<'a>(
record: &'a [u8],
out: &mut dyn FieldSink<'a>,
how: &Ndjson,
) -> Result<(), ParseError> {
let mut cx = Cx::new(record, out, how);
let mut de = serde_json::Deserializer::from_slice(record);
let walked = root(&mut cx)
.deserialize(&mut de)
.and_then(|()| de.end())
.map_err(|e| {
let line_start = match e.line() {
0 | 1 => 0,
n => memchr::memchr_iter(b'\n', record)
.nth(n - 2)
.map_or(0, |i| i + 1),
};
line_start + e.column().saturating_sub(1)
});
cx.finish(walked)
}
impl Parser for Ndjson {
fn name(&self) -> &'static str {
"ndjson"
}
fn tier(&self) -> MatcherTier {
MatcherTier::Field
}
fn signature(&self) -> &Signature {
&self.signature
}
fn parse<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<Parsed, ParseError> {
let opens = input.get(1..).and_then(|rest| {
rest.iter()
.find(|b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r'))
});
if input.first() != Some(&b'{') || !matches!(opens, Some(b'"' | b'}')) {
return Ok(Parsed::NoMatch);
}
let record = input;
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
parse_sonic(record, out, self)?;
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
parse_serde(record, out, self)?;
Ok(Parsed::Done)
}
}
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use super::*;
use crate::parse::Fields;
fn parse(line: &str) -> (Result<Parsed, ParseError>, Fields<'_>) {
let mut out = Fields::new();
let p = Ndjson::new().parse(line.as_bytes(), &mut out);
(p, out)
}
fn text<'f>(out: &'f Fields<'_>, name: &str) -> &'f [u8] {
&out.get(name).unwrap().bytes
}
#[test]
fn nested_objects_arrays_and_scalars() {
let line = r#"{"host":{"name":"web01","ip":["10.0.0.1","fe80::1"]},"level":"info","n":1.0,"ok":true,"gone":null,"msg":"a \"quoted\" word"}"#;
let (p, out) = parse(line);
assert!(matches!(p, Ok(Parsed::Done)));
assert_eq!(text(&out, "host.name"), b"web01");
assert_eq!(out.get_all("host.ip").count(), 2);
assert_eq!(text(&out, "n"), b"1.0", "a number keeps its spelling");
assert_eq!(out.get("n").unwrap().hint, Hint::Float);
assert_eq!(out.get("ok").unwrap().hint, Hint::Bool);
assert!(out.get("gone").is_none(), "null writes nothing");
assert_eq!(text(&out, "msg"), br#"a "quoted" word"#);
assert!(matches!(out.get("msg").unwrap().bytes, Cow::Owned(_)));
assert!(matches!(out.get("level").unwrap().bytes, Cow::Borrowed(_)));
}
#[test]
fn broken_or_non_object_records() {
assert!(matches!(parse("[1,2]").0, Ok(Parsed::NoMatch)));
assert!(matches!(
parse(r#"{"a":"#).0,
Err(ParseError::Malformed { .. })
));
let (p, out) = parse("{}\n");
assert!(matches!(p, Ok(Parsed::Done)));
assert!(out.is_empty());
assert!(matches!(parse("{\"a\":1} \t\r\n").0, Ok(Parsed::Done)));
for braces in ["{Key=value, Other=1}", "{", "{ x"] {
assert!(matches!(parse(braces).0, Ok(Parsed::NoMatch)), "{braces}");
}
assert!(
matches!(parse("{\"a\":1}\x0c").0, Err(ParseError::Malformed { .. })),
"a form feed isn't JSON whitespace"
);
}
#[test]
fn the_names_a_record_writes_are_bounded() {
let long = "k".repeat(32 * 1024);
let greedy = format!("{{\"{long}\":[{}1]}}", "1,".repeat(16 * 1024));
let path = "p".repeat(100);
let plain = format!("{{\"{path}\":[{}1]}}", "1,".repeat(1000));
for (name, backend) in backends() {
let mut out = Fields::new();
let got = backend(greedy.as_bytes(), &mut out);
assert!(
matches!(got, Err(ParseError::Limit { .. })),
"{name}: {got:?}"
);
assert!(out.is_empty(), "{name}");
let mut out = Fields::new();
let got = backend(plain.as_bytes(), &mut out);
assert!(got.is_ok(), "{name}: {got:?}");
assert_eq!(out.len(), 1001, "{name}");
}
}
#[test]
fn a_number_reads_the_same_from_each_backend() {
use crate::parse::Number;
let record = br#"{"a":-0,"b":1E+5,"c":18446744073709551615,"d":18446744073709551617,"e":1e309,"f":0.1,"g":-9223372036854775808,"s":"42","z":-0.0,"u":-1e-9999}"#;
let want = [
("a", Some(Number::Int(0))),
("b", Some(Number::Float(1e5))),
("c", Some(Number::UInt(u64::MAX))),
("d", None),
("e", None),
("f", Some(Number::Float(0.1))),
("g", Some(Number::Int(i64::MIN))),
("s", None),
("z", Some(Number::Float(-0.0))),
("u", Some(Number::Float(-0.0))),
];
for (name, backend) in backends() {
let mut out = Fields::new();
backend(record, &mut out).unwrap();
for (field, number) in &want {
let got = format!("{:?}", out.get(field).unwrap().number());
assert_eq!(got, format!("{number:?}"), "{name} {field}");
}
}
}
type Backend = for<'a, 'o> fn(&'a [u8], &'o mut dyn FieldSink<'a>) -> Result<(), ParseError>;
fn production<'a>(record: &'a [u8], out: &mut dyn FieldSink<'a>) -> Result<(), ParseError> {
match Ndjson::new().parse(record, out)? {
Parsed::NoMatch => Err(ParseError::Malformed {
offset: 0,
reason: "not a JSON object",
}),
_ => Ok(()),
}
}
fn serde_json<'a>(record: &'a [u8], out: &mut dyn FieldSink<'a>) -> Result<(), ParseError> {
parse_serde(record, out, &Ndjson::new())
}
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
fn sonic<'a>(record: &'a [u8], out: &mut dyn FieldSink<'a>) -> Result<(), ParseError> {
parse_sonic(record, out, &Ndjson::new())
}
fn backends() -> Vec<(&'static str, Backend)> {
let mut all: Vec<(&'static str, Backend)> = vec![("serde_json", serde_json)];
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
all.push(("sonic-rs", sonic));
all.push(("parser", production));
all
}
#[test]
fn arrays_as_json_text_and_nulls_kept() {
let how = Ndjson::new().arrays(Arrays::Json).nulls(Nulls::Keep);
let cases: &[(&str, &[(&str, &str, Hint)])] = &[
(
r#"{"a":[1,2],"n":null,"o":{}}"#,
&[("a", "[1,2]", Hint::Json), ("n", "null", Hint::Json)],
),
(
r#"{"h":{"ip":[ "10.0.0.1" , {"x":[null]} ],"z":null},"t":"x"}"#,
&[
("h.ip", r#"[ "10.0.0.1" , {"x":[null]} ]"#, Hint::Json),
("h.z", "null", Hint::Json),
("t", "x", Hint::Text),
],
),
(
r#"{"e":[],"s":"[1]"}"#,
&[("e", "[]", Hint::Json), ("s", "[1]", Hint::Text)],
),
(
"{\"q\":[\"\\\"]\\\\\",\"1.50\"]}",
&[("q", "[\"\\\"]\\\\\",\"1.50\"]", Hint::Json)],
),
];
for &(record, want) in cases {
let mut readers: Vec<(&str, Fields<'_>, Result<(), ParseError>)> = Vec::new();
let mut out = Fields::new();
let got = parse_serde(record.as_bytes(), &mut out, &how);
readers.push(("serde_json", out, got));
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
{
let mut out = Fields::new();
let got = parse_sonic(record.as_bytes(), &mut out, &how);
readers.push(("sonic-rs", out, got));
}
let mut out = Fields::new();
let got = how.parse(record.as_bytes(), &mut out).map(|_| ());
readers.push(("parser", out, got));
for (name, out, got) in readers {
assert!(got.is_ok(), "{name} {record}: {got:?}");
let rows: Vec<(&str, &[u8], Hint)> = out
.as_slice()
.iter()
.map(|(k, v)| (k.as_str(), v.bytes.as_ref(), v.hint))
.collect();
let want: Vec<(&str, &[u8], Hint)> =
want.iter().map(|&(k, v, h)| (k, v.as_bytes(), h)).collect();
assert_eq!(rows, want, "{name} {record}");
}
}
let compact = Ndjson::new().arrays(Arrays::JsonCompact);
for (record, want) in [
(
r#"{"a":[1, 2.50, 1E+3,"\/\u00e9"]}"#,
"[1,2.5,1000.0,\"/\u{e9}\"]",
),
(r#"{"a":[ {"z":1, "b":[ ]} ],"t":1}"#, r#"[{"b":[],"z":1}]"#),
(
r#"{"a":[18446744073709551616]}"#,
"[1.8446744073709552e+19]",
),
] {
let mut out = Fields::new();
assert!(
compact.parse(record.as_bytes(), &mut out).is_ok(),
"{record}"
);
let row = out.get("a").unwrap();
let theirs: serde_json::Value =
serde_json::from_str::<serde_json::Value>(record).unwrap()["a"].clone();
assert_eq!(
row.bytes.as_ref(),
serde_json::to_string(&theirs).unwrap().as_bytes(),
"{record}"
);
assert_eq!(
(row.bytes.as_ref(), row.hint),
(want.as_bytes(), Hint::Json),
"{record}"
);
}
let deep = format!(r#"{{"a":{}{}}}"#, "[".repeat(70), "]".repeat(70));
let mut out = Fields::new();
assert!(matches!(
how.parse(deep.as_bytes(), &mut out),
Err(ParseError::Limit { .. })
));
assert!(out.is_empty());
}
fn two_pass<'a>(
record: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<(), serde_json::Error> {
let Entries(entries) = serde_json::from_slice(record)?;
for (k, v) in entries {
walk(&k.0, v, out)?;
}
Ok(())
}
type Row = (String, Vec<u8>, bool, Hint);
fn rows(out: &Fields<'_>) -> Vec<Row> {
out.as_slice()
.iter()
.map(|(name, v)| {
let borrowed = matches!(v.bytes, Cow::Borrowed(_));
(name.clone(), v.bytes.to_vec(), borrowed, v.hint)
})
.collect()
}
fn reference(record: &[u8]) -> Option<Vec<Row>> {
let mut out = Fields::new();
two_pass(record, &mut out).ok().map(|()| rows(&out))
}
fn assert_matches_reference(record: &[u8]) {
let want = reference(record);
for (name, backend) in backends() {
let mut out = Fields::new();
let got = backend(record, &mut out).ok().map(|()| rows(&out));
assert_eq!(got, want, "{name} on {}", String::from_utf8_lossy(record));
}
}
const VALID: &[&str] = &[
r"{}",
r#"{"a":[{},[],1]}"#,
r#"{"a":["123",456]}"#,
r#"{"a":["true","false","null",null,1,true,false]}"#,
r#"{"a":{},"a":2}"#,
r#"{"a1":-0,"b":1E+5}"#,
r#"{"a":"ends with a backslash\\","b":42}"#,
r#"{"a":"escaped quote: \"123\"","b":456}"#,
r#"{"a":"","b":0,"":1}"#,
r#"{"n":1e309,"m":-1e309,"k":1e999999}"#,
r#"{"n":18446744073709551617,"u":1e-9999,"d":0.12345678901234567890123456789}"#,
r#"{"n":1.50,"m":1.0,"z":-0.0}"#,
r#"{ "a" : [ 1 , 2 ] , "b" : { "c" : null } }"#,
r#"{"s":"\ud83d\ude00 \u00e9 \t\/"}"#,
"{\"s\":\"\u{1F600} \u{e9}\",\"\u{e9}\":1}",
r#"{"a\"b":{"c\\":1},"A":[true]}"#,
r#"{"a":{"b":{"c":[{"d":1},{"d":"x"}]}}}"#,
"{\"a\":1,\r\n\t\"b\":[\n1\n]}",
];
#[test]
fn every_backend_writes_what_the_reference_writes() {
for record in VALID {
assert!(reference(record.as_bytes()).is_some(), "{record}");
assert_matches_reference(record.as_bytes());
}
}
const MALFORMED: &[&[u8]] = &[
br#"{"a":1,}"#,
br#"{"a":[1,]}"#,
br#"{"a":01}"#,
br#"{"a":NaN}"#,
br#"{"a":1} {}"#,
br#"{"a":"\uD800"}"#,
br#"{"a":1,"b":{"c":2,"d":}}"#,
br#"{"a":1.}"#,
br#"{"a":-}"#,
br#"{"a":1+2}"#,
br#"{"a":1e}"#,
br#"{"a":.5}"#,
br#"{"a":--1}"#,
br#"{"a":1 2}"#,
br#"{"a" 1}"#,
br#"{"a":tru}"#,
br#"{"a":nul}"#,
br"{a:1}",
br#"{"a":"x}"#,
br#"{"a":[1,2}"#,
br#"{"a":{"b":1]}"#,
br#"{"a":1"#,
br"{",
br#"{"a":1}}"#,
br#"{"a":1}x"#,
b"{\"a\":\"line\nbreak\"}",
br#"{"a":"bad \x escape"}"#,
br#"{"a":1,"a"}"#,
b"{\"a\":\"\xff\"}",
b"{\"\xc3\":1}",
br#"{"k":{"deep":[1,{"x":"y"},2,]}}"#,
];
#[test]
fn a_malformed_record_leaves_the_sink_as_it_was() {
for record in MALFORMED {
let shown = String::from_utf8_lossy(record);
assert!(reference(record).is_none(), "the reference took {shown}");
for (name, backend) in backends() {
let mut out = Fields::new();
out.field("kept", FieldValue::borrowed(b"1", Hint::Int));
out.push_prefix("outer.");
let before = rows(&out);
match backend(record, &mut out) {
Err(ParseError::Malformed { offset, .. }) => {
assert!(offset <= record.len(), "{name} on {shown}");
}
other => panic!("{name} on {shown}: {other:?}"),
}
assert_eq!(rows(&out), before, "{name} on {shown}");
out.field("x", FieldValue::borrowed(b"2", Hint::Int));
let last = out.as_slice().last().map(|(n, _)| n.as_str());
assert_eq!(last, Some("outer.x"), "{name} on {shown}");
}
}
}
const WORKER_STACK: usize = 2 * 1024 * 1024;
fn on_worker_stack(f: impl FnOnce() + Send + 'static) {
std::thread::Builder::new()
.stack_size(WORKER_STACK)
.spawn(f)
.unwrap()
.join()
.unwrap();
}
fn nest(levels: usize, arrays: bool) -> Vec<u8> {
let (open, close) = if arrays {
("[", "]")
} else {
(r#"{"a":"#, "}")
};
let mut text = String::from(r#"{"a":"#);
text.push_str(&open.repeat(levels - 1));
text.push('1');
text.push_str(&close.repeat(levels - 1));
text.push('}');
text.into_bytes()
}
#[test]
fn nesting_past_the_bound_is_a_limit() {
on_worker_stack(|| {
for arrays in [false, true] {
for levels in [1, 2, 63, 64] {
let record = nest(levels, arrays);
for (name, backend) in backends() {
let mut out = Fields::new();
let got = backend(&record, &mut out);
assert!(got.is_ok(), "{name} at {levels}: {got:?}");
assert_eq!(out.len(), 1, "{name} at {levels}");
}
}
for levels in [65, 127, 128, 129, 300, 100_000] {
let record = nest(levels, arrays);
for (name, backend) in backends() {
let mut out = Fields::new();
let got = backend(&record, &mut out);
assert!(
matches!(got, Err(ParseError::Limit { .. })),
"{name} at {levels}: {got:?}"
);
assert!(out.is_empty(), "{name} at {levels}");
}
}
}
});
}
#[test]
fn long_numbers_keep_their_text_at_any_offset() {
let mut numbers: Vec<String> = Vec::new();
for digits in [1, 15, 16, 17, 31, 32, 33, 63, 64, 65] {
let run = "7".repeat(digits);
numbers.push(run.clone());
numbers.push(format!("-{run}"));
numbers.push(format!("{run}.{run}"));
numbers.push(format!("{run}e+{digits}"));
numbers.push(format!("-{run}.5E-{run}"));
}
for pad in [0, 1, 7, 15, 16, 17, 31, 32, 33] {
let pad = "x".repeat(pad);
for n in &numbers {
let record =
format!(r#"{{"p":"{pad}","n":{n},"l":[{n},{n} ,{n}],"o":{{"n":{n}}}}}"#);
let want = reference(record.as_bytes());
assert!(want.is_some(), "{record}");
assert_matches_reference(record.as_bytes());
}
}
}
#[test]
fn a_large_record_that_fails_late_writes_nothing() {
let mut record = String::from(r#"{"a":["#);
record.push_str(&"1,".repeat(200_000));
for (name, backend) in backends() {
let mut out = Fields::new();
let got = backend(record.as_bytes(), &mut out);
assert!(matches!(got, Err(ParseError::Malformed { .. })), "{name}");
assert!(out.is_empty(), "{name}");
}
}
#[test]
fn one_parser_serves_many_threads() {
const fn shared<T: Send + Sync>(_: &T) {}
let parser = Ndjson::new();
shared(&parser);
std::thread::scope(|scope| {
for _ in 0..4 {
scope.spawn(|| {
for record in VALID {
let mut out = Fields::new();
let got = parser.parse(record.as_bytes(), &mut out);
assert!(matches!(got, Ok(Parsed::Done)), "{record}");
assert_eq!(Some(rows(&out)), reference(record.as_bytes()));
}
});
}
});
}
#[test]
#[ignore = "needs GRIPPO_LINES, a local file of real log lines"]
fn real_lines_match_the_reference() {
let path = std::env::var_os("GRIPPO_LINES").unwrap();
let text = std::fs::read_to_string(path).unwrap();
let (mut objects, mut valid) = (0_usize, 0_usize);
for record in text.lines() {
let Ok(record) = serde_json::from_str::<serde_json::Value>(record) else {
continue;
};
let Some(line) = record.get("line").and_then(serde_json::Value::as_str) else {
continue;
};
let line = line.trim_end();
let object = if line.starts_with('{') {
Some(line)
} else {
line.find(" {").map(|at| &line[at + 1..])
};
let Some(object) = object else {
continue;
};
objects += 1;
valid += usize::from(reference(object.as_bytes()).is_some());
assert_matches_reference(object.as_bytes());
}
println!("{objects} JSON candidates, {valid} of them valid JSON objects");
assert!(valid > 0);
}
mod generated {
use proptest::prelude::*;
use super::{assert_matches_reference, backends, reference, rows};
use crate::parse::Fields;
fn scalar() -> impl Strategy<Value = String> {
prop_oneof![
Just("null".to_owned()),
Just("true".to_owned()),
Just("false".to_owned()),
r"-?(0|[1-9][0-9]{0,40})(\.[0-9]{1,40})?([eE][+-]?[0-9]{1,5})?",
string(),
]
}
fn string() -> impl Strategy<Value = String> {
r#""([a-z0-9 :,{}\[\]\u{e9}]|\\["\\/bfnrt]|\\u00[2-7][0-9a-f]){0,40}""#
}
fn value() -> impl Strategy<Value = String> {
scalar().prop_recursive(4, 48, 6, |inner| {
prop_oneof![
(prop::collection::vec(inner.clone(), 0..6), "[ \t\r\n]{0,2}").prop_map(
|(items, ws)| format!("[{ws}{}{ws}]", items.join(&format!("{ws},")))
),
object(inner),
]
})
}
fn object(inner: impl Strategy<Value = String>) -> impl Strategy<Value = String> {
(
prop::collection::vec((string(), inner), 0..6),
"[ \t\r\n]{0,2}",
)
.prop_map(|(entries, ws)| {
let entries: Vec<String> = entries
.into_iter()
.map(|(k, v)| format!("{k}{ws}:{ws}{v}"))
.collect();
format!("{{{ws}{}{ws}}}", entries.join(&format!(",{ws}")))
})
}
proptest! {
#[test]
fn valid_records_match_the_reference(record in object(value())) {
prop_assert!(reference(record.as_bytes()).is_some(), "{}", record);
assert_matches_reference(record.as_bytes());
}
#[test]
fn damaged_records_match_the_reference(
record in object(value()),
at in any::<prop::sample::Index>(),
byte in prop::sample::select(br#""\{}[],:019eE.+- xu"#.to_vec()),
drop in any::<bool>(),
) {
let mut damaged = record.into_bytes();
let at = at.index(damaged.len());
if drop {
damaged.remove(at);
} else {
damaged[at] = byte;
}
prop_assume!(damaged.first() == Some(&b'{'));
let want = reference(&damaged);
for (name, backend) in backends() {
let mut out = Fields::new();
let got = backend(&damaged, &mut out).ok().map(|()| rows(&out));
prop_assert_eq!(
&got,
&want,
"{} on {}",
name,
String::from_utf8_lossy(&damaged)
);
}
}
}
}
}