grippo 0.1.0

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/format/gelf.rs
// Purpose:   The GELF parser: GELF JSON records
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A GELF record is a JSON object with `version` and `short_message`.
//!
//! Additional fields carry a leading `_`, which this drops: `_user_id` is
//! written as `user_id`. Chunking and compression are the transport's to undo.

use super::ndjson::{Entries, walk};
use crate::parse::{FieldSink, ParseError, Parsed, Parser};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;

/// The GELF parser, registered as `gelf`.
#[derive(Debug, Clone)]
pub struct Gelf {
    signature: Signature,
}

impl Default for Gelf {
    fn default() -> Self {
        Self::new()
    }
}

impl Gelf {
    /// A GELF parser.
    ///
    /// # Panics
    ///
    /// Never: the signature's literals are fixed and non-empty.
    #[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 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());
    }

    #[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));
    }
}