sui_network/
endpoint_manager.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use anemo::types::{PeerAffinity, PeerInfo};
5use mysten_network::Multiaddr;
6use tap::TapFallible;
7use tracing::warn;
8
9use crate::discovery;
10
11/// EndpointManager can be used to dynamically update the addresses of
12/// other nodes in the network.
13#[derive(Clone, Debug)]
14pub struct EndpointManager {
15    discovery_handle: discovery::Handle,
16}
17
18impl EndpointManager {
19    pub fn new(discovery_handle: discovery::Handle) -> Self {
20        Self { discovery_handle }
21    }
22
23    /// Updates the address(es) for the given endpoint.
24    ///
25    /// If the addresses have changed, forcibly reconnects to the peer.
26    pub fn update_endpoint(&self, endpoint: EndpointId, addresses: Vec<Multiaddr>) {
27        match endpoint {
28            EndpointId::P2p(peer_id) => {
29                let anemo_addresses: Vec<_> = addresses
30                    .into_iter()
31                    .filter_map(|addr| {
32                        addr.to_anemo_address()
33                            .tap_err(|_| {
34                                warn!(
35                                    ?addr,
36                                    "Skipping peer address: can't convert to anemo address"
37                                )
38                            })
39                            .ok()
40                    })
41                    .collect();
42                if anemo_addresses.is_empty() {
43                    warn!(?peer_id, "No valid addresses for peer after conversion");
44                }
45                self.discovery_handle.peer_address_change(PeerInfo {
46                    peer_id,
47                    affinity: PeerAffinity::High,
48                    address: anemo_addresses,
49                });
50            }
51        }
52    }
53}
54
55pub enum EndpointId {
56    P2p(anemo::PeerId),
57    // TODO: Implement support for updating consensus addresses via EndpointManager.
58    // Consensus(NetworkPublicKey),
59}