use std::any::Any;
use std::borrow::Cow;
use std::fmt;
use std::future::Future;
use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
use futures::FutureExt as _;
use opentelemetry::trace::{
FutureExt as _, Link, SpanBuilder, SpanContext, SpanKind, SpanRef, Status, TraceContextExt,
Tracer as _,
};
use opentelemetry::{Context, KeyValue};
use opentelemetry_sdk::trace::SdkTracer;
use serde::Serialize;
use tracing_opentelemetry::OpenTelemetrySpanExt as _;
use super::Attributes;
const SCOPE: &str = env!("CARGO_PKG_NAME");
#[derive(Debug, Clone, Default)]
pub struct SpanOptions {
pub attributes: Vec<KeyValue>,
pub kind: Option<SpanKind>,
pub links: Vec<Link>,
pub tracer: Option<SdkTracer>,
pub parent: Option<Context>,
}
impl SpanOptions {
pub fn attribute(mut self, kv: KeyValue) -> Self {
self.attributes.push(kv);
self
}
pub fn attributes(mut self, attrs: &Attributes) -> Self {
self.attributes.extend(super::otel_attributes(attrs));
self
}
pub fn kind(mut self, kind: SpanKind) -> Self {
self.kind = Some(kind);
self
}
pub fn link(mut self, link: Link) -> Self {
self.links.push(link);
self
}
pub fn tracer(mut self, tracer: SdkTracer) -> Self {
self.tracer = Some(tracer);
self
}
pub fn parent(mut self, cx: Context) -> Self {
self.parent = Some(cx);
self
}
}
pub fn active_context() -> Context {
let cx = Context::current();
if cx.span().span_context().is_valid() {
return cx;
}
let from_tracing = ::tracing::Span::current().context();
if from_tracing.span().span_context().is_valid() {
from_tracing
} else {
cx
}
}
pub fn start_span(name: impl Into<Cow<'static, str>>, opts: SpanOptions) -> Context {
let parent = opts.parent.unwrap_or_else(active_context);
let builder = SpanBuilder::from_name(name.into())
.with_kind(opts.kind.unwrap_or(SpanKind::Internal))
.with_attributes(opts.attributes)
.with_links(opts.links);
match opts.tracer {
Some(tracer) => {
let span = tracer.build_with_context(builder, &parent);
parent.with_span(span)
}
None => {
let scope = opentelemetry::InstrumentationScope::builder(SCOPE)
.with_version(env!("CARGO_PKG_VERSION"))
.build();
let tracer = opentelemetry::global::tracer_with_scope(scope);
let span = tracer.build_with_context(builder, &parent);
parent.with_span(span)
}
}
}
fn panic_message(payload: &(dyn Any + Send)) -> String {
if let Some(s) = payload.downcast_ref::<&str>() {
format!("panic: {s}")
} else if let Some(s) = payload.downcast_ref::<String>() {
format!("panic: {s}")
} else {
"panic".to_string()
}
}
pub(crate) fn mark_error_on<E: fmt::Display + ?Sized>(
span: &SpanRef<'_>,
type_name: &str,
err: &E,
) {
let message = err.to_string();
span.add_event(
"exception",
vec![
KeyValue::new("exception.type", type_name.to_string()),
KeyValue::new("exception.message", message.clone()),
],
);
span.set_status(Status::error(message));
}
fn finish<T, E: fmt::Display>(
cx: &Context,
outcome: std::thread::Result<std::result::Result<T, E>>,
) -> std::result::Result<T, E> {
let span = cx.span();
match &outcome {
Ok(Ok(_)) => {}
Ok(Err(e)) => mark_error_on(&span, std::any::type_name::<E>(), e),
Err(payload) => mark_error_on(&span, "panic", &panic_message(payload.as_ref())),
}
span.end();
match outcome {
Ok(result) => result,
Err(payload) => resume_unwind(payload),
}
}
pub async fn with_span<T, E, Fut>(
name: impl Into<Cow<'static, str>>,
opts: SpanOptions,
fut: Fut,
) -> std::result::Result<T, E>
where
Fut: Future<Output = std::result::Result<T, E>>,
E: fmt::Display,
{
let cx = start_span(name, opts);
let outcome = AssertUnwindSafe(fut.with_context(cx.clone()))
.catch_unwind()
.await;
finish(&cx, outcome)
}
pub fn with_span_sync<T, E, F>(
name: impl Into<Cow<'static, str>>,
opts: SpanOptions,
f: F,
) -> std::result::Result<T, E>
where
F: FnOnce() -> std::result::Result<T, E>,
E: fmt::Display,
{
let cx = start_span(name, opts);
let outcome = {
let _guard = cx.clone().attach();
catch_unwind(AssertUnwindSafe(f))
};
finish(&cx, outcome)
}
pub async fn traced<T, E, Fut>(
name: impl Into<Cow<'static, str>>,
fut: Fut,
) -> std::result::Result<T, E>
where
Fut: Future<Output = std::result::Result<T, E>>,
E: fmt::Display,
{
with_span(name, SpanOptions::default(), fut).await
}
pub fn traced_sync<T, E, F>(name: impl Into<Cow<'static, str>>, f: F) -> std::result::Result<T, E>
where
F: FnOnce() -> std::result::Result<T, E>,
E: fmt::Display,
{
with_span_sync(name, SpanOptions::default(), f)
}
pub fn current_span_context() -> Option<SpanContext> {
let cx = active_context();
let sc = cx.span().span_context().clone();
sc.is_valid().then_some(sc)
}
pub fn current_trace_id() -> Option<String> {
current_span_context().map(|sc| sc.trace_id().to_string())
}
pub fn current_span_id() -> Option<String> {
current_span_context().map(|sc| sc.span_id().to_string())
}
pub fn add_event(name: impl Into<Cow<'static, str>>, attributes: Vec<KeyValue>) {
active_context().span().add_event(name, attributes);
}
pub fn record_exception<E: fmt::Display + ?Sized>(err: &E) {
let cx = active_context();
let span = cx.span();
let message = err.to_string();
span.add_event(
"exception",
vec![
KeyValue::new("exception.type", std::any::type_name::<E>()),
KeyValue::new("exception.message", message),
],
);
}
pub fn set_error<E: fmt::Display + ?Sized>(err: &E) {
record_exception(err);
active_context()
.span()
.set_status(Status::error(err.to_string()));
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct TraceFields {
#[serde(skip_serializing_if = "Option::is_none")]
pub trace_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub span_id: Option<String>,
}
impl TraceFields {
pub fn to_attributes(&self) -> Attributes {
let mut m = Attributes::new();
if let Some(t) = &self.trace_id {
m.insert("trace_id".into(), t.clone().into());
}
if let Some(s) = &self.span_id {
m.insert("span_id".into(), s.clone().into());
}
m
}
}
pub fn trace_fields() -> TraceFields {
match current_span_context() {
Some(sc) => TraceFields {
trace_id: Some(sc.trace_id().to_string()),
span_id: Some(sc.span_id().to_string()),
},
None => TraceFields::default(),
}
}