#[cfg(feature = "metrics")]
mod metrics;
#[cfg(feature = "metrics")]
pub use self::metrics::metrics;
#[cfg(feature = "opentelemetry")]
mod opentelemetry;
#[cfg(feature = "opentelemetry")]
pub use self::opentelemetry::opentelemetry;
tokio::task_local! {
static TAG: Option<u64>;
}
pub fn tagged<F: IntoFuture>(tag: u64, future: F) -> impl Future<Output = F::Output> {
TAG.scope(Some(tag), future.into_future())
}
pub(crate) fn current_tag() -> Option<u64> {
TAG.try_with(|tag| *tag).ok().flatten()
}
pub(crate) fn untagged<F: Future>(future: F) -> impl Future<Output = F::Output> {
TAG.scope(None, future)
}
pub(crate) fn carry_tag<F: Future>(future: F) -> impl Future<Output = F::Output> {
TAG.scope(current_tag(), future)
}
#[cfg(test)]
mod tests {
use super::{carry_tag, current_tag, tagged, untagged};
#[tokio::test]
async fn the_innermost_tag_wins_and_untagged_clears_it() {
assert_eq!(current_tag(), None);
let seen = tagged(1, async {
let outer = current_tag();
let inner = tagged(2, async { current_tag() }).await;
let cleared = untagged(async { current_tag() }).await;
(outer, inner, cleared, current_tag())
})
.await;
assert_eq!(seen, (Some(1), Some(2), None, Some(1)));
}
#[tokio::test]
async fn a_spawned_task_gets_the_tag_only_when_carried() {
let (carried, plain) = tagged(5, async {
let carried = tokio::spawn(carry_tag(async { current_tag() }));
let plain = tokio::spawn(async { current_tag() });
(carried.await.unwrap(), plain.await.unwrap())
})
.await;
assert_eq!((carried, plain), (Some(5), None));
}
}