asyx 0.10.1 → 0.11.1
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 +8 -2
- 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 -932
- package/src/commands/validate-target-host.js +36 -59
- package/src/lib/aws-iot-config.js +26 -24
- 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 +17 -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 +22 -74
- 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
|
@@ -2,23 +2,14 @@ import { AnyEvt as AnyEvtSchema } from "./schemas.js";
|
|
|
2
2
|
import { setAssignment, getAssignment } from "../../state/assignment.js";
|
|
3
3
|
import logger from "../../lib/logger.js";
|
|
4
4
|
import { RefusedError } from "../../errors.js";
|
|
5
|
-
// Story 12.1 (step 2b): refusals that end the open (QPA-04, TCP-S3, TPB-03B). Codes are the
|
|
6
|
-
// coordinator's reasons, lower-cased.
|
|
7
5
|
export const FATAL_REJECT_CODES = new Set([
|
|
8
6
|
'invalid_secgroup', 'tcp_port_out_of_block', 'tcp_port_already_in_use', 'tcp_port_block_exhausted_for_tenant',
|
|
9
7
|
'tcp_port_block_exhausted', 'tcp_port_capacity_exhausted', 'tenant_tcp_lease_limit_reached',
|
|
10
8
|
]);
|
|
11
9
|
let openRejectReporter = null;
|
|
12
10
|
let replacedReporter = null;
|
|
13
|
-
/** Story 1.9: how "this tunnel was taken over by a newer one" is reported (the CLI prints and exits 75). */
|
|
14
11
|
export function setReplacedReporter(fn) { replacedReporter = fn; }
|
|
15
|
-
/** Register how open rejections are reported to the user (the CLI does; the SDK uses errors). */
|
|
16
12
|
export function setOpenRejectReporter(fn) { openRejectReporter = fn; }
|
|
17
|
-
/**
|
|
18
|
-
* Format milliseconds to human-readable hours:minutes
|
|
19
|
-
* @param {number} ms - Milliseconds
|
|
20
|
-
* @returns {string} Formatted string like "1h 30m" or "45m"
|
|
21
|
-
*/
|
|
22
13
|
function formatLeaseDuration(ms) {
|
|
23
14
|
const totalMinutes = Math.floor(ms / 60000);
|
|
24
15
|
const hours = Math.floor(totalMinutes / 60);
|
|
@@ -35,15 +26,12 @@ function formatLeaseDuration(ms) {
|
|
|
35
26
|
}
|
|
36
27
|
const registry = {
|
|
37
28
|
async setup_required(e) {
|
|
38
|
-
// Minimal user-facing message; CLI should exit(2)
|
|
39
|
-
// Do not add logs; leave control to caller via thrown Error with code.
|
|
40
29
|
const reason = e.data?.reason ? ` (${e.data.reason})` : "";
|
|
41
|
-
const err =
|
|
30
|
+
const err = (new Error(`Please run "asyx setup"${reason}`));
|
|
42
31
|
err.code = "SETUP_REQUIRED";
|
|
43
32
|
throw err;
|
|
44
33
|
},
|
|
45
34
|
async open_ack(e) {
|
|
46
|
-
// TPB-12: Route by instanceId - get instance context from dispatcher
|
|
47
35
|
const instanceId = e._instanceId;
|
|
48
36
|
const instanceContext = e._instanceContext;
|
|
49
37
|
if (!instanceId || !instanceContext) {
|
|
@@ -55,25 +43,19 @@ const registry = {
|
|
|
55
43
|
});
|
|
56
44
|
return;
|
|
57
45
|
}
|
|
58
|
-
// Normalize legacy format to canonical format
|
|
59
46
|
let data = e.data;
|
|
60
|
-
// Legacy format: { data: { jwt, relayId, leaseMs } }
|
|
61
|
-
// Canonical format: { data: { relayId, leaseMs, assignment: { jwt, fqdn, proto, path, ... } } }
|
|
62
47
|
if (data.jwt && !data.assignment) {
|
|
63
|
-
// Transform legacy to canonical
|
|
64
48
|
data = {
|
|
65
49
|
relayId: data.relayId,
|
|
66
50
|
leaseMs: data.leaseMs,
|
|
67
51
|
assignment: {
|
|
68
52
|
jwt: data.jwt,
|
|
69
|
-
fqdn: 'relay.customer.example',
|
|
53
|
+
fqdn: 'relay.customer.example',
|
|
70
54
|
proto: 'wss',
|
|
71
55
|
path: '/agent'
|
|
72
56
|
}
|
|
73
57
|
};
|
|
74
58
|
}
|
|
75
|
-
// QPA-CLI-11: Store QuickPass info in assignment for vault UX messaging
|
|
76
|
-
// Suppress QP: enabled and Ack received messages - they'll be consolidated in final tunnel.active message
|
|
77
59
|
const quickpassSlug = data.quickpass?.slug || null;
|
|
78
60
|
if (quickpassSlug) {
|
|
79
61
|
logger.info("qp.enabled", {
|
|
@@ -82,14 +64,8 @@ const registry = {
|
|
|
82
64
|
tunnelType: instanceContext.tunnelType
|
|
83
65
|
});
|
|
84
66
|
}
|
|
85
|
-
// Build relay URL with fallbacks for missing fields
|
|
86
|
-
// TCP-S4: Add fallbacks to prevent malformed URLs if TCP assignments omit fields
|
|
87
|
-
// UDP-S1: Add UDP support
|
|
88
67
|
const proto = data.assignment?.proto || 'wss';
|
|
89
68
|
const fqdn = data.assignment?.fqdn || data.fqdn || 'relay.unknown';
|
|
90
|
-
// TCP-S4: Always use /tcp for TCP tunnels, /agent for HTTP tunnels
|
|
91
|
-
// UDP-S1: Always use /udp for UDP tunnels
|
|
92
|
-
// Detect tunnel type by checking for publicPort (TCP/UDP-specific) or proto/tunnelMode
|
|
93
69
|
const isTcpTunnel = (data.assignment?.publicPort !== undefined ||
|
|
94
70
|
data.assignment?.proto === 'tcp' ||
|
|
95
71
|
data.publicPort !== undefined) &&
|
|
@@ -98,7 +74,6 @@ const registry = {
|
|
|
98
74
|
const isUdpTunnel = data.assignment?.tunnelMode === 'udpWs-v1' ||
|
|
99
75
|
data.assignment?.protocol === 'udp' ||
|
|
100
76
|
instanceContext.tunnelType === 'udp';
|
|
101
|
-
// Always override path for TCP/UDP tunnels, regardless of what the control plane returns
|
|
102
77
|
let path;
|
|
103
78
|
if (isUdpTunnel) {
|
|
104
79
|
path = '/udp';
|
|
@@ -110,7 +85,6 @@ const registry = {
|
|
|
110
85
|
path = data.assignment?.path || '/agent';
|
|
111
86
|
}
|
|
112
87
|
const url = `${proto}://${fqdn}${path}`;
|
|
113
|
-
// Log warning if fallbacks were used
|
|
114
88
|
if (!data.assignment?.proto || !data.assignment?.fqdn || !data.assignment?.path) {
|
|
115
89
|
logger.warn('open_ack.relay_url_fallback', {
|
|
116
90
|
requestId: e.requestId,
|
|
@@ -122,7 +96,6 @@ const registry = {
|
|
|
122
96
|
constructedUrl: url
|
|
123
97
|
});
|
|
124
98
|
}
|
|
125
|
-
// Store assignment in memory (never to disk)
|
|
126
99
|
const leaseId = e.correlationId || data.leaseId || data.assignment?.leaseId || null;
|
|
127
100
|
logger.debug("open_ack.lease_id", {
|
|
128
101
|
requestId: e.requestId,
|
|
@@ -130,18 +103,13 @@ const registry = {
|
|
|
130
103
|
leaseId,
|
|
131
104
|
tunnelType: instanceContext.tunnelType
|
|
132
105
|
});
|
|
133
|
-
// Check if this is a refresh (existing assignment) or initial connection
|
|
134
106
|
const existingAssignment = instanceContext.getAssignment(instanceId);
|
|
135
107
|
const isRefresh = existingAssignment !== null;
|
|
136
|
-
// TCP-S3: Extract TCP-specific fields from assignment
|
|
137
|
-
// E3-S8: Extract SRV status for Minecraft tunnels
|
|
138
|
-
// Reuse fqdn from above (already declared for relayUrl construction)
|
|
139
108
|
const tcpAliasFqdn = data.assignment?.tcpAliasFqdn || data.tcpAliasFqdn || null;
|
|
140
109
|
const publicPort = data.assignment?.publicPort || data.publicPort || null;
|
|
141
110
|
const srvProvisioned = data.assignment?.srvProvisioned === true;
|
|
142
111
|
const srvFqdn = data.assignment?.srvFqdn || null;
|
|
143
112
|
const warnings = data.warnings || data.assignment?.warnings || [];
|
|
144
|
-
// Extract JWT with null safety (required for tunnel authentication)
|
|
145
113
|
const jwt = data.assignment?.jwt || data.jwt || null;
|
|
146
114
|
if (!jwt) {
|
|
147
115
|
logger.error('open_ack.missing_jwt', {
|
|
@@ -153,32 +121,26 @@ const registry = {
|
|
|
153
121
|
});
|
|
154
122
|
throw new Error('Missing JWT in assignment');
|
|
155
123
|
}
|
|
156
|
-
// UDP-S1: Extract UDP-specific fields from assignment
|
|
157
124
|
const tunnelMode = data.assignment?.tunnelMode || data.tunnelMode || null;
|
|
158
125
|
const protocol = data.assignment?.protocol || data.protocol || null;
|
|
159
|
-
const assignmentJwt = data.assignment?.assignmentJwt || data.assignmentJwt || jwt;
|
|
160
|
-
// TPB-12: Use per-instance setAssignment
|
|
126
|
+
const assignmentJwt = data.assignment?.assignmentJwt || data.assignmentJwt || jwt;
|
|
161
127
|
instanceContext.setAssignment(instanceId, {
|
|
162
128
|
requestId: e.requestId,
|
|
163
129
|
relayId: data.relayId,
|
|
164
130
|
relayUrl: url,
|
|
165
|
-
jwt: assignmentJwt,
|
|
166
|
-
assignmentJwt: assignmentJwt,
|
|
131
|
+
jwt: assignmentJwt,
|
|
132
|
+
assignmentJwt: assignmentJwt,
|
|
167
133
|
leaseMs: data.leaseMs,
|
|
168
134
|
leaseId,
|
|
169
|
-
quickpassSlug,
|
|
170
|
-
// TCP-S3: Store TCP-specific fields
|
|
135
|
+
quickpassSlug,
|
|
171
136
|
tcpAliasFqdn,
|
|
172
137
|
publicPort,
|
|
173
138
|
fqdn,
|
|
174
|
-
// E3-S8: Store SRV provisioning status
|
|
175
139
|
srvProvisioned,
|
|
176
140
|
srvFqdn,
|
|
177
141
|
warnings,
|
|
178
|
-
// UDP-S1: Store UDP-specific fields
|
|
179
142
|
tunnelMode,
|
|
180
143
|
protocol,
|
|
181
|
-
// Story 2.11 c3: the named port's label moved to this address ({ port, kind, from, to })
|
|
182
144
|
portMoved: data.portMoved || null
|
|
183
145
|
});
|
|
184
146
|
logger.debug("open_ack.assignment_stored", {
|
|
@@ -192,7 +154,6 @@ const registry = {
|
|
|
192
154
|
publicPort,
|
|
193
155
|
hasWarnings: warnings.length > 0
|
|
194
156
|
});
|
|
195
|
-
// TCP-S3: Handle TCP_ALIAS_UNAVAILABLE warning (warn-only, don't fail)
|
|
196
157
|
if (warnings.includes('TCP_ALIAS_UNAVAILABLE') || warnings.some(w => w.code === 'TCP_ALIAS_UNAVAILABLE')) {
|
|
197
158
|
logger.warn('tcp.alias.unavailable', {
|
|
198
159
|
requestId: e.requestId,
|
|
@@ -202,16 +163,9 @@ const registry = {
|
|
|
202
163
|
publicPort
|
|
203
164
|
});
|
|
204
165
|
}
|
|
205
|
-
// QPA-CLI-11: Suppress all intermediate messages (QP: enabled, Ack received)
|
|
206
|
-
// These will be consolidated into the final vault UX sequence
|
|
207
166
|
},
|
|
208
167
|
async open_reject(e) {
|
|
209
|
-
// Story 12.1 (step 2b): the core holds no user-facing text and never exits. It works out the
|
|
210
|
-
// coordinator's reason and hands it to the reporter the caller registered (the CLI prints the
|
|
211
|
-
// same messages and exits where it always has). Without a reporter (SDK use), a refusal that
|
|
212
|
-
// ends the tunnel throws a RefusedError carrying the coordinator's reason as its code.
|
|
213
168
|
const d = e.data || {};
|
|
214
|
-
// TPB-12: Clean up expected requestId on rejection (prevents map leak)
|
|
215
169
|
const instanceId = e._instanceId || null;
|
|
216
170
|
if (instanceId) {
|
|
217
171
|
try {
|
|
@@ -219,23 +173,18 @@ const registry = {
|
|
|
219
173
|
clearExpectedRequestId(instanceId);
|
|
220
174
|
}
|
|
221
175
|
catch (err) {
|
|
222
|
-
// Ignore cleanup errors (module may not be available in all contexts)
|
|
223
176
|
}
|
|
224
177
|
}
|
|
225
178
|
const code = String(d.reason || 'refused').toLowerCase();
|
|
226
|
-
// Story 1.9: a live tunnel of this kind already serves the address. The open that asked fails with
|
|
227
|
-
// a RefusedError carrying the details; the flow decides whether to wait and ask again.
|
|
228
179
|
if (code === 'address_in_use' && e.requestId) {
|
|
229
180
|
const { rejectAssignment } = await import('../../state/assignment.js');
|
|
230
181
|
if (rejectAssignment(e.requestId, new RefusedError('address_in_use', 'a live tunnel of this kind already serves this address', { details: d })))
|
|
231
182
|
return;
|
|
232
183
|
}
|
|
233
|
-
// Story 3.13: a renewal (or reopen) refused because the lease is closed fails the request waiting
|
|
234
|
-
// for it with LEASE_CLOSED, so the tunnel reopens on the same address instead of printing a refusal.
|
|
235
184
|
if (code === 'lease_closed' && e.requestId) {
|
|
236
185
|
const { rejectAssignment } = await import('../../state/assignment.js');
|
|
237
186
|
const err = new RefusedError('lease_closed', 'the lease was closed', { details: d });
|
|
238
|
-
|
|
187
|
+
(err).code = 'LEASE_CLOSED';
|
|
239
188
|
if (rejectAssignment(e.requestId, err))
|
|
240
189
|
return;
|
|
241
190
|
}
|
|
@@ -247,27 +196,25 @@ const registry = {
|
|
|
247
196
|
if (report.fatal)
|
|
248
197
|
throw new RefusedError(code, `coordinator refused the open: ${d.reason}`, { details: d });
|
|
249
198
|
},
|
|
250
|
-
// Story 1.9: a newer tunnel took this address over with --replace. Only the tunnel whose lease was
|
|
251
|
-
// replaced reacts (routed by instanceId/leaseId); it stops and does not reconnect.
|
|
252
199
|
async replaced(e) {
|
|
253
200
|
const d = e.data || {};
|
|
254
201
|
const ctx = e._instanceContext;
|
|
255
202
|
const mine = ctx?.getAssignment?.(e._instanceId);
|
|
256
203
|
if (!d.leaseId || mine?.leaseId !== d.leaseId)
|
|
257
|
-
return;
|
|
204
|
+
return;
|
|
258
205
|
const report = { code: 'replaced', at: d.at || null, by: d.by || null, kind: d.kind || null, hostname: d.hostname || null, instanceId: e._instanceId || null };
|
|
259
206
|
if (replacedReporter) {
|
|
260
207
|
await replacedReporter(report);
|
|
261
208
|
return;
|
|
262
209
|
}
|
|
263
|
-
const err =
|
|
210
|
+
const err = (new Error('this tunnel was taken over by a newer tunnel for the same address'));
|
|
264
211
|
err.code = 'ERROR_REPLACED';
|
|
265
212
|
err.details = report;
|
|
266
213
|
throw err;
|
|
267
214
|
},
|
|
268
215
|
async error(e) {
|
|
269
216
|
const d = e.data || {};
|
|
270
|
-
const err =
|
|
217
|
+
const err = (new Error(d.msg || "Command failed"));
|
|
271
218
|
err.code = `ERROR_${String(d.code || "UNKNOWN").toUpperCase()}`;
|
|
272
219
|
throw err;
|
|
273
220
|
},
|
|
@@ -275,7 +222,6 @@ const registry = {
|
|
|
275
222
|
export function getHandler(type) {
|
|
276
223
|
return registry[type];
|
|
277
224
|
}
|
|
278
|
-
// Safe parse helper the caller can reuse if needed
|
|
279
225
|
export function parseAny(raw) {
|
|
280
226
|
try {
|
|
281
227
|
const txt = typeof raw === "string" ? raw : new TextDecoder().decode(raw);
|
|
@@ -2,36 +2,24 @@ import { parseAny, getHandler } from "./handlers.js";
|
|
|
2
2
|
import { getInstance, getAllInstances, resolveInstanceByRequestId } from "../../state/instance-registry.js";
|
|
3
3
|
import { resolveInstanceByLease, getAssignment } from "../../state/assignment.js";
|
|
4
4
|
import logger from "../../lib/logger.js";
|
|
5
|
-
// TPB-12: Track unmatched events to avoid log spam
|
|
6
5
|
let unmatchedEventLogged = false;
|
|
7
6
|
export async function dispatch(parsedMessage) {
|
|
8
|
-
// Extract the parsed payload from the message object
|
|
9
7
|
const payload = parsedMessage.payload;
|
|
10
8
|
if (!payload)
|
|
11
|
-
return;
|
|
12
|
-
// The payload is already parsed JSON, so we can use it directly
|
|
9
|
+
return;
|
|
13
10
|
const evt = payload;
|
|
14
11
|
if (!evt.type)
|
|
15
|
-
return;
|
|
16
|
-
// TPB-12: Route by instanceId/leaseId
|
|
12
|
+
return;
|
|
17
13
|
const instanceId = evt.instanceId || evt.data?.instanceId || null;
|
|
18
14
|
const leaseId = evt.correlationId || evt.data?.leaseId || evt.data?.assignment?.leaseId || null;
|
|
19
15
|
let targetInstanceId = null;
|
|
20
16
|
let instanceContext = null;
|
|
21
|
-
// Routing logic:
|
|
22
|
-
// 1. If instanceId present: lookup instance registry
|
|
23
|
-
// 2. If instanceId unknown but leaseId present: try leaseId resolution (resilience for rotated clientIds)
|
|
24
|
-
// 3. If both present but mismatch: log mismatch, prefer instanceId if both resolve
|
|
25
|
-
// 4. If neither: try other fallbacks, then drop
|
|
26
17
|
if (instanceId) {
|
|
27
18
|
instanceContext = getInstance(instanceId);
|
|
28
19
|
if (instanceContext) {
|
|
29
20
|
targetInstanceId = instanceId;
|
|
30
21
|
}
|
|
31
22
|
else {
|
|
32
|
-
// TPB-12: Don't early-drop on unknown instanceId - try multiple fallbacks
|
|
33
|
-
// This preserves resilience for rotated clientIds and initial connections
|
|
34
|
-
// Fallback 1: Try leaseId resolution (for rotated clientIds with existing assignments)
|
|
35
23
|
if (leaseId) {
|
|
36
24
|
const resolvedInstanceId = resolveInstanceByLease(leaseId);
|
|
37
25
|
if (resolvedInstanceId) {
|
|
@@ -49,7 +37,6 @@ export async function dispatch(parsedMessage) {
|
|
|
49
37
|
}
|
|
50
38
|
}
|
|
51
39
|
}
|
|
52
|
-
// Fallback 2: Try requestId resolution (for initial open_ack before assignment exists)
|
|
53
40
|
if (!targetInstanceId && evt.requestId) {
|
|
54
41
|
const preAssignmentInstanceId = resolveInstanceByRequestId(evt.requestId);
|
|
55
42
|
if (preAssignmentInstanceId) {
|
|
@@ -67,14 +54,7 @@ export async function dispatch(parsedMessage) {
|
|
|
67
54
|
}
|
|
68
55
|
}
|
|
69
56
|
}
|
|
70
|
-
// Defect 11.27: no fallback that matches a stored assignment's requestId here. The reply names
|
|
71
|
-
// an instance this process does not hold; every process of the device receives it, so it is
|
|
72
|
-
// used only for a request this process is still waiting for (fallback 2) or a lease it holds
|
|
73
|
-
// (fallback 1). Matching a stored requestId let one tunnel adopt another tunnel's lease when
|
|
74
|
-
// their renewal ids collided.
|
|
75
|
-
// Only log/drop if all fallbacks failed
|
|
76
57
|
if (!targetInstanceId) {
|
|
77
|
-
// 0.7.0: debug, not warn — with several tunnels on one computer every tunnel sees the others' replies.
|
|
78
58
|
logger.debug('evt.instance.unknown', {
|
|
79
59
|
instanceId,
|
|
80
60
|
leaseId,
|
|
@@ -87,7 +67,6 @@ export async function dispatch(parsedMessage) {
|
|
|
87
67
|
}
|
|
88
68
|
}
|
|
89
69
|
if (leaseId && !targetInstanceId) {
|
|
90
|
-
// Fallback to leaseId resolution when instanceId not present
|
|
91
70
|
const resolvedInstanceId = resolveInstanceByLease(leaseId);
|
|
92
71
|
if (resolvedInstanceId) {
|
|
93
72
|
instanceContext = getInstance(resolvedInstanceId);
|
|
@@ -96,7 +75,6 @@ export async function dispatch(parsedMessage) {
|
|
|
96
75
|
}
|
|
97
76
|
}
|
|
98
77
|
}
|
|
99
|
-
// Check for mismatch
|
|
100
78
|
if (instanceId && leaseId && targetInstanceId) {
|
|
101
79
|
const leaseResolvedInstanceId = resolveInstanceByLease(leaseId);
|
|
102
80
|
if (leaseResolvedInstanceId && leaseResolvedInstanceId !== instanceId) {
|
|
@@ -108,13 +86,10 @@ export async function dispatch(parsedMessage) {
|
|
|
108
86
|
eventType: evt.type,
|
|
109
87
|
requestId: evt.requestId
|
|
110
88
|
});
|
|
111
|
-
// Prefer instanceId (already set above)
|
|
112
89
|
}
|
|
113
90
|
}
|
|
114
|
-
// TPB-12: Backcompat fallback - if no instanceId/leaseId, try pre-assignment requestId, then assignment requestId, then single-instance
|
|
115
91
|
if (!targetInstanceId) {
|
|
116
92
|
const allInstances = getAllInstances();
|
|
117
|
-
// Fallback 1: Pre-assignment requestId matching (for initial open_ack before assignment exists)
|
|
118
93
|
if (evt.requestId) {
|
|
119
94
|
const preAssignmentInstanceId = resolveInstanceByRequestId(evt.requestId);
|
|
120
95
|
if (preAssignmentInstanceId) {
|
|
@@ -130,9 +105,7 @@ export async function dispatch(parsedMessage) {
|
|
|
130
105
|
}
|
|
131
106
|
}
|
|
132
107
|
}
|
|
133
|
-
// Fallback 2: Match by requestId in existing assignment (for refresh/reconnect)
|
|
134
108
|
if (!targetInstanceId && evt.requestId && allInstances.length > 0) {
|
|
135
|
-
// Try to find instance with matching requestId in assignment
|
|
136
109
|
for (const inst of allInstances) {
|
|
137
110
|
const assignment = getAssignment(inst.instanceId);
|
|
138
111
|
if (assignment && assignment.requestId === evt.requestId) {
|
|
@@ -148,7 +121,6 @@ export async function dispatch(parsedMessage) {
|
|
|
148
121
|
}
|
|
149
122
|
}
|
|
150
123
|
}
|
|
151
|
-
// Fallback 3: Single registered instance (backcompat for TPB-13)
|
|
152
124
|
if (!targetInstanceId && allInstances.length === 1) {
|
|
153
125
|
instanceContext = allInstances[0];
|
|
154
126
|
targetInstanceId = instanceContext.instanceId;
|
|
@@ -159,7 +131,6 @@ export async function dispatch(parsedMessage) {
|
|
|
159
131
|
note: 'No instanceId in event; routed to single registered instance (backcompat)'
|
|
160
132
|
});
|
|
161
133
|
}
|
|
162
|
-
// If still no target, drop event
|
|
163
134
|
if (!targetInstanceId) {
|
|
164
135
|
if (!unmatchedEventLogged) {
|
|
165
136
|
logger.warn('evt.unmatched', {
|
|
@@ -171,10 +142,7 @@ export async function dispatch(parsedMessage) {
|
|
|
171
142
|
note: 'Event dropped - no matching instance. This may be normal for late/unknown events.'
|
|
172
143
|
});
|
|
173
144
|
unmatchedEventLogged = true;
|
|
174
|
-
// Reset after 60 seconds to allow occasional logging
|
|
175
|
-
// Store timeout handle for potential cleanup (though module-level cleanup is rare)
|
|
176
145
|
const timeoutHandle = setTimeout(() => { unmatchedEventLogged = false; }, 60000);
|
|
177
|
-
// In test mode, unref the timeout so it doesn't keep the process alive
|
|
178
146
|
if (process.env.JEST_WORKER_ID !== undefined || process.env.NODE_ENV === 'test') {
|
|
179
147
|
timeoutHandle.unref();
|
|
180
148
|
}
|
|
@@ -182,11 +150,10 @@ export async function dispatch(parsedMessage) {
|
|
|
182
150
|
return;
|
|
183
151
|
}
|
|
184
152
|
}
|
|
185
|
-
// Attach instance context to event for handlers
|
|
186
153
|
evt._instanceId = targetInstanceId;
|
|
187
154
|
evt._instanceContext = instanceContext;
|
|
188
155
|
const handler = getHandler(evt.type);
|
|
189
156
|
if (!handler)
|
|
190
|
-
return;
|
|
157
|
+
return;
|
|
191
158
|
return handler(evt);
|
|
192
159
|
}
|
|
@@ -1,22 +1,9 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Single Ingress Message Handler
|
|
3
|
-
*
|
|
4
|
-
* Provides a single point of entry for all MQTT messages that:
|
|
5
|
-
* 1. Parses messages once
|
|
6
|
-
* 2. Resolves awaiters for request/response flows
|
|
7
|
-
* 3. Always forwards messages to the CP-3F dispatcher
|
|
8
|
-
*
|
|
9
|
-
* This eliminates the handler-order race that prevents CP-3F envelopes
|
|
10
|
-
* from being processed and establishes the pattern for future stories.
|
|
11
|
-
*/
|
|
12
1
|
import { AwaiterMap } from './awaiter-map.js';
|
|
13
2
|
export class MessageIngress {
|
|
14
3
|
constructor(options = {}) {
|
|
15
|
-
// QPA-CLI-10: Pass logger to AwaiterMap for quiet mode
|
|
16
4
|
this.awaiterMap = new AwaiterMap(options.maxAwaiters || 100, options.logger || null);
|
|
17
5
|
this.dispatcher = null;
|
|
18
6
|
this.observability = options.observability || false;
|
|
19
|
-
// Story 12.1 (c2): the core never prints; observability lines (ASYX_DEBUG=1) go to onObserve
|
|
20
7
|
this.onObserve = options.onObserve || null;
|
|
21
8
|
this.messageCounter = 0;
|
|
22
9
|
}
|
|
@@ -24,39 +11,19 @@ export class MessageIngress {
|
|
|
24
11
|
if (this.onObserve)
|
|
25
12
|
this.onObserve(line);
|
|
26
13
|
}
|
|
27
|
-
/**
|
|
28
|
-
* Set the CP-3F event dispatcher
|
|
29
|
-
* @param {Function} dispatcher - The dispatchEvt function
|
|
30
|
-
*/
|
|
31
14
|
setDispatcher(dispatcher) {
|
|
32
15
|
this.dispatcher = dispatcher;
|
|
33
16
|
}
|
|
34
|
-
/**
|
|
35
|
-
* Register an awaiter for request/response correlation
|
|
36
|
-
* @param {Function} criteria - Function that returns true if message matches
|
|
37
|
-
* @param {number} timeoutMs - Timeout in milliseconds
|
|
38
|
-
* @returns {Promise} Promise that resolves with the matching message
|
|
39
|
-
*/
|
|
40
17
|
registerAwaiter(criteria, timeoutMs = 5000) {
|
|
41
18
|
return this.awaiterMap.register(criteria, timeoutMs);
|
|
42
19
|
}
|
|
43
|
-
/**
|
|
44
|
-
* Cancel awaiters that match a test criteria
|
|
45
|
-
* @param {Function} testCriteria - Function that returns true if an awaiter should be cancelled
|
|
46
|
-
* @returns {number} Number of awaiters cancelled
|
|
47
|
-
*/
|
|
48
20
|
cancelAwaitersByCriteria(testCriteria) {
|
|
49
21
|
return this.awaiterMap.cancelByCriteria(testCriteria);
|
|
50
22
|
}
|
|
51
|
-
/**
|
|
52
|
-
* Main ingress handler - processes all incoming MQTT messages
|
|
53
|
-
* @param {Object} message - Raw MQTT message from transport
|
|
54
|
-
*/
|
|
55
23
|
async handleMessage(message) {
|
|
56
24
|
const msgId = ++this.messageCounter;
|
|
57
25
|
const ts = Date.now();
|
|
58
26
|
const sizeBytes = message.payload ? message.payload.length : 0;
|
|
59
|
-
// Parse message once
|
|
60
27
|
let parsedMessage;
|
|
61
28
|
let parseStatus = 'success';
|
|
62
29
|
try {
|
|
@@ -96,27 +63,21 @@ export class MessageIngress {
|
|
|
96
63
|
error: error.message
|
|
97
64
|
};
|
|
98
65
|
}
|
|
99
|
-
// Log ingress (CP-5 ready)
|
|
100
66
|
if (this.observability) {
|
|
101
67
|
this._observe(`[ingress] ts=${ts} msgId=${msgId} topic=${parsedMessage.topic} parseStatus=${parseStatus} sizeBytes=${sizeBytes}`);
|
|
102
68
|
}
|
|
103
|
-
// Check awaiters and resolve any matching promises
|
|
104
69
|
const awaiterResolved = this.awaiterMap.processMessage(parsedMessage);
|
|
105
|
-
// Always dispatch to CP-3F dispatcher (non-exclusive broadcast)
|
|
106
70
|
if (this.dispatcher) {
|
|
107
71
|
try {
|
|
108
72
|
await this.dispatcher(parsedMessage);
|
|
109
|
-
// Log dispatch completion (CP-5 ready)
|
|
110
73
|
if (this.observability) {
|
|
111
74
|
this._observe(`[dispatch] ts=${Date.now()} msgId=${msgId} dispatched=true`);
|
|
112
75
|
}
|
|
113
76
|
}
|
|
114
77
|
catch (error) {
|
|
115
|
-
// Log dispatch error but don't crash
|
|
116
78
|
if (this.observability) {
|
|
117
79
|
this._observe(`[dispatch] ts=${Date.now()} msgId=${msgId} dispatched=false error=${error.message}`);
|
|
118
80
|
}
|
|
119
|
-
// Re-throw dispatcher errors (they contain business logic like exit codes)
|
|
120
81
|
throw error;
|
|
121
82
|
}
|
|
122
83
|
}
|
|
@@ -127,10 +88,6 @@ export class MessageIngress {
|
|
|
127
88
|
sizeBytes
|
|
128
89
|
};
|
|
129
90
|
}
|
|
130
|
-
/**
|
|
131
|
-
* Get statistics about the ingress system
|
|
132
|
-
* @returns {Object} Statistics object
|
|
133
|
-
*/
|
|
134
91
|
getStats() {
|
|
135
92
|
return {
|
|
136
93
|
messageCounter: this.messageCounter,
|
|
@@ -139,30 +96,13 @@ export class MessageIngress {
|
|
|
139
96
|
observabilityEnabled: this.observability
|
|
140
97
|
};
|
|
141
98
|
}
|
|
142
|
-
/**
|
|
143
|
-
* Clear all awaiters (for cleanup)
|
|
144
|
-
*/
|
|
145
99
|
clear() {
|
|
146
100
|
this.awaiterMap.clear();
|
|
147
101
|
}
|
|
148
|
-
/**
|
|
149
|
-
* Create a session ID awaiter (backward compatibility)
|
|
150
|
-
* @param {string} sessionId - Session ID to match
|
|
151
|
-
* @param {string} expectedTopic - Expected topic pattern
|
|
152
|
-
* @param {number} timeoutMs - Timeout in milliseconds
|
|
153
|
-
* @returns {Promise} Promise that resolves with the matching message
|
|
154
|
-
*/
|
|
155
102
|
awaitSessionId(sessionId, expectedTopic, timeoutMs = 5000) {
|
|
156
103
|
const criteria = AwaiterMap.createSessionIdCriteria(sessionId, expectedTopic);
|
|
157
104
|
return this.registerAwaiter(criteria, timeoutMs);
|
|
158
105
|
}
|
|
159
|
-
/**
|
|
160
|
-
* Create a correlation ID awaiter (future use)
|
|
161
|
-
* @param {string} correlationId - Correlation ID to match
|
|
162
|
-
* @param {string} expectedTopic - Expected topic pattern
|
|
163
|
-
* @param {number} timeoutMs - Timeout in milliseconds
|
|
164
|
-
* @returns {Promise} Promise that resolves with the matching message
|
|
165
|
-
*/
|
|
166
106
|
awaitCorrelationId(correlationId, expectedTopic, timeoutMs = 5000) {
|
|
167
107
|
const criteria = AwaiterMap.createCorrelationIdCriteria(correlationId, expectedTopic);
|
|
168
108
|
return this.registerAwaiter(criteria, timeoutMs);
|