use std::future::Future;
use std::net::SocketAddr;
use std::sync::Arc;
use axum::Router;
use axum::extract::State;
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use tracing::{error, info};
use prometheus_client::registry::Registry;
use super::OPENMETRICS_CONTENT_TYPE;
pub async fn serve(
addr: SocketAddr,
registry: Arc<Registry>,
shutdown: impl Future<Output = ()> + Send + 'static,
) {
let app = Router::new()
.route("/metrics", get(handler))
.with_state(registry);
let listener = match tokio::net::TcpListener::bind(addr).await {
Ok(listener) => listener,
Err(e) => {
error!(
"Metrics listener failed to bind {addr}: {e}. \
Continuing without a metrics endpoint."
);
return;
}
};
info!("Metrics endpoint listening on http://{addr}/metrics");
if let Err(e) = axum::serve(listener, app)
.with_graceful_shutdown(shutdown)
.await
{
error!("Metrics listener error: {e}");
}
info!("Metrics endpoint stopped");
}
async fn handler(State(registry): State<Arc<Registry>>) -> Response {
match super::encode_text(®istry) {
Ok(body) => (
StatusCode::OK,
[(header::CONTENT_TYPE, OPENMETRICS_CONTENT_TYPE)],
body,
)
.into_response(),
Err(e) => {
error!("Failed to encode metrics: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
"failed to encode metrics\n",
)
.into_response()
}
}
}