-
Notifications
You must be signed in to change notification settings - Fork 38
/
conn_test.go
720 lines (637 loc) · 18.3 KB
/
conn_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
// Copyright 2018 Comcast Cable Communications Management, LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pulsar
import (
"bytes"
"context"
"fmt"
"io"
"sort"
"sync/atomic"
"testing"
"testing/iotest"
"time"
"github.com/Comcast/pulsar-client-go/api"
"github.com/Comcast/pulsar-client-go/frame"
"github.com/golang/protobuf/proto"
)
// mockReadCloser wraps a io.Reader with a no-op Close method.
// It satisfies the io.ReadCloser interface.
type mockReadCloser struct {
io.Reader
closed uint32 // atomically updated number of times Close() was called
closeErr error // return value of Close()
}
func (m *mockReadCloser) Close() error {
atomic.AddUint32(&m.closed, 1)
return m.closeErr
}
func TestConn_Read(t *testing.T) {
f := frame.Frame{
BaseCmd: &api.BaseCommand{
Type: api.BaseCommand_CONNECTED.Enum(),
Connected: &api.CommandConnected{
ProtocolVersion: proto.Int32(9),
ServerVersion: proto.String("Pulsar Server"),
},
},
}
var b bytes.Buffer
if err := f.Encode(&b); err != nil {
t.Fatal(err)
}
c := conn{
rc: &mockReadCloser{
Reader: &b,
},
closedc: make(chan struct{}),
}
var gotFrames []frame.Frame
handler := func(f frame.Frame) { gotFrames = append(gotFrames, f) }
// read should read the frame, then reach
// and return EOF
if err := c.read(handler); err != io.EOF {
t.Fatalf("conn.read() err = %v; expected EOF", err)
}
if got, expected := len(gotFrames), 1; got != expected {
t.Fatalf("conn.read() read %d frame(s); expected %d", got, expected)
}
if got := gotFrames[0]; !got.Equal(f) {
t.Fatalf("got frame:\n%+v\nnot equal to expected frame:\n%+v\n", got, f)
} else {
t.Logf("got frame:\n%+v", got)
}
}
func TestConn_Close(t *testing.T) {
c := conn{
rc: &mockReadCloser{
Reader: new(bytes.Buffer),
},
closedc: make(chan struct{}),
}
// no-op
handler := func(f frame.Frame) {}
// read should reach and return EOF
err := c.read(handler)
if err != io.EOF {
t.Fatalf("conn.read() err = %v; expected EOF", err)
}
t.Logf("conn.read() err (expected) = %v", err)
// closed should unblock
select {
case <-c.closed():
default:
t.Fatal("conn.closed() is blocking; expected to unblock")
}
}
func TestConn_GarbageInput(t *testing.T) {
mrc := &mockReadCloser{
Reader: bytes.NewBufferString("this isn't a valid Pulsar frame"),
}
c := conn{
rc: mrc,
closedc: make(chan struct{}),
}
var gotFrames []frame.Frame
handler := func(f frame.Frame) {
gotFrames = append(gotFrames, f)
}
// read should not be able to decode the frame,
// so it should close the connection and return
err := c.read(handler)
if err == nil {
t.Fatalf("conn.read() err = %v; expected non-nil", err)
}
t.Logf("conn.read() err (expected) = %v", err)
if got, expected := len(gotFrames), 0; got != expected {
t.Fatalf("conn.read() read %d frame(s); expected %d", got, expected)
}
if got, expected := atomic.LoadUint32(&mrc.closed), uint32(1); got != expected {
t.Fatalf("conn.rc.Close() called %d times; expected %d", got, expected)
}
}
func TestConn_TimeoutReader(t *testing.T) {
f := frame.Frame{
BaseCmd: &api.BaseCommand{
Type: api.BaseCommand_CONNECTED.Enum(),
Connected: &api.CommandConnected{
ProtocolVersion: proto.Int32(9),
ServerVersion: proto.String("Pulsar Server"),
},
},
}
var b bytes.Buffer
if err := f.Encode(&b); err != nil {
t.Fatal(err)
}
// the Reader here will return ErrTimeout
// on the second call to Read.
mrc := &mockReadCloser{
Reader: iotest.TimeoutReader(&b),
}
c := conn{
rc: mrc,
closedc: make(chan struct{}),
}
var gotFrames []frame.Frame
handler := func(f frame.Frame) {
gotFrames = append(gotFrames, f)
}
// read should attempt to read the frame,
// then reach and return ErrTimeout
err := c.read(handler)
if err != iotest.ErrTimeout {
t.Fatalf("conn.read() err = %v; expected %v", err, iotest.ErrTimeout)
}
t.Logf("conn.read() err (expected) = %v", err)
if got, expected := len(gotFrames), 0; got != expected {
t.Fatalf("conn.read() read %d frame(s); expected %d", got, expected)
}
}
func TestConn_Read_SlowSrc(t *testing.T) {
f := frame.Frame{
BaseCmd: &api.BaseCommand{
Type: api.BaseCommand_CONNECTED.Enum(),
Connected: &api.CommandConnected{
ProtocolVersion: proto.Int32(9),
ServerVersion: proto.String("Pulsar Server"),
},
},
}
var b bytes.Buffer
if err := f.Encode(&b); err != nil {
t.Fatal(err)
}
c := conn{
// OneByteReader returns a single byte per read,
// regardless of how big its input buffer is.
rc: &mockReadCloser{
Reader: iotest.OneByteReader(&b),
},
closedc: make(chan struct{}),
}
var gotFrames []frame.Frame
handler := func(f frame.Frame) {
gotFrames = append(gotFrames, f)
}
// read should read the frame, then reach
// and return EOF
if err := c.read(handler); err != io.EOF {
t.Fatalf("conn.read() err = %v; expected EOF", err)
}
if got, expected := len(gotFrames), 1; got != expected {
t.Fatalf("conn.read() read %d frame(s); expected %d", got, expected)
}
if got := gotFrames[0]; !got.Equal(f) {
t.Fatalf("got frame:\n%+v\nnot equal to expected frame:\n%+v\n", got, f)
} else {
t.Logf("got frame:\n%+v", got)
}
}
func TestConn_Read_MutliFrame(t *testing.T) {
N := 16
// create input frames
frames := make([]frame.Frame, N)
for i := range frames {
frames[i] = frame.Frame{
BaseCmd: &api.BaseCommand{
Type: api.BaseCommand_MESSAGE.Enum(),
Message: &api.CommandMessage{
ConsumerId: proto.Uint64(uint64(i)),
MessageId: &api.MessageIdData{
LedgerId: proto.Uint64(uint64(i)),
EntryId: proto.Uint64(uint64(i)),
},
},
},
Metadata: &api.MessageMetadata{
ProducerName: proto.String(fmt.Sprintf("test %d", i)),
SequenceId: proto.Uint64(0),
PublishTime: proto.Uint64(1513027321000),
},
Payload: []byte(fmt.Sprintf("test message %d", i)),
}
}
// write frames to read buffer
var b bytes.Buffer
for _, f := range frames {
if err := f.Encode(&b); err != nil {
t.Fatal(err)
}
}
c := conn{
rc: &mockReadCloser{
Reader: &b,
},
closedc: make(chan struct{}),
}
var gotFrames []frame.Frame
handler := func(f frame.Frame) { gotFrames = append(gotFrames, f) }
// read should read the frames, then reach
// and return EOF
if err := c.read(handler); err != io.EOF {
t.Fatalf("conn.read() err = %v; expected EOF", err)
}
if got, expected := len(gotFrames), len(frames); got != expected {
t.Fatalf("conn.read() read %d frame(s); expected %d", got, expected)
}
for i, got := range gotFrames {
if expected := frames[i]; !got.Equal(expected) {
t.Fatalf("got frame:\n%+v\nnot equal to expected frame:\n%+v\n", got, expected)
} else {
t.Logf("got frame:\n%+v", got)
}
}
}
func TestConn_writeFrame(t *testing.T) {
N := 64
// mapping of frame payload to frame.
// Since they will be written in an undetermined ordered,
// this helps look them up and match them.
frames := make([]frame.Frame, N)
for i := 0; i < N; i++ {
payload := fmt.Sprintf("%02d - test message", i) // test expects that payload as string sorts properly
frames[i] = frame.Frame{
BaseCmd: &api.BaseCommand{
Type: api.BaseCommand_MESSAGE.Enum(),
Message: &api.CommandMessage{
ConsumerId: proto.Uint64(uint64(i)),
MessageId: &api.MessageIdData{
LedgerId: proto.Uint64(uint64(i)),
EntryId: proto.Uint64(uint64(i)),
},
},
},
Metadata: &api.MessageMetadata{
ProducerName: proto.String(fmt.Sprintf("test %d", i)),
SequenceId: proto.Uint64(0),
PublishTime: proto.Uint64(1513027321000),
},
Payload: []byte(payload),
}
}
// same buffer is used for reads and writes
var rw bytes.Buffer
c := conn{
rc: &mockReadCloser{
Reader: &rw,
},
w: &rw,
closedc: make(chan struct{}),
}
// write the frames in parallel (order will
// be non-deterministic).
t.Run("writeFrame", func(t *testing.T) {
for _, f := range frames {
f := f
t.Run(string(f.Payload), func(t *testing.T) {
t.Parallel()
if err := c.writeFrame(&f); err != nil {
t.Fatal(err)
}
})
}
})
var gotFrames []frame.Frame
handler := func(f frame.Frame) { gotFrames = append(gotFrames, f) }
// read the encoded frames, which the handler
// will store in `gotFrames`.
if err := c.read(handler); err != io.EOF {
t.Fatalf("conn.read() err = %v; expected EOF", err)
}
// ensure that all the expected frames were read
sort.Slice(gotFrames, func(i, j int) bool {
return string(gotFrames[i].Payload) < string(gotFrames[j].Payload)
})
if got, expected := len(gotFrames), len(frames); got != expected {
t.Fatalf("read %d frames; expected %d", got, expected)
}
for i, f := range frames {
if got, expected := string(gotFrames[i].Payload), string(f.Payload); got != expected {
t.Errorf("frame[%d] payload = %q; expected %q", i, got, expected)
}
}
}
func TestConn_TCP_Read(t *testing.T) {
testFrames := map[string]frame.Frame{
"ping": {
BaseCmd: &api.BaseCommand{
Type: api.BaseCommand_PING.Enum(),
Ping: &api.CommandPing{},
},
},
"pong": {
BaseCmd: &api.BaseCommand{
Type: api.BaseCommand_PONG.Enum(),
Pong: &api.CommandPong{},
},
},
"message": {
BaseCmd: &api.BaseCommand{
Type: api.BaseCommand_MESSAGE.Enum(),
Message: &api.CommandMessage{
ConsumerId: proto.Uint64(1234),
MessageId: &api.MessageIdData{
EntryId: proto.Uint64(84),
LedgerId: proto.Uint64(42),
},
},
},
Metadata: &api.MessageMetadata{
ProducerName: proto.String("test"),
SequenceId: proto.Uint64(12),
PublishTime: proto.Uint64(998877),
},
Payload: []byte("hello!"),
},
}
// create a mock Pulsar server
srvCtx, closeSrv := context.WithCancel(context.Background())
defer closeSrv()
srv, err := newMockPulsarServer(srvCtx)
if err != nil {
t.Fatal(err)
}
t.Logf("Mock server addr: %q", srv.addr)
// create a conn connected to the mock Pulsar server
c, err := newTCPConn(srv.addr, time.Second)
if err != nil {
t.Fatalf("newTCPConn(%q) err = %v; nil expected", srv.addr, err)
}
// wait for the Pulsar server to accept the connection
var srvConn *conn
select {
case srvConn = <-srv.conns:
t.Log("server received connection")
case <-time.After(time.Second):
t.Fatal("timeout waiting for server to receive connection")
}
// start reading frames off the conn
received := make(chan frame.Frame, len(testFrames))
readErr := make(chan error, 1)
go func() {
readErr <- c.read(func(f frame.Frame) { received <- f })
}()
// send frames from the Pulsar server to the conn, and
// ensure that they are received by the conn as expected
for name, expected := range testFrames {
if err := srvConn.writeFrame(&expected); err != nil {
t.Fatalf("writeFrame(%q) err = %v; nil expected", name, err)
}
select {
case err := <-readErr:
t.Fatalf("unexpected conn.read() err = %v", err)
case err := <-srv.errs:
t.Fatalf("unexpected mockPulsarServer err = %v", err)
case <-time.After(time.Second):
t.Fatalf("timeout waiting for frame %q", name)
case got := <-received:
if !got.Equal(expected) {
t.Fatalf("unexpected frame received:\n%+v\nexpected %q:\n%+v", got, name, expected)
}
t.Logf("frame %q received:\n%+v", name, got)
}
}
}
func TestConn_TCP_Write(t *testing.T) {
testFrames := map[string]frame.Frame{
"ping": {
BaseCmd: &api.BaseCommand{
Type: api.BaseCommand_PING.Enum(),
Ping: &api.CommandPing{},
},
},
"pong": {
BaseCmd: &api.BaseCommand{
Type: api.BaseCommand_PONG.Enum(),
Pong: &api.CommandPong{},
},
},
"message": {
BaseCmd: &api.BaseCommand{
Type: api.BaseCommand_MESSAGE.Enum(),
Message: &api.CommandMessage{
ConsumerId: proto.Uint64(1234),
MessageId: &api.MessageIdData{
EntryId: proto.Uint64(84),
LedgerId: proto.Uint64(42),
},
},
},
Metadata: &api.MessageMetadata{
ProducerName: proto.String("test"),
SequenceId: proto.Uint64(12),
PublishTime: proto.Uint64(998877),
},
Payload: []byte("hello!"),
},
}
// create a mock Pulsar server
srvCtx, closeSrv := context.WithCancel(context.Background())
defer closeSrv()
srv, err := newMockPulsarServer(srvCtx)
if err != nil {
t.Fatal(err)
}
t.Logf("Mock server addr: %q", srv.addr)
// create a conn connected to the mock Pulsar server
c, err := newTCPConn(srv.addr, time.Second)
if err != nil {
t.Fatalf("newTCPConn(%q) err = %v; nil expected", srv.addr, err)
}
defer c.close()
// wait for the Pulsar server to accept the connection
var srvConn *conn
select {
case srvConn = <-srv.conns:
t.Log("server received connection")
case <-time.After(time.Second):
t.Fatal("timeout waiting for server to receive connection")
}
srvReceived := make(chan frame.Frame)
go func() {
defer close(srvReceived)
srvConn.read(func(f frame.Frame) {
srvReceived <- f
})
}()
// send frames from the conn to the Pulsar server, and
// ensure that they are received by the server as expected
for name, expected := range testFrames {
var err error
if expected.Metadata == nil {
err = c.sendSimpleCmd(*expected.BaseCmd)
} else {
err = c.sendPayloadCmd(*expected.BaseCmd, *expected.Metadata, expected.Payload)
}
if err != nil {
t.Fatalf("conn.send(%q) err = %v; expected nil", name, err)
}
select {
case err := <-srv.errs:
t.Fatalf("unexpected mockPulsarServer err = %v", err)
case <-time.After(time.Second):
t.Fatalf("timeout waiting for frame %q", name)
case got, ok := <-srvReceived:
if !ok {
t.Fatal("server conn.read() unexpectedly closed")
}
if !got.Equal(expected) {
t.Fatalf("unexpected frame received:\n%+v\nexpected %q:\n%+v", got, name, expected)
}
t.Logf("frame %q received:\n%+v", name, got)
}
}
}
func TestConn_TCP_ReadLocalClose(t *testing.T) {
// create a mock Pulsar server
srvCtx, closeSrv := context.WithCancel(context.Background())
defer closeSrv()
srv, err := newMockPulsarServer(srvCtx)
if err != nil {
t.Fatal(err)
}
t.Logf("Mock server addr: %q", srv.addr)
// create a conn connected to the mock Pulsar server
c, err := newTCPConn(srv.addr, time.Second)
if err != nil {
t.Fatalf("newTCPConn(%q) err = %v; nil expected", srv.addr, err)
}
defer c.close()
// wait for the Pulsar server to accept the connection
var srvConn *conn
select {
case srvConn = <-srv.conns:
t.Log("server received connection")
case <-time.After(time.Second):
t.Fatal("timeout waiting for server to receive connection")
}
// start reading from the remote conn.
// send read errors to srvConnReadErr chan
srvConnReadErr := make(chan error, 1)
go func() {
srvConnReadErr <- srvConn.read(func(f frame.Frame) {})
}()
// start reading from the conn.
// send read errors to readErr chan
readErr := make(chan error, 1)
go func() {
readErr <- c.read(func(f frame.Frame) {})
}()
// close the connection from the local conn's end
if err := c.close(); err != nil {
t.Fatalf("close() err = %v; expected nil", err)
}
select {
case err := <-readErr:
if err == nil {
t.Fatalf("read() err = %v; expected non-nil", err)
}
t.Logf("read() err (expected) = %v", err)
// ensure the connection was closed on the remote end too
select {
case err := <-srvConnReadErr:
t.Logf("remote conn read() err (expected) = %v", err)
case <-time.After(time.Second):
t.Fatal("timeout waiting for remote read() to unblock")
}
case <-time.After(time.Second):
t.Fatal("timeout waiting for read() to unblock")
}
}
func TestConn_TCP_ReadRemoteClose(t *testing.T) {
// create a mock Pulsar server
srvCtx, closeSrv := context.WithCancel(context.Background())
defer closeSrv()
srv, err := newMockPulsarServer(srvCtx)
if err != nil {
t.Fatal(err)
}
t.Logf("Mock server addr: %q", srv.addr)
// create a conn connected to the mock Pulsar server
c, err := newTCPConn(srv.addr, time.Second)
if err != nil {
t.Fatalf("newTCPConn(%q) err = %v; nil expected", srv.addr, err)
}
defer c.close()
// wait for the Pulsar server to accept the connection
var srvConn *conn
select {
case srvConn = <-srv.conns:
t.Log("server received connection")
case <-time.After(time.Second):
t.Fatal("timeout waiting for server to receive connection")
}
// start reading from the conn.
// Send read errors to readErr chan
readErr := make(chan error, 1)
go func() {
readErr <- c.read(func(f frame.Frame) {})
}()
// server initiated connection closure
if err := srvConn.close(); err != nil {
t.Fatal(err)
}
select {
case <-c.closed():
t.Log("server received re-connection")
case <-time.After(time.Second):
t.Fatal("conn.closed() blocked; expected to unblock after connection closure")
}
select {
case err := <-readErr:
if err != io.EOF {
t.Fatalf("read() err = %v; expected io.EOF", err)
}
t.Logf("read() err (expected) = %v", err)
case <-time.After(time.Second):
t.Fatal("timeout waiting for read() to unblock")
}
}
func TestConn_TCP_SendOnClosed(t *testing.T) {
// create a mock Pulsar server
srvCtx, closeSrv := context.WithCancel(context.Background())
defer closeSrv()
srv, err := newMockPulsarServer(srvCtx)
if err != nil {
t.Fatal(err)
}
t.Logf("Mock server addr: %q", srv.addr)
// create a conn connected to the mock Pulsar server
c, err := newTCPConn(srv.addr, time.Second)
if err != nil {
t.Fatalf("newTCPConn(%q) err = %v; nil expected", srv.addr, err)
}
defer c.close()
// wait for the Pulsar server to accept the connection
select {
case <-srv.conns:
t.Log("server received connection")
case <-time.After(time.Second):
t.Fatal("timeout waiting for server to receive connection")
}
// close the local conn
if err := c.close(); err != nil {
t.Fatalf("close() err = %v; expected nil", err)
}
// attempt to send a message on a closed connection
ping := api.BaseCommand{
Type: api.BaseCommand_PING.Enum(),
Ping: &api.CommandPing{},
}
if err := c.sendSimpleCmd(ping); err == nil {
t.Fatalf("sendSimpleCmd() err = %v; expected non-nil for a closed conn", err)
} else {
t.Logf("sendSimpleCmd() err (expected for a closed conn) = %v", err)
}
}