agent_sdk/observability/context.rs
1//! OpenTelemetry context propagation helpers for async boundaries.
2//!
3//! The SDK uses `tokio::spawn` in `run()`. Those spawned futures are wrapped
4//! with `FutureExt::with_context()` so the caller's `OTel` context is
5//! re-attached on every poll, surviving task migration across tokio worker
6//! threads. `run_turn()` executes directly in the caller task and therefore
7//! does not need an extra spawn propagation hop.
8
9use opentelemetry::Context;
10use opentelemetry::trace::{SpanContext, TraceContextExt};
11
12/// Capture the current `OTel` context for propagation into a spawned task.
13///
14/// Call this at the public API boundary (before `tokio::spawn`) and pass
15/// the returned `Context` via `FutureExt::with_context()`.
16#[must_use]
17pub fn capture_context() -> Context {
18 Context::current()
19}
20
21/// Capture the current `OTel` context and replace the active span.
22///
23/// This is used after starting a span that should become the parent for work
24/// performed inside an async sub-future while preserving any existing baggage
25/// from the caller context.
26#[must_use]
27pub fn current_with_span_context(span_context: SpanContext) -> Context {
28 Context::current().with_remote_span_context(span_context)
29}