Skip to main content

reth_rpc_builder/
rate_limiter.rs

1//! [`jsonrpsee`] helper layer for rate limiting certain methods.
2
3use jsonrpsee::{server::middleware::rpc::RpcServiceT, types::Request, MethodResponse};
4use std::{
5    future::Future,
6    pin::Pin,
7    sync::Arc,
8    task::{ready, Context, Poll},
9};
10use tokio::sync::{OwnedSemaphorePermit, Semaphore};
11use tokio_util::{either::Either, sync::PollSemaphore};
12use tower::Layer;
13
14/// Rate limiter for the RPC server.
15///
16/// Rate limits expensive calls such as debug_ and trace_.
17#[derive(Debug, Clone)]
18pub struct RpcRequestRateLimiter {
19    inner: Arc<RpcRequestRateLimiterInner>,
20}
21
22impl RpcRequestRateLimiter {
23    /// Create a new rate limit layer with the given number of permits.
24    pub fn new(rate_limit: usize) -> Self {
25        Self {
26            inner: Arc::new(RpcRequestRateLimiterInner {
27                call_guard: PollSemaphore::new(Arc::new(Semaphore::new(rate_limit))),
28            }),
29        }
30    }
31}
32
33impl<S> Layer<S> for RpcRequestRateLimiter {
34    type Service = RpcRequestRateLimitingService<S>;
35
36    fn layer(&self, inner: S) -> Self::Service {
37        RpcRequestRateLimitingService::new(inner, self.clone())
38    }
39}
40
41/// Rate Limiter for the RPC server
42#[derive(Debug, Clone)]
43struct RpcRequestRateLimiterInner {
44    /// Semaphore to rate limit calls
45    call_guard: PollSemaphore,
46}
47
48/// A [`RpcServiceT`] middleware that rate limits RPC calls to the server.
49#[derive(Debug, Clone)]
50pub struct RpcRequestRateLimitingService<S> {
51    /// The rate limiter for RPC requests
52    rate_limiter: RpcRequestRateLimiter,
53    /// The inner service being wrapped
54    inner: S,
55}
56
57impl<S> RpcRequestRateLimitingService<S> {
58    /// Create a new rate limited service.
59    pub const fn new(service: S, rate_limiter: RpcRequestRateLimiter) -> Self {
60        Self { inner: service, rate_limiter }
61    }
62}
63
64impl<S> RpcServiceT for RpcRequestRateLimitingService<S>
65where
66    S: RpcServiceT + Send + Sync + Clone + 'static,
67{
68    fn call<'a>(&self, req: Request<'a>) -> impl Future<Output = MethodResponse> + Send + 'a {
69        let method_name = req.method_name();
70        if method_name.starts_with("trace_") || method_name.starts_with("debug_") {
71            // Sync methods and the params decoding of async methods run inside `call`, so the
72            // inner service is only called once the permit is held.
73            let inner = self.inner.clone();
74            Either::Left(RateLimitingRequestFuture {
75                fut: async move { inner.call(req).await },
76                guard: Some(self.rate_limiter.inner.call_guard.clone()),
77                permit: None,
78            })
79        } else {
80            // if we don't need to rate limit, then there
81            // is no need to get a semaphore permit
82            Either::Right(RateLimitingRequestFuture {
83                fut: self.inner.call(req),
84                guard: None,
85                permit: None,
86            })
87        }
88    }
89
90    fn batch<'a>(
91        &self,
92        requests: jsonrpsee::core::middleware::Batch<'a>,
93    ) -> impl Future<Output = MethodResponse> + Send + 'a {
94        self.inner.batch(requests)
95    }
96
97    fn notification<'a>(
98        &self,
99        n: jsonrpsee::core::middleware::Notification<'a>,
100    ) -> impl Future<Output = MethodResponse> + Send + 'a {
101        self.inner.notification(n)
102    }
103}
104
105/// Response future.
106#[pin_project::pin_project]
107pub struct RateLimitingRequestFuture<F> {
108    #[pin]
109    fut: F,
110    guard: Option<PollSemaphore>,
111    permit: Option<OwnedSemaphorePermit>,
112}
113
114impl<F> std::fmt::Debug for RateLimitingRequestFuture<F> {
115    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        f.write_str("RateLimitingRequestFuture")
117    }
118}
119
120impl<F: Future> Future for RateLimitingRequestFuture<F> {
121    type Output = F::Output;
122
123    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
124        let this = self.project();
125        if let Some(guard) = this.guard.as_mut() {
126            *this.permit = ready!(guard.poll_acquire(cx));
127            *this.guard = None;
128        }
129        let res = this.fut.poll(cx);
130        if res.is_ready() {
131            *this.permit = None;
132        }
133        res
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140    use jsonrpsee::{
141        core::middleware::{Batch, Notification},
142        types::Id,
143        ResponsePayload,
144    };
145    use std::{
146        future::poll_fn,
147        pin::pin,
148        sync::atomic::{AtomicUsize, Ordering},
149    };
150    use tokio_util::sync::CancellationToken;
151
152    /// Counts the calls that reach it and completes them once `gate` is cancelled.
153    #[derive(Clone, Default)]
154    struct GatedService {
155        calls: Arc<AtomicUsize>,
156        gate: CancellationToken,
157    }
158
159    impl RpcServiceT for GatedService {
160        fn call<'a>(&self, req: Request<'a>) -> impl Future<Output = MethodResponse> + Send + 'a {
161            self.calls.fetch_add(1, Ordering::Relaxed);
162            let gate = self.gate.clone();
163            async move {
164                gate.cancelled().await;
165                MethodResponse::response(req.id(), ResponsePayload::success(true), usize::MAX)
166            }
167        }
168
169        fn batch<'a>(&self, _: Batch<'a>) -> impl Future<Output = MethodResponse> + Send + 'a {
170            std::future::ready(MethodResponse::notification())
171        }
172
173        fn notification<'a>(
174            &self,
175            _: Notification<'a>,
176        ) -> impl Future<Output = MethodResponse> + Send + 'a {
177            std::future::ready(MethodResponse::notification())
178        }
179    }
180
181    fn request(method: &'static str) -> Request<'static> {
182        Request::borrowed(method, None, Id::Number(0))
183    }
184
185    async fn poll_once<F: Future>(mut fut: Pin<&mut F>) -> Poll<F::Output> {
186        poll_fn(|cx| Poll::Ready(fut.as_mut().poll(cx))).await
187    }
188
189    #[tokio::test]
190    async fn limited_call_reaches_inner_service_with_permit() {
191        let inner = GatedService::default();
192        let service = RpcRequestRateLimiter::new(1).layer(inner.clone());
193
194        // Takes the only permit and waits in the inner service.
195        let mut first = pin!(service.call(request("trace_block")));
196        assert!(poll_once(first.as_mut()).await.is_pending());
197        assert_eq!(inner.calls.load(Ordering::Relaxed), 1);
198
199        // No permit is left, so the inner service must not see this call yet.
200        let mut second = pin!(service.call(request("debug_traceBlock")));
201        assert!(poll_once(second.as_mut()).await.is_pending());
202        assert_eq!(inner.calls.load(Ordering::Relaxed), 1);
203
204        // Other methods are not limited.
205        let mut unlimited = pin!(service.call(request("eth_blockNumber")));
206        assert!(poll_once(unlimited.as_mut()).await.is_pending());
207        assert_eq!(inner.calls.load(Ordering::Relaxed), 2);
208
209        inner.gate.cancel();
210        assert!(first.await.is_success());
211        assert!(second.await.is_success());
212        assert_eq!(inner.calls.load(Ordering::Relaxed), 3);
213        assert!(unlimited.await.is_success());
214    }
215}