Skip to main content

micromegas_datafusion_extensions/histogram/
otel_to_jsonb.rs

1use super::otel_codec::{ExpBuckets, OtelBuckets, OtelHistogram, decode_column};
2use datafusion::arrow::array::BinaryBuilder;
3use datafusion::arrow::datatypes::DataType;
4use datafusion::error::{DataFusionError, Result};
5use datafusion::logical_expr::{
6    ColumnarValue, ScalarUDF, Signature, SimpleScalarUDF, TypeSignature, Volatility,
7};
8use jsonb::{Number, Value};
9use std::borrow::Cow;
10use std::collections::BTreeMap;
11use std::sync::Arc;
12
13const NAME: &str = "otel_histogram_to_jsonb";
14
15fn float(v: f64) -> Value<'static> {
16    Value::Number(Number::Float64(v))
17}
18
19fn uint(v: u64) -> Value<'static> {
20    Value::Number(Number::UInt64(v))
21}
22
23fn counts(v: &[u64]) -> Value<'static> {
24    Value::Array(v.iter().copied().map(uint).collect())
25}
26
27fn exp_buckets(b: &ExpBuckets) -> Value<'static> {
28    let mut map = BTreeMap::new();
29    map.insert(
30        "offset".to_string(),
31        Value::Number(Number::Int64(i64::from(b.offset))),
32    );
33    map.insert("bucket_counts".to_string(), counts(&b.counts));
34    Value::Object(map)
35}
36
37fn to_value(h: &OtelHistogram) -> Value<'static> {
38    let mut map = BTreeMap::new();
39    map.insert("kind".to_string(), Value::String(Cow::Borrowed(h.kind())));
40    map.insert("count".to_string(), uint(h.count));
41    for (key, value) in [("sum", h.sum), ("min", h.min), ("max", h.max)] {
42        if let Some(v) = value {
43            map.insert(key.to_string(), float(v));
44        }
45    }
46    match &h.buckets {
47        OtelBuckets::Explicit { bounds, counts: c } => {
48            map.insert(
49                "explicit_bounds".to_string(),
50                Value::Array(bounds.iter().copied().map(float).collect()),
51            );
52            map.insert("bucket_counts".to_string(), counts(c));
53        }
54        OtelBuckets::Exponential {
55            scale,
56            zero_count,
57            zero_threshold,
58            positive,
59            negative,
60        } => {
61            map.insert(
62                "scale".to_string(),
63                Value::Number(Number::Int64(i64::from(*scale))),
64            );
65            map.insert("zero_count".to_string(), uint(*zero_count));
66            map.insert("zero_threshold".to_string(), float(*zero_threshold));
67            map.insert("positive".to_string(), exp_buckets(positive));
68            map.insert("negative".to_string(), exp_buckets(negative));
69        }
70    }
71    Value::Object(map)
72}
73
74fn otel_histogram_to_jsonb(args: &[ColumnarValue]) -> Result<ColumnarValue> {
75    let arrays = ColumnarValue::values_to_arrays(args)?;
76    let [array] = arrays.as_slice() else {
77        return Err(DataFusionError::Execution(format!(
78            "wrong number of arguments to {NAME}"
79        )));
80    };
81    let histograms = decode_column(NAME, array)?;
82    let mut builder = BinaryBuilder::with_capacity(histograms.len(), 0);
83    let mut buffer = Vec::new();
84    for histogram in &histograms {
85        match histogram {
86            None => builder.append_null(),
87            Some(h) => {
88                buffer.clear();
89                to_value(h).write_to_vec(&mut buffer);
90                builder.append_value(&buffer);
91            }
92        }
93    }
94    Ok(ColumnarValue::Array(Arc::new(builder.finish())))
95}
96
97/// Creates a scalar UDF returning the decoded content of an OTel histogram blob as JSONB.
98pub fn make_otel_histogram_to_jsonb_udf() -> ScalarUDF {
99    ScalarUDF::from(SimpleScalarUDF::new_with_signature(
100        NAME,
101        Signature::one_of(
102            vec![
103                TypeSignature::Exact(vec![DataType::Binary]),
104                TypeSignature::Exact(vec![DataType::BinaryView]),
105            ],
106            Volatility::Immutable,
107        ),
108        DataType::Binary,
109        Arc::new(&otel_histogram_to_jsonb),
110    ))
111}