grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/parse/config.rs
// Purpose:   Plain serde config for a source's parse plan
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Config types only. The application's config cascade fills them, and
//! [`super::ParsePlan::compile`] checks them.

use std::collections::BTreeMap;
use std::fmt;

use serde::de::{self, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};

use super::chain::{self, ChainError};

/// Settings per parser, keyed by the parser's exact name.
pub type Settings = BTreeMap<String, serde_json::Value>;

/// Which parser a hop runs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(into = "FormatRepr")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schemars", schemars(with = "FormatRepr"))]
#[non_exhaustive]
pub enum FormatChoice {
    /// `auto`: detect this hop's input by the candidates' signatures, and
    /// leave whatever that parser hands on alone.
    Auto,
    /// `auto*`: detect at this hop and at every level below it, bodies and
    /// values, until nothing matches or `max_depth`.
    AutoStar,
    /// Try these in order. The first that matches wins.
    Named(Vec<String>),
}

/// `auto`, `auto*`, one name, or a list of names.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
enum FormatRepr {
    One(String),
    List(Vec<String>),
}

impl From<String> for FormatChoice {
    fn from(name: String) -> Self {
        match name.as_str() {
            "auto" => Self::Auto,
            "auto*" => Self::AutoStar,
            _ => Self::Named(vec![name]),
        }
    }
}

impl From<FormatChoice> for FormatRepr {
    fn from(choice: FormatChoice) -> Self {
        match choice {
            FormatChoice::Auto => Self::One("auto".to_owned()),
            FormatChoice::AutoStar => Self::One("auto*".to_owned()),
            FormatChoice::Named(mut names) if names.len() == 1 => {
                Self::One(names.pop().unwrap_or_default())
            }
            FormatChoice::Named(names) => Self::List(names),
        }
    }
}

impl<'de> Deserialize<'de> for FormatChoice {
    fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
        struct Choice;
        impl<'de> Visitor<'de> for Choice {
            type Value = FormatChoice;
            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("auto, auto*, a parser name or a list of parser names")
            }
            fn visit_str<E: de::Error>(self, name: &str) -> Result<FormatChoice, E> {
                Ok(name.to_owned().into())
            }
            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<FormatChoice, A::Error> {
                let mut names = Vec::new();
                while let Some(name) = seq.next_element::<String>()? {
                    names.push(name);
                }
                Ok(FormatChoice::Named(names))
            }
        }
        de.deserialize_any(Choice)
    }
}

/// What a hop does when it has to parse its input and nothing does.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schemars", schemars(with = "String"))]
#[non_exhaustive]
pub enum FallbackConfig {
    /// Keep what parsed above it. The caller keeps the raw bytes.
    #[default]
    Raw,
    /// Reject the record.
    Reject,
    /// Try this parser once on the hop's input.
    Format(String),
}

impl From<String> for FallbackConfig {
    fn from(s: String) -> Self {
        match s.as_str() {
            "raw" => Self::Raw,
            "reject" => Self::Reject,
            _ => Self::Format(s),
        }
    }
}

impl From<FallbackConfig> for String {
    fn from(f: FallbackConfig) -> Self {
        match f {
            FallbackConfig::Raw => "raw".to_owned(),
            FallbackConfig::Reject => "reject".to_owned(),
            FallbackConfig::Format(name) => name,
        }
    }
}

/// One hop of a chain: which input it reads and which parser runs on it.
///
/// With neither `field` nor `each` it reads the body the hop before handed
/// on, and the first hop reads the record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct HopConfig {
    /// The hop's parser: a name, a list tried in order, `auto` or `auto*`.
    pub format: FormatChoice,
    /// Read this value of the hop before, by the name its parser wrote: `a.b`
    /// for the key `b` inside `a`, `["a.b"]` for the one key `a.b`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub field: Option<String>,
    /// Read every value the hop before wrote.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub each: bool,
    /// Field-name prefix. Default: empty for the first hop, else the parser's
    /// name and a dot.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prefix: Option<String>,
    /// This hop's fallback. Default: the plan's.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fallback: Option<FallbackConfig>,
    /// Settings for this hop's parsers, in place of the plan's for that name.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub settings: Settings,
}

impl HopConfig {
    /// A hop that reads a body with `format` and takes every default.
    #[must_use]
    pub const fn new(format: FormatChoice) -> Self {
        Self {
            format,
            field: None,
            each: false,
            prefix: None,
            fallback: None,
            settings: BTreeMap::new(),
        }
    }
}

/// The table form of a hop. Unknown keys are refused.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct HopTable {
    format: FormatChoice,
    #[serde(default)]
    field: Option<String>,
    #[serde(default)]
    each: bool,
    #[serde(default)]
    prefix: Option<String>,
    #[serde(default)]
    fallback: Option<FallbackConfig>,
    #[serde(default)]
    settings: Settings,
}

impl<'de> Deserialize<'de> for HopConfig {
    fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
        struct Hop;
        impl<'de> Visitor<'de> for Hop {
            type Value = HopConfig;
            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("a hop such as `cef` or `field(\"msg\"):xml`, or a table with `format`")
            }
            fn visit_str<E: de::Error>(self, text: &str) -> Result<HopConfig, E> {
                chain::hop(text).map_err(E::custom)
            }
            fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<HopConfig, A::Error> {
                let t = HopTable::deserialize(de::value::MapAccessDeserializer::new(map))?;
                Ok(HopConfig {
                    format: t.format,
                    field: t.field,
                    each: t.each,
                    prefix: t.prefix,
                    fallback: t.fallback,
                    settings: t.settings,
                })
            }
        }
        de.deserialize_any(Hop)
    }
}

/// A chain of hops, outermost first.
///
/// Written as a string or as the list the string is short for:
///
/// | Written | Means |
/// | --- | --- |
/// | `syslog` | The syslog parser and nothing else |
/// | `syslog > cef` | syslog, then its message as CEF. `->` reads the same |
/// | `syslog > (cef, leef)` | syslog, then the first of those that takes the message |
/// | `syslog > auto` | syslog, then detect the message's format, one level |
/// | `syslog > auto*` | syslog, then detect at every level below, bodies and values |
/// | `cef > field("msg"):xml` | CEF, then the value it wrote as `msg`, as XML |
/// | `cef > each:xml` | CEF, then every value it wrote that XML takes |
///
/// A hop with no selector reads the body the hop before handed on. `auto*`
/// is the last hop of its chain.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(transparent)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct Chain(pub Vec<HopConfig>);

impl std::str::FromStr for Chain {
    type Err = ChainError;

    fn from_str(text: &str) -> Result<Self, ChainError> {
        chain::chain(text).map(Self)
    }
}

impl<'de> Deserialize<'de> for Chain {
    fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
        struct Hops;
        impl<'de> Visitor<'de> for Hops {
            type Value = Chain;
            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("a chain such as `syslog > cef`, or a list of hops")
            }
            fn visit_str<E: de::Error>(self, text: &str) -> Result<Chain, E> {
                text.parse().map_err(E::custom)
            }
            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Chain, A::Error> {
                let mut hops = Vec::new();
                while let Some(hop) = seq.next_element::<HopConfig>()? {
                    hops.push(hop);
                }
                Ok(Chain(hops))
            }
        }
        de.deserialize_any(Hops)
    }
}

/// A source's parse config.
///
/// ```yaml
/// chain: syslog > auto
/// ```
///
/// ```yaml
/// chain:
///   - syslog
///   - { format: [cef, leef], prefix: "event." }
///   - { field: msg, format: "grok:fw", fallback: raw }
/// fallback: reject
/// max_depth: 4
/// settings:
///   "grok:fw": { patterns: ["..."] }
/// ```
///
/// `chain` is required: a config that names no parser doesn't load, and
/// detection runs only where the chain says `auto` or `auto*`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct ParseConfig {
    /// What to parse, outermost first.
    pub chain: Chain,
    /// What a hop does when it has to parse its input and nothing does.
    #[serde(default)]
    pub fallback: FallbackConfig,
    /// Most parsers one record may nest through on one branch.
    #[serde(default = "default_max_depth")]
    pub max_depth: usize,
    /// Most parser calls one record may take, misses included.
    #[serde(default = "default_max_invocations")]
    pub max_invocations: usize,
    /// How inputs become records before any hop runs.
    #[serde(default)]
    pub framing: super::FramingConfig,
    /// Settings per parser, keyed by the parser's exact name.
    #[serde(default)]
    pub settings: Settings,
}

const fn default_max_depth() -> usize {
    4
}

const fn default_max_invocations() -> usize {
    256
}

impl ParseConfig {
    /// A config for `chain` with every other key on its default.
    #[must_use]
    pub const fn new(chain: Chain) -> Self {
        Self {
            chain,
            fallback: FallbackConfig::Raw,
            max_depth: default_max_depth(),
            max_invocations: default_max_invocations(),
            framing: super::FramingConfig::None { trim_cr: false },
            settings: BTreeMap::new(),
        }
    }

    /// A config for a chain written as a string, such as `syslog > auto`.
    ///
    /// # Errors
    ///
    /// [`ChainError`] when the string isn't a chain.
    pub fn chain(text: &str) -> Result<Self, ChainError> {
        text.parse().map(Self::new)
    }
}