use std::future::Future;
use std::time::Instant;
use prometheus_client::encoding::{EncodeLabelSet, EncodeLabelValue, LabelValueEncoder};
use prometheus_client::metrics::counter::Counter;
use prometheus_client::metrics::family::Family;
use prometheus_client::metrics::gauge::Gauge;
use prometheus_client::metrics::histogram::Histogram;
use prometheus_client::registry::Registry;
use super::buckets;
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum Store {
P2p,
Registry,
Refit,
}
impl Store {
const fn as_str(self) -> &'static str {
match self {
Self::P2p => "p2p",
Self::Registry => "registry",
Self::Refit => "refit",
}
}
}
impl EncodeLabelValue for Store {
fn encode(&self, encoder: &mut LabelValueEncoder<'_>) -> Result<(), std::fmt::Error> {
EncodeLabelValue::encode(&self.as_str(), encoder)
}
}
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum OpResult {
Ok,
Error,
Cancelled,
}
impl OpResult {
const fn as_str(self) -> &'static str {
match self {
Self::Ok => "ok",
Self::Error => "error",
Self::Cancelled => "cancelled",
}
}
}
impl EncodeLabelValue for OpResult {
fn encode(&self, encoder: &mut LabelValueEncoder<'_>) -> Result<(), std::fmt::Error> {
EncodeLabelValue::encode(&self.as_str(), encoder)
}
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct BackendLabels {
pub store: Store,
pub op: &'static str,
pub result: OpResult,
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct BackendOpLabels {
pub store: Store,
pub op: &'static str,
}
fn fast_histogram() -> Histogram {
Histogram::new(buckets::FAST)
}
type LatencyFamily = Family<BackendLabels, Histogram, fn() -> Histogram>;
#[derive(Clone)]
pub struct BackendMetrics {
ops: Family<BackendLabels, Counter>,
latency: LatencyFamily,
in_flight: Family<BackendOpLabels, Gauge>,
}
impl BackendMetrics {
pub fn register(registry: &mut Registry) -> Self {
let ops = Family::<BackendLabels, Counter>::default();
let latency: LatencyFamily =
Family::new_with_constructor(fast_histogram as fn() -> Histogram);
let in_flight = Family::<BackendOpLabels, Gauge>::default();
let backend = registry.sub_registry_with_prefix("backend");
backend.register(
"ops",
"Storage backend operations by subsystem, method and result",
ops.clone(),
);
backend.register(
"op_seconds",
"Storage backend operation latency by subsystem, method and result",
latency.clone(),
);
backend.register(
"ops_in_flight",
"Storage backend operations currently running, by subsystem and method",
in_flight.clone(),
);
Self {
ops,
latency,
in_flight,
}
}
fn in_flight_inc(&self, store: Store, op: &'static str) {
self.in_flight
.get_or_create(&BackendOpLabels { store, op })
.inc();
}
fn in_flight_dec(&self, store: Store, op: &'static str) {
self.in_flight
.get_or_create(&BackendOpLabels { store, op })
.dec();
}
fn record_cancelled(&self, store: Store, op: &'static str) {
self.ops
.get_or_create(&BackendLabels {
store,
op,
result: OpResult::Cancelled,
})
.inc();
}
pub async fn time<T, E, F>(&self, store: Store, op: &'static str, future: F) -> Result<T, E>
where
F: Future<Output = Result<T, E>>,
{
let mut guard = InFlightGuard::enter(self.clone(), store, op);
let started = Instant::now();
let outcome = future.await;
guard.pending = false;
let labels = BackendLabels {
store,
op,
result: if outcome.is_ok() {
OpResult::Ok
} else {
OpResult::Error
},
};
let elapsed = started.elapsed().as_secs_f64();
self.ops.get_or_create(&labels).inc();
self.latency.get_or_create(&labels).observe(elapsed);
outcome
}
}
struct InFlightGuard {
metrics: BackendMetrics,
store: Store,
op: &'static str,
pending: bool,
}
impl InFlightGuard {
fn enter(metrics: BackendMetrics, store: Store, op: &'static str) -> Self {
metrics.in_flight_inc(store, op);
Self {
metrics,
store,
op,
pending: true,
}
}
}
impl Drop for InFlightGuard {
fn drop(&mut self) {
self.metrics.in_flight_dec(self.store, self.op);
if self.pending {
self.metrics.record_cancelled(self.store, self.op);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::metrics::{encode_text, new_registry};
#[tokio::test]
async fn both_results_encode_under_the_documented_names() {
let mut registry = new_registry();
let metrics = BackendMetrics::register(&mut registry);
let ok: Result<(), ()> = metrics
.time(Store::P2p, "list_workers", async { Ok(()) })
.await;
assert!(ok.is_ok());
let failed: Result<(), ()> = metrics
.time(Store::Registry, "connect", async { Err(()) })
.await;
assert!(failed.is_err());
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert!(
encoded
.contains(r#"mx_backend_ops_total{store="p2p",op="list_workers",result="ok"} 1"#),
"{encoded}"
);
assert!(
encoded.contains(
r#"mx_backend_ops_total{store="registry",op="connect",result="error"} 1"#
),
"{encoded}"
);
assert!(
encoded.contains("mx_backend_op_seconds_bucket"),
"{encoded}"
);
assert!(!encoded.contains("_total_total"), "{encoded}");
}
#[tokio::test]
async fn a_dropped_operation_is_recorded_as_cancelled() {
let mut registry = new_registry();
let metrics = BackendMetrics::register(&mut registry);
let timed_out = tokio::time::timeout(
std::time::Duration::from_millis(10),
metrics.time(
Store::P2p,
"get_metadata",
std::future::pending::<Result<(), ()>>(),
),
)
.await;
assert!(timed_out.is_err(), "the inner future should never resolve");
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert!(
encoded.contains(
r#"mx_backend_ops_total{store="p2p",op="get_metadata",result="cancelled"} 1"#
),
"{encoded}"
);
assert!(
!encoded.contains(r#"mx_backend_op_seconds_count{store="p2p",op="get_metadata"#),
"a cancellation wrote a latency sample: {encoded}"
);
assert!(
encoded.contains(r#"mx_backend_ops_in_flight{store="p2p",op="get_metadata"} 0"#),
"in-flight gauge did not return to zero: {encoded}"
);
}
#[tokio::test]
async fn the_inner_value_is_passed_through_untouched() {
let mut registry = new_registry();
let metrics = BackendMetrics::register(&mut registry);
let value: Result<u32, ()> = metrics.time(Store::Refit, "get", async { Ok(7) }).await;
assert_eq!(value, Ok(7));
}
}