-
Notifications
You must be signed in to change notification settings - Fork 0
/
comm.go
102 lines (87 loc) · 1.85 KB
/
comm.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
96
97
98
99
100
101
102
package floodsub
import (
"bufio"
"context"
"io"
pb "github.com/libp2p/go-floodsub/pb"
ggio "github.com/gogo/protobuf/io"
proto "github.com/gogo/protobuf/proto"
inet "github.com/libp2p/go-libp2p-net"
)
// get the initial RPC containing all of our subscriptions to send to new peers
func (p *PubSub) getHelloPacket() *RPC {
var rpc RPC
for t := range p.myTopics {
as := &pb.RPC_SubOpts{
Topicid: proto.String(t),
Subscribe: proto.Bool(true),
}
rpc.Subscriptions = append(rpc.Subscriptions, as)
}
return &rpc
}
func (p *PubSub) handleNewStream(s inet.Stream) {
defer s.Close()
r := ggio.NewDelimitedReader(s, 1<<20)
for {
rpc := new(RPC)
err := r.ReadMsg(&rpc.RPC)
if err != nil {
if err != io.EOF {
log.Errorf("error reading rpc from %s: %s", s.Conn().RemotePeer(), err)
}
return
}
rpc.from = s.Conn().RemotePeer()
select {
case p.incoming <- rpc:
case <-p.ctx.Done():
return
}
}
}
func (p *PubSub) handleSendingMessages(ctx context.Context, s inet.Stream, outgoing <-chan *RPC) {
var dead bool
bufw := bufio.NewWriter(s)
wc := ggio.NewDelimitedWriter(bufw)
writeMsg := func(msg proto.Message) error {
err := wc.WriteMsg(msg)
if err != nil {
return err
}
return bufw.Flush()
}
defer wc.Close()
for {
select {
case rpc, ok := <-outgoing:
if !ok {
return
}
if dead {
// continue in order to drain messages
continue
}
err := writeMsg(&rpc.RPC)
if err != nil {
log.Warningf("writing message to %s: %s", s.Conn().RemotePeer(), err)
dead = true
go func() {
p.peerDead <- s.Conn().RemotePeer()
}()
}
case <-ctx.Done():
return
}
}
}
func rpcWithSubs(subs ...*pb.RPC_SubOpts) *RPC {
return &RPC{
RPC: pb.RPC{
Subscriptions: subs,
},
}
}
func rpcWithMessages(msgs ...*pb.Message) *RPC {
return &RPC{RPC: pb.RPC{Publish: msgs}}
}