forked from nats-io/nats.go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreconnect_test.go
465 lines (386 loc) · 10.7 KB
/
reconnect_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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
package nats
import (
"sync"
"sync/atomic"
"testing"
"time"
)
func startReconnectServer(t *testing.T) *server {
return startServer(t, 22222, "")
}
func TestReconnectTotalTime(t *testing.T) {
opts := DefaultOptions
totalReconnectTime := time.Duration(opts.MaxReconnect) * opts.ReconnectWait
if totalReconnectTime < (2 * time.Minute) {
t.Fatalf("Total reconnect time should be at least 2 mins: Currently %v\n",
totalReconnectTime)
}
}
func TestReconnectDisallowedFlags(t *testing.T) {
ts := startReconnectServer(t)
ch := make(chan bool)
opts := DefaultOptions
opts.Url = "nats://localhost:22222"
opts.AllowReconnect = false
opts.ClosedCB = func(_ *Conn) {
ch <- true
}
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Should have connected ok: %v", err)
}
ts.stopServer()
if e := wait(ch); e != nil {
t.Fatal("Did not trigger ClosedCB correctly")
}
nc.Close()
}
func TestReconnectAllowedFlags(t *testing.T) {
ts := startReconnectServer(t)
ch := make(chan bool)
opts := DefaultOptions
opts.Url = "nats://localhost:22222"
opts.AllowReconnect = true
opts.MaxReconnect = 2
opts.ReconnectWait = 1 * time.Second
opts.ClosedCB = func(_ *Conn) {
ch <- true
}
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Should have connected ok: %v", err)
}
ts.stopServer()
// We want wait to timeout here, and the connection
// should not trigger the Close CB.
if e := wait(ch); e == nil {
t.Fatal("Triggered ClosedCB incorrectly")
}
if !nc.isReconnecting() {
t.Fatal("Expected to be in a reconnecting state")
}
// clear the CloseCB since ch will block
nc.Opts.ClosedCB = nil
nc.Close()
}
var reconnectOpts = Options{
Url: "nats://localhost:22222",
AllowReconnect: true,
MaxReconnect: 10,
ReconnectWait: 100 * time.Millisecond,
Timeout: DefaultTimeout,
}
func TestBasicReconnectFunctionality(t *testing.T) {
ts := startReconnectServer(t)
ch := make(chan bool)
opts := reconnectOpts
nc, _ := opts.Connect()
ec, err := NewEncodedConn(nc, "default")
if err != nil {
t.Fatalf("Failed to create an encoded connection: %v\n", err)
}
testString := "bar"
ec.Subscribe("foo", func(s string) {
if s != testString {
t.Fatal("String doesn't match")
}
ch <- true
})
ec.Flush()
ts.stopServer()
// server is stopped here...
dch := make(chan bool)
opts.DisconnectedCB = func(_ *Conn) {
dch <- true
}
wait(dch)
if err := ec.Publish("foo", testString); err != nil {
t.Fatalf("Failed to publish message: %v\n", err)
}
ts = startReconnectServer(t)
defer ts.stopServer()
if err := ec.FlushTimeout(5 * time.Second); err != nil {
t.Fatalf("Error on Flush: %v", err)
}
if e := wait(ch); e != nil {
t.Fatal("Did not receive our message")
}
expectedReconnectCount := uint64(1)
if ec.Conn.Reconnects != expectedReconnectCount {
t.Fatalf("Reconnect count incorrect: %d vs %d\n",
ec.Conn.Reconnects, expectedReconnectCount)
}
// Make sure the server who is reconnected has the reconnects stats reset.
_, cur := nc.currentServer()
if cur.reconnects != 0 {
t.Fatalf("Current Server's reconnects should be 0 vs %d\n", cur.reconnects)
}
nc.Close()
}
func TestExtendedReconnectFunctionality(t *testing.T) {
ts := startReconnectServer(t)
opts := reconnectOpts
dch := make(chan bool)
opts.DisconnectedCB = func(_ *Conn) {
dch <- true
}
rch := make(chan bool)
opts.ReconnectedCB = func(_ *Conn) {
rch <- true
}
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Should have connected ok: %v", err)
}
ec, err := NewEncodedConn(nc, "default")
if err != nil {
t.Fatalf("Failed to create an encoded connection: %v\n", err)
}
testString := "bar"
received := int32(0)
ec.Subscribe("foo", func(s string) {
atomic.AddInt32(&received, 1)
})
sub, _ := ec.Subscribe("foobar", func(s string) {
atomic.AddInt32(&received, 1)
})
ec.Publish("foo", testString)
ec.Flush()
ts.stopServer()
// server is stopped here..
// wait for disconnect
if e := waitTime(dch, 2*time.Second); e != nil {
t.Fatal("Did not receive a disconnect callback message")
}
// Sub while disconnected
ec.Subscribe("bar", func(s string) {
atomic.AddInt32(&received, 1)
})
// Unsub while disconnected
sub.Unsubscribe()
if err = ec.Publish("foo", testString); err != nil {
t.Fatalf("Received an error after disconnect: %v\n", err)
}
if err = ec.Publish("bar", testString); err != nil {
t.Fatalf("Received an error after disconnect: %v\n", err)
}
ts = startReconnectServer(t)
defer ts.stopServer()
// server is restarted here..
// wait for reconnect
if e := waitTime(rch, 2*time.Second); e != nil {
t.Fatal("Did not receive a reconnect callback message")
}
if err = ec.Publish("foobar", testString); err != nil {
t.Fatalf("Received an error after server restarted: %v\n", err)
}
if err = ec.Publish("foo", testString); err != nil {
t.Fatalf("Received an error after server restarted: %v\n", err)
}
ch := make(chan bool)
ec.Subscribe("done", func(b bool) {
ch <- true
})
ec.Publish("done", true)
if e := wait(ch); e != nil {
t.Fatal("Did not receive our message")
}
if atomic.LoadInt32(&received) != 4 {
t.Fatalf("Received != %d, equals %d\n", 4, received)
}
}
func TestParseStateReconnectFunctionality(t *testing.T) {
ts := startReconnectServer(t)
ch := make(chan bool)
opts := reconnectOpts
nc, _ := opts.Connect()
ec, err := NewEncodedConn(nc, "default")
if err != nil {
t.Fatalf("Failed to create an encoded connection: %v\n", err)
}
testString := "bar"
ec.Subscribe("foo", func(s string) {
if s != testString {
t.Fatal("String doesn't match")
}
ch <- true
})
ec.Flush()
// Simulate partialState, this needs to be cleared
nc.mu.Lock()
nc.ps.state = OP_PON
nc.mu.Unlock()
ts.stopServer()
// server is stopped here...
dch := make(chan bool)
opts.DisconnectedCB = func(_ *Conn) {
dch <- true
}
wait(dch)
if err := ec.Publish("foo", testString); err != nil {
t.Fatalf("Failed to publish message: %v\n", err)
}
ts = startReconnectServer(t)
defer ts.stopServer()
if err := ec.FlushTimeout(5 * time.Second); err != nil {
t.Fatalf("Error on Flush: %v", err)
}
if e := wait(ch); e != nil {
t.Fatal("Did not receive our message")
}
expectedReconnectCount := uint64(1)
if ec.Conn.Reconnects != expectedReconnectCount {
t.Fatalf("Reconnect count incorrect: %d vs %d\n",
ec.Conn.Reconnects, expectedReconnectCount)
}
nc.Close()
}
func TestQueueSubsOnReconnect(t *testing.T) {
ts := startReconnectServer(t)
opts := reconnectOpts
// Allow us to block on reconnect complete.
reconnectsDone := make(chan bool)
opts.ReconnectedCB = func(nc *Conn) {
reconnectsDone <- true
}
// Helper to wait on a reconnect.
waitOnReconnect := func() {
select {
case <-reconnectsDone:
break
case <-time.After(2 * time.Second):
t.Fatalf("Expected a reconnect, timedout!\n")
}
}
// Create connection
nc, _ := opts.Connect()
ec, err := NewEncodedConn(nc, "json")
if err != nil {
t.Fatalf("Failed to create an encoded connection: %v\n", err)
}
// To hold results.
results := make(map[int]int)
var mu sync.Mutex
// Make sure we got what we needed, 1 msg only and all seqnos accounted for..
checkResults := func(numSent int) {
mu.Lock()
defer mu.Unlock()
for i := 0; i < numSent; i++ {
if results[i] != 1 {
t.Fatalf("Received incorrect number of messages, [%d] for seq: %d\n", results[i], i)
}
}
// Auto reset results map
results = make(map[int]int)
}
subj := "foo.bar"
qgroup := "workers"
cb := func(seqno int) {
mu.Lock()
defer mu.Unlock()
results[seqno] = results[seqno] + 1
}
// Create Queue Subscribers
ec.QueueSubscribe(subj, qgroup, cb)
ec.QueueSubscribe(subj, qgroup, cb)
ec.Flush()
// Helper function to send messages and check results.
sendAndCheckMsgs := func(numToSend int) {
for i := 0; i < numToSend; i++ {
ec.Publish(subj, i)
}
// Wait for processing.
ec.Flush()
time.Sleep(50 * time.Millisecond)
// Check Results
checkResults(numToSend)
}
// Base Test
sendAndCheckMsgs(10)
// Stop and restart server
ts.stopServer()
ts = startReconnectServer(t)
defer ts.stopServer()
waitOnReconnect()
// Reconnect Base Test
sendAndCheckMsgs(10)
}
func TestIsClosed(t *testing.T) {
ts := startReconnectServer(t)
nc := newConnection(t)
if nc.IsClosed() == true {
t.Fatalf("IsClosed returned true when the connection is still open.")
}
ts.stopServer()
if nc.IsClosed() == true {
t.Fatalf("IsClosed returned true when the connection is still open.")
}
ts = startReconnectServer(t)
if nc.IsClosed() == true {
t.Fatalf("IsClosed returned true when the connection is still open.")
}
nc.Close()
if nc.IsClosed() == false {
t.Fatalf("IsClosed returned false after Close() was called.")
}
ts.stopServer()
}
func TestIsReconnectingAndStatus(t *testing.T) {
ts := startReconnectServer(t)
// This will kill the last 'ts' server that is created
defer func() { ts.stopServer() }()
disconnectedch := make(chan bool)
reconnectch := make(chan bool)
opts := DefaultOptions
opts.Url = "nats://localhost:22222"
opts.AllowReconnect = true
opts.MaxReconnect = 10000
opts.ReconnectWait = 100 * time.Millisecond
opts.DisconnectedCB = func(_ *Conn) {
disconnectedch <- true
}
opts.ReconnectedCB = func(_ *Conn) {
reconnectch <- true
}
// Connect, verify initial reconnecting state check, then stop the server
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Should have connected ok: %v", err)
}
if nc.IsReconnecting() == true {
t.Fatalf("IsReconnecting returned true when the connection is still open.")
}
if status := nc.Status(); status != CONNECTED {
t.Fatalf("Status returned %d when connected instead of CONNECTED", status)
}
ts.stopServer()
// Wait until we get the disconnected callback
if e := wait(disconnectedch); e != nil {
t.Fatalf("Disconnect callback wasn't triggered: %v", e)
}
if nc.IsReconnecting() == false {
t.Fatalf("IsReconnecting returned false when the client is reconnecting.")
}
if status := nc.Status(); status != RECONNECTING {
t.Fatalf("Status returned %d when reconnecting instead of CONNECTED", status)
}
ts = startReconnectServer(t)
// Wait until we get the reconnect callback
if e := wait(reconnectch); e != nil {
t.Fatalf("Reconnect callback wasn't triggered: %v", e)
}
if nc.IsReconnecting() == true {
t.Fatalf("IsReconnecting returned true after the connection was reconnected.")
}
if status := nc.Status(); status != CONNECTED {
t.Fatalf("Status returned %d when reconnected instead of CONNECTED", status)
}
// Close the connection, reconnecting should still be false
nc.Close()
if nc.IsReconnecting() == true {
t.Fatalf("IsReconnecting returned true after Close() was called.")
}
if status := nc.Status(); status != CLOSED {
t.Fatalf("Status returned %d after Close() was called instead of CLOSED", status)
}
}