grippo 0.2.2

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
// 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.
//! `%{*k}` and `%{&k}` are a reference pair: the `*` value names a field and
//! the `&` value fills it. The whole input must be consumed. Append order
//! (`/n`) is refused when the pattern compiles.

use std::ops::Range;

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,
    /// A `%{*k}` with no `%{&k}`, or the other way round, or either twice.
    #[error("dissect: reference key {0:?} needs exactly one `*` and one `&`")]
    Unpaired(String),
}

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

/// What a key's value is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Role {
    /// A field's value, under the key's name.
    Field,
    /// The name of the field its `&` pair fills.
    RefName,
    /// The value of the field named by the `*` key at this index.
    RefValue(usize),
}

/// 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, an unpaired reference, an ordered append, or no key.
    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);
        }
        pair_references(&mut keys)?;
        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> {
    let (rest, pad) = body.strip_suffix("->").map_or((body, false), |b| (b, true));
    let (rest, append, skip, role) = match rest.as_bytes().first() {
        Some(b'+') => (&rest[1..], true, false, Role::Field),
        Some(b'?') => (&rest[1..], false, true, Role::Field),
        Some(b'*') => (&rest[1..], false, false, Role::RefName),
        Some(b'&') => (&rest[1..], false, false, Role::RefValue(usize::MAX)),
        _ => (rest, false, false, Role::Field),
    };
    let named_ref = role != Role::Field && rest.is_empty();
    if named_ref || rest.contains(['*', '&', '/', '+', '?']) {
        return Err(DissectError::Modifier(body.to_owned()));
    }
    Ok(Key {
        name: (!skip && !rest.is_empty()).then(|| rest.to_owned()),
        append,
        pad,
        role,
        then: Vec::new(),
    })
}

/// Points each `&` key at its `*` key: one of each per reference name.
fn pair_references(keys: &mut [Key]) -> Result<(), DissectError> {
    for i in 0..keys.len() {
        if keys[i].role == Role::Field {
            continue;
        }
        let name = keys[i].name.clone().unwrap_or_default();
        let count = |role: fn(Role) -> bool| {
            keys.iter()
                .filter(|k| role(k.role) && k.name.as_deref() == Some(name.as_str()))
                .count()
        };
        let names = count(|r| r == Role::RefName);
        let values = count(|r| matches!(r, Role::RefValue(_)));
        if names != 1 || values != 1 {
            return Err(DissectError::Unpaired(name));
        }
        if matches!(keys[i].role, Role::RefValue(_)) {
            let at = keys
                .iter()
                .position(|k| k.role == Role::RefName && k.name == keys[i].name)
                .unwrap_or_else(|| unreachable!("invariant: counted one `*` key above"));
            keys[i].role = Role::RefValue(at);
        }
    }
    Ok(())
}

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

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

    fn signature(&self) -> &Signature {
        &self.signature
    }

    fn hands_on_body(&self) -> bool {
        false
    }

    /// A dissect line has no escape: a value goes in as it is, and the
    /// re-parse a write-back runs refuses one that holds the delimiter after it.
    fn escape_value(
        &self,
        _input: &[u8],
        _field: usize,
        at: Range<usize>,
        value: &[u8],
        out: &mut Vec<u8>,
    ) -> Option<Range<usize>> {
        out.extend_from_slice(value);
        Some(at)
    }

    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.clone()];
            match key.role {
                Role::Field => {}
                Role::RefName => continue,
                Role::RefValue(at) => {
                    let named = String::from_utf8_lossy(&line[spans[at].clone()]);
                    if !named.is_empty() {
                        let field = crate::path::key_part(named);
                        out.field(&field, FieldValue::borrowed(value, Hint::Text));
                    }
                    continue;
                }
            }
            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 a_dotted_pattern_name_is_a_nested_path() {
        let d = dissect("%{a.b} %{c}");
        for (name, value) in [("a.b", "1"), ("c", "2")] {
            let mut out = Fields::new();
            d.parse(b"1 2", &mut out).unwrap();
            let got = out
                .get(name)
                .map(|v| String::from_utf8_lossy(&v.bytes).into_owned());
            assert_eq!(got.as_deref(), Some(value), "{name}");
            #[cfg(feature = "record")]
            {
                use crate::record::Record;
                let keys: Vec<_> = crate::path::keys(name).collect();
                let at = (&out).find(&keys[..]).unwrap();
                assert_eq!((&out).text(at).unwrap(), value, "{name}");
            }
        }
    }

    #[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"));
    }

    /// The `*` value names a field and its `&` pair fills it, as Elastic's
    /// dissect reads a reference pair.
    #[test]
    fn a_reference_pair_names_and_fills_a_field() {
        let rows: &[(&str, &str, &[(&str, &str)])] = &[
            (
                "[%{ts}] [%{*p}:%{&p}]",
                "[1] [user:bob]",
                &[("ts", "1"), ("user", "bob")],
            ),
            (
                "%{*a->} %{&a} %{*b}=%{&b}",
                "k   v x=y",
                &[("k", "v"), ("x", "y")],
            ),
            ("%{&p}@%{*p}", "bob@user", &[("user", "bob")]),
            ("%{*p}=%{&p}", "a.b=1", &[(r#"["a.b"]"#, "1")]),
            ("%{*p}=%{&p} %{m}", "=1 rest", &[("m", "rest")]),
        ];
        for &(pattern, line, want) in rows {
            let (p, f) = run(&dissect(pattern), line);
            assert_eq!(p, Parsed::Done, "{pattern}");
            let want: Vec<(String, String)> = want
                .iter()
                .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
                .collect();
            assert_eq!(f, want, "{pattern} on {line}");
        }
    }

    #[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/2} %{b}"), Err(DissectError::Modifier(_))));
        assert!(matches!(
            new("%{+*a} %{&a}"),
            Err(DissectError::Modifier(_))
        ));
        assert!(matches!(new("%{*} %{&}"), Err(DissectError::Modifier(_))));
        assert!(matches!(new("%{*a} %{b}"), Err(DissectError::Unpaired(_))));
        assert!(matches!(new("%{&a} %{b}"), Err(DissectError::Unpaired(_))));
        assert!(matches!(
            new("%{*a} %{&a} %{*a}"),
            Err(DissectError::Unpaired(_))
        ));
        assert!(matches!(new("no keys"), Err(DissectError::NoKey)));
    }

    proptest::proptest! {
        /// A value without the delimiter after it, written in as it is,
        /// reads back as written.
        #[test]
        fn a_written_value_reads_back(value in "[a-z \\\"=]{0,10}") {
            let d = dissect("%{a}|%{b}|%{c}");
            let line = "1|x|2";
            let mut text = Vec::new();
            let span = d.escape_value(line.as_bytes(), 1, 2..3, value.as_bytes(), &mut text).unwrap();
            let after = [&line.as_bytes()[..span.start], &text, &line.as_bytes()[span.end..]].concat();
            let (_, f) = run(&d, std::str::from_utf8(&after).unwrap());
            let want = [("a", "1"), ("b", value.as_str()), ("c", "2")];
            let want: Vec<(String, String)> =
                want.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
            proptest::prop_assert_eq!(f, want);
        }
    }
}