go-libp2p-pubsub/subscription.go

63 lines
1.1 KiB
Go
Raw Normal View History

package pubsub
2016-10-19 23:01:06 +00:00
2016-11-17 10:27:57 +00:00
import (
"context"
"github.com/libp2p/go-libp2p-core/peer"
2016-11-17 10:27:57 +00:00
)
2016-10-19 23:01:06 +00:00
type Subscription struct {
topic string
ch chan *Message
cancelCh chan<- *Subscription
inboundSubs chan peer.ID
leavingSubs chan peer.ID
err error
2016-10-19 23:01:06 +00:00
}
func (sub *Subscription) Topic() string {
return sub.topic
}
2016-11-17 10:27:57 +00:00
func (sub *Subscription) Next(ctx context.Context) (*Message, error) {
select {
case msg, ok := <-sub.ch:
if !ok {
return msg, sub.err
}
2016-10-19 23:01:06 +00:00
2016-11-17 10:27:57 +00:00
return msg, nil
case <-ctx.Done():
return nil, ctx.Err()
2016-10-19 23:01:06 +00:00
}
}
func (sub *Subscription) Cancel() {
sub.cancelCh <- sub
}
func (sub *Subscription) NextPeerJoin(ctx context.Context) (peer.ID, error) {
select {
case newPeer, ok := <-sub.inboundSubs:
if !ok {
return newPeer, sub.err
}
return newPeer, nil
case <-ctx.Done():
return "", ctx.Err()
}
}
func (sub *Subscription) NextPeerLeave(ctx context.Context) (peer.ID, error) {
select {
case leavingPeer, ok := <-sub.leavingSubs:
if !ok {
return leavingPeer, sub.err
}
return leavingPeer, nil
case <-ctx.Done():
return "", ctx.Err()
}
}