-
Notifications
You must be signed in to change notification settings - Fork 0
/
discovery_channel.go
95 lines (83 loc) · 2.25 KB
/
discovery_channel.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package p2p
import (
"context"
"fmt"
"time"
"google.golang.org/protobuf/proto"
"github.com/apex/log"
"github.com/plan-systems/plan-vault-libp2p/helpers"
"github.com/plan-systems/plan-vault-libp2p/keyring"
pb "github.com/plan-systems/plan-vault-libp2p/protos"
"github.com/plan-systems/plan-vault-libp2p/store"
)
func NewChannelDiscovery(pctx context.Context, h *Host, cfg *Config) (*TopicHandler, error) {
channelID := helpers.ChannelURItoChannelID(cfg.URI)
channel, err := h.store.Channel(channelID)
if err != nil {
return nil, err
}
th, err := NewTopicHandler(h, channel, []byte{},
func(entry *pb.Msg) error {
return handleDiscoveryEntry(h, channel, entry)
},
func(entry *pb.Msg) error {
return handleDiscoveryEntry(h, channel, entry)
},
)
if err != nil {
return nil, err
}
th.logger = h.log.WithFields(log.Fields{"service": "discovery"})
go th.watchTopic()
return th, nil
}
func handleDiscoveryEntry(h *Host, channel *store.Channel, entry *pb.Msg) error {
body, err := h.keyring.DecodeEntry(entry)
if err != nil {
return err
}
update := &pb.Peer{}
err = proto.Unmarshal(body, update)
if err != nil {
return err
}
switch update.GetOp() {
case pb.PeerUpdateOp_Upsert:
err := handleDiscoveryUpsert(h, update)
if err != nil {
return err
}
case pb.PeerUpdateOp_RemovePermanently:
_, err := decodePeerAddr(update)
if err != nil {
return err
}
// TODO: remove this from the p2p host
default:
return fmt.Errorf("unsupported operation")
}
return nil
}
func handleDiscoveryUpsert(h *Host, update *pb.Peer) error {
addrInfo, err := decodePeerAddr(update)
if err != nil {
return err
}
// Connect ensures there is a connection between this host and
// the peer, and store the AddrInfo into our internal peerstore.
//
// TODO: Connect issues a h.Network.Dial and blocks untl a
// connection is open or an error is returned; we should
// probably not block here?
ctx, cancel := context.WithTimeout(h.ctx, 10*time.Second)
defer cancel()
err = h.Connect(ctx, addrInfo)
if err != nil {
return err
}
// save the public key in the keyring for verifying entries
h.keyring.AddMemberKey(h.discoveryURI,
keyring.MemberIDFromString(string(addrInfo.ID)),
keyring.MemberPublicKeyFromBytes(update.Key))
return nil
}