Skip to main content

semiont_telemetry/
lib.rs

1//! The telemetry a Semiont transport and a Semiont service share, reported to
2//! whatever OpenTelemetry the process installed: nothing here exports, and
3//! with nothing installed no span is recorded and no trace context travels.
4//!
5//! A transport reports through one function per row of the SDK telemetry
6//! table (protocol/specs/src/sdk-telemetry/telemetry.json): [`bus_emit`], which is
7//! also the `semiont.bus.sent` count, [`bus_recv`], [`content_put`],
8//! [`content_get`], [`content_get_graph`], [`content_get_annotations`] and
9//! [`content_get_anchored_text`].
10//! It names no span, kind or attribute of its own, and puts [`active_trace`]
11//! on what it sends.
12//!
13//! A service's own spans are the service telemetry table's, which it states
14//! itself over [`in_span`] and [`in_span_now`], continuing a caller's trace
15//! with [`continued`] and a frame's with [`continuing`].
16//!
17//! The tracer, the meter and the propagator are taken from
18//! `opentelemetry::global` at each use, so telemetry installed after a client
19//! opened is reported to all the same.
20
21#![forbid(unsafe_code)]
22// A failure is a value its caller is given: outside the tests nothing
23// unwraps one away.
24#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used))]
25
26use opentelemetry::context::FutureExt;
27use opentelemetry::trace::{SpanKind, TraceContextExt, Tracer};
28use opentelemetry::{Context, KeyValue, global};
29use semiont::transport::TraceCarrier;
30use std::collections::HashMap;
31use std::future::Future;
32
33/// The instrumentation scope every span and count here is made under.
34const SCOPE: &str = "semiont";
35
36// ── The SDK telemetry table ──────────────────────────────────────────────
37
38/// `bus.emit:{channel}` and `semiont.bus.sent`: an emit a client sent, counted
39/// and run in a span of the trace that sent it.
40pub async fn bus_emit<T>(channel: &str, scope: Option<&str>, send: impl Future<Output = T>) -> T {
41    let attributes = on_the_bus(channel, scope);
42    global::meter(SCOPE)
43        .u64_counter("semiont.bus.sent")
44        .with_description("Emits sent")
45        .build()
46        .add(1, &attributes);
47    in_span(
48        format!("bus.emit:{channel}"),
49        SpanKind::Producer,
50        attributes,
51        Context::current(),
52        send,
53    )
54    .await
55}
56
57/// `bus.recv:{channel}`: a frame's arrival, in the trace it was sent under.
58/// Answers the trace that what is done for the frame continues: the span's
59/// own, or, when nothing records one, the one the frame came with.
60pub fn bus_recv(
61    channel: &str,
62    scope: Option<&str>,
63    sent_under: Option<TraceCarrier>,
64) -> Option<TraceCarrier> {
65    let parent = continued(
66        sent_under.as_ref().map(|t| t.traceparent.as_str()),
67        sent_under.as_ref().and_then(|t| t.tracestate.as_deref()),
68    );
69    in_span_now(
70        format!("bus.recv:{channel}"),
71        SpanKind::Consumer,
72        on_the_bus(channel, scope),
73        &parent,
74        active_trace,
75    )
76    .or(sent_under)
77}
78
79/// `content.put`: an upload.
80pub async fn content_put<T>(format: &str, size_bytes: u64, upload: impl Future<Output = T>) -> T {
81    in_span(
82        "content.put".to_owned(),
83        SpanKind::Client,
84        vec![
85            KeyValue::new("content.format", format.to_owned()),
86            KeyValue::new(
87                "content.size_bytes",
88                i64::try_from(size_bytes).unwrap_or(i64::MAX),
89            ),
90        ],
91        Context::current(),
92        upload,
93    )
94    .await
95}
96
97/// `content.get`: a read of a resource's bytes, whole or as a `stream`.
98pub async fn content_get<T>(resource_id: &str, stream: bool, read: impl Future<Output = T>) -> T {
99    let mut attributes = vec![KeyValue::new("resource.id", resource_id.to_owned())];
100    if stream {
101        attributes.push(KeyValue::new("content.stream", true));
102    }
103    in_span(
104        "content.get".to_owned(),
105        SpanKind::Client,
106        attributes,
107        Context::current(),
108        read,
109    )
110    .await
111}
112
113/// `content.get_annotations`: a read of a resource's annotations.
114pub async fn content_get_annotations<T>(resource_id: &str, read: impl Future<Output = T>) -> T {
115    in_span(
116        "content.get_annotations".to_owned(),
117        SpanKind::Client,
118        vec![KeyValue::new("resource.id", resource_id.to_owned())],
119        Context::current(),
120        read,
121    )
122    .await
123}
124
125/// `content.get_graph`: a read of a resource's description.
126pub async fn content_get_graph<T>(resource_id: &str, read: impl Future<Output = T>) -> T {
127    in_span(
128        "content.get_graph".to_owned(),
129        SpanKind::Client,
130        vec![KeyValue::new("resource.id", resource_id.to_owned())],
131        Context::current(),
132        read,
133    )
134    .await
135}
136
137/// `content.get_anchored_text`: a read of a resource's anchored text.
138pub async fn content_get_anchored_text<T>(resource_id: &str, read: impl Future<Output = T>) -> T {
139    in_span(
140        "content.get_anchored_text".to_owned(),
141        SpanKind::Client,
142        vec![KeyValue::new("resource.id", resource_id.to_owned())],
143        Context::current(),
144        read,
145    )
146    .await
147}
148
149/// What a span or a count of the bus carries: the channel, and the scope
150/// when there is one.
151pub fn on_the_bus(channel: &str, scope: Option<&str>) -> Vec<KeyValue> {
152    let mut attributes = vec![KeyValue::new("bus.channel", channel.to_owned())];
153    if let Some(scope) = scope {
154        attributes.push(KeyValue::new("bus.scope", scope.to_owned()));
155    }
156    attributes
157}
158
159// ── Trace context ────────────────────────────────────────────────────────
160
161/// The W3C trace context a caller sent (`traceparent`, `tracestate`), as the
162/// parent of what is done for it; the current context when it sent none, or
163/// when the process installed no propagator.
164pub fn continued(traceparent: Option<&str>, tracestate: Option<&str>) -> Context {
165    let Some(traceparent) = traceparent else {
166        return Context::current();
167    };
168    let mut carrier = HashMap::from([("traceparent".to_owned(), traceparent.to_owned())]);
169    if let Some(state) = tracestate {
170        carrier.insert("tracestate".to_owned(), state.to_owned());
171    }
172    global::get_text_map_propagator(|propagator| {
173        propagator.extract_with_context(&Context::current(), &carrier)
174    })
175}
176
177/// Run `work` in the trace a frame arrived in: what is done for it, and what
178/// is sent in answer, belongs to the sender's trace.
179pub async fn continuing<T>(trace: Option<&TraceCarrier>, work: impl Future<Output = T>) -> T {
180    let context = continued(
181        trace.map(|t| t.traceparent.as_str()),
182        trace.and_then(|t| t.tracestate.as_deref()),
183    );
184    work.with_context(context).await
185}
186
187/// The active span's W3C trace context, when a span is active: what a
188/// transport puts on what it sends.
189pub fn active_trace() -> Option<TraceCarrier> {
190    let context = Context::current();
191    if !context.span().span_context().is_valid() {
192        return None;
193    }
194    let mut carrier: HashMap<String, String> = HashMap::new();
195    global::get_text_map_propagator(|propagator| {
196        propagator.inject_context(&context, &mut carrier);
197    });
198    Some(TraceCarrier {
199        traceparent: carrier.remove("traceparent")?,
200        tracestate: carrier.remove("tracestate").filter(|s| !s.is_empty()),
201    })
202}
203
204/// The active span's trace id, when a span is active: what the bus log's
205/// `trace=` field reads (`semiont::bus_log::set_trace_id_provider`).
206pub fn active_trace_id() -> Option<String> {
207    let context = Context::current();
208    let span = context.span();
209    let span_context = span.span_context();
210    span_context
211        .is_valid()
212        .then(|| span_context.trace_id().to_string())
213}
214
215fn started(name: String, kind: SpanKind, attributes: Vec<KeyValue>, parent: &Context) -> Context {
216    let tracer = global::tracer(SCOPE);
217    let span = tracer
218        .span_builder(name)
219        .with_kind(kind)
220        .with_attributes(attributes)
221        .start_with_context(&tracer, parent);
222    parent.with_span(span)
223}
224
225/// Run `work` in a span, a child of `parent`.
226pub async fn in_span<T>(
227    name: String,
228    kind: SpanKind,
229    attributes: Vec<KeyValue>,
230    parent: Context,
231    work: impl Future<Output = T>,
232) -> T {
233    let context = started(name, kind, attributes, &parent);
234    let out = work.with_context(context.clone()).await;
235    context.span().end();
236    out
237}
238
239/// The same, for work that does not wait.
240pub fn in_span_now<T>(
241    name: String,
242    kind: SpanKind,
243    attributes: Vec<KeyValue>,
244    parent: &Context,
245    work: impl FnOnce() -> T,
246) -> T {
247    let context = started(name, kind, attributes, parent);
248    let out = {
249        let _attached = context.clone().attach();
250        work()
251    };
252    context.span().end();
253    out
254}