alloy_rpc_client/
client.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
use crate::{poller::PollerBuilder, BatchRequest, ClientBuilder, RpcCall};
use alloy_json_rpc::{Id, Request, RpcParam, RpcReturn};
use alloy_transport::{BoxTransport, Transport};
use alloy_transport_http::Http;
use std::{
    borrow::Cow,
    ops::Deref,
    sync::{
        atomic::{AtomicU64, Ordering},
        Arc, Weak,
    },
    time::Duration,
};
use tower::{layer::util::Identity, ServiceBuilder};

/// An [`RpcClient`] in a [`Weak`] reference.
pub type WeakClient<T> = Weak<RpcClientInner<T>>;

/// A borrowed [`RpcClient`].
pub type ClientRef<'a, T> = &'a RpcClientInner<T>;

/// Parameter type of a JSON-RPC request with no parameters.
pub type NoParams = [(); 0];

/// A JSON-RPC client.
///
/// [`RpcClient`] should never be instantiated directly. Instead, use
/// [`ClientBuilder`].
///
/// [`ClientBuilder`]: crate::ClientBuilder
#[derive(Debug)]
pub struct RpcClient<T>(Arc<RpcClientInner<T>>);

impl<T> Clone for RpcClient<T> {
    fn clone(&self) -> Self {
        Self(Arc::clone(&self.0))
    }
}

impl RpcClient<Identity> {
    /// Create a new [`ClientBuilder`].
    pub const fn builder() -> ClientBuilder<Identity> {
        ClientBuilder { builder: ServiceBuilder::new() }
    }
}

#[cfg(feature = "reqwest")]
impl RpcClient<Http<reqwest::Client>> {
    /// Create a new [`RpcClient`] with an HTTP transport.
    pub fn new_http(url: reqwest::Url) -> Self {
        let http = Http::new(url);
        let is_local = http.guess_local();
        Self::new(http, is_local)
    }
}

impl<T> RpcClient<T> {
    /// Creates a new [`RpcClient`] with the given transport.
    pub fn new(t: T, is_local: bool) -> Self {
        Self(Arc::new(RpcClientInner::new(t, is_local)))
    }

    /// Creates a new [`RpcClient`] with the given inner client.
    pub fn from_inner(inner: RpcClientInner<T>) -> Self {
        Self(Arc::new(inner))
    }

    /// Get a reference to the client.
    pub const fn inner(&self) -> &Arc<RpcClientInner<T>> {
        &self.0
    }

    /// Convert the client into its inner type.
    pub fn into_inner(self) -> Arc<RpcClientInner<T>> {
        self.0
    }

    /// Get a [`Weak`] reference to the client.
    pub fn get_weak(&self) -> WeakClient<T> {
        Arc::downgrade(&self.0)
    }

    /// Borrow the client.
    pub fn get_ref(&self) -> ClientRef<'_, T> {
        &self.0
    }

    /// Sets the poll interval for the client in milliseconds.
    ///
    /// Note: This will only set the poll interval for the client if it is the only reference to the
    /// inner client. If the reference is held by many, then it will not update the poll interval.
    pub fn with_poll_interval(self, poll_interval: Duration) -> Self {
        self.inner().set_poll_interval(poll_interval);
        self
    }
}

impl<T: Transport> RpcClient<T> {
    /// Build a poller that polls a method with the given parameters.
    ///
    /// See [`PollerBuilder`] for examples and more details.
    pub fn prepare_static_poller<Params, Resp>(
        &self,
        method: impl Into<Cow<'static, str>>,
        params: Params,
    ) -> PollerBuilder<T, Params, Resp>
    where
        T: Clone,
        Params: RpcParam + 'static,
        Resp: RpcReturn + Clone,
    {
        PollerBuilder::new(self.get_weak(), method, params)
    }
}

impl<T: Transport + Clone> RpcClient<T> {
    /// Boxes the transport.
    ///
    /// This will create a new client if this instance is not the only reference to the inner
    /// client.
    pub fn boxed(self) -> RpcClient<BoxTransport> {
        let inner = match Arc::try_unwrap(self.0) {
            Ok(inner) => inner,
            Err(inner) => RpcClientInner::new(inner.transport.clone(), inner.is_local)
                .with_id(inner.id.load(Ordering::Relaxed)),
        };
        RpcClient::from_inner(inner.boxed())
    }
}

impl<T> RpcClient<Http<T>> {
    /// Create a new [`BatchRequest`] builder.
    #[inline]
    pub fn new_batch(&self) -> BatchRequest<'_, Http<T>> {
        BatchRequest::new(&self.0)
    }
}

impl<T> Deref for RpcClient<T> {
    type Target = RpcClientInner<T>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// A JSON-RPC client.
///
/// This struct manages a [`Transport`] and a request ID counter. It is used to
/// build [`RpcCall`] and [`BatchRequest`] objects. The client delegates
/// transport access to the calls.
///
/// ### Note
///
/// IDs are allocated sequentially, starting at 0. IDs are reserved via
/// [`RpcClientInner::next_id`]. Note that allocated IDs may not be used. There
/// is no guarantee that a prepared [`RpcCall`] will be sent, or that a sent
/// call will receive a response.
#[derive(Debug)]
pub struct RpcClientInner<T> {
    /// The underlying transport.
    pub(crate) transport: T,
    /// `true` if the transport is local.
    pub(crate) is_local: bool,
    /// The next request ID to use.
    pub(crate) id: AtomicU64,
    /// The poll interval for the client in milliseconds.
    pub(crate) poll_interval: AtomicU64,
}

impl<T> RpcClientInner<T> {
    /// Create a new [`RpcClient`] with the given transport.
    ///
    /// Note: Sets the poll interval to 250ms for local transports and 7s for remote transports by
    /// default.
    #[inline]
    pub const fn new(t: T, is_local: bool) -> Self {
        Self {
            transport: t,
            is_local,
            id: AtomicU64::new(0),
            poll_interval: if is_local { AtomicU64::new(250) } else { AtomicU64::new(7000) },
        }
    }

    /// Sets the starting ID for the client.
    #[inline]
    pub fn with_id(self, id: u64) -> Self {
        Self { id: AtomicU64::new(id), ..self }
    }

    /// Returns the default poll interval (milliseconds) for the client.
    pub fn poll_interval(&self) -> Duration {
        Duration::from_millis(self.poll_interval.load(Ordering::Relaxed))
    }

    /// Set the poll interval for the client in milliseconds. Default:
    /// 7s for remote and 250ms for local transports.
    pub fn set_poll_interval(&self, poll_interval: Duration) {
        self.poll_interval.store(poll_interval.as_millis() as u64, Ordering::Relaxed);
    }

    /// Returns a reference to the underlying transport.
    #[inline]
    pub const fn transport(&self) -> &T {
        &self.transport
    }

    /// Returns a mutable reference to the underlying transport.
    #[inline]
    pub fn transport_mut(&mut self) -> &mut T {
        &mut self.transport
    }

    /// Consumes the client and returns the underlying transport.
    #[inline]
    pub fn into_transport(self) -> T {
        self.transport
    }

    /// Returns a reference to the pubsub frontend if the transport supports it.
    #[cfg(feature = "pubsub")]
    pub fn pubsub_frontend(&self) -> Option<&alloy_pubsub::PubSubFrontend>
    where
        T: std::any::Any,
    {
        let t = self.transport() as &dyn std::any::Any;
        t.downcast_ref::<alloy_pubsub::PubSubFrontend>().or_else(|| {
            t.downcast_ref::<BoxTransport>()
                .and_then(|t| t.as_any().downcast_ref::<alloy_pubsub::PubSubFrontend>())
        })
    }

    /// Build a `JsonRpcRequest` with the given method and params.
    ///
    /// This function reserves an ID for the request, however the request is not sent.
    ///
    /// To send a request, use [`RpcClientInner::request`] and await the returned [`RpcCall`].
    #[inline]
    pub fn make_request<Params: RpcParam>(
        &self,
        method: impl Into<Cow<'static, str>>,
        params: Params,
    ) -> Request<Params> {
        Request::new(method, self.next_id(), params)
    }

    /// `true` if the client believes the transport is local.
    ///
    /// This can be used to optimize remote API usage, or to change program
    /// behavior on local endpoints. When the client is instantiated by parsing
    /// a URL or other external input, this value is set on a best-efforts
    /// basis and may be incorrect.
    #[inline]
    pub const fn is_local(&self) -> bool {
        self.is_local
    }

    /// Set the `is_local` flag.
    #[inline]
    pub fn set_local(&mut self, is_local: bool) {
        self.is_local = is_local;
    }

    /// Reserve a request ID value. This is used to generate request IDs.
    #[inline]
    fn increment_id(&self) -> u64 {
        self.id.fetch_add(1, Ordering::Relaxed)
    }

    /// Reserve a request ID u64.
    #[inline]
    pub fn next_id(&self) -> Id {
        self.increment_id().into()
    }
}

impl<T: Transport + Clone> RpcClientInner<T> {
    /// Prepares an [`RpcCall`].
    ///
    /// This function reserves an ID for the request, however the request is not sent.
    /// To send a request, await the returned [`RpcCall`].
    ///
    /// # Note
    ///
    /// Serialization is done lazily. It will not be performed until the call is awaited.
    /// This means that if a serializer error occurs, it will not be caught until the call is
    /// awaited.
    #[doc(alias = "prepare")]
    pub fn request<Params: RpcParam, Resp: RpcReturn>(
        &self,
        method: impl Into<Cow<'static, str>>,
        params: Params,
    ) -> RpcCall<T, Params, Resp> {
        let request = self.make_request(method, params);
        RpcCall::new(request, self.transport.clone())
    }

    /// Prepares an [`RpcCall`] with no parameters.
    ///
    /// See [`request`](Self::request) for more details.
    pub fn request_noparams<Resp: RpcReturn>(
        &self,
        method: impl Into<Cow<'static, str>>,
    ) -> RpcCall<T, NoParams, Resp> {
        self.request(method, [])
    }

    /// Type erase the service in the transport, allowing it to be used in a
    /// generic context.
    ///
    /// ## Note:
    ///
    /// This is for abstracting over `RpcClient<T>` for multiple `T` by
    /// erasing each type. E.g. if you have `RpcClient<Http>` and
    /// `RpcClient<Ws>` you can put both into a `Vec<RpcClient<BoxTransport>>`.
    pub fn boxed(self) -> RpcClientInner<BoxTransport> {
        RpcClientInner {
            transport: self.transport.boxed(),
            is_local: self.is_local,
            id: self.id,
            poll_interval: self.poll_interval,
        }
    }
}

#[cfg(feature = "pubsub")]
mod pubsub_impl {
    use super::*;
    use alloy_pubsub::{PubSubConnect, PubSubFrontend, RawSubscription, Subscription};
    use alloy_transport::TransportResult;

    impl RpcClientInner<PubSubFrontend> {
        /// Get a [`RawSubscription`] for the given subscription ID.
        pub async fn get_raw_subscription(&self, id: alloy_primitives::B256) -> RawSubscription {
            self.transport.get_subscription(id).await.unwrap()
        }

        /// Get a [`Subscription`] for the given subscription ID.
        pub async fn get_subscription<T: serde::de::DeserializeOwned>(
            &self,
            id: alloy_primitives::B256,
        ) -> Subscription<T> {
            Subscription::from(self.get_raw_subscription(id).await)
        }
    }

    impl RpcClient<PubSubFrontend> {
        /// Connect to a transport via a [`PubSubConnect`] implementor.
        pub async fn connect_pubsub<C>(connect: C) -> TransportResult<Self>
        where
            C: PubSubConnect,
        {
            ClientBuilder::default().pubsub(connect).await
        }

        /// Get the currently configured channel size. This is the number of items
        /// to buffer in new subscription channels. Defaults to 16. See
        /// [`tokio::sync::broadcast`] for a description of relevant
        /// behavior.
        ///
        /// [`tokio::sync::broadcast`]: https://docs.rs/tokio/latest/tokio/sync/broadcast/index.html
        pub fn channel_size(&self) -> usize {
            self.transport.channel_size()
        }

        /// Set the channel size.
        pub fn set_channel_size(&self, size: usize) {
            self.transport.set_channel_size(size)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use similar_asserts::assert_eq;

    #[test]
    fn test_client_with_poll_interval() {
        let poll_interval = Duration::from_millis(5_000);
        let client = RpcClient::new_http(reqwest::Url::parse("http://localhost").unwrap())
            .with_poll_interval(poll_interval);
        assert_eq!(client.poll_interval(), poll_interval);
    }
}