sc_proposer_metrics/
lib.rs1use prometheus_endpoint::{
22	prometheus::CounterVec, register, Gauge, Histogram, HistogramOpts, Opts, PrometheusError,
23	Registry, U64,
24};
25
26#[derive(Clone, Default)]
28pub struct MetricsLink(Option<Metrics>);
29
30impl MetricsLink {
31	pub fn new(registry: Option<&Registry>) -> Self {
32		Self(registry.and_then(|registry| {
33			Metrics::register(registry)
34				.map_err(|err| {
35					log::warn!("Failed to register proposer prometheus metrics: {}", err)
36				})
37				.ok()
38		}))
39	}
40
41	pub fn report<O>(&self, do_this: impl FnOnce(&Metrics) -> O) -> Option<O> {
42		self.0.as_ref().map(do_this)
43	}
44}
45
46#[derive(Clone, Copy, PartialEq, Eq, Debug)]
48pub enum EndProposingReason {
49	NoMoreTransactions,
50	HitDeadline,
51	HitBlockSizeLimit,
52	HitBlockWeightLimit,
53	TransactionForbidden,
55}
56
57#[derive(Clone)]
59pub struct Metrics {
60	pub block_constructed: Histogram,
61	pub number_of_transactions: Gauge<U64>,
62	pub end_proposing_reason: CounterVec,
63	pub create_inherents_time: Histogram,
64	pub create_block_proposal_time: Histogram,
65}
66
67impl Metrics {
68	pub fn register(registry: &Registry) -> Result<Self, PrometheusError> {
69		Ok(Self {
70			block_constructed: register(
71				Histogram::with_opts(HistogramOpts::new(
72					"substrate_proposer_block_constructed",
73					"Histogram of time taken to construct new block",
74				))?,
75				registry,
76			)?,
77			number_of_transactions: register(
78				Gauge::new(
79					"substrate_proposer_number_of_transactions",
80					"Number of transactions included in block",
81				)?,
82				registry,
83			)?,
84			create_inherents_time: register(
85				Histogram::with_opts(HistogramOpts::new(
86					"substrate_proposer_create_inherents_time",
87					"Histogram of time taken to execute create inherents",
88				))?,
89				registry,
90			)?,
91			create_block_proposal_time: register(
92				Histogram::with_opts(HistogramOpts::new(
93					"substrate_proposer_block_proposal_time",
94					"Histogram of time taken to construct a block and prepare it for proposal",
95				))?,
96				registry,
97			)?,
98			end_proposing_reason: register(
99				CounterVec::new(
100					Opts::new(
101						"substrate_proposer_end_proposal_reason",
102						"The reason why the block proposing was ended. This doesn't include errors.",
103					),
104					&["reason"],
105				)?,
106				registry,
107			)?,
108		})
109	}
110
111	pub fn report_end_proposing_reason(&self, reason: EndProposingReason) {
113		let reason = match reason {
114			EndProposingReason::HitDeadline => "hit_deadline",
115			EndProposingReason::NoMoreTransactions => "no_more_transactions",
116			EndProposingReason::HitBlockSizeLimit => "hit_block_size_limit",
117			EndProposingReason::HitBlockWeightLimit => "hit_block_weight_limit",
118			EndProposingReason::TransactionForbidden => "transactions_forbidden",
119		};
120
121		self.end_proposing_reason.with_label_values(&[reason]).inc();
122	}
123}