1use 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#[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#[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 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#[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
119pub trait SpanEndHook<O> {
122 #[doc(hidden)]
123 fn properties_at_end(self, output: &O) -> Option<SpanProperties>;
124}
125
126pub 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
151pub 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
164pub trait InstrumentFuture: Future + Sized {
166 fn instrument(self, span_desc: &'static SpanMetadata) -> InstrumentedFuture<Self> {
168 InstrumentedFuture::new(self, span_desc)
169 }
170
171 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 #[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 #[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 #[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 #[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#[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: u64,
266 depth: u32,
268}
269
270impl<F> InstrumentedFuture<F> {
271 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 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 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 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 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#[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: u64,
379 depth: u32,
381}
382
383impl<F> InstrumentedNamedFuture<F> {
384 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 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 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 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 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}