opentelemetry_proto/
proto.rs

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
/// provide serde support for proto traceIds and spanIds.
/// Those are hex encoded strings in the jsons but they are byte arrays in the proto.
/// See https://opentelemetry.io/docs/specs/otlp/#json-protobuf-encoding for more details
#[cfg(all(feature = "with-serde", feature = "gen-tonic-messages"))]
pub(crate) mod serializers {
    use crate::tonic::common::v1::any_value::{self, Value};
    use crate::tonic::common::v1::AnyValue;
    use serde::de::{self, MapAccess, Visitor};
    use serde::ser::SerializeStruct;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use std::fmt;

    // hex string <-> bytes conversion

    pub fn serialize_to_hex_string<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let hex_string = hex::encode(bytes);
        serializer.serialize_str(&hex_string)
    }

    pub fn deserialize_from_hex_string<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct BytesVisitor;

        impl<'de> Visitor<'de> for BytesVisitor {
            type Value = Vec<u8>;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a string representing hex-encoded bytes")
            }

            fn visit_str<E>(self, value: &str) -> Result<Vec<u8>, E>
            where
                E: de::Error,
            {
                hex::decode(value).map_err(E::custom)
            }
        }

        deserializer.deserialize_str(BytesVisitor)
    }

    // AnyValue <-> KeyValue conversion
    pub fn serialize_to_value<S>(value: &Option<AnyValue>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match value {
            Some(any_value) => match &any_value.value {
                Some(Value::IntValue(i)) => {
                    // Attempt to create a struct to wrap the intValue
                    let mut state = match serializer.serialize_struct("Value", 1) {
                        Ok(s) => s,
                        Err(e) => return Err(e), // Handle the error or return it
                    };

                    // Attempt to serialize the intValue field
                    if let Err(e) = state.serialize_field("intValue", &i.to_string()) {
                        return Err(e); // Handle the error or return it
                    }

                    // Finalize the struct serialization
                    state.end()
                }
                Some(value) => value.serialize(serializer),
                None => serializer.serialize_none(),
            },
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize_from_value<'de, D>(deserializer: D) -> Result<Option<AnyValue>, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ValueVisitor;

        #[derive(Deserialize)]
        #[serde(untagged)]
        enum StringOrInt {
            Int(i64),
            String(String),
        }

        impl StringOrInt {
            fn get_int<'de, V>(&self) -> Result<i64, V::Error>
            where
                V: de::MapAccess<'de>,
            {
                match self {
                    Self::Int(val) => Ok(*val),
                    Self::String(val) => Ok(val.parse::<i64>().map_err(de::Error::custom)?),
                }
            }
        }

        impl<'de> de::Visitor<'de> for ValueVisitor {
            type Value = AnyValue;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a JSON object for AnyValue")
            }

            fn visit_map<V>(self, mut map: V) -> Result<AnyValue, V::Error>
            where
                V: de::MapAccess<'de>,
            {
                let mut value: Option<any_value::Value> = None;

                while let Some(key) = map.next_key::<String>()? {
                    let key_str = key.as_str();
                    match key_str {
                        "stringValue" => {
                            let s = map.next_value()?;
                            value = Some(any_value::Value::StringValue(s));
                        }
                        "boolValue" => {
                            let b = map.next_value()?;
                            value = Some(any_value::Value::BoolValue(b));
                        }
                        "intValue" => {
                            let int_value = map.next_value::<StringOrInt>()?.get_int::<V>()?;
                            value = Some(any_value::Value::IntValue(int_value));
                        }
                        "doubleValue" => {
                            let d = map.next_value()?;
                            value = Some(any_value::Value::DoubleValue(d));
                        }
                        "arrayValue" => {
                            let a = map.next_value()?;
                            value = Some(any_value::Value::ArrayValue(a));
                        }
                        "kvlistValue" => {
                            let kv = map.next_value()?;
                            value = Some(any_value::Value::KvlistValue(kv));
                        }
                        "bytesValue" => {
                            let bytes = map.next_value()?;
                            value = Some(any_value::Value::BytesValue(bytes));
                        }
                        _ => {
                            //skip unknown keys, and handle error later.
                            continue;
                        }
                    }
                }

                if let Some(v) = value {
                    Ok(AnyValue { value: Some(v) })
                } else {
                    Err(de::Error::custom(
                        "Invalid data for AnyValue, no known keys found",
                    ))
                }
            }
        }

        let value = deserializer.deserialize_map(ValueVisitor)?;
        Ok(Some(value))
    }

    pub fn serialize_u64_to_string<S>(value: &u64, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let s = value.to_string();
        serializer.serialize_str(&s)
    }

    pub fn deserialize_string_to_u64<'de, D>(deserializer: D) -> Result<u64, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s: String = Deserialize::deserialize(deserializer)?;
        s.parse::<u64>().map_err(de::Error::custom)
    }

    pub fn serialize_i64_to_string<S>(value: &i64, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let s = value.to_string();
        serializer.serialize_str(&s)
    }

    pub fn deserialize_string_to_i64<'de, D>(deserializer: D) -> Result<i64, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s: String = Deserialize::deserialize(deserializer)?;
        s.parse::<i64>().map_err(de::Error::custom)
    }
}

#[cfg(feature = "gen-tonic-messages")]
#[path = "proto/tonic"]
/// Generated files using [`tonic`](https://docs.rs/crate/tonic) and [`prost`](https://docs.rs/crate/prost)
pub mod tonic {
    /// Service stub and clients
    #[path = ""]
    pub mod collector {
        #[cfg(feature = "logs")]
        #[path = ""]
        pub mod logs {
            #[path = "opentelemetry.proto.collector.logs.v1.rs"]
            pub mod v1;
        }

        #[cfg(feature = "metrics")]
        #[path = ""]
        pub mod metrics {
            #[path = "opentelemetry.proto.collector.metrics.v1.rs"]
            pub mod v1;
        }

        #[cfg(feature = "trace")]
        #[path = ""]
        pub mod trace {
            #[path = "opentelemetry.proto.collector.trace.v1.rs"]
            pub mod v1;
        }
    }

    /// Common types used across all signals
    #[path = ""]
    pub mod common {
        #[path = "opentelemetry.proto.common.v1.rs"]
        pub mod v1;
    }

    /// Generated types used in logging.
    #[cfg(feature = "logs")]
    #[path = ""]
    pub mod logs {
        #[path = "opentelemetry.proto.logs.v1.rs"]
        pub mod v1;
    }

    /// Generated types used in metrics.
    #[cfg(feature = "metrics")]
    #[path = ""]
    pub mod metrics {
        #[path = "opentelemetry.proto.metrics.v1.rs"]
        pub mod v1;
    }

    /// Generated types used in resources.
    #[path = ""]
    pub mod resource {
        #[path = "opentelemetry.proto.resource.v1.rs"]
        pub mod v1;
    }

    /// Generated types used in traces.
    #[cfg(feature = "trace")]
    #[path = ""]
    pub mod trace {
        #[path = "opentelemetry.proto.trace.v1.rs"]
        pub mod v1;
    }

    /// Generated types used in zpages.
    #[cfg(feature = "zpages")]
    #[path = ""]
    pub mod tracez {
        #[path = "opentelemetry.proto.tracez.v1.rs"]
        pub mod v1;
    }

    pub use crate::transform::common::tonic::Attributes;
}