-
Notifications
You must be signed in to change notification settings - Fork 113
/
pubsub_test.go
405 lines (346 loc) · 8.54 KB
/
pubsub_test.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package radix
import (
"log"
"math/rand"
"strconv"
"sync"
. "testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func publish(t *T, c Conn, ch, msg string) {
require.Nil(t, c.Do(Cmd(nil, "PUBLISH", ch, msg)))
}
func assertMsgRead(_ *T, msgCh <-chan PubSubMessage) PubSubMessage {
select {
case m := <-msgCh:
return m
case <-time.After(5 * time.Second):
panic("timedout reading")
}
}
func assertMsgNoRead(t *T, msgCh <-chan PubSubMessage) {
select {
case msg, ok := <-msgCh:
if !ok {
assert.Fail(t, "msgCh closed")
} else {
assert.Fail(t, "unexpected PubSubMessage off msgCh", "msg:%#v", msg)
}
default:
}
}
func testSubscribe(t *T, c PubSubConn, pubCh chan int) {
pubC := dial()
msgCh := make(chan PubSubMessage, 1)
ch1, ch2, msgStr := randStr(), randStr(), randStr()
require.Nil(t, c.Subscribe(msgCh, ch1, ch2))
pubChs := make([]chan int, 3)
{
for i := range pubChs {
pubChs[i] = make(chan int)
}
go func() {
for i := range pubCh {
for _, innerPubCh := range pubChs {
innerPubCh <- i
}
}
for _, innerPubCh := range pubChs {
close(innerPubCh)
}
}()
}
wg := new(sync.WaitGroup)
wg.Add(1)
go func() {
for i := range pubChs[0] {
publish(t, pubC, ch1, msgStr+"_"+strconv.Itoa(i))
}
wg.Done()
}()
wg.Add(1)
go func() {
for i := range pubChs[1] {
msg := assertMsgRead(t, msgCh)
assert.Equal(t, PubSubMessage{
Type: "message",
Channel: ch1,
Message: []byte(msgStr + "_" + strconv.Itoa(i)),
}, msg)
}
wg.Done()
}()
wg.Add(1)
go func() {
for range pubChs[2] {
require.Nil(t, c.Ping())
}
wg.Done()
}()
wg.Wait()
require.Nil(t, c.Unsubscribe(msgCh, ch1))
publish(t, pubC, ch1, msgStr)
publish(t, pubC, ch2, msgStr)
msg := assertMsgRead(t, msgCh)
assert.Equal(t, PubSubMessage{
Type: "message",
Channel: ch2,
Message: []byte(msgStr),
}, msg)
}
func TestPubSubSubscribe(t *T) {
pubCh := make(chan int)
go func() {
for i := 0; i < 1000; i++ {
pubCh <- i
}
close(pubCh)
}()
c := PubSub(dial())
testSubscribe(t, c, pubCh)
c.Close()
assert.NotNil(t, c.Ping())
assert.NotNil(t, c.Ping())
assert.NotNil(t, c.Ping())
}
func TestPubSubPSubscribe(t *T) {
pubC := dial()
c := PubSub(dial())
msgCh := make(chan PubSubMessage, 1)
p1, p2, msgStr := randStr()+"_*", randStr()+"_*", randStr()
ch1, ch2 := p1+"_"+randStr(), p2+"_"+randStr()
p3, p4 := randStr()+"_?", randStr()+"_[ae]"
ch3, ch4 := p3[:len(p3)-len("?")]+"a", p4[:len(p4)-len("[ae]")]+"a"
require.Nil(t, c.PSubscribe(msgCh, p1, p2, p3, p4))
count := 1000
wg := new(sync.WaitGroup)
wg.Add(1)
go func() {
for i := 0; i < count; i++ {
publish(t, pubC, ch1, msgStr)
}
wg.Done()
}()
wg.Add(1)
go func() {
for i := 0; i < count; i++ {
msg := assertMsgRead(t, msgCh)
assert.Equal(t, PubSubMessage{
Type: "pmessage",
Pattern: p1,
Channel: ch1,
Message: []byte(msgStr),
}, msg)
}
wg.Done()
}()
wg.Add(1)
go func() {
for i := 0; i < count; i++ {
require.Nil(t, c.Ping())
}
wg.Done()
}()
wg.Wait()
require.Nil(t, c.PUnsubscribe(msgCh, p1))
publish(t, pubC, ch1, msgStr)
publish(t, pubC, ch2, msgStr)
msg := assertMsgRead(t, msgCh)
assert.Equal(t, PubSubMessage{
Type: "pmessage",
Pattern: p2,
Channel: ch2,
Message: []byte(msgStr),
}, msg)
publish(t, pubC, ch3, msgStr)
msg = assertMsgRead(t, msgCh)
assert.Equal(t, PubSubMessage{
Type: "pmessage",
Pattern: p3,
Channel: ch3,
Message: []byte(msgStr),
}, msg)
publish(t, pubC, ch4, msgStr)
msg = assertMsgRead(t, msgCh)
assert.Equal(t, PubSubMessage{
Type: "pmessage",
Pattern: p4,
Channel: ch4,
Message: []byte(msgStr),
}, msg)
c.Close()
assert.NotNil(t, c.Ping())
assert.NotNil(t, c.Ping())
assert.NotNil(t, c.Ping())
publish(t, pubC, ch2, msgStr)
time.Sleep(250 * time.Millisecond)
assertMsgNoRead(t, msgCh)
}
func TestPubSubMixedSubscribe(t *T) {
pubC := dial()
defer pubC.Close()
c := PubSub(dial())
defer c.Close()
msgCh := make(chan PubSubMessage, 2)
const msgStr = "bar"
require.Nil(t, c.Subscribe(msgCh, "foo"))
require.Nil(t, c.PSubscribe(msgCh, "f[aeiou]o"))
publish(t, pubC, "foo", msgStr)
msg1, msg2 := assertMsgRead(t, msgCh), assertMsgRead(t, msgCh)
// If we received the pmessage first we must swap msg1 and msg1.
if msg1.Type == "pmessage" {
msg1, msg2 = msg2, msg1
}
assert.Equal(t, PubSubMessage{
Type: "message",
Channel: "foo",
Message: []byte(msgStr),
}, msg1)
assert.Equal(t, PubSubMessage{
Type: "pmessage",
Channel: "foo",
Pattern: "f[aeiou]o",
Message: []byte(msgStr),
}, msg2)
}
// Ensure that PubSubConn properly handles the case where the Conn it's reading
// from returns a timeout error.
func TestPubSubTimeout(t *T) {
c, pubC := PubSub(dial(DialReadTimeout(1*time.Second))), dial()
c.(*pubSubConn).testEventCh = make(chan string, 1)
ch, msgCh := randStr(), make(chan PubSubMessage, 1)
require.Nil(t, c.Subscribe(msgCh, ch))
msgStr := randStr()
go func() {
time.Sleep(2 * time.Second)
assert.Nil(t, pubC.Do(Cmd(nil, "PUBLISH", ch, msgStr)))
}()
assert.Equal(t, "timeout", <-c.(*pubSubConn).testEventCh)
msg := assertMsgRead(t, msgCh)
assert.Equal(t, msgStr, string(msg.Message))
}
// This attempts to catch weird race conditions which might occur due to
// subscribing/unsubscribing quickly on an active channel.
func TestPubSubChaotic(t *T) {
c, pubC := PubSub(dial()), dial()
ch, msgStr := randStr(), randStr()
stopCh := make(chan struct{})
defer close(stopCh)
go func() {
for {
select {
case <-stopCh:
return
default:
publish(t, pubC, ch, msgStr)
time.Sleep(10 * time.Millisecond)
}
}
}()
msgCh := make(chan PubSubMessage, 100)
require.Nil(t, c.Subscribe(msgCh, ch))
stopAfter := time.After(10 * time.Second)
toggleTimer := time.Tick(250 * time.Millisecond)
subbed := true
for {
waitFor := time.NewTimer(100 * time.Millisecond)
select {
case <-stopAfter:
return
case <-waitFor.C:
if subbed {
t.Fatal("waited too long to receive message")
}
case msg := <-msgCh:
waitFor.Stop()
assert.Equal(t, msgStr, string(msg.Message))
case <-toggleTimer:
waitFor.Stop()
if subbed {
require.Nil(t, c.Unsubscribe(msgCh, ch))
} else {
require.Nil(t, c.Subscribe(msgCh, ch))
}
subbed = !subbed
}
}
}
func BenchmarkPubSub(b *B) {
c, pubC := PubSub(dial()), dial()
defer c.Close()
defer pubC.Close()
msg := randStr()
msgCh := make(chan PubSubMessage, 1)
require.Nil(b, c.Subscribe(msgCh, "benchmark"))
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := pubC.Do(Cmd(nil, "PUBLISH", "benchmark", msg)); err != nil {
b.Fatal(err)
}
<-msgCh
}
}
func ExamplePubSub() {
// Create a normal redis connection
conn, err := Dial("tcp", "127.0.0.1:6379")
if err != nil {
panic(err)
}
// Pass that connection into PubSub, conn should never get used after this
ps := PubSub(conn)
defer ps.Close() // this will close Conn as well
// Subscribe to a channel called "myChannel". All publishes to "myChannel"
// will get sent to msgCh after this
msgCh := make(chan PubSubMessage)
if err := ps.Subscribe(msgCh, "myChannel"); err != nil {
panic(err)
}
// It's optional, but generally advisable, to periodically Ping the
// connection to ensure it's still alive. This should be done in a separate
// go-routine from that which is reading from msgCh.
errCh := make(chan error, 1)
go func() {
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
for range ticker.C {
if err := ps.Ping(); err != nil {
errCh <- err
return
}
}
}()
for {
select {
case msg := <-msgCh:
log.Printf("publish to channel %q received: %q", msg.Channel, msg.Message)
case err := <-errCh:
panic(err)
}
}
}
func ExamplePersistentPubSub_cluster() {
// Example of how to use PersistentPubSub with a Cluster instance.
// Initialize the cluster in any way you see fit
cluster, err := NewCluster([]string{"127.0.0.1:6379"})
if err != nil {
// handle error
}
// Have PersistentPubSub pick a random cluster node everytime it wants to
// make a new connection. If the node fails PersistentPubSub will
// automatically pick a new node to connect to.
ps := PersistentPubSub("", "", func(string, string) (Conn, error) {
topo := cluster.Topo()
node := topo[rand.Intn(len(topo))]
return Dial("tcp", node.Addr)
})
// Use the PubSubConn as normal.
msgCh := make(chan PubSubMessage)
if err = ps.Subscribe(msgCh, "myChannel"); err != nil {
// handle error
}
for msg := range msgCh {
log.Printf("publish to channel %q received: %q", msg.Channel, msg.Message)
}
}