Skip to main content

micromegas_tracing/spans/
instrumented_future.rs

1//! Manual async span instrumentation using InstrumentedFuture wrapper
2
3use crate::dispatch::{
4    on_begin_async_scope, on_end_async_named_scope_tagged, on_end_async_scope,
5    on_end_async_scope_tagged,
6};
7use crate::property_set::PropertySet;
8use crate::spans::{
9    DynSpanName, SpanLocation, SpanMetadata, SpanName, SpanProperties, StaticSpanName,
10};
11use pin_project::pin_project;
12use std::cell::UnsafeCell;
13use std::future::Future;
14use std::pin::Pin;
15use std::task::{Context, Poll};
16
17thread_local! {
18    static ASYNC_CALL_STACK: UnsafeCell<Vec<u64>> = UnsafeCell ::new(vec![0]);
19}
20
21/// Returns the current span ID from the async call stack.
22/// Returns 0 (root) if no span is active.
23#[inline]
24pub fn current_span_id() -> u64 {
25    ASYNC_CALL_STACK.with(|stack_cell| {
26        let stack = unsafe { &*stack_cell.get() };
27        stack.last().copied().unwrap_or(0)
28    })
29}
30
31/// A future wrapper that establishes a span context on every poll.
32///
33/// Unlike an RAII guard, this pushes the parent span ID onto the
34/// thread-local async call stack before each poll and pops it after,
35/// which is correct across yield points and executor thread migration.
36///
37/// The stack is padded to match the parent's depth so that
38/// `InstrumentedFuture::new()` inside the spawned task computes
39/// `depth = stack.len() - 1 = parent_depth + 1`, preserving the
40/// logical nesting across spawn boundaries.
41#[pin_project]
42pub struct SpanContextFuture<F> {
43    #[pin]
44    future: F,
45    parent_span: u64,
46    parent_depth: u32,
47}
48
49impl<F: Future> Future for SpanContextFuture<F> {
50    type Output = F::Output;
51
52    #[inline]
53    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
54        let this = self.project();
55        ASYNC_CALL_STACK.with(|stack_cell| {
56            let stack = unsafe { &mut *stack_cell.get() };
57            let saved_len = stack.len();
58            // Pad stack so that children see depth = parent_depth.
59            // At the spawn point the stack had length parent_depth + 1;
60            // we recreate that, then push parent_span on top.
61            let target_len = *this.parent_depth as usize + 1;
62            while stack.len() < target_len.saturating_sub(1) {
63                stack.push(0);
64            }
65            stack.push(*this.parent_span);
66            let res = this.future.poll(cx);
67            stack.truncate(saved_len);
68            res
69        })
70    }
71}
72
73/// Spawns a future on the tokio runtime while preserving the current span context.
74///
75/// This is a wrapper around `tokio::spawn` that captures the current span ID
76/// before spawning and establishes it as the parent context in the spawned task.
77/// This ensures that instrumented async functions called within the spawned task
78/// will correctly report the spawning context as their parent.
79///
80/// The parent span ID is pushed onto the thread-local async call stack before
81/// each poll and popped after, so it works correctly across yield points and
82/// executor thread migration.
83///
84/// # Example
85/// ```ignore
86/// use micromegas_tracing::prelude::*;
87///
88/// #[span_fn]
89/// async fn parent_work() {
90///     // Spans created in child_work will show parent_work as their parent
91///     spawn_with_context(child_work()).await.unwrap();
92/// }
93///
94/// #[span_fn]
95/// async fn child_work() {
96///     // This span's parent will be parent_work, not root
97/// }
98/// ```
99#[cfg(feature = "tokio")]
100pub fn spawn_with_context<F>(future: F) -> tokio::task::JoinHandle<F::Output>
101where
102    F: Future + Send + 'static,
103    F::Output: Send + 'static,
104{
105    let (parent_span, parent_depth) = ASYNC_CALL_STACK.with(|stack_cell| {
106        let stack = unsafe { &*stack_cell.get() };
107        (
108            stack.last().copied().unwrap_or(0),
109            (stack.len().saturating_sub(1)) as u32,
110        )
111    });
112    tokio::spawn(SpanContextFuture {
113        future,
114        parent_span,
115        parent_depth,
116    })
117}
118
119/// Runs when an instrumented future completes, to add properties to the span's end event from the
120/// future's output.
121pub trait SpanEndHook<O> {
122    #[doc(hidden)]
123    fn properties_at_end(self, output: &O) -> Option<SpanProperties>;
124}
125
126/// The end hook of a future that carries no properties: its span ends plainly.
127pub struct NoHook;
128
129impl<O> SpanEndHook<O> for NoHook {
130    #[inline(always)]
131    fn properties_at_end(self, _output: &O) -> Option<SpanProperties> {
132        None
133    }
134}
135
136impl<O, H> SpanEndHook<O> for H
137where
138    H: FnOnce(&O, &mut SpanProperties),
139{
140    fn properties_at_end(self, output: &O) -> Option<SpanProperties> {
141        let mut properties = SpanProperties::new(PropertySet::empty());
142        self(output, &mut properties);
143        if properties.is_empty() {
144            None
145        } else {
146            Some(properties)
147        }
148    }
149}
150
151/// The end hook of a future whose properties were computed when it was created.
152pub struct EntryProperties(SpanProperties);
153
154impl<O> SpanEndHook<O> for EntryProperties {
155    fn properties_at_end(self, _output: &O) -> Option<SpanProperties> {
156        if self.0.is_empty() {
157            None
158        } else {
159            Some(self.0)
160        }
161    }
162}
163
164/// Trait for adding instrumentation to futures
165pub trait InstrumentFuture: Future + Sized {
166    /// Instrument this future with the given span metadata
167    fn instrument(self, span_desc: &'static SpanMetadata) -> InstrumentedFuture<Self> {
168        InstrumentedFuture::new(self, span_desc)
169    }
170
171    /// Instruments this future, and lets `on_end` add properties to the end event from the
172    /// output. A hook that sets nothing leaves the plain end event.
173    ///
174    /// ```
175    /// use micromegas_tracing::prelude::*;
176    /// use micromegas_tracing::spans::InstrumentFuture as _;
177    ///
178    /// # #[tokio::main]
179    /// # async fn main() {
180    /// static_span_desc!(FETCH, "fetch");
181    /// let rows = async { vec![1, 2, 3] }
182    ///     .instrument_with(&FETCH, |rows, span| span.set_property("rows", rows.len()))
183    ///     .await;
184    /// # assert_eq!(rows.len(), 3);
185    /// # }
186    /// ```
187    fn instrument_with<H>(
188        self,
189        span_desc: &'static SpanMetadata,
190        on_end: H,
191    ) -> InstrumentedFuture<Self, H>
192    where
193        H: FnOnce(&Self::Output, &mut SpanProperties),
194    {
195        InstrumentedFuture::with_hook(self, span_desc, on_end)
196    }
197
198    /// Internal method for named instrumentation - do not use directly.
199    /// Use the `instrument_named!` macro for method-like syntax instead.
200    #[doc(hidden)]
201    fn __instrument_named_internal(
202        self,
203        span_location: &'static SpanLocation,
204        name: &'static str,
205    ) -> InstrumentedNamedFuture<Self> {
206        InstrumentedNamedFuture::new(self, span_location, name)
207    }
208
209    /// Internal method for runtime-named instrumentation - do not use directly.
210    /// Use the `instrument_named_dyn!` macro for method-like syntax instead.
211    #[doc(hidden)]
212    fn __instrument_named_dyn_internal<N: AsRef<str>>(
213        self,
214        span_location: &'static SpanLocation,
215        name: N,
216    ) -> InstrumentedNamedFuture<Self, DynSpanName<N>> {
217        InstrumentedNamedFuture::with_name(self, span_location, DynSpanName(name))
218    }
219
220    /// Internal method for named instrumentation with an end hook - do not use directly.
221    #[doc(hidden)]
222    fn __instrument_named_with_internal<H>(
223        self,
224        span_location: &'static SpanLocation,
225        name: &'static str,
226        on_end: H,
227    ) -> InstrumentedNamedFuture<Self, StaticSpanName, H>
228    where
229        H: FnOnce(&Self::Output, &mut SpanProperties),
230    {
231        InstrumentedNamedFuture::with_name_and_hook(
232            self,
233            span_location,
234            StaticSpanName(name),
235            on_end,
236        )
237    }
238
239    /// Internal method for runtime-named instrumentation with an end hook - do not use directly.
240    #[doc(hidden)]
241    fn __instrument_named_dyn_with_internal<N: AsRef<str>, H>(
242        self,
243        span_location: &'static SpanLocation,
244        name: N,
245        on_end: H,
246    ) -> InstrumentedNamedFuture<Self, DynSpanName<N>, H>
247    where
248        H: FnOnce(&Self::Output, &mut SpanProperties),
249    {
250        InstrumentedNamedFuture::with_name_and_hook(self, span_location, DynSpanName(name), on_end)
251    }
252}
253
254impl<F: Future> InstrumentFuture for F {}
255
256/// A wrapper that instruments a future with async span tracing
257#[pin_project]
258pub struct InstrumentedFuture<F, H = NoHook> {
259    #[pin]
260    future: F,
261    desc: &'static SpanMetadata,
262    on_end: Option<H>,
263    span_id: Option<u64>,
264    /// Parent span ID captured at future creation time
265    parent: u64,
266    /// Depth captured at future creation time
267    depth: u32,
268}
269
270impl<F> InstrumentedFuture<F> {
271    /// Create a new instrumented future
272    pub fn new(future: F, desc: &'static SpanMetadata) -> Self {
273        Self::with_hook(future, desc, NoHook)
274    }
275}
276
277impl<F> InstrumentedFuture<F, EntryProperties> {
278    /// Create an instrumented future whose end event carries `properties`, computed by the caller
279    /// before the future first runs.
280    pub fn with_properties(
281        future: F,
282        desc: &'static SpanMetadata,
283        properties: SpanProperties,
284    ) -> Self {
285        Self::with_hook(future, desc, EntryProperties(properties))
286    }
287}
288
289impl<F, H> InstrumentedFuture<F, H> {
290    /// Create a new instrumented future whose end event carries the properties `on_end` sets.
291    pub fn with_hook(future: F, desc: &'static SpanMetadata, on_end: H) -> Self {
292        let (parent, depth) = ASYNC_CALL_STACK.with(|stack_cell| {
293            let stack = unsafe { &*stack_cell.get() };
294            assert!(!stack.is_empty());
295            (
296                stack[stack.len() - 1],
297                (stack.len().saturating_sub(1)) as u32,
298            )
299        });
300        Self {
301            future,
302            desc,
303            on_end: Some(on_end),
304            span_id: None,
305            parent,
306            depth,
307        }
308    }
309}
310
311impl<F, H> Future for InstrumentedFuture<F, H>
312where
313    F: Future,
314    H: SpanEndHook<F::Output>,
315{
316    type Output = F::Output;
317
318    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
319        let this = self.project();
320        let parent = *this.parent;
321        let depth = *this.depth;
322        ASYNC_CALL_STACK.with(|stack_cell| {
323            let stack = unsafe { &mut *stack_cell.get() };
324            assert!(!stack.is_empty());
325            match this.span_id {
326                Some(span_id) => {
327                    stack.push(*span_id);
328                }
329                None => {
330                    // Begin the async span and store the span ID
331                    let span_id = on_begin_async_scope(this.desc, parent, depth);
332                    stack.push(span_id);
333                    *this.span_id = Some(span_id);
334                }
335            }
336            let res = match this.future.poll(cx) {
337                Poll::Ready(output) => {
338                    // End the async span when the future completes
339                    if let Some(span_id) = *this.span_id {
340                        let properties = this
341                            .on_end
342                            .take()
343                            .and_then(|hook| hook.properties_at_end(&output));
344                        match properties {
345                            Some(properties) => properties.with_dyn(|set, dyn_properties| {
346                                on_end_async_scope_tagged(
347                                    span_id,
348                                    parent,
349                                    this.desc,
350                                    depth,
351                                    set,
352                                    dyn_properties,
353                                );
354                            }),
355                            None => on_end_async_scope(span_id, parent, this.desc, depth),
356                        }
357                    }
358                    Poll::Ready(output)
359                }
360                Poll::Pending => Poll::Pending,
361            };
362            stack.pop();
363            res
364        })
365    }
366}
367
368/// A wrapper that instruments a future with named async span tracing
369#[pin_project]
370pub struct InstrumentedNamedFuture<F, N = StaticSpanName, H = NoHook> {
371    #[pin]
372    future: F,
373    span_location: &'static SpanLocation,
374    name: N,
375    on_end: Option<H>,
376    span_id: Option<u64>,
377    /// Parent span ID captured at future creation time
378    parent: u64,
379    /// Depth captured at future creation time
380    depth: u32,
381}
382
383impl<F> InstrumentedNamedFuture<F> {
384    /// Create a new instrumented named future
385    pub fn new(future: F, span_location: &'static SpanLocation, name: &'static str) -> Self {
386        Self::with_name(future, span_location, StaticSpanName(name))
387    }
388}
389
390impl<F, N: SpanName> InstrumentedNamedFuture<F, N> {
391    /// Create a new instrumented named future
392    pub fn with_name(future: F, span_location: &'static SpanLocation, name: N) -> Self {
393        Self::with_name_and_hook(future, span_location, name, NoHook)
394    }
395}
396
397impl<F, N: SpanName, H> InstrumentedNamedFuture<F, N, H> {
398    /// Create a new instrumented named future whose end event carries the properties `on_end`
399    /// sets.
400    pub fn with_name_and_hook(
401        future: F,
402        span_location: &'static SpanLocation,
403        name: N,
404        on_end: H,
405    ) -> Self {
406        let (parent, depth) = ASYNC_CALL_STACK.with(|stack_cell| {
407            let stack = unsafe { &*stack_cell.get() };
408            assert!(!stack.is_empty());
409            (
410                stack[stack.len() - 1],
411                (stack.len().saturating_sub(1)) as u32,
412            )
413        });
414        Self {
415            future,
416            span_location,
417            name,
418            on_end: Some(on_end),
419            span_id: None,
420            parent,
421            depth,
422        }
423    }
424}
425
426impl<F, N: SpanName, H> Future for InstrumentedNamedFuture<F, N, H>
427where
428    F: Future,
429    H: SpanEndHook<F::Output>,
430{
431    type Output = F::Output;
432
433    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
434        let this = self.project();
435        let parent = *this.parent;
436        let depth = *this.depth;
437        ASYNC_CALL_STACK.with(|stack_cell| {
438            let stack = unsafe { &mut *stack_cell.get() };
439            assert!(!stack.is_empty());
440            match this.span_id {
441                Some(span_id) => {
442                    stack.push(*span_id);
443                }
444                None => {
445                    // Begin the async named span and store the span ID
446                    let span_id = this.name.begin_async(this.span_location, parent, depth);
447                    stack.push(span_id);
448                    *this.span_id = Some(span_id);
449                }
450            }
451            let res = match this.future.poll(cx) {
452                Poll::Ready(output) => {
453                    // End the async named span when the future completes
454                    if let Some(span_id) = *this.span_id {
455                        let properties = this
456                            .on_end
457                            .take()
458                            .and_then(|hook| hook.properties_at_end(&output));
459                        match properties {
460                            Some(properties) => properties.with_dyn(|set, dyn_properties| {
461                                on_end_async_named_scope_tagged(
462                                    span_id,
463                                    parent,
464                                    this.span_location,
465                                    this.name.as_str(),
466                                    depth,
467                                    set,
468                                    dyn_properties,
469                                );
470                            }),
471                            None => this
472                                .name
473                                .end_async(span_id, parent, this.span_location, depth),
474                        }
475                    }
476                    Poll::Ready(output)
477                }
478                Poll::Pending => Poll::Pending,
479            };
480            stack.pop();
481            res
482        })
483    }
484}