alloy_transport/connect.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
use crate::{BoxTransport, Pbf, Transport, TransportError};
use futures_util::TryFutureExt;
/// Connection details for a transport.
///
/// This object captures the information necessary to establish a transport,
/// and may encapsulate reconnection logic.
///
/// ## Why implement `TransportConnect`?
///
/// Users may want to implement transport-connect for the following reasons:
/// - You want to customize a `reqwest::Client` before using it.
/// - You need to provide special authentication information to a remote provider.
/// - You have implemented a custom [`Transport`].
/// - You require a specific websocket reconnection strategy.
pub trait TransportConnect: Sized + Send + Sync + 'static {
/// The transport type that is returned by `connect`.
type Transport: Transport + Clone;
/// Returns `true` if the transport connects to a local resource.
fn is_local(&self) -> bool;
/// Connect to the transport, returning a `Transport` instance.
fn get_transport<'a: 'b, 'b>(&'a self) -> Pbf<'b, Self::Transport, TransportError>;
}
/// Connection details for a transport that can be boxed.
///
/// This trait is implemented for [`TransportConnect`] implementors that
/// produce a boxable transport. It can be used to create a boxed transport
/// without knowing the exact type of the transport.
///
/// This trait is separate from `TransportConnect`` to hide the associated type
/// in when this trait is a trait object. It is intended to allow creation of
/// several unlike transports or clients at once. E.g.
/// in something like `Vec<&dyn BoxTransportConnect>.
pub trait BoxTransportConnect {
/// Returns `true` if the transport is a local transport.
fn is_local(&self) -> bool;
/// Connect to a transport, and box it.
fn get_boxed_transport<'a: 'b, 'b>(&'a self) -> Pbf<'b, BoxTransport, TransportError>;
}
impl<T: TransportConnect> BoxTransportConnect for T {
fn is_local(&self) -> bool {
TransportConnect::is_local(self)
}
fn get_boxed_transport<'a: 'b, 'b>(&'a self) -> Pbf<'b, BoxTransport, TransportError> {
Box::pin(self.get_transport().map_ok(Transport::boxed))
}
}
#[cfg(test)]
fn _object_safe(_: Box<dyn BoxTransportConnect>) {}