grippo 0.2.3

Parse, match and scrub data faster and more efficiently.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
// 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::{
    CarriageReturns, ContainerConfig, ContainerFormat, JsonPointer, JsonPointerConfig,
    PointerError, StreamConfig, StreamEvent, StreamFramer, 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,
        }
    }
}

/// The most bytes a stock decoding parser writes for one input, unless built
/// with another cap: 16 MiB.
pub const DECODE_MAX_BYTES: usize = 16 << 20;

/// Bytes a decoding parser made from its input, for the next hop to read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Decoded {
    bytes: Vec<u8>,
    hint: Option<&'static str>,
}

impl Decoded {
    /// `bytes`, with no hint of their format.
    #[must_use]
    pub const fn new(bytes: Vec<u8>) -> Self {
        Self { bytes, hint: None }
    }

    /// The same bytes, with the format they hold named.
    #[must_use]
    pub const fn with_hint(mut self, hint: &'static str) -> Self {
        self.hint = Some(hint);
        self
    }

    /// The decoded bytes.
    #[must_use]
    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Their format, when the decoder knows it.
    #[must_use]
    pub const fn hint(&self) -> Option<&'static str> {
        self.hint
    }

    /// The decoded bytes, owned.
    #[must_use]
    pub fn into_vec(self) -> Vec<u8> {
        self.bytes
    }
}

/// 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>,
    },
    /// Decoded its input into bytes it owns, such as base64 text or a gzip
    /// stream: they are the next hop's input. It wrote no field.
    Decoded(Decoded),
}

/// 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 in the stream, a counted frame's header and a line's
        /// delimiter included. It is raised when the frame ends, or at the
        /// end of input with the bytes read.
        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. A `Decoded` body is bytes it owns.
/// - Every prefix it pushes is popped before it returns, on an error too.
/// - Its work is at most proportional to its input, or for a decoder to its
///   output, which its cap bounds.
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 this parser decodes its input and hands on bytes it owns, as
    /// [`Parsed::Decoded`], in place of writing fields. A layered record puts
    /// what such a layer hands on at its own place, with no key of its own.
    fn decodes(&self) -> bool {
        false
    }

    /// 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()
    }

    /// Whether [`Parser::parse`] can return [`Parsed::Body`]. A parser that
    /// says `false` never hands on a body, so a layer plan rejects a body hop
    /// after it. The default is `true`, which rejects nothing.
    fn hands_on_body(&self) -> bool {
        true
    }

    /// Appends `value` to `out` as this format writes field `field` of
    /// `input`, a record it read, in place of `at`: the bytes it lent for
    /// that field's value, or ones this method wrote for its old value.
    /// Returns the range of `input` the appended bytes replace, `at` or a
    /// range around it such as `at` with its quotes. An empty `input` asks
    /// for the value as written with no record around it.
    ///
    /// `None`, with `out` as it was, when the format can't hold `value`
    /// there. The default writes `value` as it is over `at`, for a format
    /// with no escape, and leaves the write-back's re-parse to refuse a value
    /// 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>> {
        let _ = (input, field);
        out.extend_from_slice(value);
        Some(at)
    }

    /// 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>;
}

/// `at` widened over its quotes, when a byte `quote` accepts sits on each
/// side of it and both are the same.
#[cfg(any(feature = "parse-kv", feature = "parse-csv", feature = "parse-gelf"))]
pub(crate) fn quoted_span(
    input: &[u8],
    at: &Range<usize>,
    quote: impl Fn(u8) -> bool,
) -> Option<Range<usize>> {
    let open = *input.get(at.start.checked_sub(1)?)?;
    (quote(open) && input.get(at.end) == Some(&open)).then(|| at.start - 1..at.end + 1)
}

/// 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 grippo format whose feature this build left out.
    #[error("{name:?} needs grippo's `{feature}` feature, which this build left out")]
    FeatureOff {
        /// The name asked for.
        name: String,
        /// The feature that builds it.
        feature: &'static str,
    },
    /// 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,
    },
}

/// Each grippo format and decoder name, the feature that builds it, and
/// whether this build has it.
const FORMAT_FEATURES: &[(&str, &str, bool)] = &[
    ("cef", "parse-cef", cfg!(feature = "parse-cef")),
    ("syslog", "parse-syslog", cfg!(feature = "parse-syslog")),
    (
        "syslog_nopri",
        "parse-syslog",
        cfg!(feature = "parse-syslog"),
    ),
    ("leef", "parse-leef", cfg!(feature = "parse-leef")),
    ("ndjson", "parse-ndjson", cfg!(feature = "parse-ndjson")),
    ("gelf", "parse-gelf", cfg!(feature = "parse-gelf")),
    ("csv", "parse-csv", cfg!(feature = "parse-csv")),
    ("kv", "parse-kv", cfg!(feature = "parse-kv")),
    ("logfmt", "parse-kv", cfg!(feature = "parse-kv")),
    ("dissect", "parse-dissect", cfg!(feature = "parse-dissect")),
    ("cri", "parse-cri", cfg!(feature = "parse-cri")),
    ("xml", "parse-xml", cfg!(feature = "parse-xml")),
    ("uri", "parse-uri", cfg!(feature = "parse-uri")),
    ("query", "parse-query", cfg!(feature = "parse-query")),
    (
        "prometheus",
        "parse-prometheus",
        cfg!(feature = "parse-prometheus"),
    ),
    ("aws_alb", "parse-cloud", cfg!(feature = "parse-cloud")),
    ("aws_nlb", "parse-cloud", cfg!(feature = "parse-cloud")),
    ("aws_elb", "parse-cloud", cfg!(feature = "parse-cloud")),
    ("aws_s3", "parse-cloud", cfg!(feature = "parse-cloud")),
    ("aws_vpc_flow", "parse-cloud", cfg!(feature = "parse-cloud")),
    ("ini", "parse-ini", cfg!(feature = "parse-ini")),
    ("properties", "parse-ini", cfg!(feature = "parse-ini")),
    ("dotenv", "parse-ini", cfg!(feature = "parse-ini")),
    ("yaml", "parse-yaml", cfg!(feature = "parse-yaml")),
    ("toml", "parse-toml", cfg!(feature = "parse-toml")),
    ("http", "parse-http", cfg!(feature = "parse-http")),
    ("headers", "parse-http", cfg!(feature = "parse-http")),
    ("msgpack", "parse-msgpack", cfg!(feature = "parse-msgpack")),
    (
        "protobuf",
        "parse-protobuf",
        cfg!(feature = "parse-protobuf"),
    ),
    ("otlp", "parse-otlp", cfg!(feature = "parse-otlp")),
    ("base64", "decode-base64", cfg!(feature = "decode-base64")),
    (
        "base64url",
        "decode-base64",
        cfg!(feature = "decode-base64"),
    ),
    ("hex", "decode-hex", cfg!(feature = "decode-hex")),
    ("gzip", "decode-gzip", cfg!(feature = "decode-gzip")),
    ("zlib", "decode-zlib", cfg!(feature = "decode-zlib")),
    ("zstd", "decode-zstd", cfg!(feature = "decode-zstd")),
    ("snappy", "decode-snappy", cfg!(feature = "decode-snappy")),
    (
        "snappy_raw",
        "decode-snappy",
        cfg!(feature = "decode-snappy"),
    ),
];

/// The feature that builds the grippo format `name` names, when this build
/// left it out. A `format:instance` name is read by its format.
#[must_use]
pub fn missing_feature(name: &str) -> Option<&'static str> {
    let format = name.split_once(':').map_or(name, |(f, _)| f);
    FORMAT_FEATURES
        .iter()
        .find(|(n, _, _)| *n == format)
        .and_then(|&(_, feature, on)| (!on).then_some(feature))
}

impl ResolveError {
    /// The error for a name no registry holds: [`ResolveError::FeatureOff`]
    /// when it's a grippo format this build left out, else
    /// [`ResolveError::Unknown`]. A registry of your own returns this too.
    #[must_use]
    pub fn unknown(name: &str) -> Self {
        missing_feature(name).map_or_else(
            || Self::Unknown(name.to_owned()),
            |feature| Self::FeatureOff {
                name: name.to_owned(),
                feature,
            },
        )
    }
}

/// 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))?;
        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;