/
server_test.go
7301 lines (6522 loc) · 194 KB
/
server_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016-2017 Apcera Inc. All rights reserved.
package server
import (
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
natsd "github.com/nats-io/gnatsd/server"
natsdTest "github.com/nats-io/gnatsd/test"
"github.com/nats-io/go-nats"
"github.com/nats-io/go-nats-streaming"
"github.com/nats-io/go-nats-streaming/pb"
"github.com/nats-io/nats-streaming-server/logger"
"github.com/nats-io/nats-streaming-server/spb"
"github.com/nats-io/nats-streaming-server/stores"
"github.com/nats-io/nuid"
)
const (
clusterName = DefaultClusterID
clientName = "me"
)
// So that we can pass tests and benchmarks...
type tLogger interface {
Fatalf(format string, args ...interface{})
Errorf(format string, args ...interface{})
}
var (
defaultDataStore string
testLogger logger.Logger
errOnPurpose = errors.New("On purpose")
)
func init() {
tmpDir, err := ioutil.TempDir(".", "data_server_")
if err != nil {
panic("Could not create tmp dir")
}
if err := os.Remove(tmpDir); err != nil {
panic(fmt.Errorf("Error removing temp directory: %v", err))
}
defaultDataStore = tmpDir
// Set debug and trace for this file.
defaultOptions.Trace = true
defaultOptions.Debug = true
// For FT tests, reduce the HB/Timeout intervals
setFTTestsHBInterval()
// Dummy/no-op Logger
testLogger = logger.NewStanLogger()
}
func stackFatalf(t tLogger, f string, args ...interface{}) {
lines := make([]string, 0, 32)
msg := fmt.Sprintf(f, args...)
lines = append(lines, msg)
// Generate the Stack of callers:
for i := 1; true; i++ {
_, file, line, ok := runtime.Caller(i)
if !ok {
break
}
msg := fmt.Sprintf("%d - %s:%d", i, file, line)
lines = append(lines, msg)
}
t.Fatalf("%s", strings.Join(lines, "\n"))
}
func msgStoreFirstAndLastSequence(t tLogger, ms stores.MsgStore) (uint64, uint64) {
f, l, err := ms.FirstAndLastSequence()
if err != nil {
stackFatalf(t, "Error getting first and last sequence: %v", err)
}
return f, l
}
func msgStoreFirstMsg(t tLogger, ms stores.MsgStore) *pb.MsgProto {
m, err := ms.FirstMsg()
if err != nil {
stackFatalf(t, "Error getting sequence first message: %v", err)
}
return m
}
func msgStoreState(t tLogger, ms stores.MsgStore) (int, uint64) {
n, b, err := ms.State()
if err != nil {
stackFatalf(t, "Error getting message state: %v", err)
}
return n, b
}
func channelsGet(t tLogger, cs *channelStore, name string) *channel {
c := cs.get(name)
if c == nil {
stackFatalf(t, "Channel %q should exist", name)
}
return c
}
// Helper function to shutdown last, a server that is being restarted in a test.
func shutdownRestartedServerOnTestExit(s **StanServer) {
srv := *s
srv.Shutdown()
srv = nil
}
// Helper function to shutdown last, a NATS server that is being restarted in a test.
func shutdownRestartedNATSServerOnTestExit(s **natsd.Server) {
srv := *s
srv.Shutdown()
srv = nil
}
// Helper function that checks that the number returned by function `f`
// is equal to `expected`, otherwise fails.
func checkCount(t tLogger, expected int, f func() (string, int)) {
if label, count := f(); count != expected {
stackFatalf(t, "Incorrect number of %s, expected %v got %v", label, expected, count)
}
}
// Helper function that waits that the number returned by function `f`
// is equal to `expected` for a certain period of time, otherwise fails.
func waitForCount(t tLogger, expected int, f func() (string, int)) {
ok := false
label := ""
count := 0
timeout := time.Now().Add(5 * time.Second)
for !ok && time.Now().Before(timeout) {
label, count = f()
if count != expected {
time.Sleep(10 * time.Millisecond)
continue
}
ok = true
}
if !ok {
stackFatalf(t, "Timeout waiting to get %v %s, got %v", expected, label, count)
}
}
// Helper function that fails if number of clients is not as expected
func checkClients(t tLogger, s *StanServer, expected int) {
checkCount(t, expected, func() (string, int) { return getClientsCountFunc(s) })
}
// Helper function that waits for a while to get the expected number of clients,
// otherwise fails.
func waitForNumClients(t tLogger, s *StanServer, expected int) {
waitForCount(t, expected, func() (string, int) { return getClientsCountFunc(s) })
}
// Helper function that returns the number of clients
func getClientsCountFunc(s *StanServer) (string, int) {
return "clients", s.clients.count()
}
// Helper function that fails if number of subscriptions is not as expected
func checkSubs(t tLogger, s *StanServer, ID string, expected int) []*subState {
// Since we need to return the array and we want the array to match
// the expected value, use the "public" API here.
subs := s.clients.getSubs(ID)
checkCount(t, expected, func() (string, int) { return "subscriptions", len(subs) })
return subs
}
// Helper function that waits for a while to get the expected number of subscriptions,
// otherwise fails.
func waitForNumSubs(t tLogger, s *StanServer, ID string, expected int) {
waitForCount(t, expected, func() (string, int) {
// We avoid getting a copy of the subscriptions array here
// by directly returning the length of the array.
c := s.clients.lookup(ID)
c.RLock()
defer c.RUnlock()
return "subscriptions", len(c.subs)
})
}
func waitForAcks(t tLogger, s *StanServer, ID string, subID uint64, expected int) {
subs := s.clients.getSubs(ID)
var sub *subState
for _, s := range subs {
s.RLock()
sID := s.ID
s.RUnlock()
if sID == subID {
sub = s
break
}
}
if sub == nil {
stackFatalf(t, "Subscription %v not found", subID)
}
waitForCount(t, 0, func() (string, int) {
sub.RLock()
count := len(sub.acksPending)
sub.RUnlock()
return "ack pending", count
})
}
func createConnectionWithNatsOpts(t tLogger, clientName string,
natsOpts ...nats.Option) (stan.Conn, *nats.Conn) {
opts := nats.DefaultOptions
opts.Servers = []string{nats.DefaultURL}
for _, opt := range natsOpts {
if err := opt(&opts); err != nil {
stackFatalf(t, "Unexpected error on setting options: %v", err)
}
}
nc, err := opts.Connect()
if err != nil {
stackFatalf(t, "Unexpected error on connect: %v", err)
}
sc, err := stan.Connect(clusterName, clientName, stan.NatsConn(nc))
if err != nil {
nc.Close()
stackFatalf(t, "Unexpected error on connect: %v", err)
}
return sc, nc
}
func NewDefaultConnection(t tLogger) stan.Conn {
sc, err := stan.Connect(clusterName, clientName)
if err != nil {
stackFatalf(t, "Expected to connect correctly, got err %v", err)
}
return sc
}
func cleanupDatastore(t *testing.T, dir string) {
if err := os.RemoveAll(dir); err != nil {
stackFatalf(t, "Error cleaning up datastore: %v", err)
}
}
// Dumb wait program to sync on callbacks, etc... Will timeout
func Wait(ch chan bool) error {
return WaitTime(ch, 5*time.Second)
}
func WaitTime(ch chan bool, timeout time.Duration) error {
select {
case <-ch:
return nil
case <-time.After(timeout):
}
return errors.New("timeout")
}
func runServerWithOpts(t *testing.T, sOpts *Options, nOpts *natsd.Options) *StanServer {
s, err := RunServerWithOpts(sOpts, nOpts)
if err != nil {
stackFatalf(t, err.Error())
}
return s
}
func runServer(t *testing.T, clusterName string) *StanServer {
s, err := RunServer(clusterName)
if err != nil {
stackFatalf(t, err.Error())
}
return s
}
// RunServerWithDebugTrace is a helper to assist debugging
func RunServerWithDebugTrace(opts *Options, enableDebug, enableTrace bool) (*StanServer, error) {
var sOpts *Options
if opts == nil {
sOpts = GetDefaultOptions()
} else {
sOpts = opts.Clone()
}
nOpts := natsd.Options{}
sOpts.Debug = enableDebug
sOpts.Trace = enableTrace
nOpts.NoLog = false
nOpts.NoSigs = true
sOpts.EnableLogging = true
return RunServerWithOpts(sOpts, &nOpts)
}
type testChannelStoreFailStore struct{ stores.Store }
func (s *testChannelStoreFailStore) CreateChannel(name string) (*stores.Channel, error) {
return nil, errOnPurpose
}
func TestChannelStore(t *testing.T) {
s := runServer(t, clusterName)
defer s.Shutdown()
cs := newChannelStore(s.store)
if cs.get("foo") != nil {
t.Fatal("Nothing should be returned")
}
c, err := cs.createChannel(s, "foo")
if err != nil {
t.Fatalf("Error creating channel: %v", err)
}
c2 := cs.get("foo")
if c2 != c {
t.Fatalf("Channels should be same, got %v vs %v", c2, c)
}
c3, err := cs.createChannel(s, "foo")
if err != nil {
t.Fatalf("Error creating channel: %v", err)
}
if c3 != c {
t.Fatalf("Channels should be same, got %v vs %v", c3, c)
}
c4, err := cs.createChannel(s, "bar")
if err != nil {
t.Fatalf("Error creating channel: %v", err)
}
if cs.count() != 2 {
t.Fatalf("Expected 2 channels, got %v", err)
}
channels := cs.getAll()
for k, v := range channels {
if k != "foo" && k != "bar" {
t.Fatalf("Unexpected channel name: %v", k)
}
if k == "foo" && v != c {
t.Fatalf("Unexpected channel for foo, expected %v, got %v", c, v)
} else if k == "bar" && v != c4 {
t.Fatalf("Unexpected channel for bar, expected %v, got %v", c4, v)
}
}
if _, _, err := cs.msgsState("baz"); err == nil || !strings.Contains(err.Error(), "not found") {
t.Fatalf("Channel baz does not exist, call should have failed, got %v", err)
}
c.store.Msgs.Store([]byte("foo"))
c4.store.Msgs.Store([]byte("bar"))
if n, _, err := cs.msgsState(""); n != 2 || err != nil {
t.Fatalf("Expected 2 messages, got %v err=%v", n, err)
}
// Produce store failure
cs.Lock()
cs.store = &testChannelStoreFailStore{Store: cs.store}
cs.Unlock()
if c, err := cs.createChannel(s, "error"); c != nil || err == nil {
t.Fatalf("Should have failed, got %v err=%v", c, err)
}
}
func TestRunServer(t *testing.T) {
// Test passing nil options
s := runServerWithOpts(t, nil, nil)
s.Shutdown()
// Test passing stan options, nil nats options
opts := GetDefaultOptions()
s = runServerWithOpts(t, opts, nil)
defer s.Shutdown()
clusterID := s.ClusterID()
if clusterID != clusterName {
t.Fatalf("Expected cluster ID of %s, found %s\n", clusterName, clusterID)
}
s.Shutdown()
// Test passing nil stan options, some nats options
nOpts := &natsd.Options{}
nOpts.NoLog = true
nOpts.NoSigs = true
s = runServerWithOpts(t, nil, nOpts)
defer s.Shutdown()
}
type dummyLogger struct {
sync.Mutex
msg string
}
func (d *dummyLogger) log(format string, args ...interface{}) {
d.Lock()
d.msg = fmt.Sprintf(format, args...)
d.Unlock()
}
func (d *dummyLogger) Noticef(format string, args ...interface{}) {
d.log(format, args...)
}
func (d *dummyLogger) Debugf(format string, args ...interface{}) {
d.log(format, args...)
}
func (d *dummyLogger) Tracef(format string, args ...interface{}) {
d.log(format, args...)
}
func (d *dummyLogger) Errorf(format string, args ...interface{}) {
d.log(format, args...)
}
func (d *dummyLogger) Fatalf(format string, args ...interface{}) {
d.log(format, args...)
}
func TestRunServerFailureLogsCause(t *testing.T) {
d := &dummyLogger{}
sOpts := GetDefaultOptions()
sOpts.NATSServerURL = "nats://localhost:4444"
sOpts.CustomLogger = d
// We expect the server to fail to start
s, err := RunServerWithOpts(sOpts, nil)
if err == nil {
s.Shutdown()
t.Fatal("Expected error, got none")
}
// We should get a trace in the log
if !strings.Contains(d.msg, "available for connection") {
t.Fatalf("Expected to get a cause as invalid connection, got: %v", d.msg)
}
}
func TestServerLoggerDebugAndTrace(t *testing.T) {
sOpts := GetDefaultOptions()
sOpts.EnableLogging = true
sOpts.Debug = true
sOpts.Trace = true
oldStderr := os.Stderr
r, w, _ := os.Pipe()
defer func() {
os.Stderr = oldStderr
r.Close()
}()
os.Stderr = w
done := make(chan bool, 1)
buf := make([]byte, 1024)
out := make([]byte, 0)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-done:
return
default:
n, _ := r.Read(buf)
out = append(out, buf[:n]...)
}
}
}()
s, err := RunServerWithOpts(sOpts, nil)
if err != nil {
t.Fatalf("Error running server: %v", err)
}
s.Shutdown()
// Signal that we are done (the channel is buffered)
done <- true
// If the go routine is sitting on a read, make it break out
// (calling r.Close() would produce races)
w.Write([]byte("*"))
wg.Wait()
// This is a bit dependent on what we currently print with
// trace and debug. May need to be adjusted.
str := string(out)
if !strings.Contains(str, "NATS conn opts") || !strings.Contains(str, "Publish subject") {
t.Fatalf("Expected tracing to include debug and trace, got %v", out)
}
}
func TestDefaultOptions(t *testing.T) {
opts := GetDefaultOptions()
opts.Debug = !defaultOptions.Debug
opts2 := GetDefaultOptions()
if opts2.Debug == opts.Debug {
t.Fatal("Modified original default options")
}
}
func TestOptionsClone(t *testing.T) {
opts := GetDefaultOptions()
opts.Trace = true
opts.PerChannel = make(map[string]*stores.ChannelLimits)
cl := &stores.ChannelLimits{}
cl.MaxMsgs = 100
opts.PerChannel["foo"] = cl
clone := opts.Clone()
if !reflect.DeepEqual(opts, clone) {
t.Fatalf("Expected %#v, got %#v", opts, clone)
}
// Change a field
opts.Trace = false
// Expecting the clone to now be different
if reflect.DeepEqual(opts, clone) {
t.Fatal("Expected clone to be different after original changed, was not")
}
// Revert the field change
opts.Trace = true
// Should be same again
if !reflect.DeepEqual(opts, clone) {
t.Fatalf("Expected %#v, got %#v", opts, clone)
}
// Change a per channel's element
cl.MaxMsgs = 50
// Expecting the clone to now be different
if reflect.DeepEqual(opts, clone) {
t.Fatal("Expected clone to be different after original changed, was not")
}
// Add one channel to original
cl2 := *cl
opts.PerChannel["bar"] = &cl2
// Verify it is not added to the cloned.
if _, exist := clone.PerChannel["bar"]; exist {
t.Fatal("The channel bar should not be in the cloned options")
}
}
func TestDoubleShutdown(t *testing.T) {
s := runServer(t, clusterName)
s.Shutdown()
ch := make(chan bool)
go func() {
s.Shutdown()
ch <- true
}()
if err := Wait(ch); err != nil {
t.Fatal("Second shutdown blocked")
}
}
func TestServerStates(t *testing.T) {
s := runServer(t, clusterName)
defer s.Shutdown()
checkState(t, s, Standalone)
s.Shutdown()
checkState(t, s, Shutdown)
// FT states are checked in ft_test.go
}
type response interface {
Unmarshal([]byte) error
}
func checkServerResponse(nc *nats.Conn, subj string, expectedError error, r response) error {
resp, err := nc.Request(subj, []byte("dummy"), time.Second)
if err != nil {
return fmt.Errorf("Unexpected error on publishing request: %v", err)
}
if err := r.Unmarshal(resp.Data); err != nil {
return fmt.Errorf("Unexpected response object: %v", err)
}
// All our protos have the Error field.
v := reflect.Indirect(reflect.ValueOf(r))
f := v.FieldByName("Error")
if !f.IsValid() {
return fmt.Errorf("Field Error not found in the response: %v", f)
}
connErr := f.String()
if connErr != expectedError.Error() {
return fmt.Errorf("Expected response to be %q, got %q", expectedError.Error(), connErr)
}
return nil
}
func TestInvalidRequests(t *testing.T) {
s := runServer(t, clusterName)
defer s.Shutdown()
// Use a bare NATS connection to send incorrect requests
nc, err := nats.Connect(nats.DefaultURL)
if err != nil {
t.Fatalf("Unexpected error on connect: %v", err)
}
defer nc.Close()
// Send a dummy message on the STAN connect subject
// Get the connect subject
connSubj := fmt.Sprintf("%s.%s", s.opts.DiscoverPrefix, clusterName)
if err := checkServerResponse(nc, connSubj, ErrInvalidConnReq,
&pb.ConnectResponse{}); err != nil {
t.Fatalf("%v", err)
}
// Send a dummy message on the STAN publish subject
if err := checkServerResponse(nc, s.info.Publish+".foo", ErrInvalidPubReq,
&pb.PubAck{}); err != nil {
t.Fatalf("%v", err)
}
// Send a dummy message on the STAN subscription init subject
if err := checkServerResponse(nc, s.info.Subscribe, ErrInvalidSubReq,
&pb.SubscriptionResponse{}); err != nil {
t.Fatalf("%v", err)
}
// Send a dummy message on the STAN subscription unsub subject
if err := checkServerResponse(nc, s.info.Unsubscribe, ErrInvalidUnsubReq,
&pb.SubscriptionResponse{}); err != nil {
t.Fatalf("%v", err)
}
// Send a dummy message on the STAN subscription close subject
if err := checkServerResponse(nc, s.info.SubClose, ErrInvalidUnsubReq,
&pb.SubscriptionResponse{}); err != nil {
t.Fatalf("%v", err)
}
// Send a dummy message on the STAN close subject
if err := checkServerResponse(nc, s.info.Close, ErrInvalidCloseReq,
&pb.CloseResponse{}); err != nil {
t.Fatalf("%v", err)
}
}
func TestClientIDIsValid(t *testing.T) {
s := runServer(t, clusterName)
defer s.Shutdown()
// Use a bare NATS connection to send incorrect requests
nc, err := nats.Connect(nats.DefaultURL)
if err != nil {
t.Fatalf("Unexpected error on connect: %v", err)
}
defer nc.Close()
// Get the connect subject
connSubj := fmt.Sprintf("%s.%s", s.opts.DiscoverPrefix, clusterName)
invalidClientIDs := []string{"", "id with spaces", "id:with:columns",
"id,with,commas", "id.with.dots", "id with spaces, commas and: columns and dots.",
"idWithLotsOfNotAllowedCharacters!@#$%^&*()"}
for _, cID := range invalidClientIDs {
req := &pb.ConnectRequest{ClientID: cID, HeartbeatInbox: "hbInbox"}
b, _ := req.Marshal()
resp, err := nc.Request(connSubj, b, time.Second)
if err != nil {
t.Fatalf("Unexpected error on publishing request: %v", err)
}
r := &pb.ConnectResponse{}
err = r.Unmarshal(resp.Data)
if err != nil {
t.Fatalf("Unexpected response object: %v", err)
}
if r.Error != ErrInvalidClientID.Error() {
t.Fatal("Expected error, got none")
}
}
validClientIDs := []string{"id", "id_with_underscores", "id-with-hypens"}
for _, cID := range validClientIDs {
req := &pb.ConnectRequest{ClientID: cID, HeartbeatInbox: "hbInbox"}
b, _ := req.Marshal()
resp, err := nc.Request(connSubj, b, time.Second)
if err != nil {
t.Fatalf("Unexpected error on publishing request: %v", err)
}
r := &pb.ConnectResponse{}
err = r.Unmarshal(resp.Data)
if err != nil {
t.Fatalf("Unexpected response object: %v", err)
}
if r.Error != "" {
t.Fatalf("Unexpected response error: %v", r.Error)
}
}
}
func sendInvalidSubRequest(s *StanServer, nc *nats.Conn, req *pb.SubscriptionRequest, expectedErr error) error {
b, err := req.Marshal()
if err != nil {
return fmt.Errorf("Error during marshal: %v", err)
}
rep, err := nc.Request(s.info.Subscribe, b, time.Second)
if err != nil {
return fmt.Errorf("Unexpected error: %v", err)
}
// Check response
subRep := &pb.SubscriptionResponse{}
subRep.Unmarshal(rep.Data)
// Expect error
if subRep.Error != expectedErr.Error() {
return fmt.Errorf("Expected error %v, got %v", expectedErr.Error(), subRep.Error)
}
return nil
}
func TestInvalidSubRequest(t *testing.T) {
s := runServer(t, clusterName)
defer s.Shutdown()
// Use a bare NATS connection to send incorrect requests
nc, err := nats.Connect(nats.DefaultURL)
if err != nil {
t.Fatalf("Unexpected error on connect: %v", err)
}
defer nc.Close()
// This test is very dependent on the validity tests performed
// in StanServer.processSubscriptionRequest(). Any cahnge there
// may require changes here.
// Create empty request
req := &pb.SubscriptionRequest{}
// We have already tested corrupted SusbcriptionRequests
// (as in Unmarshal errors) in TestInvalidRequests. Here, we check
// validity of request's fields.
// Send this empty request, clientID is missing
if err := sendInvalidSubRequest(s, nc, req, ErrMissingClient); err != nil {
t.Fatalf("%v", err)
}
// Set a clientID so we move on to next check
req.ClientID = clientName
// Test invalid AckWait values
req.AckWaitInSecs = 0
if err := sendInvalidSubRequest(s, nc, req, ErrInvalidAckWait); err != nil {
t.Fatalf("%v", err)
}
req.AckWaitInSecs = -1
if err := sendInvalidSubRequest(s, nc, req, ErrInvalidAckWait); err != nil {
t.Fatalf("%v", err)
}
// Test invalid MaxInflight values
req.AckWaitInSecs = 1
req.MaxInFlight = 0
if err := sendInvalidSubRequest(s, nc, req, ErrInvalidMaxInflight); err != nil {
t.Fatalf("%v", err)
}
req.MaxInFlight = -1
if err := sendInvalidSubRequest(s, nc, req, ErrInvalidMaxInflight); err != nil {
t.Fatalf("%v", err)
}
// Test invalid StartPosition values
req.MaxInFlight = 1
req.StartPosition = pb.StartPosition_NewOnly - 1
if err := sendInvalidSubRequest(s, nc, req, ErrInvalidStart); err != nil {
t.Fatalf("%v", err)
}
req.StartPosition = pb.StartPosition_First + 1
if err := sendInvalidSubRequest(s, nc, req, ErrInvalidStart); err != nil {
t.Fatalf("%v", err)
}
// Test invalid subjects
req.StartPosition = pb.StartPosition_First
req.Subject = "foo*.bar"
if err := sendInvalidSubRequest(s, nc, req, ErrInvalidSubject); err != nil {
t.Fatalf("%v", err)
}
// Other kinds of invalid subject
req.Subject = "foo.bar*"
if err := sendInvalidSubRequest(s, nc, req, ErrInvalidSubject); err != nil {
t.Fatalf("%v", err)
}
req.Subject = "foo.>.*"
if err := sendInvalidSubRequest(s, nc, req, ErrInvalidSubject); err != nil {
t.Fatalf("%v", err)
}
// Test Queue Group DurableName
req.Subject = "foo"
req.QGroup = "queue"
req.DurableName = "dur:name"
if err := sendInvalidSubRequest(s, nc, req, ErrInvalidDurName); err != nil {
t.Fatalf("%v", err)
}
// Reset those
req.QGroup = ""
req.DurableName = ""
// Now we should have an error that says that we can't find client ID
// (that is, client was not registered).
if err := sendInvalidSubRequest(s, nc, req, fmt.Errorf("can't find clientID: %v", clientName)); err != nil {
t.Fatalf("%v", err)
}
// There should be no client created
checkClients(t, s, 0)
// But channel "foo" should have been created though
if s.channels.count() == 0 {
t.Fatal("Expected channel foo to have been created")
}
// Create a durable
sc := NewDefaultConnection(t)
defer sc.Close()
dur, err := sc.Subscribe("foo", func(_ *stan.Msg) {}, stan.DurableName("dur"))
if err != nil {
t.Fatalf("Unexpected error on subscribe: %v", err)
}
// Close durable
if err := dur.Close(); err != nil {
t.Fatalf("Error closing durable: %v", err)
}
// Close client
sc.Close()
// Ensure this is processed
checkClients(t, s, 0)
// Try to update the durable now that client does not exist.
req.ClientID = clientName
req.Subject = "foo"
req.DurableName = "dur"
if err := sendInvalidSubRequest(s, nc, req, fmt.Errorf("can't find clientID: %v", clientName)); err != nil {
t.Fatalf("%v", err)
}
}
func sendInvalidUnsubRequest(s *StanServer, nc *nats.Conn, req *pb.UnsubscribeRequest) error {
b, err := req.Marshal()
if err != nil {
return fmt.Errorf("Error during marshal: %v", err)
}
rep, err := nc.Request(s.info.Unsubscribe, b, time.Second)
if err != nil {
return fmt.Errorf("Unexpected error: %v", err)
}
// Check response
subRep := &pb.SubscriptionResponse{}
subRep.Unmarshal(rep.Data)
// Expect error
if subRep.Error == "" {
return fmt.Errorf("Expected error, got none")
}
return nil
}
func TestInvalidUnsubRequest(t *testing.T) {
s := runServer(t, clusterName)
defer s.Shutdown()
// Use a bare NATS connection to send incorrect requests
nc, err := nats.Connect(nats.DefaultURL)
if err != nil {
t.Fatalf("Unexpected error on connect: %v", err)
}
defer nc.Close()
sc, err := stan.Connect(clusterName, clientName, stan.NatsConn(nc))
if err != nil {
t.Fatalf("Unexpected error on connect: %v", err)
}
// Create a valid subscription first
sub, err := sc.Subscribe("foo", func(_ *stan.Msg) {})
if err != nil {
t.Fatalf("Unexpected error on subscribe: %v", err)
}
// Verify server state. Client should be created
client := s.clients.lookup(clientName)
if client == nil {
t.Fatal("A client should have been created")
}
subs := checkSubs(t, s, clientName, 1)
// Create empty request
req := &pb.UnsubscribeRequest{}
// Send this empty request
if err := sendInvalidUnsubRequest(s, nc, req); err != nil {
t.Fatalf("%v", err)
}
// Unsubscribe for a subject we did not subscribe to
req.Subject = "bar"
if err := sendInvalidUnsubRequest(s, nc, req); err != nil {
t.Fatalf("%v", err)
}
// Invalid ack inbox
req.Subject = "foo"
req.ClientID = clientName
req.Inbox = "wrong"
if err := sendInvalidUnsubRequest(s, nc, req); err != nil {
t.Fatalf("%v", err)
}
// Correct subject, inbox, but invalid ClientID
req.Subject = "foo"
req.Inbox = subs[0].AckInbox
req.ClientID = "wrong"
if err := sendInvalidUnsubRequest(s, nc, req); err != nil {
t.Fatalf("%v", err)
}
// Valid unsubscribe
if err := sub.Unsubscribe(); err != nil {
t.Fatalf("Unexpected error on unsubscribe: %v\n", err)
}
time.Sleep(100 * time.Millisecond)
// Check that sub's has been removed.
checkSubs(t, s, clientName, 0)
}
func TestDuplicateClientIDs(t *testing.T) {
s := runServer(t, clusterName)
defer s.Shutdown()
c1 := NewDefaultConnection(t)
defer c1.Close()
if c2, err := stan.Connect(clusterName, clientName); err == nil || err.Error() != ErrInvalidClient.Error() {
if c2 != nil {
c2.Close()
}
t.Fatalf("Expected to get error %q, got %q", ErrInvalidClient, err)
}
// Check that there only one client registered
checkClients(t, s, 1)
}
func TestRedelivery(t *testing.T) {
s := runServer(t, clusterName)
defer s.Shutdown()
sc, err := stan.Connect(clusterName, clientName)
if err != nil {
t.Fatalf("Unexpected error on connect: %v", err)
}
defer sc.Close()
rch := make(chan bool)
cb := func(m *stan.Msg) {
if m.Redelivered {
m.Ack()
rch <- true
}
}
// Create a plain sub
if _, err := sc.Subscribe("foo", cb, stan.SetManualAckMode(),
stan.AckWait(time.Second)); err != nil {
t.Fatalf("Unexpected error on subscribe: %v", err)
}
// Send first message
if err := sc.Publish("foo", []byte("hello")); err != nil {
t.Fatalf("Unexpected error on publish: %v", err)
}
// Add a delay before the next message
time.Sleep(500 * time.Millisecond)
// Send second message
if err := sc.Publish("foo", []byte("hello")); err != nil {
t.Fatalf("Unexpected error on publish: %v", err)
}
subs := checkSubs(t, s, clientName, 1)
func(sub *subState) {
sub.RLock()
defer sub.RUnlock()
if sub.acksPending == nil || len(sub.acksPending) != 2 {
t.Fatalf("Expected to have two ackPending, got %v", len(sub.acksPending))
}
if sub.ackTimer == nil {