|
| 1 | +use actix_web::{ |
| 2 | + HttpResponse, |
| 3 | + Responder, |
| 4 | + body::MessageBody, |
| 5 | + dev::{ServiceRequest, ServiceResponse}, |
| 6 | + get, |
| 7 | + middleware::Next, |
| 8 | + web::{self, ServiceConfig} |
| 9 | +}; |
| 10 | +use documented::DocumentedFields; |
| 11 | +use prometheus_client::{ |
| 12 | + encoding::{EncodeLabelSet, text::encode}, |
| 13 | + metrics::{counter::Counter, family::Family}, |
| 14 | + registry::Registry |
| 15 | +}; |
| 16 | + |
| 17 | +use crate::api::{ |
| 18 | + common::{caching::CacheLabels, data::ApiData}, |
| 19 | + v1::metrics::ApiV1Metrics |
| 20 | +}; |
| 21 | + |
| 22 | +// TODO: Improve this macro so you can use only one macro call and it will |
| 23 | +// register all of them |
| 24 | + |
| 25 | +/// A macro that automatically initializes and registers a metric using inferred |
| 26 | +/// types and doc comments from the ApiMetrics struct |
| 27 | +#[macro_export] |
| 28 | +macro_rules! make_api_metric { |
| 29 | + ($registry:expr, $metrics_struct:ident, $name:ident) => { |
| 30 | + make_api_metric!($registry, $metrics_struct, $name, Family) |
| 31 | + }; |
| 32 | + ($registry:expr, $metrics_struct:ident, $name:ident, $type:ident) => { |
| 33 | + let $name = $type::default(); |
| 34 | + let name_str = stringify!($name); |
| 35 | + $registry.register( |
| 36 | + name_str, |
| 37 | + $metrics_struct::get_field_docs(name_str) |
| 38 | + .expect(&format!("No doc comment for '{}' field", name_str)), |
| 39 | + $name.clone() |
| 40 | + ); |
| 41 | + }; |
| 42 | +} |
| 43 | + |
| 44 | +pub trait MetricsGroup { |
| 45 | + fn init_metrics(registry: &mut Registry) -> Self; |
| 46 | +} |
| 47 | + |
| 48 | +pub struct AppMetrics { |
| 49 | + /// The root metrics registry used for storing and retrieving metrics |
| 50 | + pub registry: Registry, |
| 51 | + /// All of the global (application-wide) metrics |
| 52 | + pub global: GlobalMetrics, |
| 53 | + /// All of the API v1 metrics |
| 54 | + pub v1: ApiV1Metrics |
| 55 | +} |
| 56 | + |
| 57 | +impl AppMetrics { |
| 58 | + pub fn new() -> AppMetrics { |
| 59 | + let mut registry = <Registry>::default(); |
| 60 | + |
| 61 | + AppMetrics { |
| 62 | + global: GlobalMetrics::init_metrics(&mut registry), |
| 63 | + v1: ApiV1Metrics::init_metrics(&mut registry), |
| 64 | + registry |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +#[derive(DocumentedFields)] |
| 70 | +pub struct GlobalMetrics { |
| 71 | + /// The amount of generic API requests by endpoint and status code |
| 72 | + api_requests: Family<ApiRequestLabels, Counter>, |
| 73 | + /// The amount of cache hits by endpoint |
| 74 | + pub cache_hits: Family<CacheLabels, Counter>, |
| 75 | + /// The amount of cache misses by endpoint |
| 76 | + pub cache_misses: Family<CacheLabels, Counter> |
| 77 | +} |
| 78 | + |
| 79 | +impl MetricsGroup for GlobalMetrics { |
| 80 | + fn init_metrics(registry: &mut Registry) -> Self { |
| 81 | + make_api_metric!(registry, Self, api_requests); |
| 82 | + make_api_metric!(registry, Self, cache_hits); |
| 83 | + make_api_metric!(registry, Self, cache_misses); |
| 84 | + |
| 85 | + Self { |
| 86 | + api_requests, |
| 87 | + cache_hits, |
| 88 | + cache_misses |
| 89 | + } |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +pub fn configure(config: &mut ServiceConfig) { config.service(metrics_endpoint); } |
| 94 | + |
| 95 | +/// The endpoint to allow scraping metrics |
| 96 | +#[get("/metrics")] |
| 97 | +async fn metrics_endpoint(state: web::Data<ApiData>) -> impl Responder { |
| 98 | + let mut body = String::new(); |
| 99 | + if let Err(e) = encode(&mut body, &state.metrics.registry) { |
| 100 | + return HttpResponse::InternalServerError() |
| 101 | + .content_type("text/plain") |
| 102 | + .body(format!("Error encoding metrics: {e}")); |
| 103 | + } |
| 104 | + |
| 105 | + HttpResponse::Ok() |
| 106 | + .content_type("application/openmetrics-text; version=1.0.0; charset=utf-8") |
| 107 | + .body(body) |
| 108 | +} |
| 109 | + |
| 110 | +#[derive(Debug, Hash, PartialEq, Eq, Clone, EncodeLabelSet)] |
| 111 | +struct ApiRequestLabels { |
| 112 | + path: String, |
| 113 | + status_code: u16 |
| 114 | +} |
| 115 | + |
| 116 | +pub async fn middleware( |
| 117 | + mut service_request: ServiceRequest, |
| 118 | + next: Next<impl MessageBody> |
| 119 | +) -> Result<ServiceResponse<impl MessageBody>, actix_web::Error> { |
| 120 | + let data = service_request.extract::<web::Data<ApiData>>().await?; |
| 121 | + |
| 122 | + let path = service_request.uri().path().to_string(); |
| 123 | + let response = next.call(service_request).await; |
| 124 | + |
| 125 | + let labels = match &response { |
| 126 | + Ok(r) => ApiRequestLabels { |
| 127 | + path, |
| 128 | + status_code: r.status().as_u16() |
| 129 | + }, |
| 130 | + Err(e) => ApiRequestLabels { |
| 131 | + path, |
| 132 | + status_code: e.as_response_error().status_code().as_u16() |
| 133 | + } |
| 134 | + }; |
| 135 | + data.metrics |
| 136 | + .global |
| 137 | + .api_requests |
| 138 | + .get_or_create(&labels) |
| 139 | + .inc(); |
| 140 | + |
| 141 | + response |
| 142 | +} |
0 commit comments