1 | const mqtt = require('./')
|
2 | const crypto = require('crypto')
|
3 | const max = 1E5
|
4 | const start = Date.now() / 1000
|
5 | let errors = 0
|
6 | let packets = 0
|
7 | let randomPacket
|
8 | const firstBytes = [
|
9 | 16 * 1,
|
10 | 16 * 2,
|
11 | 16 * 3,
|
12 | 16 * 3 + 1,
|
13 | 16 * 3 + 8,
|
14 | 16 * 3 + 1 + 8,
|
15 | 16 * 3 + 2,
|
16 | 16 * 3 + 2 + 1,
|
17 | 16 * 3 + 2 + 8,
|
18 | 16 * 3 + 2 + 1 + 8,
|
19 | 16 * 3 + 4,
|
20 | 16 * 3 + 4 + 1,
|
21 | 16 * 3 + 4 + 8,
|
22 | 16 * 3 + 4 + 1 + 8,
|
23 | 16 * 4,
|
24 | 16 * 5,
|
25 | 16 * 6,
|
26 | 16 * 7,
|
27 | 16 * 8,
|
28 | 16 * 9,
|
29 | 16 * 10,
|
30 | 16 * 11,
|
31 | 16 * 12,
|
32 | 16 * 13,
|
33 | 16 * 14,
|
34 | 16 * 15
|
35 | ]
|
36 |
|
37 | function doParse () {
|
38 | const parser = mqtt.parser()
|
39 |
|
40 | parser.on('error', onError)
|
41 | parser.on('packet', onPacket)
|
42 | randomPacket = crypto.randomBytes(Math.floor(Math.random() * 512))
|
43 |
|
44 |
|
45 |
|
46 | if (Math.random() > 0.2 && randomPacket.length > 0) randomPacket.writeUInt8(firstBytes[Math.floor(Math.random() * firstBytes.length)], 0)
|
47 | parser.parse(randomPacket)
|
48 | }
|
49 |
|
50 | try {
|
51 | console.log('Starting benchmark')
|
52 | for (let i = 0; i < max; i++) {
|
53 | doParse()
|
54 | }
|
55 | } catch (e) {
|
56 | console.log('Exception occurred at packet')
|
57 | console.log(randomPacket)
|
58 | console.log(e.message)
|
59 | console.log(e.stack)
|
60 | }
|
61 |
|
62 | function onError () {
|
63 | errors++
|
64 | }
|
65 |
|
66 | function onPacket () {
|
67 | packets++
|
68 | }
|
69 |
|
70 | const delta = Math.abs(max - packets - errors)
|
71 | const time = Date.now() / 1000 - start
|
72 | console.log('Benchmark complete')
|
73 | console.log('==========================')
|
74 | console.log('Sent packets:', max)
|
75 | console.log('Total time:', Math.round(time * 100) / 100, 'seconds', '\r\n')
|
76 |
|
77 | console.log('Valid packets:', packets)
|
78 | console.log('Erroneous packets:', errors)
|
79 |
|
80 | if ((max - packets - errors) < 0) console.log('Excess packets:', delta, '\r\n')
|
81 | else console.log('Missing packets:', delta, '\r\n')
|
82 |
|
83 | console.log('Total packets:', packets + errors)
|
84 | console.log('Total errors:', errors + delta)
|
85 | console.log('Error rate:', `${((errors + delta) / max * 100).toFixed(2)}%`)
|
86 | console.log('==========================')
|