summaryrefslogtreecommitdiff
path: root/plugins/memory/pubsub.go
blob: 75cd9d2457e9ac57df789a03d7280ee1eef3d755 (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
87
88
89
90
91
92
93
94
95
package memory

import (
	"sync"

	"github.com/spiral/roadrunner/v2/pkg/bst"
	websocketsv1 "github.com/spiral/roadrunner/v2/pkg/proto/websockets/v1beta"
	"github.com/spiral/roadrunner/v2/pkg/pubsub"
	"github.com/spiral/roadrunner/v2/plugins/logger"
	"google.golang.org/protobuf/proto"
)

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

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

func (p *PubSubDriver) Publish(message []byte) error {
	p.pushCh <- message
	return nil
}

func (p *PubSubDriver) PublishAsync(message []byte) {
	go func() {
		p.pushCh <- message
	}()
}

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() (*websocketsv1.Message, error) {
	msg := <-p.pushCh
	if msg == nil {
		return nil, nil
	}

	p.RLock()
	defer p.RUnlock()

	m := &websocketsv1.Message{}
	err := proto.Unmarshal(msg, m)
	if err != nil {
		return nil, err
	}

	// push only messages, which are subscribed
	// TODO better???
	for i := 0; i < len(m.GetTopics()); i++ {
		// if we have active subscribers - send a message to a topic
		// or send nil instead
		if ok := p.storage.Contains(m.GetTopics()[i]); ok {
			return m, nil
		}
	}
	return nil, nil
}