veecle_telemetry/future.rs
1//! Future instrumentation utilities for tracing async operations.
2//!
3//! This module provides utilities for instrumenting Rust futures with telemetry spans.
4//! When a future is instrumented, the associated span is automatically entered every time
5//! the future is polled.
6//!
7//! # Examples
8//!
9//! ```rust
10//! use veecle_telemetry::future::FutureExt;
11//! use veecle_telemetry::span;
12//!
13//! async fn example() {
14//! let span = span!("async_operation", user_id = 123);
15//!
16//! some_async_work().with_span(span).await;
17//! }
18//!
19//! async fn some_async_work() {
20//! // This work will be traced under the "async_operation" span
21//! }
22//! ```
23
24use core::future::Future;
25use core::pin::Pin;
26use core::task::{Context, Poll};
27
28use crate::Span;
29
30impl<T> FutureExt for T where T: Future {}
31
32/// Extension trait for instrumenting futures with telemetry spans.
33///
34/// This trait provides methods to attach telemetry spans to futures,
35/// ensuring that the spans are entered every time the future is polled.
36pub trait FutureExt: Future + Sized {
37 /// Instruments a future with the provided [`Span`].
38 ///
39 /// The attached [`Span`] will be [entered] every time it is polled.
40 ///
41 /// [entered]: Span::enter()
42 fn with_span(self, span: Span) -> WithSpan<Self> {
43 WithSpan { inner: self, span }
44 }
45}
46
47/// A future that has been instrumented with a telemetry span.
48///
49/// This future wrapper ensures that the associated span is entered every time
50/// the future is polled.
51///
52/// Instances of this type are created using the [`FutureExt::with_span`] method.
53#[pin_project::pin_project]
54#[derive(Debug)]
55pub struct WithSpan<T> {
56 #[pin]
57 inner: T,
58 span: Span,
59}
60
61impl<T> Future for WithSpan<T>
62where
63 T: Future,
64{
65 type Output = T::Output;
66
67 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
68 let this = self.project();
69 let _enter = this.span.enter();
70 this.inner.poll(cx)
71 }
72}