sc_transaction_pool/common/
metrics.rs1use prometheus_endpoint::{register, Counter, PrometheusError, Registry, U64};
22use std::sync::Arc;
23
24use crate::LOG_TARGET;
25
26pub(crate) trait MetricsRegistrant {
28 fn register(registry: &Registry) -> Result<Box<Self>, PrometheusError>;
30}
31
32pub(crate) struct GenericMetricsLink<M: MetricsRegistrant>(Arc<Option<Box<M>>>);
34
35impl<M: MetricsRegistrant> Default for GenericMetricsLink<M> {
36 fn default() -> Self {
37 Self(Arc::from(None))
38 }
39}
40
41impl<M: MetricsRegistrant> Clone for GenericMetricsLink<M> {
42 fn clone(&self) -> Self {
43 Self(self.0.clone())
44 }
45}
46
47impl<M: MetricsRegistrant> GenericMetricsLink<M> {
48 pub fn new(registry: Option<&Registry>) -> Self {
49 Self(Arc::new(registry.and_then(|registry| {
50 M::register(registry)
51 .map_err(|error| {
52 tracing::warn!(
53 target: LOG_TARGET,
54 %error,
55 "Failed to register prometheus metrics"
56 );
57 })
58 .ok()
59 })))
60 }
61
62 pub fn report(&self, do_this: impl FnOnce(&M)) {
63 if let Some(metrics) = self.0.as_ref() {
64 do_this(&**metrics);
65 }
66 }
67}
68
69pub struct ApiMetrics {
71 pub validations_scheduled: Counter<U64>,
72 pub validations_finished: Counter<U64>,
73}
74
75impl ApiMetrics {
76 pub fn register(registry: &Registry) -> Result<Self, PrometheusError> {
78 Ok(Self {
79 validations_scheduled: register(
80 Counter::new(
81 "substrate_sub_txpool_validations_scheduled",
82 "Total number of transactions scheduled for validation",
83 )?,
84 registry,
85 )?,
86 validations_finished: register(
87 Counter::new(
88 "substrate_sub_txpool_validations_finished",
89 "Total number of transactions that finished validation",
90 )?,
91 registry,
92 )?,
93 })
94 }
95}
96
97pub trait ApiMetricsExt {
99 fn report(&self, report: impl FnOnce(&ApiMetrics));
101}
102
103impl ApiMetricsExt for Option<Arc<ApiMetrics>> {
104 fn report(&self, report: impl FnOnce(&ApiMetrics)) {
105 if let Some(metrics) = self.as_ref() {
106 report(metrics)
107 }
108 }
109}