-
Notifications
You must be signed in to change notification settings - Fork 376
/
discovery_monitor.go
67 lines (57 loc) · 1.56 KB
/
discovery_monitor.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
62
63
64
65
66
67
package tinder
import (
"context"
"time"
p2p_discovery "github.com/libp2p/go-libp2p-core/discovery"
p2p_event "github.com/libp2p/go-libp2p-core/event"
"github.com/libp2p/go-libp2p-core/host"
p2p_peer "github.com/libp2p/go-libp2p-core/peer"
"go.uber.org/zap"
)
// discovery monitor will send a event everytime we found/advertise a peer
type discoveryMonitor struct {
host host.Host
logger *zap.Logger
disc p2p_discovery.Discovery
emitter p2p_event.Emitter
}
// Advertise advertises a service
func (d *discoveryMonitor) Advertise(ctx context.Context, ns string, opts ...p2p_discovery.Option) (time.Duration, error) {
ttl, err := d.disc.Advertise(ctx, ns, opts...)
if err == nil {
d.Emit(&EvtDriverMonitor{
EventType: TypeEventMonitorAdvertise,
AddrInfo: p2p_peer.AddrInfo{
ID: d.host.ID(),
Addrs: d.host.Addrs(),
},
Topic: ns,
})
}
return ttl, err
}
// FindPeers discovers peers providing a service
func (d *discoveryMonitor) FindPeers(ctx context.Context, ns string, opts ...p2p_discovery.Option) (<-chan p2p_peer.AddrInfo, error) {
c, err := d.disc.FindPeers(ctx, ns, opts...)
if err != nil {
return nil, err
}
retc := make(chan p2p_peer.AddrInfo)
go func() {
for p := range c {
d.Emit(&EvtDriverMonitor{
EventType: TypeEventMonitorFoundPeer,
AddrInfo: p,
Topic: ns,
})
retc <- p
}
close(retc)
}()
return retc, err
}
func (d *discoveryMonitor) Emit(evt *EvtDriverMonitor) {
if err := d.emitter.Emit(*evt); err != nil {
d.logger.Warn("unable to emit `EvtDriverMonitor`", zap.Error(err))
}
}