use std::sync::Arc;
use metrics::{
Counter, Gauge, Histogram, HistogramFn, Key, KeyName, Metadata, Recorder, SharedString, Unit,
};
use sentry::metrics::DistributionMetric;
use zebra_chain::{
block::Height,
parameters::{Network, NetworkUpgrade},
};
const DISTRIBUTIONS: &[&str] = &[
"zebra.consensus.block.phase.duration_seconds",
"state.block_writer.phase.duration_seconds",
];
pub(crate) fn send_tip_block_delay(height: Height, seconds: f64) {
tip_block_delay(super::NETWORK.get(), height, seconds).capture();
}
pub(super) fn tip_block_delay(
network: Option<&Network>,
height: Height,
seconds: f64,
) -> DistributionMetric {
let distribution =
sentry::metrics::distribution("zcash.chain.tip.block_delay_seconds", seconds)
.unit(sentry::protocol::Unit::Second)
.attribute("chain.height", height.0);
match network {
Some(network) => distribution.attribute(
"chain.network_upgrade",
NetworkUpgrade::current(network, height).to_string(),
),
None => distribution,
}
}
#[derive(Debug)]
pub(crate) struct SentryRecorder;
impl Recorder for SentryRecorder {
fn describe_counter(&self, _: KeyName, _: Option<Unit>, _: SharedString) {}
fn describe_gauge(&self, _: KeyName, _: Option<Unit>, _: SharedString) {}
fn describe_histogram(&self, _: KeyName, _: Option<Unit>, _: SharedString) {}
fn register_counter(&self, key: &Key, _: &Metadata<'_>) -> Counter {
super::periodic::counter(key).unwrap_or_else(Counter::noop)
}
fn register_gauge(&self, key: &Key, _: &Metadata<'_>) -> Gauge {
super::periodic::gauge(key).unwrap_or_else(Gauge::noop)
}
fn register_histogram(&self, key: &Key, _: &Metadata<'_>) -> Histogram {
if DISTRIBUTIONS.contains(&key.name()) {
Histogram::from_arc(Arc::new(Distribution(key.clone())))
} else {
Histogram::noop()
}
}
}
struct Distribution(Key);
impl HistogramFn for Distribution {
fn record(&self, value: f64) {
if !super::is_close_to_tip() {
return;
}
let mut distribution = sentry::metrics::distribution(self.0.name().to_owned(), value)
.unit(sentry::protocol::Unit::Second);
for label in self.0.labels() {
distribution = distribution.attribute(label.key().to_owned(), label.value().to_owned());
}
distribution.capture();
}
}