Skip to main content

saluki_common/
opaque.rs

1//! Opaque payloads: a type name and the encoded bytes of a value of that type.
2//!
3//! An [`Opaque`] value carries a payload that Saluki's data model doesn't describe, in the same way as protobuf's
4//! `Any`. The type name tells a reader how to decode the bytes. A reader that doesn't know the type name forwards the
5//! payload or drops it.
6
7use std::fmt;
8
9use bytes::Bytes;
10use saluki_error::{ErrorContext as _, GenericError};
11use stringtheory::MetaString;
12
13/// A type that can be encoded into, and decoded from, an [`Opaque`] value.
14pub trait OpaqueType: Sized {
15    /// The fully qualified type name.
16    const TYPE_NAME: &'static str;
17
18    /// Encodes this value.
19    fn encode(&self) -> Bytes;
20
21    /// Decodes a value from the given data.
22    ///
23    /// # Errors
24    ///
25    /// If the data isn't a valid encoding of this type, an error is returned.
26    fn try_decode(data: Bytes) -> Result<Self, GenericError>;
27}
28
29/// An opaque payload.
30///
31/// Opaque payloads provide an escape hatch to carry arbitrarily shaped, telemetry-adjacent data across a topology. They
32/// follow the common "`Any`" pattern from Protocol Buffers, where an encoded value is carried as raw bytes alongside
33/// the qualified name of the data type, which allows callers to do lightweight filtering of events by type name before
34/// attempting to fallibly decode the raw bytes into the concrete type identified by the type name field.
35#[derive(Clone, PartialEq)]
36pub struct Opaque {
37    type_name: MetaString,
38    data: Bytes,
39}
40
41impl Opaque {
42    /// Creates a new `Opaque` from the given type name and encoded data.
43    pub fn new(type_name: impl Into<MetaString>, data: Bytes) -> Self {
44        Self {
45            type_name: type_name.into(),
46            data,
47        }
48    }
49
50    /// Creates a new `Opaque` by encoding the given value.
51    pub fn encode<T: OpaqueType>(value: &T) -> Self {
52        Self {
53            type_name: MetaString::from_static(T::TYPE_NAME),
54            data: value.encode(),
55        }
56    }
57
58    /// Returns the type name.
59    pub fn type_name(&self) -> &str {
60        &self.type_name
61    }
62
63    /// Returns the encoded data.
64    pub fn data(&self) -> &Bytes {
65        &self.data
66    }
67
68    /// Returns `true` if the type name is the type name of `T`.
69    pub fn is<T: OpaqueType>(&self) -> bool {
70        self.type_name == T::TYPE_NAME
71    }
72
73    /// Decodes the data as a value of type `T`, if the type name is the type name of `T`.
74    ///
75    /// If the type name isn't the type name of `T`, `Ok(None)` is returned.
76    ///
77    /// # Errors
78    ///
79    /// If the type name matches, but the data isn't a valid encoding of `T`, an error is returned.
80    pub fn try_decode<T: OpaqueType>(&self) -> Result<Option<T>, GenericError> {
81        if !self.is::<T>() {
82            return Ok(None);
83        }
84
85        T::try_decode(self.data.clone())
86            .with_error_context(|| format!("Failed to decode opaque payload of type `{}`.", T::TYPE_NAME))
87            .map(Some)
88    }
89}
90
91impl fmt::Debug for Opaque {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        // The data can be large, so we show only its length.
94        f.debug_struct("Opaque")
95            .field("type_name", &self.type_name)
96            .field("data_len", &self.data.len())
97            .finish()
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use saluki_error::generic_error;
104
105    use super::*;
106
107    #[derive(Debug, PartialEq)]
108    struct Be32(u32);
109
110    impl OpaqueType for Be32 {
111        const TYPE_NAME: &'static str = "saluki.test.Be32";
112
113        fn encode(&self) -> Bytes {
114            Bytes::copy_from_slice(&self.0.to_be_bytes())
115        }
116
117        fn try_decode(data: Bytes) -> Result<Self, GenericError> {
118            let raw: [u8; 4] = data[..]
119                .try_into()
120                .map_err(|_| generic_error!("Expected 4 bytes, got {}.", data.len()))?;
121            Ok(Self(u32::from_be_bytes(raw)))
122        }
123    }
124
125    struct Case {
126        name: &'static str,
127        opaque: Opaque,
128        is_be32: bool,
129        /// The expected decode result, or the expected error message.
130        expected: Result<Option<Be32>, &'static str>,
131    }
132
133    #[test]
134    fn try_decode_checks_type_name_then_decodes() {
135        let cases = [
136            Case {
137                name: "encoded",
138                opaque: Opaque::encode(&Be32(42)),
139                is_be32: true,
140                expected: Ok(Some(Be32(42))),
141            },
142            Case {
143                name: "built from parts",
144                opaque: Opaque::new(Be32::TYPE_NAME, Bytes::from_static(&[0, 0, 1, 0])),
145                is_be32: true,
146                expected: Ok(Some(Be32(256))),
147            },
148            Case {
149                name: "other type name",
150                opaque: Opaque::new("saluki.test.Other", Bytes::from_static(&[0, 0, 0, 1])),
151                is_be32: false,
152                expected: Ok(None),
153            },
154            Case {
155                name: "invalid data",
156                opaque: Opaque::new(Be32::TYPE_NAME, Bytes::from_static(&[1, 2])),
157                is_be32: true,
158                expected: Err("Failed to decode opaque payload of type `saluki.test.Be32`."),
159            },
160        ];
161
162        for Case {
163            name,
164            opaque,
165            is_be32,
166            expected,
167        } in cases
168        {
169            assert_eq!(opaque.is::<Be32>(), is_be32, "{name}");
170
171            match (opaque.try_decode::<Be32>(), expected) {
172                (Ok(actual), Ok(expected)) => assert_eq!(actual, expected, "{name}"),
173                (Err(e), Err(expected)) => assert_eq!(e.to_string(), expected, "{name}"),
174                (actual, expected) => panic!("{name}: expected {expected:?}, got {actual:?}"),
175            }
176        }
177    }
178}