|
| 1 | +use prometheus::{self, opts, register_gauge}; |
| 2 | +use warp::{reject::Rejection, reply::Reply, Filter}; |
| 3 | + |
| 4 | +#[derive(Clone, Debug)] |
| 5 | +pub struct PaymentsPollerMetrics { |
| 6 | + pub last_processed_block: prometheus::Gauge, |
| 7 | +} |
| 8 | + |
| 9 | +impl PaymentsPollerMetrics { |
| 10 | + pub fn start(metrics_port: u16) -> anyhow::Result<Self> { |
| 11 | + let registry = prometheus::Registry::new(); |
| 12 | + |
| 13 | + let last_processed_block = register_gauge!(opts!( |
| 14 | + "last_processed_block", |
| 15 | + "Last processed block by poller" |
| 16 | + ))?; |
| 17 | + |
| 18 | + registry.register(Box::new(last_processed_block.clone()))?; |
| 19 | + |
| 20 | + let metrics_route = warp::path!("metrics") |
| 21 | + .and(warp::any().map(move || registry.clone())) |
| 22 | + .and_then(PaymentsPollerMetrics::metrics_handler); |
| 23 | + |
| 24 | + tokio::task::spawn(async move { |
| 25 | + warp::serve(metrics_route) |
| 26 | + .run(([0, 0, 0, 0], metrics_port)) |
| 27 | + .await; |
| 28 | + }); |
| 29 | + |
| 30 | + Ok(Self { |
| 31 | + last_processed_block, |
| 32 | + }) |
| 33 | + } |
| 34 | + |
| 35 | + pub async fn metrics_handler(registry: prometheus::Registry) -> Result<impl Reply, Rejection> { |
| 36 | + use prometheus::Encoder; |
| 37 | + let encoder = prometheus::TextEncoder::new(); |
| 38 | + |
| 39 | + let mut buffer = Vec::new(); |
| 40 | + if let Err(e) = encoder.encode(®istry.gather(), &mut buffer) { |
| 41 | + eprintln!("could not encode prometheus metrics: {}", e); |
| 42 | + }; |
| 43 | + let res = String::from_utf8(buffer.clone()) |
| 44 | + .inspect_err(|e| eprintln!("prometheus metrics could not be parsed correctly: {e}")) |
| 45 | + .unwrap_or_default(); |
| 46 | + buffer.clear(); |
| 47 | + |
| 48 | + Ok(res) |
| 49 | + } |
| 50 | + |
| 51 | + pub fn register_last_processed_block(&self, value: u64) { |
| 52 | + self.last_processed_block.set(value as f64); |
| 53 | + } |
| 54 | +} |
0 commit comments