grippo 0.1.0

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/format/dissect.rs
// Purpose:   The dissect parser: fields between fixed delimiters
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A dissect pattern, `%{a} %{b} [%{c}]`, splits on its literal delimiters.
//!
//! Each key takes the text up to the first following delimiter, and the last
//! key takes the rest. `%{?name}` and `%{}` skip a value, `%{key->}` also eats
//! repeats of the delimiter after it, and `%{+key}` appends to an earlier key.
//! The whole input must be consumed. Reference keys (`*`, `&`) and append
//! order (`/n`) are refused when the pattern compiles.

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

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

/// A dissect pattern and how appended values join.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct DissectConfig {
    /// The pattern, such as `%{ts} %{+ts} %{host} %{msg}`.
    pub pattern: String,
    /// Between appended values. Default one space.
    #[serde(default = "space")]
    pub append_separator: String,
}

fn space() -> String {
    " ".to_owned()
}

/// Why a dissect pattern didn't compile.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DissectError {
    /// A `%{` with no closing `}`.
    #[error("dissect: unclosed %{{ at byte {0}")]
    Unclosed(usize),
    /// Two keys with no delimiter between them.
    #[error("dissect: keys at byte {0} have no delimiter between them")]
    Adjacent(usize),
    /// A modifier this parser doesn't run.
    #[error("dissect: modifier in %{{{0}}} is not supported")]
    Modifier(String),
    /// A pattern with no key.
    #[error("dissect: the pattern has no key")]
    NoKey,
}

#[derive(Debug, Clone)]
struct Key {
    name: Option<String>,
    append: bool,
    pad: bool,
    /// The delimiter after this key, empty for a key that ends the pattern.
    then: Vec<u8>,
}

/// The dissect parser, registered as `dissect`.
#[derive(Debug, Clone)]
pub struct Dissect {
    lead: Vec<u8>,
    keys: Vec<Key>,
    joiner: Vec<u8>,
    signature: Signature,
}

impl Dissect {
    /// Compile `config`.
    ///
    /// # Errors
    ///
    /// [`DissectError`] for an unclosed key, two keys with no delimiter
    /// between them, a reference or ordered append, or no key at all.
    pub fn new(config: &DissectConfig) -> Result<Self, DissectError> {
        let p = config.pattern.as_bytes();
        let mut lead = Vec::new();
        let mut keys: Vec<Key> = Vec::new();
        let mut i = 0;
        while i < p.len() {
            if p[i..].starts_with(b"%{") {
                let close = p[i..]
                    .iter()
                    .position(|&b| b == b'}')
                    .ok_or(DissectError::Unclosed(i))?;
                if keys.last().is_some_and(|k| k.then.is_empty()) {
                    return Err(DissectError::Adjacent(i));
                }
                let body = &config.pattern[i + 2..i + close];
                keys.push(parse_key(body)?);
                i += close + 1;
            } else {
                match keys.last_mut() {
                    Some(k) => k.then.push(p[i]),
                    None => lead.push(p[i]),
                }
                i += 1;
            }
        }
        if keys.is_empty() {
            return Err(DissectError::NoKey);
        }
        let mut sig = Signature::builder();
        if !lead.is_empty() {
            sig = sig.anchored([lead.clone()]);
        }
        let signature = sig
            .build()
            .unwrap_or_else(|_| unreachable!("invariant: the lead literal is non-empty"));
        Ok(Self {
            lead,
            keys,
            joiner: config.append_separator.as_bytes().to_vec(),
            signature,
        })
    }
}

fn parse_key(body: &str) -> Result<Key, DissectError> {
    if body.contains(['*', '&', '/']) {
        return Err(DissectError::Modifier(body.to_owned()));
    }
    let (body, pad) = body.strip_suffix("->").map_or((body, false), |b| (b, true));
    let (body, append, skip) = match body.as_bytes().first() {
        Some(b'+') => (&body[1..], true, false),
        Some(b'?') => (&body[1..], false, true),
        _ => (body, false, false),
    };
    Ok(Key {
        name: (!skip && !body.is_empty()).then(|| body.to_owned()),
        append,
        pad,
        then: Vec::new(),
    })
}

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

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

    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| matches!(b, b'\n' | b'\r'))
            .count();
        let line = &input[..input.len() - trail];
        if !line.starts_with(&self.lead) {
            return Ok(Parsed::NoMatch);
        }
        let mut pos = self.lead.len();
        let mut spans = Vec::with_capacity(self.keys.len());
        for key in &self.keys {
            let end = if key.then.is_empty() {
                line.len()
            } else {
                match memmem::find(&line[pos..], &key.then) {
                    Some(n) => pos + n,
                    None => return Ok(Parsed::NoMatch),
                }
            };
            spans.push(pos..end);
            pos = end + key.then.len();
            while key.pad && !key.then.is_empty() && line[pos..].starts_with(&key.then) {
                pos += key.then.len();
            }
        }
        if pos != line.len() {
            return Ok(Parsed::NoMatch);
        }
        let mut written: Vec<(&str, Vec<u8>)> = Vec::new();
        for (key, span) in self.keys.iter().zip(spans) {
            let Some(name) = key.name.as_deref() else {
                continue;
            };
            let value = &line[span];
            if key.append
                && let Some((_, joined)) = written.iter_mut().find(|(n, _)| *n == name)
            {
                joined.extend_from_slice(&self.joiner);
                joined.extend_from_slice(value);
            } else if self
                .keys
                .iter()
                .any(|k| k.append && k.name.as_deref() == Some(name))
            {
                written.push((name, value.to_vec()));
            } else {
                out.field(name, FieldValue::borrowed(value, Hint::Text));
            }
        }
        for (name, joined) in written {
            out.field(name, FieldValue::owned(joined, Hint::Text));
        }
        Ok(Parsed::Done)
    }
}

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

    fn dissect(pattern: &str) -> Dissect {
        Dissect::new(&DissectConfig {
            pattern: pattern.to_owned(),
            append_separator: " ".to_owned(),
        })
        .unwrap()
    }

    fn run(d: &Dissect, line: &str) -> (Parsed, Vec<(String, String)>) {
        let mut out = Fields::new();
        let p = d.parse(line.as_bytes(), &mut out).unwrap();
        let fields = out
            .as_slice()
            .iter()
            .map(|(n, v)| (n.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
            .collect();
        (p, fields)
    }

    #[test]
    fn splits_appends_pads_and_skips() {
        let d = dissect("%{date} %{+date} %{host->} [%{?pid}] %{msg}");
        let (_, f) = run(&d, "Nov 26 web01  [123] x");
        let host = f.iter().find(|(k, _)| k == "host").map(|(_, v)| v.as_str());
        assert_eq!(
            host,
            Some("web01 "),
            "the delimiter is ` [`, so its first match ends host"
        );
        let d = dissect("%{date} %{+date} %{host->} %{?pid} %{msg}");
        let (p, f) = run(&d, "Nov 26 web01    123 disk is full\n");
        assert_eq!(p, Parsed::Done);
        let get = |n: &str| f.iter().find(|(k, _)| k == n).map(|(_, v)| v.as_str());
        assert_eq!(get("date"), Some("Nov 26"));
        assert_eq!(get("host"), Some("web01"));
        assert_eq!(get("pid"), None);
        assert_eq!(get("msg"), Some("disk is full"));
    }

    #[test]
    fn a_lead_literal_anchors_and_the_input_must_be_consumed() {
        let d = dissect("[%{level}] %{msg}");
        assert_eq!(run(&d, "[warn] slow").0, Parsed::Done);
        assert_eq!(run(&d, "warn slow").0, Parsed::NoMatch);
        let d = dissect("%{a}|%{b}|");
        assert_eq!(run(&d, "1|2|").0, Parsed::Done);
        let (p, f) = run(&d, "1|2|3");
        assert_eq!(p, Parsed::NoMatch);
        assert!(f.is_empty(), "no match writes nothing");
    }

    #[test]
    fn bad_patterns_are_refused() {
        let new = |p: &str| {
            Dissect::new(&DissectConfig {
                pattern: p.to_owned(),
                append_separator: " ".to_owned(),
            })
        };
        assert!(matches!(new("%{a"), Err(DissectError::Unclosed(_))));
        assert!(matches!(new("%{a}%{b}"), Err(DissectError::Adjacent(_))));
        assert!(matches!(new("%{*a} %{&a}"), Err(DissectError::Modifier(_))));
        assert!(matches!(new("no keys"), Err(DissectError::NoKey)));
    }
}