use std::time::Instant;
use axum::Router;
use axum::extract::{MatchedPath, Path, Request, State};
use axum::http::{Method, Version, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use tracing::Instrument;
use crate::listener::Routes;
use crate::telemetry::pages::{self, Page};
use crate::telemetry::request;
const TEXT: &str = "text/plain; charset=utf-8";
const METRICS: &str = "text/plain; version=0.0.4; charset=utf-8";
const HTML: &str = "text/html; charset=utf-8";
const METHODS: [Method; 9] = [
Method::GET,
Method::HEAD,
Method::POST,
Method::PUT,
Method::DELETE,
Method::CONNECT,
Method::OPTIONS,
Method::TRACE,
Method::PATCH,
];
const OTHER_METHOD: &str = "_OTHER";
const UNMATCHED: &str = "unmatched";
pub(crate) fn router(routes: Routes) -> Router {
crate::probes::router()
.route("/metrics", get(metrics))
.route("/info", get(index))
.route("/info/{name}", get(module))
.route("/config", get(configs))
.route("/config/{name}", get(config))
.layer(axum::middleware::from_fn_with_state(
routes.clone(),
instrument,
))
.with_state(routes)
}
async fn metrics(State(routes): State<Routes>) -> Response {
let text = routes.telemetry.render(&routes.info.dependency_metrics());
([(header::CONTENT_TYPE, METRICS)], text).into_response()
}
async fn index(State(routes): State<Routes>) -> Response {
page(Page::Index, &routes)
}
async fn module(State(routes): State<Routes>, Path(name): Path<String>) -> Response {
page(Page::Module(&name), &routes)
}
async fn configs(State(routes): State<Routes>) -> Response {
page(Page::Configs, &routes)
}
async fn config(State(routes): State<Routes>, Path(name): Path<String>) -> Response {
page(Page::Config(&name), &routes)
}
fn page(page: Page<'_>, routes: &Routes) -> Response {
let html = pages::render(page, &routes.info.info());
let (status, content, body) = match html {
Some(html) => (axum::http::StatusCode::OK, HTML, html),
None => (
axum::http::StatusCode::NOT_FOUND,
TEXT,
"Not found".to_owned(),
),
};
(status, [(header::CONTENT_TYPE, content)], body).into_response()
}
async fn instrument(State(routes): State<Routes>, request: Request, next: Next) -> Response {
let started = Instant::now();
let method = request.method().clone();
let version = request.version();
let route = request
.extensions()
.get::<MatchedPath>()
.map_or_else(|| UNMATCHED.to_owned(), |path| path.as_str().to_owned());
let opened = request::open(request.headers(), &route, method.as_str());
let span = opened.span;
let outcome = next.run(request).instrument(span.clone()).await;
let status = outcome.status().as_u16();
span.record("http.status_code", i64::from(status));
let elapsed = started.elapsed();
routes.telemetry.rest_call(elapsed);
routes.telemetry.http_request(
method_label(&method),
status,
&route,
protocol(version),
elapsed,
);
let elapsed_ms = u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX);
span.in_scope(|| {
tracing::debug!(status, elapsed_ms, "request handled");
});
outcome
}
fn method_label(method: &Method) -> &str {
if METHODS.contains(method) {
method.as_str()
} else {
OTHER_METHOD
}
}
fn protocol(version: Version) -> &'static str {
match version {
Version::HTTP_10 => "1.0",
Version::HTTP_11 => "1.1",
Version::HTTP_2 => "2",
Version::HTTP_3 => "3",
_ => "",
}
}