use std::ops::Range;
use super::ndjson::{Entries, walk};
use crate::parse::{FieldSink, ParseError, Parsed, Parser, quoted_span};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;
#[derive(Debug, Clone)]
pub struct Gelf {
signature: Signature,
}
impl Default for Gelf {
fn default() -> Self {
Self::new()
}
}
impl Gelf {
#[must_use]
pub fn new() -> Self {
let signature = Signature::builder()
.anchored(["{"])
.all_of([r#""short_message""#, r#""version""#])
.build()
.unwrap_or_else(|_| unreachable!("invariant: the GELF literals are non-empty"));
Self { signature }
}
}
impl Parser for Gelf {
fn name(&self) -> &'static str {
"gelf"
}
fn tier(&self) -> MatcherTier {
MatcherTier::Field
}
fn signature(&self) -> &Signature {
&self.signature
}
fn hands_on_body(&self) -> bool {
false
}
fn escape_value(
&self,
input: &[u8],
_field: usize,
at: Range<usize>,
value: &[u8],
out: &mut Vec<u8>,
) -> Option<Range<usize>> {
let text = std::str::from_utf8(value).ok()?;
let span = quoted_span(input, &at, |b| b == b'"').unwrap_or(at);
serde_json::to_writer(&mut *out, text).ok()?;
Some(span)
}
fn parse<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<Parsed, ParseError> {
let trail = input
.iter()
.rev()
.take_while(|b| b.is_ascii_whitespace())
.count();
let record = &input[..input.len() - trail];
if record.first() != Some(&b'{') {
return Ok(Parsed::NoMatch);
}
let Ok(Entries(entries)) = serde_json::from_slice::<Entries<'a>>(record) else {
return Ok(Parsed::NoMatch);
};
let has = |name: &str| entries.iter().any(|(k, _)| k.0 == name);
if !has("version") || !has("short_message") {
return Ok(Parsed::NoMatch);
}
for (k, v) in entries {
let name = k.0.strip_prefix('_').unwrap_or(&k.0);
walk(name, v, out).map_err(|e| ParseError::Malformed {
offset: e.column().saturating_sub(1),
reason: "a GELF value that doesn't parse",
})?;
}
Ok(Parsed::Done)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parse::Fields;
#[test]
fn a_gelf_record_drops_the_additional_field_underscore() {
let line = br#"{"version":"1.1","host":"web01","short_message":"login failed","level":4,"_user_id":42,"_ctx":{"ip":"10.0.0.1"}}"#;
let mut out = Fields::new();
assert_eq!(Gelf::new().parse(line, &mut out).unwrap(), Parsed::Done);
assert_eq!(&*out.get("short_message").unwrap().bytes, b"login failed");
assert_eq!(&*out.get("user_id").unwrap().bytes, b"42");
assert_eq!(&*out.get("ctx.ip").unwrap().bytes, b"10.0.0.1");
assert!(out.get("_user_id").is_none());
}
proptest::proptest! {
#[test]
fn an_escaped_value_reads_back(
value in r#"[a-z "\\/\n\t\u{1}\u{e9}]{0,10}"#,
old in proptest::sample::select(vec![r#""x""#, r#""a\"b""#, "42"]),
) {
let line = format!(
r#"{{"version":"1.1","short_message":"hi","_v":{old},"_n":1}}"#
);
let start = line.find(old).unwrap();
let lent = old.strip_prefix('"').map_or(start..start + old.len(), |_| {
start + 1..start + old.len() - 1
});
let mut text = Vec::new();
let span = Gelf::new()
.escape_value(line.as_bytes(), 5, lent, value.as_bytes(), &mut text)
.unwrap();
let after = [&line.as_bytes()[..span.start], &text, &line.as_bytes()[span.end..]].concat();
let mut out = Fields::new();
proptest::prop_assert_eq!(Gelf::new().parse(&after, &mut out).unwrap(), Parsed::Done);
proptest::prop_assert_eq!(&*out.get("v").unwrap().bytes, value.as_bytes());
proptest::prop_assert_eq!(&*out.get("n").unwrap().bytes, b"1");
proptest::prop_assert_eq!(&*out.get("short_message").unwrap().bytes, b"hi");
}
}
#[test]
fn plain_json_is_not_gelf() {
let mut out = Fields::new();
let line = br#"{"msg":"x","version":"1"}"#;
assert_eq!(Gelf::new().parse(line, &mut out).unwrap(), Parsed::NoMatch);
assert!(out.is_empty());
assert!(!Gelf::new().signature().may_match(line));
}
}