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