-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnatsrouter_test.go
1130 lines (965 loc) · 30.1 KB
/
natsrouter_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
package natsrouter
import (
"bytes"
"compress/flate"
"compress/gzip"
"context"
"encoding/json"
"errors"
"io"
"math/rand"
"strings"
"testing"
"time"
"github.com/nats-io/nats-server/v2/server"
"github.com/nats-io/nats.go"
)
func emptyHandler(msg *NatsMsg) error {
return nil
}
func runServer(opts *server.Options) (*server.Server, error) {
s, err := server.NewServer(opts)
if err != nil || s == nil {
return nil, err
}
// Run server in Go routine.
go s.Start()
// Wait for accept loop(s) to be started
if !s.ReadyForConnections(10 * time.Second) {
return nil, errors.New("Unable to start NATS Server in Go Routine")
}
return s, nil
}
func TestRunServer(t *testing.T) {
opts := &server.Options{Host: "localhost", Port: server.RANDOM_PORT, NoSigs: true}
s, err := runServer(opts)
if err != nil {
t.Fatalf("Could not start NATS server: %v", err)
}
defer s.Shutdown()
// nc, err := nats.Connect(test.DefaultURL)
nc, err := nats.Connect(s.Addr().String())
if err != nil {
t.Fatalf("Could not connect to NATS server: %v", err)
}
defer nc.Close()
}
func TestConnect(t *testing.T) {
// Create test server
opts := &server.Options{Host: "localhost", Port: server.RANDOM_PORT, NoSigs: true}
s, err := runServer(opts)
if err != nil {
t.Fatalf("Could not start NATS server: %v", err)
}
defer s.Shutdown()
// Create router and connect to test server
nr, err := Connect(s.Addr().String())
if err != nil {
t.Fatalf("Could not connect to NATS server: %v", err)
}
defer nr.Close()
}
func TestOptionsConnect(t *testing.T) {
// Create test server
opts := &server.Options{Host: "localhost", Port: server.RANDOM_PORT, NoSigs: true}
s, err := runServer(opts)
if err != nil {
t.Fatalf("Could not start NATS server: %v", err)
}
defer s.Shutdown()
// Create router and connect to test server
rOpts := GetDefaultRouterOptions()
rOpts.NatsOptions.Url = s.Addr().String()
nr, err := rOpts.Connect()
if err != nil {
t.Fatalf("Could not connect to NATS server: %v", err)
}
defer nr.Close()
}
func TestDrain(t *testing.T) {
// Create test server
opts := &server.Options{Host: "localhost", Port: server.RANDOM_PORT, NoSigs: true}
s, err := runServer(opts)
if err != nil {
t.Fatalf("Could not start NATS server: %v", err)
}
defer s.Shutdown()
// Create router and connect to test server
ch := make(chan struct{})
rOpts := RouterOptions{
NatsOptions: nats.Options{
Url: s.Addr().String(),
ClosedCB: func(_ *nats.Conn) {
close(ch)
},
},
}
nr, err := rOpts.Connect()
if err != nil {
t.Fatalf("Could not connect to NATS server: %v", err)
}
nr.Drain()
select {
case <-ch:
default:
t.Error("Channel is not closed")
}
}
func getServer(t *testing.T) *server.Server {
// Create test server
opts := &server.Options{Host: "localhost", Port: server.RANDOM_PORT, NoSigs: true}
s, err := runServer(opts)
if err != nil {
t.Fatalf("Could not start NATS server: %v", err)
}
return s
}
func getServerAndRouter(t *testing.T) (*server.Server, *NatsRouter) {
s := getServer(t)
// Create router and connect to test server
nr, err := Connect(s.Addr().String())
if err != nil {
t.Fatalf("Could not connect to NATS server: %v", err)
}
return s, nr
}
func TestSubjectSubscribe(t *testing.T) {
// Create test server and router
s, nr := getServerAndRouter(t)
defer s.Shutdown()
defer nr.Close()
t.Run("subscribe with single subject", func(t *testing.T) {
sub := nr.Subject("foo")
_, err := sub.Subscribe(emptyHandler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
})
t.Run("subscribe with any subject", func(t *testing.T) {
sub := nr.Subject("foo").Any()
_, err := sub.Subscribe(emptyHandler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
})
t.Run("subscribe with all subject", func(t *testing.T) {
sub := nr.Subject("foo").All()
_, err := sub.Subscribe(emptyHandler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
})
t.Run("subscribe with multiple subjects", func(t *testing.T) {
sub := nr.Subject("a").Subject("b").Subject("c")
_, err := sub.Subscribe(emptyHandler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
got, err := sub.getSubject()
if got != "a.b.c" {
t.Errorf("subject string does not match, expected a.b.c, got %s", got)
}
if err != nil {
t.Errorf("unexpected error: %v", err)
}
})
t.Run("subscribe with invalid subject", func(t *testing.T) {
sub := nr.Subject("foo").All().Subject("bar")
_, err := sub.Subscribe(emptyHandler)
if !errors.Is(err, ErrNonLastAllSubject) {
t.Errorf("expected error '%v', but got '%v'", ErrNonLastAllSubject, err)
}
})
}
func TestQueueSubscribe(t *testing.T) {
// Create test server and router
s, nr := getServerAndRouter(t)
defer s.Shutdown()
defer nr.Close()
sub := nr.Queue("group").Subject("foo")
t.Run("subscribe", func(t *testing.T) {
_, err := sub.Subscribe(emptyHandler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
})
t.Run("unsubscribe", func(t *testing.T) {
// Subscribe and then unsubscribe to test that the subscription is successfully removed.
subscription, err := sub.Subscribe(emptyHandler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
err = subscription.Unsubscribe()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
})
}
func TestNatsRouterPublish(t *testing.T) {
// Create test server and router
s, nr := getServerAndRouter(t)
defer s.Shutdown()
defer nr.Close()
t.Run("publish to subject", func(t *testing.T) {
subject := "foo.bar"
err := nr.Publish(subject, []byte("hello, world!"))
if err != nil {
t.Errorf("unexpected error: %v", err)
}
})
}
func TestMiddlewareChain(t *testing.T) {
// define some middleware functions
middleware1 := func(next NatsCtxHandler) NatsCtxHandler {
return func(msg *NatsMsg) error {
ctx := context.WithValue(msg.Context(), "key1", "value1")
return next(msg.WithContext(ctx))
}
}
middleware2 := func(next NatsCtxHandler) NatsCtxHandler {
return func(msg *NatsMsg) error {
ctx := context.WithValue(msg.Context(), "key2", "value2")
return next(msg.WithContext(ctx))
}
}
// define a final handler function
handler := func(msg *NatsMsg) error {
if msg.Context().Value("key1") != "value1" {
t.Errorf("Expected key1 to be value1")
}
if msg.Context().Value("key2") != "value2" {
t.Errorf("Expected key2 to be value2")
}
// Send response with same content
if err := msg.Respond(msg.Data); err != nil {
t.Errorf("Failed to publish reply: %v", err)
}
return nil
}
// Create test server and router
s, nr := getServerAndRouter(t)
defer s.Shutdown()
// Add middleware
nr = nr.Use(middleware1, middleware2)
defer nr.Close()
// Get underlying connection
nc := nr.Conn()
t.Run("subscribe with middleware to single subject", func(t *testing.T) {
sub := nr.Subject("foo1")
_, err := sub.Subscribe(handler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Create message and send a request
msg := nats.NewMsg("foo1")
msg.Data = []byte("data")
reply, err := nc.RequestMsg(msg, 1*time.Second)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !bytes.Equal(msg.Data, reply.Data) {
t.Errorf("responses do not match, expected %s, received %s", string(msg.Data), string(reply.Data))
}
})
t.Run("subscribe with middleware and queue group to single subject", func(t *testing.T) {
sub := nr.Queue("group").Subject("foo2")
_, err := sub.Subscribe(handler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Create message and send a request
msg := nats.NewMsg("foo2")
msg.Data = []byte("data")
reply, err := nc.RequestMsg(msg, 1*time.Second)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !bytes.Equal(msg.Data, reply.Data) {
t.Errorf("responses do not match, expected %s, received %s", string(msg.Data), string(reply.Data))
}
})
}
func TestEncodedMiddleware(t *testing.T) {
// define some middleware functions
myMiddleware := func(next NatsCtxHandler) NatsCtxHandler {
return func(msg *NatsMsg) error {
ctx := context.WithValue(msg.Context(), "key1", "value1")
return next(msg.WithContext(ctx))
}
}
// Using any type of function without Msg requires "Reply" address to be saved
replyMiddleware := func(next NatsCtxHandler) NatsCtxHandler {
return func(msg *NatsMsg) error {
ctx := context.WithValue(msg.Context(), "reply", msg.Reply)
return next(msg.WithContext(ctx))
}
}
type Person struct {
Name string `json:"name,omitempty"`
Age uint `json:"age,omitempty"`
}
// Create test server and router
s, nr := getServerAndRouter(t)
defer s.Shutdown()
// Add first middleware
nr = nr.Use(myMiddleware)
defer nr.Close()
// Get underlying connection
nc := nr.Conn()
t.Run("subscribe with encoded middleware (*NatsMsg)", func(t *testing.T) {
// Basic function with one parameter
handler := func(msg *NatsMsg) {
if msg.Context().Value("key1") != "value1" {
t.Errorf("Expected key1 to be value1")
}
if err := msg.Respond(msg.Data); err != nil {
t.Errorf("Failed to publish reply: %v", err)
}
}
// Setup middleware, note that the encoding type does not matter
em, err := NewEncodedMiddleware(handler, "default")
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Add middleware
nr2 := nr.Use(em.EncodedMiddleware)
sub := nr2.Subject("foo1")
_, err = sub.Subscribe(emptyHandler) // emptyHandler is never called
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Create message and send a request
msg := nats.NewMsg("foo1")
msg.Data = []byte("data")
reply, err := nc.RequestMsg(msg, 1*time.Second)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !bytes.Equal(msg.Data, reply.Data) {
t.Errorf("responses do not match, expected %s, received %s", string(msg.Data), string(reply.Data))
}
})
t.Run("subscribe with encoded middleware (context.Context, *nats.Msg)", func(t *testing.T) {
// Basic function with context and nats.Msg parameter
handler := func(ctx context.Context, msg *nats.Msg) {
if ctx.Value("key1") != "value1" {
t.Errorf("Expected key1 to be value1")
}
if err := msg.Respond(msg.Data); err != nil {
t.Errorf("Failed to publish reply: %v", err)
}
}
// Setup middleware, note that the encoding type does not matter
em, err := NewEncodedMiddleware(handler, "default")
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Add middleware
nr2 := nr.Use(em.EncodedMiddleware)
sub := nr2.Subject("foo2")
_, err = sub.Subscribe(emptyHandler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Create message and send a request
msg := nats.NewMsg("foo2")
msg.Data = []byte("data")
reply, err := nc.RequestMsg(msg, 1*time.Second)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !bytes.Equal(msg.Data, reply.Data) {
t.Errorf("responses do not match, expected %s, received %s", string(msg.Data), string(reply.Data))
}
})
t.Run("subscribe with encoded middleware (context.Context, *Person)", func(t *testing.T) {
// Basic function with context and json-encoded parameter
handler := func(ctx context.Context, p *Person) {
if ctx.Value("key1") != "value1" {
t.Errorf("Expected key1 to be value1")
}
if p.Name != "someone" {
t.Errorf("Expected name to be someone")
}
reply := ctx.Value("reply").(string)
if err := nc.Publish(reply, []byte(p.Name)); err != nil {
t.Errorf("Failed to publish reply: %v", err)
}
}
// Setup middleware, note that the encoding type does not matter
em, err := NewEncodedMiddleware(handler, "json")
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Add middleware
nr2 := nr.Use(replyMiddleware, em.EncodedMiddleware)
sub := nr2.Subject("foo3")
_, err = sub.Subscribe(emptyHandler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Create message and send a request
msg := nats.NewMsg("foo3")
p := Person{Name: "someone", Age: 25}
msg.Data, err = json.Marshal(p)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
reply, err := nc.RequestMsg(msg, 1*time.Second)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !bytes.Equal([]byte("someone"), reply.Data) {
t.Errorf("responses do not match, expected someone, received %s", string(reply.Data))
}
})
t.Run("subscribe with encoded middleware (context.Context, subject, *Person)", func(t *testing.T) {
// Basic function with context, subject and json-encoded parameter
handler := func(ctx context.Context, subject string, p *Person) {
if ctx.Value("key1") != "value1" {
t.Errorf("Expected key1 to be value1")
}
if p.Name != "someone" {
t.Errorf("Expected name to be someone")
}
if subject != "foo4" {
t.Errorf("Expected subject to be foo")
}
reply := ctx.Value("reply").(string)
if err := nc.Publish(reply, []byte(p.Name)); err != nil {
t.Errorf("Failed to publish reply: %v", err)
}
}
// Setup middleware, note that the encoding type does not matter
em, err := NewEncodedMiddleware(handler, "json")
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Add middleware
nr2 := nr.Use(replyMiddleware, em.EncodedMiddleware)
sub := nr2.Subject("foo4")
_, err = sub.Subscribe(emptyHandler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Create message and send a request
msg := nats.NewMsg("foo4")
p := Person{Name: "someone", Age: 25}
msg.Data, err = json.Marshal(p)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
reply, err := nc.RequestMsg(msg, 1*time.Second)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !bytes.Equal([]byte("someone"), reply.Data) {
t.Errorf("responses do not match, expected someone, received %s", string(reply.Data))
}
})
t.Run("subscribe with encoded middleware (context.Context, *Person)", func(t *testing.T) {
// Basic function with context, subject. reply and json-encoded parameter
handler := func(ctx context.Context, subject, reply string, p *Person) {
if ctx.Value("key1") != "value1" {
t.Errorf("Expected key1 to be value1")
}
if p.Name != "someone" {
t.Errorf("Expected name to be someone")
}
if subject != "foo5" {
t.Errorf("Expected subject to be foo")
}
if err := nc.Publish(reply, []byte(p.Name)); err != nil {
t.Errorf("Failed to publish reply: %v", err)
}
}
em, err := NewEncodedMiddleware(handler, "json")
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Add middleware, note that the replyMiddleware is not needed here
nr2 := nr.Use(em.EncodedMiddleware)
sub := nr2.Subject("foo5")
_, err = sub.Subscribe(emptyHandler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Create message and send a request
msg := nats.NewMsg("foo5")
p := Person{Name: "someone", Age: 25}
msg.Data, err = json.Marshal(p)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
reply, err := nc.RequestMsg(msg, 1*time.Second)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !bytes.Equal([]byte("someone"), reply.Data) {
t.Errorf("responses do not match, expected someone, received %s", string(reply.Data))
}
})
}
func TestError(t *testing.T) {
// define a handler that always fails
errHandler := func(msg *NatsMsg) error {
return errors.New("request failed")
}
t.Run("return default error", func(t *testing.T) {
// Create test server and router
s, nr := getServerAndRouter(t)
defer s.Shutdown()
nc := nr.Conn()
defer nr.Close()
sub := nr.Subject("foo")
_, err := sub.Subscribe(errHandler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Create message and send a request
msg := nats.NewMsg("foo")
msg.Data = []byte("data")
reply, err := nc.RequestMsg(msg, 1*time.Second)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
got := reply.Header.Get("error")
if got != "json" {
t.Errorf("error header does not match, expected %s, got %s", "json", got)
}
errJson := []byte("{\"message\":\"request failed\",\"code\":500}")
if !bytes.Equal(errJson, reply.Data) {
t.Errorf("responses do not match, expected %s, received %s", string(msg.Data), string(reply.Data))
}
})
t.Run("return custom error", func(t *testing.T) {
// Create test server and router
s, _ := getServerAndRouter(t)
defer s.Shutdown()
// Create router and connect to test server
tag := "err"
format := "proto"
nr, err := Connect(s.Addr().String(), WithErrorConfigString(tag, format))
if err != nil {
t.Fatalf("Could not connect to NATS server: %v", err)
}
nc := nr.Conn()
defer nr.Close()
sub := nr.Subject("foo")
_, err = sub.Subscribe(errHandler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Create message and send a request
msg := nats.NewMsg("foo")
msg.Data = []byte("data")
reply, err := nc.RequestMsg(msg, 1*time.Second)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
got, ok := reply.Header[tag]
if !ok {
t.Errorf("error header not received")
} else if got[0] != format {
t.Errorf("error header does not match, expected %s, received %s", format, got[0])
}
errJson := []byte("{\"message\":\"request failed\",\"code\":500}")
if !bytes.Equal(errJson, reply.Data) {
t.Errorf("responses do not match, expected %s, received %s", string(msg.Data), string(reply.Data))
}
})
}
func TestRequestId(t *testing.T) {
// define a handler that always fails
errHandler := func(msg *NatsMsg) error {
return errors.New("request failed")
}
t.Run("return default request id tag", func(t *testing.T) {
// Create test server and router
s, nr := getServerAndRouter(t)
defer s.Shutdown()
nc := nr.Conn()
defer nr.Close()
sub := nr.Subject("foo")
_, err := sub.Subscribe(errHandler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Create message and send a request
msg := nats.NewMsg("foo")
msg.Data = []byte("data")
reqId := "req-1"
msg.Header.Add("request_id", reqId)
reply, err := nc.RequestMsg(msg, 1*time.Second)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
got := reply.Header.Get("request_id")
if got != reqId {
t.Errorf("header request_id does not match, expected %s, received %s", reqId, got)
}
})
t.Run("return customized request id tag", func(t *testing.T) {
// Create test server and router
s := getServer(t)
defer s.Shutdown()
// Create router and connect to test server
tag := "reqid"
nr, err := Connect(s.Addr().String(), WithRequestIdTag(tag))
if err != nil {
t.Fatalf("Could not connect to NATS server: %v", err)
}
nc := nr.Conn()
defer nr.Close()
sub := nr.Subject("foo")
_, err = sub.Subscribe(errHandler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Create message and send a request
msg := nats.NewMsg("foo")
msg.Data = []byte("data")
reqId := "req-1"
msg.Header.Add(tag, reqId)
reply, err := nc.RequestMsg(msg, 1*time.Second)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
got := reply.Header.Get(tag)
if got != reqId {
t.Errorf("header request_id does not match, expected %s, received %s", reqId, got)
}
})
}
func TestChanSubscribe(t *testing.T) {
// Create test server and router
s, nr := getServerAndRouter(t)
defer s.Shutdown()
nc := nr.Conn()
defer nr.Close()
respond := func(ch chan *NatsMsg) {
msg := <-ch
err := msg.RespondWithOriginalHeaders(msg.Data)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
}
t.Run("channel-based subscribe", func(t *testing.T) {
sub := nr.Subject("foo_ch")
ch := make(chan *NatsMsg, 4)
_, err := sub.ChanSubscribe(ch)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Start a function to read the request and send a response
go respond(ch)
// Create message and send a request
msg := nats.NewMsg("foo_ch")
msg.Data = []byte("data")
reqId := "req-1"
msg.Header.Add("request_id", reqId)
reply, err := nc.RequestMsg(msg, 1*time.Second)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
got := reply.Header.Get("request_id")
if got != reqId {
t.Errorf("header request_id does not match, expected %s, received %s", reqId, got)
}
if !bytes.Equal(msg.Data, reply.Data) {
t.Errorf("responses do not match, expected %s, received %s", string(msg.Data), string(reply.Data))
}
})
t.Run("channel-based queue subscribe", func(t *testing.T) {
sub := nr.Queue("group").Subject("foo_queue_ch")
ch := make(chan *NatsMsg, 4)
_, err := sub.ChanSubscribe(ch)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Start a function to read the request and send a response
go respond(ch)
// Create message and send a request
msg := nats.NewMsg("foo_queue_ch")
msg.Data = []byte("data")
reqId := "req-1"
msg.Header.Add("request_id", reqId)
reply, err := nc.RequestMsg(msg, 1*time.Second)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
got := reply.Header.Get("request_id")
if got != reqId {
t.Errorf("header request_id does not match, expected %s, received %s", reqId, got)
}
if !bytes.Equal(msg.Data, reply.Data) {
t.Errorf("responses do not match, expected %s, received %s", string(msg.Data), string(reply.Data))
}
})
}
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789{}[]:,"
func RandBytes(n int) []byte {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Int63()%int64(len(letterBytes))]
}
return b
}
func gzipData(data []byte) ([]byte, error) {
var buf bytes.Buffer
// Compress with gzip
zw := gzip.NewWriter(&buf)
_, err := zw.Write(data)
if err != nil {
return nil, err
}
zw.Close()
return buf.Bytes(), nil
}
func gunzipData(data []byte) ([]byte, error) {
// Decompress with gzip
zr, err := gzip.NewReader(bytes.NewReader(data))
if err != nil {
return nil, err
}
defer zr.Close()
return io.ReadAll(zr)
}
func deflateData(data []byte) ([]byte, error) {
var buf bytes.Buffer
// Compress with deflate
fw, _ := flate.NewWriter(&buf, flate.DefaultCompression)
_, err := fw.Write(data)
if err != nil {
return nil, err
}
fw.Close()
return buf.Bytes(), nil
}
func inflateData(data []byte) ([]byte, error) {
// Decompress with gzip
fr := flate.NewReader(bytes.NewReader(data))
defer fr.Close()
return io.ReadAll(fr)
}
type compressFunc func([]byte) ([]byte, error)
func TestEncoding(t *testing.T) {
shortData := []byte("short")
longData := []byte(strings.Repeat("long", 2000))
shortRandomData := RandBytes(50)
longRandomData := RandBytes(5000)
// A simple echo handler
echoHandler := func(msg *NatsMsg) error {
// Send response with same content
if err := msg.Respond(msg.Data); err != nil {
t.Errorf("Failed to publish reply: %v", err)
}
return nil
}
// Create test server and router
s, nr := getServerAndRouter(t)
defer s.Shutdown()
defer nr.Close()
// Get underlying connection
nc := nr.Conn()
noEncodingTest := func(t *testing.T, subject string, data []byte) {
sub := nr.Subject(subject)
_, err := sub.Subscribe(echoHandler)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Create message and send a request
msg := nats.NewMsg(subject)
msg.Data = data
reply, err := nc.RequestMsg(msg, 1*time.Second)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !bytes.Equal(msg.Data, reply.Data) {
t.Errorf("responses do not match, expected %s, received %s", string(msg.Data), string(reply.Data))
}
if !bytes.Equal(data, reply.Data) {
t.Errorf("response does not match original, expected %s, received %s", string(data), string(reply.Data))
}
}
t.Run("no encoding, short data", func(t *testing.T) {
noEncodingTest(t, "foo_noenc_s", shortData)
})
t.Run("no encoding, long data", func(t *testing.T) {
noEncodingTest(t, "foo_noenc_l", longData)
})
compressClientEncodingTest := func(t *testing.T, subject string, data []byte, hdr string, compress compressFunc) {
sub := nr.Subject(subject)
_, err := sub.Subscribe(func(msg *NatsMsg) error {
// Content should have been unzipped at this point
if !bytes.Equal(data, msg.Data) {
t.Errorf("request data does not match, expected %s, received %s", string(data), string(msg.Data))
}
// Send response with same content
if err := msg.Respond(msg.Data); err != nil {
t.Errorf("Failed to publish reply: %v", err)
}
return nil
})
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Create message with gzipped data
msg := nats.NewMsg(subject)
zipped, err := compress(data)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
msg.Data = zipped
// Add the encoding header
msg.Header.Add("encoding", hdr)
// Send request and verify
reply, err := nc.RequestMsg(msg, 1*time.Second)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !bytes.Equal(data, reply.Data) {
t.Errorf("responses do not match, expected %s, received %s", string(data), string(reply.Data))
}
}
compressServerEncodingTest := func(t *testing.T, subject string, data []byte, hdr string, compressed bool, decompress compressFunc) {
sub := nr.Subject(subject)
_, err := sub.Subscribe(func(msg *NatsMsg) error {
// Content is not compressed, just verify
if !bytes.Equal(data, msg.Data) {
t.Errorf("request data does not match, expected %s, received %s", string(data), string(msg.Data))
}
// Send response with same content, this should compress automatically
if err := msg.Respond(msg.Data); err != nil {
t.Errorf("Failed to publish reply: %v", err)
}
return nil
})
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// Create message with gzipped data
msg := nats.NewMsg(subject)
msg.Data = data
// Add the accept-encoding header
msg.Header.Add("accept-encoding", hdr)
// Send request and verify
reply, err := nc.RequestMsg(msg, 1*time.Second)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
received := reply.Data
if compressed {
received, err = decompress(received)
if err != nil {
t.Errorf("unexpected error: %v", err)
}