alloy_transport/trait.rs
1use crate::{BoxTransport, IntoBoxTransport, TransportError, TransportFut};
2use alloy_json_rpc::{RequestPacket, ResponsePacket};
3use tower::Service;
4
5/// A `Transport` manages the JSON-RPC request/response lifecycle.
6///
7/// `Transports` should be instantiated via the [`TransportConnect`] trait.
8///
9/// Transports are responsible for the following:
10///
11/// - Communicating with the RPC server.
12/// - Managing any ongoing connection or communication resource.
13/// - Associating responses with requests.
14/// - Associating notifications with subscriptions.
15///
16/// As a result, a `Transport` may be a simple HTTP client, or a collection of
17/// long-lived tasks.
18///
19/// ## Implementing `Transport`
20///
21/// This trait is blanket implemented for all appropriate types. To implement
22/// this trait, you must implement the [`tower::Service`] trait with the
23/// appropriate associated types. It cannot be implemented directly.
24///
25/// ### ⚠️ Always implement `Clone` ⚠️
26///
27/// [`Clone`] is not a bound on `Transport`, however, transports generally may
28/// not be used as expected unless they implement `Clone`. For example, only
29/// cloneable transports may be used by the `RpcClient` in `alloy-rpc-client`
30/// to send RPC requests, and [`BoxTransport`] may only be used to type-erase
31/// cloneable transports.
32///
33/// If you are implementing a transport, make sure it is [`Clone`].
34///
35/// [`TransportConnect`]: crate::TransportConnect
36pub trait Transport:
37 Service<
38 RequestPacket,
39 Response = ResponsePacket,
40 Error = TransportError,
41 Future = TransportFut<'static>,
42 > + Send
43 + Sync
44 + 'static
45{
46 /// Convert this transport into a boxed trait object.
47 fn boxed(self) -> BoxTransport
48 where
49 Self: IntoBoxTransport,
50 {
51 BoxTransport::new(self)
52 }
53
54 /// Make a boxed trait object by cloning this transport.
55 fn as_boxed(&self) -> BoxTransport
56 where
57 Self: IntoBoxTransport,
58 {
59 self.clone().boxed()
60 }
61}
62
63impl<T> Transport for T where
64 T: Service<
65 RequestPacket,
66 Response = ResponsePacket,
67 Error = TransportError,
68 Future = TransportFut<'static>,
69 > + Send
70 + Sync
71 + 'static
72{
73}