master
go 50 lines 1.28 KB
Raw
1 package libp2p
2
3 import (
4 "context"
5 "time"
6
7 "github.com/libp2p/go-libp2p/core/host"
8 "github.com/libp2p/go-libp2p/core/peer"
9 "github.com/libp2p/go-libp2p/p2p/discovery/mdns"
10
11 "go.uber.org/fx"
12
13 "github.com/ipfs/kubo/core/node/helpers"
14 )
15
16 const discoveryConnTimeout = time.Second * 30
17
18 type discoveryHandler struct {
19 ctx context.Context
20 host host.Host
21 }
22
23 func (dh *discoveryHandler) HandlePeerFound(p peer.AddrInfo) {
24 log.Info("connecting to discovered peer: ", p)
25 ctx, cancel := context.WithTimeout(dh.ctx, discoveryConnTimeout)
26 defer cancel()
27 if err := dh.host.Connect(ctx, p); err != nil {
28 log.Warnf("failed to connect to peer %s found by discovery: %s", p.ID, err)
29 }
30 }
31
32 func DiscoveryHandler(mctx helpers.MetricsCtx, lc fx.Lifecycle, host host.Host) *discoveryHandler {
33 return &discoveryHandler{
34 ctx: helpers.LifecycleCtx(mctx, lc),
35 host: host,
36 }
37 }
38
39 func SetupDiscovery(useMdns bool) func(helpers.MetricsCtx, fx.Lifecycle, host.Host, *discoveryHandler) error {
40 return func(mctx helpers.MetricsCtx, lc fx.Lifecycle, host host.Host, handler *discoveryHandler) error {
41 if useMdns {
42 service := mdns.NewMdnsService(host, mdns.ServiceName, handler)
43 if err := service.Start(); err != nil {
44 log.Error("error starting mdns service: ", err)
45 return nil
46 }
47 }
48 return nil
49 }
50 }