mqtt 5.5.6 → 5.6.0

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mqtt",
3
3
  "description": "A library for the MQTT protocol",
4
- "version": "5.5.6",
4
+ "version": "5.6.0",
5
5
  "contributors": [
6
6
  "Adam Rudd <adamvrr@gmail.com>",
7
7
  "Matteo Collina <matteo.collina@gmail.com> (https://github.com/mcollina)",
@@ -0,0 +1,107 @@
1
+ import type MqttClient from './client'
2
+ import getTimer, { type Timer } from './get-timer'
3
+ import type { TimerVariant } from './shared'
4
+
5
+ export default class KeepaliveManager {
6
+ private _keepalive: number
7
+
8
+ private timerId: number
9
+
10
+ private timer: Timer
11
+
12
+ private destroyed = false
13
+
14
+ private counter: number
15
+
16
+ private client: MqttClient
17
+
18
+ private _keepaliveTimeoutTimestamp: number
19
+
20
+ private _intervalEvery: number
21
+
22
+ /** Timestamp of next keepalive timeout */
23
+ get keepaliveTimeoutTimestamp() {
24
+ return this._keepaliveTimeoutTimestamp
25
+ }
26
+
27
+ /** Milliseconds of the actual interval */
28
+ get intervalEvery() {
29
+ return this._intervalEvery
30
+ }
31
+
32
+ get keepalive() {
33
+ return this._keepalive
34
+ }
35
+
36
+ constructor(client: MqttClient, variant: TimerVariant) {
37
+ this.client = client
38
+ this.timer = getTimer(variant)
39
+ this.setKeepalive(client.options.keepalive)
40
+ }
41
+
42
+ private clear() {
43
+ if (this.timerId) {
44
+ this.timer.clear(this.timerId)
45
+ this.timerId = null
46
+ }
47
+ }
48
+
49
+ /** Change the keepalive */
50
+ setKeepalive(value: number) {
51
+ // keepalive is in seconds
52
+ value *= 1000
53
+
54
+ if (
55
+ // eslint-disable-next-line no-restricted-globals
56
+ isNaN(value) ||
57
+ value <= 0 ||
58
+ value > 2147483647
59
+ ) {
60
+ throw new Error(
61
+ `Keepalive value must be an integer between 0 and 2147483647. Provided value is ${value}`,
62
+ )
63
+ }
64
+
65
+ this._keepalive = value
66
+
67
+ this.reschedule()
68
+
69
+ this.client['log'](`KeepaliveManager: set keepalive to ${value}ms`)
70
+ }
71
+
72
+ destroy() {
73
+ this.clear()
74
+ this.destroyed = true
75
+ }
76
+
77
+ reschedule() {
78
+ if (this.destroyed) {
79
+ return
80
+ }
81
+
82
+ this.clear()
83
+ this.counter = 0
84
+
85
+ // https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Figure_3.5_Keep
86
+ const keepAliveTimeout = Math.ceil(this._keepalive * 1.5)
87
+
88
+ this._keepaliveTimeoutTimestamp = Date.now() + keepAliveTimeout
89
+ this._intervalEvery = Math.ceil(this._keepalive / 2)
90
+
91
+ this.timerId = this.timer.set(() => {
92
+ // this should never happen, but just in case
93
+ if (this.destroyed) {
94
+ return
95
+ }
96
+
97
+ this.counter += 1
98
+
99
+ // after keepalive seconds, send a pingreq
100
+ if (this.counter === 2) {
101
+ this.client.sendPing()
102
+ } else if (this.counter > 2) {
103
+ this.client.onKeepaliveTimeout()
104
+ }
105
+ }, this._intervalEvery)
106
+ }
107
+ }
package/src/lib/client.ts CHANGED
@@ -39,7 +39,7 @@ import {
39
39
  } from './shared'
40
40
  import TopicAliasSend from './topic-alias-send'
41
41
  import { TypedEventEmitter } from './TypedEmitter'
42
- import PingTimer from './PingTimer'
42
+ import KeepaliveManager from './KeepaliveManager'
43
43
  import isBrowser, { isWebWorker } from './is-browser'
44
44
 
45
45
  const setImmediate =
@@ -433,10 +433,7 @@ export default class MqttClient extends TypedEventEmitter<MqttClientEventCallbac
433
433
 
434
434
  public noop: (error?: any) => void
435
435
 
436
- /** Timestamp of last received control packet */
437
- public pingResp: number
438
-
439
- public pingTimer: PingTimer
436
+ public keepaliveManager: KeepaliveManager
440
437
 
441
438
  /**
442
439
  * The connection to the Broker. In browsers env this also have `socket` property
@@ -572,8 +569,8 @@ export default class MqttClient extends TypedEventEmitter<MqttClientEventCallbac
572
569
  // map of a subscribe messageId and a topic
573
570
  this.messageIdToTopic = {}
574
571
 
575
- // Ping timer, setup in _setupPingTimer
576
- this.pingTimer = null
572
+ // Keepalive manager, setup in _setupKeepaliveManager
573
+ this.keepaliveManager = null
577
574
  // Is the client connected?
578
575
  this.connected = false
579
576
  // Are we disconnecting?
@@ -660,7 +657,7 @@ export default class MqttClient extends TypedEventEmitter<MqttClientEventCallbac
660
657
  this.log('close :: clearing connackTimer')
661
658
  clearTimeout(this.connackTimer)
662
659
 
663
- this._destroyPingTimer()
660
+ this._destroyKeepaliveManager()
664
661
 
665
662
  if (this.topicAliasRecv) {
666
663
  this.topicAliasRecv.clear()
@@ -1780,7 +1777,7 @@ export default class MqttClient extends TypedEventEmitter<MqttClientEventCallbac
1780
1777
  this._setupReconnect()
1781
1778
  }
1782
1779
 
1783
- this._destroyPingTimer()
1780
+ this._destroyKeepaliveManager()
1784
1781
 
1785
1782
  if (done && !this.connected) {
1786
1783
  this.log(
@@ -2064,45 +2061,36 @@ export default class MqttClient extends TypedEventEmitter<MqttClientEventCallbac
2064
2061
  }
2065
2062
 
2066
2063
  /**
2067
- * _setupPingTimer - setup the ping timer
2068
- *
2069
- * @api private
2064
+ * _setupKeepaliveManager - setup the keepalive manager
2070
2065
  */
2071
- private _setupPingTimer() {
2066
+ private _setupKeepaliveManager() {
2072
2067
  this.log(
2073
- '_setupPingTimer :: keepalive %d (seconds)',
2068
+ '_setupKeepaliveManager :: keepalive %d (seconds)',
2074
2069
  this.options.keepalive,
2075
2070
  )
2076
2071
 
2077
- if (!this.pingTimer && this.options.keepalive) {
2078
- this.pingTimer = new PingTimer(
2079
- this.options.keepalive,
2080
- () => {
2081
- this._checkPing()
2082
- },
2072
+ if (!this.keepaliveManager && this.options.keepalive) {
2073
+ this.keepaliveManager = new KeepaliveManager(
2074
+ this,
2083
2075
  this.options.timerVariant,
2084
2076
  )
2085
- this.pingResp = Date.now()
2086
2077
  }
2087
2078
  }
2088
2079
 
2089
- private _destroyPingTimer() {
2090
- if (this.pingTimer) {
2091
- this.log('_destroyPingTimer :: destroying ping timer')
2092
- this.pingTimer.destroy()
2093
- this.pingTimer = null
2080
+ private _destroyKeepaliveManager() {
2081
+ if (this.keepaliveManager) {
2082
+ this.log('_destroyKeepaliveManager :: destroying keepalive manager')
2083
+ this.keepaliveManager.destroy()
2084
+ this.keepaliveManager = null
2094
2085
  }
2095
2086
  }
2096
2087
 
2097
2088
  /**
2098
-
2099
- * _shiftPingInterval - reschedule the ping interval
2100
- *
2101
- * @api private
2089
+ * Reschedule the ping interval
2102
2090
  */
2103
- private _shiftPingInterval() {
2091
+ public reschedulePing() {
2104
2092
  if (
2105
- this.pingTimer &&
2093
+ this.keepaliveManager &&
2106
2094
  this.options.keepalive &&
2107
2095
  this.options.reschedulePings
2108
2096
  ) {
@@ -2115,34 +2103,20 @@ export default class MqttClient extends TypedEventEmitter<MqttClientEventCallbac
2115
2103
  */
2116
2104
  private _reschedulePing() {
2117
2105
  this.log('_reschedulePing :: rescheduling ping')
2118
- this.pingTimer.reschedule()
2106
+ this.keepaliveManager.reschedule()
2119
2107
  }
2120
2108
 
2121
- /**
2122
- * _checkPing - check if a pingresp has come back, and ping the server again
2123
- *
2124
- * @api private
2125
- */
2126
- private _checkPing() {
2127
- this.log('_checkPing :: checking ping...')
2128
- // give 100ms offset to avoid ping timeout when receiving fast responses
2129
- const timeSincePing = Date.now() - this.pingResp - 100
2130
- if (timeSincePing <= this.options.keepalive * 1000) {
2131
- this.log('_checkPing :: ping response received in time')
2132
- this._sendPing()
2133
- } else {
2134
- // do a forced cleanup since socket will be in bad shape
2135
- this.emit('error', new Error('Keepalive timeout'))
2136
- this.log('_checkPing :: calling _cleanUp with force true')
2137
- this._cleanUp(true)
2138
- }
2139
- }
2140
-
2141
- private _sendPing() {
2109
+ public sendPing() {
2142
2110
  this.log('_sendPing :: sending pingreq')
2143
2111
  this._sendPacket({ cmd: 'pingreq' })
2144
2112
  }
2145
2113
 
2114
+ public onKeepaliveTimeout() {
2115
+ this.emit('error', new Error('Keepalive timeout'))
2116
+ this.log('onKeepaliveTimeout :: calling _cleanUp with force true')
2117
+ this._cleanUp(true)
2118
+ }
2119
+
2146
2120
  /**
2147
2121
  * _resubscribe
2148
2122
  * @api private
@@ -2205,7 +2179,7 @@ export default class MqttClient extends TypedEventEmitter<MqttClientEventCallbac
2205
2179
 
2206
2180
  this.connackPacket = packet
2207
2181
  this.messageIdProvider.clear()
2208
- this._setupPingTimer()
2182
+ this._setupKeepaliveManager()
2209
2183
 
2210
2184
  this.connected = true
2211
2185
 
@@ -1,23 +1,23 @@
1
1
  import isBrowser, { isWebWorker, isReactNativeBrowser } from './is-browser'
2
- import { clearTimeout as clearT, setTimeout as setT } from 'worker-timers'
2
+ import { clearInterval as clearI, setInterval as setI } from 'worker-timers'
3
3
  import type { TimerVariant } from './shared'
4
4
 
5
5
  // dont directly assign globals to class props otherwise this throws in web workers: Uncaught TypeError: Illegal invocation
6
6
  // See: https://stackoverflow.com/questions/9677985/uncaught-typeerror-illegal-invocation-in-chrome
7
7
 
8
8
  export interface Timer {
9
- set: typeof setT
10
- clear: typeof clearT
9
+ set: typeof setI
10
+ clear: typeof clearI
11
11
  }
12
12
 
13
13
  const workerTimer: Timer = {
14
- set: setT,
15
- clear: clearT,
14
+ set: setI,
15
+ clear: clearI,
16
16
  }
17
17
 
18
18
  const nativeTimer: Timer = {
19
- set: (func, time) => setTimeout(func, time),
20
- clear: (timerId) => clearTimeout(timerId),
19
+ set: (func, time) => setInterval(func, time),
20
+ clear: (timerId) => clearInterval(timerId),
21
21
  }
22
22
 
23
23
  const getTimer = (variant: TimerVariant): Timer => {
@@ -29,8 +29,8 @@ const handleConnack: PacketHandler = (client, packet: IConnackPacket) => {
29
29
  }
30
30
  if (packet.properties.serverKeepAlive && options.keepalive) {
31
31
  options.keepalive = packet.properties.serverKeepAlive
32
- client['_shiftPingInterval']()
33
32
  }
33
+
34
34
  if (packet.properties.maximumPacketSize) {
35
35
  if (!options.properties) {
36
36
  options.properties = {}
@@ -22,19 +22,12 @@ const handle: PacketHandler = (client, packet, done) => {
22
22
  return client
23
23
  }
24
24
 
25
- // keep track of last time we received a packet (for keepalive mechanism)
26
- client.pingResp = Date.now()
27
-
28
- // do not shift on pingresp otherwise we would skip the pingreq sending
29
- if (!['pingresp', 'publish'].includes(packet.cmd)) {
30
- client['_shiftPingInterval']()
31
- }
32
-
33
25
  client.log('_handlePacket :: emitting packetreceive')
34
26
  client.emit('packetreceive', packet)
35
27
 
36
28
  switch (packet.cmd) {
37
29
  case 'publish':
30
+ // DO NOT SHIFT PING HERE, this would lead to https://github.com/mqttjs/MQTT.js/issues/1861
38
31
  handlePublish(client, packet, done)
39
32
  break
40
33
  case 'puback':
@@ -42,22 +35,28 @@ const handle: PacketHandler = (client, packet, done) => {
42
35
  case 'pubcomp':
43
36
  case 'suback':
44
37
  case 'unsuback':
38
+ client.reschedulePing()
45
39
  handleAck(client, packet)
46
40
  done()
47
41
  break
48
42
  case 'pubrel':
43
+ client.reschedulePing()
49
44
  handlePubrel(client, packet, done)
50
45
  break
51
46
  case 'connack':
47
+ // no need to reschedule ping here as keepalive manager is created after successll connect
48
+ // (when onConnect is called at the end of handleConnack)
52
49
  handleConnack(client, packet)
53
50
  done()
54
51
  break
55
52
  case 'auth':
53
+ client.reschedulePing()
56
54
  handleAuth(client, packet)
57
55
  done()
58
56
  break
59
57
  case 'pingresp':
60
- // this will be checked in _checkPing client method every keepalive interval
58
+ client.log('_handlePacket :: received pingresp')
59
+ client.reschedulePing()
61
60
  done()
62
61
  break
63
62
  case 'disconnect':
package/src/mqtt.ts CHANGED
@@ -9,7 +9,7 @@ import DefaultMessageIdProvider from './lib/default-message-id-provider'
9
9
  import UniqueMessageIdProvider from './lib/unique-message-id-provider'
10
10
  import Store, { IStore } from './lib/store'
11
11
  import connect, { connectAsync } from './lib/connect'
12
- import PingTimer from './lib/PingTimer'
12
+ import KeepaliveManager from './lib/KeepaliveManager'
13
13
 
14
14
  export const Client = MqttClient
15
15
  export {
@@ -20,7 +20,7 @@ export {
20
20
  DefaultMessageIdProvider,
21
21
  UniqueMessageIdProvider,
22
22
  IStore,
23
- PingTimer,
23
+ KeepaliveManager,
24
24
  }
25
25
  export * from './lib/client'
26
26
  export * from './lib/shared'
@@ -1,12 +0,0 @@
1
- import type { TimerVariant } from './shared';
2
- export default class PingTimer {
3
- private keepalive;
4
- private timerId;
5
- private timer;
6
- private checkPing;
7
- private destroyed;
8
- constructor(keepalive: number, checkPing: () => void, variant: TimerVariant);
9
- private clear;
10
- destroy(): void;
11
- reschedule(): void;
12
- }
@@ -1,40 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const get_timer_1 = __importDefault(require("./get-timer"));
7
- class PingTimer {
8
- constructor(keepalive, checkPing, variant) {
9
- this.destroyed = false;
10
- this.keepalive = keepalive * 1000;
11
- this.checkPing = checkPing;
12
- this.timer = (0, get_timer_1.default)(variant);
13
- this.reschedule();
14
- }
15
- clear() {
16
- if (this.timerId) {
17
- this.timer.clear(this.timerId);
18
- this.timerId = null;
19
- }
20
- }
21
- destroy() {
22
- this.clear();
23
- this.destroyed = true;
24
- }
25
- reschedule() {
26
- if (this.destroyed) {
27
- return;
28
- }
29
- this.clear();
30
- this.timerId = this.timer.set(() => {
31
- if (this.destroyed) {
32
- return;
33
- }
34
- this.checkPing();
35
- this.reschedule();
36
- }, this.keepalive);
37
- }
38
- }
39
- exports.default = PingTimer;
40
- //# sourceMappingURL=PingTimer.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"PingTimer.js","sourceRoot":"","sources":["../../src/lib/PingTimer.ts"],"names":[],"mappings":";;;;;AAAA,4DAAkD;AAGlD,MAAqB,SAAS;IAW7B,YACC,SAAiB,EACjB,SAAqB,EACrB,OAAqB;QALd,cAAS,GAAG,KAAK,CAAA;QAOxB,IAAI,CAAC,SAAS,GAAG,SAAS,GAAG,IAAI,CAAA;QACjC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAA;QAC1B,IAAI,CAAC,KAAK,GAAG,IAAA,mBAAQ,EAAC,OAAO,CAAC,CAAA;QAC9B,IAAI,CAAC,UAAU,EAAE,CAAA;IAClB,CAAC;IAEO,KAAK;QACZ,IAAI,IAAI,CAAC,OAAO,EAAE;YACjB,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;YAC9B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAA;SACnB;IACF,CAAC;IAED,OAAO;QACN,IAAI,CAAC,KAAK,EAAE,CAAA;QACZ,IAAI,CAAC,SAAS,GAAG,IAAI,CAAA;IACtB,CAAC;IAED,UAAU;QACT,IAAI,IAAI,CAAC,SAAS,EAAE;YACnB,OAAM;SACN;QAED,IAAI,CAAC,KAAK,EAAE,CAAA;QACZ,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE;YAElC,IAAI,IAAI,CAAC,SAAS,EAAE;gBACnB,OAAM;aACN;YAED,IAAI,CAAC,SAAS,EAAE,CAAA;YAGhB,IAAI,CAAC,UAAU,EAAE,CAAA;QAClB,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,CAAA;IACnB,CAAC;CACD;AApDD,4BAoDC"}
@@ -1,56 +0,0 @@
1
- import getTimer, { type Timer } from './get-timer'
2
- import type { TimerVariant } from './shared'
3
-
4
- export default class PingTimer {
5
- private keepalive: number
6
-
7
- private timerId: number
8
-
9
- private timer: Timer
10
-
11
- private checkPing: () => void
12
-
13
- private destroyed = false
14
-
15
- constructor(
16
- keepalive: number,
17
- checkPing: () => void,
18
- variant: TimerVariant,
19
- ) {
20
- this.keepalive = keepalive * 1000
21
- this.checkPing = checkPing
22
- this.timer = getTimer(variant)
23
- this.reschedule()
24
- }
25
-
26
- private clear() {
27
- if (this.timerId) {
28
- this.timer.clear(this.timerId)
29
- this.timerId = null
30
- }
31
- }
32
-
33
- destroy() {
34
- this.clear()
35
- this.destroyed = true
36
- }
37
-
38
- reschedule() {
39
- if (this.destroyed) {
40
- return
41
- }
42
-
43
- this.clear()
44
- this.timerId = this.timer.set(() => {
45
- // this should never happen, but just in case
46
- if (this.destroyed) {
47
- return
48
- }
49
-
50
- this.checkPing()
51
- // this must be called after `checkPing` otherwise in case `destroy`
52
- // is called in `checkPing` the timer would be rescheduled anyway
53
- this.reschedule()
54
- }, this.keepalive)
55
- }
56
- }