| 1 |
// Copyright 2013-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 |
"errors" |
| 18 |
"fmt" |
| 19 |
"net/url" |
| 20 |
"strconv" |
| 21 |
"sync" |
| 22 |
"sync/atomic" |
| 23 |
"testing" |
| 24 |
"time" |
| 25 |
|
| 26 |
"github.com/nats-io/jwt/v2" |
| 27 |
"github.com/nats-io/nats.go" |
| 28 |
"github.com/nats-io/nkeys" |
| 29 |
testservice "github.com/synadia-io/orbit.go/ntf-client" |
| 30 |
) |
| 31 |
|
| 32 |
// Seeds and account JWT used by the trust-server reconnect tests. These mirror |
| 33 |
// the constants in nats_test.go (which is gated by !testservice) so the |
| 34 |
// testservice build can stand on its own. |
| 35 |
var ( |
| 36 |
tsOSeed = []byte("SOAL7GTNI66CTVVNXBNQMG6V2HTDRWC3HGEP7D2OUTWNWSNYZDXWFOX4SU") |
| 37 |
tsASeed = []byte("SAAASUPRY3ONU4GJR7J5RUVYRUFZXG56F4WEXELLLORQ65AEPSMIFTOJGE") |
| 38 |
tsUSeed = []byte("SUAMK2FG4MI6UE3ACF3FK3OIQBCEIEZV7NSWFFEW63UXMRLFM2XLAXK4GY") |
| 39 |
|
| 40 |
tsAJWT = "eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJLWjZIUVRXRlY3WkRZSFo3NklRNUhPM0pINDVRNUdJS0JNMzJTSENQVUJNNk5PNkU3TUhRIiwiaWF0IjoxNTQ0MDcxODg5LCJpc3MiOiJPRDJXMkk0TVZSQTVUR1pMWjJBRzZaSEdWTDNPVEtGV1FKRklYNFROQkVSMjNFNlA0NlMzNDVZWSIsInN1YiI6IkFBUFFKUVVQS1ZYR1c1Q1pINUcySEZKVUxZU0tERUxBWlJWV0pBMjZWRFpPN1dTQlVOSVlSRk5RIiwidHlwZSI6ImFjY291bnQiLCJuYXRzIjp7ImxpbWl0cyI6eyJzdWJzIjotMSwiY29ubiI6LTEsImltcG9ydHMiOi0xLCJleHBvcnRzIjotMSwiZGF0YSI6LTEsInBheWxvYWQiOi0xLCJ3aWxkY2FyZHMiOnRydWV9fX0.8o35JPQgvhgFT84Bi2Z-zAeSiLrzzEZn34sgr1DIBEDTwa-EEiMhvTeos9cvXxoZVCCadqZxAWVwS6paAMj8Bg" |
| 41 |
) |
| 42 |
|
| 43 |
// trustServerOpts returns the testservice options needed to render a |
| 44 |
// trusted-keys server with a MEM resolver pre-loaded with the test account |
| 45 |
// JWT — the testservice equivalent of runTrustServer. |
| 46 |
func trustServerOpts(t *testing.T) []testservice.CreateOption { |
| 47 |
t.Helper() |
| 48 |
okp, err := nkeys.FromSeed(tsOSeed) |
| 49 |
if err != nil { |
| 50 |
t.Fatalf("Error creating operator key pair: %v", err) |
| 51 |
} |
| 52 |
opub, err := okp.PublicKey() |
| 53 |
if err != nil { |
| 54 |
t.Fatalf("Error getting operator public key: %v", err) |
| 55 |
} |
| 56 |
akp, err := nkeys.FromSeed(tsASeed) |
| 57 |
if err != nil { |
| 58 |
t.Fatalf("Error creating account key pair: %v", err) |
| 59 |
} |
| 60 |
apub, err := akp.PublicKey() |
| 61 |
if err != nil { |
| 62 |
t.Fatalf("Error getting account public key: %v", err) |
| 63 |
} |
| 64 |
body := fmt.Sprintf(` |
| 65 |
trusted_keys: [%q] |
| 66 |
resolver: MEM |
| 67 |
resolver_preload: { |
| 68 |
%q: %q |
| 69 |
} |
| 70 |
`, opub, apub, tsAJWT) |
| 71 |
return []testservice.CreateOption{ |
| 72 |
testservice.WithTopLevel(body), |
| 73 |
// The default rendered config has an accounts block, an authorization |
| 74 |
// block with no_auth_user, and a system_account — all of which |
| 75 |
// conflict with operator-mode trust. Strip all three. |
| 76 |
testservice.WithAccounts(`# accounts intentionally empty; using operator/account JWT trust`), |
| 77 |
testservice.WithAuthorization(`# authorization intentionally empty; using operator/account JWT trust`), |
| 78 |
testservice.WithSystemAccount(`# system_account intentionally unset`), |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
func TestReconnectTotalTime(t *testing.T) { |
| 83 |
opts := nats.GetDefaultOptions() |
| 84 |
totalReconnectTime := time.Duration(opts.MaxReconnect) * opts.ReconnectWait |
| 85 |
if totalReconnectTime < (2 * time.Minute) { |
| 86 |
t.Fatalf("Total reconnect time should be at least 2 mins: Currently %v\n", |
| 87 |
totalReconnectTime) |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
func TestDefaultReconnectJitter(t *testing.T) { |
| 92 |
opts := nats.GetDefaultOptions() |
| 93 |
if opts.ReconnectJitter != nats.DefaultReconnectJitter { |
| 94 |
t.Fatalf("Expected default jitter for non TLS to be %v, got %v", nats.DefaultReconnectJitter, opts.ReconnectJitter) |
| 95 |
} |
| 96 |
if opts.ReconnectJitterTLS != nats.DefaultReconnectJitterTLS { |
| 97 |
t.Fatalf("Expected default jitter for TLS to be %v, got %v", nats.DefaultReconnectJitterTLS, opts.ReconnectJitterTLS) |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
func TestReconnectDisallowedFlags(t *testing.T) { |
| 102 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 103 |
ch := make(chan bool) |
| 104 |
opts := nats.GetDefaultOptions() |
| 105 |
opts.Url = inst.Servers[0].URL |
| 106 |
opts.AllowReconnect = false |
| 107 |
opts.ClosedCB = func(_ *nats.Conn) { |
| 108 |
ch <- true |
| 109 |
} |
| 110 |
nc, err := opts.Connect() |
| 111 |
if err != nil { |
| 112 |
t.Fatalf("Should have connected ok: %v", err) |
| 113 |
} |
| 114 |
defer nc.Close() |
| 115 |
|
| 116 |
inst.StopServer(t, inst.Servers[0]) |
| 117 |
|
| 118 |
if e := Wait(ch); e != nil { |
| 119 |
t.Fatal("Did not trigger ClosedCB correctly") |
| 120 |
} |
| 121 |
}) |
| 122 |
} |
| 123 |
|
| 124 |
func TestReconnectAllowedFlags(t *testing.T) { |
| 125 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 126 |
ch := make(chan bool) |
| 127 |
dch := make(chan bool) |
| 128 |
opts := nats.GetDefaultOptions() |
| 129 |
opts.Url = inst.Servers[0].URL |
| 130 |
opts.AllowReconnect = true |
| 131 |
opts.MaxReconnect = 2 |
| 132 |
opts.ReconnectWait = 1 * time.Second |
| 133 |
nats.ReconnectJitter(0, 0)(&opts) |
| 134 |
|
| 135 |
opts.ClosedCB = func(_ *nats.Conn) { |
| 136 |
ch <- true |
| 137 |
} |
| 138 |
opts.DisconnectedErrCB = func(_ *nats.Conn, _ error) { |
| 139 |
dch <- true |
| 140 |
} |
| 141 |
nc, err := opts.Connect() |
| 142 |
if err != nil { |
| 143 |
t.Fatalf("Should have connected ok: %v", err) |
| 144 |
} |
| 145 |
defer nc.Close() |
| 146 |
|
| 147 |
inst.StopServer(t, inst.Servers[0]) |
| 148 |
|
| 149 |
// We want wait to timeout here, and the connection |
| 150 |
// should not trigger the Close CB. |
| 151 |
if e := WaitTime(ch, 500*time.Millisecond); e == nil { |
| 152 |
t.Fatal("Triggered ClosedCB incorrectly") |
| 153 |
} |
| 154 |
|
| 155 |
// We should wait to get the disconnected callback to ensure |
| 156 |
// that we are in the process of reconnecting. |
| 157 |
if e := Wait(dch); e != nil { |
| 158 |
t.Fatal("DisconnectedErrCB should have been triggered") |
| 159 |
} |
| 160 |
|
| 161 |
if !nc.IsReconnecting() { |
| 162 |
t.Fatal("Expected to be in a reconnecting state") |
| 163 |
} |
| 164 |
|
| 165 |
// clear the CloseCB since ch will block |
| 166 |
nc.Opts.ClosedCB = nil |
| 167 |
}) |
| 168 |
} |
| 169 |
|
| 170 |
// reconnectOptsFor returns a reconnectOpts equivalent dialed against the given |
| 171 |
// instance URL. |
| 172 |
func reconnectOptsFor(url string) nats.Options { |
| 173 |
return nats.Options{ |
| 174 |
Url: url, |
| 175 |
AllowReconnect: true, |
| 176 |
MaxReconnect: 10, |
| 177 |
ReconnectWait: 100 * time.Millisecond, |
| 178 |
Timeout: nats.DefaultTimeout, |
| 179 |
} |
| 180 |
} |
| 181 |
|
| 182 |
func TestConnCloseBreaksReconnectLoop(t *testing.T) { |
| 183 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 184 |
cch := make(chan bool) |
| 185 |
|
| 186 |
opts := reconnectOptsFor(inst.Servers[0].URL) |
| 187 |
// Bump the max reconnect attempts |
| 188 |
opts.MaxReconnect = 100 |
| 189 |
opts.ClosedCB = func(_ *nats.Conn) { |
| 190 |
cch <- true |
| 191 |
} |
| 192 |
nc, err := opts.Connect() |
| 193 |
if err != nil { |
| 194 |
t.Fatalf("Should have connected ok: %v", err) |
| 195 |
} |
| 196 |
defer nc.Close() |
| 197 |
nc.Flush() |
| 198 |
|
| 199 |
// Shutdown the server |
| 200 |
inst.StopServer(t, inst.Servers[0]) |
| 201 |
|
| 202 |
// Wait a second, then close the connection |
| 203 |
time.Sleep(time.Second) |
| 204 |
|
| 205 |
// Close the connection, this should break the reconnect loop. |
| 206 |
// Do this in a go routine since the issue was that Close() |
| 207 |
// would block until the reconnect loop is done. |
| 208 |
go nc.Close() |
| 209 |
|
| 210 |
// Even on Windows (where a createConn takes more than a second) |
| 211 |
// we should be able to break the reconnect loop with the following |
| 212 |
// timeout. |
| 213 |
if err := WaitTime(cch, 3*time.Second); err != nil { |
| 214 |
t.Fatal("Did not get a closed callback") |
| 215 |
} |
| 216 |
}) |
| 217 |
} |
| 218 |
|
| 219 |
func TestBasicReconnectFunctionality(t *testing.T) { |
| 220 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 221 |
ch := make(chan bool) |
| 222 |
dch := make(chan bool, 2) |
| 223 |
|
| 224 |
opts := reconnectOptsFor(inst.Servers[0].URL) |
| 225 |
opts.DisconnectedErrCB = func(_ *nats.Conn, _ error) { |
| 226 |
dch <- true |
| 227 |
} |
| 228 |
|
| 229 |
nc, err := opts.Connect() |
| 230 |
if err != nil { |
| 231 |
t.Fatalf("Should have connected ok: %v\n", err) |
| 232 |
} |
| 233 |
defer nc.Close() |
| 234 |
|
| 235 |
testString := "bar" |
| 236 |
nc.Subscribe("foo", func(m *nats.Msg) { |
| 237 |
if string(m.Data) != testString { |
| 238 |
t.Fatal("String doesn't match") |
| 239 |
} |
| 240 |
ch <- true |
| 241 |
}) |
| 242 |
nc.Flush() |
| 243 |
|
| 244 |
inst.StopServer(t, inst.Servers[0]) |
| 245 |
// server is stopped here... |
| 246 |
|
| 247 |
if err := Wait(dch); err != nil { |
| 248 |
t.Fatalf("Did not get the disconnected callback on time\n") |
| 249 |
} |
| 250 |
|
| 251 |
if err := nc.Publish("foo", []byte("bar")); err != nil { |
| 252 |
t.Fatalf("Failed to publish message: %v\n", err) |
| 253 |
} |
| 254 |
|
| 255 |
inst.StartServer(t, inst.Servers[0]) |
| 256 |
|
| 257 |
if err := nc.FlushTimeout(5 * time.Second); err != nil { |
| 258 |
t.Fatalf("Error on Flush: %v", err) |
| 259 |
} |
| 260 |
|
| 261 |
if e := Wait(ch); e != nil { |
| 262 |
t.Fatal("Did not receive our message") |
| 263 |
} |
| 264 |
|
| 265 |
expectedReconnectCount := uint64(1) |
| 266 |
reconnectCount := nc.Stats().Reconnects |
| 267 |
|
| 268 |
if reconnectCount != expectedReconnectCount { |
| 269 |
t.Fatalf("Reconnect count incorrect: %d vs %d\n", |
| 270 |
reconnectCount, expectedReconnectCount) |
| 271 |
} |
| 272 |
}) |
| 273 |
} |
| 274 |
|
| 275 |
func TestExtendedReconnectFunctionality(t *testing.T) { |
| 276 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 277 |
opts := reconnectOptsFor(inst.Servers[0].URL) |
| 278 |
dch := make(chan bool, 2) |
| 279 |
opts.DisconnectedErrCB = func(_ *nats.Conn, _ error) { |
| 280 |
dch <- true |
| 281 |
} |
| 282 |
rch := make(chan bool, 1) |
| 283 |
opts.ReconnectedCB = func(_ *nats.Conn) { |
| 284 |
rch <- true |
| 285 |
} |
| 286 |
nc, err := opts.Connect() |
| 287 |
if err != nil { |
| 288 |
t.Fatalf("Should have connected ok: %v", err) |
| 289 |
} |
| 290 |
defer nc.Close() |
| 291 |
|
| 292 |
testString := "bar" |
| 293 |
received := int32(0) |
| 294 |
|
| 295 |
nc.Subscribe("foo", func(*nats.Msg) { |
| 296 |
atomic.AddInt32(&received, 1) |
| 297 |
}) |
| 298 |
|
| 299 |
sub, _ := nc.Subscribe("foobar", func(*nats.Msg) { |
| 300 |
atomic.AddInt32(&received, 1) |
| 301 |
}) |
| 302 |
|
| 303 |
nc.Publish("foo", []byte(testString)) |
| 304 |
nc.Flush() |
| 305 |
|
| 306 |
inst.StopServer(t, inst.Servers[0]) |
| 307 |
// server is stopped here.. |
| 308 |
|
| 309 |
// wait for disconnect |
| 310 |
if e := WaitTime(dch, 2*time.Second); e != nil { |
| 311 |
t.Fatal("Did not receive a disconnect callback message") |
| 312 |
} |
| 313 |
|
| 314 |
// Sub while disconnected |
| 315 |
nc.Subscribe("bar", func(*nats.Msg) { |
| 316 |
atomic.AddInt32(&received, 1) |
| 317 |
}) |
| 318 |
|
| 319 |
// Unsub foobar while disconnected |
| 320 |
sub.Unsubscribe() |
| 321 |
|
| 322 |
if err = nc.Publish("foo", []byte(testString)); err != nil { |
| 323 |
t.Fatalf("Received an error after disconnect: %v\n", err) |
| 324 |
} |
| 325 |
|
| 326 |
if err = nc.Publish("bar", []byte(testString)); err != nil { |
| 327 |
t.Fatalf("Received an error after disconnect: %v\n", err) |
| 328 |
} |
| 329 |
|
| 330 |
inst.StartServer(t, inst.Servers[0]) |
| 331 |
|
| 332 |
// server is restarted here.. |
| 333 |
// wait for reconnect |
| 334 |
if e := WaitTime(rch, 2*time.Second); e != nil { |
| 335 |
t.Fatal("Did not receive a reconnect callback message") |
| 336 |
} |
| 337 |
|
| 338 |
if err = nc.Publish("foobar", []byte(testString)); err != nil { |
| 339 |
t.Fatalf("Received an error after server restarted: %v\n", err) |
| 340 |
} |
| 341 |
|
| 342 |
if err = nc.Publish("foo", []byte(testString)); err != nil { |
| 343 |
t.Fatalf("Received an error after server restarted: %v\n", err) |
| 344 |
} |
| 345 |
|
| 346 |
ch := make(chan bool) |
| 347 |
nc.Subscribe("done", func(*nats.Msg) { |
| 348 |
ch <- true |
| 349 |
}) |
| 350 |
nc.Publish("done", nil) |
| 351 |
|
| 352 |
if e := Wait(ch); e != nil { |
| 353 |
t.Fatal("Did not receive our message") |
| 354 |
} |
| 355 |
|
| 356 |
// Sleep a bit to guarantee scheduler runs and process all subs. |
| 357 |
time.Sleep(50 * time.Millisecond) |
| 358 |
|
| 359 |
if atomic.LoadInt32(&received) != 4 { |
| 360 |
t.Fatalf("Received != %d, equals %d\n", 4, received) |
| 361 |
} |
| 362 |
}) |
| 363 |
} |
| 364 |
|
| 365 |
func TestQueueSubsOnReconnect(t *testing.T) { |
| 366 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 367 |
opts := reconnectOptsFor(inst.Servers[0].URL) |
| 368 |
|
| 369 |
// Allow us to block on reconnect complete. |
| 370 |
reconnectsDone := make(chan bool) |
| 371 |
opts.ReconnectedCB = func(nc *nats.Conn) { |
| 372 |
reconnectsDone <- true |
| 373 |
} |
| 374 |
|
| 375 |
// Create connection |
| 376 |
nc, err := opts.Connect() |
| 377 |
if err != nil { |
| 378 |
t.Fatalf("Should have connected ok: %v\n", err) |
| 379 |
} |
| 380 |
defer nc.Close() |
| 381 |
|
| 382 |
// To hold results. |
| 383 |
results := make(map[int]int) |
| 384 |
var mu sync.Mutex |
| 385 |
|
| 386 |
// Make sure we got what we needed, 1 msg only and all seqnos accounted for.. |
| 387 |
checkResults := func(numSent int) { |
| 388 |
mu.Lock() |
| 389 |
defer mu.Unlock() |
| 390 |
|
| 391 |
for i := range numSent { |
| 392 |
if results[i] != 1 { |
| 393 |
t.Fatalf("Received incorrect number of messages, [%d] for seq: %d\n", results[i], i) |
| 394 |
} |
| 395 |
} |
| 396 |
|
| 397 |
// Auto reset results map |
| 398 |
results = make(map[int]int) |
| 399 |
} |
| 400 |
|
| 401 |
subj := "foo.bar" |
| 402 |
qgroup := "workers" |
| 403 |
|
| 404 |
cb := func(m *nats.Msg) { |
| 405 |
mu.Lock() |
| 406 |
defer mu.Unlock() |
| 407 |
seqno, err := strconv.Atoi(string(m.Data)) |
| 408 |
if err != nil { |
| 409 |
t.Fatalf("Received an invalid sequence number: %v\n", err) |
| 410 |
} |
| 411 |
results[seqno] = results[seqno] + 1 |
| 412 |
} |
| 413 |
|
| 414 |
// Create Queue Subscribers |
| 415 |
nc.QueueSubscribe(subj, qgroup, cb) |
| 416 |
nc.QueueSubscribe(subj, qgroup, cb) |
| 417 |
|
| 418 |
nc.Flush() |
| 419 |
|
| 420 |
// Helper function to send messages and check results. |
| 421 |
sendAndCheckMsgs := func(numToSend int) { |
| 422 |
for i := range numToSend { |
| 423 |
nc.Publish(subj, []byte(fmt.Sprint(i))) |
| 424 |
} |
| 425 |
// Wait for processing. |
| 426 |
nc.Flush() |
| 427 |
time.Sleep(50 * time.Millisecond) |
| 428 |
|
| 429 |
// Check Results |
| 430 |
checkResults(numToSend) |
| 431 |
} |
| 432 |
|
| 433 |
// Base Test |
| 434 |
sendAndCheckMsgs(10) |
| 435 |
|
| 436 |
// Stop and restart server |
| 437 |
inst.StopServer(t, inst.Servers[0]) |
| 438 |
inst.StartServer(t, inst.Servers[0]) |
| 439 |
|
| 440 |
if err := Wait(reconnectsDone); err != nil { |
| 441 |
t.Fatal("Did not get the ReconnectedCB!") |
| 442 |
} |
| 443 |
|
| 444 |
// Reconnect Base Test |
| 445 |
sendAndCheckMsgs(10) |
| 446 |
}) |
| 447 |
} |
| 448 |
|
| 449 |
func TestIsClosed(t *testing.T) { |
| 450 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 451 |
nc, err := nats.Connect(inst.Servers[0].URL, nats.MaxReconnects(-1), nats.ReconnectWait(100*time.Millisecond)) |
| 452 |
if err != nil { |
| 453 |
t.Fatalf("Should have connected ok: %v", err) |
| 454 |
} |
| 455 |
defer nc.Close() |
| 456 |
|
| 457 |
if nc.IsClosed() { |
| 458 |
t.Fatalf("IsClosed returned true when the connection is still open.") |
| 459 |
} |
| 460 |
inst.StopServer(t, inst.Servers[0]) |
| 461 |
if nc.IsClosed() { |
| 462 |
t.Fatalf("IsClosed returned true when the connection is still open.") |
| 463 |
} |
| 464 |
inst.StartServer(t, inst.Servers[0]) |
| 465 |
if nc.IsClosed() { |
| 466 |
t.Fatalf("IsClosed returned true when the connection is still open.") |
| 467 |
} |
| 468 |
nc.Close() |
| 469 |
if !nc.IsClosed() { |
| 470 |
t.Fatalf("IsClosed returned false after Close() was called.") |
| 471 |
} |
| 472 |
}) |
| 473 |
} |
| 474 |
|
| 475 |
func TestIsReconnectingAndStatus(t *testing.T) { |
| 476 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 477 |
disconnectedch := make(chan bool, 3) |
| 478 |
reconnectch := make(chan bool, 2) |
| 479 |
opts := nats.GetDefaultOptions() |
| 480 |
opts.Url = inst.Servers[0].URL |
| 481 |
opts.AllowReconnect = true |
| 482 |
opts.MaxReconnect = 10000 |
| 483 |
opts.ReconnectWait = 100 * time.Millisecond |
| 484 |
nats.ReconnectJitter(0, 0)(&opts) |
| 485 |
|
| 486 |
opts.DisconnectedErrCB = func(_ *nats.Conn, _ error) { |
| 487 |
disconnectedch <- true |
| 488 |
} |
| 489 |
opts.ReconnectedCB = func(_ *nats.Conn) { |
| 490 |
reconnectch <- true |
| 491 |
} |
| 492 |
|
| 493 |
// Connect, verify initial reconnecting state check, then stop the server |
| 494 |
nc, err := opts.Connect() |
| 495 |
if err != nil { |
| 496 |
t.Fatalf("Should have connected ok: %v", err) |
| 497 |
} |
| 498 |
defer nc.Close() |
| 499 |
|
| 500 |
if nc.IsReconnecting() { |
| 501 |
t.Fatalf("IsReconnecting returned true when the connection is still open.") |
| 502 |
} |
| 503 |
if status := nc.Status(); status != nats.CONNECTED { |
| 504 |
t.Fatalf("Status returned %d when connected instead of CONNECTED", status) |
| 505 |
} |
| 506 |
inst.StopServer(t, inst.Servers[0]) |
| 507 |
|
| 508 |
// Wait until we get the disconnected callback |
| 509 |
if e := Wait(disconnectedch); e != nil { |
| 510 |
t.Fatalf("Disconnect callback wasn't triggered: %v", e) |
| 511 |
} |
| 512 |
if !nc.IsReconnecting() { |
| 513 |
t.Fatalf("IsReconnecting returned false when the client is reconnecting.") |
| 514 |
} |
| 515 |
if status := nc.Status(); status != nats.RECONNECTING { |
| 516 |
t.Fatalf("Status returned %d when reconnecting instead of CONNECTED", status) |
| 517 |
} |
| 518 |
|
| 519 |
inst.StartServer(t, inst.Servers[0]) |
| 520 |
|
| 521 |
// Wait until we get the reconnect callback |
| 522 |
if e := Wait(reconnectch); e != nil { |
| 523 |
t.Fatalf("Reconnect callback wasn't triggered: %v", e) |
| 524 |
} |
| 525 |
if nc.IsReconnecting() { |
| 526 |
t.Fatalf("IsReconnecting returned true after the connection was reconnected.") |
| 527 |
} |
| 528 |
if status := nc.Status(); status != nats.CONNECTED { |
| 529 |
t.Fatalf("Status returned %d when reconnected instead of CONNECTED", status) |
| 530 |
} |
| 531 |
|
| 532 |
// Close the connection, reconnecting should still be false |
| 533 |
nc.Close() |
| 534 |
if nc.IsReconnecting() { |
| 535 |
t.Fatalf("IsReconnecting returned true after Close() was called.") |
| 536 |
} |
| 537 |
if status := nc.Status(); status != nats.CLOSED { |
| 538 |
t.Fatalf("Status returned %d after Close() was called instead of CLOSED", status) |
| 539 |
} |
| 540 |
}) |
| 541 |
} |
| 542 |
|
| 543 |
func TestFullFlushChanDuringReconnect(t *testing.T) { |
| 544 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 545 |
reconnectch := make(chan bool, 2) |
| 546 |
|
| 547 |
opts := nats.GetDefaultOptions() |
| 548 |
opts.Url = inst.Servers[0].URL |
| 549 |
opts.AllowReconnect = true |
| 550 |
opts.MaxReconnect = 10000 |
| 551 |
opts.ReconnectWait = 100 * time.Millisecond |
| 552 |
nats.ReconnectJitter(0, 0)(&opts) |
| 553 |
|
| 554 |
opts.ReconnectedCB = func(_ *nats.Conn) { |
| 555 |
reconnectch <- true |
| 556 |
} |
| 557 |
|
| 558 |
// Connect |
| 559 |
nc, err := opts.Connect() |
| 560 |
if err != nil { |
| 561 |
t.Fatalf("Should have connected ok: %v", err) |
| 562 |
} |
| 563 |
defer nc.Close() |
| 564 |
|
| 565 |
// Channel used to make the go routine sending messages to stop. |
| 566 |
stop := make(chan bool) |
| 567 |
|
| 568 |
// While connected, publish as fast as we can |
| 569 |
go func() { |
| 570 |
for i := 0; ; i++ { |
| 571 |
_ = nc.Publish("foo", []byte("hello")) |
| 572 |
|
| 573 |
// Make sure we are sending at least flushChanSize (1024) messages |
| 574 |
// before potentially pausing. |
| 575 |
if i%2000 == 0 { |
| 576 |
select { |
| 577 |
case <-stop: |
| 578 |
return |
| 579 |
default: |
| 580 |
time.Sleep(100 * time.Millisecond) |
| 581 |
} |
| 582 |
} |
| 583 |
} |
| 584 |
}() |
| 585 |
|
| 586 |
// Send a bit... |
| 587 |
time.Sleep(500 * time.Millisecond) |
| 588 |
|
| 589 |
// Shut down the server |
| 590 |
inst.StopServer(t, inst.Servers[0]) |
| 591 |
|
| 592 |
// Continue sending while we are disconnected |
| 593 |
time.Sleep(time.Second) |
| 594 |
|
| 595 |
// Restart the server |
| 596 |
inst.StartServer(t, inst.Servers[0]) |
| 597 |
|
| 598 |
// Wait for the reconnect CB to be invoked (but not for too long) |
| 599 |
if e := WaitTime(reconnectch, 5*time.Second); e != nil { |
| 600 |
t.Fatalf("Reconnect callback wasn't triggered: %v", e) |
| 601 |
} |
| 602 |
close(stop) |
| 603 |
}) |
| 604 |
} |
| 605 |
|
| 606 |
func TestReconnectVerbose(t *testing.T) { |
| 607 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 608 |
o := nats.GetDefaultOptions() |
| 609 |
o.Url = inst.Servers[0].URL |
| 610 |
o.ReconnectWait = 50 * time.Millisecond |
| 611 |
o.Verbose = true |
| 612 |
rch := make(chan bool) |
| 613 |
o.ReconnectedCB = func(_ *nats.Conn) { |
| 614 |
rch <- true |
| 615 |
} |
| 616 |
|
| 617 |
nc, err := o.Connect() |
| 618 |
if err != nil { |
| 619 |
t.Fatalf("Should have connected ok: %v", err) |
| 620 |
} |
| 621 |
defer nc.Close() |
| 622 |
|
| 623 |
err = nc.Flush() |
| 624 |
if err != nil { |
| 625 |
t.Fatalf("Error during flush: %v", err) |
| 626 |
} |
| 627 |
|
| 628 |
inst.StopServer(t, inst.Servers[0]) |
| 629 |
inst.StartServer(t, inst.Servers[0]) |
| 630 |
|
| 631 |
if e := Wait(rch); e != nil { |
| 632 |
t.Fatal("Should have reconnected ok") |
| 633 |
} |
| 634 |
|
| 635 |
err = nc.Flush() |
| 636 |
if err != nil { |
| 637 |
t.Fatalf("Error during flush: %v", err) |
| 638 |
} |
| 639 |
}) |
| 640 |
} |
| 641 |
|
| 642 |
func TestReconnectBufSizeOption(t *testing.T) { |
| 643 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 644 |
nc, err := nats.Connect(inst.Servers[0].URL, nats.ReconnectBufSize(32)) |
| 645 |
if err != nil { |
| 646 |
t.Fatalf("Should have connected ok: %v", err) |
| 647 |
} |
| 648 |
defer nc.Close() |
| 649 |
|
| 650 |
if nc.Opts.ReconnectBufSize != 32 { |
| 651 |
t.Fatalf("ReconnectBufSize should be 32 but it is %d", nc.Opts.ReconnectBufSize) |
| 652 |
} |
| 653 |
}) |
| 654 |
} |
| 655 |
|
| 656 |
func TestReconnectBufSize(t *testing.T) { |
| 657 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 658 |
o := nats.GetDefaultOptions() |
| 659 |
o.Url = inst.Servers[0].URL |
| 660 |
o.ReconnectBufSize = 32 // 32 bytes |
| 661 |
|
| 662 |
dch := make(chan bool) |
| 663 |
o.DisconnectedErrCB = func(_ *nats.Conn, _ error) { |
| 664 |
dch <- true |
| 665 |
} |
| 666 |
|
| 667 |
nc, err := o.Connect() |
| 668 |
if err != nil { |
| 669 |
t.Fatalf("Should have connected ok: %v", err) |
| 670 |
} |
| 671 |
defer nc.Close() |
| 672 |
|
| 673 |
err = nc.Flush() |
| 674 |
if err != nil { |
| 675 |
t.Fatalf("Error during flush: %v", err) |
| 676 |
} |
| 677 |
|
| 678 |
// Force disconnected state. |
| 679 |
inst.StopServer(t, inst.Servers[0]) |
| 680 |
|
| 681 |
if e := Wait(dch); e != nil { |
| 682 |
t.Fatal("DisconnectedErrCB should have been triggered") |
| 683 |
} |
| 684 |
|
| 685 |
msg := []byte("food") // 4 bytes paylaod, total proto is 16 bytes |
| 686 |
// These should work, 2X16 = 32 |
| 687 |
if err := nc.Publish("foo", msg); err != nil { |
| 688 |
t.Fatalf("Failed to publish message: %v\n", err) |
| 689 |
} |
| 690 |
if err := nc.Publish("foo", msg); err != nil { |
| 691 |
t.Fatalf("Failed to publish message: %v\n", err) |
| 692 |
} |
| 693 |
|
| 694 |
// This should fail since we have exhausted the backing buffer. |
| 695 |
if err := nc.Publish("foo", msg); err == nil { |
| 696 |
t.Fatalf("Expected to fail to publish message: got no error\n") |
| 697 |
} |
| 698 |
nc.Buffered() |
| 699 |
}) |
| 700 |
} |
| 701 |
|
| 702 |
func TestConnCloseNoCallback(t *testing.T) { |
| 703 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 704 |
serverURL := inst.Servers[0].URL |
| 705 |
|
| 706 |
// create a connection that manually sets the options |
| 707 |
var conns []*nats.Conn |
| 708 |
cch := make(chan string, 2) |
| 709 |
opts := reconnectOptsFor(serverURL) |
| 710 |
opts.ClosedCB = func(_ *nats.Conn) { |
| 711 |
cch <- "manual" |
| 712 |
} |
| 713 |
opts.NoCallbacksAfterClientClose = true |
| 714 |
nc, err := opts.Connect() |
| 715 |
if err != nil { |
| 716 |
t.Fatalf("Should have connected ok: %v", err) |
| 717 |
} |
| 718 |
conns = append(conns, nc) |
| 719 |
|
| 720 |
// and another connection that uses the option |
| 721 |
nc2, err := nats.Connect(serverURL, nats.NoCallbacksAfterClientClose(), |
| 722 |
nats.ClosedHandler(func(_ *nats.Conn) { |
| 723 |
cch <- "opts" |
| 724 |
})) |
| 725 |
if err != nil { |
| 726 |
t.Fatalf("Should have connected ok: %v", err) |
| 727 |
} |
| 728 |
conns = append(conns, nc2) |
| 729 |
|
| 730 |
// defer close() for safety, flush() and close() |
| 731 |
for _, c := range conns { |
| 732 |
defer c.Close() |
| 733 |
c.Flush() |
| 734 |
|
| 735 |
// Close the connection, we don't expect to get a notification |
| 736 |
c.Close() |
| 737 |
} |
| 738 |
|
| 739 |
// if the timeout happens we didn't get data from the channel |
| 740 |
// if we get a value from the channel that connection type failed. |
| 741 |
select { |
| 742 |
case <-time.After(500 * time.Millisecond): |
| 743 |
// test passed - we timed so no callback was called |
| 744 |
case what := <-cch: |
| 745 |
t.Fatalf("%s issued a callback and it shouldn't have", what) |
| 746 |
} |
| 747 |
}) |
| 748 |
} |
| 749 |
|
| 750 |
func TestReconnectBufSizeDisable(t *testing.T) { |
| 751 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 752 |
o := nats.GetDefaultOptions() |
| 753 |
o.Url = inst.Servers[0].URL |
| 754 |
|
| 755 |
// Disable buffering to always get a synchronous error when publish fails. |
| 756 |
o.ReconnectBufSize = -1 |
| 757 |
|
| 758 |
dch := make(chan bool) |
| 759 |
o.DisconnectedErrCB = func(_ *nats.Conn, _ error) { |
| 760 |
dch <- true |
| 761 |
} |
| 762 |
|
| 763 |
nc, err := o.Connect() |
| 764 |
if err != nil { |
| 765 |
t.Fatalf("Should have connected ok: %v", err) |
| 766 |
} |
| 767 |
defer nc.Close() |
| 768 |
|
| 769 |
err = nc.Flush() |
| 770 |
if err != nil { |
| 771 |
t.Fatalf("Error during flush: %v", err) |
| 772 |
} |
| 773 |
|
| 774 |
// Force disconnected state. |
| 775 |
inst.StopServer(t, inst.Servers[0]) |
| 776 |
|
| 777 |
if e := Wait(dch); e != nil { |
| 778 |
t.Fatal("DisconnectedErrCB should have been triggered") |
| 779 |
} |
| 780 |
|
| 781 |
msg := []byte("food") |
| 782 |
if err := nc.Publish("foo", msg); err != nats.ErrReconnectBufExceeded { |
| 783 |
t.Fatalf("Unexpected error: %v\n", err) |
| 784 |
} |
| 785 |
got, _ := nc.Buffered() |
| 786 |
if got != 0 { |
| 787 |
t.Errorf("Unexpected buffered bytes: %v", got) |
| 788 |
} |
| 789 |
}) |
| 790 |
} |
| 791 |
|
| 792 |
func TestAuthExpiredReconnect(t *testing.T) { |
| 793 |
c := newTester(t) |
| 794 |
inst := c.CreateServer(t, false, trustServerOpts(t)...) |
| 795 |
t.Cleanup(func() { inst.Destroy(t) }) |
| 796 |
|
| 797 |
clientURL := inst.Servers[0].URL |
| 798 |
|
| 799 |
_, err := nats.Connect(clientURL) |
| 800 |
if err == nil { |
| 801 |
t.Fatalf("Expecting an error on connect") |
| 802 |
} |
| 803 |
ukp, err := nkeys.FromSeed(tsUSeed) |
| 804 |
if err != nil { |
| 805 |
t.Fatalf("Error creating user key pair: %v", err) |
| 806 |
} |
| 807 |
upub, err := ukp.PublicKey() |
| 808 |
if err != nil { |
| 809 |
t.Fatalf("Error getting user public key: %v", err) |
| 810 |
} |
| 811 |
akp, err := nkeys.FromSeed(tsASeed) |
| 812 |
if err != nil { |
| 813 |
t.Fatalf("Error creating account key pair: %v", err) |
| 814 |
} |
| 815 |
|
| 816 |
jwtCB := func() (string, error) { |
| 817 |
claims := jwt.NewUserClaims("test") |
| 818 |
claims.Expires = time.Now().Add(time.Second).Unix() |
| 819 |
claims.Subject = upub |
| 820 |
jwt, err := claims.Encode(akp) |
| 821 |
if err != nil { |
| 822 |
return "", err |
| 823 |
} |
| 824 |
return jwt, nil |
| 825 |
} |
| 826 |
sigCB := func(nonce []byte) ([]byte, error) { |
| 827 |
kp, _ := nkeys.FromSeed(tsUSeed) |
| 828 |
sig, _ := kp.Sign(nonce) |
| 829 |
return sig, nil |
| 830 |
} |
| 831 |
|
| 832 |
errCh := make(chan error, 1) |
| 833 |
nc, err := nats.Connect(clientURL, nats.UserJWT(jwtCB, sigCB), nats.ReconnectWait(100*time.Millisecond), |
| 834 |
nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) { |
| 835 |
errCh <- err |
| 836 |
})) |
| 837 |
if err != nil { |
| 838 |
t.Fatalf("Expected to connect, got %v", err) |
| 839 |
} |
| 840 |
stasusCh := nc.StatusChanged(nats.RECONNECTING, nats.CONNECTED) |
| 841 |
select { |
| 842 |
case err := <-errCh: |
| 843 |
if !errors.Is(err, nats.ErrAuthExpired) { |
| 844 |
t.Fatalf("Expected auth expired error, got %v", err) |
| 845 |
} |
| 846 |
case <-time.After(2 * time.Second): |
| 847 |
t.Fatal("Did not get the auth expired error") |
| 848 |
} |
| 849 |
WaitOnChannel(t, stasusCh, nats.RECONNECTING) |
| 850 |
WaitOnChannel(t, stasusCh, nats.CONNECTED) |
| 851 |
nc.Close() |
| 852 |
} |
| 853 |
|
| 854 |
func TestForceReconnect(t *testing.T) { |
| 855 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 856 |
nc, err := nats.Connect(inst.Servers[0].URL, nats.ReconnectWait(10*time.Second)) |
| 857 |
if err != nil { |
| 858 |
t.Fatalf("Unexpected error on connect: %v", err) |
| 859 |
} |
| 860 |
|
| 861 |
statusCh := nc.StatusChanged(nats.RECONNECTING, nats.CONNECTED) |
| 862 |
defer close(statusCh) |
| 863 |
newStatus := make(chan nats.Status, 10) |
| 864 |
// non-blocking channel, so we need to be constantly listening |
| 865 |
go func() { |
| 866 |
for { |
| 867 |
s, ok := <-statusCh |
| 868 |
if !ok { |
| 869 |
return |
| 870 |
} |
| 871 |
newStatus <- s |
| 872 |
} |
| 873 |
}() |
| 874 |
|
| 875 |
sub, err := nc.SubscribeSync("foo") |
| 876 |
if err != nil { |
| 877 |
t.Fatalf("Error on subscribe: %v", err) |
| 878 |
} |
| 879 |
if err := nc.Publish("foo", []byte("msg")); err != nil { |
| 880 |
t.Fatalf("Error on publish: %v", err) |
| 881 |
} |
| 882 |
_, err = sub.NextMsg(time.Second) |
| 883 |
if err != nil { |
| 884 |
t.Fatalf("Error getting message: %v", err) |
| 885 |
} |
| 886 |
|
| 887 |
// Force a reconnect |
| 888 |
err = nc.ForceReconnect() |
| 889 |
if err != nil { |
| 890 |
t.Fatalf("Unexpected error on reconnect: %v", err) |
| 891 |
} |
| 892 |
|
| 893 |
WaitOnChannel(t, newStatus, nats.RECONNECTING) |
| 894 |
WaitOnChannel(t, newStatus, nats.CONNECTED) |
| 895 |
|
| 896 |
if err := nc.Publish("foo", []byte("msg")); err != nil { |
| 897 |
t.Fatalf("Error on publish: %v", err) |
| 898 |
} |
| 899 |
_, err = sub.NextMsg(time.Second) |
| 900 |
if err != nil { |
| 901 |
t.Fatalf("Error getting message: %v", err) |
| 902 |
} |
| 903 |
|
| 904 |
// shutdown server and then force a reconnect |
| 905 |
inst.StopServer(t, inst.Servers[0]) |
| 906 |
WaitOnChannel(t, newStatus, nats.RECONNECTING) |
| 907 |
_, err = sub.NextMsg(100 * time.Millisecond) |
| 908 |
if err == nil { |
| 909 |
t.Fatal("Expected error getting message") |
| 910 |
} |
| 911 |
|
| 912 |
// restart server |
| 913 |
inst.StartServer(t, inst.Servers[0]) |
| 914 |
|
| 915 |
if err := nc.ForceReconnect(); err != nil { |
| 916 |
t.Fatalf("Unexpected error on reconnect: %v", err) |
| 917 |
} |
| 918 |
// wait for the reconnect |
| 919 |
// because the connection has long ReconnectWait, |
| 920 |
// if force reconnect does not work, the test will timeout |
| 921 |
WaitOnChannel(t, newStatus, nats.CONNECTED) |
| 922 |
|
| 923 |
if err := nc.Publish("foo", []byte("msg")); err != nil { |
| 924 |
t.Fatalf("Error on publish: %v", err) |
| 925 |
} |
| 926 |
_, err = sub.NextMsg(time.Second) |
| 927 |
if err != nil { |
| 928 |
t.Fatalf("Error getting message: %v", err) |
| 929 |
} |
| 930 |
nc.Close() |
| 931 |
}) |
| 932 |
} |
| 933 |
|
| 934 |
func TestForceReconnectDisallowReconnect(t *testing.T) { |
| 935 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 936 |
nc, err := nats.Connect(inst.Servers[0].URL, nats.NoReconnect()) |
| 937 |
if err != nil { |
| 938 |
t.Fatalf("Unexpected error on connect: %v", err) |
| 939 |
} |
| 940 |
defer nc.Close() |
| 941 |
|
| 942 |
statusCh := nc.StatusChanged(nats.RECONNECTING, nats.CONNECTED) |
| 943 |
defer close(statusCh) |
| 944 |
newStatus := make(chan nats.Status, 10) |
| 945 |
// non-blocking channel, so we need to be constantly listening |
| 946 |
go func() { |
| 947 |
for { |
| 948 |
s, ok := <-statusCh |
| 949 |
if !ok { |
| 950 |
return |
| 951 |
} |
| 952 |
newStatus <- s |
| 953 |
} |
| 954 |
}() |
| 955 |
|
| 956 |
sub, err := nc.SubscribeSync("foo") |
| 957 |
if err != nil { |
| 958 |
t.Fatalf("Error on subscribe: %v", err) |
| 959 |
} |
| 960 |
if err := nc.Publish("foo", []byte("msg")); err != nil { |
| 961 |
t.Fatalf("Error on publish: %v", err) |
| 962 |
} |
| 963 |
_, err = sub.NextMsg(time.Second) |
| 964 |
if err != nil { |
| 965 |
t.Fatalf("Error getting message: %v", err) |
| 966 |
} |
| 967 |
|
| 968 |
// Force a reconnect |
| 969 |
err = nc.ForceReconnect() |
| 970 |
if err != nil { |
| 971 |
t.Fatalf("Unexpected error on reconnect: %v", err) |
| 972 |
} |
| 973 |
|
| 974 |
WaitOnChannel(t, newStatus, nats.RECONNECTING) |
| 975 |
WaitOnChannel(t, newStatus, nats.CONNECTED) |
| 976 |
|
| 977 |
if err := nc.Publish("foo", []byte("msg")); err != nil { |
| 978 |
t.Fatalf("Error on publish: %v", err) |
| 979 |
} |
| 980 |
_, err = sub.NextMsg(time.Second) |
| 981 |
if err != nil { |
| 982 |
t.Fatalf("Error getting message: %v", err) |
| 983 |
} |
| 984 |
}) |
| 985 |
} |
| 986 |
|
| 987 |
func TestForceReconnectSubsequentCalls(t *testing.T) { |
| 988 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 989 |
nc, err := nats.Connect(inst.Servers[0].URL, nats.ReconnectWait(10*time.Second)) |
| 990 |
if err != nil { |
| 991 |
t.Fatalf("Unexpected error on connect: %v", err) |
| 992 |
} |
| 993 |
defer nc.Close() |
| 994 |
|
| 995 |
statusCh := nc.StatusChanged(nats.RECONNECTING, nats.CONNECTED) |
| 996 |
defer close(statusCh) |
| 997 |
newStatus := make(chan nats.Status, 10) |
| 998 |
// non-blocking channel, so we need to be constantly listening |
| 999 |
go func() { |
| 1000 |
for { |
| 1001 |
s, ok := <-statusCh |
| 1002 |
if !ok { |
| 1003 |
return |
| 1004 |
} |
| 1005 |
newStatus <- s |
| 1006 |
} |
| 1007 |
}() |
| 1008 |
|
| 1009 |
for range 10 { |
| 1010 |
err = nc.ForceReconnect() |
| 1011 |
if err != nil { |
| 1012 |
t.Fatalf("Unexpected error on reconnect: %v", err) |
| 1013 |
} |
| 1014 |
} |
| 1015 |
|
| 1016 |
WaitOnChannel(t, newStatus, nats.RECONNECTING) |
| 1017 |
WaitOnChannel(t, newStatus, nats.CONNECTED) |
| 1018 |
|
| 1019 |
// check that we did not try to reconnect again |
| 1020 |
select { |
| 1021 |
case <-newStatus: |
| 1022 |
t.Fatal("Should not have received a new status") |
| 1023 |
case <-time.After(200 * time.Millisecond): |
| 1024 |
} |
| 1025 |
|
| 1026 |
// now force a reconnect again |
| 1027 |
if err := nc.ForceReconnect(); err != nil { |
| 1028 |
t.Fatalf("Unexpected error on reconnect: %v", err) |
| 1029 |
} |
| 1030 |
WaitOnChannel(t, newStatus, nats.RECONNECTING) |
| 1031 |
WaitOnChannel(t, newStatus, nats.CONNECTED) |
| 1032 |
}) |
| 1033 |
} |
| 1034 |
|
| 1035 |
func TestAuthExpiredForceReconnect(t *testing.T) { |
| 1036 |
c := newTester(t) |
| 1037 |
inst := c.CreateServer(t, false, trustServerOpts(t)...) |
| 1038 |
t.Cleanup(func() { inst.Destroy(t) }) |
| 1039 |
|
| 1040 |
clientURL := inst.Servers[0].URL |
| 1041 |
|
| 1042 |
_, err := nats.Connect(clientURL) |
| 1043 |
if err == nil { |
| 1044 |
t.Fatalf("Expecting an error on connect") |
| 1045 |
} |
| 1046 |
ukp, err := nkeys.FromSeed(tsUSeed) |
| 1047 |
if err != nil { |
| 1048 |
t.Fatalf("Error creating user key pair: %v", err) |
| 1049 |
} |
| 1050 |
upub, err := ukp.PublicKey() |
| 1051 |
if err != nil { |
| 1052 |
t.Fatalf("Error getting user public key: %v", err) |
| 1053 |
} |
| 1054 |
akp, err := nkeys.FromSeed(tsASeed) |
| 1055 |
if err != nil { |
| 1056 |
t.Fatalf("Error creating account key pair: %v", err) |
| 1057 |
} |
| 1058 |
|
| 1059 |
jwtCB := func() (string, error) { |
| 1060 |
claims := jwt.NewUserClaims("test") |
| 1061 |
claims.Expires = time.Now().Add(time.Second).Unix() |
| 1062 |
claims.Subject = upub |
| 1063 |
jwt, err := claims.Encode(akp) |
| 1064 |
if err != nil { |
| 1065 |
return "", err |
| 1066 |
} |
| 1067 |
return jwt, nil |
| 1068 |
} |
| 1069 |
sigCB := func(nonce []byte) ([]byte, error) { |
| 1070 |
kp, _ := nkeys.FromSeed(tsUSeed) |
| 1071 |
sig, _ := kp.Sign(nonce) |
| 1072 |
return sig, nil |
| 1073 |
} |
| 1074 |
|
| 1075 |
errCh := make(chan error, 1) |
| 1076 |
nc, err := nats.Connect(clientURL, nats.UserJWT(jwtCB, sigCB), nats.ReconnectWait(10*time.Second), |
| 1077 |
nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) { |
| 1078 |
errCh <- err |
| 1079 |
})) |
| 1080 |
if err != nil { |
| 1081 |
t.Fatalf("Expected to connect, got %v", err) |
| 1082 |
} |
| 1083 |
defer nc.Close() |
| 1084 |
statusCh := nc.StatusChanged(nats.RECONNECTING, nats.CONNECTED) |
| 1085 |
defer close(statusCh) |
| 1086 |
newStatus := make(chan nats.Status, 10) |
| 1087 |
// non-blocking channel, so we need to be constantly listening |
| 1088 |
go func() { |
| 1089 |
for { |
| 1090 |
s, ok := <-statusCh |
| 1091 |
if !ok { |
| 1092 |
return |
| 1093 |
} |
| 1094 |
newStatus <- s |
| 1095 |
} |
| 1096 |
}() |
| 1097 |
time.Sleep(100 * time.Millisecond) |
| 1098 |
select { |
| 1099 |
case err := <-errCh: |
| 1100 |
if !errors.Is(err, nats.ErrAuthExpired) { |
| 1101 |
t.Fatalf("Expected auth expired error, got %v", err) |
| 1102 |
} |
| 1103 |
case <-time.After(2 * time.Second): |
| 1104 |
t.Fatal("Did not get the auth expired error") |
| 1105 |
} |
| 1106 |
if err := nc.ForceReconnect(); err != nil { |
| 1107 |
t.Fatalf("Unexpected error on reconnect: %v", err) |
| 1108 |
} |
| 1109 |
WaitOnChannel(t, newStatus, nats.RECONNECTING) |
| 1110 |
WaitOnChannel(t, newStatus, nats.CONNECTED) |
| 1111 |
} |
| 1112 |
|
| 1113 |
func TestAlwaysReconnectOnMaxConnectionsExceededErr(t *testing.T) { |
| 1114 |
c := newTester(t) |
| 1115 |
inst := c.CreateServer(t, false, testservice.WithTopLevel("max_connections: 2")) |
| 1116 |
t.Cleanup(func() { inst.Destroy(t) }) |
| 1117 |
|
| 1118 |
srvURL := inst.Servers[0].URL |
| 1119 |
|
| 1120 |
clientOpts := func(name string) ([]nats.Option, chan error, chan struct{}, chan struct{}) { |
| 1121 |
disconnectCh := make(chan error, 10) |
| 1122 |
reconnectCh := make(chan struct{}, 10) |
| 1123 |
closedCh := make(chan struct{}, 10) |
| 1124 |
return []nats.Option{ |
| 1125 |
nats.MaxReconnects(-1), |
| 1126 |
nats.ReconnectWait(10 * time.Millisecond), |
| 1127 |
nats.Timeout(200 * time.Millisecond), |
| 1128 |
nats.DisconnectErrHandler(func(c *nats.Conn, err error) { |
| 1129 |
clientID, _ := c.GetClientID() |
| 1130 |
t.Logf("[%v] Disconnected: %v: %v", name, clientID, err) |
| 1131 |
if err != nil { |
| 1132 |
disconnectCh <- err |
| 1133 |
} |
| 1134 |
}), |
| 1135 |
nats.ReconnectHandler(func(c *nats.Conn) { |
| 1136 |
clientID, _ := c.GetClientID() |
| 1137 |
t.Logf("[%v] Reconnected: %v", name, clientID) |
| 1138 |
reconnectCh <- struct{}{} |
| 1139 |
}), |
| 1140 |
nats.ClosedHandler(func(c *nats.Conn) { |
| 1141 |
clientID, _ := c.GetClientID() |
| 1142 |
t.Logf("[%v] Closed: %v", name, clientID) |
| 1143 |
closedCh <- struct{}{} |
| 1144 |
}), |
| 1145 |
nats.Name(name), |
| 1146 |
}, disconnectCh, reconnectCh, closedCh |
| 1147 |
} |
| 1148 |
|
| 1149 |
opts1, errCh1, reconnectCh1, _ := clientOpts("A") |
| 1150 |
nc1, err := nats.Connect(srvURL, opts1...) |
| 1151 |
if err != nil { |
| 1152 |
t.Fatalf("Failed to connect first client: %v", err) |
| 1153 |
} |
| 1154 |
defer nc1.Close() |
| 1155 |
|
| 1156 |
opts2, errCh2, reconnectCh2, _ := clientOpts("B") |
| 1157 |
nc2, err := nats.Connect(srvURL, opts2...) |
| 1158 |
if err != nil { |
| 1159 |
t.Fatalf("Failed to connect second client: %v", err) |
| 1160 |
} |
| 1161 |
defer nc2.Close() |
| 1162 |
|
| 1163 |
if err := nc1.Flush(); err != nil { |
| 1164 |
t.Errorf("Unexpected error: %v", err) |
| 1165 |
} |
| 1166 |
if err := nc2.Flush(); err != nil { |
| 1167 |
t.Errorf("Unexpected error: %v", err) |
| 1168 |
} |
| 1169 |
|
| 1170 |
// Reload to lower max_connections. |
| 1171 |
inst.UpdateServer(t, inst.Servers[0], testservice.WithTopLevel("max_connections: 1")) |
| 1172 |
inst.ReloadServer(t, inst.Servers[0]) |
| 1173 |
|
| 1174 |
select { |
| 1175 |
case err := <-errCh1: |
| 1176 |
if err != nats.ErrMaxConnectionsExceeded { |
| 1177 |
t.Fatalf("Expected ErrMaxConnectionsExceeded, got %v", err) |
| 1178 |
} |
| 1179 |
case err := <-errCh2: |
| 1180 |
if err != nats.ErrMaxConnectionsExceeded { |
| 1181 |
t.Fatalf("Expected ErrMaxConnectionsExceeded, got %v", err) |
| 1182 |
} |
| 1183 |
case <-time.After(2 * time.Second): |
| 1184 |
t.Fatal("Timed out waiting for disconnect event") |
| 1185 |
} |
| 1186 |
if nc1.IsConnected() && nc2.IsConnected() { |
| 1187 |
t.Fatalf("Expected a client to be disconnected") |
| 1188 |
} |
| 1189 |
|
| 1190 |
// Reload to increase max_connections. |
| 1191 |
inst.UpdateServer(t, inst.Servers[0], testservice.WithTopLevel("max_connections: 10")) |
| 1192 |
inst.ReloadServer(t, inst.Servers[0]) |
| 1193 |
|
| 1194 |
select { |
| 1195 |
case <-reconnectCh1: |
| 1196 |
case <-reconnectCh2: |
| 1197 |
case <-time.After(3 * time.Second): |
| 1198 |
t.Fatal("Timed out waiting for reconnect event") |
| 1199 |
} |
| 1200 |
if !(nc1.IsConnected() || nc2.IsConnected()) { |
| 1201 |
t.Fatal("At least one client should have reconnected successfully") |
| 1202 |
} |
| 1203 |
} |
| 1204 |
|
| 1205 |
// Covers the config-reload path only; driving the same limit through account |
| 1206 |
// claims needs an RPC the tester does not expose. |
| 1207 |
func TestAlwaysReconnectOnAccountMaxConnectionsExceededErr(t *testing.T) { |
| 1208 |
c := newTester(t) |
| 1209 |
initialAccounts := `accounts: { |
| 1210 |
ACCT1: { |
| 1211 |
users: [ {user: "user1", password: "pass1"} ] |
| 1212 |
limits: { max_conn: 1 } |
| 1213 |
}, |
| 1214 |
ACCT2: { |
| 1215 |
users: [ {user: "user2", password: "pass2"} ] |
| 1216 |
limits: { max_conn: 2 } |
| 1217 |
} |
| 1218 |
}` |
| 1219 |
inst := c.CreateServer(t, false, |
| 1220 |
testservice.WithAccounts(initialAccounts), |
| 1221 |
testservice.WithAuthorization("# no_auth_user intentionally unset"), |
| 1222 |
testservice.WithSystemAccount(noSystemAccountBody()), |
| 1223 |
) |
| 1224 |
t.Cleanup(func() { inst.Destroy(t) }) |
| 1225 |
|
| 1226 |
srvURL := inst.Servers[0].URL |
| 1227 |
|
| 1228 |
clientOpts := func(name string) ([]nats.Option, chan error, chan struct{}, chan struct{}) { |
| 1229 |
disconnectCh := make(chan error, 10) |
| 1230 |
reconnectCh := make(chan struct{}, 10) |
| 1231 |
closedCh := make(chan struct{}, 10) |
| 1232 |
return []nats.Option{ |
| 1233 |
nats.MaxReconnects(-1), |
| 1234 |
nats.ReconnectWait(200 * time.Millisecond), |
| 1235 |
nats.Timeout(200 * time.Millisecond), |
| 1236 |
nats.DisconnectErrHandler(func(c *nats.Conn, err error) { |
| 1237 |
clientID, _ := c.GetClientID() |
| 1238 |
t.Logf("[%v] Disconnected: %v: %v", name, clientID, err) |
| 1239 |
if err != nil { |
| 1240 |
disconnectCh <- err |
| 1241 |
} |
| 1242 |
}), |
| 1243 |
nats.ReconnectHandler(func(c *nats.Conn) { |
| 1244 |
clientID, _ := c.GetClientID() |
| 1245 |
t.Logf("[%v] Reconnected: %v", name, clientID) |
| 1246 |
reconnectCh <- struct{}{} |
| 1247 |
}), |
| 1248 |
nats.ClosedHandler(func(c *nats.Conn) { |
| 1249 |
clientID, _ := c.GetClientID() |
| 1250 |
t.Logf("[%v] Closed: %v", name, clientID) |
| 1251 |
closedCh <- struct{}{} |
| 1252 |
}), |
| 1253 |
nats.Name(name), |
| 1254 |
}, disconnectCh, reconnectCh, closedCh |
| 1255 |
} |
| 1256 |
|
| 1257 |
opts1, errCh1, reconnectCh1, _ := clientOpts("ACCT1:C:1") |
| 1258 |
opts1 = append(opts1, nats.UserInfo("user1", "pass1")) |
| 1259 |
nc1, err := nats.Connect(srvURL, opts1...) |
| 1260 |
if err != nil { |
| 1261 |
t.Fatalf("Failed to connect first client: %v", err) |
| 1262 |
} |
| 1263 |
defer nc1.Close() |
| 1264 |
|
| 1265 |
// Second connection to same account fails due to limit. |
| 1266 |
opts2, _, _, _ := clientOpts("ACCT1:C:2") |
| 1267 |
opts2 = append(opts2, nats.UserInfo("user1", "pass1")) |
| 1268 |
_, err = nats.Connect(srvURL, opts2...) |
| 1269 |
if err == nil { |
| 1270 |
t.Fatal("Expected connection to fail due to account max connections limit") |
| 1271 |
} |
| 1272 |
if !errors.Is(err, nats.ErrMaxAccountConnectionsExceeded) { |
| 1273 |
t.Fatalf("Expected second connection to be properly rejected: %v", err) |
| 1274 |
} |
| 1275 |
|
| 1276 |
// Loosen account limits via reload so a second client can join. |
| 1277 |
loosenedAccounts := `accounts: { |
| 1278 |
ACCT1: { |
| 1279 |
users: [ {user: "user1", password: "pass1"} ] |
| 1280 |
limits: { max_conn: 10 } |
| 1281 |
}, |
| 1282 |
ACCT2: { |
| 1283 |
users: [ {user: "user2", password: "pass2"} ] |
| 1284 |
limits: { max_conn: 2 } |
| 1285 |
} |
| 1286 |
}` |
| 1287 |
inst.UpdateServer(t, inst.Servers[0], |
| 1288 |
testservice.WithAccounts(loosenedAccounts), |
| 1289 |
testservice.WithAuthorization("# no_auth_user intentionally unset"), |
| 1290 |
testservice.WithSystemAccount(noSystemAccountBody()), |
| 1291 |
) |
| 1292 |
inst.ReloadServer(t, inst.Servers[0]) |
| 1293 |
|
| 1294 |
if err := nc1.Flush(); err != nil { |
| 1295 |
t.Fatalf("Failed to flush first connection: %v", err) |
| 1296 |
} |
| 1297 |
|
| 1298 |
opts3, errCh3, reconnectCh3, _ := clientOpts("ACCT1:C:3") |
| 1299 |
opts3 = append(opts3, nats.UserInfo("user1", "pass1")) |
| 1300 |
nc3, err := nats.Connect(srvURL, opts3...) |
| 1301 |
if err != nil { |
| 1302 |
t.Fatalf("Failed to connect client after limit increase: %v", err) |
| 1303 |
} |
| 1304 |
defer nc3.Close() |
| 1305 |
if err = nc3.Flush(); err != nil { |
| 1306 |
t.Fatalf("Unexpected error: %v", err) |
| 1307 |
} |
| 1308 |
|
| 1309 |
if !(nc1.IsConnected() && nc3.IsConnected()) { |
| 1310 |
t.Errorf("Expected both clients to be connected") |
| 1311 |
} |
| 1312 |
|
| 1313 |
// Tighten limits — server should kick one of the two active ACCT1 clients |
| 1314 |
// with an account-limit error; the kicked client must NOT give up (we set |
| 1315 |
// MaxReconnects(-1) above) — that's the always-reconnect semantic this |
| 1316 |
// test is named for. |
| 1317 |
tightenedAccounts := `accounts: { |
| 1318 |
ACCT1: { |
| 1319 |
users: [ {user: "user1", password: "pass1"} ] |
| 1320 |
limits: { max_conn: 1 } |
| 1321 |
}, |
| 1322 |
ACCT2: { |
| 1323 |
users: [ {user: "user2", password: "pass2"} ] |
| 1324 |
limits: { max_conn: 2 } |
| 1325 |
} |
| 1326 |
}` |
| 1327 |
inst.UpdateServer(t, inst.Servers[0], |
| 1328 |
testservice.WithAccounts(tightenedAccounts), |
| 1329 |
testservice.WithAuthorization("# no_auth_user intentionally unset"), |
| 1330 |
testservice.WithSystemAccount(noSystemAccountBody()), |
| 1331 |
) |
| 1332 |
inst.ReloadServer(t, inst.Servers[0]) |
| 1333 |
|
| 1334 |
select { |
| 1335 |
case err := <-errCh1: |
| 1336 |
if !errors.Is(err, nats.ErrMaxAccountConnectionsExceeded) { |
| 1337 |
t.Fatalf("Expected account-limit error on nc1, got %v", err) |
| 1338 |
} |
| 1339 |
case err := <-errCh3: |
| 1340 |
if !errors.Is(err, nats.ErrMaxAccountConnectionsExceeded) { |
| 1341 |
t.Fatalf("Expected account-limit error on nc3, got %v", err) |
| 1342 |
} |
| 1343 |
case <-time.After(2 * time.Second): |
| 1344 |
t.Fatal("Timed out waiting for disconnect event after tighten") |
| 1345 |
} |
| 1346 |
if nc1.IsConnected() && nc3.IsConnected() { |
| 1347 |
t.Fatal("Expected one ACCT1 client to be kicked after tighten") |
| 1348 |
} |
| 1349 |
|
| 1350 |
// Re-loosen so the kicked client can reconnect. If MaxReconnects(-1) |
| 1351 |
// honored the account-limit error correctly, the kicked client kept |
| 1352 |
// retrying and now succeeds. |
| 1353 |
inst.UpdateServer(t, inst.Servers[0], |
| 1354 |
testservice.WithAccounts(loosenedAccounts), |
| 1355 |
testservice.WithAuthorization("# no_auth_user intentionally unset"), |
| 1356 |
testservice.WithSystemAccount(noSystemAccountBody()), |
| 1357 |
) |
| 1358 |
inst.ReloadServer(t, inst.Servers[0]) |
| 1359 |
|
| 1360 |
select { |
| 1361 |
case <-reconnectCh1: |
| 1362 |
case <-reconnectCh3: |
| 1363 |
case <-time.After(3 * time.Second): |
| 1364 |
t.Fatal("Timed out waiting for reconnect event after re-loosen") |
| 1365 |
} |
| 1366 |
// Both must end up connected: the survivor never dropped, and the kicked |
| 1367 |
// client reconnects once the limit is loosened. Polled because the |
| 1368 |
// reconnect is asynchronous. |
| 1369 |
checkFor(t, 3*time.Second, 50*time.Millisecond, func() error { |
| 1370 |
if !nc1.IsConnected() || !nc3.IsConnected() { |
| 1371 |
return fmt.Errorf("expected both ACCT1 clients connected, got nc1=%v nc3=%v", |
| 1372 |
nc1.IsConnected(), nc3.IsConnected()) |
| 1373 |
} |
| 1374 |
return nil |
| 1375 |
}) |
| 1376 |
} |
| 1377 |
|
| 1378 |
func TestReconnectToServerCallback(t *testing.T) { |
| 1379 |
t.Run("select custom server", func(t *testing.T) { |
| 1380 |
c := newTester(t) |
| 1381 |
srv1Inst := c.CreateServer(t, false) |
| 1382 |
t.Cleanup(func() { srv1Inst.Destroy(t) }) |
| 1383 |
srv2Inst := c.CreateServer(t, false) |
| 1384 |
t.Cleanup(func() { srv2Inst.Destroy(t) }) |
| 1385 |
|
| 1386 |
url1 := srv1Inst.Servers[0].URL |
| 1387 |
url2 := srv2Inst.Servers[0].URL |
| 1388 |
|
| 1389 |
var callbackCalled atomic.Int32 |
| 1390 |
reconnectCh := make(chan bool, 1) |
| 1391 |
|
| 1392 |
nc, err := nats.Connect( |
| 1393 |
url1+","+url2, |
| 1394 |
nats.ReconnectWait(100*time.Millisecond), |
| 1395 |
nats.MaxReconnects(10), |
| 1396 |
nats.DontRandomize(), |
| 1397 |
nats.ReconnectToServer(func(servers []nats.Server, info nats.ServerInfo) (*nats.Server, time.Duration) { |
| 1398 |
callbackCalled.Add(1) |
| 1399 |
for i := range servers { |
| 1400 |
if servers[i].URL.String() == url2 { |
| 1401 |
return &servers[i], 0 |
| 1402 |
} |
| 1403 |
} |
| 1404 |
return &servers[0], 0 |
| 1405 |
}), |
| 1406 |
nats.ReconnectHandler(func(_ *nats.Conn) { |
| 1407 |
select { |
| 1408 |
case reconnectCh <- true: |
| 1409 |
default: |
| 1410 |
} |
| 1411 |
}), |
| 1412 |
) |
| 1413 |
if err != nil { |
| 1414 |
t.Fatalf("Failed to connect: %v", err) |
| 1415 |
} |
| 1416 |
defer nc.Close() |
| 1417 |
|
| 1418 |
if nc.ConnectedUrl() != url1 { |
| 1419 |
t.Fatalf("Expected initial connection to %s, got %s", url1, nc.ConnectedUrl()) |
| 1420 |
} |
| 1421 |
|
| 1422 |
// try reconnecting a few times, we should end up on url2 each time |
| 1423 |
for i := range 5 { |
| 1424 |
if err := nc.ForceReconnect(); err != nil { |
| 1425 |
t.Fatalf("Failed to force reconnect: %v", err) |
| 1426 |
} |
| 1427 |
|
| 1428 |
select { |
| 1429 |
case <-reconnectCh: |
| 1430 |
case <-time.After(2 * time.Second): |
| 1431 |
t.Fatal("Timed out waiting for reconnect") |
| 1432 |
} |
| 1433 |
|
| 1434 |
if callbackCalled.Load() != int32(i+1) { |
| 1435 |
t.Fatal("Expected ReconnectToServer callback to be called on each reconnect") |
| 1436 |
} |
| 1437 |
|
| 1438 |
if nc.ConnectedUrl() != url2 { |
| 1439 |
t.Fatalf("Expected connection to %s after callback selection, got %s", url2, nc.ConnectedUrl()) |
| 1440 |
} |
| 1441 |
} |
| 1442 |
}) |
| 1443 |
|
| 1444 |
t.Run("wait before reconnect", func(t *testing.T) { |
| 1445 |
c := newTester(t) |
| 1446 |
srv1Inst := c.CreateServer(t, false) |
| 1447 |
t.Cleanup(func() { srv1Inst.Destroy(t) }) |
| 1448 |
srv2Inst := c.CreateServer(t, false) |
| 1449 |
t.Cleanup(func() { srv2Inst.Destroy(t) }) |
| 1450 |
|
| 1451 |
url1 := srv1Inst.Servers[0].URL |
| 1452 |
url2 := srv2Inst.Servers[0].URL |
| 1453 |
|
| 1454 |
reconnectCh := make(chan bool, 1) |
| 1455 |
|
| 1456 |
nc, err := nats.Connect( |
| 1457 |
url1+","+url2, |
| 1458 |
nats.ReconnectWait(2*time.Second), |
| 1459 |
nats.MaxReconnects(10), |
| 1460 |
nats.DontRandomize(), |
| 1461 |
nats.ReconnectToServer(func(servers []nats.Server, info nats.ServerInfo) (*nats.Server, time.Duration) { |
| 1462 |
for i := range servers { |
| 1463 |
if servers[i].URL.String() == url2 { |
| 1464 |
return &servers[i], 500 * time.Millisecond |
| 1465 |
} |
| 1466 |
} |
| 1467 |
return &servers[0], 500 * time.Millisecond |
| 1468 |
}), |
| 1469 |
nats.ReconnectHandler(func(_ *nats.Conn) { |
| 1470 |
select { |
| 1471 |
case reconnectCh <- true: |
| 1472 |
default: |
| 1473 |
} |
| 1474 |
}), |
| 1475 |
) |
| 1476 |
if err != nil { |
| 1477 |
t.Fatalf("Failed to connect: %v", err) |
| 1478 |
} |
| 1479 |
defer nc.Close() |
| 1480 |
|
| 1481 |
if nc.ConnectedUrl() != url1 { |
| 1482 |
t.Fatalf("Expected initial connection to %s, got %s", url1, nc.ConnectedUrl()) |
| 1483 |
} |
| 1484 |
now := time.Now() |
| 1485 |
if err := nc.ForceReconnect(); err != nil { |
| 1486 |
t.Fatalf("Failed to force reconnect: %v", err) |
| 1487 |
} |
| 1488 |
|
| 1489 |
select { |
| 1490 |
case <-reconnectCh: |
| 1491 |
elapsed := time.Since(now) |
| 1492 |
if elapsed < 500*time.Millisecond { |
| 1493 |
t.Fatalf("Reconnect occurred too quickly, expected ~500ms, got %v", elapsed) |
| 1494 |
} |
| 1495 |
if elapsed > 1500*time.Millisecond { |
| 1496 |
t.Fatalf("Reconnect took too long (used ReconnectWait instead of callback delay?), got %v", elapsed) |
| 1497 |
} |
| 1498 |
case <-time.After(5 * time.Second): |
| 1499 |
t.Fatal("Timed out waiting for reconnect") |
| 1500 |
} |
| 1501 |
}) |
| 1502 |
|
| 1503 |
t.Run("server not in pool fires error callback", func(t *testing.T) { |
| 1504 |
c := newTester(t) |
| 1505 |
srv1Inst := c.CreateServer(t, false) |
| 1506 |
t.Cleanup(func() { srv1Inst.Destroy(t) }) |
| 1507 |
srv2Inst := c.CreateServer(t, false) |
| 1508 |
t.Cleanup(func() { srv2Inst.Destroy(t) }) |
| 1509 |
|
| 1510 |
url1 := srv1Inst.Servers[0].URL |
| 1511 |
url2 := srv2Inst.Servers[0].URL |
| 1512 |
|
| 1513 |
reconnectCh := make(chan bool, 1) |
| 1514 |
var reconnectErr atomic.Value |
| 1515 |
|
| 1516 |
nc, err := nats.Connect( |
| 1517 |
url1+","+url2, |
| 1518 |
nats.ReconnectWait(50*time.Millisecond), |
| 1519 |
nats.MaxReconnects(10), |
| 1520 |
nats.DontRandomize(), |
| 1521 |
nats.ReconnectToServer(func(servers []nats.Server, info nats.ServerInfo) (*nats.Server, time.Duration) { |
| 1522 |
return &nats.Server{URL: &url.URL{Scheme: "nats", Host: "127.0.0.1:9999"}}, 0 |
| 1523 |
}), |
| 1524 |
nats.ReconnectErrHandler(func(_ *nats.Conn, err error) { |
| 1525 |
reconnectErr.Store(err) |
| 1526 |
}), |
| 1527 |
nats.ReconnectHandler(func(_ *nats.Conn) { |
| 1528 |
select { |
| 1529 |
case reconnectCh <- true: |
| 1530 |
default: |
| 1531 |
} |
| 1532 |
}), |
| 1533 |
) |
| 1534 |
if err != nil { |
| 1535 |
t.Fatalf("Failed to connect: %v", err) |
| 1536 |
} |
| 1537 |
defer nc.Close() |
| 1538 |
|
| 1539 |
srv1Inst.StopServer(t, srv1Inst.Servers[0]) |
| 1540 |
|
| 1541 |
select { |
| 1542 |
case <-reconnectCh: |
| 1543 |
case <-time.After(2 * time.Second): |
| 1544 |
t.Fatal("Timed out waiting for reconnect") |
| 1545 |
} |
| 1546 |
|
| 1547 |
if nc.ConnectedUrl() != url2 { |
| 1548 |
t.Fatalf("Expected connection to %s via default fallback, got %s", url2, nc.ConnectedUrl()) |
| 1549 |
} |
| 1550 |
|
| 1551 |
if storedErr, ok := reconnectErr.Load().(error); !ok { |
| 1552 |
t.Fatalf("Expected an error in ReconnectErrHandler, got %v", storedErr) |
| 1553 |
} else if !errors.Is(storedErr, nats.ErrServerNotInPool) { |
| 1554 |
t.Fatalf("Expected ErrServerNotInPool, got %v", storedErr) |
| 1555 |
} |
| 1556 |
}) |
| 1557 |
|
| 1558 |
t.Run("nil server falls back to default selection", func(t *testing.T) { |
| 1559 |
c := newTester(t) |
| 1560 |
srv1Inst := c.CreateServer(t, false) |
| 1561 |
t.Cleanup(func() { srv1Inst.Destroy(t) }) |
| 1562 |
srv2Inst := c.CreateServer(t, false) |
| 1563 |
t.Cleanup(func() { srv2Inst.Destroy(t) }) |
| 1564 |
|
| 1565 |
url1 := srv1Inst.Servers[0].URL |
| 1566 |
url2 := srv2Inst.Servers[0].URL |
| 1567 |
|
| 1568 |
reconnectCh := make(chan bool, 1) |
| 1569 |
|
| 1570 |
nc, err := nats.Connect( |
| 1571 |
url1+","+url2, |
| 1572 |
nats.ReconnectWait(50*time.Millisecond), |
| 1573 |
nats.MaxReconnects(10), |
| 1574 |
nats.DontRandomize(), |
| 1575 |
nats.ReconnectToServer(func(servers []nats.Server, info nats.ServerInfo) (*nats.Server, time.Duration) { |
| 1576 |
return nil, 0 |
| 1577 |
}), |
| 1578 |
nats.ReconnectHandler(func(_ *nats.Conn) { |
| 1579 |
select { |
| 1580 |
case reconnectCh <- true: |
| 1581 |
default: |
| 1582 |
} |
| 1583 |
}), |
| 1584 |
) |
| 1585 |
if err != nil { |
| 1586 |
t.Fatalf("Failed to connect: %v", err) |
| 1587 |
} |
| 1588 |
defer nc.Close() |
| 1589 |
|
| 1590 |
srv1Inst.StopServer(t, srv1Inst.Servers[0]) |
| 1591 |
|
| 1592 |
select { |
| 1593 |
case <-reconnectCh: |
| 1594 |
case <-time.After(2 * time.Second): |
| 1595 |
t.Fatal("Timed out waiting for reconnect") |
| 1596 |
} |
| 1597 |
|
| 1598 |
if nc.ConnectedUrl() != url2 { |
| 1599 |
t.Fatalf("Expected connection to %s via default fallback, got %s", url2, nc.ConnectedUrl()) |
| 1600 |
} |
| 1601 |
}) |
| 1602 |
} |
| 1603 |
|
| 1604 |
func TestSetServerPool(t *testing.T) { |
| 1605 |
t.Run("reconnect to server from new pool", func(t *testing.T) { |
| 1606 |
c := newTester(t) |
| 1607 |
srv1Inst := c.CreateServer(t, false) |
| 1608 |
t.Cleanup(func() { srv1Inst.Destroy(t) }) |
| 1609 |
srv2Inst := c.CreateServer(t, false) |
| 1610 |
t.Cleanup(func() { srv2Inst.Destroy(t) }) |
| 1611 |
|
| 1612 |
url1 := srv1Inst.Servers[0].URL |
| 1613 |
url2 := srv2Inst.Servers[0].URL |
| 1614 |
|
| 1615 |
reconnectCh := make(chan bool, 1) |
| 1616 |
disconnectCh := make(chan bool, 1) |
| 1617 |
|
| 1618 |
nc, err := nats.Connect( |
| 1619 |
url1, |
| 1620 |
nats.ReconnectWait(50*time.Millisecond), |
| 1621 |
nats.MaxReconnects(10), |
| 1622 |
nats.DisconnectErrHandler(func(_ *nats.Conn, _ error) { |
| 1623 |
select { |
| 1624 |
case disconnectCh <- true: |
| 1625 |
default: |
| 1626 |
} |
| 1627 |
}), |
| 1628 |
nats.ReconnectHandler(func(_ *nats.Conn) { |
| 1629 |
select { |
| 1630 |
case reconnectCh <- true: |
| 1631 |
default: |
| 1632 |
} |
| 1633 |
}), |
| 1634 |
) |
| 1635 |
if err != nil { |
| 1636 |
t.Fatalf("Failed to connect: %v", err) |
| 1637 |
} |
| 1638 |
defer nc.Close() |
| 1639 |
|
| 1640 |
if nc.ConnectedUrl() != url1 { |
| 1641 |
t.Fatalf("Expected initial connection to %s, got %s", url1, nc.ConnectedUrl()) |
| 1642 |
} |
| 1643 |
|
| 1644 |
srv3Inst := c.CreateServer(t, false) |
| 1645 |
t.Cleanup(func() { srv3Inst.Destroy(t) }) |
| 1646 |
url3 := srv3Inst.Servers[0].URL |
| 1647 |
|
| 1648 |
if err := nc.SetServerPool([]string{url2, url3}); err != nil { |
| 1649 |
t.Fatalf("Failed to set server pool: %v", err) |
| 1650 |
} |
| 1651 |
|
| 1652 |
srv1Inst.StopServer(t, srv1Inst.Servers[0]) |
| 1653 |
|
| 1654 |
select { |
| 1655 |
case <-disconnectCh: |
| 1656 |
case <-time.After(2 * time.Second): |
| 1657 |
t.Fatal("Timed out waiting for disconnect") |
| 1658 |
} |
| 1659 |
|
| 1660 |
select { |
| 1661 |
case <-reconnectCh: |
| 1662 |
case <-time.After(2 * time.Second): |
| 1663 |
t.Fatal("Timed out waiting for reconnect") |
| 1664 |
} |
| 1665 |
|
| 1666 |
connectedURL := nc.ConnectedUrl() |
| 1667 |
if connectedURL != url2 && connectedURL != url3 { |
| 1668 |
t.Fatalf("Expected connection to %s or %s, got %s", url2, url3, connectedURL) |
| 1669 |
} |
| 1670 |
}) |
| 1671 |
|
| 1672 |
t.Run("atomic operation - partial failure doesn't modify pool", func(t *testing.T) { |
| 1673 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 1674 |
originalPool := nc.ServerPool() |
| 1675 |
if len(originalPool) != 1 { |
| 1676 |
t.Fatalf("Expected 1 server in original pool, got %d", len(originalPool)) |
| 1677 |
} |
| 1678 |
|
| 1679 |
err := nc.SetServerPool([]string{ |
| 1680 |
"nats://localhost:4222", |
| 1681 |
"invalid://bad url with spaces", |
| 1682 |
"nats://localhost:4223", |
| 1683 |
}) |
| 1684 |
if err == nil { |
| 1685 |
t.Fatal("Expected error from invalid URL, got nil") |
| 1686 |
} |
| 1687 |
|
| 1688 |
currentPool := nc.ServerPool() |
| 1689 |
if len(currentPool) != len(originalPool) { |
| 1690 |
t.Fatalf("Pool was modified on error: expected %d servers, got %d", len(originalPool), len(currentPool)) |
| 1691 |
} |
| 1692 |
if currentPool[0].URL.String() != originalPool[0].URL.String() { |
| 1693 |
t.Fatalf("Pool was modified on error: expected %s, got %s", originalPool[0].URL.String(), currentPool[0].URL.String()) |
| 1694 |
} |
| 1695 |
}) |
| 1696 |
}) |
| 1697 |
|
| 1698 |
t.Run("websocket URLs rejected for non-websocket connection", func(t *testing.T) { |
| 1699 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 1700 |
originalPool := nc.ServerPool() |
| 1701 |
|
| 1702 |
err := nc.SetServerPool([]string{"ws://localhost:8080"}) |
| 1703 |
if !errors.Is(err, nats.ErrMixingWebsocketSchemes) { |
| 1704 |
t.Fatal("Expected error from websocket URL on non-websocket connection") |
| 1705 |
} |
| 1706 |
|
| 1707 |
currentPool := nc.ServerPool() |
| 1708 |
if len(currentPool) != len(originalPool) { |
| 1709 |
t.Fatalf("Pool was modified on error: expected %d servers, got %d", len(originalPool), len(currentPool)) |
| 1710 |
} |
| 1711 |
}) |
| 1712 |
}) |
| 1713 |
|
| 1714 |
t.Run("preserves reconnect count for existing servers", func(t *testing.T) { |
| 1715 |
c := newTester(t) |
| 1716 |
srv1Inst := c.CreateServer(t, false) |
| 1717 |
t.Cleanup(func() { srv1Inst.Destroy(t) }) |
| 1718 |
srv2Inst := c.CreateServer(t, false) |
| 1719 |
t.Cleanup(func() { srv2Inst.Destroy(t) }) |
| 1720 |
|
| 1721 |
url1 := srv1Inst.Servers[0].URL |
| 1722 |
url2 := srv2Inst.Servers[0].URL |
| 1723 |
|
| 1724 |
reconnectCh := make(chan struct{}, 1) |
| 1725 |
|
| 1726 |
nc, err := nats.Connect( |
| 1727 |
url1+","+url2, |
| 1728 |
nats.ReconnectWait(50*time.Millisecond), |
| 1729 |
nats.MaxReconnects(10), |
| 1730 |
nats.DontRandomize(), |
| 1731 |
nats.ReconnectHandler(func(_ *nats.Conn) { |
| 1732 |
reconnectCh <- struct{}{} |
| 1733 |
}), |
| 1734 |
) |
| 1735 |
if err != nil { |
| 1736 |
t.Fatalf("Failed to connect: %v", err) |
| 1737 |
} |
| 1738 |
defer nc.Close() |
| 1739 |
|
| 1740 |
// Shut down srv2 so it fails when attempted during reconnect. |
| 1741 |
// Then ForceReconnect: client tries url2 (fails, Reconnects++), |
| 1742 |
// then url1 (succeeds, Reconnects=0). So url2 has non-zero count. |
| 1743 |
srv2Inst.StopServer(t, srv2Inst.Servers[0]) |
| 1744 |
|
| 1745 |
if err := nc.ForceReconnect(); err != nil { |
| 1746 |
t.Fatalf("Failed to force reconnect: %v", err) |
| 1747 |
} |
| 1748 |
|
| 1749 |
select { |
| 1750 |
case <-reconnectCh: |
| 1751 |
case <-time.After(2 * time.Second): |
| 1752 |
t.Fatal("Timed out waiting for reconnect") |
| 1753 |
} |
| 1754 |
|
| 1755 |
pool := nc.ServerPool() |
| 1756 |
var srv2Reconnects int |
| 1757 |
for _, s := range pool { |
| 1758 |
if s.URL.String() == url2 { |
| 1759 |
srv2Reconnects = s.Reconnects |
| 1760 |
break |
| 1761 |
} |
| 1762 |
} |
| 1763 |
if srv2Reconnects != 1 { |
| 1764 |
t.Fatal("Expected one reconnect for srv2") |
| 1765 |
} |
| 1766 |
|
| 1767 |
srv3Inst := c.CreateServer(t, false) |
| 1768 |
t.Cleanup(func() { srv3Inst.Destroy(t) }) |
| 1769 |
url3 := srv3Inst.Servers[0].URL |
| 1770 |
|
| 1771 |
if err := nc.SetServerPool([]string{url1, url2, url3}); err != nil { |
| 1772 |
t.Fatalf("Failed to set server pool: %v", err) |
| 1773 |
} |
| 1774 |
|
| 1775 |
pool = nc.ServerPool() |
| 1776 |
for _, s := range pool { |
| 1777 |
if s.URL.String() == url2 { |
| 1778 |
if s.Reconnects != srv2Reconnects { |
| 1779 |
t.Fatalf("Expected reconnect count %d to be preserved, got %d", srv2Reconnects, s.Reconnects) |
| 1780 |
} |
| 1781 |
return |
| 1782 |
} |
| 1783 |
} |
| 1784 |
t.Fatal("srv2 not found in pool after SetServerPool") |
| 1785 |
}) |
| 1786 |
|
| 1787 |
t.Run("server pool returns deep copy", func(t *testing.T) { |
| 1788 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 1789 |
pool := nc.ServerPool() |
| 1790 |
originalURL := pool[0].URL.String() |
| 1791 |
|
| 1792 |
pool[0].URL.Host = "modified:9999" |
| 1793 |
|
| 1794 |
pool2 := nc.ServerPool() |
| 1795 |
if pool2[0].URL.String() != originalURL { |
| 1796 |
t.Fatalf("Internal pool was modified: expected %s, got %s", originalURL, pool2[0].URL.String()) |
| 1797 |
} |
| 1798 |
}) |
| 1799 |
}) |
| 1800 |
} |