Debian Codegraph @

test/ws_test.go

raw
1 // Copyright 2023 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package test
15
16 import (
17 "bytes"
18 "crypto/tls"
19 "encoding/binary"
20 "errors"
21 "fmt"
22 "math/rand"
23 "net"
24 "net/http"
25 "runtime"
26 "strings"
27 "sync"
28 "sync/atomic"
29 "testing"
30 "time"
31
32 "github.com/nats-io/nats.go"
33 "github.com/nats-io/nuid"
34 testservice "github.com/synadia-io/orbit.go/ntf-client"
35 )
36
37 // wsPlainBody returns a websocket{} snippet for a plaintext (no TLS) listener
38 // on the auto-reserved "websocket" port. compress toggles per-message deflate.
39 func wsPlainBody(compress bool) string {
40 inner := "port: {{ .Ports.websocket }}\n no_tls: true"
41 if compress {
42 inner += "\n compression: true"
43 }
44 return fmt.Sprintf("websocket {\n %s\n}", inner)
45 }
46
47 // wsTLSBody returns a websocket{} snippet with a tls sub-block referencing the
48 // server cert/key/ca mounted into the tester container. compress toggles
49 // per-message deflate.
50 // wsTLSBody returns a websocket{} body that wires the managed TLS cert/key
51 // (exposed by the tester via .TLS.CertFile/.TLS.KeyFile) into the websocket
52 // listener. Requires the create call to also include WithGeneratedTLS.
53 func wsTLSBody(compress bool) string {
54 inner := `port: {{ .Ports.websocket }}
55 tls {
56 cert_file: "{{ .TLS.CertFile }}"
57 key_file: "{{ .TLS.KeyFile }}"
58 }`
59 if compress {
60 inner += "\n compression: true"
61 }
62 return fmt.Sprintf("websocket {\n %s\n}", inner)
63 }
64
65 // wsPort returns the auto-reserved websocket port for the first server of inst,
66 // failing the test if it was not published.
67 func wsPort(t *testing.T, inst *testservice.Instance) int {
68 t.Helper()
69 p := inst.Servers[0].Ports["websocket"]
70 if p == 0 {
71 t.Fatalf("websocket port not reserved/published for instance %s", inst.ID)
72 }
73 return p
74 }
75
76 func TestWSBasic(t *testing.T) {
77 c := newTester(t)
78 inst := c.CreateServer(t, false, testservice.WithWebSocket(wsPlainBody(false)))
79 t.Cleanup(func() { inst.Destroy(t) })
80
81 url := fmt.Sprintf("ws://%s:%d", testerHost(t), wsPort(t, inst))
82 nc, err := nats.Connect(url)
83 if err != nil {
84 t.Fatalf("Error on connect: %v", err)
85 }
86 defer nc.Close()
87
88 sub, err := nc.SubscribeSync("foo")
89 if err != nil {
90 t.Fatalf("Error on subscribe: %v", err)
91 }
92
93 msgs := make([][]byte, 100)
94 for i := 0; i < len(msgs); i++ {
95 msg := make([]byte, rand.Intn(70000))
96 for j := 0; j < len(msg); j++ {
97 msg[j] = 'A' + byte(rand.Intn(26))
98 }
99 msgs[i] = msg
100 }
101 for i, msg := range msgs {
102 if err := nc.Publish("foo", msg); err != nil {
103 t.Fatalf("Error on publish: %v", err)
104 }
105 // Make sure that masking does not overwrite user data
106 if !bytes.Equal(msgs[i], msg) {
107 t.Fatalf("User content has been changed: %v, got %v", msgs[i], msg)
108 }
109 }
110
111 for i := 0; i < len(msgs); i++ {
112 msg, err := sub.NextMsg(time.Second)
113 if err != nil {
114 t.Fatalf("Error getting next message: %v", err)
115 }
116 if !bytes.Equal(msgs[i], msg.Data) {
117 t.Fatalf("Expected message: %v, got %v", msgs[i], msg)
118 }
119 }
120 }
121
122 func TestWSControlFrames(t *testing.T) {
123 c := newTester(t)
124 inst := c.CreateServer(t, false, testservice.WithWebSocket(wsPlainBody(false)))
125 t.Cleanup(func() { inst.Destroy(t) })
126 srv := inst.Servers[0]
127
128 rch := make(chan bool, 10)
129 ncSub, err := nats.Connect(srv.URL,
130 nats.ReconnectWait(50*time.Millisecond),
131 nats.ReconnectHandler(func(_ *nats.Conn) { rch <- true }),
132 )
133 if err != nil {
134 t.Fatalf("Error on connect: %v", err)
135 }
136 defer ncSub.Close()
137
138 sub, err := ncSub.SubscribeSync("foo")
139 if err != nil {
140 t.Fatalf("Error on subscribe: %v", err)
141 }
142 if err := ncSub.Flush(); err != nil {
143 t.Fatalf("Error on flush: %v", err)
144 }
145
146 dch := make(chan error, 10)
147 url := fmt.Sprintf("ws://%s:%d", testerHost(t), wsPort(t, inst))
148 nc, err := nats.Connect(url,
149 nats.ReconnectWait(50*time.Millisecond),
150 nats.DisconnectErrHandler(func(_ *nats.Conn, err error) { dch <- err }),
151 nats.ReconnectHandler(func(_ *nats.Conn) { rch <- true }),
152 )
153 if err != nil {
154 t.Fatalf("Error on connect: %v", err)
155 }
156 defer nc.Close()
157
158 // Shutdown the server, which should send a close message, which by
159 // spec the client will try to echo back.
160 inst.StopServer(t, srv)
161
162 select {
163 case <-dch:
164 // OK
165 case <-time.After(time.Second):
166 t.Fatal("Should have been disconnected")
167 }
168
169 inst.StartServer(t, srv)
170
171 // Wait for both connections to reconnect
172 if err := Wait(rch); err != nil {
173 t.Fatalf("Should have reconnected: %v", err)
174 }
175 if err := Wait(rch); err != nil {
176 t.Fatalf("Should have reconnected: %v", err)
177 }
178 // Even if the first connection reconnects, there is no guarantee
179 // that the resend of SUB has yet been processed by the server.
180 // Doing a flush here will give us the guarantee.
181 if err := ncSub.Flush(); err != nil {
182 t.Fatalf("Error on flush: %v", err)
183 }
184
185 // Publish and close connection.
186 if err := nc.Publish("foo", []byte("msg")); err != nil {
187 t.Fatalf("Error on publish: %v", err)
188 }
189 if err := nc.Flush(); err != nil {
190 t.Fatalf("Error on flush: %v", err)
191 }
192 nc.Close()
193
194 if _, err := sub.NextMsg(time.Second); err != nil {
195 t.Fatalf("Did not get message: %v", err)
196 }
197 }
198
199 func TestWSConcurrentConns(t *testing.T) {
200 c := newTester(t)
201 inst := c.CreateServer(t, false, testservice.WithWebSocket(wsPlainBody(false)))
202 t.Cleanup(func() { inst.Destroy(t) })
203
204 url := fmt.Sprintf("ws://%s:%d", testerHost(t), wsPort(t, inst))
205
206 total := 50
207 errCh := make(chan error, total)
208 wg := sync.WaitGroup{}
209 wg.Add(total)
210 for i := 0; i < total; i++ {
211 go func() {
212 defer wg.Done()
213
214 nc, err := nats.Connect(url)
215 if err != nil {
216 errCh <- fmt.Errorf("Error on connect: %v", err)
217 return
218 }
219 defer nc.Close()
220
221 sub, err := nc.SubscribeSync(nuid.Next())
222 if err != nil {
223 errCh <- fmt.Errorf("Error on subscribe: %v", err)
224 return
225 }
226 nc.Publish(sub.Subject, []byte("here"))
227 if _, err := sub.NextMsg(time.Second); err != nil {
228 errCh <- err
229 }
230 }()
231 }
232 wg.Wait()
233 select {
234 case e := <-errCh:
235 t.Fatal(e.Error())
236 default:
237 }
238 }
239
240 func TestWSCompression(t *testing.T) {
241 msgSize := rand.Intn(40000)
242 for _, test := range []struct {
243 name string
244 srvCompression bool
245 cliCompression bool
246 }{
247 {"srv_off_cli_off", false, false},
248 {"srv_off_cli_on", false, true},
249 {"srv_on_cli_off", true, false},
250 {"srv_on_cli_on", true, true},
251 } {
252 t.Run(test.name, func(t *testing.T) {
253 c := newTester(t)
254 inst := c.CreateServer(t, false, testservice.WithWebSocket(wsPlainBody(test.srvCompression)))
255 t.Cleanup(func() { inst.Destroy(t) })
256
257 url := fmt.Sprintf("ws://%s:%d", testerHost(t), wsPort(t, inst))
258 var opts []nats.Option
259 if test.cliCompression {
260 opts = append(opts, nats.Compression(true))
261 }
262 nc, err := nats.Connect(url, opts...)
263 if err != nil {
264 t.Fatalf("Error on connect: %v", err)
265 }
266 defer nc.Close()
267
268 sub, err := nc.SubscribeSync("foo")
269 if err != nil {
270 t.Fatalf("Error on subscribe: %v", err)
271 }
272
273 msgs := make([][]byte, 100)
274 for i := 0; i < len(msgs); i++ {
275 msg := make([]byte, msgSize)
276 for j := 0; j < len(msg); j++ {
277 msg[j] = 'A'
278 }
279 msgs[i] = msg
280 }
281 for i, msg := range msgs {
282 if err := nc.Publish("foo", msg); err != nil {
283 t.Fatalf("Error on publish: %v", err)
284 }
285 // Make sure that compression/masking does not touch user data
286 if !bytes.Equal(msgs[i], msg) {
287 t.Fatalf("User content has been changed: %v, got %v", msgs[i], msg)
288 }
289 }
290
291 for i := 0; i < len(msgs); i++ {
292 msg, err := sub.NextMsg(time.Second)
293 if err != nil {
294 t.Fatalf("Error getting next message (%d): %v", i+1, err)
295 }
296 if !bytes.Equal(msgs[i], msg.Data) {
297 t.Fatalf("Expected message (%d): %v, got %v", i+1, msgs[i], msg)
298 }
299 }
300 })
301 }
302 }
303
304 func TestWSWithTLS(t *testing.T) {
305 for _, test := range []struct {
306 name string
307 compression bool
308 }{
309 {"without compression", false},
310 {"with compression", true},
311 } {
312 t.Run(test.name, func(t *testing.T) {
313 c := newTester(t)
314 inst := c.CreateServer(t, false,
315 managedTLSOpts(t, testservice.TLSServerOnly()),
316 testservice.WithWebSocket(wsTLSBody(test.compression)),
317 )
318 t.Cleanup(func() { inst.Destroy(t) })
319
320 host := testerHost(t)
321 port := wsPort(t, inst)
322
323 var copts []nats.Option
324 if test.compression {
325 copts = append(copts, nats.Compression(true))
326 }
327
328 // Check that we fail to connect without proper TLS configuration.
329 nc, err := nats.Connect(fmt.Sprintf("ws://%s:%d", host, port), copts...)
330 if err == nil {
331 if nc != nil {
332 nc.Close()
333 }
334 t.Fatal("Expected error, got none")
335 }
336
337 // Same but with wss protocol, which should translate to TLS, however,
338 // since we used self signed certificates, this should fail without
339 // asking to skip server cert verification.
340 nc, err = nats.Connect(fmt.Sprintf("wss://%s:%d", host, port), copts...)
341 // The verifier error wording is platform-dependent: Linux/Go x509
342 // says "unknown authority"; older macOS Security framework said
343 // "is not standards compliant" (missing SCTs); newer macOS just
344 // says "is not trusted". Accept any of the three.
345 if err == nil || (!strings.Contains(err.Error(), "authority") &&
346 !strings.Contains(err.Error(), "compliant") &&
347 !strings.Contains(err.Error(), "not trusted")) {
348 if nc != nil {
349 nc.Close()
350 }
351 t.Fatalf("Expected error about unknown authority: %v", err)
352 }
353
354 // Skip server verification and we should be good.
355 copts = append(copts, nats.Secure(&tls.Config{InsecureSkipVerify: true}))
356 nc, err = nats.Connect(fmt.Sprintf("wss://%s:%d", host, port), copts...)
357 if err != nil {
358 t.Fatalf("Error on connect: %v", err)
359 }
360 defer nc.Close()
361
362 sub, err := nc.SubscribeSync("foo")
363 if err != nil {
364 t.Fatalf("Error on subscribe: %v", err)
365 }
366 if err := nc.Publish("foo", []byte("hello")); err != nil {
367 t.Fatalf("Error on publish: %v", err)
368 }
369 if msg, err := sub.NextMsg(time.Second); err != nil {
370 t.Fatalf("Did not get message: %v", err)
371 } else if got := string(msg.Data); got != "hello" {
372 t.Fatalf("Expected %q, got %q", "hello", got)
373 }
374 })
375 }
376 }
377
378 type testSkipTLSDialer struct {
379 dialer *net.Dialer
380 skipTLS bool
381 }
382
383 func (sd *testSkipTLSDialer) Dial(network, address string) (net.Conn, error) {
384 return sd.dialer.Dial(network, address)
385 }
386
387 func (sd *testSkipTLSDialer) SkipTLSHandshake() bool {
388 return sd.skipTLS
389 }
390
391 func TestWSWithTLSCustomDialer(t *testing.T) {
392 c := newTester(t)
393 inst := c.CreateServer(t, false,
394 managedTLSOpts(t, testservice.TLSServerOnly()),
395 testservice.WithWebSocket(wsTLSBody(false)),
396 )
397 t.Cleanup(func() { inst.Destroy(t) })
398
399 host := testerHost(t)
400 port := wsPort(t, inst)
401
402 sd := &testSkipTLSDialer{
403 dialer: &net.Dialer{
404 Timeout: 2 * time.Second,
405 },
406 skipTLS: true,
407 }
408
409 // Connect with CustomDialer that fails since TLSHandshake is disabled.
410 copts := make([]nats.Option, 0)
411 copts = append(copts, nats.Secure(&tls.Config{InsecureSkipVerify: true}))
412 copts = append(copts, nats.SetCustomDialer(sd))
413 _, err := nats.Connect(fmt.Sprintf("wss://%s:%d", host, port), copts...)
414 if err == nil {
415 t.Fatalf("Expected error on connect: %v", err)
416 }
417 if err.Error() != `invalid websocket connection` {
418 t.Logf("Expected invalid websocket connection: %v", err)
419 }
420
421 // Retry with the dialer.
422 copts = make([]nats.Option, 0)
423 sd = &testSkipTLSDialer{
424 dialer: &net.Dialer{
425 Timeout: 2 * time.Second,
426 },
427 skipTLS: false,
428 }
429 copts = append(copts, nats.Secure(&tls.Config{InsecureSkipVerify: true}))
430 copts = append(copts, nats.SetCustomDialer(sd))
431 nc, err := nats.Connect(fmt.Sprintf("wss://%s:%d", host, port), copts...)
432 if err != nil {
433 t.Fatalf("Unexpected error on connect: %v", err)
434 }
435 defer nc.Close()
436 }
437
438 func TestWSGossipAndReconnect(t *testing.T) {
439 c := newTester(t)
440 // 2-node cluster with a websocket listener on each node. The standard NATS
441 // port's advertise comes from the tester's NATS_ADVERTISE env var; the
442 // websocket block carries its own advertise because the listener has a
443 // separate port and address-family from the client port.
444 host := testerHost(t)
445 wsBody := fmt.Sprintf("websocket {\n port: {{ .Ports.websocket }}\n no_tls: true\n advertise: \"%s:{{ .Ports.websocket }}\"\n}", host)
446 clusterInst := c.CreateCluster(t, 2, false, testservice.WithWebSocket(wsBody))
447 t.Cleanup(func() { clusterInst.Destroy(t) })
448
449 s1 := clusterInst.Servers[0]
450 if s1.Ports["websocket"] == 0 {
451 t.Fatalf("websocket port not reserved/published for instance %s", clusterInst.ID)
452 }
453
454 rch := make(chan bool, 10)
455 url := fmt.Sprintf("ws://%s:%d", host, s1.Ports["websocket"])
456 nc, err := nats.Connect(url,
457 nats.ReconnectWait(50*time.Millisecond),
458 nats.ReconnectHandler(func(_ *nats.Conn) { rch <- true }),
459 )
460 if err != nil {
461 t.Fatalf("Error on connect: %v", err)
462 }
463 defer nc.Close()
464
465 timeout := time.Now().Add(time.Second)
466 for time.Now().Before(timeout) {
467 if len(nc.Servers()) > 1 {
468 break
469 }
470 time.Sleep(15 * time.Millisecond)
471 }
472 if len(nc.Servers()) == 1 {
473 t.Fatal("Did not discover server 2")
474 }
475 clusterInst.StopServer(t, s1)
476
477 // Wait for reconnect
478 if err := Wait(rch); err != nil {
479 t.Fatalf("Did not reconnect: %v", err)
480 }
481 }
482
483 func TestWSStress(t *testing.T) {
484 // Enable this test only when wanting to stress test the system, say after
485 // some changes in the library or if a bug is found. Also, don't run it
486 // with the `-race` flag!
487 t.SkipNow()
488 // Total producers (there will be 2 per subject)
489 prods := 4
490 // Total messages sent
491 total := int64(1000000)
492 // Total messages received, there is 2 consumer per subject
493 totalRecv := 2 * total
494 // We will create a "golden" slice from which sent messages
495 // will be a subset of. Receivers will check that the content
496 // match the expected content.
497 maxPayloadSize := 100000
498 mainPayload := make([]byte, maxPayloadSize)
499 for i := 0; i < len(mainPayload); i++ {
500 mainPayload[i] = 'A' + byte(rand.Intn(26))
501 }
502 for _, test := range []struct {
503 name string
504 compress bool
505 }{
506 {"no_compression", false},
507 {"with_compression", true},
508 } {
509 t.Run(test.name, func(t *testing.T) {
510 c := newTester(t)
511 inst := c.CreateServer(t, false, testservice.WithWebSocket(wsPlainBody(test.compress)))
512 t.Cleanup(func() { inst.Destroy(t) })
513
514 url := fmt.Sprintf("ws://%s:%d", testerHost(t), wsPort(t, inst))
515
516 var count int64
517 consDoneCh := make(chan struct{}, 1)
518 errCh := make(chan error, 1)
519 prodDoneCh := make(chan struct{}, prods)
520
521 pushErr := func(e error) {
522 select {
523 case errCh <- e:
524 default:
525 }
526 }
527
528 createConn := func() *nats.Conn {
529 t.Helper()
530 nc, err := nats.Connect(url,
531 nats.Compression(test.compress),
532 nats.ErrorHandler(func(_ *nats.Conn, sub *nats.Subscription, err error) {
533 if sub != nil {
534 err = fmt.Errorf("Subscription on %q - err=%v", sub.Subject, err)
535 }
536 pushErr(err)
537 }))
538 if err != nil {
539 t.Fatalf("Error connecting: %v", err)
540 }
541 return nc
542 }
543
544 cb := func(m *nats.Msg) {
545 if len(m.Data) < 4 {
546 pushErr(fmt.Errorf("Message payload too small: %+v", m.Data))
547 return
548 }
549 ps := int(binary.BigEndian.Uint32(m.Data[:4]))
550 if ps > maxPayloadSize {
551 pushErr(fmt.Errorf("Invalid message size: %v", ps))
552 return
553 }
554 if !bytes.Equal(m.Data[4:4+ps], mainPayload[:ps]) {
555 pushErr(errors.New("invalid content"))
556 return
557 }
558 if atomic.AddInt64(&count, 1) == totalRecv {
559 consDoneCh <- struct{}{}
560 }
561 }
562
563 subjects := []string{"foo", "bar"}
564 for _, subj := range subjects {
565 for i := 0; i < 2; i++ {
566 nc := createConn()
567 defer nc.Close()
568 sub, err := nc.Subscribe(subj, cb)
569 if err != nil {
570 t.Fatalf("Error on subscribe: %v", err)
571 }
572 sub.SetPendingLimits(-1, -1)
573 if err := nc.Flush(); err != nil {
574 t.Fatalf("Error on flush: %v", err)
575 }
576 }
577 }
578
579 msgsPerProd := int(total / int64(prods))
580 prodPerSubj := prods / len(subjects)
581 for _, subj := range subjects {
582 for i := 0; i < prodPerSubj; i++ {
583 go func(subj string) {
584 defer func() { prodDoneCh <- struct{}{} }()
585
586 nc := createConn()
587 defer nc.Close()
588
589 for i := 0; i < msgsPerProd; i++ {
590 // Have 80% of messages being rather small (<=1024)
591 maxSize := 1024
592 if rand.Intn(100) > 80 {
593 maxSize = maxPayloadSize
594 }
595 ps := rand.Intn(maxSize)
596 msg := make([]byte, 4+ps)
597 binary.BigEndian.PutUint32(msg, uint32(ps))
598 copy(msg[4:], mainPayload[:ps])
599 if err := nc.Publish(subj, msg); err != nil {
600 pushErr(err)
601 return
602 }
603 }
604 nc.Flush()
605 }(subj)
606 }
607 }
608
609 for i := 0; i < prods; i++ {
610 select {
611 case <-prodDoneCh:
612 case e := <-errCh:
613 t.Fatal(e)
614 }
615 }
616 // Now wait for all consumers to be done.
617 <-consDoneCh
618 })
619 }
620 }
621
622 func TestWSNoDeadlockOnAuthFailure(t *testing.T) {
623 c := newTester(t)
624 authOpts := singleUserPassOpts(`authorization {
625 user: user
626 password: pwd
627 timeout: 1
628 }`)
629 opts := append([]testservice.CreateOption{testservice.WithWebSocket(wsPlainBody(false))}, authOpts...)
630 inst := c.CreateServer(t, false, opts...)
631 t.Cleanup(func() { inst.Destroy(t) })
632
633 tm := time.AfterFunc(3*time.Second, func() {
634 buf := make([]byte, 1000000)
635 n := runtime.Stack(buf, true)
636 panic(fmt.Sprintf("Test has probably deadlocked!\n%s\n", buf[:n]))
637 })
638
639 if _, err := nats.Connect(fmt.Sprintf("ws://%s:%d", testerHost(t), wsPort(t, inst))); err == nil {
640 t.Fatal("Expected auth error, did not get any error")
641 }
642
643 tm.Stop()
644 }
645
646 func TestWsWithCustomHeaders(t *testing.T) {
647 c := newTester(t)
648 inst := c.CreateServer(t, false, testservice.WithWebSocket(wsPlainBody(false)))
649 t.Cleanup(func() { inst.Destroy(t) })
650
651 url := fmt.Sprintf("ws://%s:%d", testerHost(t), wsPort(t, inst))
652
653 staticHeader := make(http.Header, 0)
654 staticHeader.Set("Authorization", "Bearer Random Token")
655 headerProvider := func() (http.Header, error) {
656 return staticHeader, nil
657 }
658
659 for _, test := range []struct {
660 name string
661 connectionOptions []nats.Option
662 wantErr bool
663 }{
664 {
665 name: "Failure 1: Both headers and handler present",
666 connectionOptions: []nats.Option{
667 nats.WebSocketConnectionHeadersHandler(headerProvider),
668 nats.WebSocketConnectionHeaders(staticHeader),
669 },
670 wantErr: true,
671 },
672 {
673 name: "Success 1: Headers present as static headers",
674 connectionOptions: []nats.Option{
675 nats.WebSocketConnectionHeaders(staticHeader),
676 },
677 wantErr: false,
678 },
679 {
680 name: "Success 2: Header supplied through handler",
681 connectionOptions: []nats.Option{
682 nats.WebSocketConnectionHeadersHandler(headerProvider),
683 },
684 wantErr: false,
685 },
686 } {
687 t.Run(test.name, func(t *testing.T) {
688 nc, err := nats.Connect(url, test.connectionOptions...)
689 if err != nil && test.wantErr {
690 return
691 }
692 if err != nil && !test.wantErr {
693 t.Fatalf("Did not expect error, found error: %v", err)
694 }
695 defer nc.Close()
696 sub, err := nc.SubscribeSync("foo")
697 if err != nil {
698 t.Fatalf("Error on subscribe: %v", err)
699 }
700
701 msgs := make([][]byte, 100)
702 for i := 0; i < len(msgs); i++ {
703 msg := make([]byte, 100)
704 for j := 0; j < len(msg); j++ {
705 msg[j] = 'A'
706 }
707 msgs[i] = msg
708 }
709 for i, msg := range msgs {
710 if err := nc.Publish("foo", msg); err != nil {
711 t.Fatalf("Error on publish: %v", err)
712 }
713 // Make sure that compression/masking does not touch user data
714 if !bytes.Equal(msgs[i], msg) {
715 t.Fatalf("User content has been changed: %v, got %v", msgs[i], msg)
716 }
717 }
718
719 for i := 0; i < len(msgs); i++ {
720 msg, err := sub.NextMsg(time.Second)
721 if err != nil {
722 t.Fatalf("Error getting next message (%d): %v", i+1, err)
723 }
724 if !bytes.Equal(msgs[i], msg.Data) {
725 t.Fatalf("Expected message (%d): %v, got %v", i+1, msgs[i], msg)
726 }
727 }
728 })
729 }
730 }