go-libp2p-pubsub/subscription.go

60 lines
1.0 KiB
Go
Raw Normal View History

2016-10-20 01:01:06 +02:00
package floodsub
2016-11-17 11:27:57 +01:00
import (
"context"
2017-11-23 19:12:59 +01:00
"time"
2016-11-17 11:27:57 +01:00
)
2016-10-20 01:01:06 +02:00
type Subscription struct {
topic string
ch chan *Message
cancelCh chan<- *Subscription
err error
2017-11-23 19:12:59 +01:00
validate Validator
validateTimeout time.Duration
validateThrottle chan struct{}
2016-10-20 01:01:06 +02:00
}
func (sub *Subscription) Topic() string {
return sub.topic
}
2016-11-17 11:27:57 +01:00
func (sub *Subscription) Next(ctx context.Context) (*Message, error) {
select {
case msg, ok := <-sub.ch:
if !ok {
return msg, sub.err
}
2016-10-20 01:01:06 +02:00
2016-11-17 11:27:57 +01:00
return msg, nil
case <-ctx.Done():
return nil, ctx.Err()
2016-10-20 01:01:06 +02:00
}
}
func (sub *Subscription) Cancel() {
sub.cancelCh <- sub
}
func (sub *Subscription) validateMsg(ctx context.Context, msg *Message) bool {
result := make(chan bool, 1)
vctx, cancel := context.WithTimeout(ctx, sub.validateTimeout)
defer cancel()
go func() {
result <- sub.validate(vctx, msg)
}()
select {
case valid := <-result:
if !valid {
log.Debugf("validation failed for topic %s", sub.topic)
}
return valid
case <-vctx.Done():
log.Debugf("validation timeout for topic %s", sub.topic)
return false
}
}