use std::sync::LazyLock;
use std::time::Instant;
use opentelemetry::KeyValue;
use opentelemetry::metrics::{Counter, Histogram, Meter};
pub(crate) struct Metrics {
pub errors: Counter<u64>,
pub wait_time: Histogram<f64>,
pub create_time: Histogram<f64>,
pub queue_wait: Histogram<f64>,
}
pub(crate) static METRICS: LazyLock<Metrics> = LazyLock::new(|| {
let meter: Meter = opentelemetry::global::meter("halephant");
Metrics {
errors: meter
.u64_counter("db.client.connection.errors")
.with_description("Number of connection errors")
.build(),
wait_time: meter
.f64_histogram("db.client.connection.wait_time")
.with_description("Time spent waiting for a pool connection")
.with_unit("s")
.build(),
create_time: meter
.f64_histogram("db.client.connection.create_time")
.with_description("Time to establish a new upstream connection")
.with_unit("s")
.build(),
queue_wait: meter
.f64_histogram("halephant.client.wait_duration")
.with_description(
"Time a client spent blocked on the role wait queue \
waiting for pool capacity to become available",
)
.with_unit("s")
.build(),
}
});
pub(crate) fn record_checkout(start: Instant, database: &str, user: &str, node: &str) {
METRICS.wait_time.record(
start.elapsed().as_secs_f64(),
&[
KeyValue::new("db.namespace", database.to_owned()),
KeyValue::new("user", user.to_owned()),
KeyValue::new("server.address", node.to_owned()),
],
);
}
pub(crate) fn record_wait_duration(
elapsed: std::time::Duration,
database: &str,
user: &str,
routing: crate::pool::Routing,
) {
METRICS.queue_wait.record(
elapsed.as_secs_f64(),
&[
KeyValue::new("db.namespace", database.to_owned()),
KeyValue::new("user", user.to_owned()),
KeyValue::new(
"role",
match routing {
crate::pool::Routing::Primary => "primary",
crate::pool::Routing::Replica => "replica",
},
),
],
);
}
pub(crate) fn record_checkout_error(database: &str, user: &str, error_type: &'static str) {
METRICS.errors.add(
1,
&[
KeyValue::new("db.namespace", database.to_owned()),
KeyValue::new("user", user.to_owned()),
KeyValue::new("error.type", error_type),
],
);
}
pub(crate) fn record_connect(start: Instant, addr: &str, database: &str) {
METRICS.create_time.record(
start.elapsed().as_secs_f64(),
&[
KeyValue::new("server.address", addr.to_owned()),
KeyValue::new("db.namespace", database.to_owned()),
],
);
}
pub(crate) fn record_error(error_type: &str, addr: &str) {
METRICS.errors.add(
1,
&[
KeyValue::new("error.type", error_type.to_owned()),
KeyValue::new("server.address", addr.to_owned()),
],
);
}
pub struct PoolKeyInfo {
pub node: String,
pub database: String,
pub user: String,
}
pub struct PoolStats {
pub active: u32,
pub idle: u32,
pub resetting: u32,
}
pub struct PoolLimits {
pub database: String,
pub max_primary: u32,
pub max_replica: u32,
}
pub struct QueueInfo {
pub database: String,
pub user: String,
pub role: crate::pool::Routing,
pub depth: u32,
pub oldest_wait_secs: f64,
}