/
conn_test.go
2552 lines (2235 loc) · 64.6 KB
/
conn_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 2012-2022 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 (
"bufio"
"bytes"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/nats-io/nats-server/v2/server"
"github.com/nats-io/nats-server/v2/test"
"github.com/nats-io/nats.go"
)
func TestDefaultConnection(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
nc.Close()
}
func TestConnectionStatus(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
if nc.Status() != nats.CONNECTED || nc.Status().String() != "CONNECTED" {
t.Fatal("Should have status set to CONNECTED")
}
if !nc.IsConnected() {
t.Fatal("Should have status set to CONNECTED")
}
nc.Close()
if nc.Status() != nats.CLOSED || nc.Status().String() != "CLOSED" {
t.Fatal("Should have status set to CLOSED")
}
if !nc.IsClosed() {
t.Fatal("Should have status set to CLOSED")
}
}
func TestConnClosedCB(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
ch := make(chan bool)
o := nats.GetDefaultOptions()
o.Url = nats.DefaultURL
o.ClosedCB = func(_ *nats.Conn) {
ch <- true
}
nc, err := o.Connect()
if err != nil {
t.Fatalf("Should have connected ok: %v", err)
}
nc.Close()
if e := Wait(ch); e != nil {
t.Fatalf("Closed callback not triggered\n")
}
}
func TestCloseDisconnectedErrCB(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
ch := make(chan bool)
o := nats.GetDefaultOptions()
o.Url = nats.DefaultURL
o.AllowReconnect = false
o.DisconnectedErrCB = func(_ *nats.Conn, _ error) {
ch <- true
}
nc, err := o.Connect()
if err != nil {
t.Fatalf("Should have connected ok: %v", err)
}
nc.Close()
if e := Wait(ch); e != nil {
t.Fatal("Disconnected callback not triggered")
}
}
func TestServerStopDisconnectedErrCB(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
ch := make(chan bool)
o := nats.GetDefaultOptions()
o.Url = nats.DefaultURL
o.AllowReconnect = false
o.DisconnectedErrCB = func(nc *nats.Conn, _ error) {
ch <- true
}
nc, err := o.Connect()
if err != nil {
t.Fatalf("Should have connected ok: %v", err)
}
defer nc.Close()
s.Shutdown()
if e := Wait(ch); e != nil {
t.Fatalf("Disconnected callback not triggered\n")
}
}
func TestServerSecureConnections(t *testing.T) {
s, opts := RunServerWithConfig("./configs/tls.conf")
defer s.Shutdown()
endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
secureURL := fmt.Sprintf("nats://%s:%s@%s/", opts.Username, opts.Password, endpoint)
// Make sure this succeeds
nc, err := nats.Connect(secureURL, nats.Secure(), nats.RootCAs("./configs/certs/ca.pem"))
if err != nil {
t.Fatalf("Failed to create secure (TLS) connection: %v", err)
}
defer nc.Close()
omsg := []byte("Hello World")
checkRecv := make(chan bool)
received := 0
nc.Subscribe("foo", func(m *nats.Msg) {
received++
if !bytes.Equal(m.Data, omsg) {
t.Fatal("Message received does not match")
}
checkRecv <- true
})
err = nc.Publish("foo", omsg)
if err != nil {
t.Fatalf("Failed to publish on secure (TLS) connection: %v", err)
}
nc.Flush()
state, err := nc.TLSConnectionState()
if err != nil {
t.Fatalf("Expected connection state: %v", err)
}
if !state.HandshakeComplete {
t.Fatalf("Expected valid connection state")
}
if err := Wait(checkRecv); err != nil {
t.Fatal("Failed receiving message")
}
nc.Close()
// Server required, but not specified in Connect(), should switch automatically
nc, err = nats.Connect(secureURL, nats.RootCAs("./configs/certs/ca.pem"))
if err != nil {
t.Fatalf("Failed to create secure (TLS) connection: %v", err)
}
nc.Close()
// Test flag mismatch
// Wanted but not available..
ds := RunDefaultServer()
defer ds.Shutdown()
nc, err = nats.Connect(nats.DefaultURL, nats.Secure(), nats.RootCAs("./configs/certs/ca.pem"))
if err == nil || nc != nil || err != nats.ErrSecureConnWanted {
if nc != nil {
nc.Close()
}
t.Fatalf("Should have failed to create connection: %v", err)
}
// Let's be more TLS correct and verify servername, endpoint etc.
// Now do more advanced checking, verifying servername and using rootCA.
// Setup our own TLSConfig using RootCA from our self signed cert.
rootPEM, err := ioutil.ReadFile("./configs/certs/ca.pem")
if err != nil || rootPEM == nil {
t.Fatalf("failed to read root certificate")
}
pool := x509.NewCertPool()
ok := pool.AppendCertsFromPEM([]byte(rootPEM))
if !ok {
t.Fatal("failed to parse root certificate")
}
tls1 := &tls.Config{
ServerName: opts.Host,
RootCAs: pool,
MinVersion: tls.VersionTLS12,
}
nc, err = nats.Connect(secureURL, nats.Secure(tls1), nats.RootCAs("./configs/certs/ca.pem"))
if err != nil {
t.Fatalf("Got an error on Connect with Secure Options: %+v\n", err)
}
defer nc.Close()
tls2 := &tls.Config{
ServerName: "OtherHostName",
RootCAs: pool,
MinVersion: tls.VersionTLS12,
}
nc2, err := nats.Connect(secureURL, nats.Secure(tls1, tls2))
if err == nil {
nc2.Close()
t.Fatal("Was expecting an error!")
}
}
func TestClientCertificate(t *testing.T) {
s, opts := RunServerWithConfig("./configs/tlsverify.conf")
defer s.Shutdown()
endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
secureURL := fmt.Sprintf("nats://%s", endpoint)
// Make sure this fails
nc, err := nats.Connect(secureURL, nats.Secure())
if err == nil {
nc.Close()
t.Fatal("Should have failed (TLS) connection without client certificate")
}
// Check parameters validity
nc, err = nats.Connect(secureURL, nats.ClientCert("", ""))
if err == nil {
nc.Close()
t.Fatal("Should have failed due to invalid parameters")
}
// Should fail because wrong key
nc, err = nats.Connect(secureURL,
nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/key.pem"))
if err == nil {
nc.Close()
t.Fatal("Should have failed due to invalid key")
}
// Should fail because no CA
nc, err = nats.Connect(secureURL,
nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/client-key.pem"))
if err == nil {
nc.Close()
t.Fatal("Should have failed due to missing ca")
}
nc, err = nats.Connect(secureURL,
nats.RootCAs("./configs/certs/ca.pem"),
nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/client-key.pem"))
if err != nil {
t.Fatalf("Failed to create (TLS) connection: %v", err)
}
defer nc.Close()
omsg := []byte("Hello!")
checkRecv := make(chan bool)
received := 0
nc.Subscribe("foo", func(m *nats.Msg) {
received++
if !bytes.Equal(m.Data, omsg) {
t.Fatal("Message received does not match")
}
checkRecv <- true
})
err = nc.Publish("foo", omsg)
if err != nil {
t.Fatalf("Failed to publish on secure (TLS) connection: %v", err)
}
nc.Flush()
if err := Wait(checkRecv); err != nil {
t.Fatal("Failed to receive message")
}
}
func TestServerTLSHintConnections(t *testing.T) {
s, opts := RunServerWithConfig("./configs/tls.conf")
defer s.Shutdown()
endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
secureURL := fmt.Sprintf("tls://%s:%s@%s/", opts.Username, opts.Password, endpoint)
nc, err := nats.Connect(secureURL, nats.RootCAs("./configs/certs/badca.pem"))
if err == nil {
nc.Close()
t.Fatal("Expected an error from bad RootCA file")
}
nc, err = nats.Connect(secureURL, nats.RootCAs("./configs/certs/ca.pem"))
if err != nil {
t.Fatalf("Failed to create secure (TLS) connection: %v", err)
}
defer nc.Close()
}
func TestClosedConnections(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
nc := NewDefaultConnection(t)
defer nc.Close()
sub, _ := nc.SubscribeSync("foo")
if sub == nil {
t.Fatal("Failed to create valid subscription")
}
// Test all API endpoints do the right thing with a closed connection.
nc.Close()
if err := nc.Publish("foo", nil); err != nats.ErrConnectionClosed {
t.Fatalf("Publish on closed conn did not fail properly: %v\n", err)
}
if err := nc.PublishMsg(&nats.Msg{Subject: "foo"}); err != nats.ErrConnectionClosed {
t.Fatalf("PublishMsg on closed conn did not fail properly: %v\n", err)
}
if err := nc.Flush(); err != nats.ErrConnectionClosed {
t.Fatalf("Flush on closed conn did not fail properly: %v\n", err)
}
_, err := nc.Subscribe("foo", nil)
if err != nats.ErrConnectionClosed {
t.Fatalf("Subscribe on closed conn did not fail properly: %v\n", err)
}
_, err = nc.SubscribeSync("foo")
if err != nats.ErrConnectionClosed {
t.Fatalf("SubscribeSync on closed conn did not fail properly: %v\n", err)
}
_, err = nc.QueueSubscribe("foo", "bar", nil)
if err != nats.ErrConnectionClosed {
t.Fatalf("QueueSubscribe on closed conn did not fail properly: %v\n", err)
}
_, err = nc.Request("foo", []byte("help"), 10*time.Millisecond)
if err != nats.ErrConnectionClosed {
t.Fatalf("Request on closed conn did not fail properly: %v\n", err)
}
if _, err = sub.NextMsg(10); err != nats.ErrConnectionClosed {
t.Fatalf("NextMessage on closed conn did not fail properly: %v\n", err)
}
if err = sub.Unsubscribe(); err != nats.ErrConnectionClosed {
t.Fatalf("Unsubscribe on closed conn did not fail properly: %v\n", err)
}
}
func TestErrOnConnectAndDeadlock(t *testing.T) {
// We will hand run a fake server that will timeout and not return a proper
// INFO proto. This is to test that we do not deadlock. Issue #18
l, e := net.Listen("tcp", ":0")
if e != nil {
t.Fatal("Could not listen on an ephemeral port")
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
errCh := make(chan error, 1)
go func() {
conn, err := l.Accept()
if err != nil {
errCh <- fmt.Errorf("error accepting client connection: %v", err)
return
}
errCh <- nil
defer conn.Close()
// Send back a mal-formed INFO.
conn.Write([]byte("INFOZ \r\n"))
}()
go func() {
natsURL := fmt.Sprintf("nats://127.0.0.1:%d/", addr.Port)
nc, err := nats.Connect(natsURL)
if err == nil {
nc.Close()
errCh <- fmt.Errorf("expected bad INFO err, got none")
return
}
errCh <- nil
}()
// Setup a timer to watch for deadlock
select {
case e := <-errCh:
if e != nil {
t.Fatal(e.Error())
}
case <-time.After(time.Second):
t.Fatalf("Connect took too long, deadlock?")
}
}
func TestMoreErrOnConnect(t *testing.T) {
l, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal("Could not listen on an ephemeral port")
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
done := make(chan bool)
case1 := make(chan bool)
case2 := make(chan bool)
case3 := make(chan bool)
case4 := make(chan bool)
errCh := make(chan error, 5)
go func() {
for i := 0; i < 5; i++ {
conn, err := l.Accept()
if err != nil {
errCh <- fmt.Errorf("error accepting client connection: %v", err)
return
}
switch i {
case 0:
// Send back a partial INFO and close the connection.
conn.Write([]byte("INFO"))
case 1:
// Send just INFO
conn.Write([]byte("INFO\r\n"))
// Stick around a bit
<-case1
case 2:
info := fmt.Sprintf("INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n", addr.IP, addr.Port)
// Send complete INFO
conn.Write([]byte(info))
// Read connect and ping commands sent from the client
br := bufio.NewReaderSize(conn, 1024)
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
return
}
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected PING from client, got: %s", err)
return
}
// Client expect +OK, send it but then something else than PONG
conn.Write([]byte("+OK\r\n"))
// Stick around a bit
<-case2
case 3:
info := fmt.Sprintf("INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n", addr.IP, addr.Port)
// Send complete INFO
conn.Write([]byte(info))
// Read connect and ping commands sent from the client
br := bufio.NewReaderSize(conn, 1024)
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
return
}
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected PING from client, got: %s", err)
return
}
// Client expect +OK, send it but then something else than PONG
conn.Write([]byte("+OK\r\nXXX\r\n"))
// Stick around a bit
<-case3
case 4:
info := "INFO {'x'}\r\n"
// Send INFO with JSON marshall error
conn.Write([]byte(info))
// Stick around a bit
<-case4
}
conn.Close()
}
// Hang around until asked to quit
<-done
}()
natsURL := fmt.Sprintf("nats://127.0.0.1:%d", addr.Port)
if nc, err := nats.Connect(natsURL, nats.Timeout(20*time.Millisecond)); err == nil {
nc.Close()
t.Fatal("Expected error, got none")
}
if nc, err := nats.Connect(natsURL, nats.Timeout(20*time.Millisecond)); err == nil {
close(case1)
nc.Close()
t.Fatal("Expected error, got none")
}
close(case1)
opts := nats.GetDefaultOptions()
opts.Servers = []string{natsURL}
opts.Timeout = 20 * time.Millisecond
opts.Verbose = true
if nc, err := opts.Connect(); err == nil {
close(case2)
nc.Close()
t.Fatal("Expected error, got none")
}
close(case2)
if nc, err := opts.Connect(); err == nil {
close(case3)
nc.Close()
t.Fatal("Expected error, got none")
}
close(case3)
if nc, err := opts.Connect(); err == nil {
close(case4)
nc.Close()
t.Fatal("Expected error, got none")
}
close(case4)
close(done)
checkErrChannel(t, errCh)
}
func TestErrOnMaxPayloadLimit(t *testing.T) {
expectedMaxPayload := int64(10)
serverInfo := "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":%d}\r\n"
l, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal("Could not listen on an ephemeral port")
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
// Send back an INFO message with custom max payload size on connect.
var conn net.Conn
var err error
errCh := make(chan error, 1)
go func() {
conn, err = l.Accept()
if err != nil {
errCh <- fmt.Errorf("error accepting client connection: %v", err)
return
}
defer conn.Close()
info := fmt.Sprintf(serverInfo, addr.IP, addr.Port, expectedMaxPayload)
conn.Write([]byte(info))
// Read connect and ping commands sent from the client
line := make([]byte, 111)
_, err := conn.Read(line)
if err != nil {
errCh <- fmt.Errorf("expected CONNECT and PING from client, got: %s", err)
return
}
conn.Write([]byte("PONG\r\n"))
// Hang around a bit to not err on EOF in client.
time.Sleep(250 * time.Millisecond)
}()
// Wait for server mock to start
time.Sleep(100 * time.Millisecond)
natsURL := fmt.Sprintf("nats://%s:%d", addr.IP, addr.Port)
opts := nats.GetDefaultOptions()
opts.Servers = []string{natsURL}
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Expected INFO message with custom max payload, got: %s", err)
}
defer nc.Close()
got := nc.MaxPayload()
if got != expectedMaxPayload {
t.Fatalf("Expected MaxPayload to be %d, got: %d", expectedMaxPayload, got)
}
err = nc.Publish("hello", []byte("hello world"))
if err != nats.ErrMaxPayload {
t.Fatalf("Expected to fail trying to send more than max payload, got: %s", err)
}
err = nc.Publish("hello", []byte("a"))
if err != nil {
t.Fatalf("Expected to succeed trying to send less than max payload, got: %s", err)
}
checkErrChannel(t, errCh)
}
func TestConnectVerbose(t *testing.T) {
s := RunDefaultServer()
defer s.Shutdown()
o := nats.GetDefaultOptions()
o.Verbose = true
nc, err := o.Connect()
if err != nil {
t.Fatalf("Should have connected ok: %v", err)
}
nc.Close()
}
func getStacks(all bool) string {
var (
stacks []byte
stacksSize = 10000
n int
)
for {
stacks = make([]byte, stacksSize)
n = runtime.Stack(stacks, all)
if n == stacksSize {
stacksSize *= 2
continue
}
break
}
return string(stacks[:n])
}
func isRunningInAsyncCBDispatcher() error {
strStacks := getStacks(false)
if strings.Contains(strStacks, "asyncCBDispatcher") {
return nil
}
return fmt.Errorf("callback not executed from dispatcher:\n %s", strStacks)
}
func isAsyncDispatcherRunning() bool {
strStacks := getStacks(true)
return strings.Contains(strStacks, "asyncCBDispatcher")
}
func TestCallbacksOrder(t *testing.T) {
authS, authSOpts := RunServerWithConfig("./configs/tls.conf")
defer authS.Shutdown()
s := RunDefaultServer()
defer s.Shutdown()
firstDisconnect := true
dtime1 := time.Time{}
dtime2 := time.Time{}
rtime := time.Time{}
atime1 := time.Time{}
atime2 := time.Time{}
ctime := time.Time{}
cbErrors := make(chan error, 20)
reconnected := make(chan bool)
closed := make(chan bool)
asyncErr := make(chan bool, 2)
recvCh := make(chan bool, 2)
recvCh1 := make(chan bool)
recvCh2 := make(chan bool)
dch := func(nc *nats.Conn) {
if err := isRunningInAsyncCBDispatcher(); err != nil {
cbErrors <- err
return
}
time.Sleep(100 * time.Millisecond)
if firstDisconnect {
firstDisconnect = false
dtime1 = time.Now()
} else {
dtime2 = time.Now()
}
}
rch := func(nc *nats.Conn) {
if err := isRunningInAsyncCBDispatcher(); err != nil {
cbErrors <- err
reconnected <- true
return
}
time.Sleep(50 * time.Millisecond)
rtime = time.Now()
reconnected <- true
}
ech := func(nc *nats.Conn, sub *nats.Subscription, err error) {
if err := isRunningInAsyncCBDispatcher(); err != nil {
cbErrors <- err
asyncErr <- true
return
}
if sub.Subject == "foo" {
time.Sleep(20 * time.Millisecond)
atime1 = time.Now()
} else {
atime2 = time.Now()
}
asyncErr <- true
}
cch := func(nc *nats.Conn) {
if err := isRunningInAsyncCBDispatcher(); err != nil {
cbErrors <- err
closed <- true
return
}
ctime = time.Now()
closed <- true
}
url := net.JoinHostPort(authSOpts.Host, strconv.Itoa(authSOpts.Port))
url = "nats://" + url + "," + nats.DefaultURL
nc, err := nats.Connect(url,
nats.DisconnectHandler(dch),
nats.ReconnectHandler(rch),
nats.ClosedHandler(cch),
nats.ErrorHandler(ech),
nats.ReconnectWait(50*time.Millisecond),
nats.ReconnectJitter(0, 0),
nats.DontRandomize())
if err != nil {
t.Fatalf("Unable to connect: %v\n", err)
}
defer nc.Close()
ncp, err := nats.Connect(nats.DefaultURL,
nats.ReconnectWait(50*time.Millisecond))
if err != nil {
t.Fatalf("Unable to connect: %v\n", err)
}
defer ncp.Close()
// Wait to make sure that if we have closed (incorrectly) the
// asyncCBDispatcher during the connect process, this is caught here.
time.Sleep(time.Second)
s.Shutdown()
s = RunDefaultServer()
defer s.Shutdown()
if err := Wait(reconnected); err != nil {
t.Fatal("Did not get the reconnected callback")
}
var sub1 *nats.Subscription
var sub2 *nats.Subscription
recv := func(m *nats.Msg) {
// Signal that one message is received
recvCh <- true
// We will now block
if m.Subject == "foo" {
<-recvCh1
} else {
<-recvCh2
}
m.Sub.Unsubscribe()
}
sub1, err = nc.Subscribe("foo", recv)
if err != nil {
t.Fatalf("Unable to create subscription: %v\n", err)
}
sub1.SetPendingLimits(1, 100000)
sub2, err = nc.Subscribe("bar", recv)
if err != nil {
t.Fatalf("Unable to create subscription: %v\n", err)
}
sub2.SetPendingLimits(1, 100000)
nc.Flush()
ncp.Publish("foo", []byte("test"))
ncp.Publish("bar", []byte("test"))
ncp.Flush()
// Wait notification that message were received
err = Wait(recvCh)
if err == nil {
err = Wait(recvCh)
}
if err != nil {
t.Fatal("Did not receive message")
}
for i := 0; i < 2; i++ {
ncp.Publish("foo", []byte("test"))
ncp.Publish("bar", []byte("test"))
}
ncp.Flush()
if err := Wait(asyncErr); err != nil {
t.Fatal("Did not get the async callback")
}
if err := Wait(asyncErr); err != nil {
t.Fatal("Did not get the async callback")
}
close(recvCh1)
close(recvCh2)
nc.Close()
if err := Wait(closed); err != nil {
t.Fatal("Did not get the close callback")
}
if len(cbErrors) > 0 {
t.Fatalf("%v", <-cbErrors)
}
if (dtime1 == time.Time{}) || (dtime2 == time.Time{}) || (rtime == time.Time{}) || (atime1 == time.Time{}) || (atime2 == time.Time{}) || (ctime == time.Time{}) {
t.Fatalf("Some callbacks did not fire:\n%v\n%v\n%v\n%v\n%v\n%v", dtime1, rtime, atime1, atime2, dtime2, ctime)
}
if rtime.Before(dtime1) || dtime2.Before(rtime) || atime2.Before(atime1) || ctime.Before(atime2) {
t.Fatalf("Wrong callback order:\n%v\n%v\n%v\n%v\n%v\n%v", dtime1, rtime, atime1, atime2, dtime2, ctime)
}
// Close the other connection
ncp.Close()
// Check that the go routine is gone. Allow plenty of time
// to avoid flappers.
timeout := time.Now().Add(5 * time.Second)
for time.Now().Before(timeout) {
if !isAsyncDispatcherRunning() {
// Good, we are done!
return
}
time.Sleep(50 * time.Millisecond)
}
t.Fatalf("The async callback dispatcher(s) should have stopped")
}
func TestFlushReleaseOnClose(t *testing.T) {
serverInfo := "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n"
l, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal("Could not listen on an ephemeral port")
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
done := make(chan bool)
errCh := make(chan error, 1)
go func() {
conn, err := l.Accept()
if err != nil {
errCh <- fmt.Errorf("error accepting client connection: %v", err)
return
}
defer conn.Close()
info := fmt.Sprintf(serverInfo, addr.IP, addr.Port)
conn.Write([]byte(info))
// Read connect and ping commands sent from the client
br := bufio.NewReaderSize(conn, 1024)
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
return
}
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected PING from client, got: %s", err)
return
}
conn.Write([]byte("PONG\r\n"))
// Hang around until asked to quit
<-done
}()
// Wait for server mock to start
time.Sleep(100 * time.Millisecond)
natsURL := fmt.Sprintf("nats://%s:%d", addr.IP, addr.Port)
opts := nats.GetDefaultOptions()
opts.AllowReconnect = false
opts.Servers = []string{natsURL}
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Expected INFO message with custom max payload, got: %s", err)
}
defer nc.Close()
// First try a FlushTimeout() and make sure we timeout
if err := nc.FlushTimeout(50 * time.Millisecond); err == nil || err != nats.ErrTimeout {
t.Fatalf("Expected a timeout error, got: %v", err)
}
go func() {
time.Sleep(50 * time.Millisecond)
nc.Close()
}()
if err := nc.Flush(); err == nil {
t.Fatal("Expected error on Flush() released by Close()")
}
close(done)
checkErrChannel(t, errCh)
}
func TestMaxPendingOut(t *testing.T) {
serverInfo := "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n"
l, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal("Could not listen on an ephemeral port")
}
tl := l.(*net.TCPListener)
defer tl.Close()
addr := tl.Addr().(*net.TCPAddr)
done := make(chan bool)
cch := make(chan bool)
errCh := make(chan error, 1)
go func() {
conn, err := l.Accept()
if err != nil {
errCh <- fmt.Errorf("error accepting client connection: %v", err)
return
}
defer conn.Close()
info := fmt.Sprintf(serverInfo, addr.IP, addr.Port)
conn.Write([]byte(info))
// Read connect and ping commands sent from the client
br := bufio.NewReaderSize(conn, 1024)
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
return
}
if _, err := br.ReadString('\n'); err != nil {
errCh <- fmt.Errorf("expected PING from client, got: %s", err)
return
}
conn.Write([]byte("PONG\r\n"))
// Hang around until asked to quit
<-done
}()
// Wait for server mock to start
time.Sleep(100 * time.Millisecond)
natsURL := fmt.Sprintf("nats://%s:%d", addr.IP, addr.Port)
opts := nats.GetDefaultOptions()
opts.PingInterval = 20 * time.Millisecond
opts.MaxPingsOut = 2
opts.AllowReconnect = false
opts.ClosedCB = func(_ *nats.Conn) { cch <- true }
opts.Servers = []string{natsURL}
nc, err := opts.Connect()
if err != nil {
t.Fatalf("Expected INFO message with custom max payload, got: %s", err)
}
defer nc.Close()
// After 60 ms, we should have closed the connection
time.Sleep(100 * time.Millisecond)
if err := Wait(cch); err != nil {
t.Fatal("Failed to get ClosedCB")