monocle_agent/blocking.rs
1//! Span-preserving `spawn_blocking` helper.
2
3use tracing::Span;
4
5/// Spawn a blocking task that inherits the caller's current tracing span.
6///
7/// [`tokio::task::spawn_blocking`] takes a plain `FnOnce` closure, so tracing's
8/// thread-local span context is **not** propagated into it — any span or event
9/// created inside the closure would be detached from the caller's span in the
10/// exported trace (breaking the waterfall).
11///
12/// This helper captures [`Span::current`] before spawning and re-enters it as
13/// the first thing inside the closure, so child spans created in the blocking
14/// work nest correctly under the caller's span (e.g. an HTTP request span).
15///
16/// ```no_run
17/// # async fn demo() {
18/// let out = monocle_agent::spawn_blocking_in_span(|| {
19/// tracing::info_span!("encode").in_scope(|| heavy_encode())
20/// })
21/// .await
22/// .unwrap();
23/// # let _ = out;
24/// # }
25/// # fn heavy_encode() -> Vec<u8> { Vec::new() }
26/// ```
27pub fn spawn_blocking_in_span<F, R>(f: F) -> tokio::task::JoinHandle<R>
28where
29 F: FnOnce() -> R + Send + 'static,
30 R: Send + 'static,
31{
32 let span = Span::current();
33 tokio::task::spawn_blocking(move || {
34 let _guard = span.enter();
35 f()
36 })
37}