| 1 |
// Copyright 2013-2025 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 |
"fmt" |
| 18 |
"math/rand" |
| 19 |
"strconv" |
| 20 |
"sync" |
| 21 |
"sync/atomic" |
| 22 |
"testing" |
| 23 |
"time" |
| 24 |
|
| 25 |
"github.com/nats-io/nats.go" |
| 26 |
) |
| 27 |
|
| 28 |
func TestServerRestartReSliceIssue(t *testing.T) { |
| 29 |
srvA, srvB, optsA, optsB := runServers(t) |
| 30 |
defer srvA.Shutdown() |
| 31 |
|
| 32 |
urlA := fmt.Sprintf("nats://%s:%d/", optsA.Host, optsA.Port) |
| 33 |
urlB := fmt.Sprintf("nats://%s:%d/", optsB.Host, optsB.Port) |
| 34 |
|
| 35 |
// msg to send.. |
| 36 |
msg := []byte("Hello World") |
| 37 |
|
| 38 |
servers := []string{urlA, urlB} |
| 39 |
|
| 40 |
opts := nats.GetDefaultOptions() |
| 41 |
opts.Timeout = (5 * time.Second) |
| 42 |
opts.ReconnectWait = (50 * time.Millisecond) |
| 43 |
opts.MaxReconnect = 1000 |
| 44 |
|
| 45 |
numClients := 20 |
| 46 |
|
| 47 |
reconnects := int32(0) |
| 48 |
reconnectsDone := make(chan bool, numClients) |
| 49 |
opts.ReconnectedCB = func(nc *nats.Conn) { |
| 50 |
atomic.AddInt32(&reconnects, 1) |
| 51 |
reconnectsDone <- true |
| 52 |
} |
| 53 |
|
| 54 |
clients := make([]*nats.Conn, numClients) |
| 55 |
|
| 56 |
// Create 20 random clients. |
| 57 |
// Half connected to A and half to B.. |
| 58 |
for i := 0; i < numClients; i++ { |
| 59 |
opts.Url = servers[i%2] |
| 60 |
nc, err := opts.Connect() |
| 61 |
if err != nil { |
| 62 |
t.Fatalf("Failed to create connection: %v\n", err) |
| 63 |
} |
| 64 |
clients[i] = nc |
| 65 |
defer nc.Close() |
| 66 |
|
| 67 |
// Create 10 subscriptions each.. |
| 68 |
for x := 0; x < 10; x++ { |
| 69 |
subject := fmt.Sprintf("foo.%d", (rand.Int()%50)+1) |
| 70 |
nc.Subscribe(subject, func(m *nats.Msg) { |
| 71 |
// Just eat it.. |
| 72 |
}) |
| 73 |
} |
| 74 |
// Pick one subject to send to.. |
| 75 |
subject := fmt.Sprintf("foo.%d", (rand.Int()%50)+1) |
| 76 |
go func() { |
| 77 |
time.Sleep(10 * time.Millisecond) |
| 78 |
for i := 1; i <= 100; i++ { |
| 79 |
if err := nc.Publish(subject, msg); err != nil { |
| 80 |
return |
| 81 |
} |
| 82 |
if i%10 == 0 { |
| 83 |
time.Sleep(time.Millisecond) |
| 84 |
} |
| 85 |
} |
| 86 |
}() |
| 87 |
} |
| 88 |
|
| 89 |
// Wait for a short bit.. |
| 90 |
time.Sleep(20 * time.Millisecond) |
| 91 |
|
| 92 |
// Restart SrvB |
| 93 |
srvB.Shutdown() |
| 94 |
srvB = RunServer(optsB) |
| 95 |
defer srvB.Shutdown() |
| 96 |
|
| 97 |
// Check that all expected clients have reconnected |
| 98 |
done := false |
| 99 |
for i := 0; i < numClients/2 && !done; i++ { |
| 100 |
select { |
| 101 |
case <-reconnectsDone: |
| 102 |
done = true |
| 103 |
case <-time.After(3 * time.Second): |
| 104 |
t.Fatalf("Expected %d reconnects, got %d\n", numClients/2, reconnects) |
| 105 |
} |
| 106 |
} |
| 107 |
|
| 108 |
// Since srvB was restarted, its defer Shutdown() was last, so will |
| 109 |
// exectue first, which would cause clients that have reconnected to |
| 110 |
// it to try to reconnect (causing delays on Windows). So let's |
| 111 |
// explicitly close them here. |
| 112 |
// NOTE: With fix of NATS GO client (reconnect loop yields to Close()), |
| 113 |
// this change would not be required, however, it still speeeds up |
| 114 |
// the test, from more than 7s to less than one. |
| 115 |
for i := 0; i < numClients; i++ { |
| 116 |
nc := clients[i] |
| 117 |
nc.Close() |
| 118 |
} |
| 119 |
} |
| 120 |
|
| 121 |
// This will test queue subscriber semantics across a cluster in the presence |
| 122 |
// of server restarts. |
| 123 |
func TestServerRestartAndQueueSubs(t *testing.T) { |
| 124 |
srvA, srvB, optsA, optsB := runServers(t) |
| 125 |
defer srvA.Shutdown() |
| 126 |
defer srvB.Shutdown() |
| 127 |
|
| 128 |
urlA := fmt.Sprintf("nats://%s:%d/", optsA.Host, optsA.Port) |
| 129 |
urlB := fmt.Sprintf("nats://%s:%d/", optsB.Host, optsB.Port) |
| 130 |
|
| 131 |
// Client options |
| 132 |
opts := nats.GetDefaultOptions() |
| 133 |
opts.Timeout = 5 * time.Second |
| 134 |
opts.ReconnectWait = 20 * time.Millisecond |
| 135 |
opts.MaxReconnect = 1000 |
| 136 |
opts.NoRandomize = true |
| 137 |
|
| 138 |
// Allow us to block on a reconnect completion. |
| 139 |
reconnectsDone := make(chan bool) |
| 140 |
opts.ReconnectedCB = func(nc *nats.Conn) { |
| 141 |
reconnectsDone <- true |
| 142 |
} |
| 143 |
|
| 144 |
// Helper to wait on a reconnect. |
| 145 |
waitOnReconnect := func() { |
| 146 |
t.Helper() |
| 147 |
select { |
| 148 |
case <-reconnectsDone: |
| 149 |
case <-time.After(2 * time.Second): |
| 150 |
t.Fatalf("Expected a reconnect, timedout!\n") |
| 151 |
} |
| 152 |
} |
| 153 |
|
| 154 |
// Create two clients.. |
| 155 |
opts.Servers = []string{urlA, urlB} |
| 156 |
c1, err := opts.Connect() |
| 157 |
if err != nil { |
| 158 |
t.Fatalf("Failed to create connection for c1: %v\n", err) |
| 159 |
} |
| 160 |
defer c1.Close() |
| 161 |
|
| 162 |
opts.Servers = []string{urlB, urlA} |
| 163 |
c2, err := opts.Connect() |
| 164 |
if err != nil { |
| 165 |
t.Fatalf("Failed to create connection for c2: %v\n", err) |
| 166 |
} |
| 167 |
defer c2.Close() |
| 168 |
|
| 169 |
// Flusher helper function. |
| 170 |
flush := func() { |
| 171 |
// Wait for processing. |
| 172 |
c1.Flush() |
| 173 |
c2.Flush() |
| 174 |
// Wait for a short bit for cluster propagation. |
| 175 |
time.Sleep(50 * time.Millisecond) |
| 176 |
} |
| 177 |
|
| 178 |
// To hold queue results. |
| 179 |
results := make(map[int]int) |
| 180 |
var mu sync.Mutex |
| 181 |
|
| 182 |
// This corresponds to the subsriptions below. |
| 183 |
const ExpectedMsgCount = 3 |
| 184 |
|
| 185 |
// Make sure we got what we needed, 1 msg only and all seqnos accounted for.. |
| 186 |
checkResults := func(numSent int) { |
| 187 |
mu.Lock() |
| 188 |
defer mu.Unlock() |
| 189 |
|
| 190 |
for i := 0; i < numSent; i++ { |
| 191 |
if results[i] != ExpectedMsgCount { |
| 192 |
t.Fatalf("Received incorrect number of messages, [%d] vs [%d] for seq: %d\n", results[i], ExpectedMsgCount, i) |
| 193 |
} |
| 194 |
} |
| 195 |
|
| 196 |
// Auto reset results map |
| 197 |
results = make(map[int]int) |
| 198 |
} |
| 199 |
|
| 200 |
subj := "foo.bar" |
| 201 |
qgroup := "workers" |
| 202 |
|
| 203 |
cb := func(msg *nats.Msg) { |
| 204 |
mu.Lock() |
| 205 |
defer mu.Unlock() |
| 206 |
seqno, _ := strconv.Atoi(string(msg.Data)) |
| 207 |
results[seqno] = results[seqno] + 1 |
| 208 |
} |
| 209 |
|
| 210 |
// Create queue subscribers |
| 211 |
c1.QueueSubscribe(subj, qgroup, cb) |
| 212 |
c2.QueueSubscribe(subj, qgroup, cb) |
| 213 |
|
| 214 |
// Do a wildcard subscription. |
| 215 |
c1.Subscribe("foo.*", cb) |
| 216 |
c2.Subscribe("foo.*", cb) |
| 217 |
|
| 218 |
// Wait for processing. |
| 219 |
flush() |
| 220 |
|
| 221 |
sendAndCheckMsgs := func(numToSend int) { |
| 222 |
for i := 0; i < numToSend; i++ { |
| 223 |
if i%2 == 0 { |
| 224 |
c1.Publish(subj, []byte(strconv.Itoa(i))) |
| 225 |
} else { |
| 226 |
c2.Publish(subj, []byte(strconv.Itoa(i))) |
| 227 |
} |
| 228 |
} |
| 229 |
// Wait for processing. |
| 230 |
flush() |
| 231 |
// Check Results |
| 232 |
checkResults(numToSend) |
| 233 |
} |
| 234 |
|
| 235 |
//////////////////////////////////////////////////////////////////////////// |
| 236 |
// Base Test |
| 237 |
//////////////////////////////////////////////////////////////////////////// |
| 238 |
|
| 239 |
// Make sure subscriptions are propagated in the cluster |
| 240 |
if err := checkExpectedSubs(4, srvA, srvB); err != nil { |
| 241 |
t.Fatalf("%v", err) |
| 242 |
} |
| 243 |
|
| 244 |
// Now send 10 messages, from each client.. |
| 245 |
sendAndCheckMsgs(10) |
| 246 |
|
| 247 |
//////////////////////////////////////////////////////////////////////////// |
| 248 |
// Now restart SrvA and srvB, re-run test |
| 249 |
//////////////////////////////////////////////////////////////////////////// |
| 250 |
|
| 251 |
srvA.Shutdown() |
| 252 |
// Wait for client on A to reconnect to B. |
| 253 |
waitOnReconnect() |
| 254 |
|
| 255 |
srvA = RunServer(optsA) |
| 256 |
defer srvA.Shutdown() |
| 257 |
|
| 258 |
srvB.Shutdown() |
| 259 |
// Now both clients should reconnect to A. |
| 260 |
waitOnReconnect() |
| 261 |
waitOnReconnect() |
| 262 |
|
| 263 |
srvB = RunServer(optsB) |
| 264 |
defer srvB.Shutdown() |
| 265 |
|
| 266 |
// Make sure the cluster is reformed |
| 267 |
checkClusterFormed(t, srvA, srvB) |
| 268 |
|
| 269 |
// Make sure subscriptions are propagated in the cluster |
| 270 |
// Clients will be connected to srvA, so that will be 4, |
| 271 |
// but srvB will only have 2 now since we coaelsce. |
| 272 |
if err := checkExpectedSubs(4, srvA); err != nil { |
| 273 |
t.Fatalf("%v", err) |
| 274 |
} |
| 275 |
if err := checkExpectedSubs(2, srvB); err != nil { |
| 276 |
t.Fatalf("%v", err) |
| 277 |
} |
| 278 |
|
| 279 |
// Now send another 10 messages, from each client.. |
| 280 |
sendAndCheckMsgs(10) |
| 281 |
|
| 282 |
// Since servers are restarted after all client's close defer calls, |
| 283 |
// their defer Shutdown() are last, and so will be executed first, |
| 284 |
// which would cause clients to try to reconnect on exit, causing |
| 285 |
// delays on Windows. So let's explicitly close them here. |
| 286 |
c1.Close() |
| 287 |
c2.Close() |
| 288 |
} |
| 289 |
|
| 290 |
// This will test request semantics across a route |
| 291 |
func TestRequestsAcrossRoutes(t *testing.T) { |
| 292 |
srvA, srvB, optsA, optsB := runServers(t) |
| 293 |
defer srvA.Shutdown() |
| 294 |
defer srvB.Shutdown() |
| 295 |
|
| 296 |
urlA := fmt.Sprintf("nats://%s:%d/", optsA.Host, optsA.Port) |
| 297 |
urlB := fmt.Sprintf("nats://%s:%d/", optsB.Host, optsB.Port) |
| 298 |
|
| 299 |
nc1, err := nats.Connect(urlA) |
| 300 |
if err != nil { |
| 301 |
t.Fatalf("Failed to create connection for nc1: %v\n", err) |
| 302 |
} |
| 303 |
defer nc1.Close() |
| 304 |
|
| 305 |
nc2, err := nats.Connect(urlB) |
| 306 |
if err != nil { |
| 307 |
t.Fatalf("Failed to create connection for nc2: %v\n", err) |
| 308 |
} |
| 309 |
defer nc2.Close() |
| 310 |
|
| 311 |
response := []byte("I will help you") |
| 312 |
|
| 313 |
// Connect responder to srvA |
| 314 |
nc1.Subscribe("foo-req", func(m *nats.Msg) { |
| 315 |
nc1.Publish(m.Reply, response) |
| 316 |
}) |
| 317 |
// Make sure the route and the subscription are propagated. |
| 318 |
nc1.Flush() |
| 319 |
|
| 320 |
if err = checkExpectedSubs(1, srvA, srvB); err != nil { |
| 321 |
t.Fatal(err.Error()) |
| 322 |
} |
| 323 |
|
| 324 |
for i := 0; i < 100; i++ { |
| 325 |
if _, err = nc2.Request("foo-req", []byte(strconv.Itoa(i)), 250*time.Millisecond); err != nil { |
| 326 |
t.Fatalf("Received an error on Request test [%d]: %s", i, err) |
| 327 |
} |
| 328 |
} |
| 329 |
} |
| 330 |
|
| 331 |
// This will test request semantics across a route to queues |
| 332 |
func TestRequestsAcrossRoutesToQueues(t *testing.T) { |
| 333 |
srvA, srvB, optsA, optsB := runServers(t) |
| 334 |
defer srvA.Shutdown() |
| 335 |
defer srvB.Shutdown() |
| 336 |
|
| 337 |
urlA := fmt.Sprintf("nats://%s:%d/", optsA.Host, optsA.Port) |
| 338 |
urlB := fmt.Sprintf("nats://%s:%d/", optsB.Host, optsB.Port) |
| 339 |
|
| 340 |
nc1, err := nats.Connect(urlA) |
| 341 |
if err != nil { |
| 342 |
t.Fatalf("Failed to create connection for nc1: %v\n", err) |
| 343 |
} |
| 344 |
defer nc1.Close() |
| 345 |
|
| 346 |
nc2, err := nats.Connect(urlB) |
| 347 |
if err != nil { |
| 348 |
t.Fatalf("Failed to create connection for nc2: %v\n", err) |
| 349 |
} |
| 350 |
defer nc2.Close() |
| 351 |
|
| 352 |
response := []byte("I will help you") |
| 353 |
|
| 354 |
// Connect one responder to srvA |
| 355 |
nc1.QueueSubscribe("foo-req", "booboo", func(m *nats.Msg) { |
| 356 |
nc1.Publish(m.Reply, response) |
| 357 |
}) |
| 358 |
// Make sure the route and the subscription are propagated. |
| 359 |
nc1.Flush() |
| 360 |
|
| 361 |
// Connect the other responder to srvB |
| 362 |
nc2.QueueSubscribe("foo-req", "booboo", func(m *nats.Msg) { |
| 363 |
nc2.Publish(m.Reply, response) |
| 364 |
}) |
| 365 |
|
| 366 |
if err = checkExpectedSubs(2, srvA, srvB); err != nil { |
| 367 |
t.Fatal(err.Error()) |
| 368 |
} |
| 369 |
|
| 370 |
for i := 0; i < 100; i++ { |
| 371 |
if _, err = nc2.Request("foo-req", []byte(strconv.Itoa(i)), 500*time.Millisecond); err != nil { |
| 372 |
t.Fatalf("Received an error on Request test [%d]: %s", i, err) |
| 373 |
} |
| 374 |
} |
| 375 |
|
| 376 |
for i := 0; i < 100; i++ { |
| 377 |
if _, err = nc1.Request("foo-req", []byte(strconv.Itoa(i)), 500*time.Millisecond); err != nil { |
| 378 |
t.Fatalf("Received an error on Request test [%d]: %s", i, err) |
| 379 |
} |
| 380 |
} |
| 381 |
} |
| 382 |
|
| 383 |
// This is in response to Issue #1144 |
| 384 |
// https://github.com/nats-io/nats-server/issues/1144 |
| 385 |
func TestQueueDistributionAcrossRoutes(t *testing.T) { |
| 386 |
srvA, srvB, _, _ := runServers(t) |
| 387 |
defer srvA.Shutdown() |
| 388 |
defer srvB.Shutdown() |
| 389 |
|
| 390 |
checkClusterFormed(t, srvA, srvB) |
| 391 |
|
| 392 |
urlA := srvA.ClientURL() |
| 393 |
urlB := srvB.ClientURL() |
| 394 |
|
| 395 |
nc1, err := nats.Connect(urlA) |
| 396 |
if err != nil { |
| 397 |
t.Fatalf("Failed to create connection for nc1: %v\n", err) |
| 398 |
} |
| 399 |
defer nc1.Close() |
| 400 |
|
| 401 |
nc2, err := nats.Connect(urlB) |
| 402 |
if err != nil { |
| 403 |
t.Fatalf("Failed to create connection for nc2: %v\n", err) |
| 404 |
} |
| 405 |
defer nc2.Close() |
| 406 |
|
| 407 |
var qsubs []*nats.Subscription |
| 408 |
|
| 409 |
// Connect queue subscriptions as mentioned in the issue. 2(A) - 6(B) - 4(A) |
| 410 |
for i := 0; i < 2; i++ { |
| 411 |
sub, _ := nc1.QueueSubscribeSync("foo", "bar") |
| 412 |
qsubs = append(qsubs, sub) |
| 413 |
} |
| 414 |
nc1.Flush() |
| 415 |
for i := 0; i < 6; i++ { |
| 416 |
sub, _ := nc2.QueueSubscribeSync("foo", "bar") |
| 417 |
qsubs = append(qsubs, sub) |
| 418 |
} |
| 419 |
nc2.Flush() |
| 420 |
for i := 0; i < 4; i++ { |
| 421 |
sub, _ := nc1.QueueSubscribeSync("foo", "bar") |
| 422 |
qsubs = append(qsubs, sub) |
| 423 |
} |
| 424 |
nc1.Flush() |
| 425 |
|
| 426 |
if err := checkExpectedSubs(7, srvA, srvB); err != nil { |
| 427 |
t.Fatalf("%v", err) |
| 428 |
} |
| 429 |
|
| 430 |
send := 10000 |
| 431 |
for i := 0; i < send; i++ { |
| 432 |
nc2.Publish("foo", nil) |
| 433 |
} |
| 434 |
nc2.Flush() |
| 435 |
|
| 436 |
tp := func() int { |
| 437 |
var total int |
| 438 |
for i := 0; i < len(qsubs); i++ { |
| 439 |
pending, _, _ := qsubs[i].Pending() |
| 440 |
total += pending |
| 441 |
} |
| 442 |
return total |
| 443 |
} |
| 444 |
|
| 445 |
checkFor(t, time.Second, 10*time.Millisecond, func() error { |
| 446 |
if total := tp(); total != send { |
| 447 |
return fmt.Errorf("Number of total received %d", total) |
| 448 |
} |
| 449 |
return nil |
| 450 |
}) |
| 451 |
|
| 452 |
// The bug is essentially that when we deliver across a route, we |
| 453 |
// prefer locals, but if we randomize to a block of bounce backs, then |
| 454 |
// we walk to the end and find the same local for all the remote options. |
| 455 |
// So what you will see in this case is a large value at #9 (2+6, next one local). |
| 456 |
|
| 457 |
avg := send / len(qsubs) |
| 458 |
for i := 0; i < len(qsubs); i++ { |
| 459 |
total, _, _ := qsubs[i].Pending() |
| 460 |
if total > avg+(avg*3/10) { |
| 461 |
if i == 8 { |
| 462 |
t.Fatalf("Qsub in 8th position gets majority of the messages (prior 6 spots) in this test") |
| 463 |
} |
| 464 |
t.Fatalf("Received too high, %d vs %d", total, avg) |
| 465 |
} |
| 466 |
} |
| 467 |
} |