use crate::kind::DbKind;
use crate::DatabaseIdentifier;
use opentelemetry::{global::meter, metrics, KeyValue};
#[derive(Clone)]
pub(crate) struct Histogram {
histogram: metrics::Histogram<f64>,
attributes: Vec<KeyValue>,
}
impl std::fmt::Debug for Histogram {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Histogram")
.field("attributes", &self.attributes)
.finish_non_exhaustive()
}
}
impl Histogram {
pub(crate) fn record(&self, value: f64) {
self.histogram.record(value, &self.attributes);
}
}
pub(crate) type WriteTxnDurationMetric = Histogram;
pub(crate) fn create_write_txn_duration_metric<I: DatabaseIdentifier>(
identifier: &I,
) -> WriteTxnDurationMetric {
let histogram = meter("hc.db")
.f64_histogram("hc.db.write_txn.duration")
.with_unit("s")
.with_description("The time spent executing a write transaction")
.build();
let attributes = vec![
KeyValue::new("kind", db_kind_name(identifier.db_kind())),
KeyValue::new("id", identifier.database_id().to_string()),
];
Histogram {
histogram,
attributes,
}
}
pub(crate) type ConnectionUseTimeMetric = Histogram;
pub(crate) fn create_connection_use_time_metric<I: DatabaseIdentifier>(
identifier: &I,
) -> ConnectionUseTimeMetric {
let histogram = meter("hc.db")
.f64_histogram("hc.db.connections.use_time")
.with_unit("s")
.with_description("The time between borrowing a connection and returning it to the pool")
.build();
let attributes = vec![
KeyValue::new("kind", db_kind_name(identifier.db_kind())),
KeyValue::new("id", identifier.database_id().to_string()),
];
Histogram {
histogram,
attributes,
}
}
fn db_kind_name(kind: DbKind) -> &'static str {
match kind {
DbKind::Wasm => "wasm",
DbKind::Conductor => "conductor",
DbKind::PeerMetaStore => "peer_meta_store",
DbKind::Dht => "dht",
}
}