use crate::log::{self, LogValue};
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::Mutex;
use std::time::{Duration, Instant};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[repr(u8)]
pub enum ProfileMode {
#[default]
Off = 0,
Summary = 1,
Trace = 2,
}
static PROFILE_MODE: AtomicU8 = AtomicU8::new(ProfileMode::Off as u8);
#[derive(Clone, Debug, Default)]
struct SpanStats {
count: u64,
total_ns: u64,
max_ns: u64,
}
static STATS: Mutex<BTreeMap<String, SpanStats>> = Mutex::new(BTreeMap::new());
#[must_use = "span timers only record while the guard is alive"]
pub struct SpanGuard {
inner: Option<(Cow<'static, str>, Instant)>,
}
impl Drop for SpanGuard {
fn drop(&mut self) {
let Some((name, start)) = self.inner.take() else {
return;
};
let elapsed = start.elapsed();
record_span(&name, elapsed);
if profile_mode() == ProfileMode::Trace {
log::emit(
"span",
&[
("name", LogValue::Str(&name)),
("ms", LogValue::f64(elapsed.as_secs_f64() * 1_000.0, 3)),
],
);
}
}
}
pub fn set_profile_mode(mode: ProfileMode) {
PROFILE_MODE.store(mode as u8, Ordering::Relaxed);
}
pub fn profile_mode() -> ProfileMode {
match PROFILE_MODE.load(Ordering::Relaxed) {
1 => ProfileMode::Summary,
2 => ProfileMode::Trace,
_ => ProfileMode::Off,
}
}
pub fn parse_profile_mode(value: &str) -> Result<ProfileMode, String> {
match value.trim().to_ascii_lowercase().as_str() {
"0" | "off" | "false" | "no" | "none" => Ok(ProfileMode::Off),
"1" | "on" | "true" | "yes" | "summary" => Ok(ProfileMode::Summary),
"trace" | "spans" | "full" => Ok(ProfileMode::Trace),
other => Err(format!(
"unknown profile mode '{other}'; expected off, summary, or trace"
)),
}
}
pub fn init_from_env() {
if let Ok(value) = std::env::var("OXIDELM_PROFILE") {
if let Ok(mode) = parse_profile_mode(&value) {
set_profile_mode(mode);
}
}
}
#[inline]
pub fn enabled() -> bool {
PROFILE_MODE.load(Ordering::Relaxed) != ProfileMode::Off as u8
}
#[inline]
pub fn span(name: &'static str) -> SpanGuard {
if enabled() {
SpanGuard {
inner: Some((Cow::Borrowed(name), Instant::now())),
}
} else {
SpanGuard { inner: None }
}
}
#[inline]
pub fn span_owned(name: String) -> SpanGuard {
if enabled() {
SpanGuard {
inner: Some((Cow::Owned(name), Instant::now())),
}
} else {
SpanGuard { inner: None }
}
}
#[inline]
pub fn layer(index: usize) -> SpanGuard {
if enabled() {
span_owned(format!("layer.{index}"))
} else {
SpanGuard { inner: None }
}
}
fn record_span(name: &str, elapsed: Duration) {
let nanos = elapsed.as_nanos().min(u128::from(u64::MAX)) as u64;
let Ok(mut stats) = STATS.lock() else {
return;
};
let entry = stats.entry(name.to_string()).or_default();
entry.count = entry.count.saturating_add(1);
entry.total_ns = entry.total_ns.saturating_add(nanos);
entry.max_ns = entry.max_ns.max(nanos);
}
#[derive(Clone, Debug, PartialEq)]
pub struct SpanSummary {
pub name: String,
pub count: u64,
pub total: Duration,
pub mean: Duration,
pub max: Duration,
}
pub fn summary() -> Vec<SpanSummary> {
let Ok(stats) = STATS.lock() else {
return Vec::new();
};
stats
.iter()
.map(|(name, entry)| {
let mean_ns = if entry.count == 0 {
0
} else {
entry.total_ns / entry.count
};
SpanSummary {
name: name.clone(),
count: entry.count,
total: Duration::from_nanos(entry.total_ns),
mean: Duration::from_nanos(mean_ns),
max: Duration::from_nanos(entry.max_ns),
}
})
.collect()
}
pub fn reset() {
if let Ok(mut stats) = STATS.lock() {
stats.clear();
}
}
pub fn flush() {
if !enabled() {
return;
}
for entry in summary() {
log::emit(
"profile",
&[
("span", LogValue::Str(&entry.name)),
("count", LogValue::Usize(entry.count as usize)),
(
"total_ms",
LogValue::f64(entry.total.as_secs_f64() * 1_000.0, 3),
),
(
"mean_ms",
LogValue::f64(entry.mean.as_secs_f64() * 1_000.0, 3),
),
(
"max_ms",
LogValue::f64(entry.max.as_secs_f64() * 1_000.0, 3),
),
],
);
}
reset();
}
#[cfg(test)]
mod tests {
use super::{
enabled, parse_profile_mode, profile_mode, reset, set_profile_mode, span, summary,
ProfileMode,
};
use std::sync::Mutex;
use std::thread;
use std::time::Duration;
static TEST_LOCK: Mutex<()> = Mutex::new(());
#[test]
fn parse_accepts_aliases() {
assert_eq!(parse_profile_mode("off").unwrap(), ProfileMode::Off);
assert_eq!(parse_profile_mode("1").unwrap(), ProfileMode::Summary);
assert_eq!(parse_profile_mode("SUMMARY").unwrap(), ProfileMode::Summary);
assert_eq!(parse_profile_mode("trace").unwrap(), ProfileMode::Trace);
assert!(parse_profile_mode("chrome").is_err());
}
#[test]
fn disabled_spans_do_not_record() {
let _lock = TEST_LOCK.lock().unwrap();
set_profile_mode(ProfileMode::Off);
reset();
{
let _guard = span("profile.test.disabled");
thread::sleep(Duration::from_millis(1));
}
assert!(!enabled());
assert!(summary()
.iter()
.all(|entry| entry.name != "profile.test.disabled"));
}
#[test]
fn enabled_spans_aggregate() {
let _lock = TEST_LOCK.lock().unwrap();
const NAME: &str = "profile.test.aggregate";
set_profile_mode(ProfileMode::Summary);
reset();
{
let _guard = span(NAME);
thread::sleep(Duration::from_millis(1));
}
{
let _guard = span(NAME);
thread::sleep(Duration::from_millis(1));
}
let entry = summary()
.into_iter()
.find(|row| row.name == NAME)
.expect("expected profile.test.aggregate span");
assert_eq!(entry.count, 2);
assert!(entry.total >= Duration::from_millis(2));
assert_eq!(profile_mode(), ProfileMode::Summary);
set_profile_mode(ProfileMode::Off);
reset();
}
}