-
Notifications
You must be signed in to change notification settings - Fork 665
/
sub_test.go
1573 lines (1346 loc) · 36.8 KB
/
sub_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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013-2020 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package test
import (
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nuid"
)
// More advanced tests on subscriptions
func TestServerAutoUnsub(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
received := int32(0)
max := int32(10)
// Call this to make sure that we have everything setup connection wise
nc.Flush()
// When this test is run by itself it's fine, but when run with others
// we need to make sure the go routines reading has settled.
time.Sleep(250 * time.Millisecond)
base := getStableNumGoroutine(t)
sub, err := nc.Subscribe("foo", func(_ *nats.Msg) {
atomic.AddInt32(&received, 1)
})
if err != nil {
t.Fatal("Failed to subscribe: ", err)
}
sub.AutoUnsubscribe(int(max))
total := 100
for i := 0; i < total; i++ {
nc.Publish("foo", []byte("Hello"))
}
nc.Flush()
time.Sleep(100 * time.Millisecond)
if atomic.LoadInt32(&received) != max {
t.Fatalf("Received %d msgs, wanted only %d\n", received, max)
}
if sub.IsValid() {
t.Fatal("Expected subscription to be invalid after hitting max")
}
if err := sub.AutoUnsubscribe(10); err == nil {
t.Fatal("Calling AutoUnsubscribe() on closed subscription should fail")
}
checkNoGoroutineLeak(t, base, "AutoUnsubscribe() limit reached")
}
func TestClientSyncAutoUnsub(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
received := 0
max := 10
sub, _ := nc.SubscribeSync("foo")
sub.AutoUnsubscribe(max)
total := 100
for i := 0; i < total; i++ {
nc.Publish("foo", []byte("Hello"))
}
nc.Flush()
for {
_, err := sub.NextMsg(10 * time.Millisecond)
if err != nil {
if err != nats.ErrMaxMessages {
t.Fatalf("Expected '%v', but got: '%v'\n", nats.ErrMaxMessages, err.Error())
}
break
}
received++
}
if received != max {
t.Fatalf("Received %d msgs, wanted only %d\n", received, max)
}
if sub.IsValid() {
t.Fatal("Expected subscription to be invalid after hitting max")
}
if err := sub.AutoUnsubscribe(10); err == nil {
t.Fatal("Calling AutoUnsubscribe() ob closed subscription should fail")
}
}
func TestClientASyncAutoUnsub(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
received := int32(0)
max := int32(10)
sub, err := nc.Subscribe("foo", func(_ *nats.Msg) {
atomic.AddInt32(&received, 1)
})
if err != nil {
t.Fatal("Failed to subscribe: ", err)
}
sub.AutoUnsubscribe(int(max))
total := 100
for i := 0; i < total; i++ {
nc.Publish("foo", []byte("Hello"))
}
nc.Flush()
time.Sleep(10 * time.Millisecond)
if atomic.LoadInt32(&received) != max {
t.Fatalf("Received %d msgs, wanted only %d\n", received, max)
}
if err := sub.AutoUnsubscribe(10); err == nil {
t.Fatal("Calling AutoUnsubscribe() on closed subscription should fail")
}
}
func TestAutoUnsubAndReconnect(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
rch := make(chan bool)
nc, err := nats.Connect(nats.DefaultURL,
nats.ReconnectWait(50*time.Millisecond),
nats.ReconnectJitter(0, 0),
nats.ReconnectHandler(func(_ *nats.Conn) { rch <- true }))
if err != nil {
t.Fatalf("Unable to connect: %v", err)
}
defer nc.Close()
received := int32(0)
max := int32(10)
sub, err := nc.Subscribe("foo", func(_ *nats.Msg) {
atomic.AddInt32(&received, 1)
})
if err != nil {
t.Fatalf("Failed to subscribe: %v", err)
}
sub.AutoUnsubscribe(int(max))
// Send less than the max
total := int(max / 2)
for i := 0; i < total; i++ {
nc.Publish("foo", []byte("Hello"))
}
nc.Flush()
// Restart the server
s.Shutdown()
s = RunDefaultServer()
defer s.Shutdown()
// and wait to reconnect
if err := Wait(rch); err != nil {
t.Fatal("Failed to get the reconnect cb")
}
// Now send more than the total max.
total = int(3 * max)
for i := 0; i < total; i++ {
nc.Publish("foo", []byte("Hello"))
}
nc.Flush()
// Wait a bit before checking.
time.Sleep(50 * time.Millisecond)
// We should have received only up-to-max messages.
if atomic.LoadInt32(&received) != max {
t.Fatalf("Received %d msgs, wanted only %d\n", received, max)
}
}
func TestAutoUnsubWithParallelNextMsgCalls(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
rch := make(chan bool, 1)
nc, err := nats.Connect(nats.DefaultURL,
nats.ReconnectWait(50*time.Millisecond),
nats.ReconnectJitter(0, 0),
nats.ReconnectHandler(func(_ *nats.Conn) { rch <- true }))
if err != nil {
t.Fatalf("Unable to connect: %v", err)
}
defer nc.Close()
numRoutines := 3
max := 100
total := max * 2
received := int64(0)
var wg sync.WaitGroup
sub, err := nc.SubscribeSync("foo")
if err != nil {
t.Fatalf("Failed to subscribe: %v", err)
}
sub.AutoUnsubscribe(int(max))
nc.Flush()
wg.Add(numRoutines)
for i := 0; i < numRoutines; i++ {
go func(s *nats.Subscription, idx int) {
for {
// The first to reach the max delivered will cause the
// subscription to be removed, which will kick out all
// other calls to NextMsg. So don't be afraid of the long
// timeout.
_, err := s.NextMsg(3 * time.Second)
if err != nil {
break
}
atomic.AddInt64(&received, 1)
}
wg.Done()
}(sub, i)
}
msg := []byte("Hello")
for i := 0; i < max/2; i++ {
nc.Publish("foo", msg)
}
nc.Flush()
s.Shutdown()
s = RunDefaultServer()
defer s.Shutdown()
// Make sure we got the reconnected cb
if err := Wait(rch); err != nil {
t.Fatal("Failed to get reconnected cb")
}
for i := 0; i < total; i++ {
nc.Publish("foo", msg)
}
nc.Flush()
wg.Wait()
if atomic.LoadInt64(&received) != int64(max) {
t.Fatalf("Wrong number of received msg: %v instead of %v", atomic.LoadInt64(&received), max)
}
}
func TestAutoUnsubscribeFromCallback(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc, err := nats.Connect(nats.DefaultURL)
if err != nil {
t.Fatalf("Unable to connect: %v", err)
}
defer nc.Close()
max := 10
resetUnsubMark := int64(max / 2)
limit := int64(100)
received := int64(0)
msg := []byte("Hello")
// Auto-unsubscribe within the callback with a value lower
// than what was already received.
sub, err := nc.Subscribe("foo", func(m *nats.Msg) {
r := atomic.AddInt64(&received, 1)
if r == resetUnsubMark {
m.Sub.AutoUnsubscribe(int(r - 1))
nc.Flush()
}
if r == limit {
// Something went wrong... fail now
t.Fatal("Got more messages than expected")
}
nc.Publish("foo", msg)
})
if err != nil {
t.Fatalf("Failed to subscribe: %v", err)
}
sub.AutoUnsubscribe(int(max))
nc.Flush()
// Trigger the first message, the other are sent from the callback.
nc.Publish("foo", msg)
nc.Flush()
waitFor(t, 5*time.Second, 100*time.Millisecond, func() error {
recv := atomic.LoadInt64(&received)
if recv != resetUnsubMark {
return fmt.Errorf("Wrong number of received messages. Original max was %v reset to %v, actual received: %v",
max, resetUnsubMark, recv)
}
return nil
})
// Now check with AutoUnsubscribe with higher value than original
received = int64(0)
newMax := int64(2 * max)
sub, err = nc.Subscribe("foo", func(m *nats.Msg) {
r := atomic.AddInt64(&received, 1)
if r == resetUnsubMark {
m.Sub.AutoUnsubscribe(int(newMax))
nc.Flush()
}
if r == limit {
// Something went wrong... fail now
t.Fatal("Got more messages than expected")
}
nc.Publish("foo", msg)
})
if err != nil {
t.Fatalf("Failed to subscribe: %v", err)
}
sub.AutoUnsubscribe(int(max))
nc.Flush()
// Trigger the first message, the other are sent from the callback.
nc.Publish("foo", msg)
nc.Flush()
waitFor(t, 5*time.Second, 100*time.Millisecond, func() error {
recv := atomic.LoadInt64(&received)
if recv != newMax {
return fmt.Errorf("Wrong number of received messages. Original max was %v reset to %v, actual received: %v",
max, newMax, recv)
}
return nil
})
}
func TestCloseSubRelease(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
sub, _ := nc.SubscribeSync("foo")
start := time.Now()
go func() {
time.Sleep(15 * time.Millisecond)
nc.Close()
}()
if _, err := sub.NextMsg(time.Second); err == nil {
t.Fatalf("Expected an error from NextMsg")
}
elapsed := time.Since(start)
// On Windows, the minimum waitTime is at least 15ms.
if elapsed > 50*time.Millisecond {
t.Fatalf("Too much time has elapsed to release NextMsg: %dms",
(elapsed / time.Millisecond))
}
}
func TestIsValidSubscriber(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
sub, err := nc.SubscribeSync("foo")
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
if !sub.IsValid() {
t.Fatalf("Subscription should be valid")
}
for i := 0; i < 10; i++ {
nc.Publish("foo", []byte("Hello"))
}
nc.Flush()
_, err = sub.NextMsg(200 * time.Millisecond)
if err != nil {
t.Fatalf("NextMsg returned an error")
}
sub.Unsubscribe()
_, err = sub.NextMsg(200 * time.Millisecond)
if err == nil {
t.Fatalf("NextMsg should have returned an error")
}
}
func TestSlowSubscriber(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
// Override default handler for test.
nc.SetErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, _ error) {})
sub, _ := nc.SubscribeSync("foo")
sub.SetPendingLimits(100, 1024)
for i := 0; i < 200; i++ {
nc.Publish("foo", []byte("Hello"))
}
timeout := 5 * time.Second
start := time.Now()
nc.FlushTimeout(timeout)
elapsed := time.Since(start)
if elapsed >= timeout {
t.Fatalf("Flush did not return before timeout: %d > %d", elapsed, timeout)
}
// Make sure NextMsg returns an error to indicate slow consumer
_, err := sub.NextMsg(200 * time.Millisecond)
if err == nil {
t.Fatalf("NextMsg did not return an error")
}
}
func TestSlowChanSubscriber(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
// Override default handler for test.
nc.SetErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, _ error) {})
ch := make(chan *nats.Msg, 64)
sub, _ := nc.ChanSubscribe("foo", ch)
sub.SetPendingLimits(100, 1024)
for i := 0; i < 200; i++ {
nc.Publish("foo", []byte("Hello"))
}
timeout := 5 * time.Second
start := time.Now()
nc.FlushTimeout(timeout)
elapsed := time.Since(start)
if elapsed >= timeout {
t.Fatalf("Flush did not return before timeout: %d > %d", elapsed, timeout)
}
}
func TestSlowAsyncSubscriber(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
// Override default handler for test.
nc.SetErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, _ error) {})
bch := make(chan bool)
sub, _ := nc.Subscribe("foo", func(m *nats.Msg) {
// block to back us up..
<-bch
// Avoid repeated calls that would then block again
m.Sub.Unsubscribe()
})
// Make sure these are the defaults
pm, pb, _ := sub.PendingLimits()
if pm != nats.DefaultSubPendingMsgsLimit {
t.Fatalf("Pending limit for number of msgs incorrect, expected %d, got %d\n", nats.DefaultSubPendingMsgsLimit, pm)
}
if pb != nats.DefaultSubPendingBytesLimit {
t.Fatalf("Pending limit for number of bytes incorrect, expected %d, got %d\n", nats.DefaultSubPendingBytesLimit, pb)
}
// Set new limits
pml := 100
pbl := 1024 * 1024
sub.SetPendingLimits(pml, pbl)
// Make sure the set is correct
pm, pb, _ = sub.PendingLimits()
if pm != pml {
t.Fatalf("Pending limit for number of msgs incorrect, expected %d, got %d\n", pml, pm)
}
if pb != pbl {
t.Fatalf("Pending limit for number of bytes incorrect, expected %d, got %d\n", pbl, pb)
}
for i := 0; i < (int(pml) + 100); i++ {
nc.Publish("foo", []byte("Hello"))
}
timeout := 5 * time.Second
start := time.Now()
err := nc.FlushTimeout(timeout)
elapsed := time.Since(start)
if elapsed >= timeout {
t.Fatalf("Flush did not return before timeout")
}
// We want flush to work, so expect no error for it.
if err != nil {
t.Fatalf("Expected no error from Flush()\n")
}
if nc.LastError() != nats.ErrSlowConsumer {
t.Fatal("Expected LastError to indicate slow consumer")
}
// release the sub
close(bch)
}
func TestAsyncErrHandler(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
opts := nats.GetDefaultOptions()
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Could not connect to server: %v\n", err)
}
defer nc.Close()
subj := "async_test"
bch := make(chan bool)
sub, err := nc.Subscribe(subj, func(_ *nats.Msg) {
// block to back us up..
<-bch
})
if err != nil {
t.Fatalf("Could not subscribe: %v\n", err)
}
limit := 10
toSend := 100
// Limit internal subchan length to trip condition easier.
sub.SetPendingLimits(limit, 1024)
ch := make(chan bool)
aeCalled := int64(0)
nc.SetErrorHandler(func(c *nats.Conn, s *nats.Subscription, e error) {
atomic.AddInt64(&aeCalled, 1)
if s != sub {
t.Fatal("Did not receive proper subscription")
}
if e != nats.ErrSlowConsumer {
t.Fatalf("Did not receive proper error: %v vs %v", e, nats.ErrSlowConsumer)
}
// Suppress additional calls
if atomic.LoadInt64(&aeCalled) == 1 {
// release the sub
defer close(bch)
// release the test
ch <- true
}
})
b := []byte("Hello World!")
// First one trips the ch wait in subscription callback.
nc.Publish(subj, b)
nc.Flush()
for i := 0; i < toSend; i++ {
nc.Publish(subj, b)
}
if err := nc.Flush(); err != nil {
t.Fatalf("Got an error on Flush:%v", err)
}
if e := Wait(ch); e != nil {
t.Fatal("Failed to call async err handler")
}
// Make sure dropped stats is correct.
if d, _ := sub.Dropped(); d != toSend-limit+1 {
t.Fatalf("Expected Dropped to be %d, got %d", toSend-limit+1, d)
}
if ae := atomic.LoadInt64(&aeCalled); ae != 1 {
t.Fatalf("Expected err handler to be called only once, got %d", ae)
}
sub.Unsubscribe()
if _, err := sub.Dropped(); err == nil {
t.Fatal("Calling Dropped() on closed subscription should fail")
}
}
func TestAsyncErrHandlerChanSubscription(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
opts := nats.GetDefaultOptions()
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Could not connect to server: %v", err)
}
defer nc.Close()
subj := "chan_test"
limit := 10
toSend := 100
// Create our own channel.
mch := make(chan *nats.Msg, limit)
sub, err := nc.ChanSubscribe(subj, mch)
if err != nil {
t.Fatalf("Could not subscribe: %v", err)
}
ch := make(chan bool)
aeCalled := int64(0)
nc.SetErrorHandler(func(c *nats.Conn, s *nats.Subscription, e error) {
atomic.AddInt64(&aeCalled, 1)
if e != nats.ErrSlowConsumer {
t.Fatalf("Did not receive proper error: %v vs %v",
e, nats.ErrSlowConsumer)
}
// Suppress additional calls
if atomic.LoadInt64(&aeCalled) == 1 {
// release the test
ch <- true
}
})
b := []byte("Hello World!")
for i := 0; i < toSend; i++ {
nc.Publish(subj, b)
}
nc.Flush()
if e := Wait(ch); e != nil {
t.Fatal("Failed to call async err handler")
}
// Make sure dropped stats is correct.
if d, _ := sub.Dropped(); d != toSend-limit {
t.Fatalf("Expected Dropped to be %d, go %d", toSend-limit, d)
}
if ae := atomic.LoadInt64(&aeCalled); ae != 1 {
t.Fatalf("Expected err handler to be called once, got %d", ae)
}
sub.Unsubscribe()
if _, err := sub.Dropped(); err == nil {
t.Fatal("Calling Dropped() on closed subscription should fail")
}
}
// Test to make sure that we can send and async receive messages on
// different subjects within a callback.
func TestAsyncSubscriberStarvation(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
// Helper
nc.Subscribe("helper", func(m *nats.Msg) {
nc.Publish(m.Reply, []byte("Hello"))
})
ch := make(chan bool)
// Kickoff
nc.Subscribe("start", func(m *nats.Msg) {
// Helper Response
response := nats.NewInbox()
nc.Subscribe(response, func(_ *nats.Msg) {
ch <- true
})
nc.PublishRequest("helper", response, []byte("Help Me!"))
})
nc.Publish("start", []byte("Begin"))
nc.Flush()
if e := Wait(ch); e != nil {
t.Fatal("Was stalled inside of callback waiting on another callback")
}
}
func TestAsyncSubscribersOnClose(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
toSend := 10
callbacks := int32(0)
ch := make(chan bool, toSend)
nc.Subscribe("foo", func(_ *nats.Msg) {
atomic.AddInt32(&callbacks, 1)
<-ch
})
for i := 0; i < toSend; i++ {
nc.Publish("foo", []byte("Hello World!"))
}
nc.Flush()
time.Sleep(10 * time.Millisecond)
nc.Close()
// Release callbacks
for i := 1; i < toSend; i++ {
ch <- true
}
// Wait for some time.
time.Sleep(10 * time.Millisecond)
seen := atomic.LoadInt32(&callbacks)
if seen != 1 {
t.Fatalf("Expected only one callback, received %d callbacks", seen)
}
}
func TestNextMsgCallOnAsyncSub(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
sub, err := nc.Subscribe("foo", func(_ *nats.Msg) {
})
if err != nil {
t.Fatal("Failed to subscribe: ", err)
}
_, err = sub.NextMsg(time.Second)
if err == nil {
t.Fatal("Expected an error call NextMsg() on AsyncSubscriber")
}
}
func TestNextMsgCallOnClosedSub(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
sub, err := nc.SubscribeSync("foo")
if err != nil {
t.Fatal("Failed to subscribe: ", err)
}
if err = sub.Unsubscribe(); err != nil {
t.Fatal("Unsubscribe failed with err:", err)
}
_, err = sub.NextMsg(time.Second)
if err == nil {
t.Fatal("Expected an error calling NextMsg() on closed subscription")
} else if err != nats.ErrBadSubscription {
t.Fatalf("Expected '%v', but got: '%v'", nats.ErrBadSubscription, err.Error())
}
sub, err = nc.SubscribeSync("foo")
if err != nil {
t.Fatal("Failed to subscribe: ", err)
}
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
time.Sleep(100 * time.Millisecond)
sub.Unsubscribe()
wg.Done()
}()
if _, err := sub.NextMsg(time.Second); err == nil || err != nats.ErrBadSubscription {
t.Fatalf("Expected '%v', but got: '%v'", nats.ErrBadSubscription, err.Error())
}
}
func TestChanSubscriber(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
// Create our own channel.
ch := make(chan *nats.Msg, 128)
// Channel is mandatory
if _, err := nc.ChanSubscribe("foo", nil); err == nil {
t.Fatal("Creating subscription without channel should have failed")
}
_, err := nc.ChanSubscribe("foo", ch)
if err != nil {
t.Fatal("Failed to subscribe: ", err)
}
// Send some messages to ourselves.
total := 100
for i := 0; i < total; i++ {
nc.Publish("foo", []byte("Hello"))
}
received := 0
tm := time.NewTimer(5 * time.Second)
defer tm.Stop()
// Go ahead and receive
for {
select {
case _, ok := <-ch:
if !ok {
t.Fatalf("Got an error reading from channel")
}
case <-tm.C:
t.Fatalf("Timed out waiting on messages")
}
received++
if received >= total {
return
}
}
}
func TestChanQueueSubscriber(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
// Create our own channel.
ch1 := make(chan *nats.Msg, 64)
ch2 := make(chan *nats.Msg, 64)
nc.ChanQueueSubscribe("foo", "bar", ch1)
nc.ChanQueueSubscribe("foo", "bar", ch2)
// Send some messages to ourselves.
total := 100
for i := 0; i < total; i++ {
nc.Publish("foo", []byte("Hello"))
}
received := 0
tm := time.NewTimer(5 * time.Second)
defer tm.Stop()
chk := func(ok bool) {
if !ok {
t.Fatalf("Got an error reading from channel")
} else {
received++
}
}
// Go ahead and receive
for {
select {
case _, ok := <-ch1:
chk(ok)
case _, ok := <-ch2:
chk(ok)
case <-tm.C:
t.Fatalf("Timed out waiting on messages")
}
if received >= total {
return
}
}
}
func TestChanSubscriberPendingLimits(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
ncp := NewDefaultConnection(t)
defer ncp.Close()
// There was a defect that prevented to receive more than
// the default pending message limit. Trying to send more
// than this limit.
pending := 1000
total := pending + 100
for typeSubs := 0; typeSubs < 3; typeSubs++ {
func() {
// Create our own channel.
ch := make(chan *nats.Msg, total)
var err error
var sub *nats.Subscription
switch typeSubs {
case 0:
sub, err = nc.ChanSubscribe("foo", ch)
if err := sub.SetPendingLimits(pending, -1); err == nil {
t.Fatalf("Expected an error setting pending limits")
}
case 1:
sub, err = nc.ChanQueueSubscribe("foo", "bar", ch)
if err := sub.SetPendingLimits(pending, -1); err == nil {
t.Fatalf("Expected an error setting pending limits")
}
case 2:
sub, err = nc.QueueSubscribeSyncWithChan("foo", "bar", ch)
if err := sub.SetPendingLimits(pending, -1); err == nil {
t.Fatalf("Expected an error setting pending limits")
}
}
if err != nil {
t.Fatalf("Unexpected error on subscribe: %v", err)
}
defer sub.Unsubscribe()
nc.Flush()
// Send some messages
for i := 0; i < total; i++ {
if err := ncp.Publish("foo", []byte("Hello")); err != nil {
t.Fatalf("Unexpected error on publish: %v", err)
}
}
received := 0
tm := time.NewTimer(10 * time.Second)
defer tm.Stop()
chk := func(ok bool) {
if !ok {
t.Fatalf("Got an error reading from channel")
} else {
received++
}
}
// Go ahead and receive
for {
select {
case _, ok := <-ch:
chk(ok)
if received >= total {
return
}
case <-tm.C:
t.Fatalf("Timed out waiting on messages for test %d, received %d", typeSubs, received)
}
}
}()
}
}
func TestQueueChanQueueSubscriber(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
// Create our own channel.
ch1 := make(chan *nats.Msg, 64)
ch2 := make(chan *nats.Msg, 64)
nc.QueueSubscribeSyncWithChan("foo", "bar", ch1)
nc.QueueSubscribeSyncWithChan("foo", "bar", ch2)
// Send some messages to ourselves.
total := 100
for i := 0; i < total; i++ {
nc.Publish("foo", []byte("Hello"))
}
recv1 := 0
recv2 := 0
tm := time.NewTimer(5 * time.Second)
defer tm.Stop()
runTimer := time.NewTimer(500 * time.Millisecond)
defer runTimer.Stop()