use axum::{
http::{
HeaderMap, HeaderValue, StatusCode,
header::{ACCEPT, CACHE_CONTROL, CONTENT_TYPE, VARY, X_CONTENT_TYPE_OPTIONS},
},
response::{IntoResponse, Response},
};
use crate::http::{header_list_items, parse_quality};
use crate::observability::{MetricsSnapshot, encode_openmetrics, encode_prometheus};
pub const OPENMETRICS_CONTENT_TYPE: &str =
"application/openmetrics-text; version=1.0.0; charset=utf-8";
pub const PROMETHEUS_CONTENT_TYPE: &str = "text/plain; version=0.0.4; charset=utf-8";
pub struct MetricsResponse(pub MetricsSnapshot);
impl MetricsResponse {
pub fn plain_text(self) -> Response {
response(encode_prometheus(&self.0), PROMETHEUS_CONTENT_TYPE)
}
pub fn negotiate(self, headers: &HeaderMap) -> Response {
let mut response = if !headers.contains_key(ACCEPT) {
self.plain_text()
} else {
match select_content_type(headers) {
Some(PROMETHEUS_CONTENT_TYPE) => self.plain_text(),
Some(content_type) => response(encode_openmetrics(&self.0), content_type),
None => (StatusCode::NOT_ACCEPTABLE, [(CACHE_CONTROL, "no-store")]).into_response(),
}
};
response
.headers_mut()
.insert(VARY, HeaderValue::from_static("Accept"));
response
}
}
impl IntoResponse for MetricsResponse {
fn into_response(self) -> Response {
response(encode_openmetrics(&self.0), OPENMETRICS_CONTENT_TYPE)
}
}
fn response(body: String, content_type: &'static str) -> Response {
let mut response = body.into_response();
response
.headers_mut()
.insert(CONTENT_TYPE, HeaderValue::from_static(content_type));
response
.headers_mut()
.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
response
.headers_mut()
.insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
response
}
fn select_content_type(headers: &HeaderMap) -> Option<&'static str> {
let ranges: Vec<mime::Mime> = headers
.get_all(ACCEPT)
.iter()
.flat_map(|value| header_list_items(value.as_bytes()))
.filter_map(|range| std::str::from_utf8(range).ok())
.filter_map(|range| range.trim().parse().ok())
.collect();
let candidates = [
PROMETHEUS_CONTENT_TYPE,
OPENMETRICS_CONTENT_TYPE,
"application/openmetrics-text; version=1.0.0; charset=utf-8; escaping=underscores",
"application/openmetrics-text; version=1.0.0; charset=utf-8; escaping=allow-utf-8",
];
let mut selected = None;
let mut best = (0, 0, 0);
for content_type in candidates {
#[expect(
clippy::expect_used,
reason = "only built-in content-type constants are parsed"
)]
let candidate = content_type
.parse::<mime::Mime>()
.expect("built-in metrics content types are valid MIME values");
let preference = ranges
.iter()
.filter_map(|range| preference(range, &candidate))
.max_by_key(|&(specificity, parameters, quality)| (specificity, parameters, quality));
if let Some((specificity, parameters, quality)) = preference {
let score = (quality, specificity, parameters);
if quality > 0 && score > best {
selected = Some(content_type);
best = score;
}
}
}
selected
}
fn preference(range: &mime::Mime, candidate: &mime::Mime) -> Option<(u8, usize, u16)> {
let specificity = match range.essence_str() {
"*/*" => 0,
_ if range.type_() == candidate.type_()
&& range.subtype() == mime::STAR
&& range.suffix().is_none() =>
{
1
}
_ if range.essence_str() == candidate.essence_str() => 2,
_ => return None,
};
let mut quality = 1000;
let mut parameters = 0;
let mut seen = Vec::new();
let mut after_quality = false;
for (name, value) in range.params() {
if seen.contains(&name) {
return None;
}
seen.push(name);
if name == "q" {
quality = parse_quality(value.as_str()).unwrap_or(0);
after_quality = true;
} else if !after_quality {
if candidate.get_param(name) != Some(value) {
return None;
}
parameters += 1;
}
}
Some((specificity, parameters, quality))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::observability::MetricSample;
use axum::{
Router,
body::{Body, to_bytes},
http::{Method, Request},
routing::get,
};
use tower::ServiceExt;
fn snapshot() -> MetricsSnapshot {
MetricsSnapshot::new(vec![MetricSample::counter("jobs_total", 2).unwrap()]).unwrap()
}
#[tokio::test]
async fn negotiate_handles_browser_and_scraper_preferences() {
let app = Router::new().route(
"/metrics",
get(
|headers: HeaderMap| async move { MetricsResponse(snapshot()).negotiate(&headers) },
),
);
for (accept, expected) in [
(vec![], Some(PROMETHEUS_CONTENT_TYPE)),
(vec!["*/*"], Some(PROMETHEUS_CONTENT_TYPE)),
(
vec!["text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,*/*;q=0.8"],
Some(PROMETHEUS_CONTENT_TYPE),
),
(
vec!["application/openmetrics-text"],
Some(OPENMETRICS_CONTENT_TYPE),
),
(
vec![
"application/openmetrics-text;version=1.0.0;q=0.9,text/plain;version=0.0.4;q=0.8",
],
Some(OPENMETRICS_CONTENT_TYPE),
),
(
vec![
"application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;q=1,application/openmetrics-text;version=1.0.0;q=0.8,text/plain;q=0.5",
],
Some(OPENMETRICS_CONTENT_TYPE),
),
(
vec!["application/openmetrics-text;q=0.3", "text/plain;q=0.9"],
Some(PROMETHEUS_CONTENT_TYPE),
),
(
vec!["text/*;q=0.9,application/*;q=0.2"],
Some(PROMETHEUS_CONTENT_TYPE),
),
(
vec!["text/plain;q=0.1,*/*;q=0.8"],
Some(OPENMETRICS_CONTENT_TYPE),
),
(
vec!["application/openmetrics-text;q=0,*/*;q=1"],
Some(PROMETHEUS_CONTENT_TYPE),
),
(
vec!["text/plain;q=0,*/*;q=1"],
Some(OPENMETRICS_CONTENT_TYPE),
),
(
vec!["TEXT/PLAIN;version=\"0.0.4\";charset=\"UTF-8\""],
Some(PROMETHEUS_CONTENT_TYPE),
),
(
vec![
"text/plain;version=0.0.4;q=0.1,text/plain;q=0.9,application/openmetrics-text;q=0.5",
],
Some(OPENMETRICS_CONTENT_TYPE),
),
(
vec![
"text/plain;version=1.0.0,application/openmetrics-text;version=0.0.1,*/*;q=0.1",
],
Some(PROMETHEUS_CONTENT_TYPE),
),
(
vec!["text/plain;q=0.8;note=\"a,b\",application/openmetrics-text;q=0.5"],
Some(PROMETHEUS_CONTENT_TYPE),
),
(
vec!["text/plain;q=1.001,application/openmetrics-text;q=0.5"],
Some(OPENMETRICS_CONTENT_TYPE),
),
(
vec!["text/plain;q=NaN,application/openmetrics-text;q=0.5"],
Some(OPENMETRICS_CONTENT_TYPE),
),
(
vec!["text/plain;q=0.1234,application/openmetrics-text;q=0.5"],
Some(OPENMETRICS_CONTENT_TYPE),
),
(vec!["application/json"], None),
(vec!["application/*+json"], None),
(vec!["*/*;q=0"], None),
(
vec!["application/openmetrics-text;q=0,text/plain;q=0,*/*;q=1"],
None,
),
(vec!["application/openmetrics-text;version=0.0.1"], None),
(vec!["text/plain;version=1.0.0"], None),
(vec!["text/plain;charset=iso-8859-1"], None),
(vec!["application/openmetrics-text;escaping=dots"], None),
(vec!["application/openmetrics-text;escaping=values"], None),
(vec!["text/plain;version=0.0.4;version=1.0.0"], None),
(vec!["text/plain;q=0;q=1"], None),
(
vec!["text/plain;note=\"a,application/openmetrics-text\""],
None,
),
(vec![""], None),
] {
for method in [Method::GET, Method::HEAD] {
let mut request = Request::builder().method(method.clone()).uri("/metrics");
for header in &accept {
request = request.header(ACCEPT, *header);
}
let response = app
.clone()
.oneshot(request.body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.headers()[VARY], "Accept");
assert_eq!(response.headers()[CACHE_CONTROL], "no-store");
assert_eq!(
response.status(),
if expected.is_some() {
StatusCode::OK
} else {
StatusCode::NOT_ACCEPTABLE
},
"{accept:?}"
);
if let Some(expected) = expected {
assert_eq!(response.headers()[CONTENT_TYPE], expected, "{accept:?}");
assert_eq!(response.headers()[X_CONTENT_TYPE_OPTIONS], "nosniff");
let bytes = to_bytes(response.into_body(), 1024).await.unwrap();
if method == Method::HEAD {
assert!(bytes.is_empty());
} else if expected == PROMETHEUS_CONTENT_TYPE {
assert_eq!(bytes, "# TYPE jobs_total counter\njobs_total 2\n");
} else {
assert_eq!(bytes, "# TYPE jobs counter\njobs_total 2\n# EOF\n");
}
} else {
assert!(
to_bytes(response.into_body(), 1024)
.await
.unwrap()
.is_empty()
);
}
}
}
}
#[tokio::test]
async fn explicit_formats_disable_caching_for_get_and_head() {
let app = Router::new()
.route(
"/openmetrics",
get(|| async { MetricsResponse(snapshot()) }),
)
.route(
"/prometheus",
get(|| async { MetricsResponse(snapshot()).plain_text() }),
);
for (uri, content_type) in [
("/openmetrics", OPENMETRICS_CONTENT_TYPE),
("/prometheus", PROMETHEUS_CONTENT_TYPE),
] {
for method in [Method::GET, Method::HEAD] {
let response = app
.clone()
.oneshot(
Request::builder()
.method(method.clone())
.uri(uri)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()[CACHE_CONTROL], "no-store");
assert_eq!(response.headers()[CONTENT_TYPE], content_type);
assert!(!response.headers().contains_key(VARY));
let body = to_bytes(response.into_body(), 1024).await.unwrap();
assert_eq!(body.is_empty(), method == Method::HEAD);
}
}
}
#[tokio::test]
async fn negotiated_escaping_matches_the_advertised_encoding() {
for escaping in ["underscores", "allow-utf-8"] {
let mut headers = HeaderMap::new();
headers.insert(
ACCEPT,
format!("application/openmetrics-text;version=1.0.0;escaping={escaping}")
.parse()
.unwrap(),
);
let response = MetricsResponse(snapshot()).negotiate(&headers);
assert_eq!(response.status(), StatusCode::OK);
assert!(
response.headers()[CONTENT_TYPE]
.to_str()
.unwrap()
.ends_with(&format!("escaping={escaping}"))
);
assert_eq!(
to_bytes(response.into_body(), 1024).await.unwrap(),
"# TYPE jobs counter\njobs_total 2\n# EOF\n"
);
}
}
#[tokio::test]
async fn explicit_preview_is_text_without_html_interpolation() {
let sample = MetricSample::gauge("resource_info", 1.0)
.unwrap()
.with_label("name", "<script>alert(1)</script>\\\"")
.unwrap();
let response = MetricsResponse(MetricsSnapshot::new(vec![sample]).unwrap()).plain_text();
assert_eq!(response.headers()[CONTENT_TYPE], PROMETHEUS_CONTENT_TYPE);
assert_eq!(response.headers()[X_CONTENT_TYPE_OPTIONS], "nosniff");
assert!(!response.headers().contains_key(VARY));
assert_eq!(
to_bytes(response.into_body(), 1024).await.unwrap(),
"# TYPE resource_info gauge\nresource_info{name=\"<script>alert(1)</script>\\\\\\\"\"} 1\n"
);
}
}