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#[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 pub(crate) fn http(module: &RpcModule<()>) -> Self {
49 Self::new(module, RpcTransport::Http)
50 }
51
52 pub(crate) fn same_port(module: &RpcModule<()>) -> Self {
56 Self::http(module)
57 }
58
59 pub(crate) fn ws(module: &RpcModule<()>) -> Self {
61 Self::new(module, RpcTransport::WebSocket)
62 }
63
64 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#[derive(Default, Clone, Debug)]
80struct RpcServerMetricsInner {
81 connection_metrics: RpcServerConnectionMetrics,
83 call_metrics: HashMap<&'static str, RpcServerCallMetrics>,
85}
86
87#[derive(Clone, Debug)]
91pub struct RpcRequestMetricsService<S> {
92 metrics: RpcRequestMetrics,
94 inner: S,
96}
97
98impl<S> RpcRequestMetricsService<S> {
99 pub(crate) fn new(service: S, metrics: RpcRequestMetrics) -> Self {
100 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 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 self.metrics.inner.connection_metrics.connections_closed_total.increment(1);
155 }
156}
157
158#[pin_project::pin_project]
160pub struct MeteredRequestFuture<F> {
161 #[pin]
162 fut: F,
163 started_at: Instant,
165 metrics: RpcRequestMetrics,
167 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 this.metrics.inner.connection_metrics.requests_finished_total.increment(1);
189 this.metrics.inner.connection_metrics.request_time_seconds.record(elapsed);
190
191 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#[pin_project::pin_project]
209pub struct MeteredBatchRequestsFuture<F> {
210 #[pin]
211 fut: F,
212 started_at: Instant,
214 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#[derive(Debug, Clone, Copy, Eq, PartialEq)]
245pub(crate) enum RpcTransport {
246 Http,
247 WebSocket,
248 Ipc,
249}
250
251impl RpcTransport {
252 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 fn connection_metrics(&self) -> RpcServerConnectionMetrics {
263 RpcServerConnectionMetrics::new_with_labels(&[("transport", self.as_str())])
264 }
265}
266
267#[derive(Metrics, Clone)]
269#[metrics(scope = "rpc_server.connections")]
270struct RpcServerConnectionMetrics {
271 connections_opened_total: Counter,
273 connections_closed_total: Counter,
275 requests_started_total: Counter,
277 requests_finished_total: Counter,
279 request_time_seconds: Histogram,
281 batches_started_total: Counter,
283 batches_finished_total: Counter,
285 batch_response_time_seconds: Histogram,
287}
288
289#[derive(Metrics, Clone)]
291#[metrics(scope = "rpc_server.calls")]
292struct RpcServerCallMetrics {
293 started_total: Counter,
295 successful_total: Counter,
297 failed_total: Counter,
299 batched_total: Counter,
305 time_seconds: Histogram,
307}