summaryrefslogtreecommitdiff
path: root/plugins/memory/pubsub.go
blob: d027a8a5fbcf60b5e16d627721c4a7f5d0d9fe09 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package memory

import (
	"sync"

	"github.com/spiral/roadrunner/v2/pkg/bst"
	"github.com/spiral/roadrunner/v2/pkg/pubsub"
	"github.com/spiral/roadrunner/v2/plugins/logger"
)

type PubSubDriver struct {
	sync.RWMutex
	// channel with the messages from the RPC
	pushCh chan *pubsub.Message
	// user-subscribed topics
	storage bst.Storage
	log     logger.Logger
}

func NewPubSubDriver(log logger.Logger, _ string) (pubsub.PubSub, error) {
	ps := &PubSubDriver{
		pushCh:  make(chan *pubsub.Message, 10),
		storage: bst.NewBST(),
		log:     log,
	}
	return ps, nil
}

func (p *PubSubDriver) Publish(msg *pubsub.Message) error {
	p.pushCh <- msg
	return nil
}

func (p *PubSubDriver) PublishAsync(msg *pubsub.Message) {
	go func() {
		p.pushCh <- msg
	}()
}

func (p *PubSubDriver) Subscribe(connectionID string, topics ...string) error {
	p.Lock()
	defer p.Unlock()
	for i := 0; i < len(topics); i++ {
		p.storage.Insert(connectionID, topics[i])
	}
	return nil
}

func (p *PubSubDriver) Unsubscribe(connectionID string, topics ...string) error {
	p.Lock()
	defer p.Unlock()
	for i := 0; i < len(topics); i++ {
		p.storage.Remove(connectionID, topics[i])
	}
	return nil
}

func (p *PubSubDriver) Connections(topic string, res map[string]struct{}) {
	p.RLock()
	defer p.RUnlock()

	ret := p.storage.Get(topic)
	for rr := range ret {
		res[rr] = struct{}{}
	}
}

func (p *PubSubDriver) Next() (*pubsub.Message, error) {
	msg := <-p.pushCh
	if msg == nil {
		return nil, nil
	}

	p.RLock()
	defer p.RUnlock()

	// push only messages, which topics are subscibed
	// TODO better???
	// if we have active subscribers - send a message to a topic
	// or send nil instead
	if ok := p.storage.Contains(msg.Topic); ok {
		return msg, nil
	}

	return nil, nil
}