go-libp2p-pubsub/floodsub.go

120 lines
2.4 KiB
Go
Raw Normal View History

package pubsub
import (
2016-09-10 16:03:53 -07:00
"context"
2019-05-26 17:19:03 +01:00
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/protocol"
)
const (
FloodSubID = protocol.ID("/floodsub/1.0.0")
FloodSubTopicSearchSize = 5
)
2019-01-04 13:09:21 +02:00
// NewFloodsubWithProtocols returns a new floodsub-enabled PubSub objecting using the protocols specified in ps.
2018-06-04 14:14:54 -07:00
func NewFloodsubWithProtocols(ctx context.Context, h host.Host, ps []protocol.ID, opts ...Option) (*PubSub, error) {
rt := &FloodSubRouter{
protocols: ps,
}
return NewPubSub(ctx, h, rt, opts...)
}
2019-01-04 13:09:21 +02:00
// NewFloodSub returns a new PubSub object using the FloodSubRouter.
func NewFloodSub(ctx context.Context, h host.Host, opts ...Option) (*PubSub, error) {
2018-06-04 14:14:54 -07:00
return NewFloodsubWithProtocols(ctx, h, []protocol.ID{FloodSubID}, opts...)
}
2016-09-09 20:13:50 -07:00
type FloodSubRouter struct {
p *PubSub
protocols []protocol.ID
2019-11-04 20:43:48 +02:00
tracer *pubsubTracer
2016-10-20 01:01:06 +02:00
}
func (fs *FloodSubRouter) Protocols() []protocol.ID {
return fs.protocols
2016-09-09 20:13:50 -07:00
}
func (fs *FloodSubRouter) Attach(p *PubSub) {
fs.p = p
fs.tracer = p.tracer
}
2019-11-04 20:43:48 +02:00
func (fs *FloodSubRouter) AddPeer(p peer.ID, proto protocol.ID) {
fs.tracer.AddPeer(p, proto)
}
2019-11-04 20:43:48 +02:00
func (fs *FloodSubRouter) RemovePeer(p peer.ID) {
fs.tracer.RemovePeer(p)
}
func (fs *FloodSubRouter) EnoughPeers(topic string, suggested int) bool {
// check all peers in the topic
tmap, ok := fs.p.topics[topic]
if !ok {
return false
}
if suggested == 0 {
suggested = FloodSubTopicSearchSize
}
if len(tmap) >= suggested {
return true
}
return false
}
func (fs *FloodSubRouter) AcceptFrom(peer.ID) bool {
return true
}
2018-01-27 09:52:35 +02:00
func (fs *FloodSubRouter) HandleRPC(rpc *RPC) {}
func (fs *FloodSubRouter) Publish(msg *Message) {
from := msg.ReceivedFrom
tosend := make(map[peer.ID]struct{})
for _, topic := range msg.GetTopicIDs() {
tmap, ok := fs.p.topics[topic]
if !ok {
continue
}
2016-09-10 20:47:12 -07:00
2017-11-23 14:39:14 +01:00
for p := range tmap {
tosend[p] = struct{}{}
}
}
out := rpcWithMessages(msg.Message)
for pid := range tosend {
2016-09-10 20:47:12 -07:00
if pid == from || pid == peer.ID(msg.GetFrom()) {
continue
}
mch, ok := fs.p.peers[pid]
if !ok {
continue
}
select {
case mch <- out:
2019-11-04 20:43:48 +02:00
fs.tracer.SendRPC(out, pid)
default:
2017-08-29 19:42:33 -07:00
log.Infof("dropping message to peer %s: queue full", pid)
2019-11-04 20:43:48 +02:00
fs.tracer.DropRPC(out, pid)
// Drop it. The peer is too slow.
}
}
}
2019-11-04 20:43:48 +02:00
func (fs *FloodSubRouter) Join(topic string) {
fs.tracer.Join(topic)
}
2019-11-04 20:43:48 +02:00
func (fs *FloodSubRouter) Leave(topic string) {
fs.tracer.Join(topic)
}