use serde::Serialize;
use std::cell::RefCell;
macro_rules! event_stages {
($($variant:ident = $id:literal => $label:literal),+ $(,)?) => {
#[derive(Clone, Copy)]
#[repr(u32)]
pub enum EventStage {
$(#[doc = $label] $variant = $id,)+
}
pub const EVENT_STAGES: &[(u32, &str)] = &[$(($id, $label),)+];
};
}
event_stages! {
EvaluateSetup = 100 => "evaluate.setup",
RoundEngineSetup = 200 => "round.engine_setup",
RoundBind = 201 => "round.bind",
RoundForceRootsInitial = 202 => "round.force_roots_initial",
RoundSettle = 203 => "round.settle",
RoundEditsFinish = 204 => "round.edits_finish",
RoundEdgeKeyAndCycle = 205 => "round.edge_key_and_cycle",
RoundAdvance = 206 => "round.advance",
RoundRetainedTransfer = 207 => "round.retained_round_transfer",
RoundCompleteDropPrevious = 208 => "round.complete_drop_previous_and_identity_sweep",
RoundFallbackFreezeReset = 209 => "round.fallback_freeze_reset",
SettleTakeSnapshot = 300 => "settle.take_snapshot",
SettleDeferredSnapshot = 301 => "settle.deferred_snapshot",
SettleForceDeferredSlots = 302 => "settle.force_deferred_slots",
SettleBindDeferredRoots = 303 => "settle.bind_deferred_roots",
SettleForceRoots = 304 => "settle.force_roots",
SettleLiveEdges = 305 => "settle.live_edges",
SettleCompareEdges = 306 => "settle.compare_edges",
AdvanceClassify = 400 => "advance.classify",
AdvanceFreeze = 401 => "advance.freeze",
AdvanceRevisionReset = 402 => "advance.revision_reset",
RootDispatch = 500 => "root.dispatch",
RootSourceEval = 501 => "root.source_eval",
RootTypeBind = 502 => "root.recursive_bind",
RootDispatchReturn = 503 => "root.dispatch_return",
RootPublishOrDefer = 504 => "root.publish_or_handle",
RootScopeRelease = 505 => "root.scope_release",
}
#[derive(Clone, Copy, Serialize)]
pub struct Stamp {
pub wall_ns: u64,
pub cpu_ns: u64,
pub sampled_until_ns: u64,
pub allocation: crate::allocation_diagnostics::Snapshot,
pub prefix_paths: crate::semantics::PrefixPathDiagnostics,
pub traffic: crate::retention_diagnostics::TrafficSnapshot,
}
fn clock_ns(id: libc::clockid_t) -> u64 {
let mut ts = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
assert_eq!(unsafe { libc::clock_gettime(id, &mut ts) }, 0);
ts.tv_sec as u64 * 1_000_000_000 + ts.tv_nsec as u64
}
impl Stamp {
fn now() -> Self {
let wall_ns = clock_ns(libc::CLOCK_MONOTONIC);
let cpu_ns = clock_ns(libc::CLOCK_PROCESS_CPUTIME_ID);
let sampled_until_ns = clock_ns(libc::CLOCK_MONOTONIC);
Self {
wall_ns,
cpu_ns,
sampled_until_ns,
allocation: crate::allocation_diagnostics::snapshot(),
prefix_paths: crate::semantics::prefix_path_diagnostics(),
traffic: crate::retention_diagnostics::traffic_snapshot(),
}
}
}
#[derive(Serialize)]
pub struct Stage {
pub name: &'static str,
pub start: Stamp,
pub end: Stamp,
pub wall_ns: u64,
pub cpu_ns: u64,
}
#[derive(Serialize)]
pub struct Span {
pub kind: &'static str,
pub ordinal: usize,
pub start: Stamp,
pub stages: Vec<Stage>,
previous: Stamp,
#[serde(skip)]
event_scope: Option<crate::phase_events::EventScope>,
}
thread_local! { static SPANS: RefCell<Vec<Span>> = const { RefCell::new(Vec::new()) }; }
impl Span {
pub fn new(kind: &'static str, ordinal: usize) -> Self {
let start = Stamp::now();
Self {
kind,
ordinal,
start,
stages: Vec::new(),
previous: start,
event_scope: None,
}
}
pub fn enter(&mut self, stage: EventStage) {
match &self.event_scope {
Some(scope) => scope.transition(stage as u32),
None => {
self.event_scope = Some(crate::phase_events::EventScope::begin(
stage as u32,
self.ordinal as u64,
crate::phase_events::RootIdentity::NONE,
));
}
}
}
pub fn mark(&mut self, name: &'static str) {
let end = Stamp::now();
self.stages.push(Stage {
name,
start: self.previous,
end,
wall_ns: end.wall_ns - self.previous.wall_ns,
cpu_ns: end.cpu_ns - self.previous.cpu_ns,
});
self.previous = end;
}
pub fn finish(self) {
if let Some(scope) = &self.event_scope {
use crate::phase_events::Outcome;
scope.finish(match self.kind {
"advance_rejected" => Outcome::Rejected,
"advance_unwound" => Outcome::Unwound,
_ => Outcome::Ok,
});
}
SPANS.with(|s| s.borrow_mut().push(self));
}
}
pub(crate) struct AdvanceSpan {
span: Option<Span>,
active: &'static str,
accepted: bool,
}
impl AdvanceSpan {
pub(crate) fn new(ordinal: usize) -> Self {
let mut span = Span::new("advance_rejected", ordinal);
span.enter(EventStage::AdvanceClassify);
Self {
span: Some(span),
active: "classify",
accepted: false,
}
}
pub(crate) fn classified(&mut self) {
self.span.as_mut().unwrap().mark("classify");
self.span.as_mut().unwrap().enter(EventStage::AdvanceFreeze);
self.active = "freeze";
}
pub(crate) fn frozen(&mut self) {
self.span.as_mut().unwrap().mark("freeze");
self.span
.as_mut()
.unwrap()
.enter(EventStage::AdvanceRevisionReset);
self.active = "revision_reset";
}
pub(crate) fn accepted(&mut self) {
self.accepted = true;
}
}
impl Drop for AdvanceSpan {
fn drop(&mut self) {
let mut span = self.span.take().unwrap();
span.kind = if std::thread::panicking() {
"advance_unwound"
} else if self.accepted {
"advance"
} else {
"advance_rejected"
};
span.mark(self.active);
span.finish();
}
}
pub fn take_evaluation_diagnostics() -> Vec<Span> {
SPANS.with(|s| std::mem::take(&mut *s.borrow_mut()))
}