forked from meshifyiot/paho.mqtt.golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net_test.go
550 lines (480 loc) · 12.4 KB
/
net_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
package mqtt
import (
"context"
"errors"
"testing"
"time"
"reflect"
"sync"
"bytes"
"sync/atomic"
"math/rand"
"fmt"
"github.com/eclipse/paho.mqtt.golang/packets"
)
func TestSend(t *testing.T) {
setup := func(sendErr error, ordered, deferred bool) (*client, packets.ControlPacket, <-chan error, *sync.WaitGroup) {
co := NewClientOptions()
co.SetOrderMatters(ordered)
co.SetDeferredAck(deferred)
c := NewClient(co).(*client)
c.oboundP = make(chan *PacketAndToken)
c.stop = make(chan struct{})
c.workers.Add(1)
pa := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket)
pa.MessageID = 1
errC := make(chan error)
wg := sync.WaitGroup{}
go func() {
select {
case pkt := <-c.oboundP:
if !reflect.DeepEqual(pa, pkt.p) {
errC <- errors.New("packet does not match")
} else {
wg.Wait()
if pkt.sentCB != nil {
pkt.sentCB(sendErr)
}
errC <- nil
}
case <-time.After(2 * time.Second):
errC <- errors.New("timeout getting packet")
}
}()
return c, pa, errC, &wg
}
t.Run("No callback error", func(t *testing.T) {
t.Parallel()
c, cp, errC, _ := setup(nil, false, true)
cbErrC := make(chan error)
go func() { cbErrC <- sendPacketDeferred(c, cp)() }()
select {
case cbErr := <-cbErrC:
if cbErr != nil {
t.Fatalf("got unexpected callback error: %+v", cbErr)
}
case <-time.After(2 * time.Second):
t.Fatal("timeout getting send value")
}
if err := <-errC; err != nil {
t.Fatalf("error getting packet: %+v", err)
}
})
t.Run("Some callback error", func(t *testing.T) {
t.Parallel()
c, cp, errC, _ := setup(errors.New("test error"), false, true)
cbErrC := make(chan error)
go func() { cbErrC <- sendPacketDeferred(c, cp)() }()
select {
case cbErr := <-cbErrC:
if cbErr.Error() != "test error" {
t.Fatalf("got unexpected callback error: %+v", cbErr)
}
case <-time.After(2 * time.Second):
t.Fatal("timeout getting send value")
}
if err := <-errC; err != nil {
t.Fatalf("error getting packet: %+v", err)
}
})
t.Run("Error no ack", func(t *testing.T) {
t.Parallel()
c, cp, _, _ := setup(errors.New("test error"), false, true)
close(c.stop)
cbErrC := make(chan error)
go func() { cbErrC <- sendPacketDeferred(c, cp)() }()
select {
case cbErr := <-cbErrC:
if cbErr.Error() != ErrAckNotSent.Error() {
t.Fatalf("got unexpected callback error: %+v", cbErr)
}
case <-time.After(2 * time.Second):
t.Fatal("timeout getting send value")
}
})
raceTest := func(ordered bool) func(t *testing.T) {
return func(t *testing.T) {
for i := 0; i < 100; i++ {
t.Run("Error sending message", func(t *testing.T) {
t.Parallel()
c, cp, _, wg := setup(errors.New("test error"), ordered, true)
wg.Add(1)
cbErrC := make(chan error)
go func() { cbErrC <- sendPacketDeferred(c, cp)() }()
go func() {
// Wait for the packet to be enqueued.
time.Sleep(50 * time.Millisecond)
close(c.stop)
wg.Done()
}()
select {
case cbErr := <-cbErrC:
if cbErr.Error() != "test error" {
t.Fatalf("got unexpected callback error: %+v", cbErr)
}
case <-time.After(5 * time.Second):
t.Fatal("timeout getting send value")
}
})
}
}
}
t.Run("Racy tests no ordering", raceTest(false))
t.Run("Racy tests with ordering", raceTest(true))
t.Run("Send no deferred", func(t *testing.T) {
t.Parallel()
c, cp, errC, _ := setup(nil, false, false)
cbErrC := make(chan error)
go func() { cbErrC <- sendPacketDeferred(c, cp)() }()
select {
case cbErr := <-cbErrC:
if cbErr != nil {
t.Fatalf("got unexpected callback error: %+v", cbErr)
}
case <-time.After(2 * time.Second):
t.Fatal("timeout getting send value")
}
if err := <-errC; err != nil {
t.Fatalf("error getting packet: %+v", err)
}
})
}
func TestSendOrdered(t *testing.T) {
// Need to also add the corresponding values to the lists for this to work.
setup := func(sendErr error, deferred bool) *client {
co := NewClientOptions()
co.SetOrderMatters(true)
co.SetDeferredAck(deferred)
c := NewClient(co).(*client)
c.oboundP = make(chan *PacketAndToken)
c.ibound = make(chan packets.ControlPacket)
c.incomingPubChan = make(chan *packets.PublishPacket)
c.stop = make(chan struct{})
c.persist = NewMemoryStore()
c.workers.Add(1)
go alllogic(c)
return c
}
id := uint32(1)
nonDeferred := func(qos uint8) func(t *testing.T) {
return func(t *testing.T) {
t.Parallel()
c := setup(nil, false)
pubPacket := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket)
pubPacket.Qos = qos
newID := atomic.AddUint32(&id, 1)
pubPacket.MessageID = uint16(newID)
pubPacket.Payload = []byte("Hello")
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
// Client send PUBLISH.
select {
case c.ibound <- pubPacket:
case <-ctx.Done():
t.Fatal(ctx.Err())
}
// Handle PUBLISH channel.
select {
case p := <-c.incomingPubChan:
if p.MessageID != pubPacket.MessageID {
t.Fatal("Incorrect message ID")
}
if !bytes.Equal(p.Payload, pubPacket.Payload) {
t.Fatal("Incorrect payload")
}
if p.Qos != pubPacket.Qos {
t.Fatal("Incorrect QOS")
}
case <-ctx.Done():
t.Fatal(ctx.Err())
}
// Server send PUBACK/PUBREC.
select {
case pt := <-c.oboundP:
if qos == 1 {
if p, ok := pt.p.(*packets.PubackPacket); !ok {
t.Fatal("Got unexpected packet")
} else {
if p.MessageID != pubPacket.MessageID {
t.Fatal("incorrect message ID")
}
}
}
if qos == 2 {
if p, ok := pt.p.(*packets.PubrecPacket); !ok {
t.Fatal("Got unexpected packet")
} else {
if p.MessageID != pubPacket.MessageID {
t.Fatal("incorrect message ID")
}
}
}
case <-ctx.Done():
t.Fatal(ctx.Err())
}
if qos == 2 {
// Client send PUBREL.
pubrel := packets.NewControlPacket(packets.Pubrel).(*packets.PubrelPacket)
pubrel.MessageID = pubPacket.MessageID
select {
case c.ibound <- pubrel:
case <-ctx.Done():
t.Fatal(ctx.Err())
}
// Server send PUBCOMP.
select {
case pt := <-c.oboundP:
if p, ok := pt.p.(*packets.PubcompPacket); !ok {
t.Fatal("Got unexpected packet")
} else {
if p.MessageID != pubPacket.MessageID {
t.Fatal("incorrect message ID")
}
}
case <-ctx.Done():
t.Fatal(ctx.Err())
}
}
}
}
t.Run("Non-deferred", func(t *testing.T) {
t.Run("QOS 1", func(t *testing.T) {
t.Parallel()
for i := 0; i < 100; i++ {
t.Run("Works", nonDeferred(1))
}
})
t.Run("QOS 2", func(t *testing.T) {
t.Parallel()
for i := 0; i < 100; i++ {
t.Run("Works", nonDeferred(2))
}
})
})
deferred := func(qos uint8) func(t *testing.T) {
return func(t *testing.T) {
t.Parallel()
c := setup(nil, true)
pubPacket := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket)
pubPacket.Qos = qos
newID := atomic.AddUint32(&id, 1)
pubPacket.MessageID = uint16(newID)
pubPacket.Payload = []byte("Hello")
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
// Client send PUBLISH.
select {
case c.ibound <- pubPacket:
case <-ctx.Done():
t.Fatal(ctx.Err())
}
var p *packets.PublishPacket
select {
case p = <-c.incomingPubChan:
if p.MessageID != pubPacket.MessageID {
t.Fatal("Incorrect message ID")
}
if !bytes.Equal(p.Payload, pubPacket.Payload) {
t.Fatal("Incorrect payload")
}
if p.Qos != pubPacket.Qos {
t.Fatal("Incorrect QOS")
}
case <-ctx.Done():
t.Fatal(ctx.Err())
}
// Should not get acknowledgement since it is deferred.
select {
case <-c.oboundP:
t.Fatal("Got PUBACK without acknowledgement")
case <-time.After(100 * time.Millisecond):
}
msg := messageFromPublish(p)
go msg.Ack()
// Server send PUBACK/PUBREC.
select {
case pt := <-c.oboundP:
if qos == 1 {
if p, ok := pt.p.(*packets.PubackPacket); !ok {
t.Fatal("Got unexpected packet")
} else {
if p.MessageID != pubPacket.MessageID {
t.Fatal("incorrect message ID")
}
}
}
if qos == 2 {
if p, ok := pt.p.(*packets.PubrecPacket); !ok {
t.Fatal("Got unexpected packet")
} else {
if p.MessageID != pubPacket.MessageID {
t.Fatal("incorrect message ID")
}
}
}
case <-ctx.Done():
t.Fatal(ctx.Err())
}
if qos == 2 {
// Client send PUBREL.
pubrel := packets.NewControlPacket(packets.Pubrel).(*packets.PubrelPacket)
pubrel.MessageID = pubPacket.MessageID
select {
case c.ibound <- pubrel:
case <-ctx.Done():
t.Fatal(ctx.Err())
}
// Server send PUBCOMP.
select {
case pt := <-c.oboundP:
if p, ok := pt.p.(*packets.PubcompPacket); !ok {
t.Fatal("Got unexpected packet")
} else {
if p.MessageID != pubPacket.MessageID {
t.Fatal("incorrect message ID")
}
}
case <-ctx.Done():
t.Fatal(ctx.Err())
}
}
}
}
t.Run("Deferred", func(t *testing.T) {
t.Run("QOS 1", func(t *testing.T) {
t.Parallel()
for i := 0; i < 100; i++ {
t.Run("Works", deferred(1))
}
})
t.Run("QOS 2", func(t *testing.T) {
t.Parallel()
for i := 0; i < 100; i++ {
t.Run("Works", deferred(2))
}
})
})
}
func Test1MillionDuplicates(t *testing.T) {
DEBUG = NOOPLogger{}
WARN = NOOPLogger{}
CRITICAL = NOOPLogger{}
ERROR = NOOPLogger{}
rand.Seed(time.Now().UnixNano())
setup := func(sendErr error, deferred bool) *client {
co := NewClientOptions()
co.SetOrderMatters(true)
co.SetDeferredAck(deferred)
c := NewClient(co).(*client)
c.oboundP = make(chan *PacketAndToken)
c.ibound = make(chan packets.ControlPacket)
c.incomingPubChan = make(chan *packets.PublishPacket)
c.stop = make(chan struct{})
c.persist = NewMemoryStore()
c.workers.Add(1)
go alllogic(c)
return c
}
var wg sync.WaitGroup
id := uint32(1)
c := setup(nil, true)
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
errC := make(chan error)
sent := make(map[uint16]uint8, 100000)
var sentMu sync.Mutex
c.msgRouter.addRoute("#", func(_ Client, m Message) {
time.AfterFunc(time.Duration(rand.Intn(500)+500)*time.Millisecond, func() {
// fmt.Println("GOT MESSAGE:", m.MessageID(), m.Duplicate())
sentMu.Lock()
sent[m.MessageID()]++
sentMu.Unlock()
if err := m.Ack(); err != nil {
errC <- err
}
})
})
c.msgRouter.matchAndDispatch(c.incomingPubChan, c.options.Order, c)
// Handle package acknowledgements.
// Ensure they should exist.
go func() {
var count uint64
for {
select {
case p := <-c.oboundP:
if pub, ok := p.p.(*packets.PubackPacket); ok {
func() {
sentMu.Lock()
defer sentMu.Unlock()
if _, idOk := sent[pub.MessageID]; !idOk {
t.Logf("Unknown message ID: %d, %t", pub.MessageID, pub.Dup)
errC <- fmt.Errorf("got unknown message ID: %d", pub.MessageID)
} else {
sent[pub.MessageID]--
if sent[pub.MessageID] == 0 {
delete(sent, pub.MessageID)
}
count++
if count%10000 == 0 {
t.Logf("Got %d acknowledgements", count)
}
wg.Done()
}
}()
} else {
t.Log("Unknown packet type received")
errC <- errors.New("unknown packet type received")
}
case <-ctx.Done():
return
}
}
}()
sendN := func(n int) {
for i := 0; i < n; i++ {
pubPacket := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket)
pubPacket.TopicName = "test"
pubPacket.Qos = 1
newID := atomic.AddUint32(&id, 1)
pubPacket.MessageID = uint16(newID)
pubPacket.Payload = []byte("Hello")
select {
case c.ibound <- pubPacket:
case <-ctx.Done():
t.Log(ctx.Err())
errC <- ctx.Err()
}
p2 := packets.NewControlPacket(packets.Publish).(*packets.PublishPacket)
p2.TopicName = "test"
p2.Qos = 1
p2.MessageID = uint16(newID)
p2.Payload = []byte("Hello")
p2.Dup = true
select {
case c.ibound <- p2:
case <-ctx.Done():
t.Log(ctx.Err())
errC <- ctx.Err()
}
}
}
const perGR = 100000
// Send the messages.
for i := 0; i < 10; i++ {
wg.Add(perGR * 2)
go sendN(perGR)
}
doneC := make(chan struct{})
go func() {
wg.Wait()
close(doneC)
}()
for {
select {
case <-doneC:
return
case err := <-errC:
t.Fatalf("Error: %+v", err)
}
}
}