| 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 |
"bytes" |
| 18 |
"context" |
| 19 |
"errors" |
| 20 |
"fmt" |
| 21 |
"math" |
| 22 |
"regexp" |
| 23 |
"strings" |
| 24 |
"sync" |
| 25 |
"sync/atomic" |
| 26 |
"testing" |
| 27 |
"time" |
| 28 |
|
| 29 |
"github.com/nats-io/nats.go" |
| 30 |
testservice "github.com/synadia-io/orbit.go/ntf-client" |
| 31 |
) |
| 32 |
|
| 33 |
func TestCloseLeakingGoRoutines(t *testing.T) { |
| 34 |
// Goroutine baseline must be captured BEFORE the connection is created; |
| 35 |
// otherwise the conn's own goroutines are in the base and Close() trivially |
| 36 |
// satisfies the leak check (they all exit, delta is non-positive). |
| 37 |
c := newTester(t) |
| 38 |
inst := c.CreateServer(t, false) |
| 39 |
t.Cleanup(func() { inst.Destroy(t) }) |
| 40 |
|
| 41 |
base := getStableNumGoroutine(t) |
| 42 |
|
| 43 |
nc, err := nats.Connect(inst.Servers[0].URL) |
| 44 |
if err != nil { |
| 45 |
t.Fatalf("nats.Connect: %v", err) |
| 46 |
} |
| 47 |
nc.Flush() |
| 48 |
nc.Close() |
| 49 |
|
| 50 |
checkNoGoroutineLeak(t, base, "Close()") |
| 51 |
|
| 52 |
nc.Close() |
| 53 |
} |
| 54 |
|
| 55 |
func TestLeakingGoRoutinesOnFailedConnect(t *testing.T) { |
| 56 |
base := getStableNumGoroutine(t) |
| 57 |
|
| 58 |
// Use a port that is guaranteed to fail (privileged + no listener). |
| 59 |
// Cannot use nats.DefaultURL here because in the host-side dev workflow |
| 60 |
// the tester publishes its own management server on localhost:4222. |
| 61 |
nc, err := nats.Connect("nats://127.0.0.1:1") |
| 62 |
if err == nil { |
| 63 |
nc.Close() |
| 64 |
t.Fatalf("Expected failure to connect") |
| 65 |
} |
| 66 |
|
| 67 |
checkNoGoroutineLeak(t, base, "failed connect") |
| 68 |
} |
| 69 |
|
| 70 |
func TestTLSConnectionStateNonTLS(t *testing.T) { |
| 71 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 72 |
_, err := nc.TLSConnectionState() |
| 73 |
if err != nats.ErrConnectionNotTLS { |
| 74 |
t.Fatalf("Expected a not tls error, got: %v", err) |
| 75 |
} |
| 76 |
}) |
| 77 |
} |
| 78 |
|
| 79 |
func TestConnectedServer(t *testing.T) { |
| 80 |
withServerInstance(t, func(t *testing.T, nc *nats.Conn, inst *testservice.Instance) { |
| 81 |
wantURL := inst.Servers[0].URL |
| 82 |
if u := nc.ConnectedUrl(); u == "" || u != wantURL { |
| 83 |
t.Fatalf("Unexpected connected URL of %s (want %s)", u, wantURL) |
| 84 |
} |
| 85 |
if id := nc.ConnectedServerId(); id == "" { |
| 86 |
t.Fatalf("Expected a connected server id, got %s", id) |
| 87 |
} |
| 88 |
if name := nc.ConnectedServerName(); name == "" { |
| 89 |
t.Fatalf("Expected a connected server name, got %s", name) |
| 90 |
} |
| 91 |
if jsEnabled, _ := nc.ConnectedServerJetStream(); jsEnabled { |
| 92 |
t.Fatalf("Expected JetStream to be disabled") |
| 93 |
} |
| 94 |
if nc.IsSystemAccount() { |
| 95 |
t.Fatalf("Expected non-system account") |
| 96 |
} |
| 97 |
|
| 98 |
nc.Close() |
| 99 |
if u := nc.ConnectedUrl(); u != "" { |
| 100 |
t.Fatalf("Expected a nil connected URL, got %s", u) |
| 101 |
} |
| 102 |
if id := nc.ConnectedServerId(); id != "" { |
| 103 |
t.Fatalf("Expected a nil connect server, got %s", id) |
| 104 |
} |
| 105 |
if name := nc.ConnectedServerName(); name != "" { |
| 106 |
t.Fatalf("Expected a nil connect server name, got %s", name) |
| 107 |
} |
| 108 |
if jsEnabled, _ := nc.ConnectedServerJetStream(); jsEnabled { |
| 109 |
t.Fatalf("Expected JetStream to be disabled after close") |
| 110 |
} |
| 111 |
if nc.IsSystemAccount() { |
| 112 |
t.Fatalf("Expected non-system account after close") |
| 113 |
} |
| 114 |
}) |
| 115 |
} |
| 116 |
|
| 117 |
func TestConnectedClusterName(t *testing.T) { |
| 118 |
c := newTester(t) |
| 119 |
inst := c.CreateCluster(t, 3, false) |
| 120 |
t.Cleanup(func() { inst.Destroy(t) }) |
| 121 |
|
| 122 |
want := inst.Servers[0].Cluster |
| 123 |
if want == "" { |
| 124 |
t.Fatal("Expected the tester to report a cluster name") |
| 125 |
} |
| 126 |
|
| 127 |
nc := dialInstance(t, inst) |
| 128 |
if got := nc.ConnectedClusterName(); got != want { |
| 129 |
t.Fatalf("Expected cluster name %q, got %q", want, got) |
| 130 |
} |
| 131 |
|
| 132 |
nc.Close() |
| 133 |
if got := nc.ConnectedClusterName(); got != "" { |
| 134 |
t.Fatalf("Expected an empty cluster name after close, got %q", got) |
| 135 |
} |
| 136 |
} |
| 137 |
|
| 138 |
func TestConnectedDomain(t *testing.T) { |
| 139 |
withJSServer(t, func(t *testing.T, nc *nats.Conn) { |
| 140 |
if got := nc.ConnectedDomain(); got != "ABC" { |
| 141 |
t.Fatalf("Expected domain %q, got %q", "ABC", got) |
| 142 |
} |
| 143 |
|
| 144 |
nc.Close() |
| 145 |
if got := nc.ConnectedDomain(); got != "" { |
| 146 |
t.Fatalf("Expected an empty domain after close, got %q", got) |
| 147 |
} |
| 148 |
}, testservice.WithJetStream(`domain: ABC`)) |
| 149 |
|
| 150 |
t.Run("no domain configured", func(t *testing.T) { |
| 151 |
withJSServer(t, func(t *testing.T, nc *nats.Conn) { |
| 152 |
if got := nc.ConnectedDomain(); got != "" { |
| 153 |
t.Fatalf("Expected an empty domain, got %q", got) |
| 154 |
} |
| 155 |
}) |
| 156 |
}) |
| 157 |
} |
| 158 |
|
| 159 |
func TestConnectedServerJetStream(t *testing.T) { |
| 160 |
c := newTester(t) |
| 161 |
inst := c.CreateServer(t, true) |
| 162 |
t.Cleanup(func() { inst.Destroy(t) }) |
| 163 |
|
| 164 |
nc := dialInstance(t, inst) |
| 165 |
jsEnabled, jsApiLevel := nc.ConnectedServerJetStream() |
| 166 |
if !jsEnabled { |
| 167 |
t.Fatalf("Expected JetStream to be enabled") |
| 168 |
} |
| 169 |
if jsApiLevel == 0 { |
| 170 |
t.Fatalf("Expected non-zero JetStream API level") |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
func TestIsSystemAccount(t *testing.T) { |
| 175 |
const accountsSnippet = ` |
| 176 |
accounts: { |
| 177 |
SYS: { |
| 178 |
users: [ {user: "sys", password: "pass"} ] |
| 179 |
} |
| 180 |
APP: { |
| 181 |
users: [ {user: "app", password: "pass"} ] |
| 182 |
} |
| 183 |
}` |
| 184 |
|
| 185 |
c := newTester(t) |
| 186 |
inst := c.CreateServer(t, false, |
| 187 |
testservice.WithAccounts(accountsSnippet), |
| 188 |
testservice.WithAuthorization("# auth required, no no_auth_user"), |
| 189 |
testservice.WithSystemAccount("system_account: SYS"), |
| 190 |
) |
| 191 |
t.Cleanup(func() { inst.Destroy(t) }) |
| 192 |
|
| 193 |
nc := dialInstance(t, inst, nats.UserInfo("sys", "pass")) |
| 194 |
|
| 195 |
// IsSystemAccount is sent by the server in an async INFO after connect. |
| 196 |
checkFor(t, time.Second, 15*time.Millisecond, func() error { |
| 197 |
if !nc.IsSystemAccount() { |
| 198 |
return fmt.Errorf("expected system account") |
| 199 |
} |
| 200 |
return nil |
| 201 |
}) |
| 202 |
|
| 203 |
nc2 := dialInstance(t, inst, nats.UserInfo("app", "pass")) |
| 204 |
if nc2.IsSystemAccount() { |
| 205 |
t.Fatalf("Expected non-system account") |
| 206 |
} |
| 207 |
} |
| 208 |
|
| 209 |
func TestMultipleClose(t *testing.T) { |
| 210 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 211 |
var wg sync.WaitGroup |
| 212 |
for i := 0; i < 10; i++ { |
| 213 |
wg.Add(1) |
| 214 |
go func() { |
| 215 |
nc.Close() |
| 216 |
wg.Done() |
| 217 |
}() |
| 218 |
} |
| 219 |
wg.Wait() |
| 220 |
}) |
| 221 |
} |
| 222 |
|
| 223 |
func TestBadOptionTimeoutConnect(t *testing.T) { |
| 224 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 225 |
opts := nats.GetDefaultOptions() |
| 226 |
opts.Timeout = -1 |
| 227 |
opts.Url = inst.Servers[0].URL |
| 228 |
|
| 229 |
_, err := opts.Connect() |
| 230 |
if err == nil { |
| 231 |
t.Fatal("Expected an error") |
| 232 |
} |
| 233 |
if !strings.Contains(err.Error(), "invalid") { |
| 234 |
t.Fatalf("Expected a ErrNoServers error: Got %v", err) |
| 235 |
} |
| 236 |
}) |
| 237 |
} |
| 238 |
|
| 239 |
func TestSimplePublish(t *testing.T) { |
| 240 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 241 |
if err := nc.Publish("foo", []byte("Hello World")); err != nil { |
| 242 |
t.Fatal("Failed to publish string message: ", err) |
| 243 |
} |
| 244 |
}) |
| 245 |
} |
| 246 |
|
| 247 |
func TestSimplePublishNoData(t *testing.T) { |
| 248 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 249 |
if err := nc.Publish("foo", nil); err != nil { |
| 250 |
t.Fatal("Failed to publish empty message: ", err) |
| 251 |
} |
| 252 |
}) |
| 253 |
} |
| 254 |
|
| 255 |
func TestPublishDoesNotFailOnSlowConsumer(t *testing.T) { |
| 256 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 257 |
nc.SetErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, _ error) {}) |
| 258 |
|
| 259 |
sub, err := nc.SubscribeSync("foo") |
| 260 |
if err != nil { |
| 261 |
t.Fatalf("Unable to create subscription: %v", err) |
| 262 |
} |
| 263 |
if err := sub.SetPendingLimits(1, 1000); err != nil { |
| 264 |
t.Fatalf("Unable to set pending limits: %v", err) |
| 265 |
} |
| 266 |
|
| 267 |
var pubErr error |
| 268 |
msg := []byte("Hello") |
| 269 |
for i := 0; i < 10; i++ { |
| 270 |
pubErr = nc.Publish("foo", msg) |
| 271 |
if pubErr != nil { |
| 272 |
break |
| 273 |
} |
| 274 |
nc.Flush() |
| 275 |
} |
| 276 |
if pubErr != nil { |
| 277 |
t.Fatalf("Publish() should not fail because of slow consumer. Got '%v'", pubErr) |
| 278 |
} |
| 279 |
}) |
| 280 |
} |
| 281 |
|
| 282 |
func TestAsyncSubscribe(t *testing.T) { |
| 283 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 284 |
omsg := []byte("Hello World") |
| 285 |
ch := make(chan bool) |
| 286 |
|
| 287 |
if _, err := nc.Subscribe("foo", nil); err == nil { |
| 288 |
t.Fatal("Creating subscription without callback should have failed") |
| 289 |
} |
| 290 |
|
| 291 |
_, err := nc.Subscribe("foo", func(m *nats.Msg) { |
| 292 |
if !bytes.Equal(m.Data, omsg) { |
| 293 |
t.Fatal("Message received does not match") |
| 294 |
} |
| 295 |
if m.Sub == nil { |
| 296 |
t.Fatal("Callback does not have a valid Subscription") |
| 297 |
} |
| 298 |
ch <- true |
| 299 |
}) |
| 300 |
if err != nil { |
| 301 |
t.Fatal("Failed to subscribe: ", err) |
| 302 |
} |
| 303 |
nc.Publish("foo", omsg) |
| 304 |
if e := Wait(ch); e != nil { |
| 305 |
t.Fatal("Message not received for subscription") |
| 306 |
} |
| 307 |
}) |
| 308 |
} |
| 309 |
|
| 310 |
func TestAsyncSubscribeRoutineLeakOnUnsubscribe(t *testing.T) { |
| 311 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 312 |
ch := make(chan bool) |
| 313 |
|
| 314 |
base := getStableNumGoroutine(t) |
| 315 |
|
| 316 |
sub, err := nc.Subscribe("foo", func(m *nats.Msg) { ch <- true }) |
| 317 |
if err != nil { |
| 318 |
t.Fatal("Failed to subscribe: ", err) |
| 319 |
} |
| 320 |
|
| 321 |
nc.Publish("foo", []byte("hello")) |
| 322 |
|
| 323 |
if err := Wait(ch); err != nil { |
| 324 |
t.Fatal("Failed to receive message") |
| 325 |
} |
| 326 |
|
| 327 |
time.Sleep(200 * time.Millisecond) |
| 328 |
sub.Unsubscribe() |
| 329 |
checkNoGoroutineLeak(t, base, "Unsubscribe()") |
| 330 |
}) |
| 331 |
} |
| 332 |
|
| 333 |
func TestAsyncSubscribeRoutineLeakOnClose(t *testing.T) { |
| 334 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 335 |
ch := make(chan bool) |
| 336 |
|
| 337 |
// Take the base BEFORE the connection is created so the connection's |
| 338 |
// goroutines count toward the leak delta. |
| 339 |
base := getStableNumGoroutine(t) |
| 340 |
|
| 341 |
nc := dialInstance(t, inst) |
| 342 |
|
| 343 |
_, err := nc.Subscribe("foo", func(m *nats.Msg) { ch <- true }) |
| 344 |
if err != nil { |
| 345 |
t.Fatal("Failed to subscribe: ", err) |
| 346 |
} |
| 347 |
nc.Publish("foo", []byte("hello")) |
| 348 |
if err := Wait(ch); err != nil { |
| 349 |
t.Fatal("Failed to receive message") |
| 350 |
} |
| 351 |
|
| 352 |
time.Sleep(200 * time.Millisecond) |
| 353 |
nc.Close() |
| 354 |
checkNoGoroutineLeak(t, base, "Close()") |
| 355 |
}) |
| 356 |
} |
| 357 |
|
| 358 |
func TestSyncSubscribe(t *testing.T) { |
| 359 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 360 |
sub, err := nc.SubscribeSync("foo") |
| 361 |
if err != nil { |
| 362 |
t.Fatal("Failed to subscribe: ", err) |
| 363 |
} |
| 364 |
omsg := []byte("Hello World") |
| 365 |
nc.Publish("foo", omsg) |
| 366 |
msg, err := sub.NextMsg(1 * time.Second) |
| 367 |
if err != nil || !bytes.Equal(msg.Data, omsg) { |
| 368 |
t.Fatal("Message received does not match") |
| 369 |
} |
| 370 |
}) |
| 371 |
} |
| 372 |
|
| 373 |
func TestPubSubWithReply(t *testing.T) { |
| 374 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 375 |
sub, err := nc.SubscribeSync("foo") |
| 376 |
if err != nil { |
| 377 |
t.Fatal("Failed to subscribe: ", err) |
| 378 |
} |
| 379 |
omsg := []byte("Hello World") |
| 380 |
nc.PublishMsg(&nats.Msg{Subject: "foo", Reply: "bar", Data: omsg}) |
| 381 |
msg, err := sub.NextMsg(10 * time.Second) |
| 382 |
if err != nil || !bytes.Equal(msg.Data, omsg) { |
| 383 |
t.Fatal("Message received does not match") |
| 384 |
} |
| 385 |
}) |
| 386 |
} |
| 387 |
|
| 388 |
func TestMsgRespond(t *testing.T) { |
| 389 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 390 |
m := &nats.Msg{} |
| 391 |
if err := m.Respond(nil); err != nats.ErrMsgNotBound { |
| 392 |
t.Fatal("Expected ErrMsgNotBound error") |
| 393 |
} |
| 394 |
|
| 395 |
sub, err := nc.Subscribe("req", func(msg *nats.Msg) { |
| 396 |
msg.Respond([]byte("42")) |
| 397 |
}) |
| 398 |
if err != nil { |
| 399 |
t.Fatal("Failed to subscribe: ", err) |
| 400 |
} |
| 401 |
|
| 402 |
m.Sub = sub |
| 403 |
if err := m.Respond(nil); err != nats.ErrMsgNoReply { |
| 404 |
t.Fatal("Expected ErrMsgNoReply error") |
| 405 |
} |
| 406 |
|
| 407 |
response, err := nc.Request("req", []byte("help"), 50*time.Millisecond) |
| 408 |
if err != nil { |
| 409 |
t.Fatal("Request Failed: ", err) |
| 410 |
} |
| 411 |
if string(response.Data) != "42" { |
| 412 |
t.Fatalf("Expected '42', got %q", response.Data) |
| 413 |
} |
| 414 |
}) |
| 415 |
} |
| 416 |
|
| 417 |
func TestFlush(t *testing.T) { |
| 418 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 419 |
omsg := []byte("Hello World") |
| 420 |
for i := 0; i < 10000; i++ { |
| 421 |
nc.Publish("flush", omsg) |
| 422 |
} |
| 423 |
if err := nc.FlushTimeout(0); err == nil { |
| 424 |
t.Fatal("Calling FlushTimeout() with invalid timeout should fail") |
| 425 |
} |
| 426 |
if err := nc.Flush(); err != nil { |
| 427 |
t.Fatalf("Received error from flush: %s", err) |
| 428 |
} |
| 429 |
if nb, _ := nc.Buffered(); nb > 0 { |
| 430 |
t.Fatalf("Outbound buffer not empty: %d bytes", nb) |
| 431 |
} |
| 432 |
|
| 433 |
nc.Close() |
| 434 |
if _, err := nc.Buffered(); err == nil { |
| 435 |
t.Fatal("Calling Buffered() on closed connection should fail") |
| 436 |
} |
| 437 |
}) |
| 438 |
} |
| 439 |
|
| 440 |
func TestQueueSubscriber(t *testing.T) { |
| 441 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 442 |
s1, _ := nc.QueueSubscribeSync("foo", "bar") |
| 443 |
s2, _ := nc.QueueSubscribeSync("foo", "bar") |
| 444 |
omsg := []byte("Hello World") |
| 445 |
nc.Publish("foo", omsg) |
| 446 |
nc.Flush() |
| 447 |
r1, _, _ := s1.Pending() |
| 448 |
r2, _, _ := s2.Pending() |
| 449 |
if (r1 + r2) != 1 { |
| 450 |
t.Fatal("Received too many messages for multiple queue subscribers") |
| 451 |
} |
| 452 |
s1.NextMsg(time.Second) |
| 453 |
s2.NextMsg(time.Second) |
| 454 |
|
| 455 |
total := 1000 |
| 456 |
for i := 0; i < total; i++ { |
| 457 |
nc.Publish("foo", omsg) |
| 458 |
} |
| 459 |
nc.Flush() |
| 460 |
v := uint(float32(total) * 0.15) |
| 461 |
r1, _, _ = s1.Pending() |
| 462 |
r2, _, _ = s2.Pending() |
| 463 |
if r1+r2 != total { |
| 464 |
t.Fatalf("Incorrect number of messages: %d vs %d", (r1 + r2), total) |
| 465 |
} |
| 466 |
expected := total / 2 |
| 467 |
d1 := uint(math.Abs(float64(expected - r1))) |
| 468 |
d2 := uint(math.Abs(float64(expected - r2))) |
| 469 |
if d1 > v || d2 > v { |
| 470 |
t.Fatalf("Too much variance in totals: %d, %d > %d", d1, d2, v) |
| 471 |
} |
| 472 |
}) |
| 473 |
} |
| 474 |
|
| 475 |
func TestReplyArg(t *testing.T) { |
| 476 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 477 |
ch := make(chan bool) |
| 478 |
replyExpected := "bar" |
| 479 |
|
| 480 |
nc.Subscribe("foo", func(m *nats.Msg) { |
| 481 |
if m.Reply != replyExpected { |
| 482 |
t.Fatalf("Did not receive correct reply arg in callback: "+ |
| 483 |
"('%s' vs '%s')", m.Reply, replyExpected) |
| 484 |
} |
| 485 |
ch <- true |
| 486 |
}) |
| 487 |
nc.PublishMsg(&nats.Msg{Subject: "foo", Reply: replyExpected, Data: []byte("Hello")}) |
| 488 |
if e := Wait(ch); e != nil { |
| 489 |
t.Fatal("Did not receive callback") |
| 490 |
} |
| 491 |
}) |
| 492 |
} |
| 493 |
|
| 494 |
func TestSyncReplyArg(t *testing.T) { |
| 495 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 496 |
replyExpected := "bar" |
| 497 |
sub, _ := nc.SubscribeSync("foo") |
| 498 |
nc.PublishMsg(&nats.Msg{Subject: "foo", Reply: replyExpected, Data: []byte("Hello")}) |
| 499 |
msg, err := sub.NextMsg(1 * time.Second) |
| 500 |
if err != nil { |
| 501 |
t.Fatal("Received an err on NextMsg()") |
| 502 |
} |
| 503 |
if msg.Reply != replyExpected { |
| 504 |
t.Fatalf("Did not receive correct reply arg in callback: "+ |
| 505 |
"('%s' vs '%s')", msg.Reply, replyExpected) |
| 506 |
} |
| 507 |
}) |
| 508 |
} |
| 509 |
|
| 510 |
func TestUnsubscribe(t *testing.T) { |
| 511 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 512 |
received := int32(0) |
| 513 |
max := int32(10) |
| 514 |
ch := make(chan bool) |
| 515 |
nc.Subscribe("foo", func(m *nats.Msg) { |
| 516 |
atomic.AddInt32(&received, 1) |
| 517 |
if received == max { |
| 518 |
err := m.Sub.Unsubscribe() |
| 519 |
if err != nil { |
| 520 |
t.Fatal("Unsubscribe failed with err:", err) |
| 521 |
} |
| 522 |
ch <- true |
| 523 |
} |
| 524 |
}) |
| 525 |
send := 20 |
| 526 |
for i := 0; i < send; i++ { |
| 527 |
nc.Publish("foo", []byte("hello")) |
| 528 |
} |
| 529 |
nc.Flush() |
| 530 |
<-ch |
| 531 |
|
| 532 |
r := atomic.LoadInt32(&received) |
| 533 |
if r != max { |
| 534 |
t.Fatalf("Received wrong # of messages after unsubscribe: %d vs %d", |
| 535 |
r, max) |
| 536 |
} |
| 537 |
}) |
| 538 |
} |
| 539 |
|
| 540 |
func TestDoubleUnsubscribe(t *testing.T) { |
| 541 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 542 |
sub, err := nc.SubscribeSync("foo") |
| 543 |
if err != nil { |
| 544 |
t.Fatal("Failed to subscribe: ", err) |
| 545 |
} |
| 546 |
if err = sub.Unsubscribe(); err != nil { |
| 547 |
t.Fatal("Unsubscribe failed with err:", err) |
| 548 |
} |
| 549 |
if err = sub.Unsubscribe(); err == nil { |
| 550 |
t.Fatal("Unsubscribe should have reported an error") |
| 551 |
} |
| 552 |
}) |
| 553 |
} |
| 554 |
|
| 555 |
func TestRequestTimeout(t *testing.T) { |
| 556 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 557 |
// We need a responder by default otherwise we get a no responders error. |
| 558 |
nc.SubscribeSync("foo") |
| 559 |
|
| 560 |
if _, err := nc.Request("foo", []byte("help"), 10*time.Millisecond); err != nats.ErrTimeout { |
| 561 |
t.Fatalf("Expected to receive a timeout error") |
| 562 |
} |
| 563 |
}) |
| 564 |
} |
| 565 |
|
| 566 |
func TestBasicNoRespondersSupport(t *testing.T) { |
| 567 |
withServerInstance(t, func(t *testing.T, nc *nats.Conn, inst *testservice.Instance) { |
| 568 |
// Default new-style request |
| 569 |
if m, err := nc.Request("foo", nil, time.Second); err != nats.ErrNoResponders { |
| 570 |
t.Fatalf("Expected a no responders error and nil msg, got m:%+v and err: %v", m, err) |
| 571 |
} |
| 572 |
ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| 573 |
defer cancel() |
| 574 |
if m, err := nc.RequestWithContext(ctx, "foo", nil); err != nats.ErrNoResponders { |
| 575 |
t.Fatalf("Expected a no responders error and nil msg, got m:%+v and err: %v", m, err) |
| 576 |
} |
| 577 |
|
| 578 |
// Old request style (separate connection) |
| 579 |
ncOld := dialInstance(t, inst, nats.UseOldRequestStyle()) |
| 580 |
if m, err := ncOld.Request("foo", nil, time.Second); err != nats.ErrNoResponders { |
| 581 |
t.Fatalf("Expected a no responders error and nil msg, got m:%+v and err: %v", m, err) |
| 582 |
} |
| 583 |
ctx2, cancel2 := context.WithTimeout(context.Background(), time.Second) |
| 584 |
defer cancel2() |
| 585 |
if m, err := ncOld.RequestWithContext(ctx2, "foo", nil); err != nats.ErrNoResponders { |
| 586 |
t.Fatalf("Expected a no responders error and nil msg, got m:%+v and err: %v", m, err) |
| 587 |
} |
| 588 |
|
| 589 |
// SubscribeSync style |
| 590 |
inbox := nats.NewInbox() |
| 591 |
sub, err := ncOld.SubscribeSync(inbox) |
| 592 |
if err != nil { |
| 593 |
t.Fatal(err) |
| 594 |
} |
| 595 |
if err := ncOld.PublishRequest("foo", inbox, nil); err != nil { |
| 596 |
t.Fatal(err) |
| 597 |
} |
| 598 |
if m, err := sub.NextMsg(2 * time.Second); err != nats.ErrNoResponders { |
| 599 |
t.Fatalf("Expected a no responders error and nil msg, got m:%+v and err: %v", m, err) |
| 600 |
} |
| 601 |
}) |
| 602 |
} |
| 603 |
|
| 604 |
func TestOldRequest(t *testing.T) { |
| 605 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 606 |
nc := dialInstance(t, inst, nats.UseOldRequestStyle()) |
| 607 |
|
| 608 |
response := []byte("I will help you") |
| 609 |
nc.Subscribe("foo", func(m *nats.Msg) { |
| 610 |
m.Respond(response) |
| 611 |
}) |
| 612 |
msg, err := nc.Request("foo", []byte("help"), 500*time.Millisecond) |
| 613 |
if err != nil { |
| 614 |
t.Fatalf("Received an error on Request test: %s", err) |
| 615 |
} |
| 616 |
if !bytes.Equal(msg.Data, response) { |
| 617 |
t.Fatalf("Received invalid response") |
| 618 |
} |
| 619 |
|
| 620 |
// Check that Close() kicks out a Request() |
| 621 |
errCh := make(chan error, 1) |
| 622 |
start := time.Now() |
| 623 |
go func() { |
| 624 |
sub, _ := nc.SubscribeSync("checkClose") |
| 625 |
defer sub.Unsubscribe() |
| 626 |
_, err := nc.Request("checkClose", []byte("should be kicked out on close"), time.Second) |
| 627 |
errCh <- err |
| 628 |
}() |
| 629 |
time.Sleep(100 * time.Millisecond) |
| 630 |
nc.Close() |
| 631 |
if e := <-errCh; e != nats.ErrConnectionClosed { |
| 632 |
t.Fatalf("Unexpected error: %v", e) |
| 633 |
} |
| 634 |
if dur := time.Since(start); dur >= time.Second { |
| 635 |
t.Fatalf("Request took too long to bail out: %v", dur) |
| 636 |
} |
| 637 |
}) |
| 638 |
} |
| 639 |
|
| 640 |
func TestRequest(t *testing.T) { |
| 641 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 642 |
response := []byte("I will help you") |
| 643 |
nc.Subscribe("foo", func(m *nats.Msg) { |
| 644 |
nc.Publish(m.Reply, response) |
| 645 |
}) |
| 646 |
msg, err := nc.Request("foo", []byte("help"), 500*time.Millisecond) |
| 647 |
if err != nil { |
| 648 |
t.Fatalf("Received an error on Request test: %s", err) |
| 649 |
} |
| 650 |
if !bytes.Equal(msg.Data, response) { |
| 651 |
t.Fatalf("Received invalid response") |
| 652 |
} |
| 653 |
}) |
| 654 |
} |
| 655 |
|
| 656 |
func TestRequestNoBody(t *testing.T) { |
| 657 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 658 |
response := []byte("I will help you") |
| 659 |
nc.Subscribe("foo", func(m *nats.Msg) { |
| 660 |
nc.Publish(m.Reply, response) |
| 661 |
}) |
| 662 |
msg, err := nc.Request("foo", nil, 500*time.Millisecond) |
| 663 |
if err != nil { |
| 664 |
t.Fatalf("Received an error on Request test: %s", err) |
| 665 |
} |
| 666 |
if !bytes.Equal(msg.Data, response) { |
| 667 |
t.Fatalf("Received invalid response") |
| 668 |
} |
| 669 |
}) |
| 670 |
} |
| 671 |
|
| 672 |
func TestSimultaneousRequests(t *testing.T) { |
| 673 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 674 |
response := []byte("I will help you") |
| 675 |
nc.Subscribe("foo", func(m *nats.Msg) { |
| 676 |
nc.Publish(m.Reply, response) |
| 677 |
}) |
| 678 |
|
| 679 |
wg := sync.WaitGroup{} |
| 680 |
wg.Add(50) |
| 681 |
errCh := make(chan error, 50) |
| 682 |
for i := 0; i < 50; i++ { |
| 683 |
go func() { |
| 684 |
defer wg.Done() |
| 685 |
if _, err := nc.Request("foo", nil, 2*time.Second); err != nil { |
| 686 |
errCh <- fmt.Errorf("Error on request: %v", err) |
| 687 |
} |
| 688 |
}() |
| 689 |
} |
| 690 |
wg.Wait() |
| 691 |
checkErrChannel(t, errCh) |
| 692 |
}) |
| 693 |
} |
| 694 |
|
| 695 |
func TestRequestClose(t *testing.T) { |
| 696 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 697 |
wg := &sync.WaitGroup{} |
| 698 |
wg.Add(1) |
| 699 |
go func() { |
| 700 |
defer wg.Done() |
| 701 |
time.Sleep(100 * time.Millisecond) |
| 702 |
nc.Close() |
| 703 |
}() |
| 704 |
nc.SubscribeSync("foo") |
| 705 |
if _, err := nc.Request("foo", []byte("help"), 2*time.Second); err != nats.ErrInvalidConnection && err != nats.ErrConnectionClosed { |
| 706 |
t.Fatalf("Expected connection error: got %v", err) |
| 707 |
} |
| 708 |
wg.Wait() |
| 709 |
}) |
| 710 |
} |
| 711 |
|
| 712 |
func TestRequestCloseTimeout(t *testing.T) { |
| 713 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 714 |
response := []byte("I will help you") |
| 715 |
nc.Subscribe("foo", func(m *nats.Msg) { |
| 716 |
nc.Publish(m.Reply, response) |
| 717 |
nc.Close() |
| 718 |
}) |
| 719 |
if _, err := nc.Request("foo", nil, 1*time.Second); err == nil { |
| 720 |
t.Fatalf("Expected to receive a timeout error") |
| 721 |
} |
| 722 |
}) |
| 723 |
} |
| 724 |
|
| 725 |
func TestFlushInCB(t *testing.T) { |
| 726 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 727 |
ch := make(chan bool) |
| 728 |
|
| 729 |
nc.Subscribe("foo", func(_ *nats.Msg) { |
| 730 |
nc.Flush() |
| 731 |
ch <- true |
| 732 |
}) |
| 733 |
nc.Publish("foo", []byte("Hello")) |
| 734 |
if e := Wait(ch); e != nil { |
| 735 |
t.Fatal("Flush did not return properly in callback") |
| 736 |
} |
| 737 |
}) |
| 738 |
} |
| 739 |
|
| 740 |
func TestReleaseFlush(t *testing.T) { |
| 741 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 742 |
for i := 0; i < 1000; i++ { |
| 743 |
nc.Publish("foo", []byte("Hello")) |
| 744 |
} |
| 745 |
go nc.Close() |
| 746 |
nc.Flush() |
| 747 |
}) |
| 748 |
} |
| 749 |
|
| 750 |
func TestInbox(t *testing.T) { |
| 751 |
inbox := nats.NewInbox() |
| 752 |
if matched, _ := regexp.Match(`_INBOX.\S`, []byte(inbox)); !matched { |
| 753 |
t.Fatal("Bad INBOX format") |
| 754 |
} |
| 755 |
} |
| 756 |
|
| 757 |
func TestStats(t *testing.T) { |
| 758 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 759 |
data := []byte("The quick brown fox jumped over the lazy dog") |
| 760 |
iter := 10 |
| 761 |
|
| 762 |
for i := 0; i < iter; i++ { |
| 763 |
nc.Publish("foo", data) |
| 764 |
} |
| 765 |
|
| 766 |
if nc.OutMsgs != uint64(iter) { |
| 767 |
t.Fatalf("Not properly tracking OutMsgs: received %d, wanted %d", nc.OutMsgs, iter) |
| 768 |
} |
| 769 |
obb := uint64(iter * len(data)) |
| 770 |
if nc.OutBytes != obb { |
| 771 |
t.Fatalf("Not properly tracking OutBytes: received %d, wanted %d", nc.OutBytes, obb) |
| 772 |
} |
| 773 |
|
| 774 |
nc.OutMsgs, nc.OutBytes = 0, 0 |
| 775 |
|
| 776 |
nc.Subscribe("foo", func(_ *nats.Msg) {}) |
| 777 |
nc.SubscribeSync("foo") |
| 778 |
|
| 779 |
for i := 0; i < iter; i++ { |
| 780 |
nc.Publish("foo", data) |
| 781 |
} |
| 782 |
nc.Flush() |
| 783 |
|
| 784 |
if nc.InMsgs != uint64(2*iter) { |
| 785 |
t.Fatalf("Not properly tracking InMsgs: received %d, wanted %d", nc.InMsgs, 2*iter) |
| 786 |
} |
| 787 |
|
| 788 |
ibb := 2 * obb |
| 789 |
if nc.InBytes != ibb { |
| 790 |
t.Fatalf("Not properly tracking InBytes: received %d, wanted %d", nc.InBytes, ibb) |
| 791 |
} |
| 792 |
}) |
| 793 |
} |
| 794 |
|
| 795 |
func TestRaceSafeStats(t *testing.T) { |
| 796 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 797 |
go nc.Publish("foo", []byte("Hello World")) |
| 798 |
time.Sleep(200 * time.Millisecond) |
| 799 |
|
| 800 |
stats := nc.Stats() |
| 801 |
if stats.OutMsgs != uint64(1) { |
| 802 |
t.Fatalf("Not properly tracking OutMsgs: received %d, wanted %d", nc.OutMsgs, 1) |
| 803 |
} |
| 804 |
}) |
| 805 |
} |
| 806 |
|
| 807 |
func TestBadSubject(t *testing.T) { |
| 808 |
withServer(t, func(t *testing.T, nc *nats.Conn) { |
| 809 |
if err := nc.Publish("", []byte("Hello World")); !errors.Is(err, nats.ErrBadSubject) { |
| 810 |
t.Fatalf("Expected a ErrBadSubject error: Got %v", err) |
| 811 |
} |
| 812 |
if err := nc.Publish("foo bar", []byte("Hello World")); !errors.Is(err, nats.ErrBadSubject) { |
| 813 |
t.Fatalf("Expected a ErrBadSubject error: Got %v", err) |
| 814 |
} |
| 815 |
msg := &nats.Msg{Subject: "foo", Reply: "bar baz", Data: []byte("Hello World")} |
| 816 |
if err := nc.PublishMsg(msg); !errors.Is(err, nats.ErrBadSubject) { |
| 817 |
t.Fatalf("Expected a ErrBadSubject error: Got %v", err) |
| 818 |
} |
| 819 |
}) |
| 820 |
} |
| 821 |
|
| 822 |
func TestOptions(t *testing.T) { |
| 823 |
withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) { |
| 824 |
rch := make(chan bool, 1) |
| 825 |
cch := make(chan bool, 1) |
| 826 |
|
| 827 |
nc, err := nats.Connect(inst.Servers[0].URL, |
| 828 |
nats.Name("myName"), |
| 829 |
nats.MaxReconnects(2), |
| 830 |
nats.ReconnectWait(50*time.Millisecond), |
| 831 |
nats.ReconnectJitter(0, 0), |
| 832 |
nats.PingInterval(20*time.Millisecond), |
| 833 |
) |
| 834 |
if err != nil { |
| 835 |
t.Fatalf("Failed to connect: %v", err) |
| 836 |
} |
| 837 |
t.Cleanup(nc.Close) |
| 838 |
|
| 839 |
nc.SetReconnectHandler(func(_ *nats.Conn) { rch <- true }) |
| 840 |
nc.SetClosedHandler(func(_ *nats.Conn) { cch <- true }) |
| 841 |
|
| 842 |
// Stop + Start the only server on the same port to trigger reconnect. |
| 843 |
inst.StopServer(t, inst.Servers[0]) |
| 844 |
inst.StartServer(t, inst.Servers[0]) |
| 845 |
|
| 846 |
if err := Wait(rch); err != nil { |
| 847 |
t.Fatal("Failed getting reconnected cb") |
| 848 |
} |
| 849 |
|
| 850 |
nc.Close() |
| 851 |
if err := Wait(cch); err != nil { |
| 852 |
t.Fatal("Failed getting closed cb") |
| 853 |
} |
| 854 |
|
| 855 |
// Second connection with NoReconnect — stopping the server should NOT |
| 856 |
// trigger a reconnect callback. |
| 857 |
nc2, err := nats.Connect(inst.Servers[0].URL, nats.NoReconnect()) |
| 858 |
if err != nil { |
| 859 |
t.Fatalf("Failed to connect: %v", err) |
| 860 |
} |
| 861 |
t.Cleanup(nc2.Close) |
| 862 |
|
| 863 |
nc2.SetReconnectHandler(func(_ *nats.Conn) { rch <- true }) |
| 864 |
nc2.SetClosedHandler(func(_ *nats.Conn) { cch <- true }) |
| 865 |
|
| 866 |
inst.StopServer(t, inst.Servers[0]) |
| 867 |
|
| 868 |
if err := WaitTime(rch, time.Second); err == nil { |
| 869 |
t.Fatal("Unexpected reconnect cb") |
| 870 |
} |
| 871 |
|
| 872 |
nc2.Close() |
| 873 |
if err := Wait(cch); err != nil { |
| 874 |
t.Fatal("Failed getting closed cb") |
| 875 |
} |
| 876 |
}) |
| 877 |
} |
| 878 |
|
| 879 |
func TestNilConnection(t *testing.T) { |
| 880 |
var nc *nats.Conn |
| 881 |
data := []byte("ok") |
| 882 |
|
| 883 |
if err := nc.Publish("foo", data); err == nil || err != nats.ErrInvalidConnection { |
| 884 |
t.Fatalf("Expected ErrInvalidConnection error, got %v", err) |
| 885 |
} |
| 886 |
if err := nc.PublishMsg(nil); err == nil || err != nats.ErrInvalidMsg { |
| 887 |
t.Fatalf("Expected ErrInvalidMsg error, got %v", err) |
| 888 |
} |
| 889 |
if err := nc.PublishMsg(&nats.Msg{}); err == nil || err != nats.ErrInvalidConnection { |
| 890 |
t.Fatalf("Expected ErrInvalidConnection error, got %v", err) |
| 891 |
} |
| 892 |
if err := nc.PublishRequest("foo", "reply", data); err == nil || err != nats.ErrInvalidConnection { |
| 893 |
t.Fatalf("Expected ErrInvalidConnection error, got %v", err) |
| 894 |
} |
| 895 |
|
| 896 |
if _, err := nc.Subscribe("foo", nil); err == nil || err != nats.ErrInvalidConnection { |
| 897 |
t.Fatalf("Expected ErrInvalidConnection error, got %v", err) |
| 898 |
} |
| 899 |
if _, err := nc.SubscribeSync("foo"); err == nil || err != nats.ErrInvalidConnection { |
| 900 |
t.Fatalf("Expected ErrInvalidConnection error, got %v", err) |
| 901 |
} |
| 902 |
if _, err := nc.QueueSubscribe("foo", "bar", nil); err == nil || err != nats.ErrInvalidConnection { |
| 903 |
t.Fatalf("Expected ErrInvalidConnection error, got %v", err) |
| 904 |
} |
| 905 |
ch := make(chan *nats.Msg) |
| 906 |
if _, err := nc.ChanSubscribe("foo", ch); err == nil || err != nats.ErrInvalidConnection { |
| 907 |
t.Fatalf("Expected ErrInvalidConnection error, got %v", err) |
| 908 |
} |
| 909 |
if _, err := nc.ChanQueueSubscribe("foo", "bar", ch); err == nil || err != nats.ErrInvalidConnection { |
| 910 |
t.Fatalf("Expected ErrInvalidConnection error, got %v", err) |
| 911 |
} |
| 912 |
if _, err := nc.QueueSubscribeSyncWithChan("foo", "bar", ch); err == nil || err != nats.ErrInvalidConnection { |
| 913 |
t.Fatalf("Expected ErrInvalidConnection error, got %v", err) |
| 914 |
} |
| 915 |
|
| 916 |
if err := nc.Flush(); err == nil || err != nats.ErrInvalidConnection { |
| 917 |
t.Fatalf("Expected ErrInvalidConnection error, got %v", err) |
| 918 |
} |
| 919 |
if err := nc.FlushTimeout(time.Millisecond); err == nil || err != nats.ErrInvalidConnection { |
| 920 |
t.Fatalf("Expected ErrInvalidConnection error, got %v", err) |
| 921 |
} |
| 922 |
|
| 923 |
var sub *nats.Subscription |
| 924 |
if sub.Type() != nats.NilSubscription { |
| 925 |
t.Fatalf("Got wrong type for nil subscription, %v", sub.Type()) |
| 926 |
} |
| 927 |
if sub.IsValid() { |
| 928 |
t.Fatalf("Expected IsValid() to return false") |
| 929 |
} |
| 930 |
if err := sub.Unsubscribe(); err == nil || err != nats.ErrBadSubscription { |
| 931 |
t.Fatalf("Expected Unsubscribe to return proper error, got %v", err) |
| 932 |
} |
| 933 |
if err := sub.AutoUnsubscribe(1); err == nil || err != nats.ErrBadSubscription { |
| 934 |
t.Fatalf("Expected ErrBadSubscription error, got %v", err) |
| 935 |
} |
| 936 |
if _, err := sub.NextMsg(time.Millisecond); err == nil || err != nats.ErrBadSubscription { |
| 937 |
t.Fatalf("Expected ErrBadSubscription error, got %v", err) |
| 938 |
} |
| 939 |
if _, _, err := sub.Pending(); err == nil || err != nats.ErrBadSubscription { |
| 940 |
t.Fatalf("Expected ErrBadSubscription error, got %v", err) |
| 941 |
} |
| 942 |
if _, _, err := sub.MaxPending(); err == nil || err != nats.ErrBadSubscription { |
| 943 |
t.Fatalf("Expected ErrBadSubscription error, got %v", err) |
| 944 |
} |
| 945 |
if err := sub.ClearMaxPending(); err == nil || err != nats.ErrBadSubscription { |
| 946 |
t.Fatalf("Expected ErrBadSubscription error, got %v", err) |
| 947 |
} |
| 948 |
if _, _, err := sub.PendingLimits(); err == nil || err != nats.ErrBadSubscription { |
| 949 |
t.Fatalf("Expected ErrBadSubscription error, got %v", err) |
| 950 |
} |
| 951 |
if err := sub.SetPendingLimits(1, 1); err == nil || err != nats.ErrBadSubscription { |
| 952 |
t.Fatalf("Expected ErrBadSubscription error, got %v", err) |
| 953 |
} |
| 954 |
if _, err := sub.Delivered(); err == nil || err != nats.ErrBadSubscription { |
| 955 |
t.Fatalf("Expected ErrBadSubscription error, got %v", err) |
| 956 |
} |
| 957 |
if _, err := sub.Dropped(); err == nil || err != nats.ErrBadSubscription { |
| 958 |
t.Fatalf("Expected ErrBadSubscription error, got %v", err) |
| 959 |
} |
| 960 |
} |