#[cfg(feature = "metrics-prometheus")]
#[derive(Clone)]
pub struct CreditMetrics {
consumed_total: prometheus::CounterVec,
remaining: prometheus::GaugeVec,
alerts_total: prometheus::CounterVec,
}
#[cfg(feature = "metrics-prometheus")]
impl CreditMetrics {
pub fn new() -> Self {
use std::sync::OnceLock;
static INSTANCE: OnceLock<CreditMetrics> = OnceLock::new();
INSTANCE.get_or_init(Self::init_default).clone()
}
fn init_default() -> Self {
match Self::register_to(prometheus::default_registry()) {
Ok(m) => m,
Err(e) => {
tracing::warn!(
error = %e,
"{}",
crate::i18n::translate_detail(
"logs-metrics-already-registered",
&[("arg0", "CreditMetrics")]
)
);
Self::build().expect("CreditMetrics: static metric opts are valid (unreachable)")
},
}
}
pub fn register_to(registry: &prometheus::Registry) -> Result<Self, prometheus::Error> {
let metrics = Self::build()?;
registry.register(Box::new(metrics.consumed_total.clone()))?;
registry.register(Box::new(metrics.remaining.clone()))?;
registry.register(Box::new(metrics.alerts_total.clone()))?;
Ok(metrics)
}
fn build() -> Result<Self, prometheus::Error> {
let consumed_total = prometheus::CounterVec::new(
prometheus::Opts::new(
"garrison_credit_consumed_total",
"Total credit consumed (tenant-level metering)",
),
&["tenant_id", "resource"],
)?;
let remaining = prometheus::GaugeVec::new(
prometheus::Opts::new(
"garrison_credit_remaining",
"Current remaining credit for tenant",
),
&["tenant_id"],
)?;
let alerts_total = prometheus::CounterVec::new(
prometheus::Opts::new(
"garrison_credit_alerts_total",
"Total credit alert threshold triggers",
),
&["tenant_id", "threshold"],
)?;
Ok(Self {
consumed_total,
remaining,
alerts_total,
})
}
pub fn record_consumed(&self, tenant_id: &str, resource: &str, credits: u64) {
self.consumed_total
.with_label_values(&[tenant_id, resource])
.inc_by(credits as f64);
}
pub fn set_remaining(&self, tenant_id: &str, remaining_credits: u64) {
self.remaining
.with_label_values(&[tenant_id])
.set(remaining_credits as f64);
}
pub fn record_alert(&self, tenant_id: &str, threshold: u8) {
self.alerts_total
.with_label_values(&[tenant_id, &threshold.to_string()])
.inc();
}
pub fn gather(&self) -> String {
use prometheus::core::Collector;
use prometheus::Encoder;
let mut metric_families = Vec::new();
metric_families.extend(self.consumed_total.collect());
metric_families.extend(self.remaining.collect());
metric_families.extend(self.alerts_total.collect());
let mut buffer = Vec::new();
let encoder = prometheus::TextEncoder::new();
if let Err(e) = encoder.encode(&metric_families, &mut buffer) {
tracing::warn!(error = %e, "CreditMetrics::gather prometheus encode failed");
}
String::from_utf8_lossy(&buffer).into_owned()
}
}
#[cfg(feature = "metrics-prometheus")]
impl Default for CreditMetrics {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "metrics-prometheus")]
impl std::fmt::Debug for CreditMetrics {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CreditMetrics")
.field("consumed_total", &"CounterVec")
.field("remaining", &"GaugeVec")
.field("alerts_total", &"CounterVec")
.finish()
}
}
#[cfg(not(feature = "metrics-prometheus"))]
pub type CreditMetrics = ();
#[cfg(all(test, feature = "metrics-prometheus"))]
mod tests {
use super::*;
use serial_test::serial;
#[test]
#[serial]
fn credit_metrics_register_to_custom_registry() {
let registry = prometheus::Registry::new();
let metrics = CreditMetrics::register_to(®istry).expect("注册到自定义 registry 失败");
metrics.record_consumed("42", "login", 5);
metrics.set_remaining("42", 9995);
metrics.record_alert("42", 80);
let gathered = prometheus::TextEncoder::new()
.encode_to_string(®istry.gather())
.expect("encode 失败");
assert!(
gathered.contains("garrison_credit_consumed_total"),
"missing credit_consumed_total: {}",
gathered
);
assert!(
gathered.contains("garrison_credit_remaining"),
"missing credit_remaining: {}",
gathered
);
assert!(
gathered.contains("garrison_credit_alerts_total"),
"missing credit_alerts_total: {}",
gathered
);
}
#[test]
#[serial]
fn credit_consumed_total_labels() {
let registry = prometheus::Registry::new();
let metrics = CreditMetrics::register_to(®istry).unwrap();
metrics.record_consumed("42", "login", 1);
metrics.record_consumed("42", "api_call", 5);
metrics.record_consumed("99", "login", 1);
let output = prometheus::TextEncoder::new()
.encode_to_string(®istry.gather())
.unwrap();
assert!(
output.contains("tenant_id=\"42\"") && output.contains("resource=\"login\""),
"missing tenant 42 login: {}",
output
);
assert!(
output.contains("resource=\"api_call\""),
"missing api_call: {}",
output
);
}
#[test]
#[serial]
fn credit_remaining_gauge() {
let registry = prometheus::Registry::new();
let metrics = CreditMetrics::register_to(®istry).unwrap();
metrics.set_remaining("42", 5000);
let output = prometheus::TextEncoder::new()
.encode_to_string(®istry.gather())
.unwrap();
assert!(
output.contains("garrison_credit_remaining{tenant_id=\"42\"} 5000"),
"remaining should be 5000: {}",
output
);
}
#[test]
#[serial]
fn credit_alerts_total_labels() {
let registry = prometheus::Registry::new();
let metrics = CreditMetrics::register_to(®istry).unwrap();
metrics.record_alert("42", 80);
metrics.record_alert("42", 80);
metrics.record_alert("42", 90);
let output = prometheus::TextEncoder::new()
.encode_to_string(®istry.gather())
.unwrap();
assert!(
output.contains("threshold=\"80\""),
"missing threshold 80: {}",
output
);
assert!(
output.contains("threshold=\"90\""),
"missing threshold 90: {}",
output
);
assert!(
output.contains("garrison_credit_alerts_total{tenant_id=\"42\",threshold=\"80\"} 2"),
"threshold 80 count should be 2: {}",
output
);
}
#[test]
#[serial]
fn duplicate_register_returns_error() {
let registry = prometheus::Registry::new();
let _m1 = CreditMetrics::register_to(®istry).expect("首次注册失败");
let result = CreditMetrics::register_to(®istry);
assert!(result.is_err(), "重复注册应返回错误");
match result {
Err(prometheus::Error::AlreadyReg) => {},
Err(e) => panic!("期望 AlreadyReg 错误,实际: {:?}", e),
Ok(_) => panic!("期望错误,实际成功"),
}
}
#[test]
#[serial]
fn clone_shares_state() {
let registry = prometheus::Registry::new();
let m1 = CreditMetrics::register_to(®istry).unwrap();
let m2 = m1.clone();
m1.record_consumed("1", "login", 3);
m2.record_consumed("1", "login", 7);
let output = prometheus::TextEncoder::new()
.encode_to_string(®istry.gather())
.unwrap();
assert!(
output
.contains("garrison_credit_consumed_total{resource=\"login\",tenant_id=\"1\"} 10"),
"clones should share underlying Counter: {}",
output
);
}
#[test]
#[serial]
fn gather_non_empty() {
let registry = prometheus::Registry::new();
let metrics = CreditMetrics::register_to(®istry).unwrap();
metrics.record_consumed("1", "login", 1);
let output = metrics.gather();
assert!(!output.is_empty(), "gather() 应返回非空字符串");
}
#[test]
#[serial]
fn new_and_default_register_to_default_registry_once() {
let m1 = CreditMetrics::new();
let m2 = CreditMetrics::default();
m1.record_consumed("808", "api_call", 2);
m2.set_remaining("808", 7);
let gathered = m1.gather();
assert!(
gathered.contains("garrison_credit_consumed_total"),
"gather 应含 consumed_total: {}",
gathered
);
assert!(
gathered.contains("tenant_id=\"808\""),
"gather 应含 tenant 808: {}",
gathered
);
let debug = format!("{:?}", m1);
assert!(debug.contains("CreditMetrics"), "实际: {}", debug);
assert!(debug.contains("CounterVec"), "实际: {}", debug);
assert!(debug.contains("GaugeVec"), "实际: {}", debug);
}
#[test]
#[serial]
fn new_does_not_panic_when_already_registered_to_default_registry() {
let _ = CreditMetrics::register_to(prometheus::default_registry());
let m = CreditMetrics::new();
m.record_consumed("909", "login", 3);
assert!(
m.gather().contains("tenant_id=\"909\""),
"回退实例应可正常记录与收集"
);
}
#[test]
#[serial]
fn gather_contains_help_and_type_lines() {
let registry = prometheus::Registry::new();
let metrics = CreditMetrics::register_to(®istry).unwrap();
metrics.record_alert("1", 90);
metrics.record_consumed("1", "login", 1);
metrics.set_remaining("1", 2);
let output = metrics.gather();
assert!(
output.contains("# HELP garrison_credit_alerts_total"),
"{}",
output
);
assert!(
output.contains("# TYPE garrison_credit_alerts_total counter"),
"{}",
output
);
}
}
#[cfg(all(test, not(feature = "metrics-prometheus")))]
mod tests_no_feature {
use super::*;
#[test]
fn no_feature_credit_metrics_is_unit() {
let _: CreditMetrics = ();
}
}