Skip to main content

reth_rpc_builder/
metrics.rs

1use jsonrpsee::{
2    core::middleware::{Batch, Notification},
3    server::middleware::rpc::RpcServiceT,
4    types::Request,
5    MethodResponse, RpcModule,
6};
7use reth_metrics::{
8    metrics::{Counter, Histogram},
9    Metrics,
10};
11use reth_primitives_traits::FastInstant as Instant;
12use std::{
13    collections::HashMap,
14    future::Future,
15    pin::Pin,
16    sync::Arc,
17    task::{Context, Poll},
18};
19use tower::Layer;
20
21/// Metrics for the RPC server.
22///
23/// Metrics are divided into two categories:
24/// - Connection metrics: metrics for the connection (e.g. number of connections opened)
25/// - Request metrics: metrics for each RPC method (e.g. number of calls started, time taken to
26///   process a call)
27#[derive(Default, Debug, Clone)]
28pub(crate) struct RpcRequestMetrics {
29    inner: Arc<RpcServerMetricsInner>,
30}
31
32impl RpcRequestMetrics {
33    pub(crate) fn new(module: &RpcModule<()>, transport: RpcTransport) -> Self {
34        Self {
35            inner: Arc::new(RpcServerMetricsInner {
36                connection_metrics: transport.connection_metrics(),
37                call_metrics: module
38                    .method_names()
39                    .map(|method| {
40                        (method, RpcServerCallMetrics::new_with_labels(&[("method", method)]))
41                    })
42                    .collect(),
43            }),
44        }
45    }
46
47    /// Creates a new instance of the metrics layer for HTTP.
48    pub(crate) fn http(module: &RpcModule<()>) -> Self {
49        Self::new(module, RpcTransport::Http)
50    }
51
52    /// Creates a new instance of the metrics layer for same port.
53    ///
54    /// Note: currently it's not possible to track transport specific metrics for a server that runs http and ws on the same port: <https://github.com/paritytech/jsonrpsee/issues/1345> until we have this feature we will use the http metrics for this case.
55    pub(crate) fn same_port(module: &RpcModule<()>) -> Self {
56        Self::http(module)
57    }
58
59    /// Creates a new instance of the metrics layer for Ws.
60    pub(crate) fn ws(module: &RpcModule<()>) -> Self {
61        Self::new(module, RpcTransport::WebSocket)
62    }
63
64    /// Creates a new instance of the metrics layer for Ipc.
65    pub(crate) fn ipc(module: &RpcModule<()>) -> Self {
66        Self::new(module, RpcTransport::Ipc)
67    }
68}
69
70impl<S> Layer<S> for RpcRequestMetrics {
71    type Service = RpcRequestMetricsService<S>;
72
73    fn layer(&self, inner: S) -> Self::Service {
74        RpcRequestMetricsService::new(inner, self.clone())
75    }
76}
77
78/// Metrics for the RPC server
79#[derive(Default, Clone, Debug)]
80struct RpcServerMetricsInner {
81    /// Connection metrics per transport type
82    connection_metrics: RpcServerConnectionMetrics,
83    /// Call metrics per RPC method
84    call_metrics: HashMap<&'static str, RpcServerCallMetrics>,
85}
86
87/// A [`RpcServiceT`] middleware that captures RPC metrics for the server.
88///
89/// This is created per connection and captures metrics for each request.
90#[derive(Clone, Debug)]
91pub struct RpcRequestMetricsService<S> {
92    /// The metrics collector for RPC requests
93    metrics: RpcRequestMetrics,
94    /// The inner service being wrapped
95    inner: S,
96}
97
98impl<S> RpcRequestMetricsService<S> {
99    pub(crate) fn new(service: S, metrics: RpcRequestMetrics) -> Self {
100        // this instance is kept alive for the duration of the connection
101        metrics.inner.connection_metrics.connections_opened_total.increment(1);
102        Self { inner: service, metrics }
103    }
104}
105
106impl<S> RpcServiceT for RpcRequestMetricsService<S>
107where
108    S: RpcServiceT + Send + Sync + Clone + 'static,
109{
110    fn call<'a>(&self, req: Request<'a>) -> impl Future<Output = MethodResponse> + Send + 'a {
111        self.metrics.inner.connection_metrics.requests_started_total.increment(1);
112        let call_metrics = self.metrics.inner.call_metrics.get_key_value(req.method.as_ref());
113        if let Some((_, call_metrics)) = &call_metrics {
114            call_metrics.started_total.increment(1);
115        }
116        // Sync methods and the params decoding of async methods run inside `call`.
117        let started_at = Instant::now();
118        MeteredRequestFuture {
119            fut: self.inner.call(req),
120            started_at,
121            metrics: self.metrics.clone(),
122            method: call_metrics.map(|(method, _)| *method),
123        }
124    }
125
126    fn batch<'a>(&self, req: Batch<'a>) -> impl Future<Output = MethodResponse> + Send + 'a {
127        self.metrics.inner.connection_metrics.batches_started_total.increment(1);
128
129        for batch_entry in req.iter().flatten() {
130            let method_name = batch_entry.method_name();
131            if let Some(call_metrics) = self.metrics.inner.call_metrics.get(method_name) {
132                call_metrics.batched_total.increment(1);
133            }
134        }
135
136        MeteredBatchRequestsFuture {
137            fut: self.inner.batch(req),
138            started_at: Instant::now(),
139            metrics: self.metrics.clone(),
140        }
141    }
142
143    fn notification<'a>(
144        &self,
145        n: Notification<'a>,
146    ) -> impl Future<Output = MethodResponse> + Send + 'a {
147        self.inner.notification(n)
148    }
149}
150
151impl<S> Drop for RpcRequestMetricsService<S> {
152    fn drop(&mut self) {
153        // update connection metrics, connection closed
154        self.metrics.inner.connection_metrics.connections_closed_total.increment(1);
155    }
156}
157
158/// Response future to update the metrics for a single request/response pair.
159#[pin_project::pin_project]
160pub struct MeteredRequestFuture<F> {
161    #[pin]
162    fut: F,
163    /// time when the request started
164    started_at: Instant,
165    /// metrics for the method call
166    metrics: RpcRequestMetrics,
167    /// the method name if known
168    method: Option<&'static str>,
169}
170
171impl<F> std::fmt::Debug for MeteredRequestFuture<F> {
172    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173        f.write_str("MeteredRequestFuture")
174    }
175}
176
177impl<F: Future<Output = MethodResponse>> Future for MeteredRequestFuture<F> {
178    type Output = F::Output;
179
180    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
181        let this = self.project();
182
183        let res = this.fut.poll(cx);
184        if let Poll::Ready(resp) = &res {
185            let elapsed = this.started_at.elapsed().as_secs_f64();
186
187            // update transport metrics
188            this.metrics.inner.connection_metrics.requests_finished_total.increment(1);
189            this.metrics.inner.connection_metrics.request_time_seconds.record(elapsed);
190
191            // update call metrics
192            if let Some(call_metrics) =
193                this.method.and_then(|method| this.metrics.inner.call_metrics.get(method))
194            {
195                call_metrics.time_seconds.record(elapsed);
196                if resp.is_success() {
197                    call_metrics.successful_total.increment(1);
198                } else {
199                    call_metrics.failed_total.increment(1);
200                }
201            }
202        }
203        res
204    }
205}
206
207/// Response future to update the metrics for a batch of request/response pairs.
208#[pin_project::pin_project]
209pub struct MeteredBatchRequestsFuture<F> {
210    #[pin]
211    fut: F,
212    /// time when the batch request started
213    started_at: Instant,
214    /// metrics for the batch
215    metrics: RpcRequestMetrics,
216}
217
218impl<F> std::fmt::Debug for MeteredBatchRequestsFuture<F> {
219    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220        f.write_str("MeteredBatchRequestsFuture")
221    }
222}
223
224impl<F> Future for MeteredBatchRequestsFuture<F>
225where
226    F: Future,
227{
228    type Output = F::Output;
229
230    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
231        let this = self.project();
232        let res = this.fut.poll(cx);
233
234        if res.is_ready() {
235            let elapsed = this.started_at.elapsed().as_secs_f64();
236            this.metrics.inner.connection_metrics.batches_finished_total.increment(1);
237            this.metrics.inner.connection_metrics.batch_response_time_seconds.record(elapsed);
238        }
239        res
240    }
241}
242
243/// The transport protocol used for the RPC connection.
244#[derive(Debug, Clone, Copy, Eq, PartialEq)]
245pub(crate) enum RpcTransport {
246    Http,
247    WebSocket,
248    Ipc,
249}
250
251impl RpcTransport {
252    /// Returns the string representation of the transport protocol.
253    pub(crate) const fn as_str(&self) -> &'static str {
254        match self {
255            Self::Http => "http",
256            Self::WebSocket => "ws",
257            Self::Ipc => "ipc",
258        }
259    }
260
261    /// Returns the connection metrics for the transport protocol.
262    fn connection_metrics(&self) -> RpcServerConnectionMetrics {
263        RpcServerConnectionMetrics::new_with_labels(&[("transport", self.as_str())])
264    }
265}
266
267/// Metrics for the RPC connections
268#[derive(Metrics, Clone)]
269#[metrics(scope = "rpc_server.connections")]
270struct RpcServerConnectionMetrics {
271    /// The number of connections opened
272    connections_opened_total: Counter,
273    /// The number of connections closed
274    connections_closed_total: Counter,
275    /// The number of requests started
276    requests_started_total: Counter,
277    /// The number of requests finished
278    requests_finished_total: Counter,
279    /// Response for a single request/response pair
280    request_time_seconds: Histogram,
281    /// The number of batch requests started
282    batches_started_total: Counter,
283    /// The number of batch requests finished
284    batches_finished_total: Counter,
285    /// Response time for a batch request
286    batch_response_time_seconds: Histogram,
287}
288
289/// Metrics for the RPC calls
290#[derive(Metrics, Clone)]
291#[metrics(scope = "rpc_server.calls")]
292struct RpcServerCallMetrics {
293    /// The number of calls started
294    started_total: Counter,
295    /// The number of successful calls
296    successful_total: Counter,
297    /// The number of failed calls
298    failed_total: Counter,
299    /// The number of calls received as batch entries.
300    ///
301    /// jsonrpsee dispatches batch entries internally without invoking this middleware's `call`,
302    /// so only their per-method volume can be tracked; batched calls are excluded from
303    /// `started_total`, `successful_total`, `failed_total` and `time_seconds`.
304    batched_total: Counter,
305    /// Response for a single call
306    time_seconds: Histogram,
307}