diff --git a/include/libp2p/host/basic_host.hpp b/include/libp2p/host/basic_host.hpp index fbfeb55..5cd7dbb 100644 --- a/include/libp2p/host/basic_host.hpp +++ b/include/libp2p/host/basic_host.hpp @@ -229,6 +229,8 @@ namespace libp2p::host { */ StreamProtocols getSupportedProtocols() const; + size_t getConnectedPeerCount() const; + private: std::shared_ptr idmgr_; std::shared_ptr listener_; diff --git a/include/libp2p/network/connection_manager.hpp b/include/libp2p/network/connection_manager.hpp index ff11efc..3e6d485 100644 --- a/include/libp2p/network/connection_manager.hpp +++ b/include/libp2p/network/connection_manager.hpp @@ -20,6 +20,10 @@ namespace libp2p::event::network { channel_decl>; + using OnConnectionClosedChannel = + channel_decl>; + /// fired when all connections to peer closed using OnPeerDisconnectedChannel = channel_decl; @@ -54,6 +58,8 @@ namespace libp2p::network { const peer::PeerId &peer_id, const std::shared_ptr &conn); + size_t getConnectedPeerCount() const; + private: std::unordered_map> connections_; diff --git a/src/host/basic_host.cpp b/src/host/basic_host.cpp index cba6791..f9a103b 100644 --- a/src/host/basic_host.cpp +++ b/src/host/basic_host.cpp @@ -238,4 +238,8 @@ namespace libp2p::host { StreamProtocols BasicHost::getSupportedProtocols() const { return listener_->getSupportedProtocols(); } + + size_t BasicHost::getConnectedPeerCount() const { + return connection_manager_->getConnectedPeerCount(); + } } // namespace libp2p::host diff --git a/src/network/connection_manager.cpp b/src/network/connection_manager.cpp index 44e2ad9..16f4d8e 100644 --- a/src/network/connection_manager.cpp +++ b/src/network/connection_manager.cpp @@ -33,8 +33,8 @@ namespace libp2p::network { return out; } - ConnectionManager::ConnectionSPtr - ConnectionManager::getBestConnectionForPeer(const peer::PeerId &p) const { + ConnectionManager::ConnectionSPtr ConnectionManager::getBestConnectionForPeer( + const peer::PeerId &p) const { auto it = connections_.find(p); if (it != connections_.end()) { for (const auto &conn : it->second) { @@ -79,8 +79,7 @@ namespace libp2p::network { return out; } - ConnectionManager::ConnectionManager( - std::shared_ptr bus) + ConnectionManager::ConnectionManager(std::shared_ptr bus) : bus_(std::move(bus)) {} void ConnectionManager::collectGarbage() { @@ -125,6 +124,8 @@ namespace libp2p::network { // ignore errors (void)conn->close(); } + bus_->getChannel().publish( + conn); } closing_connections_to_peer_.reset(); @@ -153,6 +154,9 @@ namespace libp2p::network { [[maybe_unused]] auto erased = it->second.erase(conn); if (erased == 0) { log()->error("inconsistency in onConnectionClosed, connection not found"); + } else { + bus_->getChannel().publish( + conn); } if (it->second.empty()) { @@ -162,4 +166,7 @@ namespace libp2p::network { } } + size_t ConnectionManager::getConnectedPeerCount() const { + return connections_.size(); + } } // namespace libp2p::network