zebra_rpc/server/rpc_metrics.rs
1//! RPC metrics middleware for Prometheus metrics collection.
2//!
3//! This middleware collects metrics for JSON-RPC requests, including:
4//! - Request count by method and status
5//! - Request duration by method
6//! - Active request count
7//! - Error count by method and error code
8//!
9//! These metrics complement the OpenTelemetry tracing in `rpc_tracing.rs`,
10//! providing aggregated data suitable for dashboards and alerting.
11
12use std::{collections::HashSet, sync::Arc, time::Instant};
13
14use jsonrpsee::{
15 server::middleware::rpc::{layer::ResponseFuture, RpcServiceT},
16 MethodResponse,
17};
18
19#[cfg(test)]
20mod tests;
21
22/// Middleware that collects Prometheus metrics for each RPC request.
23///
24/// This middleware records:
25/// - `rpc.requests.total{method, status}` - Counter of requests by method and status
26/// - `rpc.request.duration_seconds{method}` - Histogram of request durations
27/// - `rpc.active_requests` - Gauge of currently active requests
28/// - `rpc.errors.total{method, error_code}` - Counter of errors by method and code
29///
30/// Method labels use registered RPC method names, or `unknown` for unregistered names.
31#[derive(Clone)]
32pub struct RpcMetricsMiddleware<S> {
33 service: S,
34 registered_methods: Arc<HashSet<&'static str>>,
35}
36
37impl<S> RpcMetricsMiddleware<S> {
38 /// Create a new `RpcMetricsMiddleware` with the given `service` and registered method names.
39 ///
40 /// Collect `registered_methods` from the server's `RpcModule::method_names()` iterator.
41 /// Requests for names outside this set are labeled `unknown`.
42 pub fn new(service: S, registered_methods: Arc<HashSet<&'static str>>) -> Self {
43 Self {
44 service,
45 registered_methods,
46 }
47 }
48
49 fn method_label(&self, method: &str) -> &'static str {
50 method_label(&self.registered_methods, method)
51 }
52}
53
54/// The registered name of `method`, or `unknown` for names the server does not register, so
55/// labels stay bounded whatever clients send.
56pub(crate) fn method_label(
57 registered_methods: &HashSet<&'static str>,
58 method: &str,
59) -> &'static str {
60 registered_methods.get(method).copied().unwrap_or("unknown")
61}
62
63impl<'a, S> RpcServiceT<'a> for RpcMetricsMiddleware<S>
64where
65 S: RpcServiceT<'a> + Send + Sync + Clone + 'static,
66{
67 type Future = ResponseFuture<futures::future::BoxFuture<'a, MethodResponse>>;
68
69 fn call(&self, request: jsonrpsee::types::Request<'a>) -> Self::Future {
70 let service = self.service.clone();
71 let method = self.method_label(request.method_name());
72 let start = Instant::now();
73
74 // Increment active requests gauge
75 metrics::gauge!("rpc.active_requests").increment(1.0);
76
77 ResponseFuture::future(Box::pin(async move {
78 let response = service.call(request).await;
79 let duration = start.elapsed().as_secs_f64();
80
81 // Determine status and record metrics
82 let status = if response.is_error() {
83 "error"
84 } else {
85 "success"
86 };
87
88 // Record request count
89 metrics::counter!("rpc.requests.total", "method" => method, "status" => status)
90 .increment(1);
91
92 // Record request duration
93 metrics::histogram!("rpc.request.duration_seconds", "method" => method)
94 .record(duration);
95
96 // Record errors with error code
97 if response.is_error() {
98 let error_code = response
99 .as_error_code()
100 .map(|c| c.to_string())
101 .unwrap_or_else(|| "unknown".to_string());
102 metrics::counter!(
103 "rpc.errors.total",
104 "method" => method,
105 "error_code" => error_code
106 )
107 .increment(1);
108 }
109
110 // Decrement active requests gauge
111 metrics::gauge!("rpc.active_requests").decrement(1.0);
112
113 response
114 }))
115 }
116}