forked from mqttjs/mqtt-packet
-
Notifications
You must be signed in to change notification settings - Fork 1
/
testRandom.js
90 lines (79 loc) · 2.51 KB
/
testRandom.js
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
'use strict'
var mqtt = require('./')
var crypto = require('crypto')
var max = 1E5
var i
var start = Date.now() / 1000
var time
var errors = 0
var packets = 0
var randomPacket
var firstBytes = [
16 * 1, // CONNECT
16 * 2, // CONNACK
16 * 3, // PUBLISH, QoS: 0, No Retain, No Dup
16 * 3 + 1, // PUBLISH, QoS: 0, Retain, No Dup
16 * 3 + 8, // PUBLISH, QoS: 0, No Retain, Dup
16 * 3 + 1 + 8, // PUBLISH, QoS: 0, Retain, Dup
16 * 3 + 2, // PUBLISH, QoS: 1, No Retain, No Dup
16 * 3 + 2 + 1, // PUBLISH, QoS: 1, Retain, No Dup
16 * 3 + 2 + 8, // PUBLISH, QoS: 1, No Retain, Dup
16 * 3 + 2 + 1 + 8, // PUBLISH, QoS: 1, Retain, Dup
16 * 3 + 4, // PUBLISH, QoS: 2, No Retain, No Dup
16 * 3 + 4 + 1, // PUBLISH, QoS: 2, Retain, No Dup
16 * 3 + 4 + 8, // PUBLISH, QoS: 2, No Retain, Dup
16 * 3 + 4 + 1 + 8, // PUBLISH, QoS: 2, Retain, Dup
16 * 4, // PUBACK
16 * 5, // PUBREC
16 * 6, // PUBREL
16 * 7, // PUBCOMP
16 * 8, // SUBSCRIBE
16 * 9, // SUBACK
16 * 10, // UNSUBSCRIBE
16 * 11, // UNSUBACK
16 * 12, // PINGREQ
16 * 13, // PINGRESP
16 * 14, // DISCONNECT
16 * 15 // RESERVED
]
function doParse () {
var parser = mqtt.parser()
parser.on('error', onError)
parser.on('packet', onPacket)
randomPacket = crypto.randomBytes(Math.floor(Math.random() * 512))
// Increase probability to have a valid first byte in order to at least
// enter the parser
if (Math.random() > 0.2 && randomPacket.length > 0) randomPacket.writeUInt8(firstBytes[Math.floor(Math.random() * firstBytes.length)], 0)
parser.parse(randomPacket)
}
try {
console.log('Starting benchmark')
for (i = 0; i < max; i++) {
doParse()
}
} catch (e) {
console.log('Exception occurred at packet')
console.log(randomPacket)
console.log(e.message)
console.log(e.stack)
}
function onError () {
errors++
}
function onPacket () {
packets++
}
var delta = Math.abs(max - packets - errors)
time = Date.now() / 1000 - start
console.log('Benchmark complete')
console.log('==========================')
console.log('Sent packets:', max)
console.log('Total time:', Math.round(time * 100) / 100, 'seconds', '\r\n')
console.log('Valid packets:', packets)
console.log('Erroneous packets:', errors)
if ((max - packets - errors) < 0) console.log('Excess packets:', delta, '\r\n')
else console.log('Missing packets:', delta, '\r\n')
console.log('Total packets:', packets + errors)
console.log('Total errors:', errors + delta)
console.log('Error rate:', ((errors + delta) / max * 100).toFixed(2) + '%')
console.log('==========================')