use std::fmt::Write as _;
use std::sync::Arc;
use proptest::prelude::*;
use super::*;
use crate::parse::{FieldSink, ParseConfig, ParsePlan, Parsed, Parser, Parsers};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;
#[derive(Debug, PartialEq, Eq)]
struct Got {
records: Vec<Vec<u8>>,
errors: Vec<String>,
}
fn kind(e: &ParseError) -> String {
match e {
ParseError::FrameTooLong { len, .. } => format!("too long {len}"),
ParseError::Malformed { .. } => "malformed".to_owned(),
other => format!("{other}"),
}
}
fn run(c: &FramingConfig, inputs: &[&[u8]]) -> Got {
let (mut state, now) = (FrameState::default(), Instant::now());
let (mut out, mut errors) = (Vec::new(), Vec::new());
for input in inputs {
if let Err(e) = c.frame(input, &mut state, now, None, &mut out) {
errors.push(kind(&e));
}
}
let mut held = Vec::new();
c.flush(&mut state, None, &mut held);
let records = out.iter().chain(&held).map(|f| f.bytes.to_vec()).collect();
Got { records, errors }
}
fn conf(split: StreamSplit, max_bytes: usize) -> StreamConfig {
StreamConfig {
split,
max_bytes,
..StreamConfig::default()
}
}
fn conf_keep(split: StreamSplit, max_bytes: usize) -> StreamConfig {
StreamConfig {
carriage_returns: CarriageReturns::Keep,
..conf(split, max_bytes)
}
}
fn conf_cap(split: StreamSplit, max_bytes: usize, max_frame_bytes: usize) -> StreamConfig {
StreamConfig {
max_frame_bytes,
..conf(split, max_bytes)
}
}
fn stream(split: StreamSplit, max_bytes: usize) -> FramingConfig {
FramingConfig::Stream(conf(split, max_bytes))
}
fn container(format: ContainerFormat, max_bytes: usize) -> FramingConfig {
FramingConfig::Container(ContainerConfig {
format,
max_bytes,
..ContainerConfig::default()
})
}
fn pointer(text: &str) -> FramingConfig {
FramingConfig::JsonPointer(JsonPointerConfig {
pointer: text.parse().unwrap(),
})
}
type Case<'c> = (
&'c str,
FramingConfig,
&'c [&'c [u8]],
&'c [&'c [u8]],
&'c [&'c str],
);
fn check(cases: &[Case<'_>]) {
for (name, c, inputs, records, errors) in cases {
let got = run(c, inputs);
let want = Got {
records: records.iter().map(|r| r.to_vec()).collect(),
errors: errors.iter().map(|&e| e.to_owned()).collect(),
};
assert_eq!(got, want, "{name}");
}
}
#[test]
fn a_stream_splits_as_its_spec_says() {
use StreamSplit::{Lf, Nul, OctetCounted};
const MB: usize = 1 << 20;
check(&[
(
"lf: CR LF, an empty line and a last line with no LF",
stream(Lf, MB),
&[b"a\nb\r\n\r\n\nc"],
&[b"a", b"b", b"c"],
&[],
),
(
"lf: a line cut across feeds",
stream(Lf, MB),
&[b"ab", b"c\r", b"\nd\n"],
&[b"abc", b"d"],
&[],
),
(
"lf: a NUL inside an LF line stays in it",
stream(Lf, MB),
&[b"a\0b\nc\n"],
&[b"a\0b", b"c"],
&[],
),
(
"lf: a line over the cap is skipped",
stream(Lf, 4),
&[b"abcdef\nok\n"],
&[b"ok"],
&["too long 7"],
),
(
"lf: a line over the cap across feeds is reported once it passes the cap, then passed to its LF",
stream(Lf, 4),
&[b"abc", b"def", b"gh\nok\n"],
&[b"ok"],
&["too long 6"],
),
(
"octet: counted frames mixed with an LF line",
stream(OctetCounted, MB),
&[b"5 <1>ab6 <2>c d<3>lf line\n"],
&[b"<1>ab", b"<2>c d", b"<3>lf line"],
&[],
),
(
"octet: the docs example, a frame cut across reads",
stream(OctetCounted, MB),
&[b"15 <13>hello w", b"orld<14>bye\n"],
&[b"<13>hello world", b"<14>bye"],
&[],
),
(
"octet: a counted frame holds an LF",
stream(OctetCounted, MB),
&[b"7 <1>a\nb\n<2>c\n"],
&[b"<1>a\nb\n", b"<2>c"],
&[],
),
(
"octet: a count cut across feeds",
stream(OctetCounted, MB),
&[b"1", b"0 ", b"<1>abcdef", b"g3 <2>"],
&[b"<1>abcdefg", b"<2>"],
&[],
),
(
"octet: what isn't a count is an LF line",
stream(OctetCounted, MB),
&[b"12x<1>a\n0 <1>b\n5 c\n2026-11-30 d\n"],
&[b"12x<1>a", b"0 <1>b", b"5 c", b"2026-11-30 d"],
&[],
),
(
"octet: a count past the cap is skipped whole",
stream(OctetCounted, 8),
&[b"20 <1>aaaaaaaaaaaaaaaaa5 <2>bb"],
&[b"<2>bb"],
&["too long 23"],
),
(
"octet: a count past the cap cut across feeds",
stream(OctetCounted, 8),
&[b"2", b"0 <1>aaaa", b"aaaaaaaaaaaaa5 <2>bb"],
&[b"<2>bb"],
&["too long 23"],
),
(
"octet: a count no integer holds is an LF line",
stream(OctetCounted, MB),
&[b"99999999999999999999 <1>a\n"],
&[b"99999999999999999999 <1>a"],
&[],
),
(
"octet: a frame the stream ends inside is dropped",
stream(OctetCounted, MB),
&[b"9 <1>ab"],
&[],
&[],
),
(
"nul: an LF inside a frame, an empty frame and a last frame",
stream(Nul, MB),
&[b"{\"a\":1}\0\0{\"b\":\n2}\0", b"ta", b"il"],
&[b"{\"a\":1}", b"{\"b\":\n2}", b"tail"],
&[],
),
(
"nul: a CR stays in the frame",
stream(Nul, MB),
&[b"a\r\0"],
&[b"a\r"],
&[],
),
(
"nul: a frame over the cap",
stream(Nul, 3),
&[b"abcd\0ef\0"],
&[b"ef"],
&["too long 5"],
),
]);
}
#[test]
fn a_stream_trims_strips_and_trusts_counts_as_its_spec_says() {
use StreamSplit::{Lf, Nul, OctetCounted};
const MB: usize = 1 << 20;
check(&[
(
"nul: a last frame loses its whitespace",
stream(Nul, MB),
&[b"a\0 b \r"],
&[b"a", b"b"],
&[],
),
(
"lf: every CR before the LF is dropped, and a line of only CRs is no record",
stream(Lf, MB),
&[b"a\r\r\n\r\r\n\r\nb\r\n"],
&[b"a", b"b"],
&[],
),
(
"lf keep: CRs stay and a line of only CRs is a record",
FramingConfig::Stream(conf_keep(Lf, MB)),
&[b"a\r\r\n\r\r\n\r\n\nb\r\n"],
&[b"a\r\r", b"\r\r", b"\r", b"b\r"],
&[],
),
(
"lf: a last line loses its whitespace, and is no record when none is left",
stream(Lf, MB),
&[b"a\n b \t", b"\n \r \t", b"\n x ", b" \r"],
&[b"a", b" b \t", b" \r \t", b"x"],
&[],
),
(
"lf: a last line of whitespace is no record",
stream(Lf, MB),
&[b"a\n \r "],
&[b"a"],
&[],
),
(
"lf: a mix of CR LF, blank lines and a last line",
stream(Lf, MB),
&[b"a\r\n\r\n\nb\r\r\n c \nlast"],
&[b"a", b"b", b" c ", b"last"],
&[],
),
(
"octet: LF lines among counted frames, a blank line and a CR LF",
stream(OctetCounted, MB),
&[b"4 <1>a5 <2>bc\n6 <3>def<4>lf line\r\n"],
&[b"<1>a", b"<2>bc", b"<3>def", b"<4>lf line"],
&[],
),
(
"octet: a leading zero or a count with no `<` is an LF line",
stream(OctetCounted, MB),
&[b"05 <1>ab\n0 \n2026 Oct 11 10:00:00 host msg\n4 <1>a"],
&[
b"05 <1>ab",
b"0 ",
b"2026 Oct 11 10:00:00 host msg",
b"<1>a",
],
&[],
),
(
"octet: the end of input after a count and its space is a last line",
stream(OctetCounted, MB),
&[b"4 "],
&[b"4"],
&[],
),
(
"octet: a last line loses its whitespace on both sides",
stream(OctetCounted, MB),
&[b"<1>a \n x "],
&[b"<1>a ", b"x"],
&[],
),
(
"octet: whitespace after the last counted frame is no record",
stream(OctetCounted, MB),
&[b"4 <1>a \t "],
&[b"<1>a"],
&[],
),
(
"octet: a counted frame the end cuts short is dropped after the lines before it",
stream(OctetCounted, MB),
&[b"<1>a\n10 <short"],
&[b"<1>a"],
&[],
),
(
"octet keep: CRs stay in LF lines and a last line still loses its whitespace",
FramingConfig::Stream(conf_keep(OctetCounted, MB)),
&[b"<1>a\r\n\r\n\n4 <2>b<3>c\r\r\n <4>d\r"],
&[b"<1>a\r", b"\r", b"<2>b", b"<3>c\r\r", b"<4>d"],
&[],
),
(
"octet strip: CRs go from LF lines",
stream(OctetCounted, MB),
&[b"<1>a\r\n\r\n\n4 <2>b<3>c\r\r\n <4>d\r"],
&[b"<1>a", b"<2>b", b"<3>c", b"<4>d"],
&[],
),
(
"octet: a count over max_frame_bytes reads as an LF line, and counting resumes after it",
FramingConfig::Stream(conf_cap(OctetCounted, 8, 16)),
&[b"20 <1>aaaaaaaaaaaaaaaaa\n5 <2>bb"],
&[b"<2>bb"],
&["too long 24"],
),
(
"octet: a count over max_frame_bytes, small, is a line",
FramingConfig::Stream(conf_cap(OctetCounted, 16, 16)),
&[b"17 <1>a\nok\n"],
&[b"17 <1>a", b"ok"],
&[],
),
(
"octet: a count of 20 digits does not eat the stream",
stream(OctetCounted, 8),
&[b"99999999999999999999 <1>a\nok\n"],
&[b"ok"],
&["too long 26"],
),
(
"octet: a count of 20 digits cut across feeds does not eat the stream",
stream(OctetCounted, 8),
&[b"9999999999", b"9999999999 <", b"1>a\nok\n"],
&[b"ok"],
&["too long 10"],
),
(
"octet: a count at max_frame_bytes is skipped whole",
FramingConfig::Stream(conf_cap(OctetCounted, 4, 8)),
&[b"8 <1>aaaaa4 <2>b"],
&[b"<2>b"],
&["too long 10"],
),
]);
}
#[test]
fn a_json_stream_splits_as_its_spec_says() {
use StreamSplit::{JsonConcat, JsonSeq};
const MB: usize = 1 << 20;
check(&[
(
"concat: values with and without space between",
stream(JsonConcat, MB),
&[b"{\"a\":1}{\"b\":[1,{\"c\":\"}\"}]} \n 42 \"s\\\"\" true[]"],
&[
b"{\"a\":1}",
b"{\"b\":[1,{\"c\":\"}\"}]}",
b"42",
b"\"s\\\"\"",
b"true",
b"[]",
],
&[],
),
(
"concat: values cut across feeds, an escape included",
stream(JsonConcat, MB),
&[b"{\"a\":\"x\\", b"\"y\"}[1", b",2]1", b"2"],
&[b"{\"a\":\"x\\\"y\"}", b"[1,2]", b"12"],
&[],
),
(
"concat: a byte no value starts with",
stream(JsonConcat, MB),
&[b"{}],{}"],
&[b"{}", b"{}"],
&["malformed"],
),
(
"concat: a value the stream ends inside is dropped",
stream(JsonConcat, MB),
&[b"{\"a\":"],
&[],
&[],
),
(
"concat: a value over the cap, reported once it passes it",
stream(JsonConcat, 8),
&[b"{\"a\":\"0123", b"456789\"}{}"],
&[b"{}"],
&["too long 10"],
),
(
"seq: RS before and LF after, RS doubled",
stream(JsonSeq, MB),
&[b"\x1e{\"a\":1}\n\x1e\x1e[2]\n\x1e3\n"],
&[b"{\"a\":1}", b"[2]", b"3"],
&[],
),
(
"seq: a text an RS cuts short is dropped",
stream(JsonSeq, MB),
&[b"\x1e{\"a\":", b"\x1e{\"b\":2}\n"],
&[b"{\"b\":2}"],
&["malformed"],
),
(
"seq: a number with no whitespace after it is dropped",
stream(JsonSeq, MB),
&[b"\x1e123\x1e{}\n\x1e4", b"5\n"],
&[b"{}", b"45"],
&["malformed"],
),
(
"seq: text before an RS is skipped to it",
stream(JsonSeq, MB),
&[b"x y\x1e{}\n"],
&[b"{}"],
&["malformed"],
),
(
"seq: a number the stream ends on is dropped",
stream(JsonSeq, MB),
&[b"\x1e12"],
&[],
&[],
),
]);
}
#[test]
fn a_json_array_stream_splits_as_its_spec_says() {
use StreamSplit::JsonArray;
const MB: usize = 1 << 20;
check(&[
("array: empty", stream(JsonArray, MB), &[b"[]"], &[], &[]),
(
"array: empty with whitespace around it",
stream(JsonArray, MB),
&[b" [ ] "],
&[],
&[],
),
(
"array: scalars",
stream(JsonArray, MB),
&[b"[1, 2, 3]"],
&[b"1", b"2", b"3"],
&[],
),
(
"array: whitespace and newlines around elements",
stream(JsonArray, MB),
&[b"\n\t [\n {\"a\":1} , {\"b\":2}\n] \n"],
&[b"{\"a\":1}", b"{\"b\":2}"],
&[],
),
(
"array: strings holding delimiters and brackets",
stream(JsonArray, MB),
&[br#"["a,b[c]{d}", "plain"]"#],
&[br#""a,b[c]{d}""#, br#""plain""#],
&[],
),
(
"array: escaped quotes",
stream(JsonArray, MB),
&[br#"["he said \"hi\", then left", 7]"#],
&[br#""he said \"hi\", then left""#, b"7"],
&[],
),
(
"array: a trailing backslash string",
stream(JsonArray, MB),
&[br#"["path\\", 1]"#],
&[br#""path\\""#, b"1"],
&[],
),
(
"array: nested arrays and objects are single elements",
stream(JsonArray, MB),
&[br#"[[1,2],[3],{"k":[4,5]},[{"a":{"b":{"c":[1,{"d":2}]}}}]]"#],
&[
b"[1,2]",
b"[3]",
br#"{"k":[4,5]}"#,
br#"[{"a":{"b":{"c":[1,{"d":2}]}}}]"#,
],
&[],
),
(
"array: elements cut across reads",
stream(JsonArray, MB),
&[b" [{\"a\":", b"1}, [2", b",3] ,", b"4", b"2 ]"],
&[b"{\"a\":1}", b"[2,3]", b"42"],
&[],
),
(
"array: bytes before the bracket are malformed and the rest is dropped",
stream(JsonArray, MB),
&[b"x[1]"],
&[],
&["malformed"],
),
(
"array: bytes after the bracket are malformed",
stream(JsonArray, MB),
&[b"[1] x", b"[2]"],
&[b"1"],
&["malformed"],
),
(
"array: no comma between elements",
stream(JsonArray, MB),
&[b"[1 2]"],
&[b"1", b"2"],
&["malformed"],
),
(
"array: a doubled comma",
stream(JsonArray, MB),
&[b"[1,,2]"],
&[b"1", b"2"],
&["malformed"],
),
(
"array: a leading comma",
stream(JsonArray, MB),
&[b"[,1]"],
&[b"1"],
&["malformed"],
),
(
"array: a trailing comma",
stream(JsonArray, MB),
&[b"[1,]"],
&[b"1"],
&["malformed"],
),
(
"array: an element over the cap is skipped and the rest goes on",
stream(JsonArray, 4),
&[b"[\"abcdef\",1,\"gh", b"ijkl\",2]"],
&[b"1", b"2"],
&["too long 8", "too long 8"],
),
(
"array: a stream that ends before the bracket gives the elements it had",
stream(JsonArray, MB),
&[b"[1,2", b",3"],
&[b"1", b"2"],
&[],
),
]);
}
#[test]
fn a_json_array_element_goes_out_when_it_is_complete() {
let c = stream(StreamSplit::JsonArray, 1 << 20);
let (mut state, now) = (FrameState::default(), Instant::now());
let mut out = Vec::new();
c.frame(b"[{\"a\":1},{\"b\"", &mut state, now, None, &mut out)
.unwrap();
assert_eq!(out.len(), 1);
assert!(matches!(out[0].bytes, Cow::Borrowed(b"{\"a\":1}")));
c.frame(b":2}", &mut state, now, None, &mut out).unwrap();
assert_eq!(out.len(), 2, "the second element ends at its brace");
c.frame(b",3", &mut state, now, None, &mut out).unwrap();
assert_eq!(out.len(), 2, "a number ends at the byte after it");
c.frame(b"]", &mut state, now, None, &mut out).unwrap();
assert_eq!(out.len(), 3);
}
#[test]
fn container_pieces_join_as_their_spec_says() {
use ContainerFormat::{Cri, JsonFile};
const MB: usize = 1 << 20;
check(&[
(
"cri: P pieces join to the F, with the first piece's time",
container(Cri, MB),
&[b"T1 stdout P ab\n", b"T2 stdout P cd\nT3 stdout F ef\n"],
&[b"T1 stdout F abcdef"],
&[],
),
(
"cri: stdout and stderr join apart",
container(Cri, MB),
&[b"T stdout P a\nT stderr F err\nT stdout F b\n"],
&[b"T stderr F err", b"T stdout F ab"],
&[],
),
(
"cri: tags after a colon are dropped from a joined line",
container(Cri, MB),
&[b"T stdout P:x a\n", b"T stdout F:y b"],
&[b"T stdout F ab"],
&[],
),
(
"cri: a whole line goes on as it came, and so does one not in the format",
container(Cri, MB),
&[b"T stdout F x:y z\nnot cri\nT stdin F x\nT stdout Q x\n stdout F x\n"],
&[
b"T stdout F x:y z",
b"not cri",
b"T stdin F x",
b"T stdout Q x",
b" stdout F x",
],
&[],
),
(
"cri: a P line with no F before the stream ends is released as a piece",
container(Cri, MB),
&[b"T stdout P a\n", b"T stdout P b\n"],
&[b"T stdout P ab"],
&[],
),
(
"cri: a line that would pass the cap is released as it stands",
container(Cri, 24),
&[b"T stdout P 0123456789\nT stdout P 0123456789\nT stdout F z\n"],
&[b"T stdout P 0123456789", b"T stdout F 0123456789z"],
&[],
),
(
"cri: a piece longer than the cap is a record alone",
container(Cri, 8),
&[b"T stdout P 0123456789\nT stdout F z\n"],
&[b"T stdout P 0123456789", b"T stdout F z"],
&[],
),
(
"json-file: pieces join in the log string, with the first line's time",
container(JsonFile, MB),
&[
br#"{"log":"ab","stream":"stdout","time":"t1"}"#,
br#"{"log":"cd\n","stream":"stdout","time":"t2"}"#,
],
&[br#"{"log":"abcd\n","stream":"stdout","time":"t1"}"#],
&[],
),
(
"json-file: an escaped backslash before n is no newline",
container(JsonFile, MB),
&[br#"{"log":"a\\n","stream":"stderr"}
{"log":"x\n","stream":"stderr"}"#],
&[br#"{"log":"a\\nx\n","stream":"stderr"}"#],
&[],
),
(
"json-file: streams join apart and a whole line goes on as it came",
container(JsonFile, MB),
&[br#"{"log":"a","stream":"stdout"}
{"log":"e\n","stream":"stderr"}
{"log":"b\n","stream":"stdout"}"#],
&[
br#"{"log":"e\n","stream":"stderr"}"#,
br#"{"log":"ab\n","stream":"stdout"}"#,
],
&[],
),
(
"json-file: a line not in the format goes on whole",
container(JsonFile, MB),
&[br#"not json
{"log":1,"stream":"stdout"}
{"msg":"x"}
{"log":"a","stream":"stdin"}
{"log":"a" "stream":"stdout"}"#],
&[
b"not json",
br#"{"log":1,"stream":"stdout"}"#,
br#"{"msg":"x"}"#,
br#"{"log":"a","stream":"stdin"}"#,
br#"{"log":"a" "stream":"stdout"}"#,
],
&[],
),
(
"json-file: a piece with no last piece is released at the end",
container(JsonFile, MB),
&[br#"{"log":"a","stream":"stdout"}"#],
&[br#"{"log":"a","stream":"stdout"}"#],
&[],
),
]);
}
#[test]
fn a_container_piece_waits_its_timeout_and_no_longer() {
let c = FramingConfig::Container(ContainerConfig {
timeout_ms: 5,
..ContainerConfig::default()
});
let base = Instant::now();
let at = |ms| base + Duration::from_millis(ms);
let mut state = FrameState::default();
let mut out = Vec::new();
c.frame(b"T stdout P a", &mut state, at(0), None, &mut out)
.unwrap();
c.frame(b"T stdout F b", &mut state, at(5), None, &mut out)
.unwrap();
let got: Vec<&[u8]> = out.iter().map(|f| f.bytes.as_ref()).collect();
assert_eq!(got, [&b"T stdout P a"[..], b"T stdout F b"]);
let mut held = Vec::new();
c.frame(b"T stderr P c", &mut state, at(10), None, &mut Vec::new())
.unwrap();
c.flush(&mut state, Some(at(14)), &mut held);
assert_eq!(held.len(), 0);
c.flush(&mut state, Some(at(15)), &mut held);
assert_eq!(held[0].bytes.as_ref(), b"T stderr P c");
}
#[test]
fn a_json_pointer_finds_the_records_in_a_document() {
const DOC: &[u8] = br#" {"items": [{"id":"a"} , {"id":"b"}], "next": "k", "none": null, "a/b": {"m~n": [7]}} "#;
check(&[
(
"an array's elements",
pointer("/items"),
&[DOC],
&[br#"{"id":"a"}"#, br#"{"id":"b"}"#],
&[],
),
(
"an array deep in the document, with siblings after it",
pointer("/a/items"),
&[br#"{"a":{"items":[1,{"x":[2]}],"z":[2,{"q":"]}"}]},"b":4}"#],
&[b"1", br#"{"x":[2]}"#],
&[],
),
(
"one element",
pointer("/items/1"),
&[DOC],
&[br#"{"id":"b"}"#],
&[],
),
(
"a member through escapes",
pointer("/a~1b/m~0n"),
&[DOC],
&[b"7"],
&[],
),
(
"a value that isn't an array is one record",
pointer("/next"),
&[DOC],
&[br#""k""#],
&[],
),
(
"nothing at the pointer",
pointer("/missing"),
&[DOC, br#"{"items":null}"#, b"[1]"],
&[],
&[],
),
("null", pointer("/none"), &[DOC], &[], &[]),
(
"an index with a leading zero",
pointer("/items/01"),
&[DOC],
&[],
&[],
),
("past the end", pointer("/items/2"), &[DOC], &[], &[]),
("through a string", pointer("/next/0"), &[DOC], &[], &[]),
(
"a key with a JSON escape",
pointer("/items"),
&[br#"{"\u0069tems":[1, 2]}"#],
&[b"1", b"2"],
&[],
),
(
"the whole document",
pointer(""),
&[b"[1, \"two\"]", br#"{"a":1}"#],
&[b"1", b"\"two\"", br#"{"a":1}"#],
&[],
),
(
"a document cut short, with text after it, empty, or missing a comma",
pointer("/items"),
&[
br#"{"items":[1,"#,
br#"{"items":[1]} x"#,
b"",
br#"{"items":[1 2]}"#,
br#"{"items" [1]}"#,
br#"{"items":[1]"#,
br#"{"items":[1], "b" 2}"#,
br#"{"items":[1],]"#,
],
&[],
&["malformed"; 8],
),
]);
let mut out = Vec::new();
pointer("/items")
.frame(
DOC,
&mut FrameState::default(),
Instant::now(),
None,
&mut out,
)
.unwrap();
assert!(out.iter().all(|f| matches!(f.bytes, Cow::Borrowed(_))));
}
#[test]
fn a_json_pointer_is_read_as_rfc_6901_says() {
for (text, want) in [
("", Ok(vec![])),
("/", Ok(vec![""])),
("/a/0", Ok(vec!["a", "0"])),
("/~01/~10", Ok(vec!["~1", "/0"])),
("items", Err(PointerError::NoSlash("items".to_owned()))),
("/a~2", Err(PointerError::Tilde { at: 2 })),
("/ab/c~", Err(PointerError::Tilde { at: 5 })),
] {
let got = text.parse::<JsonPointer>().map(|p| p.tokens().to_vec());
let want = want.map(|w| w.into_iter().map(str::to_owned).collect::<Vec<_>>());
assert_eq!(got, want, "{text}");
}
assert_eq!("/a~1b".parse::<JsonPointer>().unwrap().to_string(), "/a~1b");
}
struct Any(Signature);
impl Parser for Any {
fn name(&self) -> &'static str {
"any"
}
fn tier(&self) -> MatcherTier {
MatcherTier::Byte
}
fn signature(&self) -> &Signature {
&self.0
}
fn parse<'a>(&self, _: &'a [u8], _: &mut dyn FieldSink<'a>) -> Result<Parsed, ParseError> {
Ok(Parsed::Done)
}
}
fn compile(framing: &serde_json::Value) -> Result<ParsePlan, String> {
let mut parsers = Parsers::new();
parsers
.register(Arc::new(Any(Signature::builder().build().unwrap())))
.unwrap();
let config: ParseConfig =
serde_json::from_value(serde_json::json!({"chain": "any", "framing": framing}))
.map_err(|e| e.to_string())?;
ParsePlan::compile(&config, &parsers).map_err(|e| e.to_string())
}
#[test]
fn framing_config_loads_and_its_bounds_are_checked() {
use serde_json::json;
for framing in [
json!({"kind": "stream"}),
json!({"kind": "stream", "split": "octet_counted", "max_bytes": 8192}),
json!({"kind": "stream", "split": "json_seq"}),
json!({"kind": "stream", "split": "json_array"}),
json!({"kind": "stream", "carriage_returns": "keep", "max_frame_bytes": 4096}),
json!({"kind": "stream", "split": "nul", "strip_bom": false}),
json!({"kind": "stream", "encoding": "utf16le"}),
json!({"kind": "stream", "encoding": "bom"}),
json!({"kind": "container", "format": "json_file", "timeout_ms": 50}),
json!({"kind": "json_pointer", "pointer": "/items"}),
] {
assert!(compile(&framing).is_ok(), "{framing}");
}
for (framing, want) in [
(
json!({"kind": "stream", "max_bytes": 0}),
"framing.max_bytes must be at least 1",
),
(
json!({"kind": "container", "max_bytes": 0}),
"framing.max_bytes must be at least 1",
),
(
json!({"kind": "container", "timeout_ms": 0}),
"framing.timeout_ms must be at least 1",
),
(
json!({"kind": "stream", "splt": "lf"}),
"unknown field `splt`",
),
(
json!({"kind": "stream", "split": "crlf"}),
"unknown variant `crlf`",
),
(
json!({"kind": "stream", "carriage_returns": "drop"}),
"unknown variant `drop`",
),
(
json!({"kind": "json_pointer", "pointer": "items"}),
"a JSON pointer is empty or starts with `/`",
),
] {
let err = compile(&framing).map(|_| ()).unwrap_err();
assert!(err.contains(want), "{framing}: {err}");
}
let config = conf(StreamSplit::OctetCounted, 9);
let text = serde_json::to_string(&FramingConfig::Stream(config.clone())).unwrap();
assert_eq!(
text,
r#"{"kind":"stream","split":"octet_counted","max_bytes":9,"carriage_returns":"strip","max_frame_bytes":16777216,"strip_bom":true,"encoding":"utf8"}"#
);
let back: FramingConfig = serde_json::from_str(&text).unwrap();
assert_eq!(back, FramingConfig::Stream(config));
}
#[test]
fn a_plan_frames_a_stream_and_reports_the_frame_too_long() {
let plan =
compile(&serde_json::json!({"kind": "stream", "split": "nul", "max_bytes": 4})).unwrap();
let mut state = plan.source_state();
let mut out = Vec::new();
let err = plan
.frame(b"ok\0toolong\0b", &mut state, Instant::now(), &mut out)
.unwrap_err();
assert_eq!(err.to_string(), "a frame of 8 bytes is over max_bytes 4");
let mut last = Vec::new();
plan.finish(&mut state, &mut last);
let got: Vec<&[u8]> = out.iter().chain(&last).map(|f| f.bytes.as_ref()).collect();
assert_eq!(got, [&b"ok"[..], b"b"]);
}
#[test]
fn a_record_an_input_holds_whole_is_a_slice_of_it() {
let c = stream(StreamSplit::Lf, 1 << 20);
let (mut state, now) = (FrameState::default(), Instant::now());
let mut out = Vec::new();
c.frame(b"a\r\nb\nc", &mut state, now, None, &mut out)
.unwrap();
c.frame(b"d\n", &mut state, now, None, &mut out).unwrap();
let owned: Vec<bool> = out
.iter()
.map(|f| matches!(f.bytes, Cow::Owned(_)))
.collect();
assert_eq!(owned, [false, false, true]);
}
fn halves(body: &[u8]) -> impl Iterator<Item = [&[u8]; 2]> {
(0..=body.len()).map(move |i| [&body[..i], &body[i..]])
}
fn json_value() -> impl Strategy<Value = String> {
let leaf = prop_oneof![
"-?[1-9][0-9]{0,3}(\\.[0-9]{1,2})?",
Just("true".to_owned()),
Just("null".to_owned()),
"[a-z{}\\[\\]\"\\\\\n]{0,6}".prop_map(|s| serde_json::to_string(&s).unwrap()),
];
leaf.prop_recursive(3, 16, 4, |inner| {
prop_oneof![
prop::collection::vec(inner.clone(), 0..4).prop_map(|v| format!("[{}]", v.join(","))),
prop::collection::vec(("[a-z]{1,3}", inner), 0..4).prop_map(|v| {
let members: Vec<String> = v.iter().map(|(k, v)| format!("\"{k}\": {v}")).collect();
format!("{{{}}}", members.join(","))
}),
]
})
}
fn scalar(value: &str) -> bool {
value
.bytes()
.next()
.is_some_and(|b| b.is_ascii_digit() || matches!(b, b'-' | b't' | b'n'))
}
fn same_every_cut(c: &FramingConfig, body: &[u8], want: &[Vec<u8>]) -> Result<(), TestCaseError> {
for inputs in halves(body) {
let got = run(c, &inputs);
prop_assert_eq!(&got.records, want, "{:?}", inputs);
prop_assert!(got.errors.is_empty(), "{:?}: {:?}", inputs, got.errors);
}
Ok(())
}
proptest! {
#[test]
fn a_framed_stream_cut_anywhere_gives_its_records(
lines in prop::collection::vec("[^\n\r\u{feff}]{1,12}", 0..6),
nul in prop::collection::vec("[^\0\u{feff}]{1,12}", 0..6),
counted in prop::collection::vec((any::<bool>(), "<[a-z0-9 \n]{0,10}"), 0..6),
values in prop::collection::vec(json_value(), 0..5),
crlf in any::<bool>(),
) {
const MB: usize = 1 << 20;
let end = if crlf { "\r\n" } else { "\n" };
let body: String = lines.iter().flat_map(|l| [l.as_str(), end]).collect();
let want: Vec<Vec<u8>> = lines.iter().map(|l| l.clone().into_bytes()).collect();
same_every_cut(&stream(StreamSplit::Lf, MB), body.as_bytes(), &want)?;
let body: String = nul.iter().flat_map(|r| [r.as_str(), "\0"]).collect();
let want: Vec<Vec<u8>> = nul.iter().map(|r| r.clone().into_bytes()).collect();
same_every_cut(&stream(StreamSplit::Nul, MB), body.as_bytes(), &want)?;
let mut body = String::new();
let mut want = Vec::new();
for (count, text) in &counted {
if *count {
write!(body, "{} {text}", text.len()).unwrap();
want.push(text.clone().into_bytes());
} else {
let line = text.replace('\n', " ");
writeln!(body, "{line}").unwrap();
want.push(line.into_bytes());
}
}
same_every_cut(&stream(StreamSplit::OctetCounted, MB), body.as_bytes(), &want)?;
let want: Vec<Vec<u8>> = values.iter().map(|v| v.clone().into_bytes()).collect();
let concat: String = values
.iter()
.map(|v| if scalar(v) { format!("{v} ") } else { v.clone() })
.collect();
same_every_cut(&stream(StreamSplit::JsonConcat, MB), concat.as_bytes(), &want)?;
let seq: String = values.iter().flat_map(|v| ["\x1e", v.as_str(), "\n"]).collect();
same_every_cut(&stream(StreamSplit::JsonSeq, MB), seq.as_bytes(), &want)?;
let array = format!("[{}]", values.join(" , "));
same_every_cut(&stream(StreamSplit::JsonArray, MB), array.as_bytes(), &want)?;
let document = format!("{{\"x\": 1, \"items\": [{}]}}", values.join(" , "));
let got = run(&pointer("/items"), &[document.as_bytes()]);
prop_assert_eq!(got.records, want);
prop_assert!(got.errors.is_empty());
}
#[test]
fn a_stream_holds_no_more_than_its_cap(
bytes in prop::collection::vec(prop::sample::select(b"<0123 a{}\"\\[]\n\r\0\x1e".to_vec()), 0..40),
max_bytes in 1_usize..10,
split in prop::sample::select(vec![
StreamSplit::Lf,
StreamSplit::Nul,
StreamSplit::OctetCounted,
StreamSplit::JsonConcat,
StreamSplit::JsonSeq,
StreamSplit::JsonArray,
]),
) {
let c = stream(split, max_bytes);
let mut state = FrameState::default();
let now = Instant::now();
for piece in bytes.chunks(3) {
let _ = c.frame(piece, &mut state, now, None, &mut Vec::new());
prop_assert!(state.stream.held() <= max_bytes + 22, "{}", state.stream.held());
}
let whole = run(&c, &[&bytes]);
for inputs in halves(&bytes) {
let got = run(&c, &inputs);
prop_assert_eq!(&got.records, &whole.records, "{:?}", inputs);
}
}
#[test]
fn a_container_line_cut_anywhere_joins_back(
message in "[a-z \"\\\\]{1,24}",
cuts in prop::collection::btree_set(1_usize..24, 0..4),
) {
let cuts: Vec<usize> = cuts.into_iter().filter(|&c| c < message.len()).collect();
let mut pieces = Vec::new();
let mut from = 0;
for &cut in cuts.iter().chain([&message.len()]) {
pieces.push(&message[from..cut]);
from = cut;
}
let last = pieces.len() - 1;
let cri: Vec<String> = pieces
.iter()
.enumerate()
.map(|(n, p)| format!("T{n} stdout {} {p}\n", if n == last { 'F' } else { 'P' }))
.collect();
let got = run(&container(ContainerFormat::Cri, 1 << 20), &[cri.concat().as_bytes()]);
prop_assert_eq!(got.records, vec![format!("T0 stdout F {message}").into_bytes()]);
let escaped = |text: &str| serde_json::to_string(text).unwrap();
let docker: Vec<String> = pieces
.iter()
.enumerate()
.map(|(n, p)| {
let text = if n == last { format!("{p}\n") } else { (*p).to_owned() };
format!("{{\"log\":{},\"stream\":\"stderr\",\"time\":\"t{n}\"}}\n", escaped(&text))
})
.collect();
let got = run(&container(ContainerFormat::JsonFile, 1 << 20), &[docker.concat().as_bytes()]);
let joined = docker.concat().len();
prop_assert_eq!(got.records.len(), 1, "{}", joined);
let record: serde_json::Value = serde_json::from_slice(&got.records[0]).unwrap();
prop_assert_eq!(&record["log"], &serde_json::Value::String(format!("{message}\n")));
prop_assert_eq!(&record["time"], "t0");
}
}