asyx 0.2.4 → 0.3.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.
@@ -1,4 +1,10 @@
1
1
  import { parseAny, getHandler } from "./handlers.js";
2
+ import { getInstance, getAllInstances, resolveInstanceByRequestId } from "../../state/instance-registry.js";
3
+ import { resolveInstanceByLease, getAssignment } from "../../state/assignment.js";
4
+ import logger from "../../lib/logger.js";
5
+
6
+ // TPB-12: Track unmatched events to avoid log spam
7
+ let unmatchedEventLogged = false;
2
8
 
3
9
  export async function dispatch(parsedMessage) {
4
10
  // Extract the parsed payload from the message object
@@ -8,6 +14,203 @@ export async function dispatch(parsedMessage) {
8
14
  // The payload is already parsed JSON, so we can use it directly
9
15
  const evt = payload;
10
16
  if (!evt.type) return; // No type — ignore
17
+
18
+ // TPB-12: Route by instanceId/leaseId
19
+ const instanceId = evt.instanceId || evt.data?.instanceId || null;
20
+ const leaseId = evt.correlationId || evt.data?.leaseId || evt.data?.assignment?.leaseId || null;
21
+
22
+ let targetInstanceId = null;
23
+ let instanceContext = null;
24
+
25
+ // Routing logic:
26
+ // 1. If instanceId present: lookup instance registry
27
+ // 2. If instanceId unknown but leaseId present: try leaseId resolution (resilience for rotated clientIds)
28
+ // 3. If both present but mismatch: log mismatch, prefer instanceId if both resolve
29
+ // 4. If neither: try other fallbacks, then drop
30
+
31
+ if (instanceId) {
32
+ instanceContext = getInstance(instanceId);
33
+ if (instanceContext) {
34
+ targetInstanceId = instanceId;
35
+ } else {
36
+ // TPB-12: Don't early-drop on unknown instanceId - try multiple fallbacks
37
+ // This preserves resilience for rotated clientIds and initial connections
38
+
39
+ // Fallback 1: Try leaseId resolution (for rotated clientIds with existing assignments)
40
+ if (leaseId) {
41
+ const resolvedInstanceId = resolveInstanceByLease(leaseId);
42
+ if (resolvedInstanceId) {
43
+ instanceContext = getInstance(resolvedInstanceId);
44
+ if (instanceContext) {
45
+ targetInstanceId = resolvedInstanceId;
46
+ logger.debug('evt.routed.leaseid_fallback', {
47
+ unknownInstanceId: instanceId,
48
+ resolvedInstanceId,
49
+ leaseId,
50
+ eventType: evt.type,
51
+ requestId: evt.requestId,
52
+ note: 'Unknown instanceId; routed via leaseId (likely rotated clientId)'
53
+ });
54
+ }
55
+ }
56
+ }
57
+
58
+ // Fallback 2: Try requestId resolution (for initial open_ack before assignment exists)
59
+ if (!targetInstanceId && evt.requestId) {
60
+ const preAssignmentInstanceId = resolveInstanceByRequestId(evt.requestId);
61
+ if (preAssignmentInstanceId) {
62
+ instanceContext = getInstance(preAssignmentInstanceId);
63
+ if (instanceContext) {
64
+ targetInstanceId = preAssignmentInstanceId;
65
+ logger.debug('evt.routed.requestid_fallback_unknown_instance', {
66
+ unknownInstanceId: instanceId,
67
+ resolvedInstanceId: targetInstanceId,
68
+ requestId: evt.requestId,
69
+ leaseId,
70
+ eventType: evt.type,
71
+ note: 'Unknown instanceId; routed via requestId (initial connection or rotated clientId)'
72
+ });
73
+ }
74
+ }
75
+ }
76
+
77
+ // Fallback 3: Try matching requestId in existing assignments (for refresh/reconnect)
78
+ if (!targetInstanceId && evt.requestId) {
79
+ const allInstances = getAllInstances();
80
+ for (const inst of allInstances) {
81
+ const assignment = getAssignment(inst.instanceId);
82
+ if (assignment && assignment.requestId === evt.requestId) {
83
+ instanceContext = inst;
84
+ targetInstanceId = inst.instanceId;
85
+ logger.debug('evt.routed.assignment_requestid_fallback', {
86
+ unknownInstanceId: instanceId,
87
+ resolvedInstanceId: targetInstanceId,
88
+ requestId: evt.requestId,
89
+ leaseId,
90
+ eventType: evt.type,
91
+ note: 'Unknown instanceId; routed via requestId match in assignment'
92
+ });
93
+ break;
94
+ }
95
+ }
96
+ }
97
+
98
+ // Only log/drop if all fallbacks failed
99
+ if (!targetInstanceId) {
100
+ logger.warn('evt.instance.unknown', {
101
+ instanceId,
102
+ leaseId,
103
+ eventType: evt.type,
104
+ requestId: evt.requestId,
105
+ note: 'Event dropped - unknown instanceId and all fallbacks failed'
106
+ });
107
+ return;
108
+ }
109
+ }
110
+ }
111
+
112
+ if (leaseId && !targetInstanceId) {
113
+ // Fallback to leaseId resolution when instanceId not present
114
+ const resolvedInstanceId = resolveInstanceByLease(leaseId);
115
+ if (resolvedInstanceId) {
116
+ instanceContext = getInstance(resolvedInstanceId);
117
+ if (instanceContext) {
118
+ targetInstanceId = resolvedInstanceId;
119
+ }
120
+ }
121
+ }
122
+
123
+ // Check for mismatch
124
+ if (instanceId && leaseId && targetInstanceId) {
125
+ const leaseResolvedInstanceId = resolveInstanceByLease(leaseId);
126
+ if (leaseResolvedInstanceId && leaseResolvedInstanceId !== instanceId) {
127
+ logger.warn('evt.instance.lease_mismatch', {
128
+ instanceId,
129
+ leaseId,
130
+ leaseResolvedInstanceId,
131
+ preferredInstanceId: instanceId,
132
+ eventType: evt.type,
133
+ requestId: evt.requestId
134
+ });
135
+ // Prefer instanceId (already set above)
136
+ }
137
+ }
138
+
139
+ // TPB-12: Backcompat fallback - if no instanceId/leaseId, try pre-assignment requestId, then assignment requestId, then single-instance
140
+ if (!targetInstanceId) {
141
+ const allInstances = getAllInstances();
142
+
143
+ // Fallback 1: Pre-assignment requestId matching (for initial open_ack before assignment exists)
144
+ if (evt.requestId) {
145
+ const preAssignmentInstanceId = resolveInstanceByRequestId(evt.requestId);
146
+ if (preAssignmentInstanceId) {
147
+ instanceContext = getInstance(preAssignmentInstanceId);
148
+ if (instanceContext) {
149
+ targetInstanceId = preAssignmentInstanceId;
150
+ logger.debug('evt.routed.pre_assignment_requestid', {
151
+ instanceId: targetInstanceId,
152
+ eventType: evt.type,
153
+ requestId: evt.requestId,
154
+ note: 'No instanceId in event; routed by pre-assignment requestId (backcompat)'
155
+ });
156
+ }
157
+ }
158
+ }
159
+
160
+ // Fallback 2: Match by requestId in existing assignment (for refresh/reconnect)
161
+ if (!targetInstanceId && evt.requestId && allInstances.length > 0) {
162
+ // Try to find instance with matching requestId in assignment
163
+ for (const inst of allInstances) {
164
+ const assignment = getAssignment(inst.instanceId);
165
+ if (assignment && assignment.requestId === evt.requestId) {
166
+ instanceContext = inst;
167
+ targetInstanceId = inst.instanceId;
168
+ logger.debug('evt.routed.requestid_match', {
169
+ instanceId: targetInstanceId,
170
+ eventType: evt.type,
171
+ requestId: evt.requestId,
172
+ note: 'No instanceId in event; routed by requestId match in assignment (backcompat)'
173
+ });
174
+ break;
175
+ }
176
+ }
177
+ }
178
+
179
+ // Fallback 3: Single registered instance (backcompat for TPB-13)
180
+ if (!targetInstanceId && allInstances.length === 1) {
181
+ instanceContext = allInstances[0];
182
+ targetInstanceId = instanceContext.instanceId;
183
+ logger.debug('evt.routed.single_instance_fallback', {
184
+ instanceId: targetInstanceId,
185
+ eventType: evt.type,
186
+ requestId: evt.requestId,
187
+ note: 'No instanceId in event; routed to single registered instance (backcompat)'
188
+ });
189
+ }
190
+
191
+ // If still no target, drop event
192
+ if (!targetInstanceId) {
193
+ if (!unmatchedEventLogged) {
194
+ logger.warn('evt.unmatched', {
195
+ instanceId,
196
+ leaseId,
197
+ eventType: evt.type,
198
+ requestId: evt.requestId,
199
+ registeredInstances: allInstances.length,
200
+ note: 'Event dropped - no matching instance. This may be normal for late/unknown events.'
201
+ });
202
+ unmatchedEventLogged = true;
203
+ // Reset after 60 seconds to allow occasional logging
204
+ setTimeout(() => { unmatchedEventLogged = false; }, 60000);
205
+ }
206
+ return;
207
+ }
208
+ }
209
+
210
+ // Attach instance context to event for handlers
211
+ evt._instanceId = targetInstanceId;
212
+ evt._instanceContext = instanceContext;
213
+
11
214
  const handler = getHandler(evt.type);
12
215
  if (!handler) return; // Unknown type — ignore
13
216
  return handler(evt);
@@ -1,11 +1,20 @@
1
1
  // In-memory assignment store for JWT and relay metadata
2
2
  // Never writes to disk - memory only
3
+ // TPB-12: Per-instance assignment stores to prevent cross-wiring between tunnel instances
3
4
 
4
- let currentAssignment = null;
5
+ // Per-instance assignment storage (instanceId -> assignment)
6
+ const assignmentByInstance = new Map();
7
+
8
+ // Reverse map: leaseId -> instanceId (for routing events that only have leaseId)
9
+ const leaseToInstance = new Map();
10
+
11
+ // Legacy: requestId -> waiters (for backward compatibility during transition)
5
12
  const assignmentWaiters = new Map();
6
13
 
7
14
  /**
8
- * Set the current assignment with JWT and relay metadata
15
+ * Set assignment for a specific tunnel instance
16
+ * TPB-12: Per-instance assignment storage to prevent cross-wiring
17
+ * @param {string} instanceId - Tunnel instance ID (full MQTT clientId)
9
18
  * @param {Object} assignment - Assignment data
10
19
  * @param {string} assignment.requestId - Request ID
11
20
  * @param {string} assignment.relayId - Relay ID
@@ -14,8 +23,16 @@ const assignmentWaiters = new Map();
14
23
  * @param {number} assignment.leaseMs - Lease duration in milliseconds
15
24
  * @param {string} assignment.leaseId - Lease ID for JWT refresh (optional)
16
25
  */
17
- export function setAssignment(assignment) {
18
- currentAssignment = {
26
+ export function setAssignment(instanceId, assignment) {
27
+ // Backward compatibility: if instanceId is not provided, treat as legacy single-instance
28
+ if (typeof instanceId !== 'string' && typeof instanceId === 'object' && instanceId !== null) {
29
+ // Legacy call: setAssignment(assignment) - treat as single instance
30
+ const legacyAssignment = instanceId;
31
+ instanceId = 'legacy';
32
+ assignment = legacyAssignment;
33
+ }
34
+
35
+ const assignmentData = {
19
36
  requestId: assignment.requestId,
20
37
  relayId: assignment.relayId,
21
38
  relayUrl: assignment.relayUrl,
@@ -31,12 +48,25 @@ export function setAssignment(assignment) {
31
48
  srvProvisioned: assignment.srvProvisioned === true,
32
49
  srvFqdn: assignment.srvFqdn || null,
33
50
  warnings: assignment.warnings || [],
51
+ // UDP-S1: Store UDP-specific fields
52
+ tunnelMode: assignment.tunnelMode || null,
53
+ protocol: assignment.protocol || null,
54
+ assignmentJwt: assignment.assignmentJwt || null, // UDP-S1: Store assignmentJwt separately
34
55
  timestamp: Date.now(),
35
56
  lastRefreshMs: undefined,
36
57
  lastRefreshIso: undefined,
37
58
  lastRefreshDeltaMs: undefined
38
59
  };
39
- // Notify any waiters that are tracking this requestId
60
+
61
+ // Store per instance
62
+ assignmentByInstance.set(instanceId, assignmentData);
63
+
64
+ // Update lease -> instance mapping
65
+ if (assignment.leaseId) {
66
+ leaseToInstance.set(assignment.leaseId, instanceId);
67
+ }
68
+
69
+ // Notify any waiters that are tracking this requestId (backward compatibility)
40
70
  if (assignment.requestId && assignmentWaiters.size > 0) {
41
71
  const waiters = assignmentWaiters.get(assignment.requestId);
42
72
  if (waiters && waiters.length) {
@@ -44,7 +74,7 @@ export function setAssignment(assignment) {
44
74
  for (const waiter of waiters) {
45
75
  clearTimeout(waiter.timer);
46
76
  try {
47
- waiter.resolve({ ...currentAssignment });
77
+ waiter.resolve({ ...assignmentData });
48
78
  } catch {
49
79
  // Ignore waiter resolution errors; they should not impact CLI flow
50
80
  }
@@ -54,18 +84,56 @@ export function setAssignment(assignment) {
54
84
  }
55
85
 
56
86
  /**
57
- * Get the current assignment
58
- * @returns {Object|null} Current assignment or null if none set
87
+ * Get assignment for a specific tunnel instance
88
+ * TPB-12: Per-instance assignment retrieval
89
+ * @param {string} instanceId - Tunnel instance ID (full MQTT clientId)
90
+ * @returns {Object|null} Assignment for the instance or null if none set
59
91
  */
60
- export function getAssignment() {
61
- return currentAssignment ? { ...currentAssignment } : null;
92
+ export function getAssignment(instanceId) {
93
+ // Backward compatibility: if no instanceId provided, try to get from single instance or return null
94
+ if (!instanceId) {
95
+ // Legacy mode: if there's only one instance, return it
96
+ if (assignmentByInstance.size === 1) {
97
+ const [firstInstanceId] = assignmentByInstance.keys();
98
+ const assignment = assignmentByInstance.get(firstInstanceId);
99
+ return assignment ? { ...assignment } : null;
100
+ }
101
+ // Multiple instances or none - return null (caller must provide instanceId)
102
+ return null;
103
+ }
104
+
105
+ const assignment = assignmentByInstance.get(instanceId);
106
+ return assignment ? { ...assignment } : null;
107
+ }
108
+
109
+ /**
110
+ * Resolve instanceId from leaseId
111
+ * TPB-12: Helper to route events that only have leaseId
112
+ * @param {string} leaseId - Lease ID
113
+ * @returns {string|null} Instance ID or null if not found
114
+ */
115
+ export function resolveInstanceByLease(leaseId) {
116
+ return leaseToInstance.get(leaseId) ?? null;
62
117
  }
63
118
 
64
119
  /**
65
- * Clear the current assignment
120
+ * Clear assignment for a specific tunnel instance
121
+ * TPB-12: Per-instance assignment clearing
122
+ * @param {string} instanceId - Tunnel instance ID (full MQTT clientId)
66
123
  */
67
- export function clearAssignment() {
68
- currentAssignment = null;
124
+ export function clearAssignment(instanceId) {
125
+ if (!instanceId) {
126
+ // Legacy: clear all instances
127
+ assignmentByInstance.clear();
128
+ leaseToInstance.clear();
129
+ } else {
130
+ const assignment = assignmentByInstance.get(instanceId);
131
+ if (assignment?.leaseId) {
132
+ leaseToInstance.delete(assignment.leaseId);
133
+ }
134
+ assignmentByInstance.delete(instanceId);
135
+ }
136
+
69
137
  // Reject all outstanding waiters to avoid dangling promises
70
138
  if (assignmentWaiters.size > 0) {
71
139
  for (const [, waiters] of assignmentWaiters) {
@@ -83,11 +151,17 @@ export function clearAssignment() {
83
151
  }
84
152
 
85
153
  /**
86
- * Check if an assignment exists
87
- * @returns {boolean} True if assignment exists
154
+ * Check if an assignment exists for a specific tunnel instance
155
+ * TPB-12: Per-instance assignment check
156
+ * @param {string} instanceId - Tunnel instance ID (full MQTT clientId)
157
+ * @returns {boolean} True if assignment exists for the instance
88
158
  */
89
- export function hasAssignment() {
90
- return currentAssignment !== null;
159
+ export function hasAssignment(instanceId) {
160
+ if (!instanceId) {
161
+ // Legacy: check if any assignment exists
162
+ return assignmentByInstance.size > 0;
163
+ }
164
+ return assignmentByInstance.has(instanceId);
91
165
  }
92
166
 
93
167
  /**
@@ -101,8 +175,11 @@ export function waitForAssignment(requestId, timeoutMs = 10000) {
101
175
  return Promise.reject(new Error("waitForAssignment requires a requestId"));
102
176
  }
103
177
 
104
- if (currentAssignment && currentAssignment.requestId === requestId) {
105
- return Promise.resolve({ ...currentAssignment });
178
+ // Check all instances for matching requestId (backward compatibility)
179
+ for (const [instanceId, assignment] of assignmentByInstance) {
180
+ if (assignment.requestId === requestId) {
181
+ return Promise.resolve({ ...assignment });
182
+ }
106
183
  }
107
184
 
108
185
  return new Promise((resolve, reject) => {
@@ -132,34 +209,61 @@ export function waitForAssignment(requestId, timeoutMs = 10000) {
132
209
 
133
210
  /**
134
211
  * Get assignment metadata (without JWT for logging)
212
+ * TPB-12: Per-instance metadata retrieval
213
+ * @param {string} instanceId - Tunnel instance ID (full MQTT clientId)
135
214
  * @returns {Object|null} Assignment metadata or null
136
215
  */
137
- export function getAssignmentMetadata() {
138
- if (!currentAssignment) return null;
216
+ export function getAssignmentMetadata(instanceId) {
217
+ const assignment = getAssignment(instanceId);
218
+ if (!assignment) return null;
139
219
 
140
220
  return {
141
- requestId: currentAssignment.requestId,
142
- relayId: currentAssignment.relayId,
143
- relayUrl: currentAssignment.relayUrl,
144
- leaseMs: currentAssignment.leaseMs,
145
- leaseId: currentAssignment.leaseId,
146
- timestamp: currentAssignment.timestamp,
147
- lastRefreshIso: currentAssignment.lastRefreshIso,
148
- lastRefreshDeltaMs: currentAssignment.lastRefreshDeltaMs
221
+ requestId: assignment.requestId,
222
+ relayId: assignment.relayId,
223
+ relayUrl: assignment.relayUrl,
224
+ leaseMs: assignment.leaseMs,
225
+ leaseId: assignment.leaseId,
226
+ timestamp: assignment.timestamp,
227
+ lastRefreshIso: assignment.lastRefreshIso,
228
+ lastRefreshDeltaMs: assignment.lastRefreshDeltaMs
149
229
  };
150
230
  }
151
231
 
152
232
  /**
153
233
  * Record a successful refresh in the assignment cache and return delta ms since last refresh (or since initial assignment if none).
234
+ * TPB-12: Per-instance refresh recording
235
+ * @param {string} instanceId - Tunnel instance ID (full MQTT clientId)
154
236
  * @param {number} [nowMs]
155
237
  * @returns {number} delta milliseconds since last refresh or initial assignment
156
238
  */
157
- export function recordRefresh(nowMs = Date.now()) {
158
- if (!currentAssignment) return 0;
159
- const prev = typeof currentAssignment.lastRefreshMs === 'number' ? currentAssignment.lastRefreshMs : currentAssignment.timestamp;
239
+ export function recordRefresh(instanceId, nowMs = Date.now()) {
240
+ // Backward compatibility: if instanceId is a number, treat as legacy
241
+ if (typeof instanceId === 'number') {
242
+ nowMs = instanceId;
243
+ instanceId = null;
244
+ }
245
+
246
+ const assignment = getAssignment(instanceId);
247
+ if (!assignment) return 0;
248
+
249
+ const prev = typeof assignment.lastRefreshMs === 'number' ? assignment.lastRefreshMs : assignment.timestamp;
160
250
  const delta = nowMs - prev;
161
- currentAssignment.lastRefreshMs = nowMs;
162
- currentAssignment.lastRefreshIso = new Date(nowMs).toISOString();
163
- currentAssignment.lastRefreshDeltaMs = delta;
251
+
252
+ // Update the assignment in the map
253
+ assignment.lastRefreshMs = nowMs;
254
+ assignment.lastRefreshIso = new Date(nowMs).toISOString();
255
+ assignment.lastRefreshDeltaMs = delta;
256
+
257
+ // Update the map entry
258
+ if (instanceId) {
259
+ assignmentByInstance.set(instanceId, assignment);
260
+ } else {
261
+ // Legacy: update first instance found
262
+ const [firstInstanceId] = assignmentByInstance.keys();
263
+ if (firstInstanceId) {
264
+ assignmentByInstance.set(firstInstanceId, assignment);
265
+ }
266
+ }
267
+
164
268
  return delta;
165
269
  }
@@ -0,0 +1,130 @@
1
+ // TPB-12: Instance Registry for per-tunnel routing
2
+ // Tracks tunnel instances and their context (setAssignment callback, tunnel type, etc.)
3
+
4
+ /**
5
+ * Instance context for a tunnel instance
6
+ * @typedef {Object} InstanceContext
7
+ * @property {string} instanceId - Full MQTT clientId (instanceId)
8
+ * @property {string} tunnelType - Tunnel type ('http' | 'tcp' | 'udp')
9
+ * @property {Function} setAssignment - Per-instance setAssignment callback
10
+ * @property {Function} getAssignment - Per-instance getAssignment callback
11
+ * @property {Object} [metadata] - Additional metadata (baseClientId, etc.)
12
+ * @property {string} [expectedRequestId] - Expected requestId for initial open_ack routing
13
+ */
14
+
15
+ // Global instance registry: instanceId -> InstanceContext
16
+ const instanceRegistry = new Map();
17
+
18
+ // TPB-12: Track expected requestIds per instance for pre-assignment routing
19
+ // requestId -> instanceId (for routing open_ack before assignment exists)
20
+ const requestIdToInstance = new Map();
21
+
22
+ /**
23
+ * Register a tunnel instance
24
+ * @param {string} instanceId - Full MQTT clientId (instanceId)
25
+ * @param {Object} context - Instance context
26
+ * @param {string} context.tunnelType - Tunnel type ('http' | 'tcp' | 'udp')
27
+ * @param {Function} context.setAssignment - Per-instance setAssignment callback
28
+ * @param {Function} context.getAssignment - Per-instance getAssignment callback
29
+ * @param {Object} [context.metadata] - Additional metadata
30
+ */
31
+ export function registerInstance(instanceId, context) {
32
+ if (!instanceId || typeof instanceId !== 'string') {
33
+ throw new Error('instanceId must be a non-empty string');
34
+ }
35
+
36
+ instanceRegistry.set(instanceId, {
37
+ instanceId,
38
+ tunnelType: context.tunnelType || 'unknown',
39
+ setAssignment: context.setAssignment,
40
+ getAssignment: context.getAssignment,
41
+ metadata: context.metadata || {}
42
+ });
43
+ }
44
+
45
+ /**
46
+ * Unregister a tunnel instance
47
+ * @param {string} instanceId - Full MQTT clientId (instanceId)
48
+ */
49
+ export function unregisterInstance(instanceId) {
50
+ const context = instanceRegistry.get(instanceId);
51
+ if (context?.expectedRequestId) {
52
+ requestIdToInstance.delete(context.expectedRequestId);
53
+ }
54
+ instanceRegistry.delete(instanceId);
55
+ }
56
+
57
+ /**
58
+ * Get instance context by instanceId
59
+ * @param {string} instanceId - Full MQTT clientId (instanceId)
60
+ * @returns {InstanceContext|null} Instance context or null if not found
61
+ */
62
+ export function getInstance(instanceId) {
63
+ return instanceRegistry.get(instanceId) ?? null;
64
+ }
65
+
66
+ /**
67
+ * Get all registered instances (for debugging)
68
+ * @returns {Array<InstanceContext>} Array of all instance contexts
69
+ */
70
+ export function getAllInstances() {
71
+ return Array.from(instanceRegistry.values());
72
+ }
73
+
74
+ /**
75
+ * Set expected requestId for an instance (for pre-assignment routing)
76
+ * TPB-12: Track requestId before assignment exists so open_ack can be routed
77
+ *
78
+ * Note: This automatically clears any previous requestId for this instance,
79
+ * so reconnect/retry flows that use a new requestId are handled correctly.
80
+ *
81
+ * @param {string} instanceId - Full MQTT clientId (instanceId)
82
+ * @param {string} requestId - Expected requestId from cmd/open
83
+ */
84
+ export function setExpectedRequestId(instanceId, requestId) {
85
+ const context = instanceRegistry.get(instanceId);
86
+ if (!context) {
87
+ throw new Error(`Instance ${instanceId} not found in registry`);
88
+ }
89
+
90
+ // Remove old requestId mapping if exists (handles reconnect/retry with new requestId)
91
+ if (context.expectedRequestId) {
92
+ requestIdToInstance.delete(context.expectedRequestId);
93
+ }
94
+
95
+ // Set new requestId
96
+ context.expectedRequestId = requestId;
97
+ requestIdToInstance.set(requestId, instanceId);
98
+ }
99
+
100
+ /**
101
+ * Clear expected requestId for an instance (called after assignment is created)
102
+ * TPB-12: Clean up requestId mapping once assignment exists (routing uses leaseId after that)
103
+ * @param {string} instanceId - Full MQTT clientId (instanceId)
104
+ */
105
+ export function clearExpectedRequestId(instanceId) {
106
+ const context = instanceRegistry.get(instanceId);
107
+ if (context?.expectedRequestId) {
108
+ requestIdToInstance.delete(context.expectedRequestId);
109
+ context.expectedRequestId = undefined;
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Resolve instanceId from requestId (for pre-assignment routing)
115
+ * TPB-12: Route open_ack events by requestId before assignment exists
116
+ * @param {string} requestId - Request ID from cmd/open
117
+ * @returns {string|null} Instance ID or null if not found
118
+ */
119
+ export function resolveInstanceByRequestId(requestId) {
120
+ return requestIdToInstance.get(requestId) ?? null;
121
+ }
122
+
123
+ /**
124
+ * Clear all instances (for cleanup/testing)
125
+ */
126
+ export function clearAll() {
127
+ instanceRegistry.clear();
128
+ requestIdToInstance.clear();
129
+ }
130
+
@@ -23,7 +23,9 @@ export class HttpTunnel {
23
23
  getForceReconnect = () => null, // QPA-CLI-03: Get force reconnect function
24
24
  controlPlaneTimeoutMs = 60000,
25
25
  // QPA-04: QuickPass security group slug
26
- secGroupSlug = null
26
+ secGroupSlug = null,
27
+ // TPB-12: Instance ID for per-instance assignment routing
28
+ instanceId = null
27
29
  }) {
28
30
  this.relayUrl = relayUrl;
29
31
  this.jwt = jwt; // Accept JWT as-is (no validation)
@@ -34,6 +36,8 @@ export class HttpTunnel {
34
36
  this.ws = null;
35
37
  // QPA-04: Store secGroupSlug for use in refresh payloads
36
38
  this.secGroupSlug = secGroupSlug;
39
+ // TPB-12: Store instanceId for per-instance assignment lookups
40
+ this.instanceId = instanceId;
37
41
 
38
42
  // CLI-IMG-WSReconnect: Coordinator connection for JWT refresh
39
43
  this.coordinatorCore = coordinatorCore;
@@ -223,10 +227,11 @@ export class HttpTunnel {
223
227
  }
224
228
 
225
229
  const { getAssignment } = await import('../state/assignment.js');
226
- const assignment = getAssignment();
230
+ // TPB-12: Use instanceId for per-instance assignment lookup
231
+ const assignment = getAssignment(this.instanceId);
227
232
 
228
233
  if (!assignment || !assignment.leaseId) {
229
- this.log.warn('jwt.reauth.error', { code: 'no_assignment' });
234
+ this.log.warn('jwt.reauth.error', { code: 'no_assignment', instanceId: this.instanceId });
230
235
  return false;
231
236
  }
232
237
 
@@ -767,10 +772,10 @@ export class HttpTunnel {
767
772
  const { getAssignment } = await import('../state/assignment.js');
768
773
  const { getFpHash } = await import('../lib/fingerprint.js');
769
774
 
770
- // Get current assignment to reuse lease
771
- const currentAssignment = getAssignment();
775
+ // TPB-12: Get current assignment for this specific instance
776
+ const currentAssignment = getAssignment(this.instanceId);
772
777
  if (!currentAssignment) {
773
- this.log.error('jwt.refresh.no_current_assignment');
778
+ this.log.error('jwt.refresh.no_current_assignment', { instanceId: this.instanceId });
774
779
  process.exit(1);
775
780
  }
776
781
 
@@ -846,10 +851,10 @@ export class HttpTunnel {
846
851
  return;
847
852
  }
848
853
 
849
- // Get the new assignment
850
- const newAssignment = getAssignment();
854
+ // TPB-12: Get the new assignment for this specific instance
855
+ const newAssignment = getAssignment(this.instanceId);
851
856
  if (!newAssignment) {
852
- this.log.error('jwt.refresh.no_new_assignment');
857
+ this.log.error('jwt.refresh.no_new_assignment', { instanceId: this.instanceId });
853
858
  process.exit(1);
854
859
  }
855
860
 
@@ -938,12 +943,12 @@ export class HttpTunnel {
938
943
  async _fallbackToFreshTunnel() {
939
944
  this.refreshState = 'fallback';
940
945
 
941
- // Get current assignment to extract leaseId for reuse
946
+ // TPB-12: Get current assignment for this specific instance
942
947
  const { getAssignment } = await import('../state/assignment.js');
943
- const currentAssignment = getAssignment();
948
+ const currentAssignment = getAssignment(this.instanceId);
944
949
 
945
950
  if (!currentAssignment) {
946
- this.log.error('jwt.refresh.fallback.no_assignment', { error: 'no_current_assignment' });
951
+ this.log.error('jwt.refresh.fallback.no_assignment', { error: 'no_current_assignment', instanceId: this.instanceId });
947
952
  process.exit(1);
948
953
  }
949
954
 
@@ -1069,11 +1074,11 @@ export class HttpTunnel {
1069
1074
  continue;
1070
1075
  }
1071
1076
 
1072
- // Get the new assignment (with refreshed JWT but same leaseId)
1073
- const newAssignment = getAssignment();
1077
+ // TPB-12: Get the new assignment for this specific instance
1078
+ const newAssignment = getAssignment(this.instanceId);
1074
1079
  if (!newAssignment) {
1075
1080
  retryCount++;
1076
- this.log.warn('jwt.refresh.fallback.no_new_assignment', { retryCount, leaseId });
1081
+ this.log.warn('jwt.refresh.fallback.no_new_assignment', { retryCount, leaseId, instanceId: this.instanceId });
1077
1082
  if (retryCount >= maxFallbackRetries) {
1078
1083
  this.log.error('jwt.refresh.fallback.failure', {
1079
1084
  error: 'no_assignment_after_ack',