mqtt 5.13.1 → 5.13.2

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/src/lib/client.ts DELETED
@@ -1,2428 +0,0 @@
1
- /**
2
- * Module dependencies
3
- */
4
- import TopicAliasRecv from './topic-alias-recv'
5
- import mqttPacket, {
6
- type IAuthPacket,
7
- IConnackPacket,
8
- IDisconnectPacket,
9
- IPublishPacket,
10
- type ISubscribePacket,
11
- type ISubscription,
12
- type IUnsubscribePacket,
13
- Packet,
14
- type QoS,
15
- type ISubackPacket,
16
- type IConnectPacket,
17
- } from 'mqtt-packet'
18
- import DefaultMessageIdProvider, {
19
- type IMessageIdProvider,
20
- } from './default-message-id-provider'
21
- import { type DuplexOptions, Writable } from 'readable-stream'
22
- import clone from 'rfdc/default'
23
- import * as validations from './validations'
24
- import _debug from 'debug'
25
- import Store, { type IStore } from './store'
26
- import handlePacket from './handlers'
27
- import type { ClientOptions } from 'ws'
28
- import { type ClientRequestArgs } from 'http'
29
- import {
30
- type DoneCallback,
31
- type ErrorWithReasonCode,
32
- ErrorWithSubackPacket,
33
- type GenericCallback,
34
- type IStream,
35
- MQTTJS_VERSION,
36
- type StreamBuilder,
37
- type TimerVariant,
38
- type VoidCallback,
39
- nextTick,
40
- } from './shared'
41
- import type TopicAliasSend from './topic-alias-send'
42
- import { TypedEventEmitter } from './TypedEmitter'
43
- import KeepaliveManager from './KeepaliveManager'
44
- import isBrowser, { isWebWorker } from './is-browser'
45
- import { type Timer } from './get-timer'
46
-
47
- const setImmediate =
48
- globalThis.setImmediate ||
49
- (((...args: any[]) => {
50
- const callback = args.shift()
51
- nextTick(() => {
52
- callback(...args)
53
- })
54
- }) as typeof globalThis.setImmediate)
55
-
56
- const defaultConnectOptions: IClientOptions = {
57
- keepalive: 60,
58
- reschedulePings: true,
59
- protocolId: 'MQTT',
60
- protocolVersion: 4,
61
- reconnectPeriod: 1000,
62
- connectTimeout: 30 * 1000,
63
- clean: true,
64
- resubscribe: true,
65
- subscribeBatchSize: null,
66
- writeCache: true,
67
- timerVariant: 'auto',
68
- }
69
-
70
- export type BaseMqttProtocol =
71
- | 'wss'
72
- | 'ws'
73
- | 'mqtt'
74
- | 'mqtts'
75
- | 'tcp'
76
- | 'ssl'
77
- | 'wx'
78
- | 'wxs'
79
- | 'ali'
80
- | 'alis'
81
-
82
- // create a type that allows all MqttProtocol + `+unix` string
83
- export type MqttProtocolWithUnix = `${BaseMqttProtocol}+unix`
84
-
85
- export type MqttProtocol = BaseMqttProtocol | MqttProtocolWithUnix
86
-
87
- export type StorePutCallback = () => void
88
-
89
- export interface ISecureClientOptions {
90
- /**
91
- * optional private keys in PEM format
92
- */
93
- key?: string | string[] | Buffer | Buffer[] | any[]
94
- keyPath?: string
95
- /**
96
- * optional cert chains in PEM format
97
- */
98
- cert?: string | string[] | Buffer | Buffer[]
99
- certPath?: string
100
- /**
101
- * Optionally override the trusted CA certificates in PEM format
102
- */
103
- ca?: string | string[] | Buffer | Buffer[]
104
- caPaths?: string | string[]
105
-
106
- rejectUnauthorized?: boolean
107
- /**
108
- * optional alpn's
109
- */
110
- ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array
111
- }
112
-
113
- export type AckHandler = (
114
- topic: string,
115
- message: Buffer,
116
- packet: any,
117
- cb: (error: Error | number, code?: number) => void,
118
- ) => void
119
-
120
- export interface IClientOptions extends ISecureClientOptions {
121
- /** CLIENT PROPERTIES */
122
-
123
- /** Encoding to use. Example 'binary' */
124
- encoding?: BufferEncoding
125
- /** Set browser buffer size. Default to 512KB */
126
- browserBufferSize?: number
127
- /** used in ws protocol to set `objectMode` */
128
- binary?: boolean
129
- /** Used on ali protocol */
130
- my?: any
131
- /** Manually call `connect` after creating client instance */
132
- manualConnect?: boolean
133
- /** Custom auth packet properties */
134
- authPacket?: Partial<IAuthPacket>
135
- /** Disable/Enable writeToStream.cacheNumbers */
136
- writeCache?: boolean
137
- /** Should be set to `host` */
138
- servername?: string
139
- /** The default protocol to use when using `servers` and no protocol is specified */
140
- defaultProtocol?: MqttProtocol
141
- /** Support clientId passed in the query string of the url */
142
- query?: Record<string, string>
143
- /** Auth string in the format <username>:<password> */
144
- auth?: string
145
- /** Optional SOCKS proxy to use for TCP / TLS connections , i.e. socks5://localhost:1333, socks4://localhost:1333, socks5h://localhost:1333 . Default is socks5h. */
146
- socksProxy?: string
147
- /** Timeout for establishing a socks connection */
148
- socksTimeout?: number
149
- /** Custom ack handler */
150
- customHandleAcks?: AckHandler
151
- /** Broker port */
152
- port?: number
153
- /** Broker host. Does NOT include port */
154
- host?: string
155
- /** @deprecated use `host instead */
156
- hostname?: string
157
- /** Set to true if the connection is to a unix socket */
158
- unixSocket?: boolean
159
- /** Websocket `path` added as suffix or Unix socket path when `unixSocket` option is true */
160
- path?: string
161
- /** The `MqttProtocol` to use */
162
- protocol?: MqttProtocol
163
-
164
- /** Websocket options */
165
- wsOptions?: ClientOptions | ClientRequestArgs | DuplexOptions
166
-
167
- /**
168
- * 1000 milliseconds, interval between two reconnections
169
- */
170
- reconnectPeriod?: number
171
- /**
172
- * Set to true to enable the reconnect period to apply if the initial
173
- * connection is denied with an error in the CONNACK packet, such as with an
174
- * authentication error.
175
- */
176
- reconnectOnConnackError?: boolean
177
- /**
178
- * 30 * 1000 milliseconds, time to wait before a CONNACK is received
179
- */
180
- connectTimeout?: number
181
-
182
- /**
183
- * a Store for the incoming packets
184
- */
185
- incomingStore?: IStore
186
- /**
187
- * a Store for the outgoing packets
188
- */
189
- outgoingStore?: IStore
190
-
191
- /** Enable/Disable queue for QoS 0 packets */
192
- queueQoSZero?: boolean
193
-
194
- /** Custom log function, default uses `debug` */
195
- log?: (...args: any[]) => void
196
-
197
- /** automatically use topic alias */
198
- autoUseTopicAlias?: boolean
199
-
200
- /** automatically assign topic alias */
201
- autoAssignTopicAlias?: boolean
202
-
203
- /** Set to false to disable ping reschedule. When enabled ping messages are rescheduled on each message sent */
204
- reschedulePings?: boolean
205
-
206
- /** List of broker servers. On each reconnect try the next server will be used */
207
- servers?: Array<{
208
- host: string
209
- port: number
210
- protocol?:
211
- | 'wss'
212
- | 'ws'
213
- | 'mqtt'
214
- | 'mqtts'
215
- | 'tcp'
216
- | 'ssl'
217
- | 'wx'
218
- | 'wxs'
219
- }>
220
- /**
221
- * true, set to false to disable re-subscribe functionality
222
- */
223
- resubscribe?: boolean
224
-
225
- /**
226
- * Maximum number of topics to include in a single SUBSCRIBE packet.
227
- * When subscribing to more topics than this, the client will automatically
228
- * split them into batches of this size.
229
- * This is useful on AWS IoT Core, which limits each SUBSCRIBE packet to 8 topics.
230
- */
231
- subscribeBatchSize?: number
232
-
233
- /** when defined this function will be called to transform the url string generated by MqttClient from provided options */
234
- transformWsUrl?: (
235
- url: string,
236
- options: IClientOptions,
237
- client: MqttClient,
238
- ) => string
239
-
240
- /** when defined this function will be called to create the Websocket instance, used to add custom protocols or websocket implementations */
241
- createWebsocket?: (
242
- url: string,
243
- websocketSubProtocols: string[],
244
- options: IClientOptions,
245
- ) => any
246
-
247
- /** Custom message id provider */
248
- messageIdProvider?: IMessageIdProvider
249
-
250
- /** When using websockets, this is the timeout used when writing to socket. Default 1000 (1s) */
251
- browserBufferTimeout?: number
252
-
253
- /**
254
- * When using websockets, this sets the `objectMode` option.
255
- * When in objectMode, streams can push Strings and Buffers
256
- * as well as any other JavaScript object.
257
- * Another major difference is that when in objectMode,
258
- * the internal buffering algorithm counts objects rather than bytes.
259
- * This means if we have a Transform stream with the highWaterMark option set to 5,
260
- * the stream will only buffer a maximum of 5 objects internally
261
- */
262
- objectMode?: boolean
263
-
264
- /** CONNECT PACKET PROPERTIES */
265
-
266
- /**
267
- * 'mqttjs_' + Math.random().toString(16).substr(2, 8)
268
- */
269
- clientId?: string
270
- /**
271
- * 3=MQTT 3.1 4=MQTT 3.1.1 5=MQTT 5.0. Defaults to 4
272
- */
273
- protocolVersion?: IConnectPacket['protocolVersion']
274
- /**
275
- * 'MQTT'
276
- */
277
- protocolId?: IConnectPacket['protocolId']
278
- /**
279
- * true, set to false to receive QoS 1 and 2 messages while offline
280
- */
281
- clean?: boolean
282
- /**
283
- * 60 seconds, set to 0 to disable
284
- */
285
- keepalive?: number
286
- /**
287
- * the username required by your broker, if any
288
- */
289
- username?: string
290
- /**
291
- * the password required by your broker, if any
292
- */
293
- password?: Buffer | string
294
- /**
295
- * a message that will sent by the broker automatically when the client disconnect badly.
296
- */
297
- will?: IConnectPacket['will']
298
- /** see `connect` packet: https://github.com/mqttjs/mqtt-packet/blob/master/types/index.d.ts#L65 */
299
- properties?: IConnectPacket['properties']
300
- /**
301
- * @description 'auto', set to 'native' or 'worker' if you're having issues with 'auto' detection
302
- * or pass a custom timer object
303
- */
304
- timerVariant?: TimerVariant | Timer
305
- /**
306
- * false, set to true to force the use of native WebSocket if you're having issues with the detection
307
- */
308
- forceNativeWebSocket?: boolean
309
- }
310
-
311
- export interface IClientPublishOptions {
312
- /**
313
- * the QoS
314
- */
315
- qos?: QoS
316
- /**
317
- * the retain flag
318
- */
319
- retain?: boolean
320
- /**
321
- * whether or not mark a message as duplicate
322
- */
323
- dup?: boolean
324
- /*
325
- * MQTT 5.0 properties object
326
- */
327
- properties?: IPublishPacket['properties']
328
- /**
329
- * callback called when message is put into `outgoingStore`
330
- */
331
- cbStorePut?: StorePutCallback
332
- }
333
-
334
- export interface IClientReconnectOptions {
335
- /**
336
- * a Store for the incoming packets
337
- */
338
- incomingStore?: Store
339
- /**
340
- * a Store for the outgoing packets
341
- */
342
- outgoingStore?: Store
343
- }
344
- export interface IClientSubscribeProperties {
345
- /*
346
- * MQTT 5.0 properties object of subscribe
347
- * */
348
- properties?: ISubscribePacket['properties']
349
- }
350
-
351
- export interface IClientSubscribeOptions extends IClientSubscribeProperties {
352
- /**
353
- * the QoS
354
- */
355
- qos: QoS
356
- /*
357
- * no local flag
358
- * */
359
- nl?: boolean
360
- /*
361
- * Retain As Published flag
362
- * */
363
- rap?: boolean
364
- /*
365
- * Retain Handling option
366
- * */
367
- rh?: number
368
- }
369
- export interface ISubscriptionRequest extends IClientSubscribeOptions {
370
- /**
371
- * is a subscribed to topic
372
- */
373
- topic: string
374
- }
375
-
376
- export interface ISubscriptionGrant
377
- extends Omit<ISubscriptionRequest, 'qos' | 'properties'> {
378
- /**
379
- * is the granted qos level on it, may return 128 on error
380
- */
381
- qos: QoS | 128
382
- }
383
-
384
- export type ISubscriptionMap = {
385
- /**
386
- * object which has topic names as object keys and as value the options, like {'test1': {qos: 0}, 'test2': {qos: 2}}.
387
- */
388
- [topic: string]: IClientSubscribeOptions
389
- } & {
390
- resubscribe?: boolean
391
- }
392
-
393
- export interface IClientUnsubscribeProperties {
394
- /*
395
- * MQTT 5.0 properties object for unsubscribe
396
- * */
397
- properties?: IUnsubscribePacket['properties']
398
- }
399
-
400
- export { IConnackPacket, IDisconnectPacket, IPublishPacket, Packet }
401
- export type OnConnectCallback = (packet: IConnackPacket) => void
402
- export type OnDisconnectCallback = (packet: IDisconnectPacket) => void
403
- export type ClientSubscribeCallback = (
404
- err: Error | null,
405
- granted?: ISubscriptionGrant[],
406
- packet?: ISubackPacket,
407
- ) => void
408
- export type OnMessageCallback = (
409
- topic: string,
410
- payload: Buffer,
411
- packet: IPublishPacket,
412
- ) => void
413
- export type OnPacketCallback = (packet: Packet) => void
414
- export type OnCloseCallback = () => void
415
- export type OnErrorCallback = (error: Error | ErrorWithReasonCode) => void
416
- export type PacketCallback = (
417
- error?: Error | ErrorWithReasonCode,
418
- packet?: Packet,
419
- ) => any
420
- export type CloseCallback = (error?: Error) => void
421
-
422
- export interface MqttClientEventCallbacks {
423
- connect: OnConnectCallback
424
- message: OnMessageCallback
425
- packetsend: OnPacketCallback
426
- packetreceive: OnPacketCallback
427
- disconnect: OnDisconnectCallback
428
- error: OnErrorCallback
429
- close: OnCloseCallback
430
- end: VoidCallback
431
- reconnect: VoidCallback
432
- offline: VoidCallback
433
- outgoingEmpty: VoidCallback
434
- }
435
-
436
- /**
437
- * MqttClient constructor
438
- *
439
- * @param {Stream} stream - stream
440
- * @param {Object} [options] - connection options
441
- * (see Connection#connect)
442
- */
443
- export default class MqttClient extends TypedEventEmitter<MqttClientEventCallbacks> {
444
- public static VERSION = MQTTJS_VERSION
445
-
446
- /** Public fields */
447
-
448
- /** It's true when client is connected to broker */
449
- public connected: boolean
450
-
451
- public disconnecting: boolean
452
-
453
- public disconnected: boolean
454
-
455
- public reconnecting: boolean
456
-
457
- public incomingStore: IStore
458
-
459
- public outgoingStore: IStore
460
-
461
- public options: IClientOptions
462
-
463
- public queueQoSZero: boolean
464
-
465
- public _reconnectCount: number
466
-
467
- public log: (...args: any[]) => void
468
-
469
- public messageIdProvider: IMessageIdProvider
470
-
471
- public outgoing: Record<
472
- number,
473
- { volatile: boolean; cb: (err: Error, packet?: Packet) => void }
474
- >
475
-
476
- public messageIdToTopic: Record<number, string[]>
477
-
478
- public noop: (error?: any) => void
479
-
480
- public keepaliveManager: KeepaliveManager
481
-
482
- /**
483
- * The connection to the Broker. In browsers env this also have `socket` property
484
- * set to the `WebSocket` instance.
485
- */
486
- public stream: IStream
487
-
488
- public queue: { packet: Packet; cb: PacketCallback }[]
489
-
490
- /* Private fields */
491
-
492
- /** Function used to build the stream */
493
- private streamBuilder: StreamBuilder
494
-
495
- private _resubscribeTopics: ISubscriptionMap
496
-
497
- private connackTimer: NodeJS.Timeout
498
-
499
- private reconnectTimer: NodeJS.Timeout
500
-
501
- private _storeProcessing: boolean
502
-
503
- /** keep a reference of packets that have been successfully processed from outgoing store */
504
- private _packetIdsDuringStoreProcessing: Record<number, boolean>
505
-
506
- private _storeProcessingQueue: {
507
- invoke: () => any
508
- cbStorePut?: DoneCallback
509
- callback: GenericCallback<any>
510
- }[]
511
-
512
- private _firstConnection: boolean
513
-
514
- private topicAliasRecv: TopicAliasRecv
515
-
516
- private topicAliasSend: TopicAliasSend
517
-
518
- private _deferredReconnect: () => void
519
-
520
- private connackPacket: IConnackPacket
521
-
522
- public static defaultId() {
523
- return `mqttjs_${Math.random().toString(16).substr(2, 8)}`
524
- }
525
-
526
- constructor(streamBuilder: StreamBuilder, options: IClientOptions) {
527
- super()
528
-
529
- this.options = options || {}
530
-
531
- // Defaults
532
- for (const k in defaultConnectOptions) {
533
- if (typeof this.options[k] === 'undefined') {
534
- this.options[k] = defaultConnectOptions[k]
535
- } else {
536
- this.options[k] = options[k]
537
- }
538
- }
539
-
540
- this.log = this.options.log || _debug('mqttjs:client')
541
- this.noop = this._noop.bind(this)
542
-
543
- this.log('MqttClient :: version:', MqttClient.VERSION)
544
-
545
- if (isWebWorker) {
546
- this.log('MqttClient :: environment', 'webworker')
547
- } else {
548
- this.log(
549
- 'MqttClient :: environment',
550
- isBrowser ? 'browser' : 'node',
551
- )
552
- }
553
-
554
- this.log('MqttClient :: options.protocol', options.protocol)
555
- this.log(
556
- 'MqttClient :: options.protocolVersion',
557
- options.protocolVersion,
558
- )
559
- this.log('MqttClient :: options.username', options.username)
560
- this.log('MqttClient :: options.keepalive', options.keepalive)
561
- this.log(
562
- 'MqttClient :: options.reconnectPeriod',
563
- options.reconnectPeriod,
564
- )
565
- this.log(
566
- 'MqttClient :: options.rejectUnauthorized',
567
- options.rejectUnauthorized,
568
- )
569
- this.log(
570
- 'MqttClient :: options.properties.topicAliasMaximum',
571
- options.properties
572
- ? options.properties.topicAliasMaximum
573
- : undefined,
574
- )
575
-
576
- this.options.clientId =
577
- typeof options.clientId === 'string'
578
- ? options.clientId
579
- : MqttClient.defaultId()
580
-
581
- this.log('MqttClient :: clientId', this.options.clientId)
582
-
583
- this.options.customHandleAcks =
584
- options.protocolVersion === 5 && options.customHandleAcks
585
- ? options.customHandleAcks
586
- : (...args) => {
587
- args[3](null, 0)
588
- }
589
-
590
- // Disable pre-generated write cache if requested. Will allocate buffers on-the-fly instead. WARNING: This can affect write performance
591
- if (!this.options.writeCache) {
592
- mqttPacket.writeToStream.cacheNumbers = false
593
- }
594
-
595
- this.streamBuilder = streamBuilder
596
-
597
- this.messageIdProvider =
598
- typeof this.options.messageIdProvider === 'undefined'
599
- ? new DefaultMessageIdProvider()
600
- : this.options.messageIdProvider
601
-
602
- // Inflight message storages
603
- this.outgoingStore = options.outgoingStore || new Store()
604
- this.incomingStore = options.incomingStore || new Store()
605
-
606
- // Should QoS zero messages be queued when the connection is broken?
607
- this.queueQoSZero =
608
- options.queueQoSZero === undefined ? true : options.queueQoSZero
609
-
610
- // map of subscribed topics to support reconnection
611
- this._resubscribeTopics = {}
612
-
613
- // map of a subscribe messageId and a topic
614
- this.messageIdToTopic = {}
615
-
616
- // Keepalive manager, setup in _setupKeepaliveManager
617
- this.keepaliveManager = null
618
- // Is the client connected?
619
- this.connected = false
620
- // Are we disconnecting?
621
- this.disconnecting = false
622
- // Are we reconnecting?
623
- this.reconnecting = false
624
- // Packet queue
625
- this.queue = []
626
- // connack timer
627
- this.connackTimer = null
628
- // Reconnect timer
629
- this.reconnectTimer = null
630
- // Is processing store?
631
- this._storeProcessing = false
632
- // Packet Ids are put into the store during store processing
633
- this._packetIdsDuringStoreProcessing = {}
634
- // Store processing queue
635
- this._storeProcessingQueue = []
636
-
637
- // Inflight callbacks
638
- this.outgoing = {}
639
-
640
- // True if connection is first time.
641
- this._firstConnection = true
642
-
643
- if (options.properties && options.properties.topicAliasMaximum > 0) {
644
- if (options.properties.topicAliasMaximum > 0xffff) {
645
- this.log(
646
- 'MqttClient :: options.properties.topicAliasMaximum is out of range',
647
- )
648
- } else {
649
- this.topicAliasRecv = new TopicAliasRecv(
650
- options.properties.topicAliasMaximum,
651
- )
652
- }
653
- }
654
-
655
- // Send queued packets
656
- this.on('connect', () => {
657
- const { queue } = this
658
-
659
- const deliver = () => {
660
- const entry = queue.shift()
661
- this.log('deliver :: entry %o', entry)
662
- let packet = null
663
-
664
- if (!entry) {
665
- this._resubscribe()
666
- return
667
- }
668
-
669
- packet = entry.packet
670
- this.log('deliver :: call _sendPacket for %o', packet)
671
- let send = true
672
- if (packet.messageId && packet.messageId !== 0) {
673
- if (!this.messageIdProvider.register(packet.messageId)) {
674
- send = false
675
- }
676
- }
677
- if (send) {
678
- this._sendPacket(packet, (err) => {
679
- if (entry.cb) {
680
- entry.cb(err)
681
- }
682
- deliver()
683
- })
684
- } else {
685
- this.log(
686
- 'messageId: %d has already used. The message is skipped and removed.',
687
- packet.messageId,
688
- )
689
- deliver()
690
- }
691
- }
692
-
693
- this.log('connect :: sending queued packets')
694
- deliver()
695
- })
696
-
697
- this.on('close', () => {
698
- this.log('close :: connected set to `false`')
699
- this.connected = false
700
-
701
- this.log('close :: clearing connackTimer')
702
- clearTimeout(this.connackTimer)
703
-
704
- this._destroyKeepaliveManager()
705
-
706
- if (this.topicAliasRecv) {
707
- this.topicAliasRecv.clear()
708
- }
709
-
710
- this.log('close :: calling _setupReconnect')
711
- this._setupReconnect()
712
- })
713
-
714
- if (!this.options.manualConnect) {
715
- this.log('MqttClient :: setting up stream')
716
- this.connect()
717
- }
718
- }
719
-
720
- /**
721
- * @param packet the packet received by the broker
722
- * @return the auth packet to be returned to the broker
723
- * @api public
724
- */
725
- public handleAuth(packet: IAuthPacket, callback: PacketCallback) {
726
- callback()
727
- }
728
-
729
- /**
730
- * Handle messages with backpressure support, one at a time.
731
- * Override at will.
732
- *
733
- * @param Packet packet the packet
734
- * @param Function callback call when finished
735
- * @api public
736
- */
737
- public handleMessage(packet: IPublishPacket, callback: DoneCallback) {
738
- callback()
739
- }
740
-
741
- /**
742
- * _nextId
743
- * @return unsigned int
744
- */
745
- private _nextId() {
746
- return this.messageIdProvider.allocate()
747
- }
748
-
749
- /**
750
- * getLastMessageId
751
- * @return unsigned int
752
- */
753
- public getLastMessageId() {
754
- return this.messageIdProvider.getLastAllocated()
755
- }
756
-
757
- /**
758
- * Setup the event handlers in the inner stream, sends `connect` and `auth` packets
759
- */
760
- public connect() {
761
- const writable = new Writable()
762
- const parser = mqttPacket.parser(this.options)
763
-
764
- let completeParse = null
765
- const packets = []
766
-
767
- this.log('connect :: calling method to clear reconnect')
768
- this._clearReconnect()
769
-
770
- if (this.disconnected && !this.reconnecting) {
771
- this.incomingStore = this.options.incomingStore || new Store()
772
- this.outgoingStore = this.options.outgoingStore || new Store()
773
- this.disconnecting = false
774
- this.disconnected = false
775
- }
776
-
777
- this.log(
778
- 'connect :: using streamBuilder provided to client to create stream',
779
- )
780
- this.stream = this.streamBuilder(this)
781
-
782
- parser.on('packet', (packet) => {
783
- this.log('parser :: on packet push to packets array.')
784
- packets.push(packet)
785
- })
786
-
787
- const work = () => {
788
- this.log('work :: getting next packet in queue')
789
- const packet = packets.shift()
790
-
791
- if (packet) {
792
- this.log('work :: packet pulled from queue')
793
- handlePacket(this, packet, nextTickWork)
794
- } else {
795
- this.log('work :: no packets in queue')
796
- const done = completeParse
797
- completeParse = null
798
- this.log('work :: done flag is %s', !!done)
799
- if (done) done()
800
- }
801
- }
802
-
803
- const nextTickWork = () => {
804
- if (packets.length) {
805
- nextTick(work)
806
- } else {
807
- const done = completeParse
808
- completeParse = null
809
- done()
810
- }
811
- }
812
-
813
- writable._write = (buf, enc, done) => {
814
- completeParse = done
815
- this.log('writable stream :: parsing buffer')
816
- parser.parse(buf)
817
- work()
818
- }
819
-
820
- const streamErrorHandler = (error) => {
821
- this.log('streamErrorHandler :: error', error.message)
822
- // error.code will only be set on NodeJS env, browser don't allow to detect errors on sockets
823
- // also emitting errors on browsers seems to create issues
824
- if (error.code) {
825
- // handle error
826
- this.log('streamErrorHandler :: emitting error')
827
- this.emit('error', error)
828
- } else {
829
- this.noop(error)
830
- }
831
- }
832
-
833
- this.log('connect :: pipe stream to writable stream')
834
- this.stream.pipe(writable)
835
-
836
- // Suppress connection errors
837
- this.stream.on('error', streamErrorHandler)
838
-
839
- // Echo stream close
840
- this.stream.on('close', () => {
841
- this.log('(%s)stream :: on close', this.options.clientId)
842
- this._flushVolatile()
843
- this.log('stream: emit close to MqttClient')
844
- this.emit('close')
845
- })
846
-
847
- // Send a connect packet
848
- this.log('connect: sending packet `connect`')
849
-
850
- const connectPacket: IConnectPacket = {
851
- cmd: 'connect',
852
- protocolId: this.options.protocolId,
853
- protocolVersion: this.options.protocolVersion,
854
- clean: this.options.clean,
855
- clientId: this.options.clientId,
856
- keepalive: this.options.keepalive,
857
- username: this.options.username,
858
- password: this.options.password as Buffer,
859
- properties: this.options.properties,
860
- }
861
-
862
- if (this.options.will) {
863
- connectPacket.will = {
864
- ...this.options.will,
865
- payload: this.options.will?.payload as Buffer,
866
- }
867
- }
868
-
869
- if (this.topicAliasRecv) {
870
- if (!connectPacket.properties) {
871
- connectPacket.properties = {}
872
- }
873
- if (this.topicAliasRecv) {
874
- connectPacket.properties.topicAliasMaximum =
875
- this.topicAliasRecv.max
876
- }
877
- }
878
- // avoid message queue
879
- this._writePacket(connectPacket)
880
-
881
- // Echo connection errors
882
- parser.on('error', this.emit.bind(this, 'error'))
883
-
884
- // auth
885
- if (this.options.properties) {
886
- if (
887
- !this.options.properties.authenticationMethod &&
888
- this.options.properties.authenticationData
889
- ) {
890
- this.end(() =>
891
- this.emit(
892
- 'error',
893
- new Error('Packet has no Authentication Method'),
894
- ),
895
- )
896
- return this
897
- }
898
- if (
899
- this.options.properties.authenticationMethod &&
900
- this.options.authPacket &&
901
- typeof this.options.authPacket === 'object'
902
- ) {
903
- const authPacket: IAuthPacket = {
904
- cmd: 'auth',
905
- reasonCode: 0,
906
- ...this.options.authPacket,
907
- }
908
- this._writePacket(authPacket)
909
- }
910
- }
911
-
912
- // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
913
- this.stream.setMaxListeners(1000)
914
-
915
- clearTimeout(this.connackTimer)
916
- this.connackTimer = setTimeout(() => {
917
- this.log(
918
- '!!connectTimeout hit!! Calling _cleanUp with force `true`',
919
- )
920
- this.emit('error', new Error('connack timeout'))
921
- this._cleanUp(true)
922
- }, this.options.connectTimeout)
923
-
924
- return this
925
- }
926
-
927
- /**
928
- * publish - publish <message> to <topic>
929
- *
930
- * @param {String} topic - topic to publish to
931
- * @param {String, Buffer} message - message to publish
932
- * @param {Object} [opts] - publish options, includes:
933
- * {Number} qos - qos level to publish on
934
- * {Boolean} retain - whether or not to retain the message
935
- * {Boolean} dup - whether or not mark a message as duplicate
936
- * {Function} cbStorePut - function(){} called when message is put into `outgoingStore`
937
- * @param {Function} [callback] - function(err){}
938
- * called when publish succeeds or fails
939
- * @returns {MqttClient} this - for chaining
940
- * @api public
941
- *
942
- * @example client.publish('topic', 'message');
943
- * @example
944
- * client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
945
- * @example client.publish('topic', 'message', console.log);
946
- */
947
- public publish(topic: string, message: string | Buffer): MqttClient
948
- public publish(
949
- topic: string,
950
- message: string | Buffer,
951
- callback?: PacketCallback,
952
- ): MqttClient
953
- public publish(
954
- topic: string,
955
- message: string | Buffer,
956
- opts?: IClientPublishOptions,
957
- callback?: PacketCallback,
958
- ): MqttClient
959
- public publish(
960
- topic: string,
961
- message: string | Buffer,
962
- opts?: IClientPublishOptions | DoneCallback,
963
- callback?: PacketCallback,
964
- ): MqttClient {
965
- this.log('publish :: message `%s` to topic `%s`', message, topic)
966
- const { options } = this
967
-
968
- // .publish(topic, payload, cb);
969
- if (typeof opts === 'function') {
970
- callback = opts as DoneCallback
971
- opts = null
972
- }
973
-
974
- opts = opts || {}
975
-
976
- // default opts
977
- const defaultOpts: IClientPublishOptions = {
978
- qos: 0,
979
- retain: false,
980
- dup: false,
981
- }
982
- opts = { ...defaultOpts, ...opts }
983
-
984
- const { qos, retain, dup, properties, cbStorePut } = opts
985
-
986
- if (this._checkDisconnecting(callback)) {
987
- return this
988
- }
989
-
990
- const publishProc = () => {
991
- let messageId = 0
992
- if (qos === 1 || qos === 2) {
993
- messageId = this._nextId()
994
- if (messageId === null) {
995
- this.log('No messageId left')
996
- return false
997
- }
998
- }
999
- const packet: IPublishPacket = {
1000
- cmd: 'publish',
1001
- topic,
1002
- payload: message,
1003
- qos,
1004
- retain,
1005
- messageId,
1006
- dup,
1007
- }
1008
-
1009
- if (options.protocolVersion === 5) {
1010
- packet.properties = properties
1011
- }
1012
-
1013
- this.log('publish :: qos', qos)
1014
- switch (qos) {
1015
- case 1:
1016
- case 2:
1017
- // Add to callbacks
1018
- this.outgoing[packet.messageId] = {
1019
- volatile: false,
1020
- cb: callback || this.noop,
1021
- }
1022
- this.log('MqttClient:publish: packet cmd: %s', packet.cmd)
1023
- this._sendPacket(packet, undefined, cbStorePut)
1024
- break
1025
- default:
1026
- this.log('MqttClient:publish: packet cmd: %s', packet.cmd)
1027
- this._sendPacket(packet, callback, cbStorePut)
1028
- break
1029
- }
1030
- return true
1031
- }
1032
-
1033
- if (
1034
- this._storeProcessing ||
1035
- this._storeProcessingQueue.length > 0 ||
1036
- !publishProc()
1037
- ) {
1038
- this._storeProcessingQueue.push({
1039
- invoke: publishProc,
1040
- cbStorePut: opts.cbStorePut,
1041
- callback,
1042
- })
1043
- }
1044
-
1045
- return this
1046
- }
1047
-
1048
- public publishAsync(
1049
- topic: string,
1050
- message: string | Buffer,
1051
- ): Promise<Packet | undefined>
1052
- public publishAsync(
1053
- topic: string,
1054
- message: string | Buffer,
1055
- opts?: IClientPublishOptions,
1056
- ): Promise<Packet | undefined>
1057
- public publishAsync(
1058
- topic: string,
1059
- message: string | Buffer,
1060
- opts?: IClientPublishOptions,
1061
- ): Promise<Packet | undefined> {
1062
- return new Promise((resolve, reject) => {
1063
- this.publish(topic, message, opts, (err, packet) => {
1064
- if (err) {
1065
- reject(err)
1066
- } else {
1067
- resolve(packet)
1068
- }
1069
- })
1070
- })
1071
- }
1072
-
1073
- /**
1074
- * subscribe - subscribe to <topic>
1075
- *
1076
- * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
1077
- * @param {Object} [opts] - optional subscription options, includes:
1078
- * {Number} qos - subscribe qos level
1079
- * @param {Function} [callback] - function(err, granted){} where:
1080
- * {Error} err - subscription error (none at the moment!)
1081
- * {Array} granted - array of {topic: 't', qos: 0}
1082
- * @returns {MqttClient} this - for chaining
1083
- * @api public
1084
- * @example client.subscribe('topic');
1085
- * @example client.subscribe('topic', {qos: 1});
1086
- * @example client.subscribe({'topic': {qos: 0}, 'topic2': {qos: 1}}, console.log);
1087
- * @example client.subscribe('topic', console.log);
1088
- */
1089
- public subscribe(
1090
- topicObject: string | string[] | ISubscriptionMap,
1091
- ): MqttClient
1092
- public subscribe(
1093
- topicObject: string | string[] | ISubscriptionMap,
1094
- callback?: ClientSubscribeCallback,
1095
- ): MqttClient
1096
- public subscribe(
1097
- topicObject: string | string[] | ISubscriptionMap,
1098
- opts?: IClientSubscribeOptions | IClientSubscribeProperties,
1099
- ): MqttClient
1100
- public subscribe(
1101
- topicObject: string | string[] | ISubscriptionMap,
1102
- opts?: IClientSubscribeOptions | IClientSubscribeProperties,
1103
- callback?: ClientSubscribeCallback,
1104
- ): MqttClient
1105
- public subscribe(
1106
- topicObject: string | string[] | ISubscriptionMap,
1107
- opts?:
1108
- | IClientSubscribeOptions
1109
- | IClientSubscribeProperties
1110
- | ClientSubscribeCallback,
1111
- callback?: ClientSubscribeCallback,
1112
- ): MqttClient {
1113
- const version = this.options.protocolVersion
1114
-
1115
- if (typeof opts === 'function') {
1116
- callback = opts
1117
- }
1118
-
1119
- callback = callback || this.noop
1120
-
1121
- // force re-subscribe on reconnect. This is only true
1122
- // when provided `topicObject` is `this._resubscribeTopics`
1123
- let resubscribe = false
1124
- let topicsList = []
1125
-
1126
- if (typeof topicObject === 'string') {
1127
- topicObject = [topicObject]
1128
- topicsList = topicObject
1129
- } else if (Array.isArray(topicObject)) {
1130
- topicsList = topicObject
1131
- } else if (typeof topicObject === 'object') {
1132
- resubscribe = topicObject.resubscribe
1133
- delete topicObject.resubscribe
1134
- topicsList = Object.keys(topicObject)
1135
- }
1136
-
1137
- // validate topics
1138
- const invalidTopic = validations.validateTopics(topicsList)
1139
- if (invalidTopic !== null) {
1140
- setImmediate(callback, new Error(`Invalid topic ${invalidTopic}`))
1141
- return this
1142
- }
1143
-
1144
- if (this._checkDisconnecting(callback)) {
1145
- this.log('subscribe: discconecting true')
1146
- return this
1147
- }
1148
-
1149
- const defaultOpts: Partial<IClientSubscribeOptions> = {
1150
- qos: 0,
1151
- }
1152
-
1153
- if (version === 5) {
1154
- defaultOpts.nl = false
1155
- defaultOpts.rap = false
1156
- defaultOpts.rh = 0
1157
- }
1158
- opts = { ...defaultOpts, ...opts } as IClientSubscribeOptions
1159
-
1160
- const properties = opts.properties
1161
-
1162
- const subs: ISubscriptionRequest[] = []
1163
-
1164
- const parseSub = (
1165
- topic: string,
1166
- subOptions?: IClientSubscribeOptions,
1167
- ) => {
1168
- // subOptions is defined only when providing a subs map, use opts otherwise
1169
- subOptions = (subOptions || opts) as IClientSubscribeOptions
1170
- if (
1171
- !Object.prototype.hasOwnProperty.call(
1172
- this._resubscribeTopics,
1173
- topic,
1174
- ) ||
1175
- this._resubscribeTopics[topic].qos < subOptions.qos ||
1176
- resubscribe
1177
- ) {
1178
- const currentOpts: ISubscription & IClientSubscribeProperties =
1179
- {
1180
- topic,
1181
- qos: subOptions.qos,
1182
- }
1183
- if (version === 5) {
1184
- currentOpts.nl = subOptions.nl
1185
- currentOpts.rap = subOptions.rap
1186
- currentOpts.rh = subOptions.rh
1187
- // use opts.properties
1188
- currentOpts.properties = properties
1189
- }
1190
- this.log(
1191
- 'subscribe: pushing topic `%s` and qos `%s` to subs list',
1192
- currentOpts.topic,
1193
- currentOpts.qos,
1194
- )
1195
- subs.push(currentOpts)
1196
- }
1197
- }
1198
-
1199
- if (Array.isArray(topicObject)) {
1200
- // array of topics
1201
- topicObject.forEach((topic) => {
1202
- this.log('subscribe: array topic %s', topic)
1203
- parseSub(topic)
1204
- })
1205
- } else {
1206
- // object topic --> subOptions (no properties)
1207
- Object.keys(topicObject).forEach((topic) => {
1208
- this.log(
1209
- 'subscribe: object topic %s, %o',
1210
- topic,
1211
- topicObject[topic],
1212
- )
1213
- parseSub(topic, topicObject[topic])
1214
- })
1215
- }
1216
-
1217
- if (!subs.length) {
1218
- callback(null, [])
1219
- return this
1220
- }
1221
-
1222
- const subscribeChunkedSubs = (
1223
- chunkedSubs: ISubscriptionRequest[],
1224
- messageId: number,
1225
- ): Promise<ISubackPacket> => {
1226
- const packet: ISubscribePacket = {
1227
- cmd: 'subscribe',
1228
- subscriptions: chunkedSubs,
1229
- // qos: 1,
1230
- // retain: false,
1231
- // dup: false,
1232
- messageId,
1233
- }
1234
-
1235
- if (properties) {
1236
- packet.properties = properties
1237
- }
1238
-
1239
- // subscriptions to resubscribe to in case of disconnect
1240
- if (this.options.resubscribe) {
1241
- this.log('subscribe :: resubscribe true')
1242
- const topics = []
1243
- chunkedSubs.forEach((sub) => {
1244
- if (this.options.reconnectPeriod > 0) {
1245
- const topic: IClientSubscribeOptions = { qos: sub.qos }
1246
- if (version === 5) {
1247
- topic.nl = sub.nl || false
1248
- topic.rap = sub.rap || false
1249
- topic.rh = sub.rh || 0
1250
- topic.properties = sub.properties
1251
- }
1252
- this._resubscribeTopics[sub.topic] = topic
1253
- topics.push(sub.topic)
1254
- }
1255
- })
1256
- this.messageIdToTopic[packet.messageId] = topics
1257
- }
1258
-
1259
- const promise = new Promise<ISubackPacket>((resolve, reject) => {
1260
- this.outgoing[packet.messageId] = {
1261
- volatile: true,
1262
- cb(err, packet2: ISubackPacket) {
1263
- if (!err) {
1264
- const { granted } = packet2
1265
- for (
1266
- let grantedI = 0;
1267
- grantedI < granted.length;
1268
- grantedI += 1
1269
- ) {
1270
- chunkedSubs[grantedI].qos = granted[
1271
- grantedI
1272
- ] as QoS
1273
- }
1274
- }
1275
-
1276
- if (!err) {
1277
- resolve(packet2)
1278
- } else {
1279
- reject(
1280
- new ErrorWithSubackPacket(err.message, packet2),
1281
- )
1282
- }
1283
- },
1284
- }
1285
- })
1286
- this.log('subscribe :: call _sendPacket')
1287
- this._sendPacket(packet)
1288
- return promise
1289
- }
1290
-
1291
- const subscribeProc = () => {
1292
- const batchSize = this.options.subscribeBatchSize ?? subs.length
1293
- const subscribePromises: Promise<ISubackPacket>[] = []
1294
-
1295
- for (let i = 0; i < subs.length; i += batchSize) {
1296
- const chunkedSubs = subs.slice(i, i + batchSize)
1297
- const messageId = this._nextId()
1298
- if (messageId === null) {
1299
- this.log('No messageId left')
1300
- return false
1301
- }
1302
- subscribePromises.push(
1303
- subscribeChunkedSubs(chunkedSubs, messageId),
1304
- )
1305
- }
1306
- Promise.all(subscribePromises)
1307
- .then((packets) => {
1308
- callback(null, subs, packets.at(-1))
1309
- })
1310
- .catch((err: ErrorWithSubackPacket) => {
1311
- callback(err, subs, err.packet)
1312
- })
1313
-
1314
- return true
1315
- }
1316
-
1317
- if (
1318
- this._storeProcessing ||
1319
- this._storeProcessingQueue.length > 0 ||
1320
- !subscribeProc()
1321
- ) {
1322
- this._storeProcessingQueue.push({
1323
- invoke: subscribeProc,
1324
- callback,
1325
- })
1326
- }
1327
-
1328
- return this
1329
- }
1330
-
1331
- public subscribeAsync(
1332
- topicObject: string | string[] | ISubscriptionMap,
1333
- ): Promise<ISubscriptionGrant[]>
1334
- public subscribeAsync(
1335
- topicObject: string | string[] | ISubscriptionMap,
1336
- opts?: IClientSubscribeOptions | IClientSubscribeProperties,
1337
- ): Promise<ISubscriptionGrant[]>
1338
- public subscribeAsync(
1339
- topicObject: string | string[] | ISubscriptionMap,
1340
- opts?: IClientSubscribeOptions | IClientSubscribeProperties,
1341
- ): Promise<ISubscriptionGrant[]> {
1342
- return new Promise((resolve, reject) => {
1343
- this.subscribe(topicObject, opts, (err, granted) => {
1344
- if (err) {
1345
- reject(err)
1346
- } else {
1347
- resolve(granted)
1348
- }
1349
- })
1350
- })
1351
- }
1352
-
1353
- /**
1354
- * unsubscribe - unsubscribe from topic(s)
1355
- *
1356
- * @param {String, Array} topic - topics to unsubscribe from
1357
- * @param {Object} [opts] - optional subscription options, includes:
1358
- * {Object} properties - properties of unsubscribe packet
1359
- * @param {Function} [callback] - callback fired on unsuback
1360
- * @returns {MqttClient} this - for chaining
1361
- * @api public
1362
- * @example client.unsubscribe('topic');
1363
- * @example client.unsubscribe('topic', console.log);
1364
- */
1365
- public unsubscribe(topic: string | string[]): MqttClient
1366
- public unsubscribe(
1367
- topic: string | string[],
1368
- opts?: IClientUnsubscribeProperties,
1369
- ): MqttClient
1370
- public unsubscribe(
1371
- topic: string | string[],
1372
- callback?: PacketCallback,
1373
- ): MqttClient
1374
- public unsubscribe(
1375
- topic: string | string[],
1376
- opts?: IClientUnsubscribeProperties,
1377
- callback?: PacketCallback,
1378
- ): MqttClient
1379
- public unsubscribe(
1380
- topic: string | string[],
1381
- opts?: IClientUnsubscribeProperties | PacketCallback,
1382
- callback?: PacketCallback,
1383
- ): MqttClient {
1384
- if (typeof topic === 'string') {
1385
- topic = [topic]
1386
- }
1387
-
1388
- if (typeof opts === 'function') {
1389
- callback = opts
1390
- }
1391
-
1392
- callback = callback || this.noop
1393
-
1394
- const invalidTopic = validations.validateTopics(topic)
1395
- if (invalidTopic !== null) {
1396
- setImmediate(callback, new Error(`Invalid topic ${invalidTopic}`))
1397
- return this
1398
- }
1399
-
1400
- if (this._checkDisconnecting(callback)) {
1401
- return this
1402
- }
1403
-
1404
- const unsubscribeProc = () => {
1405
- const messageId = this._nextId()
1406
- if (messageId === null) {
1407
- this.log('No messageId left')
1408
- return false
1409
- }
1410
- const packet: IUnsubscribePacket = {
1411
- cmd: 'unsubscribe',
1412
- // qos: 1,
1413
- messageId,
1414
- unsubscriptions: [],
1415
- }
1416
-
1417
- if (typeof topic === 'string') {
1418
- packet.unsubscriptions = [topic]
1419
- } else if (Array.isArray(topic)) {
1420
- packet.unsubscriptions = topic
1421
- }
1422
-
1423
- if (this.options.resubscribe) {
1424
- packet.unsubscriptions.forEach((topic2) => {
1425
- delete this._resubscribeTopics[topic2]
1426
- })
1427
- }
1428
-
1429
- if (typeof opts === 'object' && opts.properties) {
1430
- packet.properties = opts.properties
1431
- }
1432
-
1433
- this.outgoing[packet.messageId] = {
1434
- volatile: true,
1435
- cb: callback,
1436
- }
1437
-
1438
- this.log('unsubscribe: call _sendPacket')
1439
- this._sendPacket(packet)
1440
-
1441
- return true
1442
- }
1443
-
1444
- if (
1445
- this._storeProcessing ||
1446
- this._storeProcessingQueue.length > 0 ||
1447
- !unsubscribeProc()
1448
- ) {
1449
- this._storeProcessingQueue.push({
1450
- invoke: unsubscribeProc,
1451
- callback,
1452
- })
1453
- }
1454
-
1455
- return this
1456
- }
1457
-
1458
- public unsubscribeAsync(
1459
- topic: string | string[],
1460
- ): Promise<Packet | undefined>
1461
- public unsubscribeAsync(
1462
- topic: string | string[],
1463
- opts?: IClientUnsubscribeProperties,
1464
- ): Promise<Packet | undefined>
1465
- public unsubscribeAsync(
1466
- topic: string | string[],
1467
- opts?: IClientUnsubscribeProperties,
1468
- ): Promise<Packet | undefined> {
1469
- return new Promise((resolve, reject) => {
1470
- this.unsubscribe(topic, opts, (err, packet) => {
1471
- if (err) {
1472
- reject(err)
1473
- } else {
1474
- resolve(packet)
1475
- }
1476
- })
1477
- })
1478
- }
1479
-
1480
- /**
1481
- * end - close connection
1482
- *
1483
- * @returns {MqttClient} this - for chaining
1484
- * @param {Boolean} force - do not wait for all in-flight messages to be acked
1485
- * @param {Object} opts - added to the disconnect packet
1486
- * @param {Function} cb - called when the client has been closed
1487
- *
1488
- * @api public
1489
- */
1490
- public end(cb?: DoneCallback): MqttClient
1491
- public end(force?: boolean): MqttClient
1492
- public end(opts?: Partial<IDisconnectPacket>, cb?: DoneCallback): MqttClient
1493
- public end(force?: boolean, cb?: DoneCallback): MqttClient
1494
- public end(
1495
- force?: boolean,
1496
- opts?: Partial<IDisconnectPacket>,
1497
- cb?: DoneCallback,
1498
- ): MqttClient
1499
- public end(
1500
- force?: boolean | Partial<IDisconnectPacket> | DoneCallback,
1501
- opts?: Partial<IDisconnectPacket> | DoneCallback,
1502
- cb?: DoneCallback,
1503
- ): MqttClient {
1504
- this.log('end :: (%s)', this.options.clientId)
1505
-
1506
- if (force == null || typeof force !== 'boolean') {
1507
- cb = cb || (opts as DoneCallback)
1508
- opts = force as Partial<IDisconnectPacket>
1509
- force = false
1510
- }
1511
-
1512
- if (typeof opts !== 'object') {
1513
- cb = cb || opts
1514
- opts = null
1515
- }
1516
-
1517
- this.log('end :: cb? %s', !!cb)
1518
-
1519
- if (!cb || typeof cb !== 'function') {
1520
- cb = this.noop
1521
- }
1522
-
1523
- const closeStores = () => {
1524
- this.log('end :: closeStores: closing incoming and outgoing stores')
1525
- this.disconnected = true
1526
- this.incomingStore.close((e1) => {
1527
- this.outgoingStore.close((e2) => {
1528
- this.log('end :: closeStores: emitting end')
1529
- this.emit('end')
1530
- if (cb) {
1531
- const err = e1 || e2
1532
- this.log(
1533
- 'end :: closeStores: invoking callback with args',
1534
- )
1535
- cb(err)
1536
- }
1537
- })
1538
- })
1539
- if (this._deferredReconnect) {
1540
- this._deferredReconnect()
1541
- } else if (
1542
- this.options.reconnectPeriod === 0 ||
1543
- this.options.manualConnect
1544
- ) {
1545
- this.disconnecting = false
1546
- }
1547
- }
1548
-
1549
- const finish = () => {
1550
- // defer closesStores of an I/O cycle,
1551
- // just to make sure things are
1552
- // ok for websockets
1553
- this.log(
1554
- 'end :: (%s) :: finish :: calling _cleanUp with force %s',
1555
- this.options.clientId,
1556
- force,
1557
- )
1558
- this._cleanUp(
1559
- <boolean>force,
1560
- () => {
1561
- this.log(
1562
- 'end :: finish :: calling process.nextTick on closeStores',
1563
- )
1564
- // const boundProcess = nextTick.bind(null, closeStores)
1565
- nextTick(closeStores)
1566
- },
1567
- opts,
1568
- )
1569
- }
1570
-
1571
- if (this.disconnecting) {
1572
- cb()
1573
- return this
1574
- }
1575
-
1576
- this._clearReconnect()
1577
-
1578
- this.disconnecting = true
1579
-
1580
- if (!force && Object.keys(this.outgoing).length > 0) {
1581
- // wait 10ms, just to be sure we received all of it
1582
- this.log(
1583
- 'end :: (%s) :: calling finish in 10ms once outgoing is empty',
1584
- this.options.clientId,
1585
- )
1586
- this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
1587
- } else {
1588
- this.log(
1589
- 'end :: (%s) :: immediately calling finish',
1590
- this.options.clientId,
1591
- )
1592
- finish()
1593
- }
1594
-
1595
- return this
1596
- }
1597
-
1598
- public endAsync(): Promise<void>
1599
- public endAsync(force?: boolean): Promise<void>
1600
- public endAsync(opts?: Partial<IDisconnectPacket>): Promise<void>
1601
- public endAsync(
1602
- force?: boolean,
1603
- opts?: Partial<IDisconnectPacket>,
1604
- ): Promise<void>
1605
- public endAsync(
1606
- force?: boolean | Partial<IDisconnectPacket>,
1607
- opts?: Partial<IDisconnectPacket>,
1608
- ): Promise<void> {
1609
- return new Promise((resolve, reject) => {
1610
- this.end(force as boolean, opts, (err) => {
1611
- if (err) {
1612
- reject(err)
1613
- } else {
1614
- resolve()
1615
- }
1616
- })
1617
- })
1618
- }
1619
-
1620
- /**
1621
- * removeOutgoingMessage - remove a message in outgoing store
1622
- * the outgoing callback will be called withe Error('Message removed') if the message is removed
1623
- *
1624
- * @param {Number} messageId - messageId to remove message
1625
- * @returns {MqttClient} this - for chaining
1626
- * @api public
1627
- *
1628
- * @example client.removeOutgoingMessage(client.getLastAllocated());
1629
- */
1630
- public removeOutgoingMessage(messageId: number): MqttClient {
1631
- if (this.outgoing[messageId]) {
1632
- const { cb } = this.outgoing[messageId]
1633
- this._removeOutgoingAndStoreMessage(messageId, () => {
1634
- cb(new Error('Message removed'))
1635
- })
1636
- }
1637
- return this
1638
- }
1639
-
1640
- /**
1641
- * reconnect - connect again using the same options as connect()
1642
- *
1643
- * @param {Object} [opts] - optional reconnect options, includes:
1644
- * {Store} incomingStore - a store for the incoming packets
1645
- * {Store} outgoingStore - a store for the outgoing packets
1646
- * if opts is not given, current stores are used
1647
- * @returns {MqttClient} this - for chaining
1648
- *
1649
- * @api public
1650
- */
1651
- public reconnect(
1652
- opts?: Pick<IClientOptions, 'incomingStore' | 'outgoingStore'>,
1653
- ): MqttClient {
1654
- this.log('client reconnect')
1655
- const f = () => {
1656
- if (opts) {
1657
- this.options.incomingStore = opts.incomingStore
1658
- this.options.outgoingStore = opts.outgoingStore
1659
- } else {
1660
- this.options.incomingStore = null
1661
- this.options.outgoingStore = null
1662
- }
1663
- this.incomingStore = this.options.incomingStore || new Store()
1664
- this.outgoingStore = this.options.outgoingStore || new Store()
1665
- this.disconnecting = false
1666
- this.disconnected = false
1667
- this._deferredReconnect = null
1668
- this._reconnect()
1669
- }
1670
-
1671
- if (this.disconnecting && !this.disconnected) {
1672
- this._deferredReconnect = f
1673
- } else {
1674
- f()
1675
- }
1676
- return this
1677
- }
1678
-
1679
- /**
1680
- * PRIVATE METHODS
1681
- * =====================
1682
- * */
1683
-
1684
- /**
1685
- * Flush all outgoing messages marked as `volatile` in `outgoing` queue. Volatile messages
1686
- * typically are subscription and unsubscription requests.
1687
- */
1688
- private _flushVolatile() {
1689
- if (this.outgoing) {
1690
- this.log(
1691
- '_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function',
1692
- )
1693
- Object.keys(this.outgoing).forEach((messageId) => {
1694
- if (
1695
- this.outgoing[messageId].volatile &&
1696
- typeof this.outgoing[messageId].cb === 'function'
1697
- ) {
1698
- this.outgoing[messageId].cb(new Error('Connection closed'))
1699
- delete this.outgoing[messageId]
1700
- }
1701
- })
1702
- }
1703
- }
1704
-
1705
- /**
1706
- * Flush all outgoing messages
1707
- */
1708
- private _flush() {
1709
- if (this.outgoing) {
1710
- this.log('_flush: queue exists? %b', !!this.outgoing)
1711
- Object.keys(this.outgoing).forEach((messageId) => {
1712
- if (typeof this.outgoing[messageId].cb === 'function') {
1713
- this.outgoing[messageId].cb(new Error('Connection closed'))
1714
- // This is suspicious. Why do we only delete this if we have a callback?
1715
- // If this is by-design, then adding no as callback would cause this to get deleted unintentionally.
1716
- delete this.outgoing[messageId]
1717
- }
1718
- })
1719
- }
1720
- }
1721
-
1722
- private _removeTopicAliasAndRecoverTopicName(packet: IPublishPacket) {
1723
- let alias: number | undefined
1724
-
1725
- if (packet.properties) {
1726
- alias = packet.properties.topicAlias
1727
- }
1728
-
1729
- let topic = packet.topic.toString()
1730
-
1731
- this.log(
1732
- '_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o',
1733
- alias,
1734
- topic,
1735
- )
1736
-
1737
- if (topic.length === 0) {
1738
- // restore topic from alias
1739
- if (typeof alias === 'undefined') {
1740
- return new Error('Unregistered Topic Alias')
1741
- }
1742
- topic = this.topicAliasSend.getTopicByAlias(alias)
1743
- if (typeof topic === 'undefined') {
1744
- return new Error('Unregistered Topic Alias')
1745
- }
1746
- packet.topic = topic
1747
- }
1748
- if (alias) {
1749
- delete packet.properties.topicAlias
1750
- }
1751
- }
1752
-
1753
- private _checkDisconnecting(callback?: GenericCallback<any>) {
1754
- if (this.disconnecting) {
1755
- if (callback && callback !== this.noop) {
1756
- callback(new Error('client disconnecting'))
1757
- } else {
1758
- this.emit('error', new Error('client disconnecting'))
1759
- }
1760
- }
1761
- return this.disconnecting
1762
- }
1763
-
1764
- /**
1765
- * _reconnect - implement reconnection
1766
- * @api private
1767
- */
1768
- private _reconnect() {
1769
- this.log('_reconnect: emitting reconnect to client')
1770
- this.emit('reconnect')
1771
- if (this.connected) {
1772
- this.end(() => {
1773
- this.connect()
1774
- })
1775
- this.log('client already connected. disconnecting first.')
1776
- } else {
1777
- this.log('_reconnect: calling connect')
1778
- this.connect()
1779
- }
1780
- }
1781
-
1782
- /**
1783
- * _setupReconnect - setup reconnect timer
1784
- */
1785
- private _setupReconnect() {
1786
- if (
1787
- !this.disconnecting &&
1788
- !this.reconnectTimer &&
1789
- this.options.reconnectPeriod > 0
1790
- ) {
1791
- if (!this.reconnecting) {
1792
- this.log('_setupReconnect :: emit `offline` state')
1793
- this.emit('offline')
1794
- this.log('_setupReconnect :: set `reconnecting` to `true`')
1795
- this.reconnecting = true
1796
- }
1797
- this.log(
1798
- '_setupReconnect :: setting reconnectTimer for %d ms',
1799
- this.options.reconnectPeriod,
1800
- )
1801
- this.reconnectTimer = setInterval(() => {
1802
- this.log('reconnectTimer :: reconnect triggered!')
1803
- this._reconnect()
1804
- }, this.options.reconnectPeriod)
1805
- } else {
1806
- this.log('_setupReconnect :: doing nothing...')
1807
- }
1808
- }
1809
-
1810
- /**
1811
- * _clearReconnect - clear the reconnect timer
1812
- */
1813
- private _clearReconnect() {
1814
- this.log('_clearReconnect : clearing reconnect timer')
1815
- if (this.reconnectTimer) {
1816
- clearInterval(this.reconnectTimer)
1817
- this.reconnectTimer = null
1818
- }
1819
- }
1820
-
1821
- /**
1822
- * _cleanUp - clean up on connection end
1823
- * @api private
1824
- */
1825
- private _cleanUp(forced: boolean, done?: DoneCallback, opts = {}) {
1826
- if (done) {
1827
- this.log('_cleanUp :: done callback provided for on stream close')
1828
- this.stream.on('close', done)
1829
- }
1830
-
1831
- this.log('_cleanUp :: forced? %s', forced)
1832
- if (forced) {
1833
- if (this.options.reconnectPeriod === 0 && this.options.clean) {
1834
- this._flush()
1835
- }
1836
- this.log(
1837
- '_cleanUp :: (%s) :: destroying stream',
1838
- this.options.clientId,
1839
- )
1840
- this.stream.destroy()
1841
- } else {
1842
- const packet: IDisconnectPacket = { cmd: 'disconnect', ...opts }
1843
- this.log(
1844
- '_cleanUp :: (%s) :: call _sendPacket with disconnect packet',
1845
- this.options.clientId,
1846
- )
1847
- this._sendPacket(packet, () => {
1848
- this.log(
1849
- '_cleanUp :: (%s) :: destroying stream',
1850
- this.options.clientId,
1851
- )
1852
- setImmediate(() => {
1853
- this.stream.end(() => {
1854
- this.log(
1855
- '_cleanUp :: (%s) :: stream destroyed',
1856
- this.options.clientId,
1857
- )
1858
- // once stream is closed the 'close' event will fire and that will
1859
- // emit client `close` event and call `done` callback if done is provided
1860
- })
1861
- })
1862
- })
1863
- }
1864
-
1865
- if (!this.disconnecting && !this.reconnecting) {
1866
- this.log(
1867
- '_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect.',
1868
- )
1869
- this._clearReconnect()
1870
- this._setupReconnect()
1871
- }
1872
-
1873
- this._destroyKeepaliveManager()
1874
-
1875
- if (done && !this.connected) {
1876
- this.log(
1877
- '_cleanUp :: (%s) :: removing stream `done` callback `close` listener',
1878
- this.options.clientId,
1879
- )
1880
- this.stream.removeListener('close', done)
1881
- done()
1882
- }
1883
- }
1884
-
1885
- private _storeAndSend(
1886
- packet: Packet,
1887
- cb: DoneCallback,
1888
- cbStorePut: DoneCallback,
1889
- ) {
1890
- this.log(
1891
- 'storeAndSend :: store packet with cmd %s to outgoingStore',
1892
- packet.cmd,
1893
- )
1894
- let storePacket = packet
1895
- let err: Error | undefined
1896
- if (storePacket.cmd === 'publish') {
1897
- // The original packet is for sending.
1898
- // The cloned storePacket is for storing to resend on reconnect.
1899
- // Topic Alias must not be used after disconnected.
1900
- storePacket = clone(packet)
1901
- err = this._removeTopicAliasAndRecoverTopicName(
1902
- storePacket as IPublishPacket,
1903
- )
1904
- if (err) {
1905
- return cb && cb(err)
1906
- }
1907
- }
1908
- this.outgoingStore.put(storePacket, (err2) => {
1909
- if (err2) {
1910
- return cb && cb(err2)
1911
- }
1912
- cbStorePut()
1913
- this._writePacket(packet, cb)
1914
- })
1915
- }
1916
-
1917
- private _applyTopicAlias(packet: Packet) {
1918
- if (this.options.protocolVersion === 5) {
1919
- if (packet.cmd === 'publish') {
1920
- let alias: number
1921
- if (packet.properties) {
1922
- alias = packet.properties.topicAlias
1923
- }
1924
- const topic = packet.topic.toString()
1925
- if (this.topicAliasSend) {
1926
- if (alias) {
1927
- if (topic.length !== 0) {
1928
- // register topic alias
1929
- this.log(
1930
- 'applyTopicAlias :: register topic: %s - alias: %d',
1931
- topic,
1932
- alias,
1933
- )
1934
- if (!this.topicAliasSend.put(topic, alias)) {
1935
- this.log(
1936
- 'applyTopicAlias :: error out of range. topic: %s - alias: %d',
1937
- topic,
1938
- alias,
1939
- )
1940
- return new Error(
1941
- 'Sending Topic Alias out of range',
1942
- )
1943
- }
1944
- }
1945
- } else if (topic.length !== 0) {
1946
- if (this.options.autoAssignTopicAlias) {
1947
- alias = this.topicAliasSend.getAliasByTopic(topic)
1948
- if (alias) {
1949
- packet.topic = ''
1950
- packet.properties = {
1951
- ...packet.properties,
1952
- topicAlias: alias,
1953
- }
1954
- this.log(
1955
- 'applyTopicAlias :: auto assign(use) topic: %s - alias: %d',
1956
- topic,
1957
- alias,
1958
- )
1959
- } else {
1960
- alias = this.topicAliasSend.getLruAlias()
1961
- this.topicAliasSend.put(topic, alias)
1962
- packet.properties = {
1963
- ...packet.properties,
1964
- topicAlias: alias,
1965
- }
1966
- this.log(
1967
- 'applyTopicAlias :: auto assign topic: %s - alias: %d',
1968
- topic,
1969
- alias,
1970
- )
1971
- }
1972
- } else if (this.options.autoUseTopicAlias) {
1973
- alias = this.topicAliasSend.getAliasByTopic(topic)
1974
- if (alias) {
1975
- packet.topic = ''
1976
- packet.properties = {
1977
- ...packet.properties,
1978
- topicAlias: alias,
1979
- }
1980
- this.log(
1981
- 'applyTopicAlias :: auto use topic: %s - alias: %d',
1982
- topic,
1983
- alias,
1984
- )
1985
- }
1986
- }
1987
- }
1988
- } else if (alias) {
1989
- this.log(
1990
- 'applyTopicAlias :: error out of range. topic: %s - alias: %d',
1991
- topic,
1992
- alias,
1993
- )
1994
- return new Error('Sending Topic Alias out of range')
1995
- }
1996
- }
1997
- }
1998
- }
1999
-
2000
- private _noop(err?: Error) {
2001
- this.log('noop ::', err)
2002
- }
2003
-
2004
- /** Writes the packet to stream and emits events */
2005
- private _writePacket(packet: Packet, cb?: DoneCallback) {
2006
- this.log('_writePacket :: packet: %O', packet)
2007
- this.log('_writePacket :: emitting `packetsend`')
2008
-
2009
- this.emit('packetsend', packet)
2010
-
2011
- this.log('_writePacket :: writing to stream')
2012
- const result = mqttPacket.writeToStream(
2013
- packet,
2014
- this.stream,
2015
- this.options,
2016
- )
2017
- this.log('_writePacket :: writeToStream result %s', result)
2018
- if (!result && cb && cb !== this.noop) {
2019
- this.log(
2020
- '_writePacket :: handle events on `drain` once through callback.',
2021
- )
2022
- this.stream.once('drain', cb)
2023
- } else if (cb) {
2024
- this.log('_writePacket :: invoking cb')
2025
- cb()
2026
- }
2027
- }
2028
-
2029
- /**
2030
- * _sendPacket - send or queue a packet
2031
- * @param {Object} packet - packet options
2032
- * @param {Function} cb - callback when the packet is sent
2033
- * @param {Function} cbStorePut - called when message is put into outgoingStore
2034
- * @param {Boolean} noStore - send without put to the store
2035
- * @api private
2036
- */
2037
- private _sendPacket(
2038
- packet: Packet,
2039
- cb?: DoneCallback,
2040
- cbStorePut?: DoneCallback,
2041
- noStore?: boolean,
2042
- ) {
2043
- this.log('_sendPacket :: (%s) :: start', this.options.clientId)
2044
- cbStorePut = cbStorePut || this.noop
2045
- cb = cb || this.noop
2046
-
2047
- const err = this._applyTopicAlias(packet)
2048
- if (err) {
2049
- cb(err)
2050
- return
2051
- }
2052
-
2053
- if (!this.connected) {
2054
- // allow auth packets to be sent while authenticating with the broker (mqtt5 enhanced auth)
2055
- if (packet.cmd === 'auth') {
2056
- this._writePacket(packet, cb)
2057
- return
2058
- }
2059
-
2060
- this.log(
2061
- '_sendPacket :: client not connected. Storing packet offline.',
2062
- )
2063
- this._storePacket(packet, cb, cbStorePut)
2064
- return
2065
- }
2066
-
2067
- // If "noStore" is true, the message is sent without being recorded in the store.
2068
- // Messages that have not received puback or pubcomp remain in the store after disconnection
2069
- // and are resent from the store upon reconnection.
2070
- // For resend upon reconnection, "noStore" is set to true. This is because the message is already stored in the store.
2071
- // This is to avoid interrupting other processes while recording to the store.
2072
- if (noStore) {
2073
- this._writePacket(packet, cb)
2074
- return
2075
- }
2076
-
2077
- switch (packet.cmd) {
2078
- case 'publish':
2079
- break
2080
- case 'pubrel':
2081
- this._storeAndSend(packet, cb, cbStorePut)
2082
- return
2083
- default:
2084
- this._writePacket(packet, cb)
2085
- return
2086
- }
2087
-
2088
- switch (packet.qos) {
2089
- case 2:
2090
- case 1:
2091
- this._storeAndSend(packet, cb, cbStorePut)
2092
- break
2093
- /**
2094
- * no need of case here since it will be caught by default
2095
- * and jshint comply that before default it must be a break
2096
- * anyway it will result in -1 evaluation
2097
- */
2098
- case 0:
2099
- /* falls through */
2100
- default:
2101
- this._writePacket(packet, cb)
2102
- break
2103
- }
2104
- this.log('_sendPacket :: (%s) :: end', this.options.clientId)
2105
- }
2106
-
2107
- /**
2108
- * _storePacket - queue a packet
2109
- * @param {Object} packet - packet options
2110
- * @param {Function} cb - callback when the packet is sent
2111
- * @param {Function} cbStorePut - called when message is put into outgoingStore
2112
- * @api private
2113
- */
2114
- private _storePacket(
2115
- packet: Packet,
2116
- cb: DoneCallback,
2117
- cbStorePut: DoneCallback,
2118
- ) {
2119
- this.log('_storePacket :: packet: %o', packet)
2120
- this.log('_storePacket :: cb? %s', !!cb)
2121
- cbStorePut = cbStorePut || this.noop
2122
-
2123
- let storePacket = packet
2124
- if (storePacket.cmd === 'publish') {
2125
- // The original packet is for sending.
2126
- // The cloned storePacket is for storing to resend on reconnect.
2127
- // Topic Alias must not be used after disconnected.
2128
- storePacket = clone(packet)
2129
- const err = this._removeTopicAliasAndRecoverTopicName(
2130
- storePacket as IPublishPacket,
2131
- )
2132
- if (err) {
2133
- return cb && cb(err)
2134
- }
2135
- }
2136
-
2137
- const qos = (storePacket as IPublishPacket).qos || 0
2138
- // check that the packet is not a qos of 0, or that the command is not a publish
2139
- if ((qos === 0 && this.queueQoSZero) || storePacket.cmd !== 'publish') {
2140
- this.queue.push({ packet: storePacket, cb })
2141
- } else if (qos > 0) {
2142
- cb = this.outgoing[storePacket.messageId]
2143
- ? this.outgoing[storePacket.messageId].cb
2144
- : null
2145
- this.outgoingStore.put(storePacket, (err) => {
2146
- if (err) {
2147
- return cb && cb(err)
2148
- }
2149
- cbStorePut()
2150
- })
2151
- } else if (cb) {
2152
- cb(new Error('No connection to broker'))
2153
- }
2154
- }
2155
-
2156
- /**
2157
- * _setupKeepaliveManager - setup the keepalive manager
2158
- */
2159
- private _setupKeepaliveManager() {
2160
- this.log(
2161
- '_setupKeepaliveManager :: keepalive %d (seconds)',
2162
- this.options.keepalive,
2163
- )
2164
-
2165
- if (!this.keepaliveManager && this.options.keepalive) {
2166
- this.keepaliveManager = new KeepaliveManager(
2167
- this,
2168
- this.options.timerVariant,
2169
- )
2170
- }
2171
- }
2172
-
2173
- private _destroyKeepaliveManager() {
2174
- if (this.keepaliveManager) {
2175
- this.log('_destroyKeepaliveManager :: destroying keepalive manager')
2176
- this.keepaliveManager.destroy()
2177
- this.keepaliveManager = null
2178
- }
2179
- }
2180
-
2181
- /**
2182
- * Reschedule the ping interval
2183
- */
2184
- public reschedulePing(force = false) {
2185
- if (
2186
- this.keepaliveManager &&
2187
- this.options.keepalive &&
2188
- (force || this.options.reschedulePings)
2189
- ) {
2190
- this._reschedulePing()
2191
- }
2192
- }
2193
-
2194
- /**
2195
- * Mostly needed for test purposes
2196
- */
2197
- private _reschedulePing() {
2198
- this.log('_reschedulePing :: rescheduling ping')
2199
- this.keepaliveManager.reschedule()
2200
- }
2201
-
2202
- public sendPing() {
2203
- this.log('_sendPing :: sending pingreq')
2204
- this._sendPacket({ cmd: 'pingreq' })
2205
- }
2206
-
2207
- public onKeepaliveTimeout() {
2208
- this.emit('error', new Error('Keepalive timeout'))
2209
- this.log('onKeepaliveTimeout :: calling _cleanUp with force true')
2210
- this._cleanUp(true)
2211
- }
2212
-
2213
- /**
2214
- * _resubscribe
2215
- * @api private
2216
- */
2217
- private _resubscribe() {
2218
- this.log('_resubscribe')
2219
- const _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics)
2220
- if (
2221
- !this._firstConnection &&
2222
- // Only resubscribe in case of clean connection or if the server does not have a stored session.
2223
- // The Session Present flag is available since v3.1.1
2224
- // https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc385349254
2225
- (this.options.clean ||
2226
- (this.options.protocolVersion >= 4 &&
2227
- !this.connackPacket.sessionPresent)) &&
2228
- _resubscribeTopicsKeys.length > 0
2229
- ) {
2230
- if (this.options.resubscribe) {
2231
- if (this.options.protocolVersion === 5) {
2232
- this.log('_resubscribe: protocolVersion 5')
2233
- for (
2234
- let topicI = 0;
2235
- topicI < _resubscribeTopicsKeys.length;
2236
- topicI++
2237
- ) {
2238
- const resubscribeTopic: ISubscriptionMap = {}
2239
- resubscribeTopic[_resubscribeTopicsKeys[topicI]] =
2240
- this._resubscribeTopics[
2241
- _resubscribeTopicsKeys[topicI]
2242
- ]
2243
- resubscribeTopic.resubscribe = true
2244
- this.subscribe(resubscribeTopic, {
2245
- properties:
2246
- resubscribeTopic[_resubscribeTopicsKeys[topicI]]
2247
- .properties,
2248
- })
2249
- }
2250
- } else {
2251
- this._resubscribeTopics.resubscribe = true
2252
- this.subscribe(this._resubscribeTopics)
2253
- }
2254
- } else {
2255
- this._resubscribeTopics = {}
2256
- }
2257
- }
2258
-
2259
- this._firstConnection = false
2260
- }
2261
-
2262
- /**
2263
- * _onConnect
2264
- *
2265
- * @api private
2266
- */
2267
- private _onConnect(packet: IConnackPacket) {
2268
- if (this.disconnected) {
2269
- this.emit('connect', packet)
2270
- return
2271
- }
2272
-
2273
- this.connackPacket = packet
2274
- this.messageIdProvider.clear()
2275
- this._setupKeepaliveManager()
2276
-
2277
- this.connected = true
2278
-
2279
- /** check if there are packets in outgoing store and stream them */
2280
- const startStreamProcess = () => {
2281
- let outStore = this.outgoingStore.createStream()
2282
-
2283
- /** destroy the outgoing store stream */
2284
- const remove = () => {
2285
- outStore.destroy()
2286
- outStore = null
2287
- this._flushStoreProcessingQueue()
2288
- clearStoreProcessing()
2289
- }
2290
-
2291
- /** stop store processing and clear packets id processed */
2292
- const clearStoreProcessing = () => {
2293
- this._storeProcessing = false
2294
- this._packetIdsDuringStoreProcessing = {}
2295
- }
2296
-
2297
- this.once('close', remove)
2298
- outStore.on('error', (err) => {
2299
- clearStoreProcessing()
2300
- this._flushStoreProcessingQueue()
2301
- this.removeListener('close', remove)
2302
- this.emit('error', err)
2303
- })
2304
-
2305
- /** Read next packet in outgoing store and send it */
2306
- const storeDeliver = () => {
2307
- // edge case, we wrapped this twice
2308
- if (!outStore) {
2309
- return
2310
- }
2311
-
2312
- const packet2 = outStore.read(1)
2313
-
2314
- let cb: PacketCallback
2315
-
2316
- if (!packet2) {
2317
- // read when data is available in the future
2318
- outStore.once('readable', storeDeliver)
2319
- return
2320
- }
2321
-
2322
- this._storeProcessing = true
2323
-
2324
- // Skip already processed store packets
2325
- if (this._packetIdsDuringStoreProcessing[packet2.messageId]) {
2326
- storeDeliver()
2327
- return
2328
- }
2329
-
2330
- // Avoid unnecessary stream read operations when disconnected
2331
- if (!this.disconnecting && !this.reconnectTimer) {
2332
- cb = this.outgoing[packet2.messageId]
2333
- ? this.outgoing[packet2.messageId].cb
2334
- : null
2335
- this.outgoing[packet2.messageId] = {
2336
- volatile: false,
2337
- cb(err, status) {
2338
- // Ensure that the original callback passed in to publish gets invoked
2339
- if (cb) {
2340
- cb(err, status)
2341
- }
2342
-
2343
- storeDeliver()
2344
- },
2345
- }
2346
- this._packetIdsDuringStoreProcessing[packet2.messageId] =
2347
- true
2348
- if (this.messageIdProvider.register(packet2.messageId)) {
2349
- this._sendPacket(packet2, undefined, undefined, true)
2350
- } else {
2351
- this.log(
2352
- 'messageId: %d has already used.',
2353
- packet2.messageId,
2354
- )
2355
- }
2356
- } else if (outStore.destroy) {
2357
- outStore.destroy()
2358
- }
2359
- }
2360
-
2361
- outStore.on('end', () => {
2362
- let allProcessed = true
2363
- for (const id in this._packetIdsDuringStoreProcessing) {
2364
- if (!this._packetIdsDuringStoreProcessing[id]) {
2365
- allProcessed = false
2366
- break
2367
- }
2368
- }
2369
- this.removeListener('close', remove)
2370
- if (allProcessed) {
2371
- clearStoreProcessing()
2372
- this._invokeAllStoreProcessingQueue()
2373
- this.emit('connect', packet)
2374
- } else {
2375
- startStreamProcess()
2376
- }
2377
- })
2378
- storeDeliver()
2379
- }
2380
- // start flowing
2381
- startStreamProcess()
2382
- }
2383
-
2384
- private _invokeStoreProcessingQueue() {
2385
- // If _storeProcessing is true, the message is resending.
2386
- // During resend, processing is skipped to prevent new messages from interrupting. #1635
2387
- if (!this._storeProcessing && this._storeProcessingQueue.length > 0) {
2388
- const f = this._storeProcessingQueue[0]
2389
- if (f && f.invoke()) {
2390
- this._storeProcessingQueue.shift()
2391
- return true
2392
- }
2393
- }
2394
- return false
2395
- }
2396
-
2397
- private _invokeAllStoreProcessingQueue() {
2398
- while (this._invokeStoreProcessingQueue()) {
2399
- /* empty */
2400
- }
2401
- }
2402
-
2403
- private _flushStoreProcessingQueue() {
2404
- for (const f of this._storeProcessingQueue) {
2405
- if (f.cbStorePut) f.cbStorePut(new Error('Connection closed'))
2406
- if (f.callback) f.callback(new Error('Connection closed'))
2407
- }
2408
- this._storeProcessingQueue.splice(0)
2409
- }
2410
-
2411
- /**
2412
- * _removeOutgoingAndStoreMessage
2413
- * @param {Number} messageId - messageId to remove message
2414
- * @param {Function} cb - called when the message removed
2415
- * @api private
2416
- */
2417
- private _removeOutgoingAndStoreMessage(
2418
- messageId: number,
2419
- cb: PacketCallback,
2420
- ) {
2421
- delete this.outgoing[messageId]
2422
- this.outgoingStore.del({ messageId }, (err, packet) => {
2423
- cb(err, packet)
2424
- this.messageIdProvider.deallocate(messageId)
2425
- this._invokeStoreProcessingQueue()
2426
- })
2427
- }
2428
- }