Debian Codegraph @

test/conn_test.go

raw
1 // Copyright 2012-2026 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package test
15
16 import (
17 "bufio"
18 "bytes"
19 "crypto/tls"
20 "crypto/x509"
21 "errors"
22 "fmt"
23 "io"
24 "net"
25 "os"
26 "runtime"
27 "strings"
28 "sync"
29 "sync/atomic"
30 "testing"
31 "time"
32
33 "github.com/nats-io/nats.go"
34 testservice "github.com/synadia-io/orbit.go/ntf-client"
35 )
36
37 // hostPortFromURL extracts the "host:port" portion of a "nats://host:port" URL.
38 func hostPortFromURL(u string) string {
39 return strings.TrimPrefix(strings.TrimPrefix(u, "nats://"), "tls://")
40 }
41
42 // hostFromURL extracts the host portion of a "nats://host:port" URL.
43 func hostFromURL(u string) string {
44 hp := hostPortFromURL(u)
45 h, _, err := net.SplitHostPort(hp)
46 if err != nil {
47 return hp
48 }
49 return h
50 }
51
52 func derekAuthBody() string {
53 return `authorization {
54 user: derek
55 password: porkchop
56 timeout: 1
57 }`
58 }
59
60 // emptyAccountsBody clears the built-in USERS1..USERS5 / $SYS accounts block.
61 // Pair with WithAuthorization when using a single user/pass to avoid the
62 // "Can not have a single user/pass and accounts" server error.
63 func emptyAccountsBody() string {
64 return `# accounts block intentionally empty; using single user/pass via WithAuthorization`
65 }
66
67 // noSystemAccountBody clears the built-in `system_account: "$SYS"` line.
68 // Pair with emptyAccountsBody when using a single user/pass so the rendered
69 // config has no reference to $SYS at all.
70 func noSystemAccountBody() string {
71 return `# system_account intentionally unset`
72 }
73
74 // singleUserPassOpts returns the CreateOptions needed to render a server with
75 // a single user/pass authorization block and no accounts / system_account
76 // (which would otherwise conflict with the single user/pass).
77 func singleUserPassOpts(authBody string) []testservice.CreateOption {
78 return []testservice.CreateOption{
79 testservice.WithAuthorization(authBody),
80 testservice.WithAccounts(emptyAccountsBody()),
81 testservice.WithSystemAccount(noSystemAccountBody()),
82 }
83 }
84
85 func TestDefaultConnection(t *testing.T) {
86 withServer(t, func(t *testing.T, nc *nats.Conn) {
87 nc.Close()
88 })
89 }
90
91 func TestConnectionStatus(t *testing.T) {
92 withServer(t, func(t *testing.T, nc *nats.Conn) {
93 if nc.Status() != nats.CONNECTED || nc.Status().String() != "CONNECTED" {
94 t.Fatal("Should have status set to CONNECTED")
95 }
96
97 if !nc.IsConnected() {
98 t.Fatal("Should have status set to CONNECTED")
99 }
100 nc.Close()
101 if nc.Status() != nats.CLOSED || nc.Status().String() != "CLOSED" {
102 t.Fatal("Should have status set to CLOSED")
103 }
104 if !nc.IsClosed() {
105 t.Fatal("Should have status set to CLOSED")
106 }
107 })
108 }
109
110 func TestConnClosedCB(t *testing.T) {
111 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
112 ch := make(chan bool)
113 o := nats.GetDefaultOptions()
114 o.Url = inst.Servers[0].URL
115 o.ClosedCB = func(_ *nats.Conn) {
116 ch <- true
117 }
118 nc, err := o.Connect()
119 if err != nil {
120 t.Fatalf("Should have connected ok: %v", err)
121 }
122 nc.Close()
123 if e := Wait(ch); e != nil {
124 t.Fatalf("Closed callback not triggered\n")
125 }
126 })
127 }
128
129 func TestCloseDisconnectedErrCB(t *testing.T) {
130 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
131 ch := make(chan bool)
132 o := nats.GetDefaultOptions()
133 o.Url = inst.Servers[0].URL
134 o.AllowReconnect = false
135 o.DisconnectedErrCB = func(_ *nats.Conn, _ error) {
136 ch <- true
137 }
138 nc, err := o.Connect()
139 if err != nil {
140 t.Fatalf("Should have connected ok: %v", err)
141 }
142 nc.Close()
143 if e := Wait(ch); e != nil {
144 t.Fatal("Disconnected callback not triggered")
145 }
146 })
147 }
148
149 func TestServerStopDisconnectedErrCB(t *testing.T) {
150 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
151 ch := make(chan bool)
152 o := nats.GetDefaultOptions()
153 o.Url = inst.Servers[0].URL
154 o.AllowReconnect = false
155 o.DisconnectedErrCB = func(nc *nats.Conn, _ error) {
156 ch <- true
157 }
158 nc, err := o.Connect()
159 if err != nil {
160 t.Fatalf("Should have connected ok: %v", err)
161 }
162 defer nc.Close()
163
164 inst.StopServer(t, inst.Servers[0])
165 if e := Wait(ch); e != nil {
166 t.Fatalf("Disconnected callback not triggered\n")
167 }
168 })
169 }
170
171 func TestServerSecureConnections(t *testing.T) {
172 c := newTester(t)
173 opts := append([]testservice.CreateOption{managedTLSOpts(t, testservice.TLSServerOnly())}, singleUserPassOpts(derekAuthBody())...)
174 inst := c.CreateServer(t, false, opts...)
175 t.Cleanup(func() { inst.Destroy(t) })
176 caPath, _, _ := tlsCertFiles(t, inst)
177
178 hostPort := hostPortFromURL(inst.Servers[0].URL)
179 host := hostFromURL(inst.Servers[0].URL)
180 secureURL := fmt.Sprintf("nats://derek:porkchop@%s/", hostPort)
181
182 // Make sure this succeeds
183 nc, err := nats.Connect(secureURL, nats.Secure(), nats.RootCAs(caPath))
184 if err != nil {
185 t.Fatalf("Failed to create secure (TLS) connection: %v", err)
186 }
187 defer nc.Close()
188
189 omsg := []byte("Hello World")
190 checkRecv := make(chan bool)
191
192 received := 0
193 nc.Subscribe("foo", func(m *nats.Msg) {
194 received++
195 if !bytes.Equal(m.Data, omsg) {
196 t.Fatal("Message received does not match")
197 }
198 checkRecv <- true
199 })
200 err = nc.Publish("foo", omsg)
201 if err != nil {
202 t.Fatalf("Failed to publish on secure (TLS) connection: %v", err)
203 }
204 nc.Flush()
205
206 state, err := nc.TLSConnectionState()
207 if err != nil {
208 t.Fatalf("Expected connection state: %v", err)
209 }
210 if !state.HandshakeComplete {
211 t.Fatalf("Expected valid connection state")
212 }
213
214 if err := Wait(checkRecv); err != nil {
215 t.Fatal("Failed receiving message")
216 }
217
218 nc.Close()
219
220 // Server required, but not specified in Connect(), should switch automatically
221 nc, err = nats.Connect(secureURL, nats.RootCAs(caPath))
222 if err != nil {
223 t.Fatalf("Failed to create secure (TLS) connection: %v", err)
224 }
225 nc.Close()
226
227 // Test flag mismatch
228 // Wanted but not available..
229 dInst := c.CreateServer(t, false)
230 t.Cleanup(func() { dInst.Destroy(t) })
231
232 nc, err = nats.Connect(dInst.Servers[0].URL, nats.Secure(), nats.RootCAs(caPath))
233 if err == nil || nc != nil || err != nats.ErrSecureConnWanted {
234 if nc != nil {
235 nc.Close()
236 }
237 t.Fatalf("Should have failed to create connection: %v", err)
238 }
239
240 // Let's be more TLS correct and verify servername, endpoint etc.
241 // Now do more advanced checking, verifying servername and using rootCA.
242 // Setup our own TLSConfig using RootCA from our self signed cert.
243 rootPEM, err := os.ReadFile(caPath)
244 if err != nil || rootPEM == nil {
245 t.Fatalf("failed to read root certificate")
246 }
247 pool := x509.NewCertPool()
248 ok := pool.AppendCertsFromPEM([]byte(rootPEM))
249 if !ok {
250 t.Fatal("failed to parse root certificate")
251 }
252
253 tls1 := &tls.Config{
254 ServerName: host,
255 RootCAs: pool,
256 MinVersion: tls.VersionTLS12,
257 }
258
259 nc, err = nats.Connect(secureURL, nats.Secure(tls1), nats.RootCAs(caPath))
260 if err != nil {
261 t.Fatalf("Got an error on Connect with Secure Options: %+v\n", err)
262 }
263 defer nc.Close()
264
265 tls2 := &tls.Config{
266 ServerName: "OtherHostName",
267 RootCAs: pool,
268 MinVersion: tls.VersionTLS12,
269 }
270
271 nc2, err := nats.Connect(secureURL, nats.Secure(tls1, tls2))
272 if err == nil {
273 nc2.Close()
274 t.Fatal("Was expecting an error!")
275 }
276 }
277
278 func TestClientTLSConfig(t *testing.T) {
279 c := newTester(t)
280 inst := c.CreateServer(t, false, managedTLSOpts(t))
281 t.Cleanup(func() { inst.Destroy(t) })
282 caPath, certPath, keyPath := tlsCertFiles(t, inst)
283
284 secureURL := fmt.Sprintf("nats://%s", hostPortFromURL(inst.Servers[0].URL))
285
286 // Make sure this fails
287 nc, err := nats.Connect(secureURL, nats.Secure())
288 if err == nil {
289 nc.Close()
290 t.Fatal("Should have failed (TLS) connection without client certificate")
291 }
292 cert, err := os.ReadFile(certPath)
293 if err != nil {
294 t.Fatal("Failed to read client certificate")
295 }
296 key, err := os.ReadFile(keyPath)
297 if err != nil {
298 t.Fatal("Failed to read client key")
299 }
300 rootCAs, err := os.ReadFile(caPath)
301 if err != nil {
302 t.Fatal("Failed to read root CAs")
303 }
304
305 certCB := func() (tls.Certificate, error) {
306 cert, err := tls.X509KeyPair(cert, key)
307 if err != nil {
308 return tls.Certificate{}, fmt.Errorf("nats: error loading client certificate: %w", err)
309 }
310 cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
311 if err != nil {
312 return tls.Certificate{}, fmt.Errorf("nats: error parsing client certificate: %w", err)
313 }
314 return cert, nil
315 }
316
317 caCB := func() (*x509.CertPool, error) {
318 pool := x509.NewCertPool()
319 ok := pool.AppendCertsFromPEM(rootCAs)
320 if !ok {
321 return nil, errors.New("nats: failed to parse root certificate from")
322 }
323 return pool, nil
324 }
325
326 // Check parameters validity
327 _, err = nats.Connect(secureURL, nats.ClientTLSConfig(nil, nil))
328 if !errors.Is(err, nats.ErrClientCertOrRootCAsRequired) {
329 t.Fatalf("Expected error %q, got %q", nats.ErrClientCertOrRootCAsRequired, err)
330 }
331
332 certErr := &tls.CertificateVerificationError{}
333 // Should fail because of missing CA
334 _, err = nats.Connect(secureURL,
335 nats.ClientCert(certPath, keyPath))
336 if ok := errors.As(err, &certErr); !ok {
337 t.Fatalf("Expected error %q, got %q", nats.ErrClientCertOrRootCAsRequired, err)
338 }
339
340 // Should fail because of missing certificate
341 _, err = nats.Connect(secureURL,
342 nats.ClientTLSConfig(nil, caCB))
343 if err == nil {
344 t.Fatal("Expected connection to fail due to missing certificate")
345 }
346 errStr := err.Error()
347 if !strings.Contains(errStr, "bad certificate") &&
348 !strings.Contains(errStr, "certificate required") &&
349 !strings.Contains(errStr, "connection reset by peer") &&
350 !strings.Contains(errStr, "after TLS handshake") {
351 t.Fatalf("Expected missing certificate error; got: %s", err)
352 }
353
354 nc, err = nats.Connect(secureURL,
355 nats.ClientTLSConfig(certCB, caCB))
356 if err != nil {
357 t.Fatalf("Failed to create (TLS) connection: %v", err)
358 }
359 defer nc.Close()
360
361 omsg := []byte("Hello!")
362 checkRecv := make(chan bool)
363
364 received := 0
365 nc.Subscribe("foo", func(m *nats.Msg) {
366 received++
367 if !bytes.Equal(m.Data, omsg) {
368 t.Fatal("Message received does not match")
369 }
370 checkRecv <- true
371 })
372 err = nc.Publish("foo", omsg)
373 if err != nil {
374 t.Fatalf("Failed to publish on secure (TLS) connection: %v", err)
375 }
376 nc.Flush()
377
378 if err := Wait(checkRecv); err != nil {
379 t.Fatal("Failed to receive message")
380 }
381 }
382
383 func TestClientCertificate(t *testing.T) {
384 c := newTester(t)
385 inst := c.CreateServer(t, false, managedTLSOpts(t))
386 t.Cleanup(func() { inst.Destroy(t) })
387 caPath, certPath, keyPath := tlsCertFiles(t, inst)
388
389 secureURL := fmt.Sprintf("nats://%s", hostPortFromURL(inst.Servers[0].URL))
390
391 // Make sure this fails
392 nc, err := nats.Connect(secureURL, nats.Secure())
393 if err == nil {
394 nc.Close()
395 t.Fatal("Should have failed (TLS) connection without client certificate")
396 }
397
398 // Check parameters validity
399 nc, err = nats.Connect(secureURL, nats.ClientCert("", ""))
400 if err == nil {
401 nc.Close()
402 t.Fatal("Should have failed due to invalid parameters")
403 }
404
405 // Should fail because wrong key (CA pem reused as a "key" — parses but X509KeyPair mismatch)
406 nc, err = nats.Connect(secureURL,
407 nats.ClientCert(certPath, caPath))
408 if err == nil {
409 nc.Close()
410 t.Fatal("Should have failed due to invalid key")
411 }
412
413 // Should fail because no CA
414 nc, err = nats.Connect(secureURL,
415 nats.ClientCert(certPath, keyPath))
416 if err == nil {
417 nc.Close()
418 t.Fatal("Should have failed due to missing ca")
419 }
420
421 nc, err = nats.Connect(secureURL,
422 nats.RootCAs(caPath),
423 nats.ClientCert(certPath, keyPath))
424 if err != nil {
425 t.Fatalf("Failed to create (TLS) connection: %v", err)
426 }
427 defer nc.Close()
428
429 omsg := []byte("Hello!")
430 checkRecv := make(chan bool)
431
432 received := 0
433 nc.Subscribe("foo", func(m *nats.Msg) {
434 received++
435 if !bytes.Equal(m.Data, omsg) {
436 t.Fatal("Message received does not match")
437 }
438 checkRecv <- true
439 })
440 err = nc.Publish("foo", omsg)
441 if err != nil {
442 t.Fatalf("Failed to publish on secure (TLS) connection: %v", err)
443 }
444 nc.Flush()
445
446 if err := Wait(checkRecv); err != nil {
447 t.Fatal("Failed to receive message")
448 }
449 }
450
451 func TestClientCertificateReloadOnServerRestart(t *testing.T) {
452 c := newTester(t)
453 // Server with managed mTLS — its CA signs the cert+key we'll connect with.
454 inst := c.CreateServer(t, false, managedTLSOpts(t, testservice.TLSMutual()))
455 t.Cleanup(func() { inst.Destroy(t) })
456 caPath, certFile, keyFile := tlsCertFiles(t, inst)
457
458 // Stranger instance: separate managed mTLS to obtain a client cert signed
459 // by a CA the target server does not trust.
460 stranger := c.CreateServer(t, false, managedTLSOpts(t, testservice.TLSMutual()))
461 t.Cleanup(func() { stranger.Destroy(t) })
462 _, strangerCert, strangerKey := tlsCertFiles(t, stranger)
463
464 secureURL := fmt.Sprintf("nats://%s", hostPortFromURL(inst.Servers[0].URL))
465
466 dcChan, rcChan, errChan := make(chan bool, 1), make(chan bool, 1), make(chan error, 16)
467 nc, err := nats.Connect(secureURL,
468 nats.RootCAs(caPath),
469 nats.ClientCert(certFile, keyFile),
470 nats.ReconnectWait(100*time.Millisecond),
471 nats.MaxReconnects(-1),
472 nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
473 select {
474 case errChan <- err:
475 default:
476 }
477 }),
478 nats.DisconnectErrHandler(func(_ *nats.Conn, _ error) {
479 select {
480 case dcChan <- true:
481 default:
482 }
483 }),
484 nats.ReconnectHandler(func(_ *nats.Conn) {
485 select {
486 case rcChan <- true:
487 default:
488 }
489 }),
490 )
491 if err != nil {
492 t.Fatalf("Failed to create (TLS) connection: %v", err)
493 }
494 defer nc.Close()
495
496 // Overwrite client cert/key with stranger's (untrusted) versions; the
497 // nats.go client re-reads these on every connection attempt.
498 swap := func(t *testing.T, srcCert, srcKey string) {
499 t.Helper()
500 for src, dst := range map[string]string{srcCert: certFile, srcKey: keyFile} {
501 b, err := os.ReadFile(src)
502 if err != nil {
503 t.Fatalf("read %s: %v", src, err)
504 }
505 if err := os.WriteFile(dst, b, 0o600); err != nil {
506 t.Fatalf("write %s: %v", dst, err)
507 }
508 }
509 }
510 swap(t, strangerCert, strangerKey)
511
512 // Restart the server to force a reconnect with the swapped cert.
513 inst.StopServer(t, inst.Servers[0])
514 inst.StartServer(t, inst.Servers[0])
515
516 if err := Wait(dcChan); err != nil {
517 t.Fatal("Failed to receive disconnect signal")
518 }
519
520 // Reconnection error should be a bad-certificate failure.
521 select {
522 case err := <-errChan:
523 if !strings.Contains(err.Error(), "bad certificate") && !strings.Contains(err.Error(), "certificate required") && !strings.Contains(err.Error(), "unknown certificate authority") {
524 t.Fatalf("Expected bad certificate error; got: %s", err)
525 }
526 case <-time.After(5 * time.Second):
527 t.Fatalf("Timeout waiting for reconnect error")
528 }
529
530 // Restore the valid cert+key from the target instance.
531 origCertPEM := inst.TLS.ClientCertPEM
532 origKeyPEM := inst.TLS.ClientKeyPEM
533 if err := os.WriteFile(certFile, []byte(origCertPEM), 0o600); err != nil {
534 t.Fatalf("restore cert: %v", err)
535 }
536 if err := os.WriteFile(keyFile, []byte(origKeyPEM), 0o600); err != nil {
537 t.Fatalf("restore key: %v", err)
538 }
539
540 // Subsequent reconnect should succeed.
541 if err := Wait(rcChan); err != nil {
542 t.Fatal("Failed to receive reconnect signal")
543 }
544
545 // Sanity: pub/sub round-trip.
546 omsg := []byte("Hello!")
547 checkRecv := make(chan bool)
548
549 received := 0
550 nc.Subscribe("foo", func(m *nats.Msg) {
551 received++
552 if !bytes.Equal(m.Data, omsg) {
553 t.Fatal("Message received does not match")
554 }
555 checkRecv <- true
556 })
557 if err := nc.Publish("foo", omsg); err != nil {
558 t.Fatalf("Failed to publish on secure (TLS) connection: %v", err)
559 }
560 nc.Flush()
561
562 if err := Wait(checkRecv); err != nil {
563 t.Fatal("Failed to receive message")
564 }
565 }
566
567 func TestServerTLSHintConnections(t *testing.T) {
568 c := newTester(t)
569 opts := append([]testservice.CreateOption{managedTLSOpts(t, testservice.TLSServerOnly())}, singleUserPassOpts(derekAuthBody())...)
570 inst := c.CreateServer(t, false, opts...)
571 t.Cleanup(func() { inst.Destroy(t) })
572 caPath, _, _ := tlsCertFiles(t, inst)
573
574 hostPort := hostPortFromURL(inst.Servers[0].URL)
575 secureURL := fmt.Sprintf("tls://derek:porkchop@%s/", hostPort)
576
577 nc, err := nats.Connect(secureURL, nats.RootCAs("./configs/certs/badca.pem"))
578 if err == nil {
579 nc.Close()
580 t.Fatal("Expected an error from bad RootCA file")
581 }
582
583 nc, err = nats.Connect(secureURL, nats.RootCAs(caPath))
584 if err != nil {
585 t.Fatalf("Failed to create secure (TLS) connection: %v", err)
586 }
587 defer nc.Close()
588 }
589
590 func TestClosedConnections(t *testing.T) {
591 withServer(t, func(t *testing.T, nc *nats.Conn) {
592 sub, _ := nc.SubscribeSync("foo")
593 if sub == nil {
594 t.Fatal("Failed to create valid subscription")
595 }
596
597 // Test all API endpoints do the right thing with a closed connection.
598 nc.Close()
599 if err := nc.Publish("foo", nil); err != nats.ErrConnectionClosed {
600 t.Fatalf("Publish on closed conn did not fail properly: %v\n", err)
601 }
602 if err := nc.PublishMsg(&nats.Msg{Subject: "foo"}); err != nats.ErrConnectionClosed {
603 t.Fatalf("PublishMsg on closed conn did not fail properly: %v\n", err)
604 }
605 if err := nc.Flush(); err != nats.ErrConnectionClosed {
606 t.Fatalf("Flush on closed conn did not fail properly: %v\n", err)
607 }
608 _, err := nc.Subscribe("foo", nil)
609 if err != nats.ErrConnectionClosed {
610 t.Fatalf("Subscribe on closed conn did not fail properly: %v\n", err)
611 }
612 _, err = nc.SubscribeSync("foo")
613 if err != nats.ErrConnectionClosed {
614 t.Fatalf("SubscribeSync on closed conn did not fail properly: %v\n", err)
615 }
616 _, err = nc.QueueSubscribe("foo", "bar", nil)
617 if err != nats.ErrConnectionClosed {
618 t.Fatalf("QueueSubscribe on closed conn did not fail properly: %v\n", err)
619 }
620 _, err = nc.Request("foo", []byte("help"), 10*time.Millisecond)
621 if err != nats.ErrConnectionClosed {
622 t.Fatalf("Request on closed conn did not fail properly: %v\n", err)
623 }
624 if _, err = sub.NextMsg(10); err != nats.ErrConnectionClosed {
625 t.Fatalf("NextMessage on closed conn did not fail properly: %v\n", err)
626 }
627 if err = sub.Unsubscribe(); err != nats.ErrConnectionClosed {
628 t.Fatalf("Unsubscribe on closed conn did not fail properly: %v\n", err)
629 }
630 })
631 }
632
633 func TestErrOnConnectAndDeadlock(t *testing.T) {
634 // We will hand run a fake server that will timeout and not return a proper
635 // INFO proto. This is to test that we do not deadlock. Issue #18
636
637 l, e := net.Listen("tcp", ":0")
638 if e != nil {
639 t.Fatal("Could not listen on an ephemeral port")
640 }
641 tl := l.(*net.TCPListener)
642 defer tl.Close()
643
644 addr := tl.Addr().(*net.TCPAddr)
645
646 errCh := make(chan error, 1)
647 go func() {
648 conn, err := l.Accept()
649 if err != nil {
650 errCh <- fmt.Errorf("error accepting client connection: %v", err)
651 return
652 }
653 errCh <- nil
654 defer conn.Close()
655 // Send back a mal-formed INFO.
656 conn.Write([]byte("INFOZ \r\n"))
657 }()
658
659 go func() {
660 natsURL := fmt.Sprintf("nats://127.0.0.1:%d/", addr.Port)
661 nc, err := nats.Connect(natsURL)
662 if err == nil {
663 nc.Close()
664 errCh <- errors.New("expected bad INFO err, got none")
665 return
666 }
667 errCh <- nil
668 }()
669
670 // Setup a timer to watch for deadlock
671 select {
672 case e := <-errCh:
673 if e != nil {
674 t.Fatal(e.Error())
675 }
676 case <-time.After(time.Second):
677 t.Fatalf("Connect took too long, deadlock?")
678 }
679 }
680
681 func TestMoreErrOnConnect(t *testing.T) {
682 l, e := net.Listen("tcp", "127.0.0.1:0")
683 if e != nil {
684 t.Fatal("Could not listen on an ephemeral port")
685 }
686 tl := l.(*net.TCPListener)
687 defer tl.Close()
688
689 addr := tl.Addr().(*net.TCPAddr)
690
691 done := make(chan bool)
692 case1 := make(chan bool)
693 case2 := make(chan bool)
694 case3 := make(chan bool)
695 case4 := make(chan bool)
696
697 errCh := make(chan error, 5)
698 go func() {
699 for i := 0; i < 5; i++ {
700 conn, err := l.Accept()
701 if err != nil {
702 errCh <- fmt.Errorf("error accepting client connection: %v", err)
703 return
704 }
705 switch i {
706 case 0:
707 // Send back a partial INFO and close the connection.
708 conn.Write([]byte("INFO"))
709 case 1:
710 // Send just INFO
711 conn.Write([]byte("INFO\r\n"))
712 // Stick around a bit
713 <-case1
714 case 2:
715 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)
716 // Send complete INFO
717 conn.Write([]byte(info))
718 // Read connect and ping commands sent from the client
719 br := bufio.NewReaderSize(conn, 1024)
720 if _, err := br.ReadString('\n'); err != nil {
721 errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
722 return
723 }
724 if _, err := br.ReadString('\n'); err != nil {
725 errCh <- fmt.Errorf("expected PING from client, got: %s", err)
726 return
727 }
728 // Client expect +OK, send it but then something else than PONG
729 conn.Write([]byte("+OK\r\n"))
730 // Stick around a bit
731 <-case2
732 case 3:
733 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)
734 // Send complete INFO
735 conn.Write([]byte(info))
736 // Read connect and ping commands sent from the client
737 br := bufio.NewReaderSize(conn, 1024)
738 if _, err := br.ReadString('\n'); err != nil {
739 errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
740 return
741 }
742 if _, err := br.ReadString('\n'); err != nil {
743 errCh <- fmt.Errorf("expected PING from client, got: %s", err)
744 return
745 }
746 // Client expect +OK, send it but then something else than PONG
747 conn.Write([]byte("+OK\r\nXXX\r\n"))
748 // Stick around a bit
749 <-case3
750 case 4:
751 info := "INFO {'x'}\r\n"
752 // Send INFO with JSON marshall error
753 conn.Write([]byte(info))
754 // Stick around a bit
755 <-case4
756 }
757
758 conn.Close()
759 }
760
761 // Hang around until asked to quit
762 <-done
763 }()
764
765 natsURL := fmt.Sprintf("nats://127.0.0.1:%d", addr.Port)
766
767 if nc, err := nats.Connect(natsURL, nats.Timeout(20*time.Millisecond)); err == nil {
768 nc.Close()
769 t.Fatal("Expected error, got none")
770 }
771
772 if nc, err := nats.Connect(natsURL, nats.Timeout(20*time.Millisecond)); err == nil {
773 close(case1)
774 nc.Close()
775 t.Fatal("Expected error, got none")
776 }
777
778 close(case1)
779
780 opts := nats.GetDefaultOptions()
781 opts.Servers = []string{natsURL}
782 opts.Timeout = 20 * time.Millisecond
783 opts.Verbose = true
784
785 if nc, err := opts.Connect(); err == nil {
786 close(case2)
787 nc.Close()
788 t.Fatal("Expected error, got none")
789 }
790
791 close(case2)
792
793 if nc, err := opts.Connect(); err == nil {
794 close(case3)
795 nc.Close()
796 t.Fatal("Expected error, got none")
797 }
798
799 close(case3)
800
801 if nc, err := opts.Connect(); err == nil {
802 close(case4)
803 nc.Close()
804 t.Fatal("Expected error, got none")
805 }
806
807 close(case4)
808
809 close(done)
810
811 checkErrChannel(t, errCh)
812 }
813
814 func TestErrOnMaxPayloadLimit(t *testing.T) {
815 expectedMaxPayload := int64(10)
816 serverInfo := "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":%d}\r\n"
817
818 l, e := net.Listen("tcp", "127.0.0.1:0")
819 if e != nil {
820 t.Fatal("Could not listen on an ephemeral port")
821 }
822 tl := l.(*net.TCPListener)
823 defer tl.Close()
824
825 addr := tl.Addr().(*net.TCPAddr)
826
827 // Send back an INFO message with custom max payload size on connect.
828 var conn net.Conn
829 var err error
830
831 errCh := make(chan error, 1)
832 go func() {
833 conn, err = l.Accept()
834 if err != nil {
835 errCh <- fmt.Errorf("error accepting client connection: %v", err)
836 return
837 }
838 defer conn.Close()
839 info := fmt.Sprintf(serverInfo, addr.IP, addr.Port, expectedMaxPayload)
840 conn.Write([]byte(info))
841
842 // Read connect and ping commands sent from the client
843 line := make([]byte, 111)
844 _, err := conn.Read(line)
845 if err != nil {
846 errCh <- fmt.Errorf("expected CONNECT and PING from client, got: %s", err)
847 return
848 }
849 conn.Write([]byte("PONG\r\n"))
850 // Hang around a bit to not err on EOF in client.
851 time.Sleep(250 * time.Millisecond)
852 }()
853
854 // Wait for server mock to start
855 time.Sleep(100 * time.Millisecond)
856
857 natsURL := fmt.Sprintf("nats://%s:%d", addr.IP, addr.Port)
858 opts := nats.GetDefaultOptions()
859 opts.Servers = []string{natsURL}
860 nc, err := opts.Connect()
861 if err != nil {
862 t.Fatalf("Expected INFO message with custom max payload, got: %s", err)
863 }
864 defer nc.Close()
865
866 got := nc.MaxPayload()
867 if got != expectedMaxPayload {
868 t.Fatalf("Expected MaxPayload to be %d, got: %d", expectedMaxPayload, got)
869 }
870 err = nc.Publish("hello", []byte("hello world"))
871 if err != nats.ErrMaxPayload {
872 t.Fatalf("Expected to fail trying to send more than max payload, got: %s", err)
873 }
874 err = nc.Publish("hello", []byte("a"))
875 if err != nil {
876 t.Fatalf("Expected to succeed trying to send less than max payload, got: %s", err)
877 }
878 checkErrChannel(t, errCh)
879 }
880
881 func TestConnectVerbose(t *testing.T) {
882 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
883 o := nats.GetDefaultOptions()
884 o.Url = inst.Servers[0].URL
885 o.Verbose = true
886
887 nc, err := o.Connect()
888 if err != nil {
889 t.Fatalf("Should have connected ok: %v", err)
890 }
891 nc.Close()
892 })
893 }
894
895 func getStacks(all bool) string {
896 var (
897 stacks []byte
898 stacksSize = 10000
899 n int
900 )
901 for {
902 stacks = make([]byte, stacksSize)
903 n = runtime.Stack(stacks, all)
904 if n == stacksSize {
905 stacksSize *= 2
906 continue
907 }
908 break
909 }
910 return string(stacks[:n])
911 }
912
913 func isRunningInAsyncCBDispatcher() error {
914 strStacks := getStacks(false)
915 if strings.Contains(strStacks, "asyncCBDispatcher") {
916 return nil
917 }
918 return fmt.Errorf("callback not executed from dispatcher:\n %s", strStacks)
919 }
920
921 func TestCallbacksOrder(t *testing.T) {
922 c := newTester(t)
923
924 authOpts := append([]testservice.CreateOption{managedTLSOpts(t, testservice.TLSServerOnly())}, singleUserPassOpts(derekAuthBody())...)
925 authInst := c.CreateServer(t, false, authOpts...)
926 t.Cleanup(func() { authInst.Destroy(t) })
927
928 plainInst := c.CreateServer(t, false)
929 t.Cleanup(func() { plainInst.Destroy(t) })
930
931 // Baseline the asyncCBDispatcher count *after* the tester management conn
932 // is up but *before* the test connections: the tester client owns a
933 // dispatcher that must survive the test body, so the post-Close assertion
934 // checks the count returns to this baseline rather than to zero.
935 baselineDispatchers := strings.Count(getStacks(true), "asyncCBDispatcher")
936
937 firstDisconnect := true
938 var connTime, dtime1, dtime2, rtime, atime1, atime2, ctime time.Time
939
940 cbErrors := make(chan error, 20)
941
942 connected := make(chan bool)
943 reconnected := make(chan bool)
944 closed := make(chan bool)
945 asyncErr := make(chan bool, 2)
946 recvCh := make(chan bool, 2)
947 recvCh1 := make(chan bool)
948 recvCh2 := make(chan bool)
949
950 connCh := func(nc *nats.Conn) {
951 if err := isRunningInAsyncCBDispatcher(); err != nil {
952 cbErrors <- err
953 connected <- true
954 return
955 }
956 time.Sleep(50 * time.Millisecond)
957 connTime = time.Now()
958 connected <- true
959 }
960
961 dch := func(nc *nats.Conn) {
962 if err := isRunningInAsyncCBDispatcher(); err != nil {
963 cbErrors <- err
964 return
965 }
966 time.Sleep(100 * time.Millisecond)
967 if firstDisconnect {
968 firstDisconnect = false
969 dtime1 = time.Now()
970 } else {
971 dtime2 = time.Now()
972 }
973 }
974
975 rch := func(nc *nats.Conn) {
976 if err := isRunningInAsyncCBDispatcher(); err != nil {
977 cbErrors <- err
978 reconnected <- true
979 return
980 }
981 time.Sleep(50 * time.Millisecond)
982 rtime = time.Now()
983 reconnected <- true
984 }
985
986 ech := func(nc *nats.Conn, sub *nats.Subscription, err error) {
987 if err := isRunningInAsyncCBDispatcher(); err != nil {
988 cbErrors <- err
989 asyncErr <- true
990 return
991 }
992 if sub.Subject == "foo" {
993 time.Sleep(20 * time.Millisecond)
994 atime1 = time.Now()
995 } else {
996 atime2 = time.Now()
997 }
998 asyncErr <- true
999 }
1000
1001 cch := func(nc *nats.Conn) {
1002 if err := isRunningInAsyncCBDispatcher(); err != nil {
1003 cbErrors <- err
1004 closed <- true
1005 return
1006 }
1007 ctime = time.Now()
1008 closed <- true
1009 }
1010
1011 // authInst will reject our credentials (no derek:porkchop), so we
1012 // expect the auth_required + Secure failure for the first server in
1013 // the list and a successful fallback to plainInst.
1014 url := hostPortFromURL(authInst.Servers[0].URL) + "," + plainInst.Servers[0].URL
1015 url = "nats://" + url
1016
1017 nc, err := nats.Connect(url,
1018 nats.ConnectHandler(connCh),
1019 nats.DisconnectHandler(dch),
1020 nats.ReconnectHandler(rch),
1021 nats.ClosedHandler(cch),
1022 nats.ErrorHandler(ech),
1023 nats.ReconnectWait(50*time.Millisecond),
1024 nats.ReconnectJitter(0, 0),
1025 nats.DontRandomize())
1026 if err != nil {
1027 t.Fatalf("Unable to connect: %v\n", err)
1028 }
1029 defer nc.Close()
1030
1031 // Wait for notification on connection established
1032 err = Wait(connected)
1033 if err != nil {
1034 t.Fatal("Did not get the connected callback")
1035 }
1036
1037 ncp, err := nats.Connect(plainInst.Servers[0].URL,
1038 nats.ReconnectWait(50*time.Millisecond))
1039 if err != nil {
1040 t.Fatalf("Unable to connect: %v\n", err)
1041 }
1042 defer ncp.Close()
1043
1044 // Wait to make sure that if we have closed (incorrectly) the
1045 // asyncCBDispatcher during the connect process, this is caught here.
1046 time.Sleep(time.Second)
1047
1048 // Restart the plainInst server to trigger reconnect.
1049 plainInst.StopServer(t, plainInst.Servers[0])
1050 plainInst.StartServer(t, plainInst.Servers[0])
1051
1052 if err := Wait(reconnected); err != nil {
1053 t.Fatal("Did not get the reconnected callback")
1054 }
1055
1056 var sub1, sub2 *nats.Subscription
1057
1058 recv := func(m *nats.Msg) {
1059 // Signal that one message is received
1060 recvCh <- true
1061
1062 // We will now block
1063 if m.Subject == "foo" {
1064 <-recvCh1
1065 } else {
1066 <-recvCh2
1067 }
1068 m.Sub.Unsubscribe()
1069 }
1070
1071 sub1, err = nc.Subscribe("foo", recv)
1072 if err != nil {
1073 t.Fatalf("Unable to create subscription: %v\n", err)
1074 }
1075 sub1.SetPendingLimits(1, 100000)
1076
1077 sub2, err = nc.Subscribe("bar", recv)
1078 if err != nil {
1079 t.Fatalf("Unable to create subscription: %v\n", err)
1080 }
1081 sub2.SetPendingLimits(1, 100000)
1082
1083 nc.Flush()
1084
1085 ncp.Publish("foo", []byte("test"))
1086 ncp.Publish("bar", []byte("test"))
1087 ncp.Flush()
1088
1089 // Wait notification that message were received
1090 err = Wait(recvCh)
1091 if err == nil {
1092 err = Wait(recvCh)
1093 }
1094 if err != nil {
1095 t.Fatal("Did not receive message")
1096 }
1097
1098 for i := 0; i < 2; i++ {
1099 ncp.Publish("foo", []byte("test"))
1100 ncp.Publish("bar", []byte("test"))
1101 }
1102 ncp.Flush()
1103
1104 if err := Wait(asyncErr); err != nil {
1105 t.Fatal("Did not get the async callback")
1106 }
1107 if err := Wait(asyncErr); err != nil {
1108 t.Fatal("Did not get the async callback")
1109 }
1110
1111 close(recvCh1)
1112 close(recvCh2)
1113
1114 nc.Close()
1115
1116 if err := Wait(closed); err != nil {
1117 t.Fatal("Did not get the close callback")
1118 }
1119
1120 if len(cbErrors) > 0 {
1121 t.Fatalf("%v", <-cbErrors)
1122 }
1123
1124 if (connTime == time.Time{}) || (dtime1 == time.Time{}) || (dtime2 == time.Time{}) || (rtime == time.Time{}) || (atime1 == time.Time{}) || (atime2 == time.Time{}) || (ctime == time.Time{}) {
1125 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)
1126 }
1127
1128 if dtime1.Before(connTime) || rtime.Before(dtime1) || dtime2.Before(rtime) || atime2.Before(atime1) || ctime.Before(atime2) {
1129 t.Fatalf("Wrong callback order:\n%v\n%v\n%v\n%v\n%v\n%v\n%v", connTime, dtime1, rtime, atime1, atime2, dtime2, ctime)
1130 }
1131
1132 // Close the other connection
1133 ncp.Close()
1134
1135 // Check that the test-created dispatchers are gone (count returned to
1136 // baseline). Allow plenty of time to avoid flappers.
1137 timeout := time.Now().Add(5 * time.Second)
1138 for time.Now().Before(timeout) {
1139 if strings.Count(getStacks(true), "asyncCBDispatcher") <= baselineDispatchers {
1140 return
1141 }
1142 time.Sleep(50 * time.Millisecond)
1143 }
1144 t.Fatalf("The async callback dispatcher(s) should have stopped (baseline %d, still running)", baselineDispatchers)
1145 }
1146
1147 func TestReconnectErrHandler(t *testing.T) {
1148 handler := func(ch chan bool) func(*nats.Conn, error) {
1149 return func(*nats.Conn, error) {
1150 ch <- true
1151 }
1152 }
1153 t.Run("with RetryOnFailedConnect, MaxReconnects(-1), no connection", func(t *testing.T) {
1154 // Use a known-bad URL so the initial connect retries.
1155 reconnectErr := make(chan bool)
1156
1157 nc, err := nats.Connect("nats://127.0.0.1:1",
1158 nats.ReconnectErrHandler(handler(reconnectErr)),
1159 nats.RetryOnFailedConnect(true),
1160 nats.MaxReconnects(-1))
1161 if err != nil {
1162 t.Fatalf("Unexpected error: %v", err)
1163 }
1164 defer nc.Close()
1165 if err = Wait(reconnectErr); err != nil {
1166 t.Fatal("Timeout waiting for reconnect error handler")
1167 }
1168 })
1169 }
1170
1171 func TestConnectHandler(t *testing.T) {
1172 handler := func(ch chan bool) func(*nats.Conn) {
1173 return func(*nats.Conn) {
1174 ch <- true
1175 }
1176 }
1177 t.Run("with RetryOnFailedConnect, connection established", func(t *testing.T) {
1178 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
1179 connected := make(chan bool)
1180 reconnected := make(chan bool)
1181
1182 nc, err := nats.Connect(inst.Servers[0].URL,
1183 nats.ConnectHandler(handler(connected)),
1184 nats.ReconnectHandler(handler(reconnected)),
1185 nats.RetryOnFailedConnect(true))
1186 if err != nil {
1187 t.Fatalf("Unexpected error: %v", err)
1188 }
1189 defer nc.Close()
1190 if err = Wait(connected); err != nil {
1191 t.Fatal("Timeout waiting for connect handler")
1192 }
1193 if err = WaitTime(reconnected, 100*time.Millisecond); err == nil {
1194 t.Fatal("Reconnect handler should not have been invoked")
1195 }
1196 })
1197 })
1198 t.Run("with RetryOnFailedConnect, connection failed", func(t *testing.T) {
1199 connected := make(chan bool)
1200 reconnected := make(chan bool)
1201
1202 nc, err := nats.Connect("nats://127.0.0.1:1",
1203 nats.ConnectHandler(handler(connected)),
1204 nats.ReconnectHandler(handler(reconnected)),
1205 nats.RetryOnFailedConnect(true))
1206 if err != nil {
1207 t.Fatalf("Unexpected error: %v", err)
1208 }
1209 defer nc.Close()
1210 if err = WaitTime(connected, 100*time.Millisecond); err == nil {
1211 t.Fatal("Connected handler should not have been invoked")
1212 }
1213 if err = WaitTime(reconnected, 100*time.Millisecond); err == nil {
1214 t.Fatal("Reconnect handler should not have been invoked")
1215 }
1216 })
1217 t.Run("no RetryOnFailedConnect, connection established", func(t *testing.T) {
1218 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
1219 connected := make(chan bool)
1220 reconnected := make(chan bool)
1221 nc, err := nats.Connect(inst.Servers[0].URL,
1222 nats.ConnectHandler(handler(connected)),
1223 nats.ReconnectHandler(handler(reconnected)))
1224 if err != nil {
1225 t.Fatalf("Unexpected error: %v", err)
1226 }
1227 defer nc.Close()
1228 if err = Wait(connected); err != nil {
1229 t.Fatal("Timeout waiting for connect handler")
1230 }
1231 if err = WaitTime(reconnected, 100*time.Millisecond); err == nil {
1232 t.Fatal("Reconnect handler should not have been invoked")
1233 }
1234 })
1235 })
1236 t.Run("no RetryOnFailedConnect, connection failed", func(t *testing.T) {
1237 connected := make(chan bool)
1238 reconnected := make(chan bool)
1239 _, err := nats.Connect("nats://127.0.0.1:1",
1240 nats.ConnectHandler(handler(connected)),
1241 nats.ReconnectHandler(handler(reconnected)))
1242
1243 if err == nil {
1244 t.Fatalf("Expected error on connect, got nil")
1245 }
1246 if err = WaitTime(connected, 100*time.Millisecond); err == nil {
1247 t.Fatal("Connected handler should not have been invoked")
1248 }
1249 if err = WaitTime(reconnected, 100*time.Millisecond); err == nil {
1250 t.Fatal("Reconnect handler should not have been invoked")
1251 }
1252 })
1253 t.Run("with RetryOnFailedConnect, initial connection failed, reconnect successful", func(t *testing.T) {
1254 c := newTester(t)
1255 // Create a server but stop it so the initial connect fails.
1256 inst := c.CreateServer(t, false)
1257 t.Cleanup(func() { inst.Destroy(t) })
1258 inst.StopServer(t, inst.Servers[0])
1259
1260 connected := make(chan bool)
1261 reconnected := make(chan bool)
1262
1263 nc, err := nats.Connect(inst.Servers[0].URL,
1264 nats.ConnectHandler(handler(connected)),
1265 nats.ReconnectHandler(handler(reconnected)),
1266 nats.RetryOnFailedConnect(true),
1267 nats.ReconnectWait(100*time.Millisecond))
1268 if err != nil {
1269 t.Fatalf("Expected error on connect, got nil")
1270 }
1271
1272 defer nc.Close()
1273
1274 inst.StartServer(t, inst.Servers[0])
1275
1276 if err = Wait(connected); err != nil {
1277 t.Fatal("Timeout waiting for reconnect handler")
1278 }
1279 if err = WaitTime(reconnected, 100*time.Millisecond); err == nil {
1280 t.Fatal("Reconnect handler should not have been invoked")
1281 }
1282 })
1283 t.Run("with RetryOnFailedConnect, initial connection successful, server restart", func(t *testing.T) {
1284 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
1285 connected := make(chan bool)
1286 reconnected := make(chan bool)
1287
1288 nc, err := nats.Connect(inst.Servers[0].URL,
1289 nats.ConnectHandler(handler(connected)),
1290 nats.ReconnectHandler(handler(reconnected)),
1291 nats.RetryOnFailedConnect(true),
1292 nats.ReconnectWait(100*time.Millisecond))
1293 if err != nil {
1294 t.Fatalf("Unexpected error: %v", err)
1295 }
1296 defer nc.Close()
1297
1298 if err = Wait(connected); err != nil {
1299 t.Fatal("Timeout waiting for connect handler")
1300 }
1301 if err = WaitTime(reconnected, 100*time.Millisecond); err == nil {
1302 t.Fatal("Reconnect handler should not have been invoked")
1303 }
1304
1305 inst.StopServer(t, inst.Servers[0])
1306 inst.StartServer(t, inst.Servers[0])
1307
1308 if err = Wait(reconnected); err != nil {
1309 t.Fatal("Timeout waiting for reconnect handler")
1310 }
1311 if err = WaitTime(connected, 100*time.Millisecond); err == nil {
1312 t.Fatal("Connected handler should not have been invoked")
1313 }
1314 })
1315 })
1316 }
1317
1318 func TestFlushReleaseOnClose(t *testing.T) {
1319 serverInfo := "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n"
1320
1321 l, e := net.Listen("tcp", "127.0.0.1:0")
1322 if e != nil {
1323 t.Fatal("Could not listen on an ephemeral port")
1324 }
1325 tl := l.(*net.TCPListener)
1326 defer tl.Close()
1327
1328 addr := tl.Addr().(*net.TCPAddr)
1329 done := make(chan bool)
1330
1331 errCh := make(chan error, 1)
1332 go func() {
1333 conn, err := l.Accept()
1334 if err != nil {
1335 errCh <- fmt.Errorf("error accepting client connection: %v", err)
1336 return
1337 }
1338 defer conn.Close()
1339 info := fmt.Sprintf(serverInfo, addr.IP, addr.Port)
1340 conn.Write([]byte(info))
1341
1342 // Read connect and ping commands sent from the client
1343 br := bufio.NewReaderSize(conn, 1024)
1344 if _, err := br.ReadString('\n'); err != nil {
1345 errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
1346 return
1347 }
1348 if _, err := br.ReadString('\n'); err != nil {
1349 errCh <- fmt.Errorf("expected PING from client, got: %s", err)
1350 return
1351
1352 }
1353 conn.Write([]byte("PONG\r\n"))
1354
1355 // Hang around until asked to quit
1356 <-done
1357 }()
1358
1359 // Wait for server mock to start
1360 time.Sleep(100 * time.Millisecond)
1361
1362 natsURL := fmt.Sprintf("nats://%s:%d", addr.IP, addr.Port)
1363 opts := nats.GetDefaultOptions()
1364 opts.AllowReconnect = false
1365 opts.Servers = []string{natsURL}
1366 nc, err := opts.Connect()
1367 if err != nil {
1368 t.Fatalf("Expected INFO message with custom max payload, got: %s", err)
1369 }
1370 defer nc.Close()
1371
1372 // First try a FlushTimeout() and make sure we timeout
1373 if err := nc.FlushTimeout(50 * time.Millisecond); err == nil || err != nats.ErrTimeout {
1374 t.Fatalf("Expected a timeout error, got: %v", err)
1375 }
1376
1377 go func() {
1378 time.Sleep(50 * time.Millisecond)
1379 nc.Close()
1380 }()
1381
1382 if err := nc.Flush(); err == nil {
1383 t.Fatal("Expected error on Flush() released by Close()")
1384 }
1385
1386 close(done)
1387 checkErrChannel(t, errCh)
1388 }
1389
1390 func TestMaxPendingOut(t *testing.T) {
1391 serverInfo := "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n"
1392
1393 l, e := net.Listen("tcp", "127.0.0.1:0")
1394 if e != nil {
1395 t.Fatal("Could not listen on an ephemeral port")
1396 }
1397 tl := l.(*net.TCPListener)
1398 defer tl.Close()
1399
1400 addr := tl.Addr().(*net.TCPAddr)
1401 done := make(chan bool)
1402 cch := make(chan bool)
1403
1404 errCh := make(chan error, 1)
1405 go func() {
1406 conn, err := l.Accept()
1407 if err != nil {
1408 errCh <- fmt.Errorf("error accepting client connection: %v", err)
1409 return
1410 }
1411 defer conn.Close()
1412 info := fmt.Sprintf(serverInfo, addr.IP, addr.Port)
1413 conn.Write([]byte(info))
1414
1415 // Read connect and ping commands sent from the client
1416 br := bufio.NewReaderSize(conn, 1024)
1417 if _, err := br.ReadString('\n'); err != nil {
1418 errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
1419 return
1420 }
1421 if _, err := br.ReadString('\n'); err != nil {
1422 errCh <- fmt.Errorf("expected PING from client, got: %s", err)
1423 return
1424 }
1425 conn.Write([]byte("PONG\r\n"))
1426
1427 // Hang around until asked to quit
1428 <-done
1429 }()
1430
1431 // Wait for server mock to start
1432 time.Sleep(100 * time.Millisecond)
1433
1434 natsURL := fmt.Sprintf("nats://%s:%d", addr.IP, addr.Port)
1435 opts := nats.GetDefaultOptions()
1436 opts.PingInterval = 20 * time.Millisecond
1437 opts.MaxPingsOut = 2
1438 opts.AllowReconnect = false
1439 opts.ClosedCB = func(_ *nats.Conn) { cch <- true }
1440 opts.Servers = []string{natsURL}
1441 nc, err := opts.Connect()
1442 if err != nil {
1443 t.Fatalf("Expected INFO message with custom max payload, got: %s", err)
1444 }
1445 defer nc.Close()
1446
1447 // After 60 ms, we should have closed the connection
1448 time.Sleep(100 * time.Millisecond)
1449
1450 if err := Wait(cch); err != nil {
1451 t.Fatal("Failed to get ClosedCB")
1452 }
1453 if nc.LastError() != nats.ErrStaleConnection {
1454 t.Fatalf("Expected to get %v, got %v", nats.ErrStaleConnection, nc.LastError())
1455 }
1456
1457 close(done)
1458 checkErrChannel(t, errCh)
1459 }
1460
1461 func TestErrInReadLoop(t *testing.T) {
1462 serverInfo := "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n"
1463
1464 l, e := net.Listen("tcp", "127.0.0.1:0")
1465 if e != nil {
1466 t.Fatal("Could not listen on an ephemeral port")
1467 }
1468 tl := l.(*net.TCPListener)
1469 defer tl.Close()
1470
1471 addr := tl.Addr().(*net.TCPAddr)
1472 done := make(chan bool)
1473 cch := make(chan bool)
1474
1475 errCh := make(chan error, 1)
1476 go func() {
1477 conn, err := l.Accept()
1478 if err != nil {
1479 errCh <- fmt.Errorf("error accepting client connection: %v", err)
1480 return
1481 }
1482 defer conn.Close()
1483 info := fmt.Sprintf(serverInfo, addr.IP, addr.Port)
1484 conn.Write([]byte(info))
1485
1486 // Read connect and ping commands sent from the client
1487 br := bufio.NewReaderSize(conn, 1024)
1488 if _, err := br.ReadString('\n'); err != nil {
1489 errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
1490 return
1491 }
1492 if _, err := br.ReadString('\n'); err != nil {
1493 errCh <- fmt.Errorf("expected PING from client, got: %s", err)
1494 return
1495 }
1496 conn.Write([]byte("PONG\r\n"))
1497
1498 // Read (and ignore) the SUB from the client
1499 if _, err := br.ReadString('\n'); err != nil {
1500 errCh <- fmt.Errorf("expected SUB from client, got: %s", err)
1501 return
1502 }
1503
1504 // Send something that should make the subscriber fail.
1505 conn.Write([]byte("Ivan"))
1506
1507 // Hang around until asked to quit
1508 <-done
1509 }()
1510
1511 // Wait for server mock to start
1512 time.Sleep(100 * time.Millisecond)
1513
1514 natsURL := fmt.Sprintf("nats://%s:%d", addr.IP, addr.Port)
1515 opts := nats.GetDefaultOptions()
1516 opts.AllowReconnect = false
1517 opts.ClosedCB = func(_ *nats.Conn) { cch <- true }
1518 opts.Servers = []string{natsURL}
1519 nc, err := opts.Connect()
1520 if err != nil {
1521 t.Fatalf("Expected INFO message with custom max payload, got: %s", err)
1522 }
1523 defer nc.Close()
1524
1525 received := int64(0)
1526
1527 nc.Subscribe("foo", func(_ *nats.Msg) {
1528 atomic.AddInt64(&received, 1)
1529 })
1530
1531 if err := Wait(cch); err != nil {
1532 t.Fatal("Failed to get ClosedCB")
1533 }
1534
1535 recv := int(atomic.LoadInt64(&received))
1536 if recv != 0 {
1537 t.Fatalf("Should not have received messages, got: %d", recv)
1538 }
1539
1540 close(done)
1541 checkErrChannel(t, errCh)
1542 }
1543
1544 func TestErrStaleConnection(t *testing.T) {
1545 serverInfo := "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n"
1546
1547 l, e := net.Listen("tcp", "127.0.0.1:0")
1548 if e != nil {
1549 t.Fatal("Could not listen on an ephemeral port")
1550 }
1551 tl := l.(*net.TCPListener)
1552 defer tl.Close()
1553
1554 addr := tl.Addr().(*net.TCPAddr)
1555 done := make(chan bool)
1556 dch := make(chan bool)
1557 rch := make(chan bool)
1558 cch := make(chan bool)
1559 sch := make(chan bool)
1560
1561 firstDisconnect := true
1562
1563 errCh := make(chan error, 1)
1564 go func() {
1565 for i := 0; i < 2; i++ {
1566 conn, err := l.Accept()
1567 if err != nil {
1568 errCh <- fmt.Errorf("error accepting client connection: %v", err)
1569 return
1570 }
1571 defer conn.Close()
1572 info := fmt.Sprintf(serverInfo, addr.IP, addr.Port)
1573 conn.Write([]byte(info))
1574
1575 // Read connect and ping commands sent from the client
1576 br := bufio.NewReaderSize(conn, 1024)
1577 if _, err := br.ReadString('\n'); err != nil {
1578 errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
1579 return
1580 }
1581 if _, err := br.ReadString('\n'); err != nil {
1582 errCh <- fmt.Errorf("expected PING from client, got: %s", err)
1583 return
1584 }
1585 conn.Write([]byte("PONG\r\n"))
1586
1587 if i == 0 {
1588 // Wait a tiny, and simulate a Stale Connection
1589 time.Sleep(50 * time.Millisecond)
1590 conn.Write([]byte("-ERR 'Stale Connection'\r\n"))
1591
1592 // The client should try to reconnect. When getting the
1593 // disconnected callback, it will close this channel.
1594 <-sch
1595
1596 // Close the connection and go back to accept the new
1597 // connection.
1598 conn.Close()
1599 } else {
1600 // Hang around a bit
1601 <-done
1602 }
1603 }
1604 }()
1605
1606 // Wait for server mock to start
1607 time.Sleep(100 * time.Millisecond)
1608
1609 natsURL := fmt.Sprintf("nats://%s:%d", addr.IP, addr.Port)
1610 opts := nats.GetDefaultOptions()
1611 opts.AllowReconnect = true
1612 opts.DisconnectedErrCB = func(_ *nats.Conn, _ error) {
1613 // Interested only in the first disconnect cb
1614 if firstDisconnect {
1615 firstDisconnect = false
1616 close(sch)
1617 dch <- true
1618 }
1619 }
1620 opts.ReconnectedCB = func(_ *nats.Conn) { rch <- true }
1621 opts.ClosedCB = func(_ *nats.Conn) { cch <- true }
1622 opts.ReconnectWait = 20 * time.Millisecond
1623 nats.ReconnectJitter(0, 0)(&opts)
1624 opts.MaxReconnect = 100
1625 opts.Servers = []string{natsURL}
1626 nc, err := opts.Connect()
1627 if err != nil {
1628 t.Fatalf("Expected INFO message with custom max payload, got: %s", err)
1629 }
1630 defer nc.Close()
1631
1632 // We should first gets disconnected
1633 if err := Wait(dch); err != nil {
1634 t.Fatal("Failed to get DisconnectedErrCB")
1635 }
1636
1637 // Then reconnected..
1638 if err := Wait(rch); err != nil {
1639 t.Fatal("Failed to get ReconnectedCB")
1640 }
1641
1642 // Now close the connection
1643 nc.Close()
1644
1645 // We should get the closed cb
1646 if err := Wait(cch); err != nil {
1647 t.Fatal("Failed to get ClosedCB")
1648 }
1649
1650 close(done)
1651 checkErrChannel(t, errCh)
1652 }
1653
1654 func TestServerErrorClosesConnection(t *testing.T) {
1655 serverInfo := "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":1048576}\r\n"
1656
1657 l, e := net.Listen("tcp", "127.0.0.1:0")
1658 if e != nil {
1659 t.Fatal("Could not listen on an ephemeral port")
1660 }
1661 tl := l.(*net.TCPListener)
1662 defer tl.Close()
1663
1664 addr := tl.Addr().(*net.TCPAddr)
1665 done := make(chan bool)
1666 dch := make(chan bool)
1667 cch := make(chan bool)
1668
1669 serverSentError := "Any Error"
1670 reconnected := int64(0)
1671
1672 errCh := make(chan error, 1)
1673 go func() {
1674 conn, err := l.Accept()
1675 if err != nil {
1676 errCh <- fmt.Errorf("error accepting client connection: %v", err)
1677 return
1678 }
1679 defer conn.Close()
1680 info := fmt.Sprintf(serverInfo, addr.IP, addr.Port)
1681 conn.Write([]byte(info))
1682
1683 // Read connect and ping commands sent from the client
1684 br := bufio.NewReaderSize(conn, 1024)
1685 if _, err := br.ReadString('\n'); err != nil {
1686 errCh <- fmt.Errorf("expected CONNECT from client, got: %s", err)
1687 return
1688 }
1689 if _, err := br.ReadString('\n'); err != nil {
1690 errCh <- fmt.Errorf("expected PING from client, got: %s", err)
1691 return
1692 }
1693 conn.Write([]byte("PONG\r\n"))
1694
1695 // Wait a tiny, and simulate a Stale Connection
1696 time.Sleep(50 * time.Millisecond)
1697 conn.Write([]byte("-ERR '" + serverSentError + "'\r\n"))
1698
1699 // Hang around a bit
1700 <-done
1701 }()
1702
1703 // Wait for server mock to start
1704 time.Sleep(100 * time.Millisecond)
1705
1706 natsURL := fmt.Sprintf("nats://%s:%d", addr.IP, addr.Port)
1707 opts := nats.GetDefaultOptions()
1708 opts.AllowReconnect = true
1709 opts.DisconnectedErrCB = func(_ *nats.Conn, _ error) { dch <- true }
1710 opts.ReconnectedCB = func(_ *nats.Conn) { atomic.AddInt64(&reconnected, 1) }
1711 opts.ClosedCB = func(_ *nats.Conn) { cch <- true }
1712 opts.ReconnectWait = 20 * time.Millisecond
1713 nats.ReconnectJitter(0, 0)(&opts)
1714 opts.MaxReconnect = 100
1715 opts.Servers = []string{natsURL}
1716 nc, err := opts.Connect()
1717 if err != nil {
1718 t.Fatalf("Expected INFO message with custom max payload, got: %s", err)
1719 }
1720 defer nc.Close()
1721
1722 // The server sends an error that should cause the client to simply close
1723 // the connection.
1724
1725 // We should first gets disconnected
1726 if err := Wait(dch); err != nil {
1727 t.Fatal("Failed to get DisconnectedErrCB")
1728 }
1729
1730 // We should get the closed cb
1731 if err := Wait(cch); err != nil {
1732 t.Fatal("Failed to get ClosedCB")
1733 }
1734
1735 // We should not have been reconnected
1736 if atomic.LoadInt64(&reconnected) != 0 {
1737 t.Fatal("ReconnectedCB should not have been invoked")
1738 }
1739
1740 // Check LastError(), it should be "nats: <server error in lower case>"
1741 lastErr := nc.LastError().Error()
1742 expectedErr := "nats: " + serverSentError
1743 if lastErr != expectedErr {
1744 t.Fatalf("Expected error: '%v', got '%v'", expectedErr, lastErr)
1745 }
1746
1747 close(done)
1748 checkErrChannel(t, errCh)
1749 }
1750
1751 func TestUseDefaultTimeout(t *testing.T) {
1752 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
1753 opts := &nats.Options{
1754 Servers: []string{inst.Servers[0].URL},
1755 }
1756 nc, err := opts.Connect()
1757 if err != nil {
1758 t.Fatalf("Unexpected error on connect: %v", err)
1759 }
1760 defer nc.Close()
1761 if nc.Opts.Timeout != nats.DefaultTimeout {
1762 t.Fatalf("Expected Timeout to be set to %v, got %v", nats.DefaultTimeout, nc.Opts.Timeout)
1763 }
1764 })
1765 }
1766
1767 func TestLastErrorNoRace(t *testing.T) {
1768 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
1769 // Access LastError in disconnection and closed handlers to make sure
1770 // that there is no race. It is possible in some cases that
1771 // nc.LastError() returns a non nil error. We don't care here about the
1772 // returned value.
1773 dch := func(c *nats.Conn) {
1774 c.LastError()
1775 }
1776 closedCh := make(chan struct{})
1777 cch := func(c *nats.Conn) {
1778 c.LastError()
1779 closedCh <- struct{}{}
1780 }
1781 nc, err := nats.Connect(inst.Servers[0].URL,
1782 nats.DisconnectHandler(dch),
1783 nats.ClosedHandler(cch),
1784 nats.MaxReconnects(-1),
1785 nats.ReconnectWait(5*time.Millisecond),
1786 nats.ReconnectJitter(0, 0))
1787 if err != nil {
1788 t.Fatalf("Unable to connect: %v\n", err)
1789 }
1790 defer nc.Close()
1791
1792 // Restart the server several times to trigger a reconnection.
1793 for i := 0; i < 10; i++ {
1794 inst.StopServer(t, inst.Servers[0])
1795 time.Sleep(10 * time.Millisecond)
1796 inst.StartServer(t, inst.Servers[0])
1797 }
1798 nc.Close()
1799 inst.StopServer(t, inst.Servers[0])
1800 select {
1801 case <-closedCh:
1802 case <-time.After(5 * time.Second):
1803 t.Fatal("Timeout waiting for the closed callback")
1804 }
1805 })
1806 }
1807
1808 type customDialer struct {
1809 ch chan bool
1810 }
1811
1812 func (cd *customDialer) Dial(network, address string) (net.Conn, error) {
1813 cd.ch <- true
1814 return nil, errors.New("on purpose")
1815 }
1816
1817 func TestUseCustomDialer(t *testing.T) {
1818 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
1819 serverURL := inst.Servers[0].URL
1820
1821 dialer := &net.Dialer{
1822 Timeout: 10 * time.Second,
1823 FallbackDelay: -1,
1824 }
1825 opts := &nats.Options{
1826 Servers: []string{serverURL},
1827 Dialer: dialer,
1828 }
1829 nc, err := opts.Connect()
1830 if err != nil {
1831 t.Fatalf("Unexpected error on connect: %v", err)
1832 }
1833 defer nc.Close()
1834 if nc.Opts.Dialer != dialer {
1835 t.Fatalf("Expected Dialer to be set to %v, got %v", dialer, nc.Opts.Dialer)
1836 }
1837 if nc.Opts.AllowMultipathTCP != nil {
1838 t.Fatal("Expected AllowMultipathTCP to be unset")
1839 }
1840
1841 // Should be possible to set via variadic func based Option setter
1842 dialer2 := &net.Dialer{
1843 Timeout: 5 * time.Second,
1844 FallbackDelay: -1,
1845 }
1846 nc2, err := nats.Connect(serverURL, nats.Dialer(dialer2), nats.MultipathTCP(true))
1847 if err != nil {
1848 t.Fatalf("Unexpected error on connect: %v", err)
1849 }
1850 defer nc2.Close()
1851 if nc2.Opts.Dialer.FallbackDelay > 0 {
1852 t.Fatalf("Expected for dialer to be customized to disable dual stack support")
1853 }
1854 if nc2.Opts.AllowMultipathTCP == nil || !*nc2.Opts.AllowMultipathTCP {
1855 t.Fatal("Expected AllowMultipathTCP to be true")
1856 }
1857
1858 // By default, dialer still uses the DefaultTimeout
1859 nc3, err := nats.Connect(serverURL, nats.MultipathTCP(false))
1860 if err != nil {
1861 t.Fatalf("Unexpected error on connect: %v", err)
1862 }
1863 defer nc3.Close()
1864 if nc3.Opts.Dialer.Timeout != nats.DefaultTimeout {
1865 t.Fatalf("Expected Dialer.Timeout to be set to %v, got %v", nats.DefaultTimeout, nc.Opts.Dialer.Timeout)
1866 }
1867 if nc3.Opts.AllowMultipathTCP == nil || *nc3.Opts.AllowMultipathTCP {
1868 t.Fatal("Expected AllowMultipathTCP to be false")
1869 }
1870
1871 // Create custom dialer that return error on Dial().
1872 cdialer := &customDialer{ch: make(chan bool, 10)}
1873
1874 // When both Dialer and CustomDialer are set, CustomDialer
1875 // should take precedence. That means that the connection
1876 // should fail for these two set of options.
1877 options := []*nats.Options{
1878 {Dialer: dialer, CustomDialer: cdialer},
1879 {CustomDialer: cdialer},
1880 }
1881 for _, o := range options {
1882 o.Servers = []string{serverURL}
1883 nc, err := o.Connect()
1884 // As of now, Connect() would not return the actual dialer error,
1885 // instead it returns "no server available for connections".
1886 // So use go channel to ensure that custom dialer's Dial() method
1887 // was invoked.
1888 if err == nil {
1889 if nc != nil {
1890 nc.Close()
1891 }
1892 t.Fatal("Expected error, got none")
1893 }
1894 if err := Wait(cdialer.ch); err != nil {
1895 t.Fatal("Did not get our notification")
1896 }
1897 }
1898 // Same with variadic
1899 foptions := [][]nats.Option{
1900 {nats.Dialer(dialer), nats.SetCustomDialer(cdialer)},
1901 {nats.SetCustomDialer(cdialer)},
1902 }
1903 for _, fos := range foptions {
1904 nc, err := nats.Connect(serverURL, fos...)
1905 if err == nil {
1906 if nc != nil {
1907 nc.Close()
1908 }
1909 t.Fatal("Expected error, got none")
1910 }
1911 if err := Wait(cdialer.ch); err != nil {
1912 t.Fatal("Did not get our notification")
1913 }
1914 }
1915 })
1916 }
1917
1918 func TestDefaultOptionsDialer(t *testing.T) {
1919 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
1920 opts1 := nats.GetDefaultOptions()
1921 opts1.Url = inst.Servers[0].URL
1922 opts2 := nats.GetDefaultOptions()
1923 opts2.Url = inst.Servers[0].URL
1924
1925 nc1, err := opts1.Connect()
1926 if err != nil {
1927 t.Fatalf("Unexpected error on connect: %v", err)
1928 }
1929 defer nc1.Close()
1930
1931 nc2, err := opts2.Connect()
1932 if err != nil {
1933 t.Fatalf("Unexpected error on connect: %v", err)
1934 }
1935 defer nc2.Close()
1936
1937 if nc1.Opts.Dialer == nc2.Opts.Dialer {
1938 t.Fatalf("Expected each connection to have its own dialer")
1939 }
1940 })
1941 }
1942
1943 type lowWriteBufferDialer struct{}
1944
1945 func (d *lowWriteBufferDialer) Dial(network, address string) (net.Conn, error) {
1946 c, err := net.Dial(network, address)
1947 if err != nil {
1948 return nil, err
1949 }
1950 c.(*net.TCPConn).SetWriteBuffer(100)
1951 return c, nil
1952 }
1953
1954 func TestCustomFlusherTimeout(t *testing.T) {
1955 if runtime.GOOS == "windows" {
1956 t.SkipNow()
1957 }
1958 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
1959 // Reasonably large flusher timeout will not induce errors
1960 // when we can flush fast
1961 nc1, err := nats.Connect(inst.Servers[0].URL, nats.FlusherTimeout(10*time.Second))
1962 if err != nil {
1963 t.Fatalf("Expected to be able to connect, got: %s", err)
1964 }
1965 doneCh := make(chan struct{}, 1)
1966 // We want to have a payload size that is big enough so that after
1967 // few publish, the socket buffer will be full and produce the timeout.
1968 // Since we try to produce the error in the flusher and not the publish
1969 // call itself, use a size that is a bit less than the internal
1970 // buffer used by the library.
1971 payloadBytes := make([]byte, 32*1024-200)
1972
1973 errCh := make(chan error, 1)
1974 wg := sync.WaitGroup{}
1975 wg.Add(1)
1976 go func() {
1977 defer wg.Done()
1978 for {
1979 select {
1980 case <-time.After(200 * time.Millisecond):
1981 err := nc1.Publish("hello", payloadBytes)
1982 if err != nil {
1983 errCh <- err
1984 return
1985 }
1986 case <-doneCh:
1987 return
1988 }
1989 }
1990 }()
1991 defer nc1.Close()
1992
1993 addr := startStalledMockServer(t)
1994
1995 nc2, err := nats.Connect(
1996 // URL to fake server
1997 fmt.Sprintf("nats://127.0.0.1:%d", addr.Port),
1998 // Use custom dialer so we can set write buffer to low value
1999 nats.SetCustomDialer(&lowWriteBufferDialer{}),
2000 // Use short flusher timeout to trigger the error
2001 nats.FlusherTimeout(15*time.Millisecond),
2002 // Make sure the library does not close connection due
2003 // to pings for this test.
2004 nats.PingInterval(20*time.Second),
2005 // No reconnect
2006 nats.NoReconnect(),
2007 // Notify when connection lost
2008 nats.ClosedHandler(func(_ *nats.Conn) {
2009 doneCh <- struct{}{}
2010 }),
2011 // Use error handler to silence the stderr output
2012 nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, _ error) {
2013 }))
2014 if err != nil {
2015 t.Fatalf("Expected to be able to connect, got: %s", err)
2016 }
2017 defer nc2.Close()
2018
2019 var (
2020 pubErr error
2021 nc2Err error
2022 tm = time.NewTimer(5 * time.Second)
2023 )
2024
2025 forLoop:
2026 for {
2027 select {
2028 case <-time.After(100 * time.Millisecond):
2029 // We are trying to get the flusher to report the error, but it
2030 // is possible that the Publish() call itself flushes and we don't
2031 // want to fail the test for that.
2032 pubErr = nc2.Publish("world", payloadBytes)
2033 nc2Err = nc2.LastError()
2034 if nc2Err != nil {
2035 break forLoop
2036 }
2037 case <-tm.C:
2038 // We got an error, but not from flusher. Don't fail yet. Will check
2039 // if this is a timeout error as expected.
2040 if pubErr != nil {
2041 break forLoop
2042 }
2043 t.Fatalf("Timeout publishing messages")
2044 }
2045 }
2046
2047 // Close nc2 to fire its ClosedHandler, which signals the publisher
2048 // goroutine (via doneCh) to exit. The fake server is torn down by
2049 // the t.Cleanup registered in startStalledFakeServer.
2050 nc2.Close()
2051 wg.Wait()
2052
2053 // One of those two are guaranteed to be set.
2054 err = nc2Err
2055 if err == nil {
2056 err = pubErr
2057 }
2058 // Check that error is a timeout error as expected.
2059 ope, ok := err.(*net.OpError)
2060 if !ok {
2061 t.Fatalf("expected a net.Error, got %v", err)
2062 }
2063 if !ope.Timeout() {
2064 t.Fatalf("expected a timeout, got %v", err)
2065 }
2066 if ope.Op != "write" {
2067 t.Fatalf("expected a write error, got %v", err)
2068 }
2069
2070 // Check that there is no error from nc1
2071 select {
2072 case e := <-errCh:
2073 t.Fatal(e)
2074 default:
2075 }
2076 })
2077 }
2078
2079 // startStalledMockServer starts a fake NATS server on an ephemeral port
2080 // that completes the INFO/CONNECT/PING handshake and then stops reading
2081 // from the socket, so client writes eventually stall.
2082 func startStalledMockServer(t *testing.T) *net.TCPAddr {
2083 t.Helper()
2084 l, err := net.Listen("tcp", "127.0.0.1:0")
2085 if err != nil {
2086 t.Fatalf("Could not listen on an ephemeral port: %v", err)
2087 }
2088 addr := l.Addr().(*net.TCPAddr)
2089
2090 done := make(chan struct{})
2091 exited := make(chan struct{})
2092
2093 go func() {
2094 defer close(exited)
2095 conn, err := l.Accept()
2096 if err != nil {
2097 return
2098 }
2099 defer conn.Close()
2100 if err := conn.(*net.TCPConn).SetReadBuffer(1024); err != nil {
2101 t.Errorf("Expected SetReadBuffer to succeed, got: %v", err)
2102 return
2103 }
2104 info := fmt.Sprintf(
2105 "INFO {\"server_id\":\"foobar\",\"host\":\"%s\",\"port\":%d,\"auth_required\":false,\"tls_required\":false,\"max_payload\":%d}\r\n",
2106 addr.IP, addr.Port, 1024*1024,
2107 )
2108 conn.Write([]byte(info))
2109 line := make([]byte, 100)
2110 if _, err := conn.Read(line); err != nil {
2111 t.Errorf("Expected CONNECT+PING, got: %v", err)
2112 return
2113 }
2114 conn.Write([]byte("PONG\r\n"))
2115 <-done
2116 }()
2117
2118 t.Cleanup(func() {
2119 close(done)
2120 l.Close()
2121 <-exited
2122 })
2123 return addr
2124 }
2125
2126 func TestReconnectOnFlusherError(t *testing.T) {
2127 if runtime.GOOS == "windows" {
2128 t.SkipNow()
2129 }
2130
2131 for _, tc := range []struct {
2132 name string
2133 withOption bool
2134 noReconnect bool
2135 wantReconnect bool
2136 wantClosed bool
2137 }{
2138 {"enabled", true, false, true, false},
2139 {"disabled", false, false, false, false},
2140 {"no_reconnect", true, true, false, true},
2141 } {
2142 t.Run(tc.name, func(t *testing.T) {
2143 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
2144 realURL := inst.Servers[0].URL
2145 fakeAddr := startStalledMockServer(t)
2146
2147 reconnectedCh := make(chan struct{}, 1)
2148 closedCh := make(chan struct{}, 1)
2149 asyncErrCh := make(chan error, 1)
2150
2151 opts := []nats.Option{
2152 nats.SetCustomDialer(&lowWriteBufferDialer{}),
2153 nats.FlusherTimeout(15 * time.Millisecond),
2154 nats.MaxReconnects(10),
2155 nats.DontRandomize(),
2156 nats.ReconnectHandler(func(_ *nats.Conn) {
2157 select {
2158 case reconnectedCh <- struct{}{}:
2159 default:
2160 }
2161 }),
2162 nats.ClosedHandler(func(_ *nats.Conn) {
2163 select {
2164 case closedCh <- struct{}{}:
2165 default:
2166 }
2167 }),
2168 nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
2169 select {
2170 case asyncErrCh <- err:
2171 default:
2172 }
2173 }),
2174 }
2175 if tc.withOption {
2176 opts = append(opts, nats.ReconnectOnFlusherError())
2177 }
2178 if tc.noReconnect {
2179 opts = append(opts, nats.NoReconnect())
2180 }
2181
2182 nc, err := nats.Connect(
2183 fmt.Sprintf("nats://127.0.0.1:%d,%s", fakeAddr.Port, realURL),
2184 opts...,
2185 )
2186 if err != nil {
2187 t.Fatalf("Connect: %v", err)
2188 }
2189 defer nc.Close()
2190
2191 if url := nc.ConnectedUrl(); url != fmt.Sprintf("nats://127.0.0.1:%d", fakeAddr.Port) {
2192 t.Fatalf("Expected initial connection to fake server, got %q", url)
2193 }
2194
2195 stopPub := make(chan struct{})
2196 pubDone := make(chan struct{})
2197 go func() {
2198 defer close(pubDone)
2199 tick := time.NewTicker(50 * time.Millisecond)
2200 defer tick.Stop()
2201 // Slightly under the library's internal buffer size so the
2202 // flusher goroutine (not the Publish call) triggers the write.
2203 payload := make([]byte, 32*1024-200)
2204 for {
2205 select {
2206 case <-stopPub:
2207 return
2208 case <-tick.C:
2209 nc.Publish("hello", payload)
2210 }
2211 }
2212 }()
2213 defer func() {
2214 close(stopPub)
2215 <-pubDone
2216 }()
2217
2218 // Confirm the flusher actually observes a write error.
2219 select {
2220 case <-asyncErrCh:
2221 case <-time.After(3 * time.Second):
2222 t.Fatal("flusher did not report an async write error within 3s")
2223 }
2224
2225 if tc.wantReconnect {
2226 select {
2227 case <-reconnectedCh:
2228 case <-time.After(5 * time.Second):
2229 t.Fatal("expected reconnect after flusher error")
2230 }
2231 if url := nc.ConnectedUrl(); url != realURL {
2232 t.Fatalf("expected to be reconnected to real server %q, got %q", realURL, url)
2233 }
2234 } else if tc.wantClosed {
2235 WaitOnChannel(t, closedCh, struct{}{})
2236 if !nc.IsClosed() {
2237 t.Fatalf("expected IsClosed() to be true, got status %v", nc.Status())
2238 }
2239 } else {
2240 select {
2241 case <-reconnectedCh:
2242 t.Fatal("unexpected reconnect when ReconnectOnFlusherError is disabled")
2243 case <-time.After(500 * time.Millisecond):
2244 }
2245 }
2246 })
2247 })
2248 }
2249 }
2250
2251 func TestNewServers(t *testing.T) {
2252 c := newTester(t)
2253 // Pre-create a 3-node cluster, immediately stop the third node so clients
2254 // connect to what looks like a 2-node cluster. Bringing the third node
2255 // back must fire DiscoveredServersHandler on all three connections.
2256 inst := c.CreateCluster(t, 3, false)
2257 t.Cleanup(func() { inst.Destroy(t) })
2258
2259 joiner := inst.Servers[2]
2260 inst.StopServer(t, joiner)
2261
2262 // Give the remaining two nodes a moment to settle into a 2-node view.
2263 time.Sleep(500 * time.Millisecond)
2264
2265 ch := make(chan bool, 16)
2266 cb := func(_ *nats.Conn) {
2267 ch <- true
2268 }
2269 url := inst.Servers[0].URL
2270 nc1, err := nats.Connect(url, nats.DiscoveredServersHandler(cb))
2271 if err != nil {
2272 t.Fatalf("Error on connect: %v", err)
2273 }
2274 defer nc1.Close()
2275
2276 nc2, err := nats.Connect(url)
2277 if err != nil {
2278 t.Fatalf("Error on connect: %v", err)
2279 }
2280 defer nc2.Close()
2281 nc2.SetDiscoveredServersHandler(cb)
2282
2283 opts := nats.GetDefaultOptions()
2284 opts.Url = url
2285 opts.DiscoveredServersCB = cb
2286 nc3, err := opts.Connect()
2287 if err != nil {
2288 t.Fatalf("Error on connect: %v", err)
2289 }
2290 defer nc3.Close()
2291
2292 // Make sure that handler is not invoked on initial connect.
2293 select {
2294 case <-ch:
2295 t.Fatalf("Handler should not have been invoked")
2296 case <-time.After(500 * time.Millisecond):
2297 }
2298
2299 // Bring the third node back; the existing cluster gossips its return
2300 // to the clients via connect_urls INFO. Each of the three connections
2301 // should fire its DiscoveredServersHandler.
2302 inst.StartServer(t, joiner)
2303
2304 for i := 0; i < 3; i++ {
2305 if err := Wait(ch); err != nil {
2306 t.Fatalf("Did not get our callback (iteration %d)", i)
2307 }
2308 }
2309 }
2310
2311 func TestBarrier(t *testing.T) {
2312 withServerInstance(t, func(t *testing.T, nc *nats.Conn, inst *testservice.Instance) {
2313 pubMsgs := int32(0)
2314 ch := make(chan bool, 1)
2315
2316 sub1, err := nc.Subscribe("pub", func(_ *nats.Msg) {
2317 atomic.AddInt32(&pubMsgs, 1)
2318 time.Sleep(250 * time.Millisecond)
2319 })
2320 if err != nil {
2321 t.Fatalf("Error on subscribe: %v", err)
2322 }
2323
2324 sub2, err := nc.Subscribe("close", func(_ *nats.Msg) {
2325 // The "close" message was sent/received lat, but
2326 // because we are dealing with different subscriptions,
2327 // which are dispatched by different dispatchers, and
2328 // because the "pub" subscription is delayed, this
2329 // callback is likely to be invoked before the sub1's
2330 // second callback is invoked. Using the Barrier call
2331 // here will ensure that the given function will be invoked
2332 // after the preceding messages have been dispatched.
2333 nc.Barrier(func() {
2334 res := atomic.LoadInt32(&pubMsgs) == 2
2335 ch <- res
2336 })
2337 })
2338 if err != nil {
2339 t.Fatalf("Error on subscribe: %v", err)
2340 }
2341
2342 // Send 2 "pub" messages followed by a "close" message
2343 for i := 0; i < 2; i++ {
2344 if err := nc.Publish("pub", []byte("pub msg")); err != nil {
2345 t.Fatalf("Error on publish: %v", err)
2346 }
2347 }
2348 if err := nc.Publish("close", []byte("closing")); err != nil {
2349 t.Fatalf("Error on publish: %v", err)
2350 }
2351
2352 select {
2353 case ok := <-ch:
2354 if !ok {
2355 t.Fatal("The barrier function was invoked before the second message")
2356 }
2357 case <-time.After(2 * time.Second):
2358 t.Fatal("Waited for too long...")
2359 }
2360
2361 // Remove all subs
2362 sub1.Unsubscribe()
2363 sub2.Unsubscribe()
2364
2365 // Barrier should be invoked in place. Since we use buffered channel
2366 // we are ok.
2367 nc.Barrier(func() { ch <- true })
2368 if err := Wait(ch); err != nil {
2369 t.Fatal("Barrier function was not invoked")
2370 }
2371
2372 if _, err := nc.Subscribe("foo", func(m *nats.Msg) {
2373 // To check that the Barrier() function works if the subscription
2374 // is unsubscribed after the call was made, sleep a bit here.
2375 time.Sleep(250 * time.Millisecond)
2376 m.Sub.Unsubscribe()
2377 }); err != nil {
2378 t.Fatalf("Error on subscribe: %v", err)
2379 }
2380 if err := nc.Publish("foo", []byte("hello")); err != nil {
2381 t.Fatalf("Error on publish: %v", err)
2382 }
2383 // We need to Flush here to make sure that message has been received
2384 // and posted to subscription's internal queue before calling Barrier.
2385 if err := nc.Flush(); err != nil {
2386 t.Fatalf("Error on flush: %v", err)
2387 }
2388 nc.Barrier(func() { ch <- true })
2389 if err := Wait(ch); err != nil {
2390 t.Fatal("Barrier function was not invoked")
2391 }
2392
2393 // Test with AutoUnsubscribe now...
2394 sub1, err = nc.Subscribe("foo", func(m *nats.Msg) {
2395 // Since we auto-unsubscribe with 1, there should not be another
2396 // invocation of this callback, but the Barrier should still be
2397 // invoked.
2398 nc.Barrier(func() { ch <- true })
2399 })
2400 if err != nil {
2401 t.Fatalf("Error on subscribe: %v", err)
2402 }
2403 sub1.AutoUnsubscribe(1)
2404 // Send 2 messages and flush
2405 for i := 0; i < 2; i++ {
2406 if err := nc.Publish("foo", []byte("hello")); err != nil {
2407 t.Fatalf("Error on publish: %v", err)
2408 }
2409 }
2410 if err := nc.Flush(); err != nil {
2411 t.Fatalf("Error on flush: %v", err)
2412 }
2413 // Check barrier was invoked
2414 if err := Wait(ch); err != nil {
2415 t.Fatal("Barrier function was not invoked")
2416 }
2417
2418 // Check that Barrier only affects asynchronous subscriptions
2419 sub1, err = nc.Subscribe("foo", func(m *nats.Msg) {
2420 nc.Barrier(func() { ch <- true })
2421 })
2422 if err != nil {
2423 t.Fatalf("Error on subscribe: %v", err)
2424 }
2425 syncSub, err := nc.SubscribeSync("foo")
2426 if err != nil {
2427 t.Fatalf("Error on subscribe: %v", err)
2428 }
2429 msgChan := make(chan *nats.Msg, 1)
2430 chanSub, err := nc.ChanSubscribe("foo", msgChan)
2431 if err != nil {
2432 t.Fatalf("Error on subscribe: %v", err)
2433 }
2434 if err := nc.Publish("foo", []byte("hello")); err != nil {
2435 t.Fatalf("Error on publish: %v", err)
2436 }
2437 if err := nc.Flush(); err != nil {
2438 t.Fatalf("Error on flush: %v", err)
2439 }
2440 // Check barrier was invoked even if we did not yet consume
2441 // from the 2 other type of subscriptions
2442 if err := Wait(ch); err != nil {
2443 t.Fatal("Barrier function was not invoked")
2444 }
2445 if _, err := syncSub.NextMsg(time.Second); err != nil {
2446 t.Fatalf("Sync sub did not receive the message")
2447 }
2448 select {
2449 case <-msgChan:
2450 case <-time.After(time.Second):
2451 t.Fatal("Chan sub did not receive the message")
2452 }
2453 chanSub.Unsubscribe()
2454 syncSub.Unsubscribe()
2455 sub1.Unsubscribe()
2456
2457 atomic.StoreInt32(&pubMsgs, 0)
2458 // Check barrier does not prevent new messages to be delivered.
2459 sub1, err = nc.Subscribe("foo", func(_ *nats.Msg) {
2460 if pm := atomic.AddInt32(&pubMsgs, 1); pm == 1 {
2461 nc.Barrier(func() {
2462 nc.Publish("foo", []byte("second"))
2463 nc.Flush()
2464 })
2465 } else if pm == 2 {
2466 ch <- true
2467 }
2468 })
2469 if err != nil {
2470 t.Fatalf("Error on subscribe: %v", err)
2471 }
2472 if err := nc.Publish("foo", []byte("first")); err != nil {
2473 t.Fatalf("Error on publish: %v", err)
2474 }
2475 if err := Wait(ch); err != nil {
2476 t.Fatal("Barrier function was not invoked")
2477 }
2478 sub1.Unsubscribe()
2479
2480 // Check that barrier works if called before connection
2481 // is closed.
2482 if _, err := nc.Subscribe("bar", func(_ *nats.Msg) {
2483 nc.Barrier(func() { ch <- true })
2484 nc.Close()
2485 }); err != nil {
2486 t.Fatalf("Error on subscribe: %v", err)
2487 }
2488 if err := nc.Publish("bar", []byte("hello")); err != nil {
2489 t.Fatalf("Error on publish: %v", err)
2490 }
2491 // This could fail if the connection is closed before we get
2492 // here.
2493 nc.Flush()
2494 if err := Wait(ch); err != nil {
2495 t.Fatal("Barrier function was not invoked")
2496 }
2497
2498 // Finally, check that if connection is closed, Barrier returns
2499 // an error.
2500 if err := nc.Barrier(func() { ch <- true }); err != nats.ErrConnectionClosed {
2501 t.Fatalf("Expected error %v, got %v", nats.ErrConnectionClosed, err)
2502 }
2503
2504 // Check that one can call connection methods from Barrier
2505 // when there is no async subscriptions
2506 nc2, err := nats.Connect(inst.Servers[0].URL)
2507 if err != nil {
2508 t.Fatalf("Failed to connect: %v", err)
2509 }
2510 defer nc2.Close()
2511
2512 if err := nc2.Barrier(func() {
2513 ch <- nc2.TLSRequired()
2514 }); err != nil {
2515 t.Fatalf("Error on Barrier: %v", err)
2516 }
2517 if err := Wait(ch); err != nil {
2518 t.Fatal("Barrier was blocked")
2519 }
2520 })
2521 }
2522
2523 func TestReceiveInfoRightAfterFirstPong(t *testing.T) {
2524 l, err := net.Listen("tcp", "127.0.0.1:0")
2525 if err != nil {
2526 t.Fatalf("Error on listen: %v", err)
2527 }
2528 tl := l.(*net.TCPListener)
2529 defer tl.Close()
2530 addr := tl.Addr().(*net.TCPAddr)
2531
2532 wg := sync.WaitGroup{}
2533 wg.Add(1)
2534 go func() {
2535 defer wg.Done()
2536
2537 c, err := tl.Accept()
2538 if err != nil {
2539 return
2540 }
2541 defer c.Close()
2542 // Send the initial INFO
2543 c.Write([]byte("INFO {}\r\n"))
2544 buf := make([]byte, 0, 100)
2545 b := make([]byte, 100)
2546 for {
2547 n, err := c.Read(b)
2548 if err != nil {
2549 return
2550 }
2551 buf = append(buf, b[:n]...)
2552 if bytes.Contains(buf, []byte("PING\r\n")) {
2553 break
2554 }
2555 }
2556 // Send PONG and following INFO in one go (or at least try).
2557 // The processing of PONG in sendConnect() should leave the
2558 // rest for the readLoop to process.
2559 c.Write([]byte(fmt.Sprintf("PONG\r\nINFO {\"connect_urls\":[\"127.0.0.1:%d\", \"me:1\"]}\r\n", addr.Port)))
2560 // Wait for client to disconnect
2561 for {
2562 if _, err := c.Read(buf); err != nil {
2563 return
2564 }
2565 }
2566 }()
2567
2568 nc, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", addr.Port))
2569 if err != nil {
2570 t.Fatalf("Error on connect: %v", err)
2571 }
2572 defer nc.Close()
2573 var (
2574 ds []string
2575 timeout = time.Now().Add(2 * time.Second)
2576 ok = false
2577 )
2578 for time.Now().Before(timeout) {
2579 ds = nc.DiscoveredServers()
2580 if len(ds) == 1 && ds[0] == "nats://me:1" {
2581 ok = true
2582 break
2583 }
2584 time.Sleep(50 * time.Millisecond)
2585 }
2586 nc.Close()
2587 wg.Wait()
2588 if !ok {
2589 t.Fatalf("Unexpected discovered servers: %v", ds)
2590 }
2591 }
2592
2593 func TestReceiveInfoWithEmptyConnectURLs(t *testing.T) {
2594 // Self-contained: this test binds its own mock TCP listeners. The ports are
2595 // shifted off the defaults because 4222 belongs to the tester's management
2596 // endpoint when its ports are published.
2597 const (
2598 listenPort1 = 50222
2599 listenPort2 = 50223
2600 extraPort = 50224
2601 )
2602 ready := make(chan error, 2)
2603 ch := make(chan bool, 1)
2604 wg := sync.WaitGroup{}
2605 wg.Add(1)
2606
2607 go func() {
2608 defer wg.Done()
2609
2610 ports := []int{listenPort1, listenPort2}
2611 for i := 0; i < 2; i++ {
2612 l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", ports[i]))
2613 if err != nil {
2614 ready <- fmt.Errorf("error on listen: %v", err)
2615 return
2616 }
2617 tl := l.(*net.TCPListener)
2618 defer tl.Close()
2619
2620 ready <- nil
2621
2622 c, err := tl.Accept()
2623 if err != nil {
2624 return
2625 }
2626 defer c.Close()
2627
2628 c.Write([]byte(fmt.Sprintf("INFO {\"server_id\":\"server%d\"}\r\n", (i + 1))))
2629 buf := make([]byte, 0, 100)
2630 b := make([]byte, 100)
2631 for {
2632 n, err := c.Read(b)
2633 if err != nil {
2634 return
2635 }
2636 buf = append(buf, b[:n]...)
2637 if bytes.Contains(buf, []byte("PING\r\n")) {
2638 break
2639 }
2640 }
2641 if i == 0 {
2642 c.Write([]byte(fmt.Sprintf("PONG\r\nINFO {\"server_id\":\"server1\",\"connect_urls\":[\"127.0.0.1:%d\", \"127.0.0.1:%d\", \"127.0.0.1:%d\"]}\r\n",
2643 listenPort1, listenPort2, extraPort)))
2644 <-ch
2645 c.Close()
2646 } else {
2647 c.Write([]byte("PONG\r\nINFO {\"server_id\":\"server2\"}\r\n"))
2648 for {
2649 if _, err := c.Read(buf); err != nil {
2650 return
2651 }
2652 }
2653 }
2654 }
2655 }()
2656
2657 e := <-ready
2658 if e != nil {
2659 t.Fatal(e.Error())
2660 }
2661
2662 rch := make(chan bool)
2663 nc, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", listenPort1),
2664 nats.ReconnectWait(50*time.Millisecond),
2665 nats.ReconnectJitter(0, 0),
2666 nats.ReconnectHandler(func(_ *nats.Conn) {
2667 rch <- true
2668 }))
2669 if err != nil {
2670 t.Fatalf("Error on connect: %v", err)
2671 }
2672 defer nc.Close()
2673 var (
2674 ds []string
2675 timeout = time.Now().Add(2 * time.Second)
2676 ok = false
2677 )
2678 want2 := fmt.Sprintf("nats://127.0.0.1:%d", listenPort2)
2679 want3 := fmt.Sprintf("nats://127.0.0.1:%d", extraPort)
2680 for time.Now().Before(timeout) {
2681 ds = nc.DiscoveredServers()
2682 if len(ds) == 2 {
2683 if (ds[0] == want2 && ds[1] == want3) ||
2684 (ds[0] == want3 && ds[1] == want2) {
2685 ok = true
2686 break
2687 }
2688 }
2689 time.Sleep(50 * time.Millisecond)
2690 }
2691 if !ok {
2692 t.Fatalf("Unexpected discovered servers: %v", ds)
2693 }
2694 ch <- true
2695 if err := Wait(rch); err != nil {
2696 t.Fatal("Did not reconnect")
2697 }
2698 ds = nc.DiscoveredServers()
2699 if len(ds) != 2 ||
2700 !((ds[0] == want2 && ds[1] == want3) ||
2701 (ds[0] == want3 && ds[1] == want2)) {
2702 t.Fatalf("Unexpected discovered servers list: %v", ds)
2703 }
2704 nc.Close()
2705 wg.Wait()
2706 }
2707
2708 func TestNilOpts(t *testing.T) {
2709 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
2710 // Test a single nil option
2711 var o1, o2, o3 nats.Option
2712 nc, err := nats.Connect(inst.Servers[0].URL, o1)
2713 if err != nil {
2714 t.Fatalf("Unexpected error with one nil option: %v", err)
2715 }
2716 nc.Close()
2717
2718 // Test nil, opt, nil
2719 o2 = nats.ReconnectBufSize(2222)
2720 nc, err = nats.Connect(inst.Servers[0].URL, o1, o2, o3)
2721 if err != nil {
2722 t.Fatalf("Unexpected error with multiple nil options: %v", err)
2723 }
2724 defer nc.Close()
2725 // check that the opt was set
2726 if nc.Opts.ReconnectBufSize != 2222 {
2727 t.Fatal("Unexpected error: option not set.")
2728 }
2729 })
2730 }
2731
2732 func TestGetClientID(t *testing.T) {
2733 c := newTester(t)
2734 inst := c.CreateCluster(t, 2, false)
2735 t.Cleanup(func() { inst.Destroy(t) })
2736
2737 srvA := inst.Servers[0]
2738 srvB := inst.Servers[1]
2739
2740 // Separate channels for discovery vs reconnect so the CID-stability check
2741 // (CID must NOT change when an async INFO updates the server pool) is
2742 // independent from the failover check (CID must change after reconnect).
2743 discoveredCh := make(chan bool, 4)
2744 reconnectCh := make(chan bool, 2)
2745 // Pass both URLs so the client knows where to fail over to even if cluster
2746 // discovery hasn't completed yet.
2747 allURLs := srvA.URL + "," + srvB.URL
2748 nc1, err := nats.Connect(allURLs,
2749 nats.MaxReconnects(-1),
2750 nats.ReconnectWait(50*time.Millisecond),
2751 nats.DontRandomize(),
2752 nats.DiscoveredServersHandler(func(_ *nats.Conn) {
2753 select {
2754 case discoveredCh <- true:
2755 default:
2756 }
2757 }),
2758 nats.ReconnectHandler(func(_ *nats.Conn) {
2759 reconnectCh <- true
2760 }))
2761 if err != nil {
2762 t.Fatalf("Error on connect: %v", err)
2763 }
2764 defer nc1.Close()
2765
2766 cid, err := nc1.GetClientID()
2767 if err != nil {
2768 t.Fatalf("Error getting CID: %v", err)
2769 }
2770 if cid == 0 {
2771 t.Fatal("Unexpected cid value, make sure server is 1.2.0+")
2772 }
2773
2774 // CID-stability: when the cluster gossips and an async INFO updates the
2775 // server pool, the existing connection's CID must NOT change (only
2776 // reconnect changes it). Wait for at least one discovery and re-check.
2777 if err := Wait(discoveredCh); err == nil {
2778 stableCID, err := nc1.GetClientID()
2779 if err != nil {
2780 t.Fatalf("Error getting CID after discovery: %v", err)
2781 }
2782 if stableCID != cid {
2783 t.Fatalf("CID changed after async INFO discovery: %v -> %v", cid, stableCID)
2784 }
2785 }
2786
2787 // Create a client to server B
2788 nc2, err := nats.Connect(srvB.URL)
2789 if err != nil {
2790 t.Fatalf("Error on connect: %v", err)
2791 }
2792 defer nc2.Close()
2793
2794 // Stop server A, nc1 will reconnect to B, and should have different CID
2795 inst.StopServer(t, srvA)
2796 // Wait for nc1 to reconnect
2797 if err := Wait(reconnectCh); err != nil {
2798 t.Fatal("Did not reconnect")
2799 }
2800 newCID, err := nc1.GetClientID()
2801 if err != nil {
2802 t.Fatalf("Error getting CID: %v", err)
2803 }
2804 if newCID == 0 {
2805 t.Fatal("Unexpected cid value, make sure server is 1.2.0+")
2806 }
2807 if newCID == cid {
2808 t.Fatalf("Expected different CID since server already had a client")
2809 }
2810 nc1.Close()
2811 newCID, err = nc1.GetClientID()
2812 if err == nil {
2813 t.Fatalf("Expected error, got none")
2814 }
2815 if newCID != 0 {
2816 t.Fatalf("Expected 0 on connection closed, got %v", newCID)
2817 }
2818
2819 // Stop clients and remaining server
2820 nc1.Close()
2821 nc2.Close()
2822
2823 // Now have dummy server that returns no CID and check we get expected error.
2824 l, e := net.Listen("tcp", "127.0.0.1:0")
2825 if e != nil {
2826 t.Fatal("Could not listen on an ephemeral port")
2827 }
2828 tl := l.(*net.TCPListener)
2829 defer tl.Close()
2830
2831 addr := tl.Addr().(*net.TCPAddr)
2832
2833 wg := sync.WaitGroup{}
2834 wg.Add(1)
2835 errCh := make(chan error, 1)
2836 mockCh := make(chan bool, 1)
2837 go func() {
2838 defer wg.Done()
2839 conn, err := l.Accept()
2840 if err != nil {
2841 errCh <- fmt.Errorf("error accepting client connection: %v", err)
2842 return
2843 }
2844 defer conn.Close()
2845 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)
2846 conn.Write([]byte(info))
2847
2848 // Read connect and ping commands sent from the client
2849 line := make([]byte, 256)
2850 _, err = conn.Read(line)
2851 if err != nil {
2852 errCh <- fmt.Errorf("expected CONNECT and PING from client, got: %s", err)
2853 return
2854 }
2855 conn.Write([]byte("PONG\r\n"))
2856 // Now wait to be notified that we can finish
2857 <-mockCh
2858 }()
2859
2860 nc, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", addr.Port))
2861 if err != nil {
2862 t.Fatalf("Error on connect: %v", err)
2863 }
2864 defer nc.Close()
2865
2866 if cid, err := nc.GetClientID(); err != nats.ErrClientIDNotSupported || cid != 0 {
2867 t.Fatalf("Expected err=%v and cid=0, got err=%v and cid=%v", nats.ErrClientIDNotSupported, err, cid)
2868 }
2869 // Release fake server
2870 nc.Close()
2871 mockCh <- true
2872 wg.Wait()
2873 checkErrChannel(t, errCh)
2874 }
2875
2876 func TestTLSDontSkipVerify(t *testing.T) {
2877 c := newTester(t)
2878 // SANs intentionally exclude IPs so the 127.0.0.1 URL trips IP-SAN
2879 // verification; the testerHost name is included so the host:port URL
2880 // below verifies in both host-side ("localhost") and sibling-container
2881 // ("nats") modes.
2882 sans := []string{"localhost"}
2883 if h := testerHost(t); h != "localhost" {
2884 sans = append(sans, h)
2885 }
2886 tlsOpt := testservice.WithGeneratedTLS(testservice.TLSServerOnly(), testservice.TLSSANs(sans...))
2887 opts := append([]testservice.CreateOption{tlsOpt}, singleUserPassOpts(derekAuthBody())...)
2888 inst := c.CreateServer(t, false, opts...)
2889 t.Cleanup(func() { inst.Destroy(t) })
2890 caPath, _, _ := tlsCertFiles(t, inst)
2891
2892 host := hostFromURL(inst.Servers[0].URL)
2893 port := inst.Servers[0].Port
2894
2895 // Resolve testerHost to an IP so the IP-SAN check below trips on a real
2896 // reachable address. In host-side mode testerHost is "localhost" → 127.0.0.1
2897 // is reachable directly; in sibling-container / CI mode 127.0.0.1 points at
2898 // the test container itself and the spawned server lives behind the docker
2899 // service name, so we have to dial via the resolved IP of testerHost.
2900 ip := "127.0.0.1"
2901 if host != "localhost" && host != "127.0.0.1" {
2902 ips, lerr := net.LookupHost(host)
2903 if lerr != nil || len(ips) == 0 {
2904 t.Fatalf("could not resolve %q to an IP: %v", host, lerr)
2905 }
2906 ip = ips[0]
2907 }
2908
2909 // Connect with nats:// prefix to a server that requires TLS.
2910 // The library will automatically switch to TLS, but we should
2911 // not skip hostname verification.
2912 sURL := fmt.Sprintf("nats://derek:porkchop@%s:%d", ip, port)
2913 nc, err := nats.Connect(sURL, nats.RootCAs(caPath))
2914 // Verify that error is about hostname verification
2915 if err == nil || !strings.Contains(err.Error(), "IP SAN") {
2916 if nc != nil {
2917 nc.Close()
2918 }
2919 t.Fatalf("Expected error about hostname verification, got %v", err)
2920 }
2921 // Check that we can override skip verify by providing our own TLS Config.
2922 nc, err = nats.Connect(sURL, nats.RootCAs(caPath),
2923 nats.Secure(&tls.Config{InsecureSkipVerify: true}))
2924 if err != nil {
2925 t.Fatalf("Error on connect: %v", err)
2926 }
2927 nc.Close()
2928
2929 // Now change the URL to include hostname and verify that using
2930 // nats:// scheme does work.
2931 sURL = fmt.Sprintf("nats://derek:porkchop@%s:%d", host, port)
2932 nc, err = nats.Connect(sURL, nats.RootCAs(caPath))
2933 if err != nil {
2934 t.Fatalf("Error on connect: %v", err)
2935 }
2936 nc.Close()
2937 }
2938
2939 func TestRetryOnFailedConnect(t *testing.T) {
2940 // Flipping auth on between restarts is not covered anywhere: it needs a
2941 // port-preserving reconfigure API the tester lacks, and
2942 // TestRetryOnFailedConnectWithAuthError caps MaxReconnects at 2, so its
2943 // close cannot distinguish auth-abort from retry exhaustion.
2944 c := newTester(t)
2945 inst := c.CreateServer(t, false)
2946 t.Cleanup(func() { inst.Destroy(t) })
2947
2948 srv := inst.Servers[0]
2949 url := srv.URL
2950
2951 // Bring the server down so the initial connect fails — RetryOnFailedConnect
2952 // should then retry until we bring it back.
2953 inst.StopServer(t, srv)
2954
2955 // First, prove a plain connect actually fails right now.
2956 if nc, err := nats.Connect(url, nats.Timeout(200*time.Millisecond), nats.MaxReconnects(0)); err == nil {
2957 nc.Close()
2958 t.Fatal("Expected error, did not get one")
2959 }
2960
2961 reconnectedCh := make(chan bool, 1)
2962 connectedCh := make(chan bool, 1)
2963 dch := make(chan bool, 1)
2964 nc, err := nats.Connect(url,
2965 nats.RetryOnFailedConnect(true),
2966 nats.MaxReconnects(-1),
2967 nats.ReconnectWait(15*time.Millisecond),
2968 nats.DisconnectErrHandler(func(_ *nats.Conn, _ error) {
2969 dch <- true
2970 }),
2971 nats.ConnectHandler(func(_ *nats.Conn) {
2972 connectedCh <- true
2973 }),
2974 nats.ReconnectHandler(func(_ *nats.Conn) {
2975 reconnectedCh <- true
2976 }),
2977 nats.NoCallbacksAfterClientClose())
2978 if err != nil {
2979 t.Fatalf("Unexpected error: %v", err)
2980 }
2981 defer nc.Close()
2982
2983 sub, err := nc.SubscribeSync("foo")
2984 if err != nil {
2985 t.Fatalf("Error on subscribe: %v", err)
2986 }
2987 if err := nc.Publish("foo", []byte("msg")); err != nil {
2988 t.Fatalf("Error on publish: %v", err)
2989 }
2990
2991 for i := 0; i < 2; i++ {
2992 // Bring the server back; first iteration fires ConnectHandler,
2993 // second fires ReconnectHandler.
2994 inst.StartServer(t, srv)
2995
2996 switch i {
2997 case 0:
2998 select {
2999 case <-connectedCh:
3000 case <-time.After(2 * time.Second):
3001 t.Fatal("Should have connected")
3002 }
3003 case 1:
3004 select {
3005 case <-reconnectedCh:
3006 case <-time.After(2 * time.Second):
3007 t.Fatal("Should have reconnected")
3008 }
3009 }
3010
3011 // The message we queued before the server came up should arrive.
3012 if _, err := sub.NextMsg(time.Second); err != nil {
3013 t.Fatalf("Iter=%v - did not receive message: %v", i, err)
3014 }
3015
3016 // Take the server down again; DisconnectErrHandler should fire.
3017 inst.StopServer(t, srv)
3018
3019 select {
3020 case <-dch:
3021 case <-time.After(time.Second):
3022 t.Fatal("Should have been disconnected")
3023 }
3024
3025 if i == 0 {
3026 if err := nc.Publish("foo", []byte("msg")); err != nil {
3027 t.Fatalf("Iter=%v - error on publish: %v", i, err)
3028 }
3029 }
3030 }
3031 nc.Close()
3032 }
3033
3034 func TestRetryOnFailedConnectReconnectErrCB(t *testing.T) {
3035 errChan := make(chan error, 10)
3036
3037 nc, err := nats.Connect("nats://127.0.0.1:1",
3038 nats.RetryOnFailedConnect(true),
3039 nats.MaxReconnects(0), // Limited retries for faster test
3040 nats.ReconnectWait(10*time.Millisecond),
3041 nats.ReconnectErrHandler(func(_ *nats.Conn, err error) {
3042 errChan <- err
3043 }),
3044 )
3045 if err != nil {
3046 t.Fatalf("Unexpected error: %v", err)
3047 }
3048 defer nc.Close()
3049
3050 // Verify the first error is the initial connection error
3051 select {
3052 case err := <-errChan:
3053 if !errors.Is(err, nats.ErrNoServers) {
3054 t.Fatalf("Expected ErrNoServers for initial connection failure, got: %v", err)
3055 }
3056 case <-time.After(200 * time.Millisecond):
3057 t.Fatal("Should have received initial connection error in ReconnectErrCB")
3058 }
3059 }
3060
3061 func TestRetryOnFailedConnectWithAuthError(t *testing.T) {
3062 c := newTester(t)
3063 inst := c.CreateServer(t, false, singleUserPassOpts(`authorization {
3064 user: user
3065 password: password
3066 }`)...)
3067 t.Cleanup(func() { inst.Destroy(t) })
3068
3069 errChan := make(chan error, 10)
3070 closedCh := make(chan bool, 1)
3071
3072 // Try to connect without credentials
3073 nc, err := nats.Connect(inst.Servers[0].URL,
3074 nats.RetryOnFailedConnect(true),
3075 nats.MaxReconnects(2),
3076 nats.ReconnectWait(10*time.Millisecond),
3077 nats.ReconnectErrHandler(func(_ *nats.Conn, err error) {
3078 errChan <- err
3079 }),
3080 nats.ClosedHandler(func(_ *nats.Conn) {
3081 closedCh <- true
3082 }),
3083 )
3084 if err != nil {
3085 t.Fatalf("Unexpected error: %v", err)
3086 }
3087 defer nc.Close()
3088
3089 // Wait for closed due to auth failure
3090 select {
3091 case <-closedCh:
3092 case <-time.After(500 * time.Millisecond):
3093 t.Fatal("Connection should have closed due to auth failure")
3094 }
3095
3096 select {
3097 case err := <-errChan:
3098 if !errors.Is(err, nats.ErrAuthorization) {
3099 t.Fatalf("Expected ErrAuthorization for auth failure, got: %v", err)
3100 }
3101 case <-time.After(500 * time.Millisecond):
3102 t.Fatal("Should have received authorization error in ReconnectErrCB")
3103 }
3104 }
3105
3106 func TestRetryOnFailedConnectWithTLSError(t *testing.T) {
3107 c := newTester(t)
3108 // Server with a deliberately tiny TLS handshake timeout so the initial
3109 // connect attempts trip the server's handshake timer, exercising the
3110 // retry-on-failed-connect path.
3111 inst := c.CreateServer(t, false,
3112 managedTLSOpts(t, testservice.TLSServerOnly(), testservice.TLSTimeout(100*time.Microsecond)),
3113 )
3114 t.Cleanup(func() { inst.Destroy(t) })
3115
3116 connectedCh := make(chan bool, 1)
3117 nc, err := nats.Connect(inst.Servers[0].URL,
3118 nats.Secure(&tls.Config{InsecureSkipVerify: true}),
3119 nats.RetryOnFailedConnect(true),
3120 nats.MaxReconnects(-1),
3121 nats.ReconnectWait(15*time.Millisecond),
3122 nats.ConnectHandler(func(_ *nats.Conn) {
3123 connectedCh <- true
3124 }),
3125 nats.NoCallbacksAfterClientClose())
3126 if err != nil {
3127 t.Fatalf("Unexpected error: %v", err)
3128 }
3129 defer nc.Close()
3130
3131 // Wait for several failed attempts.
3132 time.Sleep(100 * time.Millisecond)
3133 // Bump TLS timeout to a reasonable value on the running server and reload.
3134 inst.UpdateServer(t, inst.Servers[0], testservice.WithTLSTimeout(2*time.Second))
3135 inst.ReloadServer(t, inst.Servers[0])
3136
3137 select {
3138 case <-connectedCh:
3139 case <-time.After(time.Second):
3140 t.Fatal("Should have connected")
3141 }
3142 }
3143
3144 func TestConnStatusChangedEvents(t *testing.T) {
3145 t.Run("default events", func(t *testing.T) {
3146 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
3147 nc, err := nats.Connect(inst.Servers[0].URL)
3148 if err != nil {
3149 t.Fatalf("Unexpected error: %s", err)
3150 }
3151 statusCh := nc.StatusChanged()
3152 defer close(statusCh)
3153 newStatus := make(chan nats.Status, 10)
3154 // non-blocking channel, so we need to be constantly listening
3155 go func() {
3156 for {
3157 s, ok := <-statusCh
3158 if !ok {
3159 return
3160 }
3161 newStatus <- s
3162 }
3163 }()
3164 time.Sleep(50 * time.Millisecond)
3165
3166 inst.StopServer(t, inst.Servers[0])
3167 WaitOnChannel(t, newStatus, nats.RECONNECTING)
3168
3169 inst.StartServer(t, inst.Servers[0])
3170
3171 WaitOnChannel(t, newStatus, nats.CONNECTED)
3172
3173 nc.Close()
3174 WaitOnChannel(t, newStatus, nats.CLOSED)
3175
3176 select {
3177 case s := <-newStatus:
3178 t.Fatalf("Unexpected status received: %s", s)
3179 case <-time.After(100 * time.Millisecond):
3180 }
3181 })
3182 })
3183
3184 t.Run("custom event only", func(t *testing.T) {
3185 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
3186 nc, err := nats.Connect(inst.Servers[0].URL)
3187 if err != nil {
3188 t.Fatalf("Unexpected error: %s", err)
3189 }
3190 statusCh := nc.StatusChanged(nats.CLOSED)
3191 defer close(statusCh)
3192 newStatus := make(chan nats.Status, 10)
3193 // non-blocking channel, so we need to be constantly listening
3194 go func() {
3195 for {
3196 s, ok := <-statusCh
3197 if !ok {
3198 return
3199 }
3200 newStatus <- s
3201 }
3202 }()
3203 time.Sleep(50 * time.Millisecond)
3204 inst.StopServer(t, inst.Servers[0])
3205 inst.StartServer(t, inst.Servers[0])
3206 nc.Close()
3207 WaitOnChannel(t, newStatus, nats.CLOSED)
3208
3209 select {
3210 case s := <-newStatus:
3211 t.Fatalf("Unexpected status received: %s", s)
3212 case <-time.After(100 * time.Millisecond):
3213 }
3214 })
3215 })
3216 t.Run("do not block on channel if it's not used", func(t *testing.T) {
3217 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
3218 nc, err := nats.Connect(inst.Servers[0].URL)
3219 if err != nil {
3220 t.Fatalf("Unexpected error: %s", err)
3221 }
3222 defer nc.Close()
3223 // do not use the returned channel, client should never block
3224 _ = nc.StatusChanged()
3225 inst.StopServer(t, inst.Servers[0])
3226 inst.StartServer(t, inst.Servers[0])
3227
3228 if err := nc.Publish("foo", []byte("msg")); err != nil {
3229 t.Fatalf("Unexpected error: %v", err)
3230 }
3231 time.Sleep(100 * time.Millisecond)
3232 })
3233 })
3234 }
3235
3236 func TestRemoveStatusListener(t *testing.T) {
3237 t.Run("with channel not closed", func(t *testing.T) {
3238 withServer(t, func(t *testing.T, nc *nats.Conn) {
3239 statusCh := nc.StatusChanged()
3240 done := make(chan struct{})
3241 go func() {
3242 _, ok := <-statusCh
3243 if !ok {
3244 done <- struct{}{}
3245 return
3246 }
3247 }()
3248 time.Sleep(50 * time.Millisecond)
3249
3250 nc.RemoveStatusListener(statusCh)
3251
3252 select {
3253 case <-done:
3254 case <-time.After(time.Second):
3255 t.Fatal("Expected to receive done signal")
3256 }
3257 })
3258 })
3259 t.Run("with channel closed", func(t *testing.T) {
3260 withServer(t, func(t *testing.T, nc *nats.Conn) {
3261 statusCh := nc.StatusChanged()
3262 done := make(chan struct{})
3263 go func() {
3264 _, ok := <-statusCh
3265 if !ok {
3266 done <- struct{}{}
3267 return
3268 }
3269 }()
3270 time.Sleep(50 * time.Millisecond)
3271
3272 close(statusCh)
3273 nc.RemoveStatusListener(statusCh)
3274
3275 select {
3276 case <-done:
3277 case <-time.After(time.Second):
3278 t.Fatal("Expected to receive done signal")
3279 }
3280 })
3281 })
3282 t.Run("does not remove other listeners", func(t *testing.T) {
3283 withServer(t, func(t *testing.T, nc *nats.Conn) {
3284 // Create two status listeners for the same status
3285 statusCh1 := nc.StatusChanged(nats.CLOSED)
3286 statusCh2 := nc.StatusChanged(nats.CLOSED)
3287
3288 // Remove only the first listener
3289 nc.RemoveStatusListener(statusCh1)
3290
3291 // Verify first channel is closed
3292 select {
3293 case _, ok := <-statusCh1:
3294 if ok {
3295 t.Fatal("Expected channel 1 to be closed")
3296 }
3297 default:
3298 t.Fatal("Expected channel 1 to be closed")
3299 }
3300
3301 // Trigger CLOSED status
3302 nc.Close()
3303
3304 // Second listener should still receive the event
3305 select {
3306 case status := <-statusCh2:
3307 if status != nats.CLOSED {
3308 t.Fatalf("Expected CLOSED status, got %v", status)
3309 }
3310 case <-time.After(time.Second):
3311 t.Fatal("Expected second listener to receive CLOSED status")
3312 }
3313 })
3314 })
3315 }
3316
3317 func TestTLSHandshakeFirst(t *testing.T) {
3318 c := newTester(t)
3319 // First server: managed TLS without handshake_first. TLSHandshakeFirst
3320 // client should fail to connect because the server still sends INFO before
3321 // handshake.
3322 classicOpts := append([]testservice.CreateOption{managedTLSOpts(t, testservice.TLSServerOnly())}, singleUserPassOpts(derekAuthBody())...)
3323 classicInst := c.CreateServer(t, false, classicOpts...)
3324 t.Cleanup(func() { classicInst.Destroy(t) })
3325 classicCA, _, _ := tlsCertFiles(t, classicInst)
3326
3327 secureURL := fmt.Sprintf("tls://derek:porkchop@%s:%d", hostFromURL(classicInst.Servers[0].URL), classicInst.Servers[0].Port)
3328 nc, err := nats.Connect(secureURL,
3329 nats.RootCAs(classicCA),
3330 nats.TLSHandshakeFirst())
3331 if err == nil || !strings.Contains(err.Error(), "TLS handshake") {
3332 if err == nil {
3333 nc.Close()
3334 }
3335 t.Fatalf("Expected error about not being a TLS handshake, got %v", err)
3336 }
3337
3338 // Second server: handshake_first enabled. TLSHandshakeFirst client should
3339 // connect and complete the TLS handshake.
3340 hsOpts := append([]testservice.CreateOption{managedTLSOpts(t, testservice.TLSServerOnly(), testservice.TLSHandshakeFirst())}, singleUserPassOpts(derekAuthBody())...)
3341 hsInst := c.CreateServer(t, false, hsOpts...)
3342 t.Cleanup(func() { hsInst.Destroy(t) })
3343 hsCA, _, _ := tlsCertFiles(t, hsInst)
3344
3345 secureURL = fmt.Sprintf("tls://derek:porkchop@%s:%d", hostFromURL(hsInst.Servers[0].URL), hsInst.Servers[0].Port)
3346 nc, err = nats.Connect(secureURL,
3347 nats.RootCAs(hsCA),
3348 nats.TLSHandshakeFirst())
3349 if err != nil {
3350 t.Fatalf("Unexpected error: %v", err)
3351 }
3352 defer nc.Close()
3353
3354 state, err := nc.TLSConnectionState()
3355 if err != nil {
3356 t.Fatalf("Expected connection state: %v", err)
3357 }
3358 if !state.HandshakeComplete {
3359 t.Fatalf("Expected valid connection state")
3360 }
3361 }
3362
3363 func TestTLSHandshakeFirstEOFAfterHandshake(t *testing.T) {
3364 // Simulate a proxy (like nginx) that completes the TLS handshake
3365 // but then closes the connection because the client certificate
3366 // is not trusted. The client should get a descriptive error
3367 // instead of a bare EOF.
3368
3369 cert, err := tls.LoadX509KeyPair("./configs/certs/server.pem", "./configs/certs/key.pem")
3370 if err != nil {
3371 t.Fatalf("Can't load server cert: %v", err)
3372 }
3373 tlsConf := &tls.Config{
3374 Certificates: []tls.Certificate{cert},
3375 ServerName: "localhost",
3376 }
3377
3378 l, err := net.Listen("tcp", "127.0.0.1:0")
3379 if err != nil {
3380 t.Fatalf("Could not listen: %v", err)
3381 }
3382 defer l.Close()
3383
3384 addr := l.Addr().(*net.TCPAddr)
3385
3386 // Mock server: complete TLS handshake then immediately close,
3387 // simulating nginx rejecting an untrusted client cert.
3388 go func() {
3389 conn, err := l.Accept()
3390 if err != nil {
3391 return
3392 }
3393 tlsConn := tls.Server(conn, tlsConf)
3394 tlsConn.Handshake()
3395 // Close without sending INFO — this is what nginx does
3396 // when it rejects the client certificate.
3397 tlsConn.Close()
3398 }()
3399
3400 _, err = nats.Connect(
3401 fmt.Sprintf("tls://localhost:%d", addr.Port),
3402 nats.RootCAs("./configs/certs/ca.pem"),
3403 nats.TLSHandshakeFirst(),
3404 )
3405 if err == nil {
3406 t.Fatal("Expected error, got nil")
3407 }
3408 // Should be detectable as a TLS error.
3409 if !errors.Is(err, nats.ErrTLS) {
3410 t.Fatalf("Expected error to wrap nats.ErrTLS, got: %v", err)
3411 }
3412 // Should still wrap io.EOF for backwards compatibility.
3413 if !errors.Is(err, io.EOF) {
3414 t.Fatalf("Expected error to wrap io.EOF, got: %v", err)
3415 }
3416 }
3417
3418 func TestTLSHandshakeFirstMTLSReject(t *testing.T) {
3419 // Test that when the NATS server itself does mTLS verification
3420 // and rejects the client cert, the error is a clear TLS alert
3421 // (not a wrapped EOF).
3422 c := newTester(t)
3423 // Target server: managed mTLS + handshake_first.
3424 inst := c.CreateServer(t, false,
3425 managedTLSOpts(t, testservice.TLSMutual(), testservice.TLSHandshakeFirst()),
3426 )
3427 t.Cleanup(func() { inst.Destroy(t) })
3428 caPath, _, _ := tlsCertFiles(t, inst)
3429
3430 // Stranger instance: separate managed mTLS solely to mint a client cert
3431 // signed by a CA the target server does not trust.
3432 stranger := c.CreateServer(t, false, managedTLSOpts(t, testservice.TLSMutual()))
3433 t.Cleanup(func() { stranger.Destroy(t) })
3434 _, strangerCert, strangerKey := tlsCertFiles(t, stranger)
3435
3436 // Connect with a client cert signed by a different CA.
3437 _, err := nats.Connect(
3438 inst.Servers[0].URL,
3439 nats.RootCAs(caPath),
3440 nats.ClientCert(strangerCert, strangerKey),
3441 nats.TLSHandshakeFirst(),
3442 )
3443 if err == nil {
3444 t.Fatal("Expected error, got nil")
3445 }
3446 // NATS server sends a proper TLS alert, so we should NOT get EOF.
3447 if errors.Is(err, io.EOF) {
3448 t.Fatalf("Expected TLS alert error, not EOF: %v", err)
3449 }
3450 // Should contain a TLS-related error message.
3451 errStr := err.Error()
3452 if !strings.Contains(errStr, "tls:") {
3453 t.Fatalf("Expected TLS certificate error, got: %v", err)
3454 }
3455 }
3456
3457 func TestTLSEOFAfterHandshakeNonTLSFirst(t *testing.T) {
3458 // When the server requires TLS (but not handshake-first), completes
3459 // the TLS handshake via the INFO-driven upgrade, then immediately
3460 // closes, the error should also be wrapped.
3461
3462 cert, err := tls.LoadX509KeyPair("./configs/certs/server.pem", "./configs/certs/key.pem")
3463 if err != nil {
3464 t.Fatalf("Can't load server cert: %v", err)
3465 }
3466 tlsConf := &tls.Config{
3467 Certificates: []tls.Certificate{cert},
3468 ServerName: "localhost",
3469 }
3470
3471 l, err := net.Listen("tcp", "127.0.0.1:0")
3472 if err != nil {
3473 t.Fatalf("Could not listen: %v", err)
3474 }
3475 defer l.Close()
3476
3477 addr := l.Addr().(*net.TCPAddr)
3478
3479 // Mock server: send INFO requiring TLS, do TLS upgrade, then close.
3480 go func() {
3481 conn, err := l.Accept()
3482 if err != nil {
3483 return
3484 }
3485 defer conn.Close()
3486
3487 // Send INFO with tls_required before TLS handshake.
3488 info := fmt.Sprintf("INFO {\"server_id\":\"test\",\"host\":\"localhost\",\"port\":%d,\"tls_required\":true,\"tls_available\":true,\"max_payload\":1048576}\r\n", addr.Port)
3489 conn.Write([]byte(info))
3490
3491 // Upgrade to TLS.
3492 tlsConn := tls.Server(conn, tlsConf)
3493 if err := tlsConn.Handshake(); err != nil {
3494 return
3495 }
3496 // Wait a bit so the client starts writing CONNECT+PING,
3497 // then close — this makes "broken pipe" more likely.
3498 time.Sleep(50 * time.Millisecond)
3499 tlsConn.Close()
3500 }()
3501
3502 _, err = nats.Connect(
3503 fmt.Sprintf("nats://localhost:%d", addr.Port),
3504 nats.RootCAs("./configs/certs/ca.pem"),
3505 )
3506 if err == nil {
3507 t.Fatal("Expected error, got nil")
3508 }
3509 if !errors.Is(err, nats.ErrTLS) {
3510 t.Fatalf("Expected error to wrap nats.ErrTLS, got: %v", err)
3511 }
3512 }
3513
3514 func TestTLSEOFAfterHandshakeBrokenPipe(t *testing.T) {
3515 // Simulate a scenario where the server does a hard close (TCP RST)
3516 // after TLS handshake, which can cause "broken pipe" or
3517 // "connection reset by peer" on the client side.
3518
3519 cert, err := tls.LoadX509KeyPair("./configs/certs/server.pem", "./configs/certs/key.pem")
3520 if err != nil {
3521 t.Fatalf("Can't load server cert: %v", err)
3522 }
3523 tlsConf := &tls.Config{
3524 Certificates: []tls.Certificate{cert},
3525 ServerName: "localhost",
3526 }
3527
3528 l, err := net.Listen("tcp", "127.0.0.1:0")
3529 if err != nil {
3530 t.Fatalf("Could not listen: %v", err)
3531 }
3532 defer l.Close()
3533
3534 addr := l.Addr().(*net.TCPAddr)
3535
3536 go func() {
3537 conn, err := l.Accept()
3538 if err != nil {
3539 return
3540 }
3541
3542 // Send INFO with tls_required.
3543 info := fmt.Sprintf("INFO {\"server_id\":\"test\",\"host\":\"localhost\",\"port\":%d,\"tls_required\":true,\"tls_available\":true,\"max_payload\":1048576}\r\n", addr.Port)
3544 conn.Write([]byte(info))
3545
3546 // Upgrade to TLS.
3547 tlsConn := tls.Server(conn, tlsConf)
3548 if err := tlsConn.Handshake(); err != nil {
3549 conn.Close()
3550 return
3551 }
3552
3553 // Force a TCP RST by setting linger to 0 then closing.
3554 // This causes "connection reset by peer" on the client
3555 // instead of a graceful EOF.
3556 if tcpConn, ok := conn.(*net.TCPConn); ok {
3557 tcpConn.SetLinger(0)
3558 }
3559 conn.Close()
3560 }()
3561
3562 _, err = nats.Connect(
3563 fmt.Sprintf("nats://localhost:%d", addr.Port),
3564 nats.RootCAs("./configs/certs/ca.pem"),
3565 )
3566 if err == nil {
3567 t.Fatal("Expected error, got nil")
3568 }
3569 if !errors.Is(err, nats.ErrTLS) {
3570 t.Fatalf("Expected error to wrap nats.ErrTLS, got: %v", err)
3571 }
3572 }
3573
3574 func TestWriteBufferSizeOption(t *testing.T) {
3575 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
3576 nc, err := nats.Connect(inst.Servers[0].URL, nats.WriteBufferSize(64*1024))
3577 if err != nil {
3578 t.Fatalf("Expected to connect, got: %v", err)
3579 }
3580 defer nc.Close()
3581
3582 if nc.Opts.WriteBufferSize != 64*1024 {
3583 t.Fatalf("Expected WriteBufferSize 64KB, got %d", nc.Opts.WriteBufferSize)
3584 }
3585
3586 sub, err := nc.SubscribeSync("foo")
3587 if err != nil {
3588 t.Fatalf("Error subscribing: %v", err)
3589 }
3590 if err := nc.Publish("foo", []byte("hello")); err != nil {
3591 t.Fatalf("Error publishing: %v", err)
3592 }
3593 if _, err := sub.NextMsg(2 * time.Second); err != nil {
3594 t.Fatalf("Error receiving message: %v", err)
3595 }
3596 })
3597 }