Debian Codegraph @

test/sub_test.go

raw
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 "sync"
20 "sync/atomic"
21 "testing"
22 "time"
23
24 "github.com/nats-io/nats.go"
25 "github.com/nats-io/nuid"
26 testservice "github.com/synadia-io/orbit.go/ntf-client"
27 )
28
29 // More advanced tests on subscriptions
30
31 func TestServerAutoUnsub(t *testing.T) {
32 withServer(t, func(t *testing.T, nc *nats.Conn) {
33 received := int32(0)
34 max := int32(10)
35
36 // Call this to make sure that we have everything setup connection wise
37 nc.Flush()
38
39 // When this test is run by itself it's fine, but when run with others
40 // we need to make sure the go routines reading has settled.
41 time.Sleep(250 * time.Millisecond)
42
43 base := getStableNumGoroutine(t)
44
45 sub, err := nc.Subscribe("foo", func(_ *nats.Msg) {
46 atomic.AddInt32(&received, 1)
47 })
48 if err != nil {
49 t.Fatal("Failed to subscribe: ", err)
50 }
51 sub.AutoUnsubscribe(int(max))
52 total := 100
53 for range total {
54 nc.Publish("foo", []byte("Hello"))
55 }
56 nc.Flush()
57 time.Sleep(100 * time.Millisecond)
58
59 if atomic.LoadInt32(&received) != max {
60 t.Fatalf("Received %d msgs, wanted only %d\n", received, max)
61 }
62 if sub.IsValid() {
63 t.Fatal("Expected subscription to be invalid after hitting max")
64 }
65 if err := sub.AutoUnsubscribe(10); err == nil {
66 t.Fatal("Calling AutoUnsubscribe() on closed subscription should fail")
67 }
68 checkNoGoroutineLeak(t, base, "AutoUnsubscribe() limit reached")
69 })
70 }
71
72 func TestClientSyncAutoUnsub(t *testing.T) {
73 withServer(t, func(t *testing.T, nc *nats.Conn) {
74 received := 0
75 max := 10
76 sub, _ := nc.SubscribeSync("foo")
77 sub.AutoUnsubscribe(max)
78 total := 100
79 for range total {
80 nc.Publish("foo", []byte("Hello"))
81 }
82 nc.Flush()
83 for {
84 _, err := sub.NextMsg(10 * time.Millisecond)
85 if err != nil {
86 if err != nats.ErrMaxMessages {
87 t.Fatalf("Expected '%v', but got: '%v'\n", nats.ErrMaxMessages, err.Error())
88 }
89 break
90 }
91 received++
92 }
93 if received != max {
94 t.Fatalf("Received %d msgs, wanted only %d\n", received, max)
95 }
96 if sub.IsValid() {
97 t.Fatal("Expected subscription to be invalid after hitting max")
98 }
99 if err := sub.AutoUnsubscribe(10); err == nil {
100 t.Fatal("Calling AutoUnsubscribe() ob closed subscription should fail")
101 }
102 })
103 }
104
105 func TestClientChanAutoUnsub(t *testing.T) {
106 withServer(t, func(t *testing.T, nc *nats.Conn) {
107 received := 0
108 max := 10
109 ch := make(chan *nats.Msg, max)
110 sub, _ := nc.ChanSubscribe("foo", ch)
111 sub.AutoUnsubscribe(max)
112 total := 100
113 for range total {
114 nc.Publish("foo", []byte("Hello"))
115 }
116 nc.Flush()
117
118 // Drain the channel
119 for {
120 select {
121 case <-ch:
122 received++
123 case <-time.After(10 * time.Millisecond):
124 if received != max {
125 t.Fatalf("Received %d msgs, wanted only %d", received, max)
126 }
127 if sub.IsValid() {
128 t.Fatal("Expected subscription to be invalid after hitting max")
129 }
130 if err := sub.AutoUnsubscribe(10); err == nil {
131 t.Fatal("Calling AutoUnsubscribe() ob closed subscription should fail")
132 }
133 return
134 }
135 }
136 })
137 }
138
139 func TestClientASyncAutoUnsub(t *testing.T) {
140 withServer(t, func(t *testing.T, nc *nats.Conn) {
141 received := int32(0)
142 max := int32(10)
143 sub, err := nc.Subscribe("foo", func(_ *nats.Msg) {
144 atomic.AddInt32(&received, 1)
145 })
146 if err != nil {
147 t.Fatal("Failed to subscribe: ", err)
148 }
149 sub.AutoUnsubscribe(int(max))
150 total := 100
151 for range total {
152 nc.Publish("foo", []byte("Hello"))
153 }
154 nc.Flush()
155 time.Sleep(10 * time.Millisecond)
156
157 if atomic.LoadInt32(&received) != max {
158 t.Fatalf("Received %d msgs, wanted only %d\n", received, max)
159 }
160 if err := sub.AutoUnsubscribe(10); err == nil {
161 t.Fatal("Calling AutoUnsubscribe() on closed subscription should fail")
162 }
163 })
164 }
165
166 func TestAutoUnsubAndReconnect(t *testing.T) {
167 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
168 rch := make(chan bool)
169
170 nc, err := nats.Connect(inst.Servers[0].URL,
171 nats.ReconnectWait(50*time.Millisecond),
172 nats.ReconnectJitter(0, 0),
173 nats.ReconnectHandler(func(_ *nats.Conn) { rch <- true }))
174 if err != nil {
175 t.Fatalf("Unable to connect: %v", err)
176 }
177 defer nc.Close()
178
179 received := int32(0)
180 max := int32(10)
181 sub, err := nc.Subscribe("foo", func(_ *nats.Msg) {
182 atomic.AddInt32(&received, 1)
183 })
184 if err != nil {
185 t.Fatalf("Failed to subscribe: %v", err)
186 }
187 sub.AutoUnsubscribe(int(max))
188
189 // Send less than the max
190 total := int(max / 2)
191 for range total {
192 nc.Publish("foo", []byte("Hello"))
193 }
194 nc.Flush()
195
196 // Restart the server
197 inst.StopServer(t, inst.Servers[0])
198 inst.StartServer(t, inst.Servers[0])
199
200 // and wait to reconnect
201 if err := Wait(rch); err != nil {
202 t.Fatal("Failed to get the reconnect cb")
203 }
204
205 // Now send more than the total max.
206 total = int(3 * max)
207 for range total {
208 nc.Publish("foo", []byte("Hello"))
209 }
210 nc.Flush()
211
212 // Wait a bit before checking.
213 time.Sleep(50 * time.Millisecond)
214
215 // We should have received only up-to-max messages.
216 if atomic.LoadInt32(&received) != max {
217 t.Fatalf("Received %d msgs, wanted only %d\n", received, max)
218 }
219 })
220 }
221
222 func TestAutoUnsubWithParallelNextMsgCalls(t *testing.T) {
223 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
224 rch := make(chan bool, 1)
225
226 nc, err := nats.Connect(inst.Servers[0].URL,
227 nats.ReconnectWait(50*time.Millisecond),
228 nats.ReconnectJitter(0, 0),
229 nats.ReconnectHandler(func(_ *nats.Conn) { rch <- true }))
230 if err != nil {
231 t.Fatalf("Unable to connect: %v", err)
232 }
233 defer nc.Close()
234
235 numRoutines := 3
236 max := 100
237 total := max * 2
238 received := int64(0)
239
240 var wg sync.WaitGroup
241
242 sub, err := nc.SubscribeSync("foo")
243 if err != nil {
244 t.Fatalf("Failed to subscribe: %v", err)
245 }
246 sub.AutoUnsubscribe(int(max))
247 nc.Flush()
248
249 wg.Add(numRoutines)
250
251 for i := range numRoutines {
252 go func(s *nats.Subscription, idx int) {
253 for {
254 // The first to reach the max delivered will cause the
255 // subscription to be removed, which will kick out all
256 // other calls to NextMsg. So don't be afraid of the long
257 // timeout.
258 _, err := s.NextMsg(3 * time.Second)
259 if err != nil {
260 break
261 }
262 atomic.AddInt64(&received, 1)
263 }
264 wg.Done()
265 }(sub, i)
266 }
267
268 msg := []byte("Hello")
269 for range max / 2 {
270 nc.Publish("foo", msg)
271 }
272 nc.Flush()
273
274 inst.StopServer(t, inst.Servers[0])
275 inst.StartServer(t, inst.Servers[0])
276
277 // Make sure we got the reconnected cb
278 if err := Wait(rch); err != nil {
279 t.Fatal("Failed to get reconnected cb")
280 }
281
282 for range total {
283 nc.Publish("foo", msg)
284 }
285 nc.Flush()
286
287 wg.Wait()
288 if atomic.LoadInt64(&received) != int64(max) {
289 t.Fatalf("Wrong number of received msg: %v instead of %v", atomic.LoadInt64(&received), max)
290 }
291 })
292 }
293
294 func TestAutoUnsubscribeFromCallback(t *testing.T) {
295 withServer(t, func(t *testing.T, nc *nats.Conn) {
296 max := 10
297 resetUnsubMark := int64(max / 2)
298 limit := int64(100)
299 received := int64(0)
300
301 msg := []byte("Hello")
302
303 // Auto-unsubscribe within the callback with a value lower
304 // than what was already received.
305
306 sub, err := nc.Subscribe("foo", func(m *nats.Msg) {
307 r := atomic.AddInt64(&received, 1)
308 if r == resetUnsubMark {
309 m.Sub.AutoUnsubscribe(int(r - 1))
310 nc.Flush()
311 }
312 if r == limit {
313 // Something went wrong... fail now
314 t.Fatal("Got more messages than expected")
315 }
316 nc.Publish("foo", msg)
317 })
318 if err != nil {
319 t.Fatalf("Failed to subscribe: %v", err)
320 }
321 sub.AutoUnsubscribe(int(max))
322 nc.Flush()
323
324 // Trigger the first message, the other are sent from the callback.
325 nc.Publish("foo", msg)
326 nc.Flush()
327
328 waitFor(t, time.Second, 100*time.Millisecond, func() error {
329 recv := atomic.LoadInt64(&received)
330 if recv != resetUnsubMark {
331 return fmt.Errorf("Wrong number of received messages. Original max was %v reset to %v, actual received: %v",
332 max, resetUnsubMark, recv)
333 }
334 return nil
335 })
336
337 // Now check with AutoUnsubscribe with higher value than original
338 received = int64(0)
339 newMax := int64(2 * max)
340
341 sub, err = nc.Subscribe("foo", func(m *nats.Msg) {
342 r := atomic.AddInt64(&received, 1)
343 if r == resetUnsubMark {
344 m.Sub.AutoUnsubscribe(int(newMax))
345 nc.Flush()
346 }
347 if r == limit {
348 // Something went wrong... fail now
349 t.Fatal("Got more messages than expected")
350 }
351 nc.Publish("foo", msg)
352 })
353 if err != nil {
354 t.Fatalf("Failed to subscribe: %v", err)
355 }
356 sub.AutoUnsubscribe(int(max))
357 nc.Flush()
358
359 // Trigger the first message, the other are sent from the callback.
360 nc.Publish("foo", msg)
361 nc.Flush()
362
363 waitFor(t, time.Second, 100*time.Millisecond, func() error {
364 recv := atomic.LoadInt64(&received)
365 if recv != newMax {
366 return fmt.Errorf("Wrong number of received messages. Original max was %v reset to %v, actual received: %v",
367 max, newMax, recv)
368 }
369 return nil
370 })
371 })
372 }
373
374 func TestCloseSubRelease(t *testing.T) {
375 withServer(t, func(t *testing.T, nc *nats.Conn) {
376 sub, _ := nc.SubscribeSync("foo")
377 start := time.Now()
378 go func() {
379 time.Sleep(15 * time.Millisecond)
380 nc.Close()
381 }()
382 if _, err := sub.NextMsg(time.Second); err == nil {
383 t.Fatalf("Expected an error from NextMsg")
384 }
385 elapsed := time.Since(start)
386
387 // On Windows, the minimum waitTime is at least 15ms.
388 if elapsed > 50*time.Millisecond {
389 t.Fatalf("Too much time has elapsed to release NextMsg: %dms",
390 (elapsed / time.Millisecond))
391 }
392 })
393 }
394
395 func TestIsValidSubscriber(t *testing.T) {
396 withServer(t, func(t *testing.T, nc *nats.Conn) {
397 sub, err := nc.SubscribeSync("foo")
398 if err != nil {
399 t.Fatalf("Error on subscribe: %v", err)
400 }
401 if !sub.IsValid() {
402 t.Fatalf("Subscription should be valid")
403 }
404 for range 10 {
405 nc.Publish("foo", []byte("Hello"))
406 }
407 nc.Flush()
408 _, err = sub.NextMsg(200 * time.Millisecond)
409 if err != nil {
410 t.Fatalf("NextMsg returned an error")
411 }
412 sub.Unsubscribe()
413 _, err = sub.NextMsg(200 * time.Millisecond)
414 if err == nil {
415 t.Fatalf("NextMsg should have returned an error")
416 }
417 })
418 }
419
420 func TestSlowSubscriber(t *testing.T) {
421 withServer(t, func(t *testing.T, nc *nats.Conn) {
422 // Override default handler for test.
423 nc.SetErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, _ error) {})
424
425 sub, _ := nc.SubscribeSync("foo")
426 sub.SetPendingLimits(100, 1024)
427
428 for range 200 {
429 nc.Publish("foo", []byte("Hello"))
430 }
431 timeout := 5 * time.Second
432 start := time.Now()
433 nc.FlushTimeout(timeout)
434 elapsed := time.Since(start)
435 if elapsed >= timeout {
436 t.Fatalf("Flush did not return before timeout: %d > %d", elapsed, timeout)
437 }
438 // Make sure NextMsg returns an error to indicate slow consumer
439 _, err := sub.NextMsg(200 * time.Millisecond)
440 if err == nil {
441 t.Fatalf("NextMsg did not return an error")
442 }
443 })
444 }
445
446 func TestSlowChanSubscriber(t *testing.T) {
447 withServer(t, func(t *testing.T, nc *nats.Conn) {
448 // Override default handler for test.
449 nc.SetErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, _ error) {})
450
451 ch := make(chan *nats.Msg, 64)
452 sub, _ := nc.ChanSubscribe("foo", ch)
453 sub.SetPendingLimits(100, 1024)
454
455 for range 200 {
456 nc.Publish("foo", []byte("Hello"))
457 }
458 timeout := 5 * time.Second
459 start := time.Now()
460 nc.FlushTimeout(timeout)
461 elapsed := time.Since(start)
462 if elapsed >= timeout {
463 t.Fatalf("Flush did not return before timeout: %d > %d", elapsed, timeout)
464 }
465 })
466 }
467
468 func TestSlowAsyncSubscriber(t *testing.T) {
469 withServer(t, func(t *testing.T, nc *nats.Conn) {
470 // Override default handler for test.
471 nc.SetErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, _ error) {})
472
473 bch := make(chan bool)
474
475 sub, _ := nc.Subscribe("foo", func(m *nats.Msg) {
476 // block to back us up..
477 <-bch
478 // Avoid repeated calls that would then block again
479 m.Sub.Unsubscribe()
480 })
481 // Make sure these are the defaults
482 pm, pb, _ := sub.PendingLimits()
483 if pm != nats.DefaultSubPendingMsgsLimit {
484 t.Fatalf("Pending limit for number of msgs incorrect, expected %d, got %d\n", nats.DefaultSubPendingMsgsLimit, pm)
485 }
486 if pb != nats.DefaultSubPendingBytesLimit {
487 t.Fatalf("Pending limit for number of bytes incorrect, expected %d, got %d\n", nats.DefaultSubPendingBytesLimit, pb)
488 }
489
490 // Set new limits
491 pml := 100
492 pbl := 1024 * 1024
493
494 sub.SetPendingLimits(pml, pbl)
495
496 // Make sure the set is correct
497 pm, pb, _ = sub.PendingLimits()
498 if pm != pml {
499 t.Fatalf("Pending limit for number of msgs incorrect, expected %d, got %d\n", pml, pm)
500 }
501 if pb != pbl {
502 t.Fatalf("Pending limit for number of bytes incorrect, expected %d, got %d\n", pbl, pb)
503 }
504
505 for range int(pml) + 100 {
506 nc.Publish("foo", []byte("Hello"))
507 }
508
509 timeout := 5 * time.Second
510 start := time.Now()
511 err := nc.FlushTimeout(timeout)
512 elapsed := time.Since(start)
513 if elapsed >= timeout {
514 t.Fatalf("Flush did not return before timeout")
515 }
516 // We want flush to work, so expect no error for it.
517 if err != nil {
518 t.Fatalf("Expected no error from Flush()\n")
519 }
520 if nc.LastError() != nats.ErrSlowConsumer {
521 t.Fatal("Expected LastError to indicate slow consumer")
522 }
523 // release the sub
524 close(bch)
525 })
526 }
527
528 func TestAsyncErrHandler(t *testing.T) {
529 withServer(t, func(t *testing.T, nc *nats.Conn) {
530 subj := "async_test"
531 bch := make(chan bool)
532
533 sub, err := nc.Subscribe(subj, func(_ *nats.Msg) {
534 // block to back us up..
535 <-bch
536 })
537 if err != nil {
538 t.Fatalf("Could not subscribe: %v\n", err)
539 }
540
541 limit := 10
542 toSend := 100
543
544 // Limit internal subchan length to trip condition easier.
545 sub.SetPendingLimits(limit, 1024)
546
547 ch := make(chan bool)
548
549 aeCalled := int64(0)
550
551 nc.SetErrorHandler(func(c *nats.Conn, s *nats.Subscription, e error) {
552 atomic.AddInt64(&aeCalled, 1)
553
554 if s != sub {
555 t.Fatal("Did not receive proper subscription")
556 }
557 if !errors.Is(e, nats.ErrSlowConsumer) {
558 t.Fatalf("Did not receive proper error: %v vs %v", e, nats.ErrSlowConsumer)
559 }
560 // Suppress additional calls
561 if atomic.LoadInt64(&aeCalled) == 1 {
562 // release the sub
563 defer close(bch)
564 // release the test
565 ch <- true
566 }
567 })
568
569 b := []byte("Hello World!")
570 // First one trips the ch wait in subscription callback.
571 nc.Publish(subj, b)
572 nc.Flush()
573 for range toSend {
574 nc.Publish(subj, b)
575 }
576 if err := nc.Flush(); err != nil {
577 t.Fatalf("Got an error on Flush:%v", err)
578 }
579
580 if e := Wait(ch); e != nil {
581 t.Fatal("Failed to call async err handler")
582 }
583 // Make sure dropped stats is correct.
584 if d, _ := sub.Dropped(); d != toSend-limit+1 {
585 t.Fatalf("Expected Dropped to be %d, got %d", toSend-limit+1, d)
586 }
587 if ae := atomic.LoadInt64(&aeCalled); ae != 1 {
588 t.Fatalf("Expected err handler to be called only once, got %d", ae)
589 }
590
591 sub.Unsubscribe()
592 if _, err := sub.Dropped(); err == nil {
593 t.Fatal("Calling Dropped() on closed subscription should fail")
594 }
595 })
596 }
597
598 func TestAsyncErrHandlerChanSubscription(t *testing.T) {
599 withServer(t, func(t *testing.T, nc *nats.Conn) {
600 subj := "chan_test"
601
602 limit := 10
603 toSend := 100
604
605 // Create our own channel.
606 mch := make(chan *nats.Msg, limit)
607 sub, err := nc.ChanSubscribe(subj, mch)
608 if err != nil {
609 t.Fatalf("Could not subscribe: %v", err)
610 }
611 ch := make(chan bool)
612 aeCalled := int64(0)
613
614 nc.SetErrorHandler(func(c *nats.Conn, s *nats.Subscription, e error) {
615 atomic.AddInt64(&aeCalled, 1)
616 if !errors.Is(e, nats.ErrSlowConsumer) {
617 t.Fatalf("Did not receive proper error: %v vs %v",
618 e, nats.ErrSlowConsumer)
619 }
620 // Suppress additional calls
621 if atomic.LoadInt64(&aeCalled) == 1 {
622 // release the test
623 ch <- true
624 }
625 })
626
627 b := []byte("Hello World!")
628 for range toSend {
629 nc.Publish(subj, b)
630 }
631 nc.Flush()
632
633 if e := Wait(ch); e != nil {
634 t.Fatal("Failed to call async err handler")
635 }
636 // Make sure dropped stats is correct.
637 if d, _ := sub.Dropped(); d != toSend-limit {
638 t.Fatalf("Expected Dropped to be %d, go %d", toSend-limit, d)
639 }
640 if ae := atomic.LoadInt64(&aeCalled); ae != 1 {
641 t.Fatalf("Expected err handler to be called once, got %d", ae)
642 }
643
644 sub.Unsubscribe()
645 if _, err := sub.Dropped(); err == nil {
646 t.Fatal("Calling Dropped() on closed subscription should fail")
647 }
648 })
649 }
650
651 // Test to make sure that we can send and async receive messages on
652 // different subjects within a callback.
653 func TestAsyncSubscriberStarvation(t *testing.T) {
654 withServer(t, func(t *testing.T, nc *nats.Conn) {
655 // Helper
656 nc.Subscribe("helper", func(m *nats.Msg) {
657 nc.Publish(m.Reply, []byte("Hello"))
658 })
659
660 ch := make(chan bool)
661
662 // Kickoff
663 nc.Subscribe("start", func(m *nats.Msg) {
664 // Helper Response
665 response := nats.NewInbox()
666 nc.Subscribe(response, func(_ *nats.Msg) {
667 ch <- true
668 })
669 nc.PublishRequest("helper", response, []byte("Help Me!"))
670 })
671
672 nc.Publish("start", []byte("Begin"))
673 nc.Flush()
674
675 if e := Wait(ch); e != nil {
676 t.Fatal("Was stalled inside of callback waiting on another callback")
677 }
678 })
679 }
680
681 func TestAsyncSubscribersOnClose(t *testing.T) {
682 withServer(t, func(t *testing.T, nc *nats.Conn) {
683 toSend := 10
684 callbacks := int32(0)
685 ch := make(chan bool, toSend)
686
687 nc.Subscribe("foo", func(_ *nats.Msg) {
688 atomic.AddInt32(&callbacks, 1)
689 <-ch
690 })
691
692 for range toSend {
693 nc.Publish("foo", []byte("Hello World!"))
694 }
695 nc.Flush()
696 time.Sleep(10 * time.Millisecond)
697 nc.Close()
698
699 // Release callbacks
700 for i := 1; i < toSend; i++ {
701 ch <- true
702 }
703
704 // Wait for some time.
705 time.Sleep(10 * time.Millisecond)
706 seen := atomic.LoadInt32(&callbacks)
707 if seen != 1 {
708 t.Fatalf("Expected only one callback, received %d callbacks", seen)
709 }
710 })
711 }
712
713 func TestNextMsgCallOnAsyncSub(t *testing.T) {
714 withServer(t, func(t *testing.T, nc *nats.Conn) {
715 sub, err := nc.Subscribe("foo", func(_ *nats.Msg) {
716 })
717 if err != nil {
718 t.Fatal("Failed to subscribe: ", err)
719 }
720 _, err = sub.NextMsg(time.Second)
721 if err == nil {
722 t.Fatal("Expected an error call NextMsg() on AsyncSubscriber")
723 }
724 })
725 }
726
727 func TestNextMsgCallOnClosedSub(t *testing.T) {
728 withServer(t, func(t *testing.T, nc *nats.Conn) {
729 sub, err := nc.SubscribeSync("foo")
730 if err != nil {
731 t.Fatal("Failed to subscribe: ", err)
732 }
733
734 if err = sub.Unsubscribe(); err != nil {
735 t.Fatal("Unsubscribe failed with err:", err)
736 }
737
738 _, err = sub.NextMsg(time.Second)
739 if err == nil {
740 t.Fatal("Expected an error calling NextMsg() on closed subscription")
741 } else if err != nats.ErrBadSubscription {
742 t.Fatalf("Expected '%v', but got: '%v'", nats.ErrBadSubscription, err.Error())
743 }
744
745 sub, err = nc.SubscribeSync("foo")
746 if err != nil {
747 t.Fatal("Failed to subscribe: ", err)
748 }
749 wg := sync.WaitGroup{}
750 wg.Add(1)
751 go func() {
752 time.Sleep(100 * time.Millisecond)
753 sub.Unsubscribe()
754 wg.Done()
755 }()
756
757 if _, err := sub.NextMsg(time.Second); err == nil || err != nats.ErrBadSubscription {
758 t.Fatalf("Expected '%v', but got: '%v'", nats.ErrBadSubscription, err.Error())
759 }
760 })
761 }
762
763 func TestChanSubscriber(t *testing.T) {
764 withServer(t, func(t *testing.T, nc *nats.Conn) {
765 // Create our own channel.
766 ch := make(chan *nats.Msg, 128)
767
768 // Channel is mandatory
769 if _, err := nc.ChanSubscribe("foo", nil); err == nil {
770 t.Fatal("Creating subscription without channel should have failed")
771 }
772
773 _, err := nc.ChanSubscribe("foo", ch)
774 if err != nil {
775 t.Fatal("Failed to subscribe: ", err)
776 }
777
778 // Send some messages to ourselves.
779 total := 100
780 for range total {
781 nc.Publish("foo", []byte("Hello"))
782 }
783
784 received := 0
785 tm := time.NewTimer(5 * time.Second)
786 defer tm.Stop()
787
788 // Go ahead and receive
789 for {
790 select {
791 case _, ok := <-ch:
792 if !ok {
793 t.Fatalf("Got an error reading from channel")
794 }
795 case <-tm.C:
796 t.Fatalf("Timed out waiting on messages")
797 }
798 received++
799 if received >= total {
800 return
801 }
802 }
803 })
804 }
805
806 func TestChanQueueSubscriber(t *testing.T) {
807 withServer(t, func(t *testing.T, nc *nats.Conn) {
808 // Create our own channel.
809 ch1 := make(chan *nats.Msg, 64)
810 ch2 := make(chan *nats.Msg, 64)
811
812 nc.ChanQueueSubscribe("foo", "bar", ch1)
813 nc.ChanQueueSubscribe("foo", "bar", ch2)
814
815 // Send some messages to ourselves.
816 total := 100
817 for range total {
818 nc.Publish("foo", []byte("Hello"))
819 }
820
821 received := 0
822 tm := time.NewTimer(5 * time.Second)
823 defer tm.Stop()
824
825 chk := func(ok bool) {
826 if !ok {
827 t.Fatalf("Got an error reading from channel")
828 } else {
829 received++
830 }
831 }
832
833 // Go ahead and receive
834 for {
835 select {
836 case _, ok := <-ch1:
837 chk(ok)
838 case _, ok := <-ch2:
839 chk(ok)
840 case <-tm.C:
841 t.Fatalf("Timed out waiting on messages")
842 }
843 if received >= total {
844 return
845 }
846 }
847 })
848 }
849
850 func TestChanSubscriberPendingLimits(t *testing.T) {
851 withServerInstance(t, func(t *testing.T, nc *nats.Conn, inst *testservice.Instance) {
852 ncp := dialInstance(t, inst)
853
854 // There was a defect that prevented to receive more than
855 // the default pending message limit. Trying to send more
856 // than this limit.
857 pending := 1000
858 total := pending + 100
859
860 for typeSubs := 0; typeSubs < 3; typeSubs++ {
861
862 func() {
863 // Create our own channel.
864 ch := make(chan *nats.Msg, total)
865
866 var err error
867 var sub *nats.Subscription
868 switch typeSubs {
869 case 0:
870 sub, err = nc.ChanSubscribe("foo", ch)
871 if err := sub.SetPendingLimits(pending, -1); err == nil {
872 t.Fatalf("Expected an error setting pending limits")
873 }
874 case 1:
875 sub, err = nc.ChanQueueSubscribe("foo", "bar", ch)
876 if err := sub.SetPendingLimits(pending, -1); err == nil {
877 t.Fatalf("Expected an error setting pending limits")
878 }
879 case 2:
880 sub, err = nc.QueueSubscribeSyncWithChan("foo", "bar", ch)
881 if err := sub.SetPendingLimits(pending, -1); err == nil {
882 t.Fatalf("Expected an error setting pending limits")
883 }
884 }
885 if err != nil {
886 t.Fatalf("Unexpected error on subscribe: %v", err)
887 }
888 defer sub.Unsubscribe()
889 nc.Flush()
890
891 // Send some messages
892 for range total {
893 if err := ncp.Publish("foo", []byte("Hello")); err != nil {
894 t.Fatalf("Unexpected error on publish: %v", err)
895 }
896 }
897
898 received := 0
899 tm := time.NewTimer(10 * time.Second)
900 defer tm.Stop()
901
902 chk := func(ok bool) {
903 if !ok {
904 t.Fatalf("Got an error reading from channel")
905 } else {
906 received++
907 }
908 }
909
910 // Go ahead and receive
911 for {
912 select {
913 case _, ok := <-ch:
914 chk(ok)
915 if received >= total {
916 return
917 }
918 case <-tm.C:
919 t.Fatalf("Timed out waiting on messages for test %d, received %d", typeSubs, received)
920 }
921 }
922 }()
923 }
924 })
925 }
926
927 func TestQueueChanQueueSubscriber(t *testing.T) {
928 withServer(t, func(t *testing.T, nc *nats.Conn) {
929 // Create our own channel.
930 ch1 := make(chan *nats.Msg, 64)
931 ch2 := make(chan *nats.Msg, 64)
932
933 nc.QueueSubscribeSyncWithChan("foo", "bar", ch1)
934 nc.QueueSubscribeSyncWithChan("foo", "bar", ch2)
935
936 // Send some messages to ourselves.
937 total := 100
938 for range total {
939 nc.Publish("foo", []byte("Hello"))
940 }
941
942 recv1 := 0
943 recv2 := 0
944 tm := time.NewTimer(5 * time.Second)
945 defer tm.Stop()
946 runTimer := time.NewTimer(500 * time.Millisecond)
947 defer runTimer.Stop()
948
949 chk := func(ok bool, which int) {
950 if !ok {
951 t.Fatalf("Got an error reading from channel")
952 } else {
953 if which == 1 {
954 recv1++
955 } else {
956 recv2++
957 }
958 }
959 }
960
961 // Go ahead and receive
962 recvLoop:
963 for {
964 select {
965 case _, ok := <-ch1:
966 chk(ok, 1)
967 case _, ok := <-ch2:
968 chk(ok, 2)
969 case <-tm.C:
970 t.Fatalf("Timed out waiting on messages")
971 case <-runTimer.C:
972 break recvLoop
973 }
974 }
975
976 if recv1+recv2 > total {
977 t.Fatalf("Received more messages than expected: %v vs %v", (recv1 + recv2), total)
978 }
979 })
980 }
981
982 func TestUnsubscribeChanOnSubscriber(t *testing.T) {
983 withServer(t, func(t *testing.T, nc *nats.Conn) {
984 // Override default handler for test.
985 nc.SetErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, _ error) {})
986
987 // Create our own channel.
988 ch := make(chan *nats.Msg, 8)
989 sub, _ := nc.ChanSubscribe("foo", ch)
990
991 // Send some messages to ourselves.
992 total := 100
993 for range total {
994 nc.Publish("foo", []byte("Hello"))
995 }
996
997 sub.Unsubscribe()
998 for len(ch) > 0 {
999 <-ch
1000 }
1001 // Make sure we can send to the channel still.
1002 // Test that we do not close it.
1003 ch <- &nats.Msg{}
1004 })
1005 }
1006
1007 func TestCloseChanOnSubscriber(t *testing.T) {
1008 withServer(t, func(t *testing.T, nc *nats.Conn) {
1009 // Create our own channel.
1010 ch := make(chan *nats.Msg, 8)
1011 nc.ChanSubscribe("foo", ch)
1012
1013 // Send some messages to ourselves.
1014 total := 100
1015 for range total {
1016 nc.Publish("foo", []byte("Hello"))
1017 }
1018
1019 nc.Close()
1020 for len(ch) > 0 {
1021 <-ch
1022 }
1023 // Make sure we can send to the channel still.
1024 // Test that we do not close it.
1025 ch <- &nats.Msg{}
1026 })
1027 }
1028
1029 func TestAsyncSubscriptionPending(t *testing.T) {
1030 withServer(t, func(t *testing.T, nc *nats.Conn) {
1031 // Send some messages to ourselves.
1032 total := 100
1033 msg := []byte("0123456789")
1034
1035 inCb := make(chan bool)
1036 block := make(chan bool)
1037
1038 sub, _ := nc.Subscribe("foo", func(m *nats.Msg) {
1039 inCb <- true
1040 <-block
1041 // Avoid repeated calls to this callback
1042 m.Sub.Unsubscribe()
1043 })
1044 defer sub.Unsubscribe()
1045
1046 for range total {
1047 nc.Publish("foo", msg)
1048 }
1049 nc.Flush()
1050
1051 // Wait that a message is received, so checks are safe
1052 if err := Wait(inCb); err != nil {
1053 t.Fatal("No message received")
1054 }
1055
1056 // Test old way
1057 q, _, _ := sub.Pending()
1058 if q != total && q != total-1 {
1059 t.Fatalf("Expected %d or %d, got %d", total, total-1, q)
1060 }
1061
1062 // New way, make sure the same and check bytes.
1063 m, b, _ := sub.Pending()
1064 mlen := len(msg)
1065 totalSize := total * mlen
1066
1067 if m != total && m != total-1 {
1068 t.Fatalf("Expected msgs of %d or %d, got %d", total, total-1, m)
1069 }
1070 if b != totalSize && b != totalSize-mlen {
1071 t.Fatalf("Expected bytes of %d or %d, got %d",
1072 totalSize, totalSize-mlen, b)
1073 }
1074
1075 // Make sure max has been set. Since we block after the first message is
1076 // received, MaxPending should be >= total - 1 and <= total
1077 mm, bm, _ := sub.MaxPending()
1078 if mm < total-1 || mm > total {
1079 t.Fatalf("Expected max msgs (%d) to be between %d and %d",
1080 mm, total-1, total)
1081 }
1082 if bm < totalSize-mlen || bm > totalSize {
1083 t.Fatalf("Expected max bytes (%d) to be between %d and %d",
1084 bm, totalSize, totalSize-mlen)
1085 }
1086 // Check that clear works.
1087 sub.ClearMaxPending()
1088 mm, bm, _ = sub.MaxPending()
1089 if mm != 0 {
1090 t.Fatalf("Expected max msgs to be 0 vs %d after clearing", mm)
1091 }
1092 if bm != 0 {
1093 t.Fatalf("Expected max bytes to be 0 vs %d after clearing", bm)
1094 }
1095
1096 close(block)
1097 sub.Unsubscribe()
1098
1099 // These calls should fail once the subscription is closed.
1100 if _, _, err := sub.Pending(); err == nil {
1101 t.Fatal("Calling Pending() on closed subscription should fail")
1102 }
1103 if _, _, err := sub.MaxPending(); err == nil {
1104 t.Fatal("Calling MaxPending() on closed subscription should fail")
1105 }
1106 if err := sub.ClearMaxPending(); err == nil {
1107 t.Fatal("Calling ClearMaxPending() on closed subscription should fail")
1108 }
1109 })
1110 }
1111
1112 func TestAsyncSubscriptionPendingDrain(t *testing.T) {
1113 withServer(t, func(t *testing.T, nc *nats.Conn) {
1114 // Send some messages to ourselves.
1115 total := 100
1116 msg := []byte("0123456789")
1117
1118 sub, _ := nc.Subscribe("foo", func(_ *nats.Msg) {})
1119 defer sub.Unsubscribe()
1120
1121 for range total {
1122 nc.Publish("foo", msg)
1123 }
1124 nc.Flush()
1125
1126 // Wait for all delivered.
1127 waitFor(t, 2*time.Second, 15*time.Millisecond, func() error {
1128 if d, _ := sub.Delivered(); d != int64(total) {
1129 return fmt.Errorf("Wrong delivered count: %v vs %v", d, total)
1130 }
1131 m, b, _ := sub.Pending()
1132 if m != 0 {
1133 return fmt.Errorf("Expected msgs of 0, got %d", m)
1134 }
1135 if b != 0 {
1136 return fmt.Errorf("Expected bytes of 0, got %d", b)
1137 }
1138 return nil
1139 })
1140
1141 sub.Unsubscribe()
1142 if _, err := sub.Delivered(); err == nil {
1143 t.Fatal("Calling Delivered() on closed subscription should fail")
1144 }
1145 })
1146 }
1147
1148 func TestSyncSubscriptionPendingDrain(t *testing.T) {
1149 withServer(t, func(t *testing.T, nc *nats.Conn) {
1150 // Send some messages to ourselves.
1151 total := 100
1152 msg := []byte("0123456789")
1153
1154 sub, _ := nc.SubscribeSync("foo")
1155 defer sub.Unsubscribe()
1156
1157 for range total {
1158 nc.Publish("foo", msg)
1159 }
1160 nc.Flush()
1161
1162 // Wait for all delivered.
1163 for d, _ := sub.Delivered(); d != int64(total); d, _ = sub.Delivered() {
1164 sub.NextMsg(10 * time.Millisecond)
1165 }
1166
1167 m, b, _ := sub.Pending()
1168 if m != 0 {
1169 t.Fatalf("Expected msgs of 0, got %d", m)
1170 }
1171 if b != 0 {
1172 t.Fatalf("Expected bytes of 0, got %d", b)
1173 }
1174
1175 sub.Unsubscribe()
1176 if _, err := sub.Delivered(); err == nil {
1177 t.Fatal("Calling Delivered() on closed subscription should fail")
1178 }
1179 })
1180 }
1181
1182 func TestSyncSubscriptionPending(t *testing.T) {
1183 withServer(t, func(t *testing.T, nc *nats.Conn) {
1184 sub, _ := nc.SubscribeSync("foo")
1185 defer sub.Unsubscribe()
1186
1187 // Send some messages to ourselves.
1188 total := 100
1189 msg := []byte("0123456789")
1190 for range total {
1191 nc.Publish("foo", msg)
1192 }
1193 nc.Flush()
1194
1195 // Test old way
1196 q, _, _ := sub.Pending()
1197 if q != total && q != total-1 {
1198 t.Fatalf("Expected %d or %d, got %d", total, total-1, q)
1199 }
1200
1201 // New way, make sure the same and check bytes.
1202 m, b, _ := sub.Pending()
1203 mlen := len(msg)
1204
1205 if m != total {
1206 t.Fatalf("Expected msgs of %d, got %d", total, m)
1207 }
1208 if b != total*mlen {
1209 t.Fatalf("Expected bytes of %d, got %d", total*mlen, b)
1210 }
1211
1212 // Now drain some down and make sure pending is correct
1213 for range total - 1 {
1214 sub.NextMsg(10 * time.Millisecond)
1215 }
1216 m, b, _ = sub.Pending()
1217 if m != 1 {
1218 t.Fatalf("Expected msgs of 1, got %d", m)
1219 }
1220 if b != mlen {
1221 t.Fatalf("Expected bytes of %d, got %d", mlen, b)
1222 }
1223 })
1224 }
1225
1226 func TestSetPendingLimits(t *testing.T) {
1227 withServer(t, func(t *testing.T, nc *nats.Conn) {
1228 // Override default handler for test.
1229 nc.SetErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, _ error) {})
1230
1231 payload := []byte("hello")
1232 payloadLen := len(payload)
1233 toSend := 100
1234
1235 var sub *nats.Subscription
1236
1237 // Check for invalid values
1238 invalid := func() error {
1239 if err := sub.SetPendingLimits(0, 1); err == nil {
1240 return errors.New("Setting limit with 0 should fail")
1241 }
1242 if err := sub.SetPendingLimits(1, 0); err == nil {
1243 return errors.New("Setting limit with 0 should fail")
1244 }
1245 return nil
1246 }
1247 // function to send messages
1248 send := func(subject string, count int) {
1249 for range count {
1250 if err := nc.Publish(subject, payload); err != nil {
1251 t.Fatalf("Unexpected error on publish: %v", err)
1252 }
1253 }
1254 nc.Flush()
1255 }
1256
1257 // Check pending vs expected values
1258 var limitCount, limitBytes int
1259 var expectedCount, expectedBytes int
1260 checkPending := func() error {
1261 lc, lb, err := sub.PendingLimits()
1262 if err != nil {
1263 return err
1264 }
1265 if lc != limitCount || lb != limitBytes {
1266 return fmt.Errorf("Unexpected limits, expected %v msgs %v bytes, got %v msgs %v bytes",
1267 limitCount, limitBytes, lc, lb)
1268 }
1269 msgs, bytes, err := sub.Pending()
1270 if err != nil {
1271 return fmt.Errorf("Unexpected error getting pending counts: %v", err)
1272 }
1273 if (msgs != expectedCount && msgs != expectedCount-1) ||
1274 (bytes != expectedBytes && bytes != expectedBytes-payloadLen) {
1275 return fmt.Errorf("Unexpected counts, expected %v msgs %v bytes, got %v msgs %v bytes",
1276 expectedCount, expectedBytes, msgs, bytes)
1277 }
1278 return nil
1279 }
1280
1281 recv := make(chan bool)
1282 block := make(chan bool)
1283 cb := func(m *nats.Msg) {
1284 recv <- true
1285 <-block
1286 m.Sub.Unsubscribe()
1287 }
1288 subj := "foo"
1289 sub, err := nc.Subscribe(subj, cb)
1290 if err != nil {
1291 t.Fatalf("Unexpected error on subscribe: %v", err)
1292 }
1293 defer sub.Unsubscribe()
1294 if err := invalid(); err != nil {
1295 t.Fatalf("%v", err)
1296 }
1297 // Check we apply limit only for size
1298 limitCount = -1
1299 limitBytes = (toSend / 2) * payloadLen
1300 if err := sub.SetPendingLimits(limitCount, limitBytes); err != nil {
1301 t.Fatalf("Unexpected error setting limits: %v", err)
1302 }
1303 // Send messages
1304 send(subj, toSend)
1305 // Wait for message to be received
1306 if err := Wait(recv); err != nil {
1307 t.Fatal("Did not get our message")
1308 }
1309 expectedBytes = limitBytes
1310 expectedCount = limitBytes / payloadLen
1311 if err := checkPending(); err != nil {
1312 t.Fatalf("%v", err)
1313 }
1314 // Release callback
1315 block <- true
1316
1317 subj = "bar"
1318 sub, err = nc.Subscribe(subj, cb)
1319 if err != nil {
1320 t.Fatalf("Unexpected error on subscribe: %v", err)
1321 }
1322 defer sub.Unsubscribe()
1323 // Check we apply limit only for count
1324 limitCount = toSend / 4
1325 limitBytes = -1
1326 if err := sub.SetPendingLimits(limitCount, limitBytes); err != nil {
1327 t.Fatalf("Unexpected error setting limits: %v", err)
1328 }
1329 // Send messages
1330 send(subj, toSend)
1331 // Wait for message to be received
1332 if err := Wait(recv); err != nil {
1333 t.Fatal("Did not get our message")
1334 }
1335 expectedCount = limitCount
1336 expectedBytes = limitCount * payloadLen
1337 if err := checkPending(); err != nil {
1338 t.Fatalf("%v", err)
1339 }
1340 // Release callback
1341 block <- true
1342
1343 subj = "baz"
1344 sub, err = nc.SubscribeSync(subj)
1345 if err != nil {
1346 t.Fatalf("Unexpected error on subscribe: %v", err)
1347 }
1348 defer sub.Unsubscribe()
1349 if err := invalid(); err != nil {
1350 t.Fatalf("%v", err)
1351 }
1352 // Check we apply limit only for size
1353 limitCount = -1
1354 limitBytes = (toSend / 2) * payloadLen
1355 if err := sub.SetPendingLimits(limitCount, limitBytes); err != nil {
1356 t.Fatalf("Unexpected error setting limits: %v", err)
1357 }
1358 // Send messages
1359 send(subj, toSend)
1360 expectedBytes = limitBytes
1361 expectedCount = limitBytes / payloadLen
1362 if err := checkPending(); err != nil {
1363 t.Fatalf("%v", err)
1364 }
1365 sub.Unsubscribe()
1366 nc.Flush()
1367
1368 subj = "boz"
1369 sub, err = nc.SubscribeSync(subj)
1370 if err != nil {
1371 t.Fatalf("Unexpected error on subscribe: %v", err)
1372 }
1373 defer sub.Unsubscribe()
1374 // Check we apply limit only for count
1375 limitCount = toSend / 4
1376 limitBytes = -1
1377 if err := sub.SetPendingLimits(limitCount, limitBytes); err != nil {
1378 t.Fatalf("Unexpected error setting limits: %v", err)
1379 }
1380 // Send messages
1381 send(subj, toSend)
1382 expectedCount = limitCount
1383 expectedBytes = limitCount * payloadLen
1384 if err := checkPending(); err != nil {
1385 t.Fatalf("%v", err)
1386 }
1387 sub.Unsubscribe()
1388 nc.Flush()
1389 })
1390 }
1391
1392 func TestSubscriptionTypes(t *testing.T) {
1393 withServer(t, func(t *testing.T, nc *nats.Conn) {
1394 sub, _ := nc.Subscribe("foo", func(_ *nats.Msg) {})
1395 defer sub.Unsubscribe()
1396 if st := sub.Type(); st != nats.AsyncSubscription {
1397 t.Fatalf("Expected AsyncSubscription, got %v", st)
1398 }
1399 // Check Pending
1400 if err := sub.SetPendingLimits(1, 100); err != nil {
1401 t.Fatalf("We should be able to SetPendingLimits()")
1402 }
1403 if _, _, err := sub.Pending(); err != nil {
1404 t.Fatalf("We should be able to call Pending()")
1405 }
1406 sub.Unsubscribe()
1407 if err := sub.SetPendingLimits(1, 100); err == nil {
1408 t.Fatal("Calling SetPendingLimits() on closed subscription should fail")
1409 }
1410 if _, _, err := sub.PendingLimits(); err == nil {
1411 t.Fatal("Calling PendingLimits() on closed subscription should fail")
1412 }
1413
1414 sub, _ = nc.SubscribeSync("foo")
1415 defer sub.Unsubscribe()
1416 if st := sub.Type(); st != nats.SyncSubscription {
1417 t.Fatalf("Expected SyncSubscription, got %v", st)
1418 }
1419 // Check Pending
1420 if err := sub.SetPendingLimits(1, 100); err != nil {
1421 t.Fatalf("We should be able to SetPendingLimits()")
1422 }
1423 if _, _, err := sub.Pending(); err != nil {
1424 t.Fatalf("We should be able to call Pending()")
1425 }
1426 sub.Unsubscribe()
1427 if err := sub.SetPendingLimits(1, 100); err == nil {
1428 t.Fatal("Calling SetPendingLimits() on closed subscription should fail")
1429 }
1430 if _, _, err := sub.PendingLimits(); err == nil {
1431 t.Fatal("Calling PendingLimits() on closed subscription should fail")
1432 }
1433
1434 sub, _ = nc.ChanSubscribe("foo", make(chan *nats.Msg))
1435 defer sub.Unsubscribe()
1436 if st := sub.Type(); st != nats.ChanSubscription {
1437 t.Fatalf("Expected ChanSubscription, got %v", st)
1438 }
1439 // Check Pending
1440 if err := sub.SetPendingLimits(1, 100); err == nil {
1441 t.Fatalf("We should NOT be able to SetPendingLimits() on ChanSubscriber")
1442 }
1443 if _, _, err := sub.Pending(); err == nil {
1444 t.Fatalf("We should NOT be able to call Pending() on ChanSubscriber")
1445 }
1446 if _, _, err := sub.MaxPending(); err == nil {
1447 t.Fatalf("We should NOT be able to call MaxPending() on ChanSubscriber")
1448 }
1449 if err := sub.ClearMaxPending(); err == nil {
1450 t.Fatalf("We should NOT be able to call ClearMaxPending() on ChanSubscriber")
1451 }
1452 if _, _, err := sub.PendingLimits(); err == nil {
1453 t.Fatalf("We should NOT be able to call PendingLimits() on ChanSubscriber")
1454 }
1455 })
1456 }
1457
1458 func TestAutoUnsubOnSyncSubCanStillRespond(t *testing.T) {
1459 withServer(t, func(t *testing.T, nc *nats.Conn) {
1460 subj := nuid.Next()
1461 sub, err := nc.SubscribeSync(subj)
1462 if err != nil {
1463 t.Fatalf("Error susbscribing: %v", err)
1464 }
1465 // When the single message is delivered, the
1466 // auto unsub will reap the subscription removing
1467 // the connection, make sure Respond still works.
1468 if err := sub.AutoUnsubscribe(1); err != nil {
1469 t.Fatalf("Error autounsub: %v", err)
1470 }
1471
1472 inbox := nats.NewInbox()
1473 if err = nc.PublishRequest(subj, inbox, nil); err != nil {
1474 t.Fatalf("Error making request: %v", err)
1475 }
1476
1477 m, err := sub.NextMsg(time.Second)
1478 if err != nil {
1479 t.Fatalf("Error getting next message")
1480 }
1481 if err := m.Respond(nil); err != nil {
1482 t.Fatalf("Error responding: %v", err)
1483 }
1484 })
1485 }
1486
1487 func TestSubscribe_ClosedHandler(t *testing.T) {
1488 withServer(t, func(t *testing.T, nc *nats.Conn) {
1489 ch := make(chan string, 1)
1490 sub, err := nc.Subscribe("foo", func(_ *nats.Msg) {})
1491 if err != nil {
1492 t.Fatalf("Error subscribing: %v", err)
1493 }
1494 sub.SetClosedHandler(func(subj string) {
1495 ch <- subj
1496 })
1497 sub.Unsubscribe()
1498 select {
1499 case subj := <-ch:
1500 if subj != "foo" {
1501 t.Fatalf("Expected 'foo', got '%v'", subj)
1502 }
1503 case <-time.After(1 * time.Second):
1504 t.Fatal("Did not receive closed callback")
1505 }
1506
1507 sub, err = nc.Subscribe("bar", func(_ *nats.Msg) {})
1508 if err != nil {
1509 t.Fatalf("Error subscribing: %v", err)
1510 }
1511 sub.SetClosedHandler(func(subj string) {
1512 ch <- subj
1513 })
1514 sub.Drain()
1515 select {
1516 case subj := <-ch:
1517 if subj != "bar" {
1518 t.Fatalf("Expected 'bar', got '%v'", subj)
1519 }
1520 case <-time.After(1 * time.Second):
1521 t.Fatal("Did not receive closed callback")
1522 }
1523 })
1524 }
1525
1526 func TestSubscriptionEvents(t *testing.T) {
1527 t.Run("default events", func(t *testing.T) {
1528 withServer(t, func(t *testing.T, nc *nats.Conn) {
1529 // disable slow consumer prints
1530 nc.SetErrorHandler(func(c *nats.Conn, s *nats.Subscription, e error) {})
1531
1532 blockChan := make(chan struct{})
1533 sub, err := nc.Subscribe("foo", func(_ *nats.Msg) {
1534 // block in subscription callback
1535 // to force slow consumer
1536 <-blockChan
1537 })
1538 if err != nil {
1539 t.Fatalf("Error subscribing: %v", err)
1540 }
1541 sub.SetPendingLimits(10, 1024)
1542 status := sub.StatusChanged()
1543
1544 // initial status
1545 WaitOnChannel(t, status, nats.SubscriptionActive)
1546
1547 for range 11 {
1548 nc.Publish("foo", []byte("Hello"))
1549 }
1550 WaitOnChannel(t, status, nats.SubscriptionSlowConsumer)
1551 close(blockChan)
1552
1553 sub.Drain()
1554
1555 WaitOnChannel(t, status, nats.SubscriptionDraining)
1556
1557 WaitOnChannel(t, status, nats.SubscriptionClosed)
1558 })
1559 })
1560
1561 t.Run("slow consumer event only", func(t *testing.T) {
1562 withServer(t, func(t *testing.T, nc *nats.Conn) {
1563 blockChan := make(chan struct{})
1564 sub, err := nc.Subscribe("foo", func(_ *nats.Msg) {
1565 // block in subscription callback
1566 // to force slow consumer
1567 <-blockChan
1568 })
1569 // disable slow consumer prints
1570 nc.SetErrorHandler(func(c *nats.Conn, s *nats.Subscription, e error) {})
1571 defer sub.Unsubscribe()
1572 if err != nil {
1573 t.Fatalf("Error subscribing: %v", err)
1574 }
1575 sub.SetPendingLimits(10, 1024)
1576 status := sub.StatusChanged(nats.SubscriptionSlowConsumer)
1577
1578 for range 20 {
1579 nc.Publish("foo", []byte("Hello"))
1580 }
1581 WaitOnChannel(t, status, nats.SubscriptionSlowConsumer)
1582 close(blockChan)
1583
1584 // now try with sync sub
1585 sub, err = nc.SubscribeSync("foo")
1586 if err != nil {
1587 t.Fatalf("Error subscribing: %v", err)
1588 }
1589 defer sub.Unsubscribe()
1590 sub.SetPendingLimits(10, 1024)
1591 status = sub.StatusChanged(nats.SubscriptionSlowConsumer)
1592
1593 for range 20 {
1594 nc.Publish("foo", []byte("Hello"))
1595 }
1596 WaitOnChannel(t, status, nats.SubscriptionSlowConsumer)
1597 })
1598 })
1599
1600 t.Run("return closed channel if subscription is closed", func(t *testing.T) {
1601 withServer(t, func(t *testing.T, nc *nats.Conn) {
1602 sub, err := nc.Subscribe("foo", func(_ *nats.Msg) {})
1603 nc.SetErrorHandler(func(c *nats.Conn, s *nats.Subscription, e error) {})
1604 if err != nil {
1605 t.Fatalf("Error subscribing: %v", err)
1606 }
1607 // Unsubscribe first to set status to SubscriptionClosed.
1608 if err = sub.Unsubscribe(); err != nil {
1609 t.Fatalf("Error unsubscribing: %v", err)
1610 }
1611 // Ensure StatusChanged channel is closed after receiving current status.
1612 statusCh := sub.StatusChanged()
1613 select {
1614 case status := <-statusCh:
1615 if status != nats.SubscriptionClosed {
1616 t.Fatalf("Current subscription status is not closed")
1617 }
1618 case <-time.After(1 * time.Second):
1619 t.Fatalf("StatusChanged() channel does not receive current status")
1620 }
1621 select {
1622 case _, ok := <-statusCh:
1623 if ok {
1624 t.Fatalf("StatusChanged() channel is not closed")
1625 }
1626 default:
1627 t.Fatalf("StatusChanged() channel exists and is blocking")
1628 }
1629 })
1630 })
1631
1632 t.Run("return closed channel without status if not listening for closed", func(t *testing.T) {
1633 withServer(t, func(t *testing.T, nc *nats.Conn) {
1634 sub, err := nc.Subscribe("foo", func(_ *nats.Msg) {})
1635 if err != nil {
1636 t.Fatalf("Error subscribing: %v", err)
1637 }
1638 if err = sub.Unsubscribe(); err != nil {
1639 t.Fatalf("Error unsubscribing: %v", err)
1640 }
1641 statusCh := sub.StatusChanged(nats.SubscriptionSlowConsumer)
1642 select {
1643 case _, ok := <-statusCh:
1644 if ok {
1645 t.Fatalf("Expected channel to be closed without sending a value")
1646 }
1647 default:
1648 t.Fatalf("StatusChanged() channel exists and is blocking")
1649 }
1650 })
1651 })
1652
1653 t.Run("do not block channel if it's not read", func(t *testing.T) {
1654 withServer(t, func(t *testing.T, nc *nats.Conn) {
1655 // disable slow consumer prints
1656 nc.SetErrorHandler(func(c *nats.Conn, s *nats.Subscription, e error) {})
1657
1658 blockChan := make(chan struct{})
1659 sub, err := nc.Subscribe("foo", func(_ *nats.Msg) {
1660 // block in subscription callback
1661 // to force slow consumer
1662 <-blockChan
1663 })
1664 defer sub.Unsubscribe()
1665 if err != nil {
1666 t.Fatalf("Error subscribing: %v", err)
1667 }
1668 sub.SetPendingLimits(10, 1024)
1669 status := sub.StatusChanged()
1670 WaitOnChannel(t, status, nats.SubscriptionActive)
1671
1672 // chan length is 10, so make sure we switch state more times
1673 for range 20 {
1674 // subscription will enter slow consumer state
1675 for range 11 {
1676 nc.Publish("foo", []byte("Hello"))
1677 }
1678
1679 // messages flow normally, status flips to active
1680 for range 10 {
1681 nc.Publish("foo", []byte("Hello"))
1682 blockChan <- struct{}{}
1683 }
1684 }
1685 // do not read from subscription
1686 close(blockChan)
1687 })
1688 })
1689 }
1690
1691 func TestMaxSubscriptionsExceeded(t *testing.T) {
1692 c := newTester(t)
1693 inst := c.CreateServer(t, false, testservice.WithTopLevel("max_subscriptions: 5"))
1694 t.Cleanup(func() { inst.Destroy(t) })
1695
1696 ch := make(chan error)
1697 nc, err := nats.Connect(inst.Servers[0].URL, nats.ErrorHandler(func(c *nats.Conn, s *nats.Subscription, err error) {
1698 ch <- err
1699 }))
1700 if err != nil {
1701 t.Fatalf("Error on connect: %v", err)
1702 }
1703 defer nc.Close()
1704
1705 for range 6 {
1706 s, err := nc.Subscribe("foo", func(_ *nats.Msg) {})
1707 if err != nil {
1708 t.Fatalf("Error subscribing: %v", err)
1709 }
1710 defer s.Unsubscribe()
1711 }
1712
1713 WaitOnChannel(t, ch, nats.ErrMaxSubscriptionsExceeded)
1714
1715 // wait for the server to process the SUBs
1716 time.Sleep(100 * time.Millisecond)
1717 }
1718
1719 func TestClosedHandlerOnConnectionClose(t *testing.T) {
1720 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
1721 closedHandlerCalled := make(chan struct{}, 1)
1722
1723 t.Run("subscribe", func(t *testing.T) {
1724 nc, err := nats.Connect(inst.Servers[0].URL)
1725 if err != nil {
1726 t.Fatalf("Unexpected error: %v", err)
1727 }
1728 sub, err := nc.Subscribe("test.subject", func(m *nats.Msg) {})
1729 if err != nil {
1730 t.Fatalf("Unexpected error: %v", err)
1731 }
1732
1733 sub.SetClosedHandler(func(subject string) {
1734 closedHandlerCalled <- struct{}{}
1735 })
1736
1737 nc.Close()
1738
1739 WaitOnChannel(t, closedHandlerCalled, struct{}{})
1740 })
1741
1742 t.Run("chan subscribe", func(t *testing.T) {
1743 nc, err := nats.Connect(inst.Servers[0].URL)
1744 if err != nil {
1745 t.Fatalf("Unexpected error: %v", err)
1746 }
1747 msgCh := make(chan *nats.Msg, 64)
1748 sub, err := nc.ChanSubscribe("test.subject", msgCh)
1749 if err != nil {
1750 t.Fatalf("Unexpected error: %v", err)
1751 }
1752
1753 sub.SetClosedHandler(func(subject string) {
1754 closedHandlerCalled <- struct{}{}
1755 })
1756
1757 nc.Close()
1758
1759 WaitOnChannel(t, closedHandlerCalled, struct{}{})
1760 })
1761
1762 t.Run("sync subscribe", func(t *testing.T) {
1763 nc, err := nats.Connect(inst.Servers[0].URL)
1764 if err != nil {
1765 t.Fatalf("Unexpected error: %v", err)
1766 }
1767 sub, err := nc.SubscribeSync("test.subject")
1768 if err != nil {
1769 t.Fatalf("Unexpected error: %v", err)
1770 }
1771
1772 sub.SetClosedHandler(func(subject string) {
1773 closedHandlerCalled <- struct{}{}
1774 })
1775
1776 nc.Close()
1777
1778 WaitOnChannel(t, closedHandlerCalled, struct{}{})
1779 })
1780 })
1781 }
1782
1783 const denyFooSubscribeAuthSnippet = `
1784 authorization: {
1785 users = [
1786 {
1787 user: test
1788 password: test
1789 permissions: {
1790 subscribe: {
1791 deny: "foo"
1792 }
1793 }
1794 }
1795 ]
1796 }`
1797
1798 func TestSubscribeSyncPermissionError(t *testing.T) {
1799 c := newTester(t)
1800 inst := c.CreateServer(t, false, testservice.WithAuthorization(denyFooSubscribeAuthSnippet))
1801 t.Cleanup(func() { inst.Destroy(t) })
1802
1803 t.Run("PermissionErrOnSubscribe enabled", func(t *testing.T) {
1804 nc, err := nats.Connect(inst.Servers[0].URL,
1805 nats.UserInfo("test", "test"),
1806 nats.PermissionErrOnSubscribe(true),
1807 nats.ErrorHandler(func(*nats.Conn, *nats.Subscription, error) {}))
1808 if err != nil {
1809 t.Fatalf("Error on connect: %v", err)
1810 }
1811 defer nc.Close()
1812
1813 subs := make([]*nats.Subscription, 0, 100)
1814 for i := range 10 {
1815 var subject string
1816 if i%2 == 0 {
1817 subject = "foo"
1818 } else {
1819 subject = "bar"
1820 }
1821 sub, err := nc.SubscribeSync(subject)
1822 if err != nil {
1823 t.Fatalf("Error on subscribe: %v", err)
1824 }
1825 defer sub.Unsubscribe()
1826 subs = append(subs, sub)
1827 }
1828
1829 for _, sub := range subs {
1830 _, err = sub.NextMsg(100 * time.Millisecond)
1831 if sub.Subject == "foo" {
1832 if !errors.Is(err, nats.ErrPermissionViolation) {
1833 t.Fatalf("Expected permissions violation error, got %v", err)
1834 }
1835 // subsequent calls should return the same error
1836 _, err = sub.NextMsg(100 * time.Millisecond)
1837 if !errors.Is(err, nats.ErrPermissionViolation) {
1838 t.Fatalf("Expected permissions violation error, got %v", err)
1839 }
1840 } else {
1841 if !errors.Is(err, nats.ErrTimeout) {
1842 t.Fatalf("Expected timeout error, got %v", err)
1843 }
1844 }
1845 }
1846 })
1847
1848 t.Run("PermissionErrOnSubscribe disabled", func(t *testing.T) {
1849 nc, err := nats.Connect(inst.Servers[0].URL, nats.UserInfo("test", "test"))
1850 if err != nil {
1851 t.Fatalf("Error on connect: %v", err)
1852 }
1853 defer nc.Close()
1854
1855 // Cause a subscribe error
1856 sub, err := nc.SubscribeSync("foo")
1857 if err != nil {
1858 t.Fatalf("Error on subscribe: %v", err)
1859 }
1860 defer sub.Unsubscribe()
1861
1862 _, err = sub.NextMsg(100 * time.Millisecond)
1863 if !errors.Is(err, nats.ErrTimeout) {
1864 t.Fatalf("Expected timeout error, got %v", err)
1865 }
1866 })
1867 }