use anyhow::Context;
use serde::Serialize;
use std::io::Write;
pub(crate) mod metadata;
const TARGET: &str = "rcp::timing";
const FINISHED_FIELD: &str = "timing_finished";
const MAX_SCOPES: usize = 256;
const MAX_HISTOGRAM_MICROS: u64 = 1 << 56;
#[macro_export]
macro_rules! timing_scope {
($name:literal) => {
$crate::timing::Scope::new(tracing::info_span!(
target: "rcp::timing", $name, timing_finished = tracing::field::Empty
))
};
(trace, $name:literal) => {
$crate::timing::Scope::new(tracing::trace_span!(
target: "rcp::timing", $name, timing_finished = tracing::field::Empty
))
};
}
#[must_use = "keep the timing scope alive until the measured work finishes"]
pub struct Scope {
span: Option<tracing::Span>,
}
impl Scope {
#[doc(hidden)]
pub fn new(span: tracing::Span) -> Self {
Self { span: Some(span) }
}
fn span(&self) -> &tracing::Span {
self.span.as_ref().expect("scope has not finished")
}
pub async fn measure<F: std::future::Future>(self, future: F) -> F::Output {
use tracing::Instrument;
let output = future.instrument(self.span().clone()).await;
self.finish();
output
}
pub fn finish(mut self) {
if let Some(span) = self.span.take() {
span.record(FINISHED_FIELD, true);
}
}
}
impl Drop for Scope {
fn drop(&mut self) {
if let Some(span) = self.span.take() {
span.record(FINISHED_FIELD, false);
}
}
}
pub(crate) fn timing_filter(detail: bool) -> tracing_subscriber::filter::Targets {
tracing_subscriber::filter::Targets::new().with_target(
TARGET,
if detail {
tracing::Level::TRACE
} else {
tracing::Level::INFO
},
)
}
struct ActiveScope {
name: &'static str,
start: std::time::Instant,
lane: u64,
}
struct Aggregate {
finished: u64,
interrupted: u64,
total: std::time::Duration,
max: std::time::Duration,
histogram: hdrhistogram::Histogram<u64>,
}
impl Default for Aggregate {
fn default() -> Self {
Self {
finished: 0,
interrupted: 0,
total: std::time::Duration::ZERO,
max: std::time::Duration::ZERO,
histogram: hdrhistogram::Histogram::new_with_bounds(1, MAX_HISTOGRAM_MICROS, 2)
.expect("valid fixed histogram bounds"),
}
}
}
impl Aggregate {
fn record(&mut self, elapsed: std::time::Duration, finished: bool) {
if finished {
self.finished += 1;
} else {
self.interrupted += 1;
}
self.total = self.total.saturating_add(elapsed);
self.max = self.max.max(elapsed);
let micros = elapsed.as_micros().min(u128::from(MAX_HISTOGRAM_MICROS)) as u64;
self.histogram
.record(micros)
.expect("sample is within fixed bounds");
}
fn summary(&self, name: &'static str) -> ScopeSummary {
let count = self.finished + self.interrupted;
ScopeSummary {
name,
count,
finished: self.finished,
interrupted: self.interrupted,
total_seconds: self.total.as_secs_f64(),
mean_seconds: self.total.as_secs_f64() / count as f64,
p50_seconds: self.histogram.value_at_quantile(0.5) as f64 / 1_000_000.0,
p95_seconds: self.histogram.value_at_quantile(0.95) as f64 / 1_000_000.0,
max_seconds: self.max.as_secs_f64(),
}
}
}
#[derive(Serialize)]
struct ScopeSummary {
name: &'static str,
count: u64,
finished: u64,
interrupted: u64,
total_seconds: f64,
mean_seconds: f64,
p50_seconds: f64,
p95_seconds: f64,
max_seconds: f64,
}
#[derive(Serialize)]
struct Summary<'a> {
schema_version: u8,
identifier: &'a str,
pid: u32,
scopes: Vec<ScopeSummary>,
}
struct State {
identifier: String,
epoch: std::time::Instant,
next_lane: u64,
available_lanes: std::collections::BinaryHeap<std::cmp::Reverse<(std::time::Instant, u64)>>,
aggregates: std::collections::BTreeMap<&'static str, Aggregate>,
summary: Option<std::fs::File>,
timeline: Option<std::io::BufWriter<std::fs::File>>,
timeline_started: bool,
error: Option<anyhow::Error>,
finalized: bool,
}
impl State {
fn allocate_lane(&mut self, start: std::time::Instant) -> u64 {
if self.timeline.is_none() {
return 0;
}
if let Some(std::cmp::Reverse((end, _))) = self.available_lanes.peek()
&& *end <= start
{
return self.available_lanes.pop().unwrap().0.1;
}
self.next_lane += 1;
self.next_lane
}
fn record(&mut self, scope: ActiveScope, finished: bool, end: std::time::Instant) {
if self.finalized {
return;
}
let elapsed = end.duration_since(scope.start);
if self.summary.is_some() {
let name = if self.aggregates.contains_key(scope.name)
|| self.aggregates.len() < MAX_SCOPES - 1
{
scope.name
} else {
"__overflow__"
};
self.aggregates
.entry(name)
.or_default()
.record(elapsed, finished);
}
if let Some(timeline) = &mut self.timeline {
let event = serde_json::json!({
"name": scope.name, "cat": TARGET, "ph": "X",
"pid": std::process::id(), "tid": scope.lane,
"ts": scope.start.duration_since(self.epoch).as_secs_f64() * 1_000_000.0,
"dur": elapsed.as_secs_f64() * 1_000_000.0,
"args": { "identifier": self.identifier, "finished": finished }
});
let separator: &[u8] = if self.timeline_started {
b",\n"
} else {
b"[\n"
};
let result = timeline
.write_all(separator)
.map_err(anyhow::Error::from)
.and_then(|()| serde_json::to_writer(timeline, &event).map_err(Into::into));
self.timeline_started = true;
if self.error.is_none() {
self.error = result.err();
}
self.available_lanes
.push(std::cmp::Reverse((end, scope.lane)));
}
}
}
pub(crate) struct TimingLayer {
state: std::sync::Arc<std::sync::Mutex<State>>,
timeline_enabled: bool,
}
impl TimingLayer {
pub(crate) fn new(
identifier: String,
summary: Option<std::fs::File>,
timeline: Option<std::fs::File>,
) -> (Self, TimingGuard) {
let timeline_enabled = timeline.is_some();
let state = std::sync::Arc::new(std::sync::Mutex::new(State {
identifier,
epoch: std::time::Instant::now(),
next_lane: 0,
available_lanes: std::collections::BinaryHeap::new(),
aggregates: std::collections::BTreeMap::new(),
summary,
timeline: timeline.map(std::io::BufWriter::new),
timeline_started: false,
error: None,
finalized: false,
}));
(
Self {
state: state.clone(),
timeline_enabled,
},
TimingGuard { state },
)
}
}
#[derive(Default)]
struct Completion(Option<bool>);
impl tracing::field::Visit for Completion {
fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {
if field.name() == FINISHED_FIELD {
self.0 = Some(value);
}
}
fn record_debug(&mut self, _: &tracing::field::Field, _: &dyn std::fmt::Debug) {}
}
impl<S> tracing_subscriber::Layer<S> for TimingLayer
where
S: tracing::Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
{
fn on_new_span(
&self,
attributes: &tracing::span::Attributes<'_>,
id: &tracing::span::Id,
context: tracing_subscriber::layer::Context<'_, S>,
) {
if attributes.metadata().target() != TARGET
|| attributes
.metadata()
.fields()
.field(FINISHED_FIELD)
.is_none()
{
return;
}
let start = std::time::Instant::now();
let lane = if self.timeline_enabled {
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
state.allocate_lane(start)
} else {
0
};
if let Some(span) = context.span(id) {
span.extensions_mut().insert(ActiveScope {
name: attributes.metadata().name(),
start,
lane,
});
}
}
fn on_record(
&self,
id: &tracing::span::Id,
values: &tracing::span::Record<'_>,
context: tracing_subscriber::layer::Context<'_, S>,
) {
let mut completion = Completion::default();
values.record(&mut completion);
if let Some(finished) = completion.0
&& let Some(span) = context.span(id)
{
let scope = span.extensions_mut().remove::<ActiveScope>();
if let Some(scope) = scope {
let end = std::time::Instant::now();
self.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.record(scope, finished, end);
}
}
}
}
pub(crate) struct TimingGuard {
state: std::sync::Arc<std::sync::Mutex<State>>,
}
impl TimingGuard {
pub(crate) fn finish(&mut self) -> anyhow::Result<()> {
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if state.finalized {
return Ok(());
}
state.finalized = true;
let mut error = state.error.take();
if let Some(file) = state.summary.take() {
let summary = Summary {
schema_version: 1,
identifier: &state.identifier,
pid: std::process::id(),
scopes: state
.aggregates
.iter()
.map(|(&name, aggregate)| aggregate.summary(name))
.collect(),
};
let mut writer = std::io::BufWriter::new(file);
let result = serde_json::to_writer_pretty(&mut writer, &summary)
.context("failed to write timing summary")
.and_then(|()| writer.flush().context("failed to flush timing summary"));
if error.is_none() {
error = result.err();
}
}
if let Some(mut timeline) = state.timeline.take() {
let closing: &[u8] = if state.timeline_started {
b"\n]\n"
} else {
b"[]\n"
};
let result = timeline
.write_all(closing)
.and_then(|()| timeline.flush())
.context("failed to flush elapsed scope timeline");
if error.is_none() {
error = result.err();
}
}
match error {
Some(error) => Err(error),
None => Ok(()),
}
}
}
impl Drop for TimingGuard {
fn drop(&mut self) {
if let Err(error) = self.finish() {
eprintln!("Failed to write scoped timings: {error:#}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use tracing_subscriber::prelude::*;
fn collector(detail: bool) -> (tracing::Dispatch, TimingGuard, tempfile::NamedTempFile) {
let file = tempfile::NamedTempFile::new().unwrap();
let (layer, guard) =
TimingLayer::new("test-role".into(), Some(file.reopen().unwrap()), None);
let subscriber =
tracing_subscriber::registry().with(layer.with_filter(timing_filter(detail)));
(tracing::Dispatch::new(subscriber), guard, file)
}
fn report(guard: &mut TimingGuard, file: &tempfile::NamedTempFile) -> serde_json::Value {
guard.finish().unwrap();
serde_json::from_reader(file.reopen().unwrap()).unwrap()
}
#[test]
fn finished_scope_is_recorded_before_clones_and_children_drop() {
tracing::subscriber::with_default(tracing_subscriber::registry(), || {
let (dispatch, mut guard, file) = collector(false);
tracing::dispatcher::with_default(&dispatch, || {
let scope = crate::timing_scope!("parent");
let clone = scope.span().clone();
let child =
tracing::info_span!(target: "rcp::timing", parent: scope.span(), "child");
scope.finish();
let result = report(&mut guard, &file);
assert_eq!(result["schema_version"], 1);
assert_eq!(result["identifier"], "test-role");
assert_eq!(result["pid"], std::process::id());
assert_eq!(result["scopes"].as_array().unwrap().len(), 1);
assert_eq!(result["scopes"][0]["count"], 1);
assert_eq!(result["scopes"][0]["finished"], 1);
assert_eq!(result["scopes"][0]["interrupted"], 0);
drop((clone, child));
});
});
}
#[test]
fn scope_drop_records_interruption_with_original_subscriber() {
let (dispatch, mut guard, file) = collector(false);
let scope =
tracing::dispatcher::with_default(&dispatch, || crate::timing_scope!("dropped"));
drop(scope);
let result = report(&mut guard, &file);
assert_eq!(result["scopes"][0]["count"], 1);
assert_eq!(result["scopes"][0]["finished"], 0);
assert_eq!(result["scopes"][0]["interrupted"], 1);
}
#[test]
fn detail_scopes_require_explicit_enablement() {
for detail in [false, true] {
let (dispatch, mut guard, file) = collector(detail);
tracing::dispatcher::with_default(&dispatch, || {
crate::timing_scope!("coarse").finish();
crate::timing_scope!(trace, "detail").finish();
});
let result = report(&mut guard, &file);
assert_eq!(
result["scopes"].as_array().unwrap().len(),
if detail { 2 } else { 1 }
);
}
}
#[test]
fn elapsed_time_includes_async_suspension_and_cancellation() {
let (dispatch, mut guard, file) = collector(false);
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.unwrap();
tracing::dispatcher::with_default(&dispatch, || {
runtime.block_on(async {
let scope = crate::timing_scope!("suspension");
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
scope.finish();
let task = tokio::spawn(async {
let _scope = crate::timing_scope!("cancellation");
std::future::pending::<()>().await;
});
tokio::task::yield_now().await;
task.abort();
assert!(task.await.unwrap_err().is_cancelled());
})
});
let result = report(&mut guard, &file);
let scopes = result["scopes"].as_array().unwrap();
let suspended = scopes.iter().find(|s| s["name"] == "suspension").unwrap();
assert!(suspended["total_seconds"].as_f64().unwrap() >= 0.015);
let cancelled = scopes.iter().find(|s| s["name"] == "cancellation").unwrap();
assert_eq!(cancelled["interrupted"], 1);
}
#[test]
fn measured_error_results_are_finished_and_cancelled_futures_are_interrupted() {
let (dispatch, mut guard, file) = collector(false);
let runtime = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
tracing::dispatcher::with_default(&dispatch, || {
runtime.block_on(async {
let result = crate::timing_scope!("error-result")
.measure(async { Err::<(), _>("failed") })
.await;
assert_eq!(result, Err("failed"));
let task = tokio::spawn(
crate::timing_scope!("cancelled-future").measure(std::future::pending::<()>()),
);
tokio::task::yield_now().await;
task.abort();
assert!(task.await.unwrap_err().is_cancelled());
})
});
let result = report(&mut guard, &file);
let scopes = result["scopes"].as_array().unwrap();
assert_eq!(
scopes.iter().find(|s| s["name"] == "error-result").unwrap()["finished"],
1
);
assert_eq!(
scopes
.iter()
.find(|s| s["name"] == "cancelled-future")
.unwrap()["interrupted"],
1
);
}
#[test]
fn concurrent_scopes_keep_exact_counts() {
let (dispatch, mut guard, file) = collector(false);
std::thread::scope(|threads| {
for _ in 0..8 {
threads.spawn(|| {
tracing::dispatcher::with_default(&dispatch, || {
for _ in 0..100 {
crate::timing_scope!("parallel").finish();
drop(crate::timing_scope!("parallel"));
}
})
});
}
});
let result = report(&mut guard, &file);
assert_eq!(result["scopes"][0]["count"], 1600);
assert_eq!(result["scopes"][0]["finished"], 800);
assert_eq!(result["scopes"][0]["interrupted"], 800);
}
#[test]
fn summary_distribution_includes_interrupted_samples() {
let mut aggregate = Aggregate::default();
aggregate.record(std::time::Duration::from_secs(1), true);
aggregate.record(std::time::Duration::from_secs(3), false);
let summary = aggregate.summary("distribution");
assert_eq!(summary.count, 2);
assert_eq!(summary.total_seconds, 4.0);
assert_eq!(summary.mean_seconds, 2.0);
assert!((summary.p50_seconds - 1.0).abs() < 0.01);
assert!((summary.p95_seconds - 3.0).abs() < 0.03);
assert_eq!(summary.max_seconds, 3.0);
}
#[test]
fn overlapping_timeline_scopes_have_distinct_lanes() {
let file = tempfile::NamedTempFile::new().unwrap();
let (layer, mut guard) =
TimingLayer::new("timeline".into(), None, Some(file.reopen().unwrap()));
let subscriber =
tracing_subscriber::registry().with(layer.with_filter(timing_filter(false)));
tracing::subscriber::with_default(subscriber, || {
let first = crate::timing_scope!("overlap");
let second = crate::timing_scope!("overlap");
first.finish();
drop(second);
});
guard.finish().unwrap();
let events: serde_json::Value = serde_json::from_reader(file.reopen().unwrap()).unwrap();
let events = events.as_array().unwrap();
assert_eq!(events.len(), 2);
assert_ne!(events[0]["tid"], events[1]["tid"]);
assert_eq!(events[0]["ph"], "X");
assert_eq!(events[0]["args"]["finished"], true);
assert_eq!(events[1]["args"]["finished"], false);
}
#[test]
fn sequential_timeline_scopes_reuse_lanes_while_another_scope_stays_active() {
let file = tempfile::NamedTempFile::new().unwrap();
let (layer, mut guard) =
TimingLayer::new("timeline".into(), None, Some(file.reopen().unwrap()));
let subscriber =
tracing_subscriber::registry().with(layer.with_filter(timing_filter(false)));
tracing::subscriber::with_default(subscriber, || {
let outer = crate::timing_scope!("outer");
for _ in 0..64 {
crate::timing_scope!("sequential").finish();
}
drop(outer);
});
guard.finish().unwrap();
let events: serde_json::Value = serde_json::from_reader(file.reopen().unwrap()).unwrap();
let events = events.as_array().unwrap();
assert_eq!(events.len(), 65);
let sequential_lane = &events[0]["tid"];
for event in &events[..64] {
assert_eq!(&event["tid"], sequential_lane);
}
assert_ne!(&events[64]["tid"], sequential_lane);
}
#[test]
fn delayed_scope_registration_cannot_reuse_an_overlapping_lane() {
let file = tempfile::NamedTempFile::new().unwrap();
let (_, guard) = TimingLayer::new("timeline".into(), None, Some(file.reopen().unwrap()));
let mut state = guard.state.lock().unwrap();
let start = state.epoch;
let first_lane = state.allocate_lane(start);
state.record(
ActiveScope {
name: "first",
start,
lane: first_lane,
},
true,
start + std::time::Duration::from_secs(2),
);
let overlapping_lane = state.allocate_lane(start + std::time::Duration::from_secs(1));
assert_ne!(overlapping_lane, first_lane);
let later_lane = state.allocate_lane(start + std::time::Duration::from_secs(3));
assert_eq!(later_lane, first_lane);
}
#[test]
fn summary_only_scopes_do_not_allocate_timeline_lanes() {
let (dispatch, guard, _file) = collector(false);
tracing::dispatcher::with_default(&dispatch, || {
for _ in 0..64 {
crate::timing_scope!("summary").finish();
}
});
let state = guard.state.lock().unwrap();
assert_eq!(state.next_lane, 0);
assert_eq!(state.aggregates["summary"].finished, 64);
}
#[test]
fn output_write_failures_are_returned() {
let file = std::fs::OpenOptions::new()
.write(true)
.open("/dev/full")
.unwrap();
let (_, mut guard) = TimingLayer::new("unwritable".into(), Some(file), None);
assert!(guard.finish().is_err());
}
#[test]
fn empty_outputs_are_valid_and_finalization_is_idempotent() {
let summary = tempfile::NamedTempFile::new().unwrap();
let timeline = tempfile::NamedTempFile::new().unwrap();
let (_, mut guard) = TimingLayer::new(
"empty".into(),
Some(summary.reopen().unwrap()),
Some(timeline.reopen().unwrap()),
);
guard.finish().unwrap();
guard.finish().unwrap();
let result: serde_json::Value = serde_json::from_reader(summary.reopen().unwrap()).unwrap();
assert_eq!(result["scopes"], serde_json::json!([]));
let events: serde_json::Value =
serde_json::from_reader(timeline.reopen().unwrap()).unwrap();
assert_eq!(events, serde_json::json!([]));
}
#[test]
fn extra_scope_names_fold_into_bounded_overflow_bucket() {
let (dispatch, mut guard, file) = collector(false);
drop(dispatch);
{
let mut state = guard.state.lock().unwrap();
for index in 0..300 {
let name = Box::leak(format!("scope-{index}").into_boxed_str());
let start = std::time::Instant::now();
state.record(
ActiveScope {
name,
start,
lane: index,
},
true,
start,
);
}
}
let result = report(&mut guard, &file);
let scopes = result["scopes"].as_array().unwrap();
assert_eq!(scopes.len(), 256);
assert_eq!(
scopes
.iter()
.map(|scope| scope["count"].as_u64().unwrap())
.sum::<u64>(),
300
);
let overflow = scopes
.iter()
.find(|scope| scope["name"] == "__overflow__")
.unwrap();
assert_eq!(overflow["count"], 45);
}
#[test]
fn elapsed_timeline_write_failures_are_returned() {
let file = std::fs::OpenOptions::new()
.write(true)
.open("/dev/full")
.unwrap();
let (layer, mut guard) = TimingLayer::new("unwritable".into(), None, Some(file));
let subscriber =
tracing_subscriber::registry().with(layer.with_filter(timing_filter(false)));
tracing::subscriber::with_default(subscriber, || crate::timing_scope!("scope").finish());
assert!(guard.finish().is_err());
}
}