select random peer instead of just the first (#109)

This commit is contained in:
Richard Ramos 2021-10-28 15:26:25 -04:00 committed by GitHub
parent 8ba64affba
commit b7a7143803
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 4 additions and 7 deletions

View File

@ -2,6 +2,7 @@ package utils
import (
"errors"
"math/rand"
logging "github.com/ipfs/go-log"
"github.com/libp2p/go-libp2p-core/host"
@ -10,8 +11,7 @@ import (
var log = logging.Logger("utils")
// SelectPeer is used to return a peer that supports a given protocol.
// It currently selects the first peer returned by the peerstore
// SelectPeer is used to return a random peer that supports a given protocol.
func SelectPeer(host host.Host, protocolId string) (*peer.ID, error) {
// @TODO We need to be more strategic about which peers we dial. Right now we just set one on the service.
// Ideally depending on the query and our set of peers we take a subset of ideal peers.
@ -19,9 +19,6 @@ func SelectPeer(host host.Host, protocolId string) (*peer.ID, error) {
// - which topics they track
// - latency?
// - default store peer?
// Selects the best peer for a given protocol
var peers peer.IDSlice
for _, peer := range host.Peerstore().Peers() {
protocols, err := host.Peerstore().SupportsProtocols(peer, protocolId)
@ -36,8 +33,8 @@ func SelectPeer(host host.Host, protocolId string) (*peer.ID, error) {
}
if len(peers) >= 1 {
// TODO: proper heuristic here that compares peer scores and selects "best" one. For now the first peer for the given protocol is returned
return &peers[0], nil
// TODO: proper heuristic here that compares peer scores and selects "best" one. For now a random peer for the given protocol is returned
return &peers[rand.Intn(len(peers))], nil // nolint: gosec
}
return nil, errors.New("no suitable peers found")