grippo 0.2.3

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/format/cri.rs
// Purpose:   The CRI container log parser
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! `<RFC 3339 time> <stdout|stderr> <F|P> <message>`, as container runtimes
//! write a pod's log file.
//!
//! The message goes on as the body. `partial` is `true` for a `P` line, which
//! the `container` framing, behind the `framing` feature, joins to the rest
//! of its line. Docker's json-file lines are JSON, so the `ndjson` parser
//! reads them.

use std::ops::Range;

use crate::field::{Scan, field};
use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;

/// Where the stream marker must end by. A runtime's timestamp is at most 35
/// bytes, so a line that puts the marker later isn't one, and the signature
/// can stop reading there.
const MARKER_BY: usize = 64;

/// The CRI parser, registered as `cri`.
#[derive(Debug, Clone)]
pub struct Cri {
    signature: Signature,
}

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

impl Cri {
    /// A CRI parser.
    ///
    /// # Panics
    ///
    /// Never: the signature's literals are fixed and non-empty.
    #[must_use]
    pub fn new() -> Self {
        let signature = Signature::builder()
            .any_of([" stdout ", " stderr "])
            .verify(flag_follows)
            .within(MARKER_BY)
            .build()
            .unwrap_or_else(|_| unreachable!("invariant: the CRI literals are non-empty"));
        Self { signature }
    }
}

/// `F ` or `P ` after the 8-byte stream word at `at`, the whole marker inside
/// the first [`MARKER_BY`] bytes.
fn flag_follows(span: &[u8], at: usize) -> bool {
    at + 10 <= MARKER_BY && matches!(span.get(at + 8..at + 10), Some(b"F " | b"P "))
}

impl Parser for Cri {
    fn name(&self) -> &'static str {
        "cri"
    }

    fn tier(&self) -> MatcherTier {
        MatcherTier::Field
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    /// A CRI line has no escape: a value goes in as it is, and the re-parse
    /// a write-back runs refuses one that doesn't read back.
    fn escape_value(
        &self,
        _input: &[u8],
        _field: usize,
        at: Range<usize>,
        value: &[u8],
        out: &mut Vec<u8>,
    ) -> Option<Range<usize>> {
        out.extend_from_slice(value);
        Some(at)
    }

    fn parse<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Parsed, ParseError> {
        let Some(Scan::Match(t)) = field("TIMESTAMP_ISO8601").map(|f| (f.scan)(input, 0)) else {
            return Ok(Parsed::NoMatch);
        };
        let rest = &input[t..];
        let stream_len = if rest.starts_with(b" stdout ") || rest.starts_with(b" stderr ") {
            6
        } else {
            return Ok(Parsed::NoMatch);
        };
        let flag_at = t + 1 + stream_len + 1;
        let partial = match input.get(flag_at..flag_at + 2) {
            Some(b"F ") => false,
            Some(b"P ") => true,
            _ => return Ok(Parsed::NoMatch),
        };
        let body = flag_at + 2;
        if body > MARKER_BY {
            return Ok(Parsed::NoMatch);
        }
        let trail = input[body..]
            .iter()
            .rev()
            .take_while(|&&b| b == b'\n')
            .count();
        let end = input.len() - trail;
        out.field(
            "timestamp",
            FieldValue::borrowed(&input[..t], Hint::Timestamp),
        );
        out.field(
            "stream",
            FieldValue::borrowed(&input[t + 1..t + 1 + stream_len], Hint::Text),
        );
        let flag: &'static [u8] = if partial { b"true" } else { b"false" };
        out.field("partial", FieldValue::borrowed(flag, Hint::Bool));
        out.body_field(
            "message",
            FieldValue::borrowed(&input[body..end], Hint::Text),
        );
        Ok(Parsed::Body {
            span: body..end,
            hint: (input.get(body) == Some(&b'{')).then_some("ndjson"),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse::Fields;

    #[test]
    fn a_full_and_a_partial_line() {
        let line = b"2026-11-26T00:22:33.123456789Z stdout F {\"level\":\"info\"}\n";
        let mut out = Fields::new();
        let Parsed::Body { span, hint } = Cri::new().parse(line, &mut out).unwrap() else {
            panic!("no body")
        };
        assert_eq!(&line[span], b"{\"level\":\"info\"}");
        assert_eq!(hint, Some("ndjson"));
        assert_eq!(&*out.get("stream").unwrap().bytes, b"stdout");
        assert_eq!(&*out.get("partial").unwrap().bytes, b"false");

        let mut out = Fields::new();
        Cri::new()
            .parse(b"2026-11-26T00:22:33Z stderr P half a li", &mut out)
            .unwrap();
        assert_eq!(&*out.get("partial").unwrap().bytes, b"true");
        assert_eq!(&*out.get("message").unwrap().bytes, b"half a li");
    }

    proptest::proptest! {
        /// A message without a line end, written in as it is, reads back as
        /// written.
        #[test]
        fn a_written_message_reads_back(value in "[a-z {}\"\t]{0,12}") {
            let line = b"2026-11-26T00:22:33Z stdout F old message\n";
            let mut text = Vec::new();
            let span = Cri::new().escape_value(line, 3, 30..41, value.as_bytes(), &mut text).unwrap();
            let after = [&line[..span.start], &text, &line[span.end..]].concat();
            let mut out = Fields::new();
            let parsed = Cri::new().parse(&after, &mut out).unwrap();
            let body = matches!(parsed, Parsed::Body { .. });
            proptest::prop_assert!(body);
            proptest::prop_assert_eq!(&*out.get("message").unwrap().bytes, value.as_bytes());
        }
    }

    #[test]
    fn other_lines_are_no_match() {
        for line in [
            &b"2026-11-26T00:22:33Z stdin F x"[..],
            b"stdout F x",
            b"2026-11-26T00:22:33Z stdout X y",
        ] {
            let mut out = Fields::new();
            assert_eq!(Cri::new().parse(line, &mut out).unwrap(), Parsed::NoMatch);
            assert!(out.is_empty());
        }
    }

    #[test]
    fn the_parser_and_its_signature_agree_on_where_the_marker_may_sit() {
        let cri = Cri::new();
        let longest = b"2026-11-26T00:22:33.123456789+10:00 stdout F m";
        assert!(cri.signature().may_match(longest));
        assert!(matches!(
            cri.parse(longest, &mut Fields::new()),
            Ok(Parsed::Body { .. })
        ));
        let late = b"2026-11-26T00:22:33.12345678901234567890123456789012345Z stdout F m";
        assert!(!cri.signature().may_match(late));
        assert!(matches!(
            cri.parse(late, &mut Fields::new()),
            Ok(Parsed::NoMatch)
        ));
        // The marker's last byte sits at byte 64 in one and byte 65 in the next.
        for (pad, fits) in [(54, true), (55, false)] {
            let line = format!("{} stderr P m", "x".repeat(pad));
            assert_eq!(cri.signature().may_match(line.as_bytes()), fits, "{pad}");
        }
        assert!(
            !cri.signature()
                .may_match(b"2026-11-26T00:22:33Z stdout X m")
        );
    }
}