docspec_http/metrics/
mod.rs1pub mod middleware;
14
15use axum::http::header::CONTENT_TYPE;
16use metrics::{describe_counter, describe_histogram};
17use metrics_exporter_prometheus::{
18 BuildError, Matcher, PrometheusBuilder, PrometheusHandle, PrometheusRecorder,
19};
20
21pub const METRIC_HTTP_REQUESTS_TOTAL: &str = "docspec_http_requests_total";
25
26pub const METRIC_HTTP_REQUEST_DURATION_SECONDS: &str = "docspec_http_request_duration_seconds";
28
29pub const METRIC_HTTP_REQUEST_BODY_BYTES: &str = "docspec_http_request_body_bytes";
31
32pub const METRIC_CONVERSIONS_TOTAL: &str = "docspec_conversions_total";
34
35pub const METRIC_CONVERSION_DURATION_SECONDS: &str = "docspec_conversion_duration_seconds";
37
38pub const METRIC_CONVERSION_OUTPUT_BYTES: &str = "docspec_conversion_output_bytes";
40
41pub const LABEL_METHOD: &str = "method";
45
46pub const LABEL_PATH: &str = "path";
48
49pub const LABEL_STATUS: &str = "status";
51
52pub const LABEL_RESULT: &str = "result";
54
55pub const LABEL_ERROR_CLASS: &str = "error_class";
57
58pub const LABEL_INPUT_MIME_TYPE: &str = "input_mime_type";
60
61pub const LABEL_OUTPUT_MIME_TYPE: &str = "output_mime_type";
63
64pub const PATH_UNKNOWN: &str = "unknown";
68
69pub const RESULT_SUCCESS: &str = "success";
71
72pub const RESULT_CLIENT_ERROR: &str = "client_error";
74
75pub const RESULT_SERVER_ERROR: &str = "server_error";
77
78pub const ERROR_CLASS_NONE: &str = "none";
80
81pub const INPUT_MIME_NONE: &str = "none";
86
87pub const INPUT_MIME_UNSUPPORTED: &str = "unsupported";
93
94pub const OUTPUT_MIME_NONE: &str = "none";
99
100pub const HTTP_LATENCY_BUCKETS: [f64; 11] = [
104 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
105];
106
107pub const HTTP_BODY_SIZE_BUCKETS: [f64; 12] = [
109 100.0, 200.0, 400.0, 800.0, 1_600.0, 3_200.0, 6_400.0, 12_800.0, 25_600.0, 51_200.0, 102_400.0,
110 204_800.0,
111];
112
113pub const CONVERSION_DURATION_BUCKETS: [f64; 11] = HTTP_LATENCY_BUCKETS;
117
118pub const CONVERSION_OUTPUT_BYTES_BUCKETS: [f64; 12] = HTTP_BODY_SIZE_BUCKETS;
123
124fn configure_buckets(builder: PrometheusBuilder) -> Result<PrometheusBuilder, BuildError> {
127 builder
128 .set_buckets_for_metric(
129 Matcher::Full(METRIC_HTTP_REQUEST_DURATION_SECONDS.to_owned()),
130 &HTTP_LATENCY_BUCKETS,
131 )?
132 .set_buckets_for_metric(
133 Matcher::Full(METRIC_HTTP_REQUEST_BODY_BYTES.to_owned()),
134 &HTTP_BODY_SIZE_BUCKETS,
135 )?
136 .set_buckets_for_metric(
137 Matcher::Full(METRIC_CONVERSION_DURATION_SECONDS.to_owned()),
138 &CONVERSION_DURATION_BUCKETS,
139 )?
140 .set_buckets_for_metric(
141 Matcher::Full(METRIC_CONVERSION_OUTPUT_BYTES.to_owned()),
142 &CONVERSION_OUTPUT_BYTES_BUCKETS,
143 )
144}
145
146#[inline]
156pub fn build_recorder() -> Result<(PrometheusRecorder, PrometheusHandle), BuildError> {
157 let recorder = configure_buckets(PrometheusBuilder::new())?.build_recorder();
158 let handle = recorder.handle();
159 Ok((recorder, handle))
160}
161
162#[inline]
173pub fn install_global() -> Result<PrometheusHandle, BuildError> {
174 let handle = configure_buckets(PrometheusBuilder::new())?.install_recorder()?;
175
176 describe_counter!(METRIC_HTTP_REQUESTS_TOTAL, "Total HTTP requests received.");
177 describe_histogram!(
178 METRIC_HTTP_REQUEST_DURATION_SECONDS,
179 "HTTP request latency in seconds."
180 );
181 describe_histogram!(
182 METRIC_HTTP_REQUEST_BODY_BYTES,
183 "HTTP request body size in bytes, labeled by input MIME type."
184 );
185 describe_counter!(
186 METRIC_CONVERSIONS_TOTAL,
187 "Total document conversions, labeled by result, error class, and input/output MIME type."
188 );
189 describe_histogram!(
190 METRIC_CONVERSION_DURATION_SECONDS,
191 "Document conversion duration in seconds, labeled by result and input/output MIME type."
192 );
193 describe_histogram!(
194 METRIC_CONVERSION_OUTPUT_BYTES,
195 "Document conversion output size in bytes (recorded only on successful conversions), labeled by input/output MIME type."
196 );
197
198 Ok(handle)
199}
200
201#[inline]
210pub fn metrics_handler(
211 handle: PrometheusHandle,
212) -> impl Fn() -> core::future::Ready<axum::response::Response> + Clone + Send + 'static {
213 move || {
214 let output = handle.render();
215 core::future::ready(
216 axum::http::Response::builder()
217 .header(CONTENT_TYPE, "text/plain; version=0.0.4; charset=utf-8")
218 .body(axum::body::Body::from(output))
219 .unwrap_or_else(|_| {
220 let mut response = axum::response::Response::new(axum::body::Body::from(
221 "failed to render metrics response",
222 ));
223 *response.status_mut() = axum::http::StatusCode::INTERNAL_SERVER_ERROR;
224 response
225 }),
226 )
227 }
228}
229
230#[cfg(test)]
231mod handler_tests {
232 #![allow(
233 clippy::tests_outside_test_module,
234 clippy::unwrap_used,
235 clippy::expect_used
236 )]
237
238 use super::*;
239 use axum::body::to_bytes;
240
241 #[tokio::test]
242 async fn metrics_handler_returns_200() {
243 let (recorder, handle) = build_recorder().expect("test recorder builds");
244 let result = metrics::with_local_recorder(&recorder, || {
245 let handler = metrics_handler(handle);
246 handler()
247 });
248 let response = result.await;
249 assert_eq!(response.status(), axum::http::StatusCode::OK);
250 }
251
252 #[tokio::test]
253 async fn metrics_handler_content_type_is_prometheus_text() {
254 let (recorder, handle) = build_recorder().expect("test recorder builds");
255 let result = metrics::with_local_recorder(&recorder, || {
256 let handler = metrics_handler(handle);
257 handler()
258 });
259 let response = result.await;
260 let content_type = response
261 .headers()
262 .get(axum::http::header::CONTENT_TYPE)
263 .expect("content-type header present")
264 .to_str()
265 .expect("content-type is valid str");
266 assert_eq!(content_type, "text/plain; version=0.0.4; charset=utf-8");
267 }
268
269 #[tokio::test]
270 async fn metrics_handler_body_is_valid_utf8() {
271 let (recorder, handle) = build_recorder().expect("test recorder builds");
272 let result = metrics::with_local_recorder(&recorder, || {
273 let handler = metrics_handler(handle);
274 handler()
275 });
276 let response = result.await;
277 let body_bytes = to_bytes(response.into_body(), usize::MAX)
278 .await
279 .expect("body readable");
280 let _body_str = String::from_utf8(body_bytes.to_vec()).expect("body is valid UTF-8");
281 }
282}