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
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
// Project:   grippo
// File:      src/format/protobuf.rs
// Purpose:   The protobuf parser: one message an input, read by a descriptor set
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! One protobuf message an input, read by a descriptor set from config.
//!
//! Fields are named by their field names as `ndjson` names a JSON record's: a
//! nested message joins its parent with `.`, and a repeated field writes each
//! element under its name.
//!
//! Protobuf is binary, so it goes through prost-reflect rather than a walker
//! of grippo's own. The descriptor set is the bytes `protoc
//! --descriptor_set_out` writes, given in config. Every value is copied: a
//! string, bytes as their raw bytes, an enum as its value's name or, when the
//! descriptor has none, its number. A map field writes `<field>.<key>` in key
//! order. A field the input leaves at its default writes nothing, and a field
//! the descriptor doesn't know is dropped. Nesting past 64 containers, the
//! root counted, is `ParseError::Limit`.
//!
//! With `parse-otlp`, [`Protobuf::otlp`] reads an OTLP logs message by the
//! OTLP schema built in, compiled from opentelemetry-proto v1.11.1. It writes
//! the names and values OTLP/JSON gives: `body.stringValue`, `traceId` in
//! hex, `severityNumber` as its number.

use std::borrow::Cow;

use prost_reflect::{DescriptorPool, DynamicMessage, Kind, MapKey, MessageDescriptor, Value};
use thiserror::Error;

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

/// Why a [`Protobuf`] parser could not be built.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ProtobufError {
    /// The descriptor set doesn't decode, or its files don't link.
    #[error("a descriptor set that doesn't decode: {0}")]
    Descriptor(String),
    /// The descriptor set has no message of this full name.
    #[error("no message {0:?} in the descriptor set")]
    NoMessage(String),
}

/// The protobuf parser, registered as `protobuf`, or `otlp` for the OTLP
/// schema built in.
#[derive(Debug, Clone)]
pub struct Protobuf {
    message: MessageDescriptor,
    naming: Naming,
    signature: Signature,
}

/// How field names and values are written.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Naming {
    /// Field names as declared, bytes raw, an enum by its value's name.
    Declared,
    /// As OTLP/JSON writes them: JSON names, bytes in hex, an enum by number.
    OtlpJson,
}

/// The OTLP common, resource and logs schema, compiled by protox from the
/// files under `proto/opentelemetry-proto`.
#[cfg(feature = "parse-otlp")]
pub(crate) const OTLP_LOGS: &[u8] = include_bytes!("otlp_logs.binpb");

/// [`OTLP_LOGS`] decoded once.
#[cfg(feature = "parse-otlp")]
pub(crate) fn otlp_pool() -> &'static DescriptorPool {
    static POOL: std::sync::LazyLock<DescriptorPool> = std::sync::LazyLock::new(|| {
        DescriptorPool::decode(OTLP_LOGS)
            .unwrap_or_else(|_| unreachable!("invariant: a test decodes the built-in OTLP schema"))
    });
    &POOL
}

impl Protobuf {
    /// A parser for the message `message`, a full name such as
    /// `acme.v1.Event`, from the encoded `FileDescriptorSet` `descriptors`.
    ///
    /// # Errors
    ///
    /// [`ProtobufError`] when the set doesn't decode or holds no such message.
    ///
    /// # Panics
    ///
    /// Never: an empty signature always builds.
    pub fn new(descriptors: &[u8], message: &str) -> Result<Self, ProtobufError> {
        let pool = DescriptorPool::decode(descriptors)
            .map_err(|e| ProtobufError::Descriptor(e.to_string()))?;
        let message = pool
            .get_message_by_name(message)
            .ok_or_else(|| ProtobufError::NoMessage(message.to_owned()))?;
        Ok(Self::of(message, Naming::Declared))
    }

    /// A parser for the OTLP message `message`, such as
    /// `opentelemetry.proto.logs.v1.LogRecord`, writing OTLP/JSON's names and
    /// values. It is registered as `otlp`.
    ///
    /// # Errors
    ///
    /// [`ProtobufError::NoMessage`] for a message the OTLP logs schema lacks.
    #[cfg(feature = "parse-otlp")]
    pub fn otlp(message: &str) -> Result<Self, ProtobufError> {
        let found = otlp_pool()
            .get_message_by_name(message)
            .ok_or_else(|| ProtobufError::NoMessage(message.to_owned()))?;
        Ok(Self::of(found, Naming::OtlpJson))
    }

    fn of(message: MessageDescriptor, naming: Naming) -> Self {
        let signature = Signature::builder()
            .build()
            .unwrap_or_else(|_| unreachable!("invariant: an empty signature always builds"));
        Self {
            message,
            naming,
            signature,
        }
    }

    /// The full name of the message it reads.
    #[must_use]
    pub fn message(&self) -> &str {
        self.message.full_name()
    }
}

const fn owned(text: String, hint: Hint) -> FieldValue<'static> {
    FieldValue::owned(text.into_bytes(), hint)
}

fn float(f: f64) -> FieldValue<'static> {
    if f.is_finite() {
        owned(format!("{f:?}"), Hint::Float)
    } else {
        owned(f.to_string(), Hint::Text)
    }
}

fn map_key(key: &MapKey) -> String {
    match key {
        MapKey::Bool(b) => b.to_string(),
        MapKey::I32(n) => n.to_string(),
        MapKey::I64(n) => n.to_string(),
        MapKey::U32(n) => n.to_string(),
        MapKey::U64(n) => n.to_string(),
        MapKey::String(s) => s.clone(),
    }
}

/// `bytes` as lower-case hex.
fn hex(bytes: &[u8]) -> Vec<u8> {
    const DIGITS: &[u8; 16] = b"0123456789abcdef";
    bytes
        .iter()
        .flat_map(|b| [DIGITS[usize::from(b >> 4)], DIGITS[usize::from(b & 15)]])
        .collect()
}

/// Write `value`, of a field of kind `kind`, as the next value.
fn walk(
    tree: &mut Tree<'_, '_>,
    value: &Value,
    kind: &Kind,
    naming: Naming,
) -> Result<(), ParseError> {
    match value {
        Value::Bool(b) => tree.scalar(owned(b.to_string(), Hint::Bool))?,
        Value::I32(n) => tree.scalar(owned(n.to_string(), Hint::Int))?,
        Value::I64(n) => tree.scalar(owned(n.to_string(), Hint::Int))?,
        Value::U32(n) => tree.scalar(owned(n.to_string(), Hint::Int))?,
        Value::U64(n) => tree.scalar(owned(n.to_string(), Hint::Int))?,
        Value::F32(f) => tree.scalar(float(f64::from(*f)))?,
        Value::F64(f) => tree.scalar(float(*f))?,
        Value::String(s) => tree.scalar(owned(s.clone(), Hint::Text))?,
        Value::Bytes(b) if naming == Naming::OtlpJson => {
            tree.scalar(FieldValue::owned(hex(b), Hint::Text))?;
        }
        Value::Bytes(b) => tree.scalar(FieldValue::owned(b.to_vec(), Hint::Text))?,
        Value::EnumNumber(n) => {
            let name = match kind {
                Kind::Enum(e) if naming == Naming::Declared => {
                    e.get_value(*n).map(|v| v.name().to_owned())
                }
                _ => None,
            };
            let value =
                name.map_or_else(|| owned(n.to_string(), Hint::Int), |n| owned(n, Hint::Text));
            tree.scalar(value)?;
        }
        Value::Message(m) => {
            tree.open_map()?;
            message(tree, m, naming)?;
            tree.close();
        }
        Value::List(items) => {
            tree.open_list()?;
            for item in items {
                walk(tree, item, kind, naming)?;
            }
            tree.close();
        }
        Value::Map(entries) => {
            let value_kind = match kind {
                Kind::Message(entry) => entry.map_entry_value_field().kind(),
                other => other.clone(),
            };
            let mut sorted: Vec<(&MapKey, &Value)> = entries.iter().collect();
            sorted.sort_by(|a, b| a.0.cmp(b.0));
            tree.open_map()?;
            for (key, item) in sorted {
                tree.key(Cow::Owned(map_key(key)));
                walk(tree, item, &value_kind, naming)?;
            }
            tree.close();
        }
    }
    Ok(())
}

fn message(tree: &mut Tree<'_, '_>, m: &DynamicMessage, naming: Naming) -> Result<(), ParseError> {
    for (field, value) in m.fields() {
        let name = match naming {
            Naming::Declared => field.name(),
            Naming::OtlpJson => field.json_name(),
        };
        tree.key(Cow::Borrowed(name));
        walk(tree, value, &field.kind(), naming)?;
    }
    Ok(())
}

impl Parser for Protobuf {
    fn hands_on_body(&self) -> bool {
        false
    }

    fn name(&self) -> &'static str {
        match self.naming {
            Naming::Declared => "protobuf",
            Naming::OtlpJson => "otlp",
        }
    }

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

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

    fn parse<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Parsed, ParseError> {
        let m = DynamicMessage::decode(self.message.clone(), input).map_err(|_| {
            ParseError::Malformed {
                offset: 0,
                reason: "protobuf that doesn't decode as the configured message",
            }
        })?;
        let mut tree = Tree::new(out, input.len());
        let walked = tree
            .open_map()
            .and_then(|()| message(&mut tree, &m, self.naming));
        tree.finish(walked)?;
        Ok(Parsed::Done)
    }
}

#[cfg(test)]
mod tests {
    use prost_reflect::prost::Message;
    use prost_reflect::prost_types::field_descriptor_proto::{Label, Type};
    use prost_reflect::prost_types::{
        DescriptorProto, EnumDescriptorProto, EnumValueDescriptorProto, FieldDescriptorProto,
        FileDescriptorProto, FileDescriptorSet, MessageOptions,
    };

    use super::*;
    use crate::parse::Fields;

    fn field(
        name: &str,
        number: i32,
        ty: Type,
        label: Label,
        type_name: &str,
    ) -> FieldDescriptorProto {
        FieldDescriptorProto {
            name: Some(name.to_owned()),
            number: Some(number),
            r#type: Some(ty as i32),
            label: Some(label as i32),
            type_name: (!type_name.is_empty()).then(|| type_name.to_owned()),
            ..FieldDescriptorProto::default()
        }
    }

    /// `acme.Event` and the types it uses, as an encoded descriptor set.
    fn descriptors() -> Vec<u8> {
        use Label::{Optional, Repeated};
        let entry = DescriptorProto {
            name: Some("CountsEntry".to_owned()),
            field: vec![
                field("key", 1, Type::String, Optional, ""),
                field("value", 2, Type::Int32, Optional, ""),
            ],
            options: Some(MessageOptions {
                map_entry: Some(true),
                ..MessageOptions::default()
            }),
            ..DescriptorProto::default()
        };
        let event = DescriptorProto {
            name: Some("Event".to_owned()),
            field: vec![
                field("host", 1, Type::String, Optional, ""),
                field("n", 2, Type::Int64, Optional, ""),
                field("tags", 3, Type::String, Repeated, ""),
                field("inner", 4, Type::Message, Optional, ".acme.Inner"),
                field(
                    "counts",
                    5,
                    Type::Message,
                    Repeated,
                    ".acme.Event.CountsEntry",
                ),
                field("level", 6, Type::Enum, Optional, ".acme.Level"),
                field("raw", 7, Type::Bytes, Optional, ""),
                field("ratio", 8, Type::Double, Optional, ""),
                field("ok", 9, Type::Bool, Optional, ""),
                field("levels", 10, Type::Enum, Repeated, ".acme.Level"),
            ],
            nested_type: vec![entry],
            ..DescriptorProto::default()
        };
        let inner = DescriptorProto {
            name: Some("Inner".to_owned()),
            field: vec![
                field("a_b", 1, Type::String, Optional, ""),
                field("child", 2, Type::Message, Optional, ".acme.Inner"),
            ],
            ..DescriptorProto::default()
        };
        let level = EnumDescriptorProto {
            name: Some("Level".to_owned()),
            value: ["UNSET", "INFO", "WARN"]
                .iter()
                .zip(0..)
                .map(|(name, number)| EnumValueDescriptorProto {
                    name: Some((*name).to_owned()),
                    number: Some(number),
                    ..EnumValueDescriptorProto::default()
                })
                .collect(),
            ..EnumDescriptorProto::default()
        };
        let file = FileDescriptorProto {
            name: Some("acme.proto".to_owned()),
            package: Some("acme".to_owned()),
            message_type: vec![event, inner],
            enum_type: vec![level],
            syntax: Some("proto3".to_owned()),
            ..FileDescriptorProto::default()
        };
        FileDescriptorSet { file: vec![file] }.encode_to_vec()
    }

    fn parser() -> Protobuf {
        Protobuf::new(&descriptors(), "acme.Event").unwrap()
    }

    fn event(set: &[(&str, Value)]) -> Vec<u8> {
        let desc = parser().message;
        let mut m = DynamicMessage::new(desc);
        for (name, value) in set {
            m.set_field_by_name(name, value.clone());
        }
        m.encode_to_vec()
    }

    fn nested(levels: usize) -> Vec<u8> {
        let pool = DescriptorPool::decode(descriptors().as_slice()).unwrap();
        let inner = pool.get_message_by_name("acme.Inner").unwrap();
        let mut m = DynamicMessage::new(inner.clone());
        m.set_field_by_name("a_b", Value::String("leaf".to_owned()));
        for _ in 0..levels {
            let mut up = DynamicMessage::new(inner.clone());
            up.set_field_by_name("child", Value::Message(m));
            m = up;
        }
        event(&[("inner", Value::Message(m))])
    }

    /// The fields an input writes, or the error it gives.
    type Want<'a> = Result<Vec<(&'a str, &'a [u8], Hint)>, &'a str>;

    #[test]
    fn messages_read_into_fields_or_fail_whole() {
        use Hint::{Bool, Float, Int, Text};
        let pool = DescriptorPool::decode(descriptors().as_slice()).unwrap();
        let inner_desc = pool.get_message_by_name("acme.Inner").unwrap();
        let mut inner = DynamicMessage::new(inner_desc);
        inner.set_field_by_name("a_b", Value::String("x".to_owned()));
        let counts = Value::Map(
            [("b", 2), ("x.y", 3), ("a", 1)]
                .into_iter()
                .map(|(k, v)| (MapKey::String(k.to_owned()), Value::I32(v)))
                .collect(),
        );
        let full = event(&[
            ("host", Value::String("web01".to_owned())),
            ("n", Value::I64(-7)),
            (
                "tags",
                Value::List(vec![
                    Value::String("a".to_owned()),
                    Value::String("b".to_owned()),
                ]),
            ),
            ("inner", Value::Message(inner)),
            ("counts", counts),
            ("level", Value::EnumNumber(2)),
            ("raw", Value::Bytes(vec![0, 255].into())),
            ("ratio", Value::F64(0.5)),
            ("ok", Value::Bool(true)),
            (
                "levels",
                Value::List(vec![Value::EnumNumber(1), Value::EnumNumber(9)]),
            ),
        ]);
        let mut truncated = full.clone();
        truncated.truncate(full.len() - 3);
        let cases: Vec<(Vec<u8>, Want<'_>)> = vec![
            (
                full,
                Ok(vec![
                    ("outer.host", b"web01", Text),
                    ("outer.n", b"-7", Int),
                    ("outer.tags", b"a", Text),
                    ("outer.tags", b"b", Text),
                    ("outer.inner.a_b", b"x", Text),
                    ("outer.counts.a", b"1", Int),
                    ("outer.counts.b", b"2", Int),
                    ("outer.counts[\"x.y\"]", b"3", Int),
                    ("outer.level", b"WARN", Text),
                    ("outer.raw", &[0, 255], Text),
                    ("outer.ratio", b"0.5", Float),
                    ("outer.ok", b"true", Bool),
                    ("outer.levels", b"INFO", Text),
                    ("outer.levels", b"9", Int),
                ]),
            ),
            (event(&[("n", Value::I64(0))]), Ok(vec![])),
            (Vec::new(), Ok(vec![])),
            (truncated, Err("malformed")),
            (vec![0xff, 0xff, 0xff], Err("malformed")),
            (nested(70), Err("limit")),
        ];
        for (input, want) in cases {
            let mut out = Fields::new();
            out.push_prefix("outer.");
            let got = parser().parse(&input, &mut out);
            out.pop_prefix();
            out.field("after", FieldValue::borrowed(b"1", Hint::Int));
            let mut rows: Vec<(String, Vec<u8>, Hint)> = out
                .as_slice()
                .iter()
                .map(|(n, v)| (n.clone(), v.bytes.to_vec(), v.hint))
                .collect();
            assert_eq!(rows.pop().map(|r| r.0), Some("after".to_owned()));
            match (got, want) {
                (Ok(Parsed::Done), Ok(want)) => {
                    let want: Vec<(String, Vec<u8>, Hint)> = want
                        .into_iter()
                        .map(|(n, v, h)| (n.to_owned(), v.to_vec(), h))
                        .collect();
                    assert_eq!(rows, want);
                }
                (Err(ParseError::Malformed { .. }), Err("malformed"))
                | (Err(ParseError::Limit { .. }), Err("limit")) => {
                    assert!(rows.is_empty(), "{rows:?}");
                }
                (got, want) => panic!("{input:x?}: {got:?}, want {want:?}"),
            }
        }
        let deep = nested(60);
        let mut out = Fields::new();
        assert!(matches!(parser().parse(&deep, &mut out), Ok(Parsed::Done)));
        assert_eq!(out.len(), 1);
    }

    /// The checked-in OTLP descriptor set is what protox compiles from the
    /// pinned .proto files. `GRIPPO_WRITE_OTLP=1` rewrites it.
    #[cfg(feature = "parse-otlp")]
    #[test]
    fn the_otlp_schema_compiles_from_the_pinned_protos() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let protos = root.join("proto/opentelemetry-proto");
        let files = [
            "common/v1/common.proto",
            "resource/v1/resource.proto",
            "logs/v1/logs.proto",
        ]
        .map(|f| format!("opentelemetry/proto/{f}"));
        let built = protox::Compiler::new([&protos])
            .unwrap()
            .include_imports(true)
            .include_source_info(false)
            .open_files(files)
            .unwrap()
            .encode_file_descriptor_set();
        if std::env::var_os("GRIPPO_WRITE_OTLP").is_some() {
            std::fs::write(root.join("src/format/otlp_logs.binpb"), &built).unwrap();
        }
        assert!(built == OTLP_LOGS, "regenerate with GRIPPO_WRITE_OTLP=1");
        let record = Protobuf::otlp("opentelemetry.proto.logs.v1.LogRecord").unwrap();
        assert_eq!(record.name(), "otlp");
        assert!(matches!(
            Protobuf::otlp("acme.Event"),
            Err(ProtobufError::NoMessage(_))
        ));
    }

    #[test]
    fn bad_config_is_refused() {
        assert!(matches!(
            Protobuf::new(b"\xff\xff", "acme.Event"),
            Err(ProtobufError::Descriptor(_))
        ));
        assert!(matches!(
            Protobuf::new(&descriptors(), "acme.Nope"),
            Err(ProtobufError::NoMessage(_))
        ));
        assert_eq!(parser().message(), "acme.Event");
    }
}