discovery.go 1.41 KB
Newer Older
tavit ohanian's avatar
tavit ohanian committed
1
package dms3p2p
Łukasz Magiera's avatar
Łukasz Magiera committed
2 3 4 5 6

import (
	"context"
	"time"

tavit ohanian's avatar
tavit ohanian committed
7 8 9
	"gitlab.dms3.io/p2p/go-p2p-core/host"
	"gitlab.dms3.io/p2p/go-p2p-core/peer"
	"gitlab.dms3.io/p2p/go-p2p/p2p/discovery"
Łukasz Magiera's avatar
Łukasz Magiera committed
10
	"go.uber.org/fx"
11

tavit ohanian's avatar
tavit ohanian committed
12
	"gitlab.dms3.io/dms3/go-dms3/core/node/helpers"
Łukasz Magiera's avatar
Łukasz Magiera committed
13 14 15 16 17 18 19 20 21
)

const discoveryConnTimeout = time.Second * 30

type discoveryHandler struct {
	ctx  context.Context
	host host.Host
}

Raúl Kripalani's avatar
Raúl Kripalani committed
22
func (dh *discoveryHandler) HandlePeerFound(p peer.AddrInfo) {
23
	log.Info("connecting to discovered peer: ", p)
Łukasz Magiera's avatar
Łukasz Magiera committed
24 25 26
	ctx, cancel := context.WithTimeout(dh.ctx, discoveryConnTimeout)
	defer cancel()
	if err := dh.host.Connect(ctx, p); err != nil {
27
		log.Warnf("failed to connect to peer %s found by discovery: %s", p.ID, err)
Łukasz Magiera's avatar
Łukasz Magiera committed
28 29 30
	}
}

31
func DiscoveryHandler(mctx helpers.MetricsCtx, lc fx.Lifecycle, host host.Host) *discoveryHandler {
Łukasz Magiera's avatar
Łukasz Magiera committed
32
	return &discoveryHandler{
33
		ctx:  helpers.LifecycleCtx(mctx, lc),
Łukasz Magiera's avatar
Łukasz Magiera committed
34 35 36 37
		host: host,
	}
}

38 39 40 41 42 43 44 45 46 47 48 49
func SetupDiscovery(mdns 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 mdns {
			if mdnsInterval == 0 {
				mdnsInterval = 5
			}
			service, err := discovery.NewMdnsService(helpers.LifecycleCtx(mctx, lc), host, time.Duration(mdnsInterval)*time.Second, discovery.ServiceTag)
			if err != nil {
				log.Error("mdns error: ", err)
				return nil
			}
			service.RegisterNotifee(handler)
Łukasz Magiera's avatar
Łukasz Magiera committed
50
		}
51
		return nil
Łukasz Magiera's avatar
Łukasz Magiera committed
52 53
	}
}