Skip to main content

graphrt_otel/
otlp.rs

1//! OTLP/JSON encoding (opentelemetry-proto JSON mapping: hex ids, 64-bit integers
2//! as strings, lowerCamelCase field names).
3
4use serde_json::{Value as Json, json};
5
6use crate::span::{AttrValue, Attributes, Span};
7
8/// Instrumentation scope name used for every span and metric.
9pub const SCOPE_NAME: &str = "graphrt";
10
11/// Resource attributes describing the process emitting telemetry.
12#[derive(Clone, Debug, PartialEq)]
13pub struct Resource {
14    pub attributes: Attributes,
15}
16
17impl Resource {
18    /// Resource with `service.name` and the SDK attributes.
19    pub fn new(service_name: &str) -> Self {
20        Self {
21            attributes: vec![
22                ("service.name".to_owned(), AttrValue::from(service_name)),
23                ("telemetry.sdk.name".to_owned(), AttrValue::from("graphrt-otel")),
24                ("telemetry.sdk.language".to_owned(), AttrValue::from("rust")),
25                ("telemetry.sdk.version".to_owned(), AttrValue::from(env!("CARGO_PKG_VERSION"))),
26            ],
27        }
28    }
29
30    /// Add or replace an attribute.
31    pub fn with(mut self, key: &str, value: impl Into<AttrValue>) -> Self {
32        let value = value.into();
33        match self.attributes.iter_mut().find(|(k, _)| k == key) {
34            Some(slot) => slot.1 = value,
35            None => self.attributes.push((key.to_owned(), value)),
36        }
37        self
38    }
39}
40
41impl Default for Resource {
42    fn default() -> Self {
43        Self::new("graphrt")
44    }
45}
46
47/// Encode one attribute value.
48pub fn any_value(value: &AttrValue) -> Json {
49    match value {
50        AttrValue::Str(s) => json!({ "stringValue": s }),
51        AttrValue::Int(i) => json!({ "intValue": i.to_string() }),
52        AttrValue::Double(d) if d.is_finite() => json!({ "doubleValue": d }),
53        AttrValue::Double(d) => json!({ "stringValue": d.to_string() }),
54        AttrValue::Bool(b) => json!({ "boolValue": b }),
55    }
56}
57
58/// Encode an attribute list as OTLP `KeyValue`s.
59pub fn attributes(attrs: &Attributes) -> Json {
60    Json::Array(attrs.iter().map(|(k, v)| json!({ "key": k, "value": any_value(v) })).collect())
61}
62
63/// Encode one span.
64pub fn span(span: &Span) -> Json {
65    let mut out = json!({
66        "traceId": span.trace_id.to_hex(),
67        "spanId": span.span_id.to_hex(),
68        "name": span.name,
69        "kind": span.kind.code(),
70        "startTimeUnixNano": span.start_unix_nano.to_string(),
71        "endTimeUnixNano": span.end_unix_nano.max(span.start_unix_nano).to_string(),
72        "attributes": attributes(&span.attributes),
73        "events": span.events.iter().map(|e| json!({
74            "timeUnixNano": e.time_unix_nano.to_string(),
75            "name": e.name,
76            "attributes": attributes(&e.attributes),
77        })).collect::<Vec<_>>(),
78        "status": { "code": span.status.code(), "message": span.status_message },
79    });
80    if let Some(obj) = out.as_object_mut() {
81        if let Some(parent) = span.parent_span_id {
82            obj.insert("parentSpanId".into(), Json::String(parent.to_hex()));
83        }
84        if span.dropped_events > 0 {
85            obj.insert("droppedEventsCount".into(), json!(span.dropped_events));
86        }
87    }
88    out
89}
90
91/// Encode an `ExportTraceServiceRequest`.
92pub fn traces_request(resource: &Resource, spans: &[Span]) -> Json {
93    json!({
94        "resourceSpans": [{
95            "resource": { "attributes": attributes(&resource.attributes) },
96            "scopeSpans": [{
97                "scope": { "name": SCOPE_NAME, "version": env!("CARGO_PKG_VERSION") },
98                "spans": spans.iter().map(span).collect::<Vec<_>>(),
99            }],
100        }],
101    })
102}
103
104/// Wrap encoded metrics in an `ExportMetricsServiceRequest`.
105pub fn metrics_request(resource: &Resource, metrics: Vec<Json>) -> Json {
106    json!({
107        "resourceMetrics": [{
108            "resource": { "attributes": attributes(&resource.attributes) },
109            "scopeMetrics": [{
110                "scope": { "name": SCOPE_NAME, "version": env!("CARGO_PKG_VERSION") },
111                "metrics": metrics,
112            }],
113        }],
114    })
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120    use crate::span::{SpanId, StatusCode, TraceId};
121
122    #[test]
123    fn span_encoding_uses_spec_field_names() {
124        let mut s = Span::new(TraceId::random(), Some(SpanId::random()), "node", 10);
125        s.end_unix_nano = 20;
126        s.set("graphrt.node.id", "llm");
127        s.set("gen_ai.usage.input_tokens", 12u64);
128        s.set("ok", true);
129        s.set("ratio", 0.5);
130        s.add_event("retry", 15, vec![("attempt".into(), AttrValue::from(2u32))]);
131        s.error("boom");
132        let j = span(&s);
133        assert_eq!(j["traceId"].as_str().map(str::len), Some(32));
134        assert_eq!(j["spanId"].as_str().map(str::len), Some(16));
135        assert!(j["parentSpanId"].is_string());
136        assert_eq!(j["startTimeUnixNano"], "10");
137        assert_eq!(j["endTimeUnixNano"], "20");
138        assert_eq!(j["kind"], 1);
139        assert_eq!(j["status"]["code"], StatusCode::Error.code());
140        assert_eq!(j["attributes"][1]["value"]["intValue"], "12");
141        assert_eq!(j["attributes"][2]["value"]["boolValue"], true);
142        assert_eq!(j["attributes"][3]["value"]["doubleValue"], 0.5);
143        assert_eq!(j["events"][0]["timeUnixNano"], "15");
144        let req = traces_request(&Resource::new("svc"), &[s]);
145        assert_eq!(req["resourceSpans"][0]["scopeSpans"][0]["scope"]["name"], SCOPE_NAME);
146        assert_eq!(req["resourceSpans"][0]["resource"]["attributes"][0]["value"]["stringValue"], "svc");
147    }
148}