use prometheus::{
register_histogram_vec, register_int_counter, register_int_counter_vec, register_int_gauge,
HistogramVec, IntCounter, IntCounterVec, IntGauge,
};
use std::sync::OnceLock;
#[derive(Clone)]
pub struct Metrics {
pub messages_in: IntCounter,
pub bytes_in: IntCounter,
pub messages_out: IntCounter,
pub bytes_out: IntCounter,
pub requests_total: IntCounterVec,
pub request_latency: HistogramVec,
pub isr_changes: IntCounter,
pub leader_elections: IntCounter,
pub log_size_bytes: IntGauge,
pub active_connections: IntGauge,
pub request_errors: IntCounterVec,
}
impl Metrics {
pub fn global() -> &'static Metrics {
static GLOBAL: OnceLock<Metrics> = OnceLock::new();
GLOBAL.get_or_init(Self::create)
}
fn create() -> Self {
Self {
messages_in: register_int_counter!("rivine_messages_in_total", "接收消息总数").unwrap(),
bytes_in: register_int_counter!("rivine_bytes_in_total", "接收字节数").unwrap(),
messages_out: register_int_counter!("rivine_messages_out_total", "发送消息总数").unwrap(),
bytes_out: register_int_counter!("rivine_bytes_out_total", "发送字节数").unwrap(),
requests_total: register_int_counter_vec!("rivine_requests_total", "请求总数", &["api"])
.unwrap(),
request_latency: register_histogram_vec!(
"rivine_request_latency_seconds",
"请求延迟",
&["api"]
)
.unwrap(),
isr_changes: register_int_counter!("rivine_isr_changes_total", "ISR 变化次数").unwrap(),
leader_elections: register_int_counter!("rivine_leader_elections_total", "Leader 选举次数")
.unwrap(),
log_size_bytes: register_int_gauge!("rivine_log_size_bytes", "日志总大小").unwrap(),
active_connections: register_int_gauge!("rivine_active_connections", "活跃连接数").unwrap(),
request_errors: register_int_counter_vec!(
"rivine_request_errors_total",
"请求错误数",
&["api"]
)
.unwrap(),
}
}
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct HealthStatus {
pub status: &'static str,
pub version: &'static str,
}
impl Default for HealthStatus {
fn default() -> Self {
Self {
status: "ok",
version: env!("CARGO_PKG_VERSION"),
}
}
}