2022-09-20 09:58:40 +03:00
|
|
|
use axum::headers::HeaderName;
|
|
|
|
use axum::http::HeaderValue;
|
|
|
|
use axum::response::{IntoResponse, Response};
|
|
|
|
use axum::{routing::get, Extension, Router};
|
2022-11-12 11:24:32 +03:00
|
|
|
use log::info;
|
2022-09-20 09:58:40 +03:00
|
|
|
use std::net::SocketAddr;
|
|
|
|
use std::sync::Arc;
|
2023-01-26 08:24:09 +03:00
|
|
|
use tokio::sync::broadcast;
|
2022-09-20 09:58:40 +03:00
|
|
|
|
|
|
|
use crate::app::Web3ProxyApp;
|
|
|
|
|
|
|
|
/// Run a prometheus metrics server on the given port.
|
2023-01-26 08:24:09 +03:00
|
|
|
pub async fn serve(
|
|
|
|
app: Arc<Web3ProxyApp>,
|
|
|
|
port: u16,
|
|
|
|
mut shutdown_receiver: broadcast::Receiver<()>,
|
|
|
|
) -> anyhow::Result<()> {
|
|
|
|
// routes should be ordered most to least common
|
2022-09-20 09:58:40 +03:00
|
|
|
let app = Router::new().route("/", get(root)).layer(Extension(app));
|
|
|
|
|
2023-01-26 08:24:09 +03:00
|
|
|
// TODO: config for the host?
|
2022-09-20 09:58:40 +03:00
|
|
|
let addr = SocketAddr::from(([0, 0, 0, 0], port));
|
|
|
|
info!("prometheus listening on port {}", port);
|
|
|
|
|
2023-01-26 08:24:09 +03:00
|
|
|
let service = app.into_make_service();
|
2022-09-20 09:58:40 +03:00
|
|
|
|
|
|
|
// `axum::Server` is a re-export of `hyper::Server`
|
|
|
|
axum::Server::bind(&addr)
|
|
|
|
.serve(service)
|
2023-01-26 08:24:09 +03:00
|
|
|
.with_graceful_shutdown(async move {
|
|
|
|
let _ = shutdown_receiver.recv().await;
|
|
|
|
})
|
2022-09-20 09:58:40 +03:00
|
|
|
.await
|
|
|
|
.map_err(Into::into)
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn root(Extension(app): Extension<Arc<Web3ProxyApp>>) -> Response {
|
2022-12-28 09:11:18 +03:00
|
|
|
let serialized = app.prometheus_metrics().await;
|
2022-09-20 09:58:40 +03:00
|
|
|
|
|
|
|
let mut r = serialized.into_response();
|
|
|
|
|
|
|
|
// // TODO: is there an easier way to do this?
|
|
|
|
r.headers_mut().insert(
|
|
|
|
HeaderName::from_static("content-type"),
|
|
|
|
HeaderValue::from_static("application/openmetrics-text; version=1.0.0; charset=utf-8"),
|
|
|
|
);
|
|
|
|
|
|
|
|
r
|
|
|
|
}
|