mqtt 5.0.0-beta.2 → 5.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/connect/wx.js CHANGED
@@ -1,133 +1,132 @@
1
- 'use strict'
2
-
3
1
  const { Buffer } = require('buffer')
4
- const Transform = require('readable-stream').Transform
2
+ const { Transform } = require('readable-stream')
5
3
  const duplexify = require('duplexify')
6
4
 
7
5
  /* global wx */
8
- let socketTask, proxy, stream
9
-
10
- function buildProxy () {
11
- const proxy = new Transform()
12
- proxy._write = function (chunk, encoding, next) {
13
- socketTask.send({
14
- data: chunk.buffer,
15
- success: function () {
16
- next()
17
- },
18
- fail: function (errMsg) {
19
- next(new Error(errMsg))
20
- }
21
- })
22
- }
23
- proxy._flush = function socketEnd (done) {
24
- socketTask.close({
25
- success: function () {
26
- done()
27
- }
28
- })
29
- }
30
-
31
- return proxy
6
+ let socketTask
7
+ let proxy
8
+ let stream
9
+
10
+ function buildProxy() {
11
+ const _proxy = new Transform()
12
+ _proxy._write = (chunk, encoding, next) => {
13
+ socketTask.send({
14
+ data: chunk.buffer,
15
+ success() {
16
+ next()
17
+ },
18
+ fail(errMsg) {
19
+ next(new Error(errMsg))
20
+ },
21
+ })
22
+ }
23
+ _proxy._flush = (done) => {
24
+ socketTask.close({
25
+ success() {
26
+ done()
27
+ },
28
+ })
29
+ }
30
+
31
+ return _proxy
32
32
  }
33
33
 
34
- function setDefaultOpts (opts) {
35
- if (!opts.hostname) {
36
- opts.hostname = 'localhost'
37
- }
38
- if (!opts.path) {
39
- opts.path = '/'
40
- }
41
-
42
- if (!opts.wsOptions) {
43
- opts.wsOptions = {}
44
- }
34
+ function setDefaultOpts(opts) {
35
+ if (!opts.hostname) {
36
+ opts.hostname = 'localhost'
37
+ }
38
+ if (!opts.path) {
39
+ opts.path = '/'
40
+ }
41
+
42
+ if (!opts.wsOptions) {
43
+ opts.wsOptions = {}
44
+ }
45
45
  }
46
46
 
47
- function buildUrl (opts, client) {
48
- const protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'
49
- let url = protocol + '://' + opts.hostname + opts.path
50
- if (opts.port && opts.port !== 80 && opts.port !== 443) {
51
- url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
52
- }
53
- if (typeof (opts.transformWsUrl) === 'function') {
54
- url = opts.transformWsUrl(url, opts, client)
55
- }
56
- return url
47
+ function buildUrl(opts, client) {
48
+ const protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'
49
+ let url = `${protocol}://${opts.hostname}${opts.path}`
50
+ if (opts.port && opts.port !== 80 && opts.port !== 443) {
51
+ url = `${protocol}://${opts.hostname}:${opts.port}${opts.path}`
52
+ }
53
+ if (typeof opts.transformWsUrl === 'function') {
54
+ url = opts.transformWsUrl(url, opts, client)
55
+ }
56
+ return url
57
57
  }
58
58
 
59
- function bindEventHandler () {
60
- socketTask.onOpen(function () {
61
- stream.setReadable(proxy)
62
- stream.setWritable(proxy)
63
- stream.emit('connect')
64
- })
65
-
66
- socketTask.onMessage(function (res) {
67
- let data = res.data
68
-
69
- if (data instanceof ArrayBuffer) data = Buffer.from(data)
70
- else data = Buffer.from(data, 'utf8')
71
- proxy.push(data)
72
- })
73
-
74
- socketTask.onClose(function () {
75
- stream.end()
76
- stream.destroy()
77
- })
78
-
79
- socketTask.onError(function (res) {
80
- stream.destroy(new Error(res.errMsg))
81
- })
59
+ function bindEventHandler() {
60
+ socketTask.onOpen(() => {
61
+ stream.setReadable(proxy)
62
+ stream.setWritable(proxy)
63
+ stream.emit('connect')
64
+ })
65
+
66
+ socketTask.onMessage((res) => {
67
+ let { data } = res
68
+
69
+ if (data instanceof ArrayBuffer) data = Buffer.from(data)
70
+ else data = Buffer.from(data, 'utf8')
71
+ proxy.push(data)
72
+ })
73
+
74
+ socketTask.onClose(() => {
75
+ stream.end()
76
+ stream.destroy()
77
+ })
78
+
79
+ socketTask.onError((res) => {
80
+ stream.destroy(new Error(res.errMsg))
81
+ })
82
82
  }
83
83
 
84
- function buildStream (client, opts) {
85
- opts.hostname = opts.hostname || opts.host
86
-
87
- if (!opts.hostname) {
88
- throw new Error('Could not determine host. Specify host manually.')
89
- }
90
-
91
- const websocketSubProtocol =
92
- (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
93
- ? 'mqttv3.1'
94
- : 'mqtt'
95
-
96
- setDefaultOpts(opts)
97
-
98
- const url = buildUrl(opts, client)
99
- socketTask = wx.connectSocket({
100
- url: url,
101
- protocols: [websocketSubProtocol]
102
- })
103
-
104
- proxy = buildProxy()
105
- stream = duplexify.obj()
106
- stream._destroy = function (err, cb) {
107
- socketTask.close({
108
- success: function () {
109
- cb && cb(err)
110
- }
111
- })
112
- }
113
-
114
- const destroyRef = stream.destroy
115
- stream.destroy = function () {
116
- stream.destroy = destroyRef
117
-
118
- const self = this
119
- setTimeout(function () {
120
- socketTask.close({
121
- fail: function () {
122
- self._destroy(new Error())
123
- }
124
- })
125
- }, 0)
126
- }.bind(stream)
127
-
128
- bindEventHandler()
129
-
130
- return stream
84
+ function buildStream(client, opts) {
85
+ opts.hostname = opts.hostname || opts.host
86
+
87
+ if (!opts.hostname) {
88
+ throw new Error('Could not determine host. Specify host manually.')
89
+ }
90
+
91
+ const websocketSubProtocol =
92
+ opts.protocolId === 'MQIsdp' && opts.protocolVersion === 3
93
+ ? 'mqttv3.1'
94
+ : 'mqtt'
95
+
96
+ setDefaultOpts(opts)
97
+
98
+ const url = buildUrl(opts, client)
99
+ socketTask = wx.connectSocket({
100
+ url,
101
+ protocols: [websocketSubProtocol],
102
+ })
103
+
104
+ proxy = buildProxy()
105
+ stream = duplexify.obj()
106
+ stream._destroy = (err, cb) => {
107
+ socketTask.close({
108
+ success() {
109
+ if (cb) cb(err)
110
+ },
111
+ })
112
+ }
113
+
114
+ const destroyRef = stream.destroy
115
+ stream.destroy = () => {
116
+ stream.destroy = destroyRef
117
+
118
+ setTimeout(() => {
119
+ socketTask.close({
120
+ fail() {
121
+ stream._destroy(new Error())
122
+ },
123
+ })
124
+ }, 0)
125
+ }
126
+
127
+ bindEventHandler()
128
+
129
+ return stream
131
130
  }
132
131
 
133
132
  module.exports = buildStream
@@ -1,69 +1,63 @@
1
- 'use strict'
2
-
3
1
  /**
4
2
  * DefaultMessageAllocator constructor
5
3
  * @constructor
6
4
  */
7
- function DefaultMessageIdProvider () {
8
- if (!(this instanceof DefaultMessageIdProvider)) {
9
- return new DefaultMessageIdProvider()
10
- }
11
-
12
- /**
13
- * MessageIDs starting with 1
14
- * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
15
- */
16
- this.nextId = Math.max(1, Math.floor(Math.random() * 65535))
17
- }
18
-
19
- /**
20
- * allocate
21
- *
22
- * Get the next messageId.
23
- * @return unsigned int
24
- */
25
- DefaultMessageIdProvider.prototype.allocate = function () {
26
- // id becomes current state of this.nextId and increments afterwards
27
- const id = this.nextId++
28
- // Ensure 16 bit unsigned int (max 65535, nextId got one higher)
29
- if (this.nextId === 65536) {
30
- this.nextId = 1
31
- }
32
- return id
33
- }
34
-
35
- /**
36
- * getLastAllocated
37
- * Get the last allocated messageId.
38
- * @return unsigned int
39
- */
40
- DefaultMessageIdProvider.prototype.getLastAllocated = function () {
41
- return (this.nextId === 1) ? 65535 : (this.nextId - 1)
42
- }
43
-
44
- /**
45
- * register
46
- * Register messageId. If success return true, otherwise return false.
47
- * @param { unsigned int } - messageId to register,
48
- * @return boolean
49
- */
50
- DefaultMessageIdProvider.prototype.register = function (messageId) {
51
- return true
52
- }
53
-
54
- /**
55
- * deallocate
56
- * Deallocate messageId.
57
- * @param { unsigned int } - messageId to deallocate,
58
- */
59
- DefaultMessageIdProvider.prototype.deallocate = function (messageId) {
60
- }
61
-
62
- /**
63
- * clear
64
- * Deallocate all messageIds.
65
- */
66
- DefaultMessageIdProvider.prototype.clear = function () {
5
+ class DefaultMessageIdProvider {
6
+ constructor() {
7
+ /**
8
+ * MessageIDs starting with 1
9
+ * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
10
+ */
11
+ this.nextId = Math.max(1, Math.floor(Math.random() * 65535))
12
+ }
13
+
14
+ /**
15
+ * allocate
16
+ *
17
+ * Get the next messageId.
18
+ * @return unsigned int
19
+ */
20
+ allocate() {
21
+ // id becomes current state of this.nextId and increments afterwards
22
+ const id = this.nextId++
23
+ // Ensure 16 bit unsigned int (max 65535, nextId got one higher)
24
+ if (this.nextId === 65536) {
25
+ this.nextId = 1
26
+ }
27
+ return id
28
+ }
29
+
30
+ /**
31
+ * getLastAllocated
32
+ * Get the last allocated messageId.
33
+ * @return unsigned int
34
+ */
35
+ getLastAllocated() {
36
+ return this.nextId === 1 ? 65535 : this.nextId - 1
37
+ }
38
+
39
+ /**
40
+ * register
41
+ * Register messageId. If success return true, otherwise return false.
42
+ * @param { unsigned int } - messageId to register,
43
+ * @return boolean
44
+ */
45
+ register(messageId) {
46
+ return true
47
+ }
48
+
49
+ /**
50
+ * deallocate
51
+ * Deallocate messageId.
52
+ * @param { unsigned int } - messageId to deallocate,
53
+ */
54
+ deallocate(messageId) {}
55
+
56
+ /**
57
+ * clear
58
+ * Deallocate all messageIds.
59
+ */
60
+ clear() {}
67
61
  }
68
62
 
69
63
  module.exports = DefaultMessageIdProvider
@@ -0,0 +1,153 @@
1
+ // Other Socket Errors: EADDRINUSE, ECONNRESET, ENOTFOUND, ETIMEDOUT.
2
+
3
+ const errors = {
4
+ 0: '',
5
+ 1: 'Unacceptable protocol version',
6
+ 2: 'Identifier rejected',
7
+ 3: 'Server unavailable',
8
+ 4: 'Bad username or password',
9
+ 5: 'Not authorized',
10
+ 16: 'No matching subscribers',
11
+ 17: 'No subscription existed',
12
+ 128: 'Unspecified error',
13
+ 129: 'Malformed Packet',
14
+ 130: 'Protocol Error',
15
+ 131: 'Implementation specific error',
16
+ 132: 'Unsupported Protocol Version',
17
+ 133: 'Client Identifier not valid',
18
+ 134: 'Bad User Name or Password',
19
+ 135: 'Not authorized',
20
+ 136: 'Server unavailable',
21
+ 137: 'Server busy',
22
+ 138: 'Banned',
23
+ 139: 'Server shutting down',
24
+ 140: 'Bad authentication method',
25
+ 141: 'Keep Alive timeout',
26
+ 142: 'Session taken over',
27
+ 143: 'Topic Filter invalid',
28
+ 144: 'Topic Name invalid',
29
+ 145: 'Packet identifier in use',
30
+ 146: 'Packet Identifier not found',
31
+ 147: 'Receive Maximum exceeded',
32
+ 148: 'Topic Alias invalid',
33
+ 149: 'Packet too large',
34
+ 150: 'Message rate too high',
35
+ 151: 'Quota exceeded',
36
+ 152: 'Administrative action',
37
+ 153: 'Payload format invalid',
38
+ 154: 'Retain not supported',
39
+ 155: 'QoS not supported',
40
+ 156: 'Use another server',
41
+ 157: 'Server moved',
42
+ 158: 'Shared Subscriptions not supported',
43
+ 159: 'Connection rate exceeded',
44
+ 160: 'Maximum connect time',
45
+ 161: 'Subscription Identifiers not supported',
46
+ 162: 'Wildcard Subscriptions not supported',
47
+ }
48
+
49
+ function handleAck(client, packet) {
50
+ /* eslint no-fallthrough: "off" */
51
+ const { messageId } = packet
52
+ const type = packet.cmd
53
+ let response = null
54
+ const cb = client.outgoing[messageId] ? client.outgoing[messageId].cb : null
55
+ let err
56
+
57
+ // Checking `!cb` happens to work, but it's not technically "correct".
58
+ //
59
+ // Why? client code assumes client "no callback" is the same as client "we're not
60
+ // waiting for responses" (puback, pubrec, pubcomp, suback, or unsuback).
61
+ //
62
+ // It would be better to check `if (!client.outgoing[messageId])` here, but
63
+ // there's no reason to change it and risk (another) regression.
64
+ //
65
+ // The only reason client code works is becaues code in MqttClient.publish,
66
+ // MqttClinet.subscribe, and MqttClient.unsubscribe ensures client we will
67
+ // have a callback even if the user doesn't pass one in.)
68
+ if (!cb) {
69
+ client.log('_handleAck :: Server sent an ack in error. Ignoring.')
70
+ // Server sent an ack in error, ignore it.
71
+ return
72
+ }
73
+
74
+ // Process
75
+ client.log('_handleAck :: packet type', type)
76
+ switch (type) {
77
+ case 'pubcomp':
78
+ // same thing as puback for QoS 2
79
+ case 'puback': {
80
+ const pubackRC = packet.reasonCode
81
+ // Callback - we're done
82
+ if (pubackRC && pubackRC > 0 && pubackRC !== 16) {
83
+ err = new Error(`Publish error: ${errors[pubackRC]}`)
84
+ err.code = pubackRC
85
+ client._removeOutgoingAndStoreMessage(messageId, () => {
86
+ cb(err, packet)
87
+ })
88
+ } else {
89
+ client._removeOutgoingAndStoreMessage(messageId, cb)
90
+ }
91
+
92
+ break
93
+ }
94
+ case 'pubrec': {
95
+ response = {
96
+ cmd: 'pubrel',
97
+ qos: 2,
98
+ messageId,
99
+ }
100
+ const pubrecRC = packet.reasonCode
101
+
102
+ if (pubrecRC && pubrecRC > 0 && pubrecRC !== 16) {
103
+ err = new Error(`Publish error: ${errors[pubrecRC]}`)
104
+ err.code = pubrecRC
105
+ client._removeOutgoingAndStoreMessage(messageId, () => {
106
+ cb(err, packet)
107
+ })
108
+ } else {
109
+ client._sendPacket(response)
110
+ }
111
+ break
112
+ }
113
+ case 'suback': {
114
+ delete client.outgoing[messageId]
115
+ client.messageIdProvider.deallocate(messageId)
116
+ for (
117
+ let grantedI = 0;
118
+ grantedI < packet.granted.length;
119
+ grantedI++
120
+ ) {
121
+ if ((packet.granted[grantedI] & 0x80) !== 0) {
122
+ // suback with Failure status
123
+ const topics = client.messageIdToTopic[messageId]
124
+ if (topics) {
125
+ topics.forEach((topic) => {
126
+ delete client._resubscribeTopics[topic]
127
+ })
128
+ }
129
+ }
130
+ }
131
+ delete client.messageIdToTopic[messageId]
132
+ client._invokeStoreProcessingQueue()
133
+ cb(null, packet)
134
+ break
135
+ }
136
+ case 'unsuback': {
137
+ delete client.outgoing[messageId]
138
+ client.messageIdProvider.deallocate(messageId)
139
+ client._invokeStoreProcessingQueue()
140
+ cb(null)
141
+ break
142
+ }
143
+ default:
144
+ client.emit('error', new Error('unrecognized packet type'))
145
+ }
146
+
147
+ if (client.disconnecting && Object.keys(client.outgoing).length === 0) {
148
+ client.emit('outgoingEmpty')
149
+ }
150
+ }
151
+
152
+ module.exports = handleAck
153
+ module.exports.errors = errors
@@ -0,0 +1,34 @@
1
+ const { errors } = require('./ack')
2
+
3
+ function handleAuth(client, packet) {
4
+ const { options } = client
5
+ const version = options.protocolVersion
6
+ const rc = version === 5 ? packet.reasonCode : packet.returnCode
7
+
8
+ if (version !== 5) {
9
+ const err = new Error(
10
+ `Protocol error: Auth packets are only supported in MQTT 5. Your version:${version}`,
11
+ )
12
+ err.code = rc
13
+ client.emit('error', err)
14
+ return
15
+ }
16
+
17
+ client.handleAuth(packet, (err, packet2) => {
18
+ if (err) {
19
+ client.emit('error', err)
20
+ return
21
+ }
22
+
23
+ if (rc === 24) {
24
+ client.reconnecting = false
25
+ client._sendPacket(packet2)
26
+ } else {
27
+ const error = new Error(`Connection refused: ${errors[rc]}`)
28
+ err.code = rc
29
+ client.emit('error', error)
30
+ }
31
+ })
32
+ }
33
+
34
+ module.exports = handleAuth
@@ -0,0 +1,51 @@
1
+ const { errors } = require('./ack')
2
+ const TopicAliasSend = require('../topic-alias-send')
3
+
4
+ function handleConnack(client, packet) {
5
+ client.log('_handleConnack')
6
+ const { options } = client
7
+ const version = options.protocolVersion
8
+ const rc = version === 5 ? packet.reasonCode : packet.returnCode
9
+
10
+ clearTimeout(client.connackTimer)
11
+ delete client.topicAliasSend
12
+
13
+ if (packet.properties) {
14
+ if (packet.properties.topicAliasMaximum) {
15
+ if (packet.properties.topicAliasMaximum > 0xffff) {
16
+ client.emit(
17
+ 'error',
18
+ new Error('topicAliasMaximum from broker is out of range'),
19
+ )
20
+ return
21
+ }
22
+ if (packet.properties.topicAliasMaximum > 0) {
23
+ client.topicAliasSend = new TopicAliasSend(
24
+ packet.properties.topicAliasMaximum,
25
+ )
26
+ }
27
+ }
28
+ if (packet.properties.serverKeepAlive && options.keepalive) {
29
+ options.keepalive = packet.properties.serverKeepAlive
30
+ client._shiftPingInterval()
31
+ }
32
+ if (packet.properties.maximumPacketSize) {
33
+ if (!options.properties) {
34
+ options.properties = {}
35
+ }
36
+ options.properties.maximumPacketSize =
37
+ packet.properties.maximumPacketSize
38
+ }
39
+ }
40
+
41
+ if (rc === 0) {
42
+ client.reconnecting = false
43
+ client._onConnect(packet)
44
+ } else if (rc > 0) {
45
+ const err = new Error(`Connection refused: ${errors[rc]}`)
46
+ err.code = rc
47
+ client.emit('error', err)
48
+ }
49
+ }
50
+
51
+ module.exports = handleConnack
@@ -0,0 +1,66 @@
1
+ const handlePublish = require('./publish')
2
+ const handleAuth = require('./auth')
3
+ const handleConnack = require('./connack')
4
+ const handleAck = require('./ack')
5
+ const handlePubrel = require('./pubrel')
6
+
7
+ function handle(client, packet, done) {
8
+ const { options } = client
9
+
10
+ if (
11
+ options.protocolVersion === 5 &&
12
+ options.properties &&
13
+ options.properties.maximumPacketSize &&
14
+ options.properties.maximumPacketSize < packet.length
15
+ ) {
16
+ client.emit('error', new Error(`exceeding packets size ${packet.cmd}`))
17
+ client.end({
18
+ reasonCode: 149,
19
+ properties: { reasonString: 'Maximum packet size was exceeded' },
20
+ })
21
+ return client
22
+ }
23
+ client.log('_handlePacket :: emitting packetreceive')
24
+ client.emit('packetreceive', packet)
25
+
26
+ switch (packet.cmd) {
27
+ case 'publish':
28
+ handlePublish(client, packet, done)
29
+ break
30
+ case 'puback':
31
+ case 'pubrec':
32
+ case 'pubcomp':
33
+ case 'suback':
34
+ case 'unsuback':
35
+ handleAck(client, packet)
36
+ done()
37
+ break
38
+ case 'pubrel':
39
+ handlePubrel(client, packet, done)
40
+ break
41
+ case 'connack':
42
+ handleConnack(client, packet)
43
+ done()
44
+ break
45
+ case 'auth':
46
+ handleAuth(client, packet)
47
+ done()
48
+ break
49
+ case 'pingresp':
50
+ // this will be checked in _checkPing client method every keepalive interval
51
+ client.pingResp = true
52
+ done()
53
+ break
54
+ case 'disconnect':
55
+ client.emit('disconnect', packet)
56
+ done()
57
+ break
58
+ default:
59
+ // TODO: unknown packet received. Should we emit an error?
60
+ client.log('_handlePacket :: unknown command')
61
+ done()
62
+ break
63
+ }
64
+ }
65
+
66
+ module.exports = handle