use crate::category::Trace;
use crate::record;
use crate::redact::FIELDS_MAX;
use crate::tracer::{current, Ctx};
use crate::value::Value;
use std::future::{poll_fn, Future};
use std::pin::pin;
use std::sync::atomic::Ordering;
use std::time::Instant;
#[must_use = "a span ends when it is dropped"]
pub struct Span {
open: Option<Open>,
}
pub(crate) struct Open {
pub(crate) ctx: Ctx,
pub(crate) parent: u64,
pub(crate) started: Instant,
pub(crate) fields: Vec<(String, Value)>,
pub(crate) err: Option<String>,
}
impl Span {
#[doc(hidden)]
pub fn open(cat: Trace, name: &'static str, fields: Vec<(&'static str, Value)>) -> Span {
let Some(scope) = current() else {
return Span::none();
};
let id = scope.alloc_span();
let line = record::start(&scope, id, cat, name, fields);
scope.emit(&line);
let ctx = scope.child(id);
assert_eq!(ctx.span_id(), id);
let open = Open {
ctx,
parent: scope.span_id(),
started: Instant::now(),
fields: Vec::new(),
err: None,
};
Span { open: Some(open) }
}
pub fn none() -> Span {
Span { open: None }
}
pub fn is_enabled(&self) -> bool {
self.open.is_some()
}
pub fn id(&self) -> u64 {
self.open.as_ref().map_or(0, |open| open.ctx.span_id())
}
pub fn record(&mut self, key: &str, value: impl Into<Value>) {
let Some(open) = self.open.as_mut() else {
return;
};
if open.fields.len() == FIELDS_MAX {
open.ctx
.inner
.shared
.dropped
.fetch_add(1, Ordering::Relaxed);
return;
}
open.fields.push((key.to_owned(), value.into()));
assert!(open.fields.len() <= FIELDS_MAX);
}
pub fn fail(&mut self, msg: impl Into<String>) {
if let Some(open) = self.open.as_mut() {
open.err = Some(msg.into());
}
}
pub fn enter<R>(&self, f: impl FnOnce() -> R) -> R {
match &self.open {
Some(open) => open.ctx.enter(f),
None => f(),
}
}
pub fn instrument<F: Future>(&self, fut: F) -> impl Future<Output = F::Output> {
let ctx = self.open.as_ref().map(|open| open.ctx.clone());
async move {
let mut fut = pin!(fut);
poll_fn(|cx| match &ctx {
Some(ctx) => ctx.enter(|| fut.as_mut().poll(cx)),
None => fut.as_mut().poll(cx),
})
.await
}
}
}
impl Drop for Span {
fn drop(&mut self) {
let Some(open) = self.open.take() else { return };
let line = record::end(&open);
open.ctx.emit(&line);
if open.parent == 0 {
open.ctx.flush();
}
}
}