|
| 1 | +use prometheus::{self, opts, register_int_counter, IntCounter}; |
| 2 | +use warp::{reject::Rejection, reply::Reply, Filter}; |
| 3 | + |
| 4 | +#[derive(Clone, Debug)] |
| 5 | +pub struct GatewayMetrics { |
| 6 | + pub success_response: IntCounter, |
| 7 | + pub server_error_response: IntCounter, |
| 8 | + pub user_error_response: IntCounter, |
| 9 | +} |
| 10 | + |
| 11 | +impl GatewayMetrics { |
| 12 | + pub fn start(metrics_port: u16) -> anyhow::Result<Self> { |
| 13 | + let registry = prometheus::Registry::new(); |
| 14 | + |
| 15 | + let success_response = |
| 16 | + register_int_counter!(opts!("success_response_count", "Success Responses"))?; |
| 17 | + |
| 18 | + let server_error_response = |
| 19 | + register_int_counter!(opts!("server_error_response_count", "Success Responses"))?; |
| 20 | + |
| 21 | + let user_error_response = |
| 22 | + register_int_counter!(opts!("user_error_response_count", "Success Responses"))?; |
| 23 | + |
| 24 | + registry.register(Box::new(success_response.clone()))?; |
| 25 | + registry.register(Box::new(server_error_response.clone()))?; |
| 26 | + registry.register(Box::new(user_error_response.clone()))?; |
| 27 | + |
| 28 | + let metrics_route = warp::path!("metrics") |
| 29 | + .and(warp::any().map(move || registry.clone())) |
| 30 | + .and_then(GatewayMetrics::metrics_handler); |
| 31 | + |
| 32 | + tokio::task::spawn(async move { |
| 33 | + warp::serve(metrics_route) |
| 34 | + .run(([0, 0, 0, 0], metrics_port)) |
| 35 | + .await; |
| 36 | + }); |
| 37 | + |
| 38 | + Ok(Self { |
| 39 | + success_response, |
| 40 | + server_error_response, |
| 41 | + user_error_response, |
| 42 | + }) |
| 43 | + } |
| 44 | + |
| 45 | + pub async fn metrics_handler(registry: prometheus::Registry) -> Result<impl Reply, Rejection> { |
| 46 | + use prometheus::Encoder; |
| 47 | + let encoder = prometheus::TextEncoder::new(); |
| 48 | + |
| 49 | + let mut buffer = Vec::new(); |
| 50 | + if let Err(e) = encoder.encode(®istry.gather(), &mut buffer) { |
| 51 | + eprintln!("could not encode prometheus metrics: {}", e); |
| 52 | + }; |
| 53 | + let res = String::from_utf8(buffer.clone()) |
| 54 | + .inspect_err(|e| eprintln!("prometheus metrics could not be parsed correctly: {e}")) |
| 55 | + .unwrap_or_default(); |
| 56 | + buffer.clear(); |
| 57 | + |
| 58 | + Ok(res) |
| 59 | + } |
| 60 | + |
| 61 | + pub fn inc_success_response(&self) { |
| 62 | + self.success_response.inc(); |
| 63 | + } |
| 64 | + |
| 65 | + pub fn inc_server_error_response(&self) { |
| 66 | + self.server_error_response.inc(); |
| 67 | + } |
| 68 | + |
| 69 | + pub fn inc_user_error_response(&self) { |
| 70 | + self.user_error_response.inc(); |
| 71 | + } |
| 72 | +} |
0 commit comments