zebra_network/peer/
load_tracked_client.rs1use std::{
5 net::{IpAddr, SocketAddr},
6 sync::Arc,
7 task::{Context, Poll},
8};
9
10use tower::{
11 load::{Load, PeakEwma},
12 Service,
13};
14
15use crate::{
16 constants::{EWMA_DECAY_TIME_NANOS, EWMA_DEFAULT_RTT},
17 peer::{Client, ConnectedAddr, ConnectionInfo},
18 protocol::external::{
19 canonical_socket_addr,
20 types::{PeerServices, Version},
21 },
22};
23
24#[derive(Debug)]
28pub struct LoadTrackedClient {
29 service: PeakEwma<Client>,
31
32 connection_info: Arc<ConnectionInfo>,
34
35 pub(crate) block_advert_tx: tokio::sync::mpsc::Sender<crate::peer_set::BlockAdvert>,
37}
38
39impl From<Client> for LoadTrackedClient {
41 fn from(client: Client) -> Self {
42 let connection_info = client.connection_info.clone();
43 let block_advert_tx = client.block_advert_tx.clone();
44
45 let service = PeakEwma::new(
46 client,
47 EWMA_DEFAULT_RTT,
48 EWMA_DECAY_TIME_NANOS,
49 tower::load::CompleteOnResponse::default(),
50 );
51
52 LoadTrackedClient {
53 service,
54 connection_info,
55 block_advert_tx,
56 }
57 }
58}
59
60impl LoadTrackedClient {
61 pub fn remote_version(&self) -> Version {
63 self.connection_info.remote.version
64 }
65
66 pub fn remote_services(&self) -> PeerServices {
68 self.connection_info.remote.services
69 }
70
71 pub(crate) fn connection_info(&self) -> &Arc<ConnectionInfo> {
73 &self.connection_info
74 }
75
76 pub fn is_inbound_direct_from_ip(&self, ip: &IpAddr) -> bool {
78 let expected_ip = canonical_socket_addr(SocketAddr::new(*ip, 0)).ip();
79
80 matches!(
81 self.connection_info.connected_addr,
82 ConnectedAddr::InboundDirect { addr }
83 if canonical_socket_addr(addr.remove_socket_addr_privacy()).ip() == expected_ip
84 )
85 }
86}
87
88impl<Request> Service<Request> for LoadTrackedClient
89where
90 Client: Service<Request>,
91{
92 type Response = <Client as Service<Request>>::Response;
93 type Error = <Client as Service<Request>>::Error;
94 type Future = <PeakEwma<Client> as Service<Request>>::Future;
95
96 fn poll_ready(&mut self, context: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
97 self.service.poll_ready(context)
98 }
99
100 fn call(&mut self, request: Request) -> Self::Future {
101 self.service.call(request)
102 }
103}
104
105impl Load for LoadTrackedClient {
106 type Metric = <PeakEwma<Client> as Load>::Metric;
107
108 fn load(&self) -> Self::Metric {
109 self.service.load()
110 }
111}