grippo 0.2.3

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/parse/frame/container.rs
// Purpose:   Container log lines joined from the pieces a runtime split them into
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A container runtime splits a long line into pieces: CRI marks each piece
//! but the last `P`, and the json-file driver leaves the trailing newline
//! off every piece's `log` but the last. The pieces of one line join here,
//! stdout and stderr apart, into a line of the same format, so the `cri` and
//! `ndjson` parsers read it as they read a whole one.

use std::ops::Range;
use std::time::{Duration, Instant};

use memchr::memchr;
use serde::{Deserialize, Serialize};

use super::Frame;
use super::json::{key_is, members, skip_space};

/// Which container log format the lines are in.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ContainerFormat {
    /// `<time> <stream> <P|F>[:<tags>] <message>`, the CRI format a kubelet's
    /// runtime writes.
    #[default]
    Cri,
    /// A JSON object a line with `log`, `stream` and `time`, as the
    /// json-file logging driver writes.
    JsonFile,
}

/// Settings for [`FramingConfig::Container`](super::FramingConfig::Container).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct ContainerConfig {
    /// The lines' format.
    pub format: ContainerFormat,
    /// Most bytes one joined line holds. A line that would grow past it is
    /// released as it stands, still marked as a piece.
    pub max_bytes: usize,
    /// How long a line waits for its next piece, in milliseconds. The next
    /// input or a flush releases one that has waited this long.
    pub timeout_ms: u64,
}

impl Default for ContainerConfig {
    fn default() -> Self {
        Self {
            format: ContainerFormat::Cri,
            max_bytes: 1 << 20,
            timeout_ms: 1000,
        }
    }
}

/// The line being joined on each stream: stdout, then stderr.
#[derive(Debug, Default, Clone)]
pub(super) struct Joins {
    runs: [Run; 2],
}

/// A line joined from the pieces so far.
#[derive(Debug, Default, Clone)]
struct Run {
    /// The first piece whole, with each later piece's message added.
    bytes: Vec<u8>,
    /// Where the next message goes: the end of a CRI line, or the closing
    /// quote of a json-file line's `log`.
    at: usize,
    /// The CRI tag, set to `F` when the last piece arrives.
    tag: Range<usize>,
    /// When the latest piece arrived, while a line is held.
    latest: Option<Instant>,
}

impl Run {
    fn release(&mut self) -> Frame<'static> {
        self.latest = None;
        Frame::new(std::mem::take(&mut self.bytes))
    }

    fn waited_out(&self, c: &ContainerConfig, now: Instant) -> bool {
        self.latest
            .is_some_and(|latest| now.duration_since(latest) >= Duration::from_millis(c.timeout_ms))
    }

    /// Hold `line`, the first piece.
    fn begin(&mut self, line: &[u8], piece: &Piece, now: Instant) {
        self.bytes.clear();
        self.bytes.extend_from_slice(line);
        self.at = piece.message.end;
        self.tag = piece.tag.clone();
        self.latest = Some(now);
    }

    /// Add a later piece's `message`.
    fn add(&mut self, message: &[u8], now: Instant) {
        self.bytes.extend_from_slice(message);
        self.bytes[self.at..].rotate_right(message.len());
        self.at += message.len();
        self.latest = Some(now);
    }

    /// Mark the line whole: a CRI tag becomes `F`, its `:` tags dropped.
    fn close(&mut self) {
        let Range { start, end } = self.tag;
        if end > start {
            self.bytes[start] = b'F';
            self.bytes.copy_within(end.., start + 1);
            self.bytes.truncate(self.bytes.len() - (end - start - 1));
        }
    }
}

/// One line read as a piece.
struct Piece {
    /// 0 for stdout, 1 for stderr.
    stream: usize,
    /// The message, as a range of the line: a CRI line's text, or the body
    /// of a json-file line's `log` string.
    message: Range<usize>,
    /// Whether the line ends with this piece.
    last: bool,
    /// The CRI tag's range, empty for json-file.
    tag: Range<usize>,
}

const fn stream(name: &[u8]) -> Option<usize> {
    match name {
        b"stdout" => Some(0),
        b"stderr" => Some(1),
        _ => None,
    }
}

/// A CRI line: `<time> <stream> <tag> <message>`, the tag `P` or `F` and any
/// `:` tags after it.
fn cri(line: &[u8]) -> Option<Piece> {
    let time = memchr(b' ', line).filter(|&end| end > 0)?;
    let name = time + 1;
    let name_end = name + memchr(b' ', &line[name..])?;
    let stream = stream(&line[name..name_end])?;
    let tag = name_end + 1;
    let tag_end = memchr(b' ', &line[tag..]).map_or(line.len(), |i| tag + i);
    let last = match line[tag..tag_end].split(|&b| b == b':').next() {
        Some(b"F") => true,
        Some(b"P") => false,
        _ => return None,
    };
    Some(Piece {
        stream,
        message: (tag_end + 1).min(line.len())..line.len(),
        last,
        tag: tag..tag_end,
    })
}

/// A json-file line: an object whose `log` and `stream` are strings.
fn json_file(line: &[u8]) -> Option<Piece> {
    let open = skip_space(line, 0);
    if line.get(open) != Some(&b'{') {
        return None;
    }
    let (mut log, mut name) = (None, None);
    for entry in members(line, open) {
        let (key, value) = entry.ok()?;
        if key_is(&line[key.clone()], "log") {
            log = Some(value);
        } else if key_is(&line[key], "stream") {
            name = Some(value);
        }
    }
    let (log, name) = (log?, name?);
    if line[log.start] != b'"' || line[name.start] != b'"' {
        return None;
    }
    let body = log.start + 1..log.end - 1;
    Some(Piece {
        stream: stream(&line[name.start + 1..name.end - 1])?,
        last: ends_in_newline(&line[body.clone()]),
        message: body,
        tag: 0..0,
    })
}

/// Whether a JSON string's body ends in the escape `\n`.
fn ends_in_newline(body: &[u8]) -> bool {
    body.strip_suffix(b"n")
        .is_some_and(|rest| rest.iter().rev().take_while(|&&b| b == b'\\').count() % 2 == 1)
}

/// Join the lines of `input`, appending each whole line to `out`.
pub(super) fn frame<'a>(
    c: &ContainerConfig,
    input: &'a [u8],
    joins: &mut Joins,
    now: Instant,
    out: &mut Vec<Frame<'a>>,
) {
    let mut rest = input;
    while !rest.is_empty() {
        let end = memchr(b'\n', rest).unwrap_or(rest.len());
        let line = &rest[..end];
        rest = rest.get(end + 1..).unwrap_or_default();
        if !line.is_empty() {
            piece(c, line, joins, now, out);
        }
    }
}

fn piece<'a>(
    c: &ContainerConfig,
    line: &'a [u8],
    joins: &mut Joins,
    now: Instant,
    out: &mut Vec<Frame<'a>>,
) {
    let read = match c.format {
        ContainerFormat::Cri => cri(line),
        ContainerFormat::JsonFile => json_file(line),
    };
    let Some(piece) = read else {
        out.push(Frame::new(line));
        return;
    };
    let run = &mut joins.runs[piece.stream];
    // A piece after the timeout finds the line released, as a flush would
    // have left it, so the result doesn't turn on timers.
    if run.waited_out(c, now)
        || (run.latest.is_some() && run.bytes.len() + piece.message.len() > c.max_bytes)
    {
        out.push(run.release());
    }
    if run.latest.is_none() {
        if piece.last || line.len() > c.max_bytes {
            out.push(Frame::new(line));
        } else {
            run.begin(line, &piece, now);
        }
        return;
    }
    run.add(&line[piece.message.clone()], now);
    if piece.last {
        run.close();
        out.push(run.release());
    }
}

/// Release a line that has waited out its timeout at `now`, or every held
/// line when `now` is `None`.
pub(super) fn flush(
    c: &ContainerConfig,
    joins: &mut Joins,
    now: Option<Instant>,
    out: &mut Vec<Frame<'static>>,
) {
    for run in &mut joins.runs {
        let due = match now {
            Some(now) => run.waited_out(c, now),
            None => run.latest.is_some(),
        };
        if due {
            out.push(run.release());
        }
    }
}