pub mod backend;
pub mod buckets;
pub mod cache;
pub mod exposition;
pub mod grpc;
pub mod registry;
use prometheus_client::encoding::EncodeLabelSet;
use prometheus_client::encoding::text::encode;
use prometheus_client::metrics::family::Family;
use prometheus_client::metrics::gauge::Gauge;
use prometheus_client::registry::Registry;
use crate::backend_config::BackendConfig;
pub use exposition::serve;
pub const OPENMETRICS_CONTENT_TYPE: &str =
"application/openmetrics-text; version=1.0.0; charset=utf-8";
const NAMESPACE: &str = "mx";
#[must_use]
pub fn new_registry() -> Registry {
Registry::with_prefix(NAMESPACE)
}
pub fn encode_text(registry: &Registry) -> Result<String, std::fmt::Error> {
let mut buffer = String::new();
encode(&mut buffer, registry)?;
Ok(buffer)
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct BuildInfoLabels {
pub component: &'static str,
pub version: &'static str,
pub backend: String,
pub scheme: String,
}
pub fn register_build_info(registry: &mut Registry, backend: &BackendConfig) {
let family = Family::<BuildInfoLabels, Gauge>::default();
registry.register(
"build_info",
"Build and deployment constants for this process; always 1",
family.clone(),
);
family
.get_or_create(&BuildInfoLabels {
component: "server",
version: env!("CARGO_PKG_VERSION"),
backend: backend.to_string(),
scheme: modelexpress_common::envs::metrics_scheme(),
})
.set(1);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn build_info_is_one_series_in_the_mx_namespace() {
let mut registry = new_registry();
register_build_info(
&mut registry,
&BackendConfig::Redis {
url: "redis://localhost:6379".to_string(),
},
);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert!(
encoded.contains("# TYPE mx_build_info gauge"),
"expected an mx-prefixed gauge, got: {encoded}"
);
let series: Vec<_> = encoded
.lines()
.filter(|line| line.starts_with("mx_build_info{"))
.collect();
assert_eq!(series.len(), 1, "expected one series, got: {encoded}");
assert!(
series[0].ends_with(" 1"),
"expected value 1, got: {series:?}"
);
assert!(series[0].contains(r#"component="server""#), "{series:?}");
assert!(series[0].contains(r#"backend="redis""#), "{series:?}");
assert!(encoded.trim_end().ends_with("# EOF"), "not OpenMetrics");
}
}