github.com/qri-io/qri@v0.10.1-0.20220104210721-c771715036cb/p2p/discovery.go (about)

     1  package p2p
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	peer "github.com/libp2p/go-libp2p-core/peer"
     8  	discovery "github.com/libp2p/go-libp2p/p2p/discovery"
     9  )
    10  
    11  const (
    12  	discoveryConnTimeout = time.Second * 30
    13  	discoveryInterval    = time.Second * 5
    14  )
    15  
    16  // setupDiscovery initiates local peer discovery, allocating a discovery service
    17  // if one doesn't exist, then registering to be notified on peer discovery
    18  func (n *QriNode) setupDiscovery(ctx context.Context) error {
    19  	var err error
    20  	if n.Discovery, err = discovery.NewMdnsService(ctx, n.host, discoveryInterval, discovery.ServiceTag); err != nil {
    21  		return err
    22  	}
    23  	// Registering will call n.HandlePeerFound when peers are discovered
    24  	n.Discovery.RegisterNotifee(n)
    25  	return nil
    26  }
    27  
    28  // HandlePeerFound deals with the discovery of a peer that may or may not
    29  // support the qri protocol
    30  func (n *QriNode) HandlePeerFound(pinfo peer.AddrInfo) {
    31  	log.Debugf("found peer %s", pinfo.ID)
    32  	ctx, cancel := context.WithTimeout(context.Background(), discoveryConnTimeout)
    33  	defer cancel()
    34  	n.Host().Connect(ctx, pinfo)
    35  }