grippo 0.2.0

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/parse/frame/otlp_protobuf.rs
// Purpose:   OTLP logs in protobuf, each log record a frame
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! The protobuf twin of the `otlp_json` framer. A logs export decodes by the
//! OTLP schema built into `format::protobuf`, and each log record becomes a
//! frame of its own protobuf bytes, with its resource and scope as protobuf
//! context. `Protobuf::otlp` reads each of them into the fields `ndjson`
//! writes for the OTLP/JSON form.
//!
//! Each frame and context is a copy: prost-reflect decodes into owned
//! values, and each record is encoded again on its own.

use std::borrow::Cow;

use prost::Message;
use prost_reflect::{DynamicMessage, Value};

use super::Frame;
use crate::format::protobuf::otlp_pool;
use crate::parse::ParseError;

/// The messages a message holds in its repeated field `name`.
fn messages<'m>(m: &'m DynamicMessage, name: &str) -> Vec<&'m DynamicMessage> {
    match m.get_field_by_name(name) {
        Some(Cow::Borrowed(Value::List(items))) => items
            .iter()
            .filter_map(|v| match v {
                Value::Message(m) => Some(m),
                _ => None,
            })
            .collect(),
        _ => Vec::new(),
    }
}

/// The encoded message in the field `name`, when it is set.
fn encoded(m: &DynamicMessage, name: &str) -> Option<Vec<u8>> {
    if !m.has_field_by_name(name) {
        return None;
    }
    match m.get_field_by_name(name).as_deref() {
        Some(Value::Message(inner)) => Some(inner.encode_to_vec()),
        _ => None,
    }
}

/// Append a frame for each log record in the export `input`.
pub(super) fn frame(input: &[u8], out: &mut Vec<Frame<'_>>) -> Result<(), ParseError> {
    let logs = otlp_pool()
        .get_message_by_name("opentelemetry.proto.logs.v1.LogsData")
        .unwrap_or_else(|| unreachable!("invariant: the built-in OTLP schema has LogsData"));
    let export = DynamicMessage::decode(logs, input).map_err(|_| ParseError::Malformed {
        offset: 0,
        reason: "an OTLP logs export that doesn't decode as protobuf",
    })?;
    for r in messages(&export, "resource_logs") {
        let resource = encoded(r, "resource");
        for s in messages(r, "scope_logs") {
            let scope = encoded(s, "scope");
            for record in messages(s, "log_records") {
                let mut context = Vec::new();
                if let Some(v) = &resource {
                    context.push(("resource", Cow::Owned(v.clone())));
                }
                if let Some(v) = &scope {
                    context.push(("scope", Cow::Owned(v.clone())));
                }
                out.push(Frame {
                    bytes: Cow::Owned(record.encode_to_vec()),
                    context,
                });
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::time::Instant;

    use super::*;
    use crate::parse::{FrameState, FramingConfig};

    /// An OTLP/JSON export: ids in hex, as OTLP/JSON writes them.
    const EXPORT: &str = r#"{"resourceLogs":[
        {"resource":{"attributes":[{"key":"host","value":{"stringValue":"web01"}}]},
         "scopeLogs":[{"scope":{"name":"app","version":"1.2"},"logRecords":[
            {"timeUnixNano":"1700000000000000001","severityNumber":9,"severityText":"INFO",
             "body":{"stringValue":"started"},
             "attributes":[{"key":"n","value":{"intValue":"42"}},{"key":"ok","value":{"boolValue":true}},{"key":"r","value":{"doubleValue":0.5}}],
             "traceId":"5b8efff798038103d269b633813fc60c","spanId":"eee19b7ec3c1b174"},
            {"body":{"kvlistValue":{"values":[{"key":"k","value":{"stringValue":"v"}}]}}}]}]},
        {"scopeLogs":[{"logRecords":[{"body":{"stringValue":"c"}}]}]}
    ]}"#;

    fn frames<'a>(c: &FramingConfig, input: &'a [u8]) -> Result<Vec<Frame<'a>>, ParseError> {
        let mut out = Vec::new();
        c.frame(
            input,
            &mut FrameState::default(),
            Instant::now(),
            None,
            &mut out,
        )?;
        Ok(out)
    }

    #[cfg(feature = "parse-ndjson")]
    fn rows(p: &dyn crate::parse::Parser, bytes: &[u8]) -> Vec<(String, Vec<u8>)> {
        let mut out = crate::parse::Fields::new();
        p.parse(bytes, &mut out).unwrap();
        let mut rows: Vec<(String, Vec<u8>)> = out
            .as_slice()
            .iter()
            .map(|(n, v)| (n.clone(), v.bytes.to_vec()))
            .collect();
        rows.sort();
        rows
    }

    #[cfg(feature = "parse-ndjson")]
    fn otlp(message: &str) -> crate::format::protobuf::Protobuf {
        crate::format::protobuf::Protobuf::otlp(&format!("opentelemetry.proto.{message}")).unwrap()
    }

    /// `EXPORT` as protobuf, its hex ids read as the bytes they spell.
    fn wire() -> Vec<u8> {
        use base64::Engine;
        let b64 = |h: &str| {
            let bytes: Vec<u8> = (0..h.len())
                .step_by(2)
                .map(|i| u8::from_str_radix(&h[i..i + 2], 16).unwrap())
                .collect();
            base64::engine::general_purpose::STANDARD.encode(bytes)
        };
        let proto_json = EXPORT
            .replace(
                "5b8efff798038103d269b633813fc60c",
                &b64("5b8efff798038103d269b633813fc60c"),
            )
            .replace("eee19b7ec3c1b174", &b64("eee19b7ec3c1b174"));
        let logs = otlp_pool()
            .get_message_by_name("opentelemetry.proto.logs.v1.LogsData")
            .unwrap();
        let mut de = serde_json::Deserializer::from_str(&proto_json);
        DynamicMessage::deserialize(logs, &mut de)
            .unwrap()
            .encode_to_vec()
    }

    /// The same export as OTLP/JSON and as protobuf: each protobuf frame,
    /// read by `Protobuf::otlp`, writes exactly the fields `ndjson` writes for
    /// its JSON twin, and so do the resource and scope.
    #[cfg(feature = "parse-ndjson")]
    #[test]
    fn a_protobuf_export_reads_as_its_json_twin_does() {
        use crate::format::ndjson::Ndjson;
        let wire = wire();
        let from_json = frames(&FramingConfig::OtlpJson, EXPORT.as_bytes()).unwrap();
        let from_wire = frames(&FramingConfig::OtlpProtobuf, &wire).unwrap();
        assert_eq!(from_wire.len(), 3);
        assert_eq!(from_json.len(), from_wire.len());
        let record = otlp("logs.v1.LogRecord");
        for (j, p) in from_json.iter().zip(&from_wire) {
            assert_eq!(rows(&record, &p.bytes), rows(&Ndjson::new(), &j.bytes));
            let names = |f: &Frame<'_>| f.context.iter().map(|(n, _)| *n).collect::<Vec<_>>();
            assert_eq!(names(j), names(p));
            for ((name, a), (_, b)) in j.context.iter().zip(&p.context) {
                let schema = if *name == "resource" {
                    otlp("resource.v1.Resource")
                } else {
                    otlp("common.v1.InstrumentationScope")
                };
                assert_eq!(rows(&schema, b), rows(&Ndjson::new(), a), "{name}");
            }
        }
        let first = rows(&record, &from_wire[0].bytes);
        for (name, value) in [
            ("body.stringValue", "started"),
            ("traceId", "5b8efff798038103d269b633813fc60c"),
            ("severityNumber", "9"),
            ("timeUnixNano", "1700000000000000001"),
        ] {
            assert!(
                first.contains(&(name.to_owned(), value.as_bytes().to_vec())),
                "{name}"
            );
        }
    }

    #[test]
    fn bad_or_empty_exports() {
        assert_eq!(frames(&FramingConfig::OtlpProtobuf, b"").unwrap().len(), 0);
        assert_eq!(
            frames(&FramingConfig::OtlpProtobuf, &wire()).unwrap().len(),
            3
        );
        for bad in [&b"\xff\xff\xff"[..], b"\x0a\x05ab", EXPORT.as_bytes()] {
            assert!(
                matches!(
                    frames(&FramingConfig::OtlpProtobuf, bad),
                    Err(ParseError::Malformed { .. })
                ),
                "{bad:x?}"
            );
        }
    }
}