-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathdiscovery.go
61 lines (51 loc) · 1.66 KB
/
discovery.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package libp2p
import (
"context"
"time"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p/p2p/discovery/mdns"
legacymdns "github.com/libp2p/go-libp2p/p2p/discovery/mdns_legacy"
"go.uber.org/fx"
"github.com/ipfs/go-ipfs/core/node/helpers"
)
const discoveryConnTimeout = time.Second * 30
type discoveryHandler struct {
ctx context.Context
host host.Host
}
func (dh *discoveryHandler) HandlePeerFound(p peer.AddrInfo) {
log.Info("connecting to discovered peer: ", p)
ctx, cancel := context.WithTimeout(dh.ctx, discoveryConnTimeout)
defer cancel()
if err := dh.host.Connect(ctx, p); err != nil {
log.Warnf("failed to connect to peer %s found by discovery: %s", p.ID, err)
}
}
func DiscoveryHandler(mctx helpers.MetricsCtx, lc fx.Lifecycle, host host.Host) *discoveryHandler {
return &discoveryHandler{
ctx: helpers.LifecycleCtx(mctx, lc),
host: host,
}
}
func SetupDiscovery(useMdns bool, mdnsInterval int) func(helpers.MetricsCtx, fx.Lifecycle, host.Host, *discoveryHandler) error {
return func(mctx helpers.MetricsCtx, lc fx.Lifecycle, host host.Host, handler *discoveryHandler) error {
if useMdns {
service := mdns.NewMdnsService(host, mdns.ServiceName, handler)
if err := service.Start(); err != nil {
log.Error("error starting mdns service: ", err)
return nil
}
if mdnsInterval == 0 {
mdnsInterval = 5
}
legacyService, err := legacymdns.NewMdnsService(mctx, host, time.Duration(mdnsInterval)*time.Second, legacymdns.ServiceTag)
if err != nil {
log.Error("mdns error: ", err)
return nil
}
legacyService.RegisterNotifee(handler)
}
return nil
}
}