asyx 0.1.2 → 0.1.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.
@@ -0,0 +1,1145 @@
1
+ /**
2
+ * MqttControlPlaneClient
3
+ *
4
+ * Encapsulates MQTT control-plane connection management, client ID rotation,
5
+ * reconnect logic, and JWT refresh buffering as described in docs/cli-mqtt-refresh_algo.md.
6
+ *
7
+ * This module provides a clean abstraction for CLI MQTT operations, making the
8
+ * logic testable in isolation via dependency injection.
9
+ *
10
+ * @see docs/cli-mqtt-refresh_algo.md
11
+ */
12
+
13
+ import mqtt from 'mqtt';
14
+ import { ulid } from 'ulid';
15
+
16
+ /**
17
+ * @typedef {'soft' | 'hard'} MqttFaultKind
18
+ */
19
+
20
+ /**
21
+ * @typedef {Object} MqttControlPlaneClientOptions
22
+ * @property {string} url - MQTT broker URL (e.g., 'wss://...')
23
+ * @property {string} baseClientId - Base client ID (e.g., 'cli_F285616B53CE')
24
+ * @property {Object} [mqttOptions] - Additional mqtt.js options (cert, key, ca, etc.)
25
+ * @property {(client: any) => void | Promise<void>} [onConnected] - Called after successful connect
26
+ * @property {(reason: string) => void} [onOffline] - Called when connection goes offline
27
+ * @property {(reason: string, err?: unknown) => void} [onFatalError] - Called when we give up due to JWT expiry or unrecoverable error
28
+ * @property {() => Promise<number>} onRefreshLease - Async refresh function. Must publish the refresh request over MQTT and resolve with new exp (ms since epoch). Throw on hard failure.
29
+ * @property {number} [refreshEarlySeconds] - Seconds before exp when we should start refresh (e.g. 0.75 * ttl, default: 675s for 15min TTL)
30
+ * @property {number} [maxReconnectDelayMs] - Max reconnect delay in ms (default 5000)
31
+ * @property {'unique' | 'legacy'} [mode] - Mode: 'unique' (default) or 'legacy'
32
+ * @property {Object} [logger] - Logger for structured logging
33
+ * @property {any} [mqttLib] - Optional mqtt library for dependency injection (defaults to real mqtt)
34
+ * @property {any} [ulidLib] - Optional ulid library for dependency injection (defaults to real ulid)
35
+ */
36
+
37
+ export class MqttControlPlaneClient {
38
+ /**
39
+ * @param {MqttControlPlaneClientOptions} opts
40
+ */
41
+ constructor(opts) {
42
+ this.url = opts.url;
43
+ this.baseClientId = opts.baseClientId;
44
+ this.mqttOptions = opts.mqttOptions ?? {};
45
+ this.onConnected = opts.onConnected;
46
+ this.onOffline = opts.onOffline;
47
+ this.onFatalError = opts.onFatalError;
48
+ this.onRefreshLease = opts.onRefreshLease;
49
+ this.refreshEarlySeconds = opts.refreshEarlySeconds ?? 675; // 0.75 * 900s (15 min TTL)
50
+ this.maxReconnectDelayMs = opts.maxReconnectDelayMs ?? 5000;
51
+ this.mode = opts.mode || (process.env.ASYX_MQTT_CLIENTID_MODE === 'legacy' ? 'legacy' : 'unique');
52
+ this.logger = opts.logger;
53
+
54
+ // Dependency injection: allow tests to inject mock mqtt library
55
+ this.mqtt = opts.mqttLib || mqtt;
56
+
57
+ // Dependency injection: allow tests to inject mock ulid library
58
+ this.ulidLib = opts.ulidLib;
59
+
60
+ // Initialize client ID based on mode
61
+ this.currentClientId = this.makeClientId();
62
+
63
+ // State tracking
64
+ this.client = null;
65
+ this.shuttingDown = false;
66
+ this.mqttOnline = false;
67
+ this.hardErrorCount = 0;
68
+ this.reconnectTimer = null;
69
+ this.connectStartTime = null;
70
+ this.reconnectAttempts = 0; // Track total reconnect attempts
71
+ this.maxReconnectAttempts = parseInt(process.env.ASYX_MQTT_MAX_RECONNECT_ATTEMPTS || '20', 10); // Default 20 attempts (was 100, but too many for policy issues)
72
+
73
+ // Refresh state
74
+ this.refreshTimer = null;
75
+ this.refreshPending = false;
76
+ this.refreshDeadlineMs = null;
77
+ this.currentLeaseId = null; // Current lease ID for correlation with jwt_expired_before_refresh
78
+ this.rearmTimeout = null; // QPA-CLI-08: Timeout for refresh re-arm after reconnect
79
+ this.flushPendingRefreshTimer = null; // Timer for flushing pending refresh after reconnect
80
+
81
+ // Watchdog state
82
+ this.watchdogTimer = null;
83
+ this.WATCHDOG_TIMEOUT_MS = 60000; // 60 seconds
84
+
85
+ // Pending message handler (for Transport interface)
86
+ this._pendingMessageHandler = null;
87
+ }
88
+
89
+ // Public API --------------------------------------------------------------
90
+
91
+ /**
92
+ * Connect to MQTT broker (initial connection).
93
+ * Returns a promise that resolves when connected or rejects on fatal error.
94
+ * @returns {Promise<void>}
95
+ */
96
+ async connect() {
97
+ this.shuttingDown = false;
98
+ return this.connectWithNewClient(/* initial */ true);
99
+ }
100
+
101
+ /**
102
+ * Disconnect and clean up all timers.
103
+ * @param {Object} [opts] - Options
104
+ * @param {boolean} [opts.preserveState] - If true, don't set shuttingDown (for forceReconnect)
105
+ * @returns {Promise<void>}
106
+ */
107
+ async disconnect(opts = {}) {
108
+ if (!opts.preserveState) {
109
+ this.shuttingDown = true;
110
+ }
111
+ this.clearReconnectTimer();
112
+ this.clearRefreshTimer();
113
+ this.clearWatchdog();
114
+ this.clearRearmTimeout(); // QPA-CLI-08: Clear rearm timeout on disconnect
115
+ this.clearFlushPendingRefreshTimer(); // Clear flush pending refresh timer
116
+ if (!opts.preserveState) {
117
+ this.refreshPending = false;
118
+ this.refreshDeadlineMs = null;
119
+ }
120
+ this.mqttOnline = false;
121
+
122
+ if (this.client) {
123
+ const c = this.client;
124
+ this.client = null;
125
+ return new Promise((resolve) => {
126
+ try {
127
+ c.end(true, {}, () => resolve());
128
+ } catch {
129
+ resolve();
130
+ }
131
+ });
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Force a manual reconnect (tear down and reconnect).
137
+ * Used when we need a fresh MQTT session (e.g., after ack timeout).
138
+ * @param {string} reason - Reason for reconnect
139
+ * @returns {Promise<void>}
140
+ */
141
+ async forceReconnect(reason = 'manual') {
142
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
143
+ this.logger?.debug('mqtt.control_plane.manual_reconnect', { reason });
144
+ await this.disconnect({ preserveState: true });
145
+ return this.connect();
146
+ }
147
+
148
+ /**
149
+ * Publish a message.
150
+ * @param {string} topic
151
+ * @param {string | Buffer} payload
152
+ * @param {Object} [opts]
153
+ * @returns {Promise<void>}
154
+ */
155
+ async publish(topic, payload, opts = {}) {
156
+ return new Promise((resolve, reject) => {
157
+ if (!this.client || !this.mqttOnline) {
158
+ return reject(new Error("MQTT offline"));
159
+ }
160
+ this.client.publish(topic, payload, opts, (err) => {
161
+ if (err) reject(err);
162
+ else resolve();
163
+ });
164
+ });
165
+ }
166
+
167
+ /**
168
+ * Subscribe to a topic.
169
+ * @param {string} topic
170
+ * @param {number} qos
171
+ * @returns {Promise<void>}
172
+ */
173
+ async subscribe(topic, qos = 0) {
174
+ return new Promise((resolve, reject) => {
175
+ if (!this.client || !this.mqttOnline) {
176
+ return reject(new Error("MQTT offline"));
177
+ }
178
+ this.client.subscribe(topic, { qos }, (err) => {
179
+ if (err) reject(err);
180
+ else resolve();
181
+ });
182
+ });
183
+ }
184
+
185
+ /**
186
+ * Schedule a JWT refresh based on an expiration timestamp (ms since epoch).
187
+ * @param {number} expMs - Expiration timestamp in milliseconds since epoch
188
+ * @param {string} [leaseId] - Optional lease ID for correlation
189
+ */
190
+ scheduleRefresh(expMs, leaseId = null) {
191
+ this.refreshDeadlineMs = expMs;
192
+ if (leaseId) {
193
+ this.currentLeaseId = leaseId;
194
+ }
195
+ this.clearRefreshTimer();
196
+
197
+ const now = Date.now();
198
+ const triggerAt = expMs - this.refreshEarlySeconds * 1000;
199
+ const delayMs = Math.max(0, triggerAt - now);
200
+
201
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
202
+ this.logger?.debug('mqtt.control_plane.refresh.scheduled', {
203
+ expEpochMs: expMs,
204
+ leaseId: this.currentLeaseId,
205
+ leadMs: this.refreshEarlySeconds * 1000,
206
+ refreshAtEpochMs: triggerAt,
207
+ skewMs: now - expMs,
208
+ delayMs
209
+ });
210
+
211
+ this.refreshTimer = setTimeout(() => {
212
+ this.refreshTimer = null;
213
+ this.logger?.debug('mqtt.control_plane.refresh.timer_fired', {
214
+ expEpochMs: expMs,
215
+ leaseId: this.currentLeaseId,
216
+ now: Date.now()
217
+ });
218
+ void this.refreshLeaseToken("scheduled");
219
+ }, delayMs);
220
+ // Don't keep process alive for refresh timer (can be very long delays)
221
+ // Always use unref() since we manage these timers explicitly
222
+ if (this.refreshTimer) {
223
+ this.refreshTimer.unref();
224
+ }
225
+
226
+ this.logger?.debug('mqtt.control_plane.refresh.timer_created', {
227
+ expEpochMs: expMs,
228
+ leaseId: this.currentLeaseId,
229
+ delayMs,
230
+ timerId: this.refreshTimer ? 'set' : 'null'
231
+ });
232
+ }
233
+
234
+ /**
235
+ * Check if MQTT is online.
236
+ * @returns {boolean}
237
+ */
238
+ isOnline() {
239
+ return this.mqttOnline && this.client !== null;
240
+ }
241
+
242
+ /**
243
+ * Get current client ID.
244
+ * @returns {string}
245
+ */
246
+ getClientId() {
247
+ return this.currentClientId;
248
+ }
249
+
250
+ /**
251
+ * Set message handler (for Transport interface).
252
+ * Converts mqtt.js format (topic, payload, packet) to MqttCore format {topic, payload: Uint8Array}
253
+ * @param {(message: {topic: string, payload: Uint8Array}) => void} handler
254
+ */
255
+ setMessageHandler(handler) {
256
+ // Wrap handler to convert mqtt.js format to MqttCore format
257
+ const wrappedHandler = (topic, payload, packet) => {
258
+ // Convert payload to Uint8Array as expected by MqttCore
259
+ const payloadBytes = payload instanceof Buffer
260
+ ? new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength)
261
+ : payload instanceof Uint8Array
262
+ ? payload
263
+ : typeof payload === 'string'
264
+ ? new TextEncoder().encode(payload)
265
+ : new Uint8Array(Buffer.from(payload));
266
+
267
+ handler({ topic, payload: payloadBytes });
268
+ };
269
+
270
+ this._pendingMessageHandler = wrappedHandler;
271
+ if (this.client && this.mqttOnline) {
272
+ this.client.on('message', wrappedHandler);
273
+ }
274
+ }
275
+
276
+ // Internal helpers --------------------------------------------------------
277
+
278
+ /**
279
+ * Generate client ID based on mode.
280
+ * @returns {string}
281
+ */
282
+ makeClientId() {
283
+ if (this.mode === 'legacy') {
284
+ return this.baseClientId;
285
+ }
286
+
287
+ // Unique mode: baseClientId + ULID
288
+ const ulidValue = this.ulidLib ? this.ulidLib() : ulid();
289
+ return `${this.baseClientId}_${ulidValue}`;
290
+ }
291
+
292
+ /**
293
+ * Connect with a new client (initial or after fault).
294
+ * @param {boolean} initial - true for first connect, false for reconnect
295
+ * @returns {Promise<void>}
296
+ */
297
+ connectWithNewClient(initial = false) {
298
+ if (this.shuttingDown) return Promise.resolve();
299
+
300
+ // Avoid double-connect attempts
301
+ if (this.client) {
302
+ // already connected or connecting
303
+ return Promise.resolve();
304
+ }
305
+
306
+ // Rotate client ID on reconnect (hard faults)
307
+ if (!initial && this.mode === 'unique') {
308
+ this.currentClientId = this.makeClientId();
309
+ } else if (initial) {
310
+ this.currentClientId = this.makeClientId();
311
+ }
312
+
313
+ // Build options: match AwsIotTransport exactly
314
+ // For mqtts:// URLs, protocol must be set in options; mqtt.js doesn't auto-detect it
315
+ const options = {
316
+ clientId: this.currentClientId,
317
+ protocolVersion: 4, // MQTT 3.1.1 (required for AWS IoT)
318
+ clean: true,
319
+ keepalive: this.mqttOptions.keepalive ?? 25,
320
+ reconnectPeriod: 0, // we manage reconnects
321
+ cert: this.mqttOptions.cert,
322
+ key: this.mqttOptions.key,
323
+ ca: this.mqttOptions.ca,
324
+ rejectUnauthorized: true,
325
+ connectTimeout: this.mqttOptions.connectTimeout ?? 8000,
326
+ resubscribe: false,
327
+ // Protocol and port for TLS (mqtts) - required for client certificate authentication
328
+ protocol: this.mqttOptions.protocol || 'mqtts',
329
+ port: this.mqttOptions.port || 443,
330
+ // ALPN for port 443 (AWS IoT)
331
+ ALPNProtocols: this.mqttOptions.ALPNProtocols || ['x-amzn-mqtt-ca'],
332
+ };
333
+
334
+ // Log connection attempt with TLS info (but not the actual cert/key data)
335
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
336
+ this.logger?.debug('mqtt.control_plane.dial', {
337
+ clientId: this.currentClientId,
338
+ mode: this.mode,
339
+ initial,
340
+ hasCert: !!options.cert,
341
+ hasKey: !!options.key,
342
+ hasCa: !!options.ca,
343
+ rejectUnauthorized: options.rejectUnauthorized,
344
+ alpnProtocols: options.ALPNProtocols
345
+ });
346
+
347
+ const client = this.mqtt.connect(this.url, options);
348
+ this.client = client;
349
+ this.mqttOnline = false;
350
+ this.connectStartTime = Date.now();
351
+ this.startWatchdog();
352
+
353
+ return new Promise((resolve, reject) => {
354
+ let resolvedOrRejected = false;
355
+ let hasConnected = false; // Track if connect event has fired
356
+ let lastError = null; // Track last error for better diagnostics
357
+
358
+ const onConnect = async () => {
359
+ hasConnected = true;
360
+ this.clearWatchdog();
361
+ this.mqttOnline = true;
362
+ this.hardErrorCount = 0;
363
+ this.reconnectAttempts = 0; // Reset on successful connect
364
+ this.connectStartTime = null;
365
+
366
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
367
+ this.logger?.debug('mqtt.control_plane.connected', {
368
+ clientId: this.currentClientId
369
+ });
370
+
371
+ // Wire up message handler if set
372
+ if (this._pendingMessageHandler) {
373
+ client.on('message', this._pendingMessageHandler);
374
+ }
375
+
376
+ try {
377
+ if (this.onConnected) {
378
+ await this.onConnected(client);
379
+ }
380
+ } catch (e) {
381
+ this.handleFatal("onConnected_failed", e);
382
+ }
383
+
384
+ if (!resolvedOrRejected && initial) {
385
+ resolvedOrRejected = true;
386
+ resolve();
387
+ }
388
+
389
+ // If we had a pending refresh because we were offline, try now.
390
+ if (this.refreshPending) {
391
+ // Grace period: if we're within 30s of expiry, attempt one refresh before exiting
392
+ const now = Date.now();
393
+ const gracePeriodMs = 30000; // 30 seconds
394
+ const timeUntilExpiry = this.refreshDeadlineMs ? (this.refreshDeadlineMs - now) : Infinity;
395
+
396
+ if (timeUntilExpiry < gracePeriodMs && timeUntilExpiry > 0) {
397
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
398
+ this.logger?.debug('mqtt.control_plane.refresh.grace_period', {
399
+ timeUntilExpiry,
400
+ gracePeriodMs
401
+ });
402
+ }
403
+
404
+ this.clearFlushPendingRefreshTimer();
405
+ this.flushPendingRefreshTimer = setTimeout(() => {
406
+ this.flushPendingRefreshTimer = null;
407
+ void this.refreshLeaseToken("pending_after_reconnect");
408
+ }, 500);
409
+ this.flushPendingRefreshTimer?.unref(); // Don't keep process alive
410
+ }
411
+
412
+ // QPA-CLI-08: Schedule refresh re-arm check after reconnect
413
+ // Use a short delay to avoid racing with existing resend logic
414
+ this.clearRearmTimeout();
415
+ this.logger?.debug('jwt.refresh.rearm.scheduled', {
416
+ delayMs: 1000,
417
+ refreshDeadlineMs: this.refreshDeadlineMs,
418
+ leaseId: this.currentLeaseId,
419
+ refreshPending: this.refreshPending,
420
+ hasRefreshTimer: this.refreshTimer !== null
421
+ });
422
+ this.rearmTimeout = setTimeout(() => {
423
+ this.rearmTimeout = null;
424
+ this.ensureRefreshScheduled();
425
+ }, 1000);
426
+ this.rearmTimeout?.unref(); // Don't keep process alive for this timer
427
+ };
428
+
429
+ const onError = (err) => {
430
+ lastError = err; // Store error for diagnostics
431
+
432
+ // Try to extract more details from the client's internal state
433
+ let socketError = null;
434
+ let streamError = null;
435
+ try {
436
+ // mqtt.js client may have a stream or socket with error info
437
+ if (client.stream) {
438
+ streamError = client.stream._readableState?.error || client.stream._writableState?.error;
439
+ }
440
+ if (client.socket) {
441
+ socketError = client.socket.error || client.socket._socket?.error;
442
+ }
443
+ } catch (e) {
444
+ // Ignore errors accessing internal state
445
+ }
446
+
447
+ const fault = this.classifyMqttFault("error", err, undefined, !hasConnected);
448
+
449
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
450
+ this.logger?.debug('mqtt.control_plane.error', {
451
+ fault,
452
+ error: err?.message || String(err),
453
+ code: err?.code,
454
+ name: err?.name,
455
+ errno: err?.errno,
456
+ syscall: err?.syscall,
457
+ beforeConnect: !hasConnected,
458
+ clientId: this.currentClientId,
459
+ baseClientId: this.baseClientId,
460
+ socketError: socketError ? { message: socketError.message, code: socketError.code } : undefined,
461
+ streamError: streamError ? { message: streamError.message, code: streamError.code } : undefined
462
+ });
463
+
464
+ this.handleFault(fault, err || socketError || streamError);
465
+
466
+ if (!resolvedOrRejected && !initial) {
467
+ resolvedOrRejected = true;
468
+ reject(err);
469
+ }
470
+ };
471
+
472
+ const onOffline = () => {
473
+ // offline event may fire before close, capture any available error info
474
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
475
+ this.logger?.debug('mqtt.control_plane.offline', {
476
+ beforeConnect: !hasConnected,
477
+ clientId: this.currentClientId,
478
+ baseClientId: this.baseClientId,
479
+ lastError: lastError ? {
480
+ code: lastError.code,
481
+ message: lastError.message,
482
+ name: lastError.name
483
+ } : undefined
484
+ });
485
+
486
+ // offline is usually a soft fault, but if it happens before connect, treat as hard
487
+ if (!hasConnected) {
488
+ const fault = this.classifyMqttFault("error", lastError || undefined, undefined, true);
489
+ this.handleFault(fault, lastError || new Error("MQTT went offline before connect"));
490
+ }
491
+ };
492
+
493
+ const onClose = (...args) => {
494
+ // mqtt.js close event may pass: () or (hadError) or (code, reason)
495
+ // Capture all arguments for diagnostics
496
+ const closeCode = args[0] !== undefined && typeof args[0] === 'number' ? args[0] : undefined;
497
+ const closeReason = args[1] !== undefined ? String(args[1]) : undefined;
498
+ const hadError = args[0] === true || (closeCode === undefined && args[0] === true);
499
+
500
+ // If close fires before connect, it's likely a hard fault (auth/policy issue)
501
+ const isBeforeConnect = !hasConnected;
502
+
503
+ // Try to extract more diagnostic info from client state
504
+ let clientState = {};
505
+ try {
506
+ if (client) {
507
+ clientState = {
508
+ connected: client.connected,
509
+ disconnecting: client.disconnecting,
510
+ reconnecting: client.reconnecting,
511
+ options: {
512
+ clientId: client.options?.clientId,
513
+ protocol: client.options?.protocol,
514
+ protocolVersion: client.options?.protocolVersion
515
+ }
516
+ };
517
+ // Try to get socket state if available
518
+ if (client.stream) {
519
+ clientState.streamState = {
520
+ readable: client.stream.readable,
521
+ writable: client.stream.writable,
522
+ destroyed: client.stream.destroyed
523
+ };
524
+ }
525
+ }
526
+ } catch (e) {
527
+ // Ignore errors accessing internal state
528
+ }
529
+
530
+ const fault = this.classifyMqttFault("close", lastError || undefined, closeCode, isBeforeConnect);
531
+
532
+ // Log close code/reason more accurately
533
+ const codeStr = closeCode !== undefined && closeCode !== null
534
+ ? String(closeCode)
535
+ : (lastError?.code ? String(lastError.code) : (hadError ? 'error' : 'unknown'));
536
+
537
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
538
+ this.logger?.debug('mqtt.control_plane.close', {
539
+ fault,
540
+ closeCode: codeStr,
541
+ closeReason: closeReason || undefined,
542
+ hadError: hadError || undefined,
543
+ beforeConnect: isBeforeConnect,
544
+ lastError: lastError ? {
545
+ code: lastError.code,
546
+ message: lastError.message,
547
+ name: lastError.name,
548
+ stack: lastError.stack
549
+ } : undefined,
550
+ clientId: this.currentClientId,
551
+ baseClientId: this.baseClientId,
552
+ clientState: Object.keys(clientState).length > 0 ? clientState : undefined,
553
+ // Diagnostic: if this keeps happening, it's likely a policy/auth issue
554
+ diagnostic: isBeforeConnect && !lastError ?
555
+ 'Connection closed before MQTT handshake. Likely causes: AWS IoT policy mismatch, certificate auth failure, or TLS handshake rejection. Check AWS IoT policy allows clientId pattern: ' + this.baseClientId + '*' : undefined
556
+ });
557
+
558
+ // Don't reject immediately - let reconnect loop handle retries
559
+ // The reconnect loop will retry with backoff, and only call handleFatal after max attempts
560
+ this.handleFault(fault, lastError || (hadError ? new Error('MQTT connection had error') : undefined));
561
+
562
+ // Don't reject the promise here - let the reconnect loop handle it
563
+ // If we've exhausted retries, handleFault will eventually call handleFatal
564
+ };
565
+
566
+ const onEnd = () => {
567
+ // If end fires before connect, it's likely a hard fault
568
+ const isBeforeConnect = !hasConnected;
569
+ const fault = this.classifyMqttFault("close", lastError || undefined, undefined, isBeforeConnect);
570
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
571
+ this.logger?.debug('mqtt.control_plane.end', {
572
+ fault,
573
+ beforeConnect: isBeforeConnect,
574
+ lastError: lastError ? {
575
+ code: lastError.code,
576
+ message: lastError.message,
577
+ name: lastError.name
578
+ } : undefined,
579
+ clientId: this.currentClientId,
580
+ baseClientId: this.baseClientId
581
+ });
582
+ // Don't reject immediately - let reconnect loop handle it
583
+ this.handleFault(fault, lastError);
584
+ };
585
+
586
+ client.on("connect", onConnect);
587
+ client.on("error", onError);
588
+ client.on("offline", onOffline);
589
+ client.on("close", onClose);
590
+ client.on("end", onEnd);
591
+
592
+ // Also try to capture errors from the underlying socket/stream if available
593
+ try {
594
+ if (client.stream) {
595
+ client.stream.on('error', (streamErr) => {
596
+ if (!lastError) {
597
+ lastError = streamErr;
598
+ }
599
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
600
+ this.logger?.debug('mqtt.control_plane.stream.error', {
601
+ error: streamErr?.message || String(streamErr),
602
+ code: streamErr?.code,
603
+ errno: streamErr?.errno,
604
+ syscall: streamErr?.syscall,
605
+ beforeConnect: !hasConnected,
606
+ clientId: this.currentClientId
607
+ });
608
+ });
609
+
610
+ // Also listen for secureConnect event to see if TLS handshake succeeds
611
+ if (client.stream.once) {
612
+ client.stream.once('secureConnect', () => {
613
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
614
+ this.logger?.debug('mqtt.control_plane.tls.secure_connect', {
615
+ clientId: this.currentClientId,
616
+ authorized: client.stream?.authorized,
617
+ authorizationError: client.stream?.authorizationError?.message
618
+ });
619
+ });
620
+ }
621
+ }
622
+ if (client.socket) {
623
+ client.socket.on('error', (socketErr) => {
624
+ if (!lastError) {
625
+ lastError = socketErr;
626
+ }
627
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
628
+ this.logger?.debug('mqtt.control_plane.socket.error', {
629
+ error: socketErr?.message || String(socketErr),
630
+ code: socketErr?.code,
631
+ errno: socketErr?.errno,
632
+ syscall: socketErr?.syscall,
633
+ beforeConnect: !hasConnected,
634
+ clientId: this.currentClientId
635
+ });
636
+ });
637
+
638
+ // For TLS sockets, check authorization
639
+ if (client.socket.authorized !== undefined) {
640
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
641
+ this.logger?.debug('mqtt.control_plane.tls.authorization', {
642
+ clientId: this.currentClientId,
643
+ authorized: client.socket.authorized,
644
+ authorizationError: client.socket.authorizationError?.message
645
+ });
646
+ }
647
+ }
648
+ } catch (e) {
649
+ // Ignore errors accessing internal state
650
+ this.logger?.debug('mqtt.control_plane.internal_state_access_error', {
651
+ error: e?.message,
652
+ clientId: this.currentClientId
653
+ });
654
+ }
655
+ });
656
+ }
657
+
658
+ /**
659
+ * Classify MQTT fault as hard or soft.
660
+ * @param {string} event - Event type: 'error', 'close', 'end'
661
+ * @param {any} [err] - Error object
662
+ * @param {number} [closeCode] - MQTT close code
663
+ * @param {boolean} [beforeConnect] - true if fault occurred before connect event
664
+ * @returns {MqttFaultKind}
665
+ */
666
+ classifyMqttFault(event, err, closeCode, beforeConnect = false) {
667
+ // Fix code_NaN: log real codes, fall back to 'unknown'
668
+ const code = (err && (err.code)) || undefined;
669
+ const name = (err && (err.name)) || "";
670
+ const msg = (err && (err.message)) || "";
671
+
672
+ // If close/end fires before connect, it's likely a hard fault (auth/policy issue)
673
+ if (beforeConnect) {
674
+ return "hard";
675
+ }
676
+
677
+ // Clean shutdown (soft)
678
+ if (event === "close" && closeCode === 1000) {
679
+ return "soft";
680
+ }
681
+
682
+ // Hard network / broker faults
683
+ if (
684
+ code === "ECONNRESET" ||
685
+ code === "ETIMEDOUT" ||
686
+ code === "EPIPE"
687
+ ) {
688
+ return "hard";
689
+ }
690
+
691
+ // TLS / auth / protocol problems are also hard
692
+ if (
693
+ name.includes("TLS") ||
694
+ msg.includes("certificate") ||
695
+ msg.includes("TLS") ||
696
+ String(code || "").includes("CERT") ||
697
+ msg.includes("authentication") ||
698
+ msg.includes("authorization") ||
699
+ msg.includes("policy")
700
+ ) {
701
+ return "hard";
702
+ }
703
+
704
+ // MQTT protocol errors (close codes 1-5) are hard faults
705
+ if (event === "close" && closeCode !== undefined && closeCode !== null) {
706
+ // MQTT 3.1.1 close codes: 1-5 are protocol errors (hard)
707
+ if (closeCode >= 1 && closeCode <= 5) {
708
+ return "hard";
709
+ }
710
+ // Close code 0 or undefined might be network-level (could be hard or soft)
711
+ // But if we have an error, prefer that classification
712
+ }
713
+
714
+ // Everything else: treat as soft by default
715
+ return "soft";
716
+ }
717
+
718
+ /**
719
+ * Handle a fault (soft or hard).
720
+ * Hard faults trigger clientId rotation and immediate reconnect.
721
+ * @param {MqttFaultKind} kind
722
+ * @param {any} [err]
723
+ */
724
+ handleFault(kind, err) {
725
+ if (this.shuttingDown) return;
726
+
727
+ this.mqttOnline = false;
728
+ this.clearWatchdog();
729
+
730
+ const reason = err?.message || err?.code || kind;
731
+ this.onOffline?.(reason);
732
+
733
+ if (kind === "hard") {
734
+ this.hardErrorCount++;
735
+ this.reconnectAttempts++;
736
+
737
+ // Check if we've exhausted retries
738
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
739
+ const errorDetails = {
740
+ reason: 'max_reconnect_attempts_exceeded',
741
+ attempts: this.reconnectAttempts,
742
+ hardErrorCount: this.hardErrorCount,
743
+ lastError: err ? {
744
+ code: err.code,
745
+ message: err.message,
746
+ name: err.name
747
+ } : undefined,
748
+ clientId: this.currentClientId,
749
+ baseClientId: this.baseClientId,
750
+ policyInfo: `Check AWS IoT policy for clientId pattern: ${this.baseClientId}*`
751
+ };
752
+
753
+ this.logger?.error('mqtt.control_plane.fatal', errorDetails);
754
+ this.handleFatal('max_reconnect_attempts', new Error(
755
+ `MQTT connection failed after ${this.reconnectAttempts} attempts. ` +
756
+ `Last error: ${err?.message || err?.code || 'unknown'}. ` +
757
+ `Check AWS IoT policy for clientId pattern: ${this.baseClientId}*`
758
+ ));
759
+ return;
760
+ }
761
+
762
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
763
+ this.logger?.debug('mqtt.control_plane.fault.hard', {
764
+ hardErrorCount: this.hardErrorCount,
765
+ reconnectAttempts: this.reconnectAttempts,
766
+ maxAttempts: this.maxReconnectAttempts,
767
+ reason,
768
+ clientId: this.currentClientId,
769
+ baseClientId: this.baseClientId
770
+ });
771
+ this.forceCloseClient();
772
+ this.scheduleReconnect(/* immediate */ true);
773
+ } else {
774
+ this.reconnectAttempts++;
775
+
776
+ // Check if we've exhausted retries
777
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
778
+ const errorDetails = {
779
+ reason: 'max_reconnect_attempts_exceeded',
780
+ attempts: this.reconnectAttempts,
781
+ lastError: err ? {
782
+ code: err.code,
783
+ message: err.message,
784
+ name: err.name
785
+ } : undefined,
786
+ clientId: this.currentClientId,
787
+ baseClientId: this.baseClientId
788
+ };
789
+
790
+ this.logger?.error('mqtt.control_plane.fatal', errorDetails);
791
+ this.handleFatal('max_reconnect_attempts', new Error(
792
+ `MQTT connection failed after ${this.reconnectAttempts} attempts. ` +
793
+ `Last error: ${err?.message || err?.code || 'unknown'}`
794
+ ));
795
+ return;
796
+ }
797
+
798
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
799
+ this.logger?.debug('mqtt.control_plane.fault.soft', {
800
+ reconnectAttempts: this.reconnectAttempts,
801
+ maxAttempts: this.maxReconnectAttempts,
802
+ reason,
803
+ clientId: this.currentClientId
804
+ });
805
+ this.forceCloseClient();
806
+ this.scheduleReconnect(/* immediate */ false);
807
+ }
808
+ }
809
+
810
+ /**
811
+ * Force close the current client.
812
+ */
813
+ forceCloseClient() {
814
+ if (!this.client) return;
815
+ try {
816
+ this.client.end(true);
817
+ } catch {
818
+ // ignore
819
+ }
820
+ this.client.removeAllListeners();
821
+ this.client = null;
822
+ }
823
+
824
+ /**
825
+ * Schedule reconnect with jittered backoff.
826
+ * @param {boolean} immediate - true for hard faults (ECONNRESET, etc.), false for soft
827
+ */
828
+ scheduleReconnect(immediate) {
829
+ if (this.shuttingDown) return;
830
+ if (this.reconnectTimer) return; // already scheduled
831
+
832
+ const base = immediate ? 0 : 200;
833
+ const expFactor = Math.min(this.hardErrorCount, 5);
834
+ const delayNoJitter =
835
+ this.hardErrorCount === 0 ? base : base * Math.pow(2, expFactor);
836
+ const jitter = Math.random() * 200; // 0-200ms jitter
837
+ const delay =
838
+ this.hardErrorCount === 0
839
+ ? base
840
+ : Math.min(this.maxReconnectDelayMs, delayNoJitter + jitter);
841
+
842
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
843
+ this.logger?.debug('mqtt.control_plane.reconnect.scheduled', {
844
+ immediate,
845
+ delay,
846
+ hardErrorCount: this.hardErrorCount,
847
+ attempt: this.hardErrorCount + 1
848
+ });
849
+
850
+ this.reconnectTimer = setTimeout(() => {
851
+ this.reconnectTimer = null;
852
+ void this.connectWithNewClient();
853
+ }, delay);
854
+ // Don't keep process alive for reconnect timer
855
+ if (this.reconnectTimer) {
856
+ this.reconnectTimer.unref();
857
+ }
858
+ }
859
+
860
+ /**
861
+ * Start watchdog timer to detect stuck connections.
862
+ */
863
+ startWatchdog() {
864
+ this.clearWatchdog();
865
+ this.watchdogTimer = setTimeout(() => {
866
+ if (this.connectStartTime && Date.now() - this.connectStartTime > this.WATCHDOG_TIMEOUT_MS) {
867
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
868
+ this.logger?.debug('mqtt.control_plane.watchdog', {
869
+ elapsed: Date.now() - this.connectStartTime,
870
+ clientId: this.currentClientId
871
+ });
872
+ this.handleFault("hard", new Error("Watchdog timeout: connection stuck in CONNECTING"));
873
+ }
874
+ }, this.WATCHDOG_TIMEOUT_MS);
875
+ // Don't keep process alive for watchdog timer (long timeout)
876
+ if (this.watchdogTimer) {
877
+ this.watchdogTimer.unref();
878
+ }
879
+ }
880
+
881
+ /**
882
+ * Clear watchdog timer.
883
+ */
884
+ clearWatchdog() {
885
+ if (this.watchdogTimer) {
886
+ clearTimeout(this.watchdogTimer);
887
+ this.watchdogTimer = null;
888
+ }
889
+ }
890
+
891
+ /**
892
+ * Clear reconnect timer.
893
+ */
894
+ clearReconnectTimer() {
895
+ if (this.reconnectTimer) {
896
+ clearTimeout(this.reconnectTimer);
897
+ this.reconnectTimer = null;
898
+ }
899
+ }
900
+
901
+ /**
902
+ * Clear refresh timer.
903
+ */
904
+ clearRefreshTimer() {
905
+ if (this.refreshTimer) {
906
+ this.logger?.debug('mqtt.control_plane.refresh.timer_cleared', {
907
+ refreshDeadlineMs: this.refreshDeadlineMs,
908
+ leaseId: this.currentLeaseId
909
+ });
910
+ clearTimeout(this.refreshTimer);
911
+ this.refreshTimer = null;
912
+ }
913
+ }
914
+
915
+ /**
916
+ * Clear rearm timeout (QPA-CLI-08).
917
+ */
918
+ clearRearmTimeout() {
919
+ if (this.rearmTimeout) {
920
+ clearTimeout(this.rearmTimeout);
921
+ this.rearmTimeout = null;
922
+ }
923
+ }
924
+
925
+ /**
926
+ * Clear flush pending refresh timer.
927
+ */
928
+ clearFlushPendingRefreshTimer() {
929
+ if (this.flushPendingRefreshTimer) {
930
+ clearTimeout(this.flushPendingRefreshTimer);
931
+ this.flushPendingRefreshTimer = null;
932
+ }
933
+ }
934
+
935
+ /**
936
+ * Attempt to refresh the lease token.
937
+ * @param {string} reason - Reason for refresh (e.g., 'scheduled', 'pending_after_reconnect')
938
+ */
939
+ async refreshLeaseToken(reason) {
940
+ if (this.shuttingDown) return;
941
+
942
+ // If we already missed the deadline, exit.
943
+ if (this.refreshDeadlineMs && Date.now() > this.refreshDeadlineMs) {
944
+ this.handleFatal("jwt_expired_before_refresh");
945
+ return;
946
+ }
947
+
948
+ if (!this.client || !this.mqttOnline) {
949
+ // offline, mark pending
950
+ this.refreshPending = true;
951
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
952
+ this.logger?.debug('mqtt.control_plane.refresh.pending', {
953
+ reason,
954
+ pending: true,
955
+ refreshDeadlineMs: this.refreshDeadlineMs,
956
+ leaseId: this.currentLeaseId
957
+ });
958
+ return;
959
+ }
960
+
961
+ try {
962
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
963
+ this.logger?.debug('mqtt.control_plane.refresh.attempting', {
964
+ reason,
965
+ refreshDeadlineMs: this.refreshDeadlineMs,
966
+ leaseId: this.currentLeaseId
967
+ });
968
+ const newExp = await this.onRefreshLease();
969
+ this.refreshPending = false;
970
+ if (newExp) {
971
+ this.scheduleRefresh(newExp);
972
+ }
973
+ } catch (err) {
974
+ // If it's an offline-ish error, buffer and try after reconnect
975
+ if (this.isOfflineError(err)) {
976
+ this.refreshPending = true;
977
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
978
+ this.logger?.debug('mqtt.control_plane.refresh.buffered', {
979
+ reason: 'connection_closed_during_refresh',
980
+ error: err?.message || String(err),
981
+ code: err?.code,
982
+ refreshDeadlineMs: this.refreshDeadlineMs,
983
+ leaseId: this.currentLeaseId
984
+ });
985
+ return;
986
+ }
987
+
988
+ // Check if deadline exceeded before treating as fatal
989
+ if (this.refreshDeadlineMs && Date.now() > this.refreshDeadlineMs) {
990
+ this.handleFatal("jwt_expired_before_refresh", err);
991
+ return;
992
+ }
993
+
994
+ // Real failure (non-recoverable, non-offline error)
995
+ this.handleFatal("jwt_refresh_failed", err);
996
+ }
997
+ }
998
+
999
+ /**
1000
+ * Check if error is an offline/connection error (should buffer refresh).
1001
+ * @param {any} err
1002
+ * @returns {boolean}
1003
+ */
1004
+ isOfflineError(err) {
1005
+ const msg = (err && err.message) || "";
1006
+ const code = (err && err.code) || "";
1007
+ return (
1008
+ msg.includes("offline") ||
1009
+ msg.includes("not connected") ||
1010
+ msg.includes("Connection closed") ||
1011
+ code === "ECONNRESET" ||
1012
+ code === "ETIMEDOUT"
1013
+ );
1014
+ }
1015
+
1016
+ /**
1017
+ * QPA-CLI-08: Ensure a refresh is scheduled after reconnect.
1018
+ * Checks if refresh is pending or if we need to re-arm a refresh.
1019
+ */
1020
+ ensureRefreshScheduled() {
1021
+ // Safety buffer: 5 minutes before lease expiry
1022
+ const SAFETY_BUFFER_MS = 5 * 60 * 1000;
1023
+
1024
+ this.logger?.debug('jwt.refresh.rearm.checking', {
1025
+ refreshDeadlineMs: this.refreshDeadlineMs,
1026
+ leaseId: this.currentLeaseId,
1027
+ refreshPending: this.refreshPending,
1028
+ hasRefreshTimer: this.refreshTimer !== null,
1029
+ mqttOnline: this.mqttOnline
1030
+ });
1031
+
1032
+ // If no lease expiration tracked, nothing to do (still waiting for lease)
1033
+ if (!this.refreshDeadlineMs) {
1034
+ this.logger?.debug('jwt.refresh.rearm.skip', {
1035
+ reason: 'no_lease',
1036
+ refreshDeadlineMs: null,
1037
+ leaseId: this.currentLeaseId
1038
+ });
1039
+ return;
1040
+ }
1041
+
1042
+ const now = Date.now();
1043
+ const expEpochMs = this.refreshDeadlineMs;
1044
+ const timeUntilExpiry = expEpochMs - now;
1045
+
1046
+ // If lease already expired, let existing fatal path handle it
1047
+ if (timeUntilExpiry <= 0) {
1048
+ this.logger?.debug('jwt.refresh.rearm.skip', {
1049
+ reason: 'lease_expired',
1050
+ expEpochMs,
1051
+ leaseId: this.currentLeaseId,
1052
+ timeUntilExpiry
1053
+ });
1054
+ return;
1055
+ }
1056
+
1057
+ // If refresh is already pending, existing retry/resend logic will handle it
1058
+ if (this.refreshPending) {
1059
+ this.logger?.debug('jwt.refresh.rearm.skip', {
1060
+ reason: 'pending',
1061
+ refreshPending: true,
1062
+ expEpochMs,
1063
+ leaseId: this.currentLeaseId
1064
+ });
1065
+ return;
1066
+ }
1067
+
1068
+ // Calculate when the next refresh would be scheduled (based on refreshEarlySeconds)
1069
+ // This is when the refresh timer would fire if it exists
1070
+ const nextRefreshMs = expEpochMs - (this.refreshEarlySeconds * 1000);
1071
+ const timeUntilNextRefresh = nextRefreshMs - now;
1072
+ const safetyBufferPointMs = expEpochMs - SAFETY_BUFFER_MS;
1073
+
1074
+ // Check if refresh timer is missing or if next refresh is too close to expiry
1075
+ // If nextRefreshMs > safetyBufferPointMs, the refresh is scheduled too late
1076
+ const hasRefreshTimer = this.refreshTimer !== null;
1077
+ const needsRearm = !hasRefreshTimer || nextRefreshMs > safetyBufferPointMs;
1078
+
1079
+ this.logger?.debug('jwt.refresh.rearm.calculated', {
1080
+ expEpochMs,
1081
+ leaseId: this.currentLeaseId,
1082
+ nextRefreshMs,
1083
+ timeUntilNextRefresh,
1084
+ safetyBufferPointMs,
1085
+ hasRefreshTimer,
1086
+ needsRearm,
1087
+ now
1088
+ });
1089
+
1090
+ if (needsRearm) {
1091
+ // Determine reason for rearm
1092
+ const reason = !hasRefreshTimer ? 'no_timer' : 'approaching_expiration';
1093
+
1094
+ // QPA-CLI-10: Telemetry logs default to debug for quiet mode
1095
+ this.logger?.debug('jwt.refresh.rearm', {
1096
+ reason,
1097
+ expEpochMs,
1098
+ leaseId: this.currentLeaseId,
1099
+ nextRefreshMs: hasRefreshTimer ? nextRefreshMs : null,
1100
+ timeUntilExpiry,
1101
+ safetyBufferMs: SAFETY_BUFFER_MS,
1102
+ hasRefreshTimer
1103
+ });
1104
+
1105
+ // Trigger a new refresh publish immediately
1106
+ // This will set refreshPending = true and update refreshDeadlineMs via scheduleRefresh
1107
+ void this.refreshLeaseToken('rearm');
1108
+ } else {
1109
+ // Safe deadline exists, skip rearm
1110
+ this.logger?.debug('jwt.refresh.rearm.skip', {
1111
+ reason: 'safe_deadline',
1112
+ nextRefreshMs,
1113
+ expEpochMs,
1114
+ leaseId: this.currentLeaseId,
1115
+ timeUntilNextRefresh,
1116
+ timeUntilExpiry,
1117
+ safetyBufferPointMs
1118
+ });
1119
+ }
1120
+ }
1121
+
1122
+ /**
1123
+ * Handle fatal error (JWT expired, max retries, etc.).
1124
+ * @param {string} reason
1125
+ * @param {any} [err]
1126
+ */
1127
+ handleFatal(reason, err) {
1128
+ const errorDetails = {
1129
+ reason,
1130
+ error: err?.message || String(err),
1131
+ errorCode: err?.code,
1132
+ errorName: err?.name,
1133
+ clientId: this.currentClientId,
1134
+ baseClientId: this.baseClientId,
1135
+ reconnectAttempts: this.reconnectAttempts,
1136
+ hardErrorCount: this.hardErrorCount,
1137
+ policyInfo: `Check AWS IoT policy for clientId pattern: ${this.baseClientId}*`
1138
+ };
1139
+
1140
+ this.logger?.error('mqtt.control_plane.fatal', errorDetails);
1141
+ this.onFatalError?.(reason, err);
1142
+ void this.disconnect();
1143
+ }
1144
+ }
1145
+