grow-apache-skywalking 0.2.0

Rust SDK for Apache SkyWalking by Grow Codes
Documentation
// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
//! Span helpers: `with_span`, `traced`, current ids, events and errors (SPEC §5).

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;

/// Instrumentation scope used when no tracer is given.
const SCOPE: &str = env!("CARGO_PKG_NAME");

/// Options for [`with_span`] / [`with_span_sync`].
#[derive(Debug, Clone, Default)]
pub struct SpanOptions {
    /// Span attributes.
    pub attributes: Vec<KeyValue>,
    /// Span kind (default `Internal`).
    pub kind: Option<SpanKind>,
    /// Links to other spans.
    pub links: Vec<Link>,
    /// Tracer to use (default: the global tracer for this crate's scope).
    pub tracer: Option<SdkTracer>,
    /// Explicit parent (default: the active context).
    pub parent: Option<Context>,
}

impl SpanOptions {
    /// Adds an attribute.
    pub fn attribute(mut self, kv: KeyValue) -> Self {
        self.attributes.push(kv);
        self
    }
    /// Adds attributes from an [`Attributes`] map.
    pub fn attributes(mut self, attrs: &Attributes) -> Self {
        self.attributes.extend(super::otel_attributes(attrs));
        self
    }
    /// Sets the kind.
    pub fn kind(mut self, kind: SpanKind) -> Self {
        self.kind = Some(kind);
        self
    }
    /// Adds a link.
    pub fn link(mut self, link: Link) -> Self {
        self.links.push(link);
        self
    }
    /// Sets the tracer.
    pub fn tracer(mut self, tracer: SdkTracer) -> Self {
        self.tracer = Some(tracer);
        self
    }
    /// Sets the parent context.
    pub fn parent(mut self, cx: Context) -> Self {
        self.parent = Some(cx);
        self
    }
}

/// The active context: the OpenTelemetry current context, or — when it has no span — the
/// context of the current `tracing` span (via `tracing-opentelemetry`).
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
    }
}

/// Starts a span and returns the context that holds it.
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),
    }
}

/// Runs `fut` inside a new span (SPEC §5 `withSpan`). The span ends when the future finishes;
/// an `Err` (or a panic) records an `exception` event and sets the status to `ERROR`, and the
/// result is returned unchanged (panics are resumed).
///
/// ```no_run
/// # use grow_apache_skywalking::tracing::{with_span, SpanOptions};
/// # async fn demo() -> Result<(), std::io::Error> {
/// let n = with_span("load-user", SpanOptions::default(), async { Ok::<_, std::io::Error>(42) }).await?;
/// # Ok(()) }
/// ```
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)
}

/// Synchronous [`with_span`]: runs `f` with the span's context attached.
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)
}

/// Wraps a future in a span named `name` with default options (SPEC §5 `traced`).
///
/// For whole functions prefer `#[tracing::instrument]` (re-exported as [`instrument`](macro@super::instrument))
/// together with [`otel_layer`](super::otel_layer).
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
}

/// Synchronous [`traced`].
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)
}

/// The active span context, when it is valid.
pub fn current_span_context() -> Option<SpanContext> {
    let cx = active_context();
    let sc = cx.span().span_context().clone();
    sc.is_valid().then_some(sc)
}

/// The active trace id (32 lower-case hex), when a span is active.
pub fn current_trace_id() -> Option<String> {
    current_span_context().map(|sc| sc.trace_id().to_string())
}

/// The active span id (16 lower-case hex), when a span is active.
pub fn current_span_id() -> Option<String> {
    current_span_context().map(|sc| sc.span_id().to_string())
}

/// Adds an event to the active span.
pub fn add_event(name: impl Into<Cow<'static, str>>, attributes: Vec<KeyValue>) {
    active_context().span().add_event(name, attributes);
}

/// Records an `exception` event (type + message) on the active span.
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),
        ],
    );
}

/// Records the exception and sets the active span's status to `ERROR`.
pub fn set_error<E: fmt::Display + ?Sized>(err: &E) {
    record_exception(err);
    active_context()
        .span()
        .set_status(Status::error(err.to_string()));
}

/// Log correlation fields (snake_case keys on purpose — the log field convention).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct TraceFields {
    /// Active trace id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace_id: Option<String>,
    /// Active span id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub span_id: Option<String>,
}

impl TraceFields {
    /// The fields as attributes (`trace_id`, `span_id`; absent ones omitted).
    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
    }
}

/// `{ trace_id, span_id }` of the active span (SPEC §5 `traceFields`).
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(),
    }
}