github.com/koko1123/flow-go-1@v0.29.6/network/p2p/unicast/streamfactory.go (about)

     1  package unicast
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/libp2p/go-libp2p/core/host"
     7  	"github.com/libp2p/go-libp2p/core/network"
     8  	"github.com/libp2p/go-libp2p/core/peer"
     9  	"github.com/libp2p/go-libp2p/core/protocol"
    10  	"github.com/libp2p/go-libp2p/p2p/net/swarm"
    11  	"github.com/multiformats/go-multiaddr"
    12  )
    13  
    14  // StreamFactory is a wrapper around libp2p host.Host to provide abstraction and encapsulation for unicast stream manager so that
    15  // it can create libp2p streams with finer granularity.
    16  type StreamFactory interface {
    17  	SetStreamHandler(protocol.ID, network.StreamHandler)
    18  	DialAddress(peer.ID) []multiaddr.Multiaddr
    19  	ClearBackoff(peer.ID)
    20  	Connect(context.Context, peer.AddrInfo) error
    21  	NewStream(context.Context, peer.ID, ...protocol.ID) (network.Stream, error)
    22  }
    23  
    24  type LibP2PStreamFactory struct {
    25  	host host.Host
    26  }
    27  
    28  func NewLibP2PStreamFactory(h host.Host) StreamFactory {
    29  	return &LibP2PStreamFactory{host: h}
    30  }
    31  
    32  func (l *LibP2PStreamFactory) SetStreamHandler(pid protocol.ID, handler network.StreamHandler) {
    33  	l.host.SetStreamHandler(pid, handler)
    34  }
    35  
    36  func (l *LibP2PStreamFactory) DialAddress(p peer.ID) []multiaddr.Multiaddr {
    37  	return l.host.Peerstore().Addrs(p)
    38  }
    39  
    40  func (l *LibP2PStreamFactory) ClearBackoff(p peer.ID) {
    41  	if swm, ok := l.host.Network().(*swarm.Swarm); ok {
    42  		swm.Backoff().Clear(p)
    43  	}
    44  }
    45  
    46  func (l *LibP2PStreamFactory) Connect(ctx context.Context, pid peer.AddrInfo) error {
    47  	return l.host.Connect(ctx, pid)
    48  }
    49  
    50  func (l *LibP2PStreamFactory) NewStream(ctx context.Context, p peer.ID, pids ...protocol.ID) (network.Stream, error) {
    51  	return l.host.NewStream(ctx, p, pids...)
    52  }