2021-11-01 14:42:55 +00:00
|
|
|
package relay
|
2021-04-15 02:17:12 +00:00
|
|
|
|
2023-10-20 19:56:18 +00:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
|
|
|
"github.com/waku-org/go-waku/waku/v2/protocol"
|
|
|
|
"golang.org/x/exp/slices"
|
|
|
|
)
|
2021-04-15 02:17:12 +00:00
|
|
|
|
2023-07-19 16:25:35 +00:00
|
|
|
// Subscription handles the details of a particular Topic subscription. There may be many subscriptions for a given topic.
|
2021-04-15 02:17:12 +00:00
|
|
|
type Subscription struct {
|
2023-10-20 19:56:18 +00:00
|
|
|
ID int
|
|
|
|
Unsubscribe func() //for internal use only. For relay Subscription use relay protocol's unsubscribe
|
|
|
|
Ch chan *protocol.Envelope
|
|
|
|
contentFilter protocol.ContentFilter
|
|
|
|
subType SubscriptionType
|
|
|
|
noConsume bool
|
2021-04-15 02:17:12 +00:00
|
|
|
}
|
|
|
|
|
2023-10-20 19:56:18 +00:00
|
|
|
type SubscriptionType int
|
|
|
|
|
|
|
|
const (
|
|
|
|
SpecificContentTopics SubscriptionType = iota
|
|
|
|
AllContentTopics
|
|
|
|
)
|
|
|
|
|
|
|
|
// Submit allows a message to be submitted for a subscription
|
|
|
|
func (s *Subscription) Submit(ctx context.Context, msg *protocol.Envelope) {
|
|
|
|
//Filter and notify
|
|
|
|
// - if contentFilter doesn't have a contentTopic
|
|
|
|
// - if contentFilter has contentTopics and it matches with message
|
|
|
|
if !s.noConsume && (len(s.contentFilter.ContentTopicsList()) == 0 ||
|
2024-01-12 17:40:27 +00:00
|
|
|
(len(s.contentFilter.ContentTopicsList()) > 0 && slices.Contains(s.contentFilter.ContentTopicsList(), msg.Message().ContentTopic))) {
|
2023-10-20 19:56:18 +00:00
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
case s.Ch <- msg:
|
|
|
|
}
|
2023-05-05 09:49:15 +00:00
|
|
|
}
|
2021-04-15 02:17:12 +00:00
|
|
|
}
|
|
|
|
|
2023-10-20 19:56:18 +00:00
|
|
|
// NewSubscription creates a subscription that will only receive messages based on the contentFilter
|
|
|
|
func NewSubscription(contentFilter protocol.ContentFilter) *Subscription {
|
|
|
|
ch := make(chan *protocol.Envelope)
|
|
|
|
var subType SubscriptionType
|
|
|
|
if len(contentFilter.ContentTopicsList()) == 0 {
|
|
|
|
subType = AllContentTopics
|
2023-05-05 12:03:44 +00:00
|
|
|
}
|
2023-10-20 19:56:18 +00:00
|
|
|
return &Subscription{
|
|
|
|
Unsubscribe: func() {
|
|
|
|
close(ch)
|
|
|
|
},
|
|
|
|
Ch: ch,
|
|
|
|
contentFilter: contentFilter,
|
|
|
|
subType: subType,
|
2023-05-05 09:49:15 +00:00
|
|
|
}
|
2021-04-15 02:17:12 +00:00
|
|
|
}
|