1#![forbid(unsafe_code)]
22#![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
33const SCOPE: &str = "semiont";
35
36pub 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
57pub 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
79pub 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
97pub 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
113pub 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
125pub 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
137pub 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
149pub 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
159pub 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
177pub 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
187pub 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
204pub 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
225pub 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
239pub 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}