asyx 0.1.2 → 0.2.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/README.md +150 -8
- package/package.json +10 -2
- package/src/commands/tunnel.js +1160 -91
- package/src/control-plane/MqttControlPlaneClient.js +1150 -0
- package/src/control-plane/MqttControlPlaneTransport.js +150 -0
- package/src/lib/logger.js +8 -4
- package/src/mqtt/awaiter-map.js +92 -2
- package/src/mqtt/events/handlers.js +120 -11
- package/src/mqtt/ingress.js +11 -1
- package/src/state/assignment.js +9 -0
- package/src/tcp-v1/framing.js +203 -0
- package/src/tunnel/http-tunnel.js +246 -28
- package/src/tunnel/tcp-tunnel.js +896 -0
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TCP-v1 Framing Protocol
|
|
3
|
+
*
|
|
4
|
+
* Binary frame format:
|
|
5
|
+
* [frameType:1 byte][streamId:4 bytes (big-endian)][length:4 bytes (big-endian)][payload:length bytes]
|
|
6
|
+
*
|
|
7
|
+
* Frame types:
|
|
8
|
+
* - 0x01: STREAM_OPEN
|
|
9
|
+
* - 0x02: STREAM_DATA
|
|
10
|
+
* - 0x03: STREAM_CLOSE
|
|
11
|
+
* - 0x04: STREAM_ERROR
|
|
12
|
+
* - 0x05: PING
|
|
13
|
+
* - 0x06: PONG
|
|
14
|
+
*
|
|
15
|
+
* Max payload size: 64 KiB (65535 bytes)
|
|
16
|
+
* StreamId: 24-bit value (stored as 32-bit, but only lower 24 bits used)
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export const FrameType = {
|
|
20
|
+
STREAM_OPEN: 0x01,
|
|
21
|
+
STREAM_DATA: 0x02,
|
|
22
|
+
STREAM_CLOSE: 0x03,
|
|
23
|
+
STREAM_ERROR: 0x04,
|
|
24
|
+
PING: 0x05,
|
|
25
|
+
PONG: 0x06,
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const MAX_FRAME_PAYLOAD = 64 * 1024; // 64 KiB
|
|
29
|
+
export const FRAME_HEADER_SIZE = 9; // 1 byte type + 4 bytes streamId + 4 bytes length
|
|
30
|
+
|
|
31
|
+
export class TcpV1FramingError extends Error {
|
|
32
|
+
constructor(message, code) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.name = 'TcpV1FramingError';
|
|
35
|
+
this.code = code;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Encode a frame to binary format
|
|
41
|
+
* @param {Object} frame - Frame object with type, streamId, and payload
|
|
42
|
+
* @param {number} frame.type - Frame type (FrameType constant)
|
|
43
|
+
* @param {number} frame.streamId - Stream ID (24-bit, 0 for PING/PONG)
|
|
44
|
+
* @param {Buffer|Uint8Array} frame.payload - Frame payload (max 64 KiB)
|
|
45
|
+
* @returns {Buffer} Encoded frame
|
|
46
|
+
* @throws {TcpV1FramingError} If frame is invalid
|
|
47
|
+
*/
|
|
48
|
+
export function encodeFrame(frame) {
|
|
49
|
+
const { type, streamId = 0, payload = Buffer.alloc(0) } = frame;
|
|
50
|
+
|
|
51
|
+
// Validate frame type
|
|
52
|
+
if (type < FrameType.STREAM_OPEN || type > FrameType.PONG) {
|
|
53
|
+
throw new TcpV1FramingError(`Invalid frame type: ${type}`, 'INVALID_FRAME_TYPE');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Convert payload to Buffer if needed
|
|
57
|
+
const payloadBuf = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);
|
|
58
|
+
|
|
59
|
+
// Validate payload size
|
|
60
|
+
if (payloadBuf.length > MAX_FRAME_PAYLOAD) {
|
|
61
|
+
throw new TcpV1FramingError(
|
|
62
|
+
`Payload size ${payloadBuf.length} exceeds max ${MAX_FRAME_PAYLOAD}`,
|
|
63
|
+
'PAYLOAD_TOO_LARGE'
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// StreamID validation (PING/PONG can have 0)
|
|
68
|
+
if (type !== FrameType.PING && type !== FrameType.PONG) {
|
|
69
|
+
if (streamId === 0) {
|
|
70
|
+
throw new TcpV1FramingError('StreamID required for non-PING/PONG frames', 'MISSING_STREAM_ID');
|
|
71
|
+
}
|
|
72
|
+
// Ensure streamId fits in 24 bits
|
|
73
|
+
if (streamId > 0x00FFFFFF) {
|
|
74
|
+
throw new TcpV1FramingError(`StreamID ${streamId} exceeds 24-bit limit`, 'INVALID_STREAM_ID');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Create frame buffer
|
|
79
|
+
const frameBuf = Buffer.allocUnsafe(FRAME_HEADER_SIZE + payloadBuf.length);
|
|
80
|
+
|
|
81
|
+
// Write frame type (1 byte)
|
|
82
|
+
frameBuf[0] = type;
|
|
83
|
+
|
|
84
|
+
// Write streamId (4 bytes, big-endian, only lower 24 bits used)
|
|
85
|
+
frameBuf.writeUInt32BE(streamId & 0x00FFFFFF, 1);
|
|
86
|
+
|
|
87
|
+
// Write payload length (4 bytes, big-endian)
|
|
88
|
+
frameBuf.writeUInt32BE(payloadBuf.length, 5);
|
|
89
|
+
|
|
90
|
+
// Write payload
|
|
91
|
+
if (payloadBuf.length > 0) {
|
|
92
|
+
payloadBuf.copy(frameBuf, FRAME_HEADER_SIZE);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return frameBuf;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Decode a frame from binary format
|
|
100
|
+
* @param {Buffer|Uint8Array} data - Binary frame data
|
|
101
|
+
* @param {number} [offset=0] - Offset to start reading from
|
|
102
|
+
* @returns {Object} Decoded frame object with type, streamId, payload, and consumed bytes
|
|
103
|
+
* @throws {TcpV1FramingError} If frame is invalid
|
|
104
|
+
*/
|
|
105
|
+
export function decodeFrame(data, offset = 0) {
|
|
106
|
+
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
|
|
107
|
+
|
|
108
|
+
// Check if we have enough data for header
|
|
109
|
+
if (buf.length - offset < FRAME_HEADER_SIZE) {
|
|
110
|
+
throw new TcpV1FramingError(
|
|
111
|
+
`Insufficient data for frame header: need ${FRAME_HEADER_SIZE} bytes, got ${buf.length - offset}`,
|
|
112
|
+
'INCOMPLETE_FRAME'
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// If offset is provided, create a subarray view
|
|
117
|
+
const view = offset > 0 ? buf.subarray(offset) : buf;
|
|
118
|
+
|
|
119
|
+
// Read frame type (1 byte)
|
|
120
|
+
const type = view[0];
|
|
121
|
+
|
|
122
|
+
// Validate frame type
|
|
123
|
+
if (type < FrameType.STREAM_OPEN || type > FrameType.PONG) {
|
|
124
|
+
throw new TcpV1FramingError(`Invalid frame type: ${type}`, 'INVALID_FRAME_TYPE');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Read streamId (4 bytes, big-endian, only lower 24 bits used)
|
|
128
|
+
const streamId = view.readUInt32BE(1) & 0x00FFFFFF;
|
|
129
|
+
|
|
130
|
+
// Read payload length (4 bytes, big-endian)
|
|
131
|
+
const payloadLength = view.readUInt32BE(5);
|
|
132
|
+
|
|
133
|
+
// Validate payload length
|
|
134
|
+
if (payloadLength > MAX_FRAME_PAYLOAD) {
|
|
135
|
+
throw new TcpV1FramingError(
|
|
136
|
+
`Payload length ${payloadLength} exceeds max ${MAX_FRAME_PAYLOAD}`,
|
|
137
|
+
'PAYLOAD_TOO_LARGE'
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Check if we have enough data for payload
|
|
142
|
+
const totalFrameSize = FRAME_HEADER_SIZE + payloadLength;
|
|
143
|
+
if (view.length < totalFrameSize) {
|
|
144
|
+
throw new TcpV1FramingError(
|
|
145
|
+
`Insufficient data for frame payload: need ${totalFrameSize} bytes, got ${view.length}`,
|
|
146
|
+
'INCOMPLETE_FRAME'
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// StreamID validation (PING/PONG can have 0)
|
|
151
|
+
if (type !== FrameType.PING && type !== FrameType.PONG) {
|
|
152
|
+
if (streamId === 0) {
|
|
153
|
+
throw new TcpV1FramingError('StreamID required for non-PING/PONG frames', 'MISSING_STREAM_ID');
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Read payload
|
|
158
|
+
const payload = payloadLength > 0
|
|
159
|
+
? view.subarray(FRAME_HEADER_SIZE, FRAME_HEADER_SIZE + payloadLength)
|
|
160
|
+
: Buffer.alloc(0);
|
|
161
|
+
|
|
162
|
+
return {
|
|
163
|
+
type,
|
|
164
|
+
streamId,
|
|
165
|
+
payload,
|
|
166
|
+
consumed: totalFrameSize,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Validate a frame for protocol violations
|
|
172
|
+
* @param {Object} frame - Frame object to validate
|
|
173
|
+
* @returns {void}
|
|
174
|
+
* @throws {TcpV1FramingError} If frame is invalid
|
|
175
|
+
*/
|
|
176
|
+
export function validateFrame(frame) {
|
|
177
|
+
const { type, streamId = 0, payload = Buffer.alloc(0) } = frame;
|
|
178
|
+
|
|
179
|
+
// Validate frame type
|
|
180
|
+
if (type < FrameType.STREAM_OPEN || type > FrameType.PONG) {
|
|
181
|
+
throw new TcpV1FramingError(`Invalid frame type: ${type}`, 'INVALID_FRAME_TYPE');
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Validate payload size
|
|
185
|
+
const payloadBuf = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);
|
|
186
|
+
if (payloadBuf.length > MAX_FRAME_PAYLOAD) {
|
|
187
|
+
throw new TcpV1FramingError(
|
|
188
|
+
`Payload size ${payloadBuf.length} exceeds max ${MAX_FRAME_PAYLOAD}`,
|
|
189
|
+
'PAYLOAD_TOO_LARGE'
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// StreamID validation (PING/PONG can have 0)
|
|
194
|
+
if (type !== FrameType.PING && type !== FrameType.PONG) {
|
|
195
|
+
if (streamId === 0) {
|
|
196
|
+
throw new TcpV1FramingError('StreamID required for non-PING/PONG frames', 'MISSING_STREAM_ID');
|
|
197
|
+
}
|
|
198
|
+
if (streamId > 0x00FFFFFF) {
|
|
199
|
+
throw new TcpV1FramingError(`StreamID ${streamId} exceeds 24-bit limit`, 'INVALID_STREAM_ID');
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
@@ -19,7 +19,11 @@ export class HttpTunnel {
|
|
|
19
19
|
// CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
|
|
20
20
|
isControlPlaneConnected = () => true,
|
|
21
21
|
waitForControlPlane = () => Promise.resolve(),
|
|
22
|
-
|
|
22
|
+
getLastMqttError = () => null, // QPA-CLI-02: Get last MQTT error for diagnostics
|
|
23
|
+
getForceReconnect = () => null, // QPA-CLI-03: Get force reconnect function
|
|
24
|
+
controlPlaneTimeoutMs = 60000,
|
|
25
|
+
// QPA-04: QuickPass security group slug
|
|
26
|
+
secGroupSlug = null
|
|
23
27
|
}) {
|
|
24
28
|
this.relayUrl = relayUrl;
|
|
25
29
|
this.jwt = jwt; // Accept JWT as-is (no validation)
|
|
@@ -28,6 +32,8 @@ export class HttpTunnel {
|
|
|
28
32
|
this.localPort = localPort;
|
|
29
33
|
this.log = log;
|
|
30
34
|
this.ws = null;
|
|
35
|
+
// QPA-04: Store secGroupSlug for use in refresh payloads
|
|
36
|
+
this.secGroupSlug = secGroupSlug;
|
|
31
37
|
|
|
32
38
|
// CLI-IMG-WSReconnect: Coordinator connection for JWT refresh
|
|
33
39
|
this.coordinatorCore = coordinatorCore;
|
|
@@ -36,6 +42,8 @@ export class HttpTunnel {
|
|
|
36
42
|
// CLI-IMG-ControlPlane-Watchdog: Control-plane connectivity helpers
|
|
37
43
|
this.isControlPlaneConnected = isControlPlaneConnected;
|
|
38
44
|
this.waitForControlPlane = waitForControlPlane;
|
|
45
|
+
this.getLastMqttError = getLastMqttError; // QPA-CLI-02: Store helper to get last MQTT error
|
|
46
|
+
this.getForceReconnect = getForceReconnect; // QPA-CLI-03: Store helper to force reconnect
|
|
39
47
|
this.controlPlaneTimeoutMs = Number(controlPlaneTimeoutMs) || 60000;
|
|
40
48
|
|
|
41
49
|
// CRT-Relay-E: Heartbeat properties
|
|
@@ -51,9 +59,15 @@ export class HttpTunnel {
|
|
|
51
59
|
this.headers = null; // Store headers for reuse during reconnects
|
|
52
60
|
|
|
53
61
|
// CLI-JWT-REFRESH: Refresh state machine
|
|
54
|
-
|
|
62
|
+
// QPA-CLI-01: Extended states for resilience
|
|
63
|
+
this.refreshState = 'idle'; // idle | pending | waiting_control_plane | retry_scheduled | fallback | failed
|
|
55
64
|
this.refreshAttempts = 0;
|
|
56
65
|
this.refreshMaxAttempts = parseInt(process.env.ASYX_TUNNEL_REFRESH_MAX_RETRIES || '3', 10);
|
|
66
|
+
// QPA-CLI-01: Refresh supervisor state
|
|
67
|
+
this.refreshRetryTimer = null;
|
|
68
|
+
this.refreshDeadline = null; // JWT expiry deadline (expMs - safetyMargin)
|
|
69
|
+
this.refreshRetryCount = 0;
|
|
70
|
+
this.refreshRetryMaxDelay = 30000; // Max 30s between retries
|
|
57
71
|
|
|
58
72
|
// CLI-RES-DPJWT-LEAD: Proactive refresh scheduling
|
|
59
73
|
this.refreshTimer = null;
|
|
@@ -328,27 +342,117 @@ export class HttpTunnel {
|
|
|
328
342
|
async _ensureControlPlane(reason, forceWait = false) {
|
|
329
343
|
if (!forceWait && this.isControlPlaneConnected()) return true;
|
|
330
344
|
|
|
331
|
-
|
|
345
|
+
// QPA-CLI-01: Log actual MQTT reason when control-plane is offline
|
|
346
|
+
const mqttReason = this.isControlPlaneConnected() ? 'connected' : 'offline';
|
|
347
|
+
this.log.warn({ reason, mqttReason }, "Control-plane offline, waiting for reconnect");
|
|
332
348
|
|
|
333
349
|
try {
|
|
334
350
|
// Use waitForControlPlane which internally calls transport.waitForConnect()
|
|
335
351
|
await this.waitForControlPlane();
|
|
336
|
-
|
|
352
|
+
// CLI-MQTT-UniqueID-CleanSession: Get session client ID from transport for logging
|
|
353
|
+
const lastMqttError = this.getLastMqttError ? this.getLastMqttError() : null;
|
|
354
|
+
const sessionClientId = lastMqttError?.clientId || 'unknown';
|
|
355
|
+
this.log.info({ reason, sessionClientId }, "Control-plane reconnected");
|
|
337
356
|
return true;
|
|
338
357
|
} catch (err) {
|
|
339
|
-
//
|
|
358
|
+
// QPA-CLI-02: Get last MQTT error for diagnostic information
|
|
359
|
+
const lastMqttError = this.getLastMqttError ? this.getLastMqttError() : null;
|
|
360
|
+
const mqttReasonCode = lastMqttError?.code;
|
|
361
|
+
const mqttReason = lastMqttError?.reason || this._extractMqttReasonFromError(lastMqttError);
|
|
362
|
+
|
|
363
|
+
// QPA-CLI-01: Extract and log actual MQTT reason from WaitForConnectError
|
|
364
|
+
let mqttErrorReason = 'unknown';
|
|
340
365
|
if (err.name === 'WaitForConnectError') {
|
|
341
|
-
|
|
366
|
+
// WaitForConnectError has a 'reason' property: 'timeout' | 'terminated'
|
|
367
|
+
mqttErrorReason = err.reason || 'timeout';
|
|
368
|
+
|
|
369
|
+
// QPA-CLI-03: Force reconnect on timeout
|
|
370
|
+
if (mqttErrorReason === 'timeout' && this.getForceReconnect) {
|
|
371
|
+
const forceReconnect = this.getForceReconnect();
|
|
372
|
+
if (forceReconnect) {
|
|
373
|
+
this.log.info('mqtt.transport.force_reconnect.attempt', { reason, attempt: 1 });
|
|
374
|
+
try {
|
|
375
|
+
await forceReconnect();
|
|
376
|
+
// Retry waitForControlPlane up to 3 times with 5s delay
|
|
377
|
+
const maxRetries = 3;
|
|
378
|
+
const retryDelayMs = 5000;
|
|
379
|
+
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
380
|
+
try {
|
|
381
|
+
await new Promise(resolve => setTimeout(resolve, retryDelayMs));
|
|
382
|
+
await this.waitForControlPlane();
|
|
383
|
+
this.log.info('mqtt.transport.force_reconnect.success', { reason, attempt });
|
|
384
|
+
this.log.info({ reason }, "Control-plane reconnected after force reconnect");
|
|
385
|
+
return true;
|
|
386
|
+
} catch (retryErr) {
|
|
387
|
+
if (attempt < maxRetries) {
|
|
388
|
+
this.log.warn('mqtt.transport.force_reconnect.retry', { reason, attempt: attempt + 1, error: retryErr.message });
|
|
389
|
+
} else {
|
|
390
|
+
this.log.warn('mqtt.transport.force_reconnect.exhausted', { reason, attempts: maxRetries });
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
} catch (forceErr) {
|
|
395
|
+
this.log.warn('mqtt.transport.force_reconnect.failed', { reason, error: forceErr.message });
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// QPA-CLI-02: Include MQTT error details in log
|
|
401
|
+
this.log.warn('mqtt.transport.wait_for_connect.failed', {
|
|
402
|
+
reason,
|
|
403
|
+
mqttReason: mqttErrorReason,
|
|
404
|
+
mqttErrorCode: mqttReasonCode,
|
|
405
|
+
mqttErrorReason: mqttReason,
|
|
406
|
+
mqttEvent: lastMqttError?.event,
|
|
407
|
+
error: err.message
|
|
408
|
+
});
|
|
409
|
+
// QPA-CLI-02: User-facing message includes MQTT reason if available
|
|
410
|
+
let userMessage = `⚠️ Control-plane offline (${mqttErrorReason})`;
|
|
411
|
+
if (mqttReason && mqttReason !== 'unknown') {
|
|
412
|
+
userMessage += `. MQTT reason: ${mqttReason}`;
|
|
413
|
+
}
|
|
414
|
+
userMessage += `. Waiting for reconnect…\n`;
|
|
415
|
+
process.stdout.write(userMessage);
|
|
342
416
|
return false;
|
|
343
417
|
}
|
|
344
418
|
if (err.message === "control_plane_timeout") {
|
|
345
|
-
|
|
419
|
+
// QPA-CLI-02: Include MQTT error details in timeout log
|
|
420
|
+
this.log.warn('mqtt.transport.wait_for_connect.timeout', {
|
|
421
|
+
reason,
|
|
422
|
+
mqttErrorCode: mqttReasonCode,
|
|
423
|
+
mqttErrorReason: mqttReason,
|
|
424
|
+
mqttEvent: lastMqttError?.event
|
|
425
|
+
});
|
|
426
|
+
let userMessage = `⚠️ Control-plane offline (timeout)`;
|
|
427
|
+
if (mqttReason && mqttReason !== 'unknown') {
|
|
428
|
+
userMessage += `. MQTT reason: ${mqttReason}`;
|
|
429
|
+
}
|
|
430
|
+
userMessage += `. Waiting for reconnect…\n`;
|
|
431
|
+
process.stdout.write(userMessage);
|
|
346
432
|
return false;
|
|
347
433
|
}
|
|
348
434
|
throw err;
|
|
349
435
|
}
|
|
350
436
|
}
|
|
351
437
|
|
|
438
|
+
// QPA-CLI-02: Extract human-readable MQTT reason from error object
|
|
439
|
+
_extractMqttReasonFromError(mqttError) {
|
|
440
|
+
if (!mqttError) return 'unknown';
|
|
441
|
+
if (mqttError.reason) return mqttError.reason;
|
|
442
|
+
if (mqttError.code) {
|
|
443
|
+
const codeNum = typeof mqttError.code === 'string' ? parseInt(mqttError.code, 10) : mqttError.code;
|
|
444
|
+
const reasonMap = {
|
|
445
|
+
4: 'bad_username_password',
|
|
446
|
+
5: 'identifier_in_use',
|
|
447
|
+
6: 'server_unavailable',
|
|
448
|
+
7: 'bad_username_password',
|
|
449
|
+
8: 'not_authorized'
|
|
450
|
+
};
|
|
451
|
+
return reasonMap[codeNum] || `code_${codeNum}`;
|
|
452
|
+
}
|
|
453
|
+
return 'unknown';
|
|
454
|
+
}
|
|
455
|
+
|
|
352
456
|
async open() {
|
|
353
457
|
// CLI-IMG-WSReconnect: Start the connection process
|
|
354
458
|
return this._attemptConnect();
|
|
@@ -441,7 +545,14 @@ export class HttpTunnel {
|
|
|
441
545
|
});
|
|
442
546
|
|
|
443
547
|
this.ws.on('close', (code, reason) => {
|
|
444
|
-
|
|
548
|
+
// QPA-CLI-10: Normal closures (code 1000) are debug-level, not warnings
|
|
549
|
+
const reasonStr = reason?.toString() || '';
|
|
550
|
+
const isNormalClose = code === 1000 && (reasonStr === 'closing' || reasonStr === '');
|
|
551
|
+
if (isNormalClose) {
|
|
552
|
+
this.log.debug({ code, reason: reasonStr }, 'Tunnel WS closed');
|
|
553
|
+
} else {
|
|
554
|
+
this.log.warn({ code, reason: reasonStr }, 'Tunnel WS closed');
|
|
555
|
+
}
|
|
445
556
|
// CRT-Relay-E: Stop heartbeat on close
|
|
446
557
|
this.stopHeartbeat();
|
|
447
558
|
// CLI-REAUTH: Cleanup control frame waiters on socket close
|
|
@@ -502,13 +613,25 @@ export class HttpTunnel {
|
|
|
502
613
|
|
|
503
614
|
this.retryCount++;
|
|
504
615
|
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
616
|
+
// QPA-CLI-10: Normal closures (code 1000) are debug-level, not warnings
|
|
617
|
+
const isNormalClose = code === 1000 && (reasonStr === 'closing' || reasonStr === '');
|
|
618
|
+
if (isNormalClose) {
|
|
619
|
+
this.log.debug({
|
|
620
|
+
delay,
|
|
621
|
+
retryCount: this.retryCount,
|
|
622
|
+
maxRetries: this.maxRetries,
|
|
623
|
+
code,
|
|
624
|
+
reason: reasonStr
|
|
625
|
+
}, 'Tunnel WS reconnect scheduled');
|
|
626
|
+
} else {
|
|
627
|
+
this.log.warn({
|
|
628
|
+
delay,
|
|
629
|
+
retryCount: this.retryCount,
|
|
630
|
+
maxRetries: this.maxRetries,
|
|
631
|
+
code,
|
|
632
|
+
reason: reasonStr
|
|
633
|
+
}, 'Tunnel WS reconnect scheduled');
|
|
634
|
+
}
|
|
512
635
|
|
|
513
636
|
// Schedule reconnect attempt
|
|
514
637
|
this.reconnectTimer = setTimeout(() => {
|
|
@@ -533,26 +656,106 @@ export class HttpTunnel {
|
|
|
533
656
|
}
|
|
534
657
|
}
|
|
535
658
|
|
|
659
|
+
// QPA-CLI-01: Schedule retry with exponential backoff
|
|
660
|
+
_scheduleRefreshRetry(reason) {
|
|
661
|
+
// Clear any existing retry timer
|
|
662
|
+
if (this.refreshRetryTimer) {
|
|
663
|
+
clearTimeout(this.refreshRetryTimer);
|
|
664
|
+
this.refreshRetryTimer = null;
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// QPA-CLI-03: Check if we've exceeded the deadline AND MQTT is still offline
|
|
668
|
+
if (this.refreshDeadline && Date.now() >= this.refreshDeadline) {
|
|
669
|
+
// Only mark expired if control plane is still offline
|
|
670
|
+
if (!this.isControlPlaneConnected()) {
|
|
671
|
+
this.log.error('jwt.refresh.expired', {
|
|
672
|
+
retryCount: this.refreshRetryCount,
|
|
673
|
+
deadline: this.refreshDeadline,
|
|
674
|
+
elapsed: Date.now() - (this.refreshDeadline - this.LEAD_MS)
|
|
675
|
+
});
|
|
676
|
+
this.refreshState = 'failed';
|
|
677
|
+
process.stdout.write(`❌ JWT expired while control-plane was offline. Exiting.\n`);
|
|
678
|
+
process.exit(1);
|
|
679
|
+
} else {
|
|
680
|
+
// Control plane came back, reset deadline and continue
|
|
681
|
+
this.log.info('jwt.refresh.deadline_extended', {
|
|
682
|
+
retryCount: this.refreshRetryCount,
|
|
683
|
+
oldDeadline: this.refreshDeadline
|
|
684
|
+
});
|
|
685
|
+
// Extend deadline by another 90 seconds
|
|
686
|
+
this.refreshDeadline = Date.now() + 90000;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// Calculate exponential backoff delay
|
|
691
|
+
this.refreshRetryCount += 1;
|
|
692
|
+
const baseDelay = 5000; // 5 seconds
|
|
693
|
+
const delayMs = Math.min(baseDelay * Math.pow(2, this.refreshRetryCount - 1), this.refreshRetryMaxDelay);
|
|
694
|
+
|
|
695
|
+
this.log.info('jwt.refresh.delay', {
|
|
696
|
+
reason: 'control_plane_offline',
|
|
697
|
+
retryCount: this.refreshRetryCount,
|
|
698
|
+
nextDelayMs: delayMs,
|
|
699
|
+
deadline: this.refreshDeadline ? new Date(this.refreshDeadline).toISOString() : null
|
|
700
|
+
});
|
|
701
|
+
|
|
702
|
+
// QPA-CLI-01: Operator feedback
|
|
703
|
+
process.stdout.write(`⚠️ QuickPass token refresh delayed – reconnecting control plane… (retry ${this.refreshRetryCount})\n`);
|
|
704
|
+
|
|
705
|
+
this.refreshState = 'retry_scheduled';
|
|
706
|
+
this.refreshRetryTimer = setTimeout(() => {
|
|
707
|
+
this.refreshRetryTimer = null;
|
|
708
|
+
// Retry the refresh
|
|
709
|
+
this.attemptJwtRefresh().catch(err => {
|
|
710
|
+
this.log.error('jwt.refresh.retry.failed', { error: err.message, retryCount: this.refreshRetryCount });
|
|
711
|
+
});
|
|
712
|
+
}, delayMs);
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// QPA-CLI-01: Cancel scheduled retry (called when MQTT reconnects)
|
|
716
|
+
_cancelRefreshRetry() {
|
|
717
|
+
if (this.refreshRetryTimer) {
|
|
718
|
+
clearTimeout(this.refreshRetryTimer);
|
|
719
|
+
this.refreshRetryTimer = null;
|
|
720
|
+
}
|
|
721
|
+
if (this.refreshState === 'retry_scheduled' || this.refreshState === 'waiting_control_plane') {
|
|
722
|
+
this.log.info('jwt.refresh.resumed', { retryCount: this.refreshRetryCount });
|
|
723
|
+
this.refreshState = 'pending';
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
|
|
536
727
|
// CLI-IMG-WSReconnect: JWT refresh logic
|
|
537
728
|
async attemptJwtRefresh() {
|
|
538
729
|
try {
|
|
539
|
-
if (
|
|
730
|
+
// QPA-CLI-01: Check if we've exceeded max attempts (only for actual refresh attempts, not retries)
|
|
731
|
+
if (this.refreshAttempts >= this.refreshMaxAttempts && this.refreshState !== 'retry_scheduled' && this.refreshState !== 'waiting_control_plane') {
|
|
540
732
|
this.log.error('jwt.refresh.exhausted', { retryCount: this.refreshAttempts });
|
|
541
733
|
this.refreshState = 'failed';
|
|
542
734
|
process.exit(1);
|
|
543
735
|
}
|
|
544
736
|
|
|
737
|
+
// QPA-CLI-01: Set refresh deadline on first attempt
|
|
738
|
+
if (this.refreshState === 'idle' && this.jwtMeta?.expMs) {
|
|
739
|
+
const safetyMargin = 90000; // QPA-CLI-03: Extended to 90 seconds safety margin
|
|
740
|
+
this.refreshDeadline = this.jwtMeta.expMs - safetyMargin;
|
|
741
|
+
this.refreshRetryCount = 0; // Reset retry count for new refresh cycle
|
|
742
|
+
}
|
|
743
|
+
|
|
545
744
|
this.refreshAttempts += 1;
|
|
546
745
|
this.refreshState = 'pending';
|
|
547
746
|
this.log.info('jwt.refresh.start', { retryCount: this.refreshAttempts });
|
|
548
747
|
|
|
549
|
-
// CLI-
|
|
748
|
+
// QPA-CLI-01: Ensure control-plane connectivity with retry logic
|
|
550
749
|
const ready = await this._ensureControlPlane("jwt_refresh");
|
|
551
750
|
if (!ready) {
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
751
|
+
// QPA-CLI-01: Instead of immediately falling back, schedule a retry
|
|
752
|
+
this.refreshState = 'waiting_control_plane';
|
|
753
|
+
this._scheduleRefreshRetry('control_plane_offline');
|
|
754
|
+
return; // Keep tunnel running, retry will happen via timer
|
|
555
755
|
}
|
|
756
|
+
|
|
757
|
+
// QPA-CLI-01: Control-plane is ready, cancel any pending retry
|
|
758
|
+
this._cancelRefreshRetry();
|
|
556
759
|
|
|
557
760
|
// Check if we have coordinator connection
|
|
558
761
|
if (!this.coordinatorCore || !this.coordinatorIngress) {
|
|
@@ -596,6 +799,11 @@ export class HttpTunnel {
|
|
|
596
799
|
...fingerprint
|
|
597
800
|
};
|
|
598
801
|
|
|
802
|
+
// QPA-04: Include secGroupSlug in refresh payload if provided
|
|
803
|
+
if (this.secGroupSlug) {
|
|
804
|
+
refreshPayload.secGroupSlug = this.secGroupSlug;
|
|
805
|
+
}
|
|
806
|
+
|
|
599
807
|
// Set up topic for refresh request
|
|
600
808
|
const cmdOpenTopic = `asyx/tunnel/clients/${this.deviceId}/cmd/open`;
|
|
601
809
|
|
|
@@ -671,8 +879,12 @@ export class HttpTunnel {
|
|
|
671
879
|
const deltaMs = recordRefresh(Date.now());
|
|
672
880
|
this.log.info('jwt.refresh.delta', { deltaMs });
|
|
673
881
|
this.log.info('jwt.refresh.success', { retryCount: this.refreshAttempts, leaseId: newAssignment.leaseId, method: 'in_band' });
|
|
882
|
+
// QPA-CLI-01: Reset retry state on success
|
|
674
883
|
this.refreshState = 'idle';
|
|
675
884
|
this.refreshAttempts = 0;
|
|
885
|
+
this.refreshRetryCount = 0;
|
|
886
|
+
this.refreshDeadline = null;
|
|
887
|
+
this._cancelRefreshRetry();
|
|
676
888
|
return; // Socket stayed open, no reconnect needed
|
|
677
889
|
}
|
|
678
890
|
|
|
@@ -701,8 +913,12 @@ export class HttpTunnel {
|
|
|
701
913
|
const deltaMs = recordRefresh(Date.now());
|
|
702
914
|
this.log.info('jwt.refresh.delta', { deltaMs });
|
|
703
915
|
this.log.info('jwt.refresh.success', { retryCount: this.refreshAttempts, leaseId: newAssignment.leaseId, method: 'reconnect' });
|
|
916
|
+
// QPA-CLI-01: Reset retry state on success
|
|
704
917
|
this.refreshState = 'idle';
|
|
705
918
|
this.refreshAttempts = 0;
|
|
919
|
+
this.refreshRetryCount = 0;
|
|
920
|
+
this.refreshDeadline = null;
|
|
921
|
+
this._cancelRefreshRetry();
|
|
706
922
|
|
|
707
923
|
// CLI-RES-DPJWT-LEAD: Schedule next proactive refresh
|
|
708
924
|
this.scheduleRefresh(this.jwt, 'refresh_success');
|
|
@@ -755,18 +971,15 @@ export class HttpTunnel {
|
|
|
755
971
|
await this.waitForControlPlane();
|
|
756
972
|
this.log.info('jwt.refresh.fallback.control_plane_recovered', { leaseId });
|
|
757
973
|
} catch (waitError) {
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
this.log.error('jwt.refresh.fallback.failure', {
|
|
974
|
+
// QPA-CLI-01: Instead of exiting, schedule a retry
|
|
975
|
+
this.log.warn('jwt.refresh.fallback.control_plane_wait_failed', {
|
|
761
976
|
error: waitError.message,
|
|
762
|
-
reason: 'control_plane_timeout_exhausted',
|
|
763
977
|
retryCount,
|
|
764
978
|
leaseId
|
|
765
979
|
});
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
continue; // Retry fallback after brief delay
|
|
980
|
+
// Schedule retry with backoff
|
|
981
|
+
this._scheduleRefreshRetry('fallback_control_plane_offline');
|
|
982
|
+
return; // Keep tunnel running, retry will happen via timer
|
|
770
983
|
}
|
|
771
984
|
}
|
|
772
985
|
|
|
@@ -1070,6 +1283,11 @@ export class HttpTunnel {
|
|
|
1070
1283
|
clearTimeout(this.refreshTimer);
|
|
1071
1284
|
this.refreshTimer = null;
|
|
1072
1285
|
}
|
|
1286
|
+
// QPA-CLI-01: Clean up retry timer
|
|
1287
|
+
if (this.refreshRetryTimer) {
|
|
1288
|
+
clearTimeout(this.refreshRetryTimer);
|
|
1289
|
+
this.refreshRetryTimer = null;
|
|
1290
|
+
}
|
|
1073
1291
|
|
|
1074
1292
|
// CLI-REAUTH: Cleanup control frame waiters
|
|
1075
1293
|
clearAllWaiters();
|