grippo 0.1.1

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/parse/mod.rs
// Purpose:   The Parser trait, its output contract and parser lookup
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! One [`Parser`] trait for every format, and a driver that runs a chain of
//! them: `syslog > cef > field("msg"):xml`.
//!
//! A parser reads bytes and writes fields into a caller-owned [`FieldSink`]
//! as borrowed spans. It returns [`Parsed::Body`] when it read an envelope
//! and the rest is another parser's input, so syslog hands its message to a
//! CEF parser without a copy.

mod capture;
mod chain;
mod config;
mod driver;
mod frame;
mod number;
mod sink;
mod trace;

#[cfg(feature = "both-paths")]
pub mod both_paths;

use std::borrow::Cow;
use std::collections::HashMap;
use std::ops::Range;
use std::sync::Arc;

use thiserror::Error;

use crate::strmatch::Signature;
use crate::tier::MatcherTier;

pub use chain::ChainError;
pub use config::{Chain, FallbackConfig, FormatChoice, HopConfig, ParseConfig, Settings};
#[cfg(test)]
#[allow(
    unused_imports,
    reason = "its test sits behind the stock parser features"
)]
pub(crate) use driver::gate_pays;
pub use driver::{Batch, CompileError, Outcome, ParsePlan, ParserCounts, SourceState, Status};
#[cfg(feature = "parse-grok")]
pub(crate) use driver::{Counter, counter};
#[cfg(feature = "framing")]
pub use frame::{
    ContainerConfig, ContainerFormat, JsonPointer, JsonPointerConfig, PointerError, StreamConfig,
    StreamSplit,
};
pub use frame::{Frame, FrameState, FramingConfig, MultiLineConfig};
pub use number::Number;
pub use sink::{FieldSink, Fields, PrefixStack, SinkMark};
pub use trace::{Event, Failure, Input, Step, Trace};

/// How a parser saw a value. The sink decides what to store it as.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Hint {
    /// Text, kept as written.
    Text,
    /// A whole number.
    Int,
    /// A number with a fraction or exponent.
    Float,
    /// `true` or `false`.
    Bool,
    /// An IPv4 or IPv6 address.
    Ip,
    /// A timestamp, kept as written.
    Timestamp,
    /// A JSON value, kept as written.
    Json,
}

/// One field value: bytes from the input, or owned when the parser had to
/// unescape them, plus how the parser saw them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldValue<'a> {
    /// The value's bytes.
    pub bytes: Cow<'a, [u8]>,
    /// How the parser saw them.
    pub hint: Hint,
}

impl<'a> FieldValue<'a> {
    /// A borrowed value.
    #[must_use]
    pub const fn borrowed(bytes: &'a [u8], hint: Hint) -> Self {
        Self {
            bytes: Cow::Borrowed(bytes),
            hint,
        }
    }

    /// An owned value, for bytes the parser had to rewrite.
    #[must_use]
    pub const fn owned(bytes: Vec<u8>, hint: Hint) -> Self {
        Self {
            bytes: Cow::Owned(bytes),
            hint,
        }
    }

    /// The same value with its bytes owned, so it outlives the input.
    #[must_use]
    pub fn into_owned(self) -> FieldValue<'static> {
        FieldValue {
            bytes: Cow::Owned(self.bytes.into_owned()),
            hint: self.hint,
        }
    }
}

/// What a parser made of its input.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Parsed {
    /// Not this parser's input. It wrote no field.
    NoMatch,
    /// Consumed it all. Nothing nested.
    Done,
    /// Read an envelope. `span` is the next hop's input, a range of the same
    /// buffer. `hint` names its format when the envelope says, for a caller
    /// running the parser itself: the driver picks by the chain alone.
    Body {
        /// The body's range within this parser's input.
        span: Range<usize>,
        /// The body's format, when the envelope says.
        hint: Option<&'static str>,
    },
}

/// A parser that accepted its input and then found it broken.
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum ParseError {
    /// The input breaks the format at `offset`.
    #[error("malformed at byte {offset}: {reason}")]
    Malformed {
        /// Byte offset into the parser's input.
        offset: usize,
        /// What is wrong there.
        reason: &'static str,
    },
    /// A bound was hit: a nesting depth, a field count, a work budget.
    #[error("limit reached: {what}")]
    Limit {
        /// Which bound.
        what: &'static str,
    },
    /// A framed record over its framing's `max_bytes`, skipped without
    /// being held.
    #[error("a frame of {len} bytes is over max_bytes {max}")]
    FrameTooLong {
        /// Its length: its octet count, or the bytes read of it when its end
        /// hadn't arrived.
        len: u64,
        /// The cap.
        max: usize,
    },
    /// Any other failure, from a parser outside this crate.
    #[error(transparent)]
    Other(Box<dyn std::error::Error + Send + Sync>),
}

/// A format parser.
///
/// The contract every implementation keeps, and the driver relies on:
/// - `NoMatch` means nothing was written to the sink.
/// - A span the parser accepts is never one its signature rules out.
/// - A `Body` span lies within the input.
/// - Every prefix it pushes is popped before it returns, on an error too.
/// - Its work is at most proportional to its input.
pub trait Parser: Send + Sync {
    /// Registry name: a format (`syslog`), or a format and an instance
    /// (`grok:firewall`). See [`valid_parser_name`].
    fn name(&self) -> &str;

    /// The slowest tier anything in this parser runs on.
    fn tier(&self) -> MatcherTier;

    /// The cheapest test that rules a span out.
    fn signature(&self) -> &Signature;

    /// What a line costs, measured on the reference host, or `None` where
    /// nothing was. A stock parser has its own row in the table.
    fn cost(&self) -> Option<crate::cost::Cost> {
        crate::cost::of(&format!("parser.{}", self.name()))
    }

    /// [`Parser::parse`] for a [`Batch`]: the parser's own counts go to
    /// `counts`, and the batch adds them when it publishes. The default
    /// counts at once, as `parse` does.
    ///
    /// # Errors
    ///
    /// As [`Parser::parse`].
    fn parse_counted<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
        counts: &mut ParserCounts,
    ) -> Result<Parsed, ParseError> {
        let _ = counts;
        self.parse(input, out)
    }

    /// Whether `auto` may pick this parser by its signature. A parser whose
    /// signature has no literal is never detected, whatever this returns.
    fn detectable(&self) -> bool {
        !self.signature().is_literal_free()
    }

    /// Parse `input`, writing fields into `out`.
    ///
    /// # Errors
    ///
    /// [`ParseError`] when the input is this parser's but is broken. Fields
    /// written before the error are rolled back by the driver.
    fn parse<'a>(&self, input: &'a [u8], out: &mut dyn FieldSink<'a>)
    -> Result<Parsed, ParseError>;
}

/// Why a parser could not be built from its name and settings.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ResolveError {
    /// No parser has this name.
    #[error("no parser named {0:?}")]
    Unknown(String),
    /// A parser name that breaks [`valid_parser_name`].
    #[error("parser name {0:?} is not `format` or `format:instance` in lower case")]
    BadName(String),
    /// The settings do not fit the parser.
    #[error("parser {name:?}: {reason}")]
    Settings {
        /// The parser's name.
        name: String,
        /// What is wrong with the settings.
        reason: String,
    },
}

/// Turns a format name and its settings into a parser.
///
/// An application's registry implements this. [`Parsers`] is the plain
/// in-memory one.
pub trait Resolve {
    /// The parser named `name`, built with `settings` when it takes any.
    ///
    /// It may build a new parser on every call. The plan keeps each `Arc` it
    /// gets, so a configured instance and a candidate can share a name, and
    /// their counters, which carry the same labels, add up.
    ///
    /// # Errors
    ///
    /// [`ResolveError`] when there is no such parser or the settings don't fit.
    fn resolve(
        &self,
        name: &str,
        settings: Option<&serde_json::Value>,
    ) -> Result<Arc<dyn Parser>, ResolveError>;

    /// The parsers `auto` and `auto*` choose from, in registration order.
    fn candidates(&self) -> Vec<Arc<dyn Parser>>;
}

/// Ready-built parsers by name. Settings are refused, since nothing here
/// builds a parser.
#[derive(Default, Clone)]
pub struct Parsers {
    by_name: HashMap<String, Arc<dyn Parser>>,
    order: Vec<Arc<dyn Parser>>,
}

impl std::fmt::Debug for Parsers {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_list()
            .entries(self.order.iter().map(|p| p.name()))
            .finish()
    }
}

impl Parsers {
    /// An empty set.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add `parser` under its own name, replacing any parser of that name.
    ///
    /// # Errors
    ///
    /// [`ResolveError::BadName`] when the name breaks [`valid_parser_name`].
    pub fn register(&mut self, parser: Arc<dyn Parser>) -> Result<(), ResolveError> {
        let name = parser.name().to_owned();
        if !valid_parser_name(&name) {
            return Err(ResolveError::BadName(name));
        }
        if let Some(old) = self.by_name.insert(name, Arc::clone(&parser)) {
            self.order.retain(|p| !Arc::ptr_eq(p, &old));
        }
        self.order.push(parser);
        Ok(())
    }
}

/// `true` for `format` or `format:instance`: a format of `[a-z][a-z0-9_]*`,
/// and an instance of `[a-z0-9_.-]+`. The chain's own words, `auto`, `each`,
/// `field`, `raw` and `reject`, are no format.
#[must_use]
pub fn valid_parser_name(name: &str) -> bool {
    let (format, instance) = match name.split_once(':') {
        Some((f, i)) => (f, Some(i)),
        None => (name, None),
    };
    let mut fb = format.bytes();
    let format_ok = fb.next().is_some_and(|b| b.is_ascii_lowercase())
        && fb.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
        && !chain::RESERVED.contains(&format);
    let instance_ok = instance.is_none_or(|i| {
        !i.is_empty()
            && i.bytes().all(|b| {
                b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.' | b'-')
            })
    });
    format_ok && instance_ok
}

impl Resolve for Parsers {
    fn resolve(
        &self,
        name: &str,
        settings: Option<&serde_json::Value>,
    ) -> Result<Arc<dyn Parser>, ResolveError> {
        let parser = self
            .by_name
            .get(name)
            .ok_or_else(|| ResolveError::Unknown(name.to_owned()))?;
        if settings.is_some() {
            return Err(ResolveError::Settings {
                name: name.to_owned(),
                reason: "this parser takes no settings".to_owned(),
            });
        }
        Ok(Arc::clone(parser))
    }

    fn candidates(&self) -> Vec<Arc<dyn Parser>> {
        self.order.clone()
    }
}

#[cfg(test)]
mod tests;