-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpubsub.go
308 lines (263 loc) · 6.79 KB
/
pubsub.go
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package redplex
import (
"bufio"
"bytes"
"net"
"sync"
"time"
"github.com/cenkalti/backoff"
"github.com/sirupsen/logrus"
)
// Writable is an interface passed into Pubsub. It's called when we want to
// publish data.
type Writable interface {
Write(b []byte)
}
// The Listener wraps a function that's called when a pubsub message it sent.
type Listener struct {
IsPattern bool
Channel string
Conn Writable
}
// listenerMap is a map of patterns or channels to Listeners.
type listenerMap map[string][]Writable
// broadcast pushes the byte slice asynchronously to the list of listeners.
// Blocks until all listeners have been called.
func (l listenerMap) broadcast(pattern []byte, b []byte) {
listeners := l[string(pattern)]
count := float64(len(listeners))
throughputMessages.Add(count)
throughputBytes.Add(count * float64(len(b)))
var wg sync.WaitGroup
wg.Add(len(listeners))
for _, l := range listeners {
go func(l Writable) { l.Write(b); wg.Done() }(l)
}
wg.Wait()
}
// add inserts the listener into the pattern's set of listeners.
func (l listenerMap) add(channel string, listener Writable) (shouldSubscribe bool) {
list := l[channel]
shouldSubscribe = len(list) == 0
l[channel] = append(list, listener)
return shouldSubscribe
}
// remove pulls the listener out of the map.
func (l listenerMap) remove(channel string, listener Writable) (shouldUnsubscribe bool) {
list := l[channel]
changed := false
for i, other := range list {
if other == listener {
changed = true
list[i] = list[len(list)-1]
list[len(list)-1] = nil
list = list[:len(list)-1]
break
}
}
if !changed {
return false
}
if len(list) == 0 {
delete(l, channel)
return true
}
l[channel] = list
return false
}
// removeAll removes all channels the listener is connected to.
func (l listenerMap) removeAll(conn Writable) (toUnsub [][]byte) {
for channel, list := range l {
for i := 0; i < len(list); i++ {
if list[i] == conn {
list[i] = list[len(list)-1]
list[len(list)-1] = nil
list = list[:len(list)-1]
i--
continue
}
}
if len(list) == 0 {
delete(l, channel)
toUnsub = append(toUnsub, []byte(channel))
} else {
l[channel] = list
}
}
return toUnsub
}
// Pubsub manages the connection of redplex to the remote pubsub server.
type Pubsub struct {
dialer Dialer
closer chan struct{}
writeTimeout time.Duration
mu sync.Mutex
connection net.Conn
patterns listenerMap
channels listenerMap
}
// NewPubsub creates a new Pubsub instance.
func NewPubsub(dialer Dialer, writeTimeout time.Duration) *Pubsub {
return &Pubsub{
dialer: dialer,
writeTimeout: writeTimeout,
patterns: listenerMap{},
channels: listenerMap{},
closer: make(chan struct{}),
}
}
// Start creates a pubsub listener to proxy connection data.
func (p *Pubsub) Start() {
backoff := backoff.NewExponentialBackOff()
backoff.MaxInterval = time.Second * 10
for {
cnx, err := p.dialer.Dial()
if err != nil {
logrus.WithError(err).Info("redplex/pubsub: error dialing to pubsub master")
select {
case <-time.After(backoff.NextBackOff()):
serverReconnects.Inc()
continue
case <-p.closer:
return
}
}
backoff.Reset()
err = p.read(cnx)
select {
case <-p.closer:
return
default:
logrus.WithError(err).Info("redplex/pubsub: lost connection to pubsub server")
}
}
}
// Close frees resources associated with the pubsub server.
func (p *Pubsub) Close() {
close(p.closer)
p.mu.Lock()
if p.connection != nil {
p.connection.Close()
}
p.mu.Unlock()
}
// Subscribe adds the listener to the channel.
func (p *Pubsub) Subscribe(listener Listener) {
p.mu.Lock()
if listener.IsPattern {
if p.patterns.add(listener.Channel, listener.Conn) {
p.command(NewRequest(commandPSubscribe, 1).Bulk([]byte(listener.Channel)))
}
} else {
if p.channels.add(listener.Channel, listener.Conn) {
p.command(NewRequest(commandSubscribe, 1).Bulk([]byte(listener.Channel)))
}
}
p.mu.Unlock()
}
// Unsubscribe removes the listener from the channel.
func (p *Pubsub) Unsubscribe(listener Listener) {
p.mu.Lock()
if listener.IsPattern {
if p.patterns.remove(listener.Channel, listener.Conn) {
p.command(NewRequest(commandPUnsubscribe, 1).Bulk([]byte(listener.Channel)))
}
} else {
if p.channels.remove(listener.Channel, listener.Conn) {
p.command(NewRequest(commandUnsubscribe, 1).Bulk([]byte(listener.Channel)))
}
}
p.mu.Unlock()
}
// UnsubscribeAll removes all channels the writer is subscribed to.
func (p *Pubsub) UnsubscribeAll(c Writable) {
p.mu.Lock()
var (
toUnsub = p.patterns.removeAll(c)
command []byte
)
if len(toUnsub) > 0 {
r := NewRequest(commandPUnsubscribe, len(toUnsub))
for _, p := range toUnsub {
r.Bulk(p)
}
command = append(command, r.Bytes()...)
}
toUnsub = p.channels.removeAll(c)
if len(toUnsub) > 0 {
r := NewRequest(commandUnsubscribe, len(toUnsub))
for _, p := range toUnsub {
r.Bulk(p)
}
command = append(command, r.Bytes()...)
}
if p.connection != nil && len(command) > 0 {
p.connection.SetWriteDeadline(time.Now().Add(p.writeTimeout))
go p.connection.Write(command)
}
p.mu.Unlock()
}
// command sends the request to the pubsub server asynchronously.
func (p *Pubsub) command(r *Request) {
if p.connection != nil {
p.connection.SetWriteDeadline(time.Now().Add(p.writeTimeout))
go p.connection.Write(r.Bytes())
}
}
// command sends the request to the pubsub server and blocks until it sends.
func (p *Pubsub) commandSync(r *Request) {
if p.connection != nil {
p.connection.SetWriteDeadline(time.Now().Add(p.writeTimeout))
p.connection.Write(r.Bytes())
}
}
func (p *Pubsub) resubscribe(cnx net.Conn) {
p.mu.Lock()
p.connection = cnx
if len(p.channels) > 0 {
cmd := NewRequest(commandSubscribe, len(p.channels))
for channel := range p.channels {
cmd.Bulk([]byte(channel))
}
p.commandSync(cmd)
}
if len(p.patterns) > 0 {
cmd := NewRequest(commandPSubscribe, len(p.patterns))
for pattern := range p.patterns {
cmd.Bulk([]byte(pattern))
}
p.commandSync(cmd)
}
p.mu.Unlock()
}
// read grabs commands from the connection, reading them until the
// connection terminates.
func (p *Pubsub) read(cnx net.Conn) error {
var (
reader = bufio.NewReader(cnx)
buffer = bytes.NewBuffer(nil)
)
p.resubscribe(cnx)
// The only thing that
for {
buffer.Reset()
if err := ReadNextFull(buffer, reader); err != nil {
p.mu.Lock()
p.connection = nil
p.mu.Unlock()
return err
}
bytes := copyBytes(buffer.Bytes())
parsed, err := ParsePublishCommand(bytes)
if err != nil {
continue // expected, we can get replies from subscriptions, which we'll ignore
}
p.mu.Lock()
if parsed.IsPattern {
p.patterns.broadcast(parsed.ChannelOrPattern, bytes)
} else {
p.channels.broadcast(parsed.ChannelOrPattern, bytes)
}
p.mu.Unlock()
}
}