2018-08-28 03:01:08 +00:00
|
|
|
package pubsub
|
2016-10-19 23:01:06 +00:00
|
|
|
|
2016-11-17 10:27:57 +00:00
|
|
|
import (
|
|
|
|
"context"
|
2019-06-12 14:06:16 +00:00
|
|
|
)
|
|
|
|
|
2019-10-31 18:26:25 +00:00
|
|
|
// Subscription handles the details of a particular Topic subscription.
|
|
|
|
// There may be many subscriptions for a given Topic.
|
2016-10-19 23:01:06 +00:00
|
|
|
type Subscription struct {
|
2019-06-12 14:06:16 +00:00
|
|
|
topic string
|
|
|
|
ch chan *Message
|
|
|
|
cancelCh chan<- *Subscription
|
2019-09-30 09:55:37 +00:00
|
|
|
ctx context.Context
|
2019-10-31 18:26:25 +00:00
|
|
|
err error
|
2016-10-19 23:01:06 +00:00
|
|
|
}
|
|
|
|
|
2019-10-31 18:26:25 +00:00
|
|
|
// Topic returns the topic string associated with the Subscription
|
2016-10-19 23:01:06 +00:00
|
|
|
func (sub *Subscription) Topic() string {
|
|
|
|
return sub.topic
|
|
|
|
}
|
|
|
|
|
2019-06-12 14:06:16 +00:00
|
|
|
// Next returns the next message in our subscription
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-10-31 18:26:25 +00:00
|
|
|
// Cancel closes the subscription. If this is the last active subscription then pubsub will send an unsubscribe
|
|
|
|
// announcement to the network.
|
2016-10-19 23:01:06 +00:00
|
|
|
func (sub *Subscription) Cancel() {
|
2019-09-30 09:55:37 +00:00
|
|
|
select {
|
|
|
|
case sub.cancelCh <- sub:
|
|
|
|
case <-sub.ctx.Done():
|
|
|
|
}
|
2016-10-19 23:01:06 +00:00
|
|
|
}
|
2019-06-07 12:31:14 +00:00
|
|
|
|
2019-07-01 15:43:49 +00:00
|
|
|
func (sub *Subscription) close() {
|
2019-06-21 06:46:41 +00:00
|
|
|
close(sub.ch)
|
|
|
|
}
|