servers/otlp/
utils.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use api::v1::value::ValueData;
16use api::v1::ColumnDataType;
17use itertools::Itertools;
18use jsonb::{Number as JsonbNumber, Value as JsonbValue};
19use opentelemetry_proto::tonic::common::v1::{any_value, KeyValue};
20
21pub fn bytes_to_hex_string(bs: &[u8]) -> String {
22    bs.iter().map(|b| format!("{:02x}", b)).join("")
23}
24
25pub fn any_value_to_jsonb(value: any_value::Value) -> JsonbValue<'static> {
26    match value {
27        any_value::Value::StringValue(s) => JsonbValue::String(s.into()),
28        any_value::Value::IntValue(i) => JsonbValue::Number(JsonbNumber::Int64(i)),
29        any_value::Value::DoubleValue(d) => JsonbValue::Number(JsonbNumber::Float64(d)),
30        any_value::Value::BoolValue(b) => JsonbValue::Bool(b),
31        any_value::Value::ArrayValue(a) => {
32            let values = a
33                .values
34                .into_iter()
35                .map(|v| match v.value {
36                    Some(value) => any_value_to_jsonb(value),
37                    None => JsonbValue::Null,
38                })
39                .collect();
40            JsonbValue::Array(values)
41        }
42        any_value::Value::KvlistValue(kv) => key_value_to_jsonb(kv.values),
43        any_value::Value::BytesValue(b) => JsonbValue::String(bytes_to_hex_string(&b).into()),
44    }
45}
46
47pub fn key_value_to_jsonb(key_values: Vec<KeyValue>) -> JsonbValue<'static> {
48    JsonbValue::Object(
49        key_values
50            .into_iter()
51            .map(|kv| {
52                (
53                    kv.key,
54                    kv.value
55                        .and_then(|v| v.value)
56                        .map_or(JsonbValue::Null, any_value_to_jsonb),
57                )
58            })
59            .collect(),
60    )
61}
62
63#[inline]
64pub(crate) fn make_string_column_data(
65    name: &str,
66    value: String,
67) -> (String, ColumnDataType, ValueData) {
68    make_column_data(name, ColumnDataType::String, ValueData::StringValue(value))
69}
70
71#[inline]
72pub(crate) fn make_column_data(
73    name: &str,
74    data_type: ColumnDataType,
75    value: ValueData,
76) -> (String, ColumnDataType, ValueData) {
77    (name.to_string(), data_type, value)
78}