-
Notifications
You must be signed in to change notification settings - Fork 116
/
stan_test.go
2908 lines (2510 loc) · 71.7 KB
/
stan_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 2016-2021 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 stan
////////////////////////////////////////////////////////////////////////////////
// Package scoped specific tests here..
////////////////////////////////////////////////////////////////////////////////
import (
"bytes"
"errors"
"fmt"
"math/rand"
"net"
"os"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
natsd "github.com/nats-io/nats-server/v2/test"
"github.com/nats-io/nats-streaming-server/server"
"github.com/nats-io/nats.go"
"github.com/nats-io/stan.go/pb"
)
func RunServer(ID string) *server.StanServer {
s, err := server.RunServer(ID)
if err != nil {
panic(err)
}
return s
}
func runServerWithOpts(sOpts *server.Options) *server.StanServer {
s, err := server.RunServerWithOpts(sOpts, nil)
if err != nil {
panic(err)
}
return s
}
// Dumb wait program to sync on callbacks, etc... Will timeout
func Wait(ch chan bool) error {
return WaitTime(ch, 5*time.Second)
}
func WaitTime(ch chan bool, timeout time.Duration) error {
select {
case <-ch:
return nil
case <-time.After(timeout):
}
return errors.New("timeout")
}
func TestVersionMatchesTag(t *testing.T) {
tag := os.Getenv("TRAVIS_TAG")
if tag == "" {
t.SkipNow()
}
// We expect a tag of the form vX.Y.Z. If that's not the case,
// we need someone to have a look. So fail if first letter is not
// a `v`
if tag[0] != 'v' {
t.Fatalf("Expect tag to start with `v`, tag is: %s", tag)
}
// Strip the `v` from the tag for the version comparison.
if Version != tag[1:] {
t.Fatalf("Version (%s) does not match tag (%s)", Version, tag[1:])
}
}
func TestNoNats(t *testing.T) {
var errTxt string
switch runtime.GOOS {
case "windows":
errTxt = "i/o timeout"
default:
errTxt = nats.ErrNoServers.Error()
}
_, err := Connect("someNonExistentServerID", "myTestClient")
if err == nil || !strings.Contains(err.Error(), errTxt) {
t.Fatalf("Expected NATS: No Servers err, got %v\n", err)
}
}
func TestUnreachable(t *testing.T) {
s := natsd.RunDefaultServer()
defer s.Shutdown()
nc, err := nats.Connect(nats.DefaultURL)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc.Close()
_, err = nc.Request("no.responders", nil, 50*time.Millisecond)
noResponders := err == nats.ErrNoResponders
nc.Close()
// Non-Existent or Unreachable
connectTime := 25 * time.Millisecond
start := time.Now()
if _, err := Connect("someNonExistentServerID", "myTestClient", ConnectWait(connectTime)); err != ErrConnectReqTimeout {
t.Fatalf("Expected Unreachable err, got %v\n", err)
}
if !noResponders {
if delta := time.Since(start); delta < connectTime {
t.Fatalf("Expected to wait at least %v, but only waited %v\n", connectTime, delta)
}
}
}
const (
clusterName = "my_test_cluster"
clientName = "me"
)
// So that we can pass tests and benchmarks...
type tLogger interface {
Fatalf(format string, args ...interface{})
Errorf(format string, args ...interface{})
}
func stackFatalf(t tLogger, f string, args ...interface{}) {
lines := make([]string, 0, 32)
msg := fmt.Sprintf(f, args...)
lines = append(lines, msg)
// Generate the Stack of callers:
for i := 1; true; i++ {
_, file, line, ok := runtime.Caller(i)
if !ok {
break
}
msg := fmt.Sprintf("%d - %s:%d", i, file, line)
lines = append(lines, msg)
}
t.Fatalf("%s", strings.Join(lines, "\n"))
}
func NewDefaultConnection(t tLogger) Conn {
sc, err := Connect(clusterName, clientName)
if err != nil {
stackFatalf(t, "Expected to connect correctly, got err %v", err)
}
return sc
}
func TestConnClosedOnConnectFailure(t *testing.T) {
s := natsd.RunDefaultServer()
defer s.Shutdown()
// Non-Existent or Unreachable
connectTime := 25 * time.Millisecond
if _, err := Connect("someNonExistentServerID", "myTestClient", ConnectWait(connectTime)); err != ErrConnectReqTimeout {
t.Fatalf("Expected Unreachable err, got %v\n", err)
}
// Check that the underlying NATS connection has been closed.
// We will first stop the server. If we have left the NATS connection
// opened, it should be trying to reconnect.
s.Shutdown()
// Wait a bit
time.Sleep(500 * time.Millisecond)
// Inspecting go routines in search for a doReconnect
buf := make([]byte, 10000)
n := runtime.Stack(buf, true)
if strings.Contains(string(buf[:n]), "doReconnect") {
t.Fatalf("NATS Connection suspected to not have been closed\n%s", buf[:n])
}
}
func TestNatsConnNotClosedOnClose(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
// Create a NATS connection
nc, err := nats.Connect(nats.DefaultURL)
if err != nil {
t.Fatalf("Unexpected error on Connect: %v", err)
}
defer nc.Close()
// Pass this NATS connection to NATS Streaming
sc, err := Connect(clusterName, clientName, NatsConn(nc))
if err != nil {
t.Fatalf("Unexpected error on connect: %v", err)
}
// Now close the NATS Streaming connection
sc.Close()
// Verify that NATS connection is not closed
if nc.IsClosed() {
t.Fatal("NATS connection should NOT have been closed in Connect")
}
}
func TestBasicConnect(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
sc := NewDefaultConnection(t)
defer sc.Close()
}
func TestBasicPublish(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
sc := NewDefaultConnection(t)
defer sc.Close()
if err := sc.Publish("foo", []byte("Hello World!")); err != nil {
t.Fatalf("Expected no errors on publish, got %v\n", err)
}
}
func TestBasicPublishAsync(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
sc := NewDefaultConnection(t)
defer sc.Close()
ch := make(chan bool)
var glock sync.Mutex
var guid string
acb := func(lguid string, err error) {
glock.Lock()
defer glock.Unlock()
if lguid != guid {
t.Fatalf("Expected a matching guid in ack callback, got %s vs %s\n", lguid, guid)
}
ch <- true
}
glock.Lock()
guid, _ = sc.PublishAsync("foo", []byte("Hello World!"), acb)
glock.Unlock()
if guid == "" {
t.Fatalf("Expected non-empty guid to be returned.")
}
if err := Wait(ch); err != nil {
t.Fatal("Did not receive our ack callback")
}
}
func TestTimeoutPublish(t *testing.T) {
ns := natsd.RunDefaultServer()
defer ns.Shutdown()
opts := server.GetDefaultOptions()
opts.NATSServerURL = nats.DefaultURL
opts.ID = clusterName
s := runServerWithOpts(opts)
defer s.Shutdown()
sc, err := Connect(clusterName, clientName,
ConnectWait(250*time.Millisecond),
PubAckWait(50*time.Millisecond))
if err != nil {
t.Fatalf("Expected to connect correctly, got err %v\n", err)
}
defer sc.Close()
ch := make(chan bool)
var glock sync.Mutex
var guid string
acb := func(lguid string, err error) {
glock.Lock()
defer glock.Unlock()
if lguid != guid {
t.Fatalf("Expected a matching guid in ack callback, got %s vs %s\n", lguid, guid)
}
if err != ErrTimeout {
t.Fatalf("Expected a timeout error, got %v", err)
}
ch <- true
}
// Kill the NATS Streaming server so we timeout.
s.Shutdown()
glock.Lock()
guid, _ = sc.PublishAsync("foo", []byte("Hello World!"), acb)
glock.Unlock()
if guid == "" {
t.Fatalf("Expected non-empty guid to be returned.")
}
if err := Wait(ch); err != nil {
t.Fatal("Did not receive our ack callback with a timeout err")
}
// Publish synchronously
if err := sc.Publish("foo", []byte("hello")); err == nil || err != ErrTimeout {
t.Fatalf("Expected Timeout error on publish, got %v", err)
}
}
func TestPublishWithClosedNATSConn(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
nc, err := nats.Connect(nats.DefaultURL)
if err != nil {
t.Fatalf("Unexpected error on connect: %v", err)
}
defer nc.Close()
sc, err := Connect(clusterName, clientName, NatsConn(nc))
if err != nil {
t.Fatalf("Unexpected error on connect: %v", err)
}
defer sc.Close()
// Close the NATS Connection
nc.Close()
msg := []byte("hello")
// Publish should fail
if err := sc.Publish("foo", msg); err == nil {
t.Fatal("Expected error on publish")
}
// Even PublishAsync should fail right away
if _, err := sc.PublishAsync("foo", msg, nil); err == nil {
t.Fatal("Expected error on publish")
}
}
func TestBasicSubscription(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
sc := NewDefaultConnection(t)
defer sc.Close()
sub, err := sc.Subscribe("foo", func(m *Msg) {})
if err != nil {
t.Fatalf("Unexpected error on Subscribe, got %v", err)
}
defer sub.Unsubscribe()
// Close connection
sc.Close()
// Expect ErrConnectionClosed on subscribe
if _, err := sc.Subscribe("foo", func(m *Msg) {}); err == nil || err != ErrConnectionClosed {
t.Fatalf("Expected ErrConnectionClosed on subscribe, got %v", err)
}
if _, err := sc.QueueSubscribe("foo", "bar", func(m *Msg) {}); err == nil || err != ErrConnectionClosed {
t.Fatalf("Expected ErrConnectionClosed on subscribe, got %v", err)
}
}
func TestBasicQueueSubscription(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
sc := NewDefaultConnection(t)
defer sc.Close()
ch := make(chan bool)
count := uint32(0)
cb := func(m *Msg) {
if m.Sequence == 1 {
if atomic.AddUint32(&count, 1) == 2 {
ch <- true
}
}
}
sub, err := sc.QueueSubscribe("foo", "bar", cb)
if err != nil {
t.Fatalf("Expected no error on Subscribe, got %v\n", err)
}
defer sub.Unsubscribe()
// Test that durable and non durable queue subscribers with
// same name can coexist and they both receive the same message.
if _, err = sc.QueueSubscribe("foo", "bar", cb, DurableName("durable-queue-sub")); err != nil {
t.Fatalf("Unexpected error on QueueSubscribe with DurableName: %v", err)
}
// Publish a message
if err := sc.Publish("foo", []byte("msg")); err != nil {
t.Fatalf("Unexpected error on publish: %v", err)
}
// Wait for both messages to be received.
if err := Wait(ch); err != nil {
t.Fatal("Did not get our message")
}
// Check that one cannot use ':' for the queue durable name.
if _, err := sc.QueueSubscribe("foo", "bar", cb, DurableName("my:dur")); err == nil {
t.Fatal("Expected to get an error regarding durable name")
}
}
func TestDurableQueueSubscriber(t *testing.T) {
s := RunServer(clusterName)
defer s.Shutdown()
sc := NewDefaultConnection(t)
defer sc.Close()
total := 5
for i := 0; i < total; i++ {
if err := sc.Publish("foo", []byte("msg")); err != nil {
t.Fatalf("Unexpected error on publish: %v", err)
}
}
ch := make(chan bool)
firstBatch := uint64(total)
secondBatch := uint64(2 * total)
cb := func(m *Msg) {
if !m.Redelivered &&
(m.Sequence == uint64(firstBatch) || m.Sequence == uint64(secondBatch)) {
ch <- true
}
}
if _, err := sc.QueueSubscribe("foo", "bar", cb,
DeliverAllAvailable(),
DurableName("durable-queue-sub")); err != nil {
t.Fatalf("Unexpected error on QueueSubscribe with DurableName: %v", err)
}
if err := Wait(ch); err != nil {
t.Fatal("Did not get our message")
}
// Close connection
sc.Close()
// Create new connection
sc = NewDefaultConnection(t)
defer sc.Close()
// Send more messages
for i := 0; i < total; i++ {
if err := sc.Publish("foo", []byte("msg")); err != nil {
t.Fatalf("Unexpected error on publish: %v", err)
}
}
// Create durable queue sub, it should receive from where it left of,
// and ignore the start position
if _, err := sc.QueueSubscribe("foo", "bar", cb,
StartAtSequence(uint64(10*total)),
DurableName("durable-queue-sub")); err != nil {
t.Fatalf("Unexpected error on QueueSubscribe with DurableName: %v", err)
}
if err := Wait(ch); err != nil {
t.Fatal("Did not get our message")
}
}
func TestBasicPubSub(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
sc := NewDefaultConnection(t)
defer sc.Close()
ch := make(chan bool)
received := int32(0)
toSend := int32(500)
hw := []byte("Hello World")
msgMap := make(map[uint64]struct{})
sub, err := sc.Subscribe("foo", func(m *Msg) {
if m.Subject != "foo" {
t.Fatalf("Expected subject of 'foo', got '%s'\n", m.Subject)
}
if !bytes.Equal(m.Data, hw) {
t.Fatalf("Wrong payload, got %q\n", m.Data)
}
// Make sure Seq and Timestamp are set
if m.Sequence == 0 {
t.Fatalf("Expected Sequence to be set\n")
}
if m.Timestamp == 0 {
t.Fatalf("Expected timestamp to be set\n")
}
if _, ok := msgMap[m.Sequence]; ok {
t.Fatalf("Detected duplicate for sequence: %d\n", m.Sequence)
}
msgMap[m.Sequence] = struct{}{}
if nr := atomic.AddInt32(&received, 1); nr >= int32(toSend) {
ch <- true
}
})
if err != nil {
t.Fatalf("Unexpected error on Subscribe, got %v", err)
}
defer sub.Unsubscribe()
for i := int32(0); i < toSend; i++ {
if err := sc.Publish("foo", hw); err != nil {
t.Fatalf("Received error on publish: %v\n", err)
}
}
if err := WaitTime(ch, 1*time.Second); err != nil {
t.Fatal("Did not receive our messages")
}
}
func TestBasicPubQueueSub(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
sc := NewDefaultConnection(t)
defer sc.Close()
ch := make(chan bool)
received := int32(0)
toSend := int32(100)
hw := []byte("Hello World")
sub, err := sc.QueueSubscribe("foo", "bar", func(m *Msg) {
if m.Subject != "foo" {
t.Fatalf("Expected subject of 'foo', got '%s'\n", m.Subject)
}
if !bytes.Equal(m.Data, hw) {
t.Fatalf("Wrong payload, got %q\n", m.Data)
}
// Make sure Seq and Timestamp are set
if m.Sequence == 0 {
t.Fatalf("Expected Sequence to be set\n")
}
if m.Timestamp == 0 {
t.Fatalf("Expected timestamp to be set\n")
}
if nr := atomic.AddInt32(&received, 1); nr >= int32(toSend) {
ch <- true
}
})
if err != nil {
t.Fatalf("Unexpected error on Subscribe, got %v", err)
}
defer sub.Unsubscribe()
for i := int32(0); i < toSend; i++ {
sc.Publish("foo", hw)
}
if err := WaitTime(ch, 1*time.Second); err != nil {
t.Fatal("Did not receive our messages")
}
}
func TestSubscriptionStartPositionLast(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
sc := NewDefaultConnection(t)
defer sc.Close()
// Publish ten messages
for i := 0; i < 10; i++ {
data := []byte(fmt.Sprintf("%d", i))
sc.Publish("foo", data)
}
ch := make(chan bool)
received := int32(0)
mcb := func(m *Msg) {
atomic.AddInt32(&received, 1)
if m.Sequence != 10 {
t.Fatalf("Wrong sequence received: got %d vs. %d\n", m.Sequence, 10)
}
ch <- true
}
// Now subscribe and set start position to last received.
sub, err := sc.Subscribe("foo", mcb, StartWithLastReceived())
if err != nil {
t.Fatalf("Unexpected error on Subscribe, got %v", err)
}
defer sub.Unsubscribe()
// Check for sub setup
rsub := sub.(*subscription)
if rsub.opts.StartAt != pb.StartPosition_LastReceived {
t.Fatalf("Incorrect StartAt state: %s\n", rsub.opts.StartAt)
}
if err := Wait(ch); err != nil {
t.Fatal("Did not receive our message")
}
if received > int32(1) {
t.Fatalf("Should have received only 1 message, but got %d\n", received)
}
}
func TestSubscriptionStartAtSequence(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
sc := NewDefaultConnection(t)
defer sc.Close()
// Publish ten messages
for i := 1; i <= 10; i++ {
data := []byte(fmt.Sprintf("%d", i))
sc.Publish("foo", data)
}
ch := make(chan bool)
received := int32(0)
shouldReceive := int32(5)
// Capture the messages that are delivered.
savedMsgs := make([]*Msg, 0, 5)
mcb := func(m *Msg) {
savedMsgs = append(savedMsgs, m)
if nr := atomic.AddInt32(&received, 1); nr >= int32(shouldReceive) {
ch <- true
}
}
// Now subscribe and set start position to #6, so should received 6-10.
sub, err := sc.Subscribe("foo", mcb, StartAtSequence(6))
if err != nil {
t.Fatalf("Expected no error on Subscribe, got %v\n", err)
}
defer sub.Unsubscribe()
// Check for sub setup
rsub := sub.(*subscription)
if rsub.opts.StartAt != pb.StartPosition_SequenceStart {
t.Fatalf("Incorrect StartAt state: %s\n", rsub.opts.StartAt)
}
if err := Wait(ch); err != nil {
t.Fatal("Did not receive our messages")
}
// Check we received them in order.
for i, seq := 0, uint64(6); i < 5; i++ {
m := savedMsgs[i]
// Check Sequence
if m.Sequence != seq {
t.Fatalf("Expected seq: %d, got %d\n", seq, m.Sequence)
}
// Check payload
dseq, _ := strconv.Atoi(string(m.Data))
if dseq != int(seq) {
t.Fatalf("Expected payload: %d, got %d\n", seq, dseq)
}
seq++
}
}
func TestSubscriptionStartAtTime(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
sc := NewDefaultConnection(t)
defer sc.Close()
// Publish first 5
for i := 1; i <= 5; i++ {
data := []byte(fmt.Sprintf("%d", i))
sc.Publish("foo", data)
}
// Buffer each side so slow tests still work.
time.Sleep(250 * time.Millisecond)
startTime := time.Now()
time.Sleep(250 * time.Millisecond)
// Publish last 5
for i := 6; i <= 10; i++ {
data := []byte(fmt.Sprintf("%d", i))
sc.Publish("foo", data)
}
ch := make(chan bool)
received := int32(0)
shouldReceive := int32(5)
// Capture the messages that are delivered.
savedMsgs := make([]*Msg, 0, 5)
mcb := func(m *Msg) {
savedMsgs = append(savedMsgs, m)
if nr := atomic.AddInt32(&received, 1); nr >= int32(shouldReceive) {
ch <- true
}
}
// Now subscribe and set start position to #6, so should received 6-10.
sub, err := sc.Subscribe("foo", mcb, StartAtTime(startTime))
if err != nil {
t.Fatalf("Expected no error on Subscribe, got %v\n", err)
}
defer sub.Unsubscribe()
// Check for sub setup
rsub := sub.(*subscription)
if rsub.opts.StartAt != pb.StartPosition_TimeDeltaStart {
t.Fatalf("Incorrect StartAt state: %s\n", rsub.opts.StartAt)
}
if err := Wait(ch); err != nil {
t.Fatal("Did not receive our messages")
}
// Check we received them in order.
for i, seq := 0, uint64(6); i < 5; i++ {
m := savedMsgs[i]
// Check time is always greater than startTime
if m.Timestamp < startTime.UnixNano() {
t.Fatalf("Expected all messages to have timestamp > startTime.")
}
// Check Sequence
if m.Sequence != seq {
t.Fatalf("Expected seq: %d, got %d\n", seq, m.Sequence)
}
// Check payload
dseq, _ := strconv.Atoi(string(m.Data))
if dseq != int(seq) {
t.Fatalf("Expected payload: %d, got %d\n", seq, dseq)
}
seq++
}
// Now test Ago helper
delta := time.Since(startTime)
atomic.StoreInt32(&received, 0)
sub, err = sc.Subscribe("foo", mcb, StartAtTimeDelta(delta))
if err != nil {
t.Fatalf("Expected no error on Subscribe, got %v\n", err)
}
defer sub.Unsubscribe()
if err := Wait(ch); err != nil {
t.Fatal("Did not receive our messages")
}
}
func TestSubscriptionStartAt(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
sc := NewDefaultConnection(t)
defer sc.Close()
// Publish ten messages
for i := 1; i <= 10; i++ {
sc.Publish("foo", []byte("hello"))
}
ch := make(chan bool)
received := 0
mcb := func(m *Msg) {
received++
if received == 10 {
ch <- true
}
}
// Now subscribe and set start position to sequence. It should be
// sequence 0
sub, err := sc.Subscribe("foo", mcb, StartAt(pb.StartPosition_SequenceStart))
if err != nil {
t.Fatalf("Expected no error on Subscribe, got %v", err)
}
defer sub.Unsubscribe()
// Check for sub setup
rsub := sub.(*subscription)
if rsub.opts.StartAt != pb.StartPosition_SequenceStart {
t.Fatalf("Incorrect StartAt state: %s\n", rsub.opts.StartAt)
}
if err := Wait(ch); err != nil {
t.Fatal("Did not receive our messages")
}
}
func TestSubscriptionStartAtFirst(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
sc := NewDefaultConnection(t)
defer sc.Close()
// Publish ten messages
for i := 1; i <= 10; i++ {
data := []byte(fmt.Sprintf("%d", i))
sc.Publish("foo", data)
}
ch := make(chan bool)
received := int32(0)
shouldReceive := int32(10)
// Capture the messages that are delivered.
savedMsgs := make([]*Msg, 0, 10)
mcb := func(m *Msg) {
savedMsgs = append(savedMsgs, m)
if nr := atomic.AddInt32(&received, 1); nr >= int32(shouldReceive) {
ch <- true
}
}
// Now subscribe and set start position to #6, so should received 6-10.
sub, err := sc.Subscribe("foo", mcb, DeliverAllAvailable())
if err != nil {
t.Fatalf("Expected no error on Subscribe, got %v\n", err)
}
defer sub.Unsubscribe()
// Check for sub setup
rsub := sub.(*subscription)
if rsub.opts.StartAt != pb.StartPosition_First {
t.Fatalf("Incorrect StartAt state: %s\n", rsub.opts.StartAt)
}
if err := Wait(ch); err != nil {
t.Fatal("Did not receive our messages")
}
if received != shouldReceive {
t.Fatalf("Expected %d msgs but received %d\n", shouldReceive, received)
}
// Check we received them in order.
for i, seq := 0, uint64(1); i < 10; i++ {
m := savedMsgs[i]
// Check Sequence
if m.Sequence != seq {
t.Fatalf("Expected seq: %d, got %d\n", seq, m.Sequence)
}
// Check payload
dseq, _ := strconv.Atoi(string(m.Data))
if dseq != int(seq) {
t.Fatalf("Expected payload: %d, got %d\n", seq, dseq)
}
seq++
}
}
func TestUnsubscribe(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
sc := NewDefaultConnection(t)
defer sc.Close()
// Create a valid one
sc.Subscribe("foo", nil)
// Now subscribe, but we will unsubscribe before sending any messages.
sub, err := sc.Subscribe("foo", func(m *Msg) {
t.Fatalf("Did not expect to receive any messages\n")
})
if err != nil {
t.Fatalf("Expected no error on Subscribe, got %v\n", err)
}
// Create another valid one
sc.Subscribe("foo", nil)
// Unsubscribe middle one.
err = sub.Unsubscribe()
if err != nil {
t.Fatalf("Expected no errors from unsubscribe: got %v\n", err)
}
// Do it again, should not dump, but should get error.
err = sub.Unsubscribe()
if err == nil || err != ErrBadSubscription {
t.Fatalf("Expected a bad subscription err, got %v\n", err)
}
// Publish ten messages
for i := 1; i <= 10; i++ {
data := []byte(fmt.Sprintf("%d", i))
sc.Publish("foo", data)
}
sc.Close()
sc = NewDefaultConnection(t)
defer sc.Close()
sub1, err := sc.Subscribe("foo", func(_ *Msg) {})
if err != nil {
t.Fatalf("Unexpected error on subscribe: %v", err)
}
sub2, err := sc.Subscribe("foo", func(_ *Msg) {})
if err != nil {
t.Fatalf("Unexpected error on subscribe: %v", err)
}
// Override clientID to get an error on Subscription.Close() and Unsubscribe()
sc.(*conn).Lock()
sc.(*conn).clientID = "foobar"
sc.(*conn).Unlock()
if err := sub1.Close(); err == nil || !strings.Contains(err.Error(), "unknown") {
t.Fatalf("Expected error about unknown clientID, got %v", err)
}
if err := sub2.Close(); err == nil || !strings.Contains(err.Error(), "unknown") {
t.Fatalf("Expected error about unknown clientID, got %v", err)
}
}
func TestUnsubscribeWhileConnClosing(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
sc, err := Connect(clusterName, clientName, PubAckWait(50*time.Millisecond))
if err != nil {
t.Fatalf("Expected to connect correctly, got err %v\n", err)
}
defer sc.Close()
sub, err := sc.Subscribe("foo", nil)
if err != nil {
t.Fatalf("Expected no error on Subscribe, got %v\n", err)
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
time.Sleep(time.Duration(rand.Intn(50)) * time.Millisecond)
sc.Close()
wg.Done()
}()
// Unsubscribe
sub.Unsubscribe()
wg.Wait()
}
func TestDupClientID(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
sc := NewDefaultConnection(t)
defer sc.Close()
if _, err := Connect(clusterName, clientName); err == nil {
t.Fatal("Expected to get an error for duplicate clientID")
}
}
func TestClose(t *testing.T) {
// Run a NATS Streaming server
s := RunServer(clusterName)
defer s.Shutdown()
sc := NewDefaultConnection(t)
defer sc.Close()
sub, err := sc.Subscribe("foo", func(m *Msg) {
t.Fatalf("Did not expect to receive any messages\n")
})
if err != nil {
t.Fatalf("Expected no errors when subscribing, got %v\n", err)
}
err = sc.Close()
if err != nil {
t.Fatalf("Did not expect error on Close(), got %v\n", err)
}
if _, err := sc.PublishAsync("foo", []byte("Hello World!"), nil); err == nil || err != ErrConnectionClosed {
t.Fatalf("Expected an ErrConnectionClosed on publish async to a closed connection, got %v", err)
}
if err := sc.Publish("foo", []byte("Hello World!")); err == nil || err != ErrConnectionClosed {
t.Fatalf("Expected an ErrConnectionClosed error on publish to a closed connection, got %v", err)
}
if err := sub.Unsubscribe(); err == nil || err != ErrConnectionClosed {
t.Fatalf("Expected an ErrConnectionClosed error on unsubscribe to a closed connection, got %v", err)
}