consensus_core/network/
metrics_layer.rsuse std::sync::Arc;
use prometheus::HistogramTimer;
use super::metrics::NetworkRouteMetrics;
pub(crate) trait SizedRequest {
fn size(&self) -> usize;
fn route(&self) -> String;
}
pub(crate) trait SizedResponse {
fn size(&self) -> usize;
fn error_type(&self) -> Option<String>;
}
#[derive(Clone)]
pub(crate) struct MetricsCallbackMaker {
metrics: Arc<NetworkRouteMetrics>,
excessive_message_size: usize,
}
impl MetricsCallbackMaker {
pub(crate) fn new(metrics: Arc<NetworkRouteMetrics>, excessive_message_size: usize) -> Self {
Self {
metrics,
excessive_message_size,
}
}
pub(crate) fn handle_request(&self, request: &dyn SizedRequest) -> MetricsResponseCallback {
let route = request.route();
self.metrics.requests.with_label_values(&[&route]).inc();
self.metrics
.inflight_requests
.with_label_values(&[&route])
.inc();
let request_size = request.size();
if request_size > 0 {
self.metrics
.request_size
.with_label_values(&[&route])
.observe(request_size as f64);
}
if request_size > self.excessive_message_size {
self.metrics
.excessive_size_requests
.with_label_values(&[&route])
.inc();
}
let timer = self
.metrics
.request_latency
.with_label_values(&[&route])
.start_timer();
MetricsResponseCallback {
metrics: self.metrics.clone(),
timer,
route,
excessive_message_size: self.excessive_message_size,
}
}
}
pub(crate) struct MetricsResponseCallback {
metrics: Arc<NetworkRouteMetrics>,
#[allow(unused)]
timer: HistogramTimer,
route: String,
excessive_message_size: usize,
}
impl MetricsResponseCallback {
pub(crate) fn on_response(&mut self, response: &dyn SizedResponse) {
let response_size = response.size();
if response_size > 0 {
self.metrics
.response_size
.with_label_values(&[&self.route])
.observe(response_size as f64);
}
if response_size > self.excessive_message_size {
self.metrics
.excessive_size_responses
.with_label_values(&[&self.route])
.inc();
}
if let Some(err) = response.error_type() {
self.metrics
.errors
.with_label_values(&[&self.route, &err])
.inc();
}
}
pub(crate) fn on_error<E>(&mut self, _error: &E) {
self.metrics
.errors
.with_label_values(&[&self.route, "unknown"])
.inc();
}
}
impl Drop for MetricsResponseCallback {
fn drop(&mut self) {
self.metrics
.inflight_requests
.with_label_values(&[&self.route])
.dec();
}
}