alloy_transport/
trait.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
use crate::{BoxTransport, TransportError, TransportFut};
use alloy_json_rpc::{RequestPacket, ResponsePacket};
use tower::Service;

/// A `Transport` manages the JSON-RPC request/response lifecycle.
///
/// `Transports` should be instantiated via the [`TransportConnect`] trait.
///
/// Transports are responsible for the following:
///
/// - Communicating with the RPC server.
/// - Managing any ongoing connection or communication resource.
/// - Associating responses with requests.
/// - Associating notifications with subscriptions.
///
/// As a result, a `Transport` may be a simple HTTP client, or a collection of
/// long-lived tasks.
///
/// ## Implementing `Transport`
///
/// This trait is blanket implemented for all appropriate types. To implement
/// this trait, you must implement the [`tower::Service`] trait with the
/// appropriate associated types. It cannot be implemented directly.
///
/// ### ⚠️ Always implement `Clone` ⚠️
///
/// [`Clone`] is not a bound on `Transport`, however, transports generally may
/// not be used as expected unless they implement `Clone`. For example, only
/// cloneable transports may be used by the `RpcClient` in `alloy-rpc-client`
/// to send RPC requests, and [`BoxTransport`] may only be used to type-erase
/// cloneable transports.
///
/// If you are implementing a transport, make sure it is [`Clone`].
///
/// [`TransportConnect`]: crate::TransportConnect
pub trait Transport:
    Service<
        RequestPacket,
        Response = ResponsePacket,
        Error = TransportError,
        Future = TransportFut<'static>,
    > + Send
    + Sync
    + 'static
{
    /// Convert this transport into a boxed trait object.
    fn boxed(self) -> BoxTransport
    where
        Self: Sized + Clone,
    {
        BoxTransport::new(self)
    }

    /// Make a boxed trait object by cloning this transport.
    fn as_boxed(&self) -> BoxTransport
    where
        Self: Sized + Clone,
    {
        self.clone().boxed()
    }
}

impl<T> Transport for T where
    T: Service<
            RequestPacket,
            Response = ResponsePacket,
            Error = TransportError,
            Future = TransportFut<'static>,
        > + Send
        + Sync
        + 'static
{
}