@openrobops/iso21423 0.0.0-stage → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +358 -2
- package/dist/ccs-CU8XD5sl.d.cts +69 -0
- package/dist/ccs-CU8XD5sl.d.ts +69 -0
- package/dist/chunk-3JNSIJSX.js +31 -0
- package/dist/chunk-3JNSIJSX.js.map +1 -0
- package/dist/chunk-5ZIUSUHF.js +55 -0
- package/dist/chunk-5ZIUSUHF.js.map +1 -0
- package/dist/chunk-DMJ6T3RX.js +445 -0
- package/dist/chunk-DMJ6T3RX.js.map +1 -0
- package/dist/chunk-GPNR37CI.js +1915 -0
- package/dist/chunk-GPNR37CI.js.map +1 -0
- package/dist/chunk-JDO725KR.js +210 -0
- package/dist/chunk-JDO725KR.js.map +1 -0
- package/dist/chunk-JIYCTQXR.js +1 -0
- package/dist/chunk-JIYCTQXR.js.map +1 -0
- package/dist/chunk-JLUENXGS.js +48 -0
- package/dist/chunk-JLUENXGS.js.map +1 -0
- package/dist/chunk-JQAMNFAF.js +1 -0
- package/dist/chunk-JQAMNFAF.js.map +1 -0
- package/dist/chunk-LTPOAVGF.js +44 -0
- package/dist/chunk-LTPOAVGF.js.map +1 -0
- package/dist/chunk-ODBIFZN3.js +65 -0
- package/dist/chunk-ODBIFZN3.js.map +1 -0
- package/dist/chunk-OH2DOPKJ.js +107 -0
- package/dist/chunk-OH2DOPKJ.js.map +1 -0
- package/dist/chunk-QAA44UNO.js +1 -0
- package/dist/chunk-QAA44UNO.js.map +1 -0
- package/dist/chunk-RD7PYTIT.js +107 -0
- package/dist/chunk-RD7PYTIT.js.map +1 -0
- package/dist/chunk-UJC46NTA.js +13 -0
- package/dist/chunk-UJC46NTA.js.map +1 -0
- package/dist/chunk-UW6WTEPT.js +293 -0
- package/dist/chunk-UW6WTEPT.js.map +1 -0
- package/dist/chunk-W7DIDPTG.js +1 -0
- package/dist/chunk-W7DIDPTG.js.map +1 -0
- package/dist/core.cjs +2874 -0
- package/dist/core.cjs.map +1 -0
- package/dist/core.d.cts +996 -0
- package/dist/core.d.ts +996 -0
- package/dist/core.js +59 -0
- package/dist/core.js.map +1 -0
- package/dist/gateway.cjs +2937 -0
- package/dist/gateway.cjs.map +1 -0
- package/dist/gateway.d.cts +165 -0
- package/dist/gateway.d.ts +165 -0
- package/dist/gateway.js +21 -0
- package/dist/gateway.js.map +1 -0
- package/dist/geometry.cjs +98 -0
- package/dist/geometry.cjs.map +1 -0
- package/dist/geometry.d.cts +38 -0
- package/dist/geometry.d.ts +38 -0
- package/dist/geometry.js +14 -0
- package/dist/geometry.js.map +1 -0
- package/dist/identity-BGr2FJmC.d.cts +258 -0
- package/dist/identity-Bw8Dik5S.d.ts +258 -0
- package/dist/index.cjs +3327 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +118 -0
- package/dist/index.d.ts +118 -0
- package/dist/index.js +193 -0
- package/dist/index.js.map +1 -0
- package/dist/schema.cjs +375 -0
- package/dist/schema.cjs.map +1 -0
- package/dist/schema.d.cts +28 -0
- package/dist/schema.d.ts +28 -0
- package/dist/schema.js +14 -0
- package/dist/schema.js.map +1 -0
- package/dist/session-RV32MFpV.d.cts +139 -0
- package/dist/session-ueiESY7Y.d.ts +139 -0
- package/dist/session.cjs +855 -0
- package/dist/session.cjs.map +1 -0
- package/dist/session.d.cts +94 -0
- package/dist/session.d.ts +94 -0
- package/dist/session.js +20 -0
- package/dist/session.js.map +1 -0
- package/dist/testing.cjs +205 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +94 -0
- package/dist/testing.d.ts +94 -0
- package/dist/testing.js +169 -0
- package/dist/testing.js.map +1 -0
- package/dist/topics-BiVeZyTW.d.cts +43 -0
- package/dist/topics-BiVeZyTW.d.ts +43 -0
- package/dist/topics.cjs +134 -0
- package/dist/topics.cjs.map +1 -0
- package/dist/topics.d.cts +41 -0
- package/dist/topics.d.ts +41 -0
- package/dist/topics.js +30 -0
- package/dist/topics.js.map +1 -0
- package/dist/transport-BT4AjTn9.d.cts +61 -0
- package/dist/transport-BT4AjTn9.d.ts +61 -0
- package/dist/types.cjs +186 -0
- package/dist/types.cjs.map +1 -0
- package/dist/types.d.cts +83 -0
- package/dist/types.d.ts +83 -0
- package/dist/types.js +50 -0
- package/dist/types.js.map +1 -0
- package/dist/validators-Be0ce1b8.d.cts +29 -0
- package/dist/validators-Be0ce1b8.d.ts +29 -0
- package/package.json +48 -4
package/dist/gateway.cjs
ADDED
|
@@ -0,0 +1,2937 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/gateway/index.ts
|
|
31
|
+
var gateway_exports = {};
|
|
32
|
+
__export(gateway_exports, {
|
|
33
|
+
FleetGateway: () => FleetGateway,
|
|
34
|
+
RetainedRequestJanitor: () => RetainedRequestJanitor,
|
|
35
|
+
publishSelfCheck: () => publishSelfCheck
|
|
36
|
+
});
|
|
37
|
+
module.exports = __toCommonJS(gateway_exports);
|
|
38
|
+
|
|
39
|
+
// src/errors.ts
|
|
40
|
+
var Iso21423Error = class extends Error {
|
|
41
|
+
constructor(message) {
|
|
42
|
+
super(message);
|
|
43
|
+
this.name = new.target.name;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
var ValidationError = class extends Iso21423Error {
|
|
47
|
+
constructor(message, errors) {
|
|
48
|
+
super(message);
|
|
49
|
+
this.errors = errors;
|
|
50
|
+
}
|
|
51
|
+
errors;
|
|
52
|
+
};
|
|
53
|
+
var RequestFailed = class extends Iso21423Error {
|
|
54
|
+
constructor(message, finalStatus) {
|
|
55
|
+
super(message);
|
|
56
|
+
this.finalStatus = finalStatus;
|
|
57
|
+
}
|
|
58
|
+
finalStatus;
|
|
59
|
+
};
|
|
60
|
+
var RequestTimeout = class extends Iso21423Error {
|
|
61
|
+
};
|
|
62
|
+
var BrokerUnavailable = class extends Iso21423Error {
|
|
63
|
+
};
|
|
64
|
+
var AuthorizationDenied = class extends Iso21423Error {
|
|
65
|
+
constructor(message, topic) {
|
|
66
|
+
super(message);
|
|
67
|
+
this.topic = topic;
|
|
68
|
+
}
|
|
69
|
+
topic;
|
|
70
|
+
};
|
|
71
|
+
var NotCapableError = class extends Iso21423Error {
|
|
72
|
+
};
|
|
73
|
+
var IllegalTransition = class extends Iso21423Error {
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
// src/core/client.ts
|
|
77
|
+
var import_node_crypto2 = require("crypto");
|
|
78
|
+
|
|
79
|
+
// src/session/mqttTransport.ts
|
|
80
|
+
var MqttAdapter = class {
|
|
81
|
+
constructor(acquire, checkWill, ownsClient) {
|
|
82
|
+
this.acquire = acquire;
|
|
83
|
+
this.checkWill = checkWill;
|
|
84
|
+
this.ownsClient = ownsClient;
|
|
85
|
+
}
|
|
86
|
+
acquire;
|
|
87
|
+
checkWill;
|
|
88
|
+
ownsClient;
|
|
89
|
+
client;
|
|
90
|
+
ended = false;
|
|
91
|
+
wired = false;
|
|
92
|
+
messageCbs = [];
|
|
93
|
+
stateCbs = [];
|
|
94
|
+
/**
|
|
95
|
+
* Acquires the underlying mqtt client (via the constructor-supplied `acquire`) and wires
|
|
96
|
+
* message/connection-state listeners exactly once per adapter instance, so repeated `connect()`
|
|
97
|
+
* calls (e.g. reconnect flows) don't accumulate duplicate listeners. For a caller-constructed
|
|
98
|
+
* client whose will doesn't match `opts.will`, throws (P-4) rather than silently diverging.
|
|
99
|
+
*/
|
|
100
|
+
async connect(opts) {
|
|
101
|
+
const client = await this.acquire(opts);
|
|
102
|
+
if (this.checkWill && opts.will && client.options?.will?.topic !== opts.will.topic) {
|
|
103
|
+
throw new Iso21423Error(
|
|
104
|
+
`caller-constructed mqtt client must be created with will { topic: "${opts.will.topic}", payload: '${opts.will.payload}', qos: ${opts.will.qos}, retain: ${opts.will.retain} } (P-4)`
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
if (!this.wired) {
|
|
108
|
+
this.wired = true;
|
|
109
|
+
client.on("message", ((topic, payload, packet) => {
|
|
110
|
+
const msg = {
|
|
111
|
+
topic,
|
|
112
|
+
payload,
|
|
113
|
+
qos: packet?.qos ?? 0,
|
|
114
|
+
retain: packet?.retain ?? false
|
|
115
|
+
};
|
|
116
|
+
for (const cb of this.messageCbs) cb(msg);
|
|
117
|
+
}));
|
|
118
|
+
client.on("reconnect", (() => this.emitState("reconnecting")));
|
|
119
|
+
client.on("offline", (() => this.emitState("offline")));
|
|
120
|
+
client.on("close", (() => this.emitState("closed")));
|
|
121
|
+
client.on("connect", (() => this.emitState("connected")));
|
|
122
|
+
}
|
|
123
|
+
if (client.connected) {
|
|
124
|
+
this.client = client;
|
|
125
|
+
this.emitState("connected");
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
let settled = false;
|
|
129
|
+
const resolveReject = { resolve: null, reject: null };
|
|
130
|
+
const onConnect = (() => {
|
|
131
|
+
if (settled) return;
|
|
132
|
+
settled = true;
|
|
133
|
+
this.client = client;
|
|
134
|
+
resolveReject.resolve();
|
|
135
|
+
});
|
|
136
|
+
const onError = ((err) => {
|
|
137
|
+
if (settled) return;
|
|
138
|
+
settled = true;
|
|
139
|
+
if (this.ownsClient) {
|
|
140
|
+
client.endAsync(true).catch(() => {
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
resolveReject.reject(new BrokerUnavailable(`mqtt connect failed: ${err.message}`));
|
|
144
|
+
});
|
|
145
|
+
try {
|
|
146
|
+
await new Promise((resolve, reject) => {
|
|
147
|
+
resolveReject.resolve = resolve;
|
|
148
|
+
resolveReject.reject = reject;
|
|
149
|
+
client.on("connect", onConnect);
|
|
150
|
+
client.on("error", onError);
|
|
151
|
+
});
|
|
152
|
+
} finally {
|
|
153
|
+
try {
|
|
154
|
+
const clientWithRemoval = client;
|
|
155
|
+
(clientWithRemoval.off ?? clientWithRemoval.removeListener)?.("connect", onConnect);
|
|
156
|
+
(clientWithRemoval.off ?? clientWithRemoval.removeListener)?.("error", onError);
|
|
157
|
+
} catch {
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
async publish(topic, payload, opts) {
|
|
162
|
+
await this.live().publishAsync(topic, payload, opts);
|
|
163
|
+
}
|
|
164
|
+
/** Subscribes and reports whether the broker granted it — false if any SUBACK return code was a refusal (>= 0x80, ND-15) or no grants came back. */
|
|
165
|
+
async subscribe(filter, opts) {
|
|
166
|
+
const grants = await this.live().subscribeAsync(filter, opts);
|
|
167
|
+
const granted = grants.length > 0 && grants.every((g) => g.qos < 128);
|
|
168
|
+
return { granted };
|
|
169
|
+
}
|
|
170
|
+
async unsubscribe(filter) {
|
|
171
|
+
await this.live().unsubscribeAsync(filter);
|
|
172
|
+
}
|
|
173
|
+
onMessage(cb) {
|
|
174
|
+
this.messageCbs.push(cb);
|
|
175
|
+
}
|
|
176
|
+
onConnectionState(cb) {
|
|
177
|
+
this.stateCbs.push(cb);
|
|
178
|
+
}
|
|
179
|
+
async end() {
|
|
180
|
+
this.ended = true;
|
|
181
|
+
if (this.client) await this.client.endAsync();
|
|
182
|
+
this.emitState("closed");
|
|
183
|
+
}
|
|
184
|
+
/** Returns the connected client or throws {@link BrokerUnavailable} if `end()` was called or `connect()` hasn't completed. */
|
|
185
|
+
live() {
|
|
186
|
+
if (this.ended || !this.client) throw new BrokerUnavailable("mqtt transport is not connected");
|
|
187
|
+
return this.client;
|
|
188
|
+
}
|
|
189
|
+
emitState(s) {
|
|
190
|
+
for (const cb of this.stateCbs) cb(s);
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
function createMqttTransport(url, opts = {}) {
|
|
194
|
+
return new MqttAdapter(async (connectOpts) => {
|
|
195
|
+
let mod;
|
|
196
|
+
try {
|
|
197
|
+
mod = await import("mqtt");
|
|
198
|
+
} catch (err) {
|
|
199
|
+
throw new BrokerUnavailable(
|
|
200
|
+
`the "mqtt" peer dependency is not installed: ${err.message}`
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
return mod.connect(url, {
|
|
204
|
+
...opts.tls,
|
|
205
|
+
clientId: connectOpts.clientId,
|
|
206
|
+
clean: connectOpts.cleanSession,
|
|
207
|
+
keepalive: connectOpts.keepalive,
|
|
208
|
+
username: connectOpts.username ?? opts.username,
|
|
209
|
+
password: connectOpts.password ?? opts.password,
|
|
210
|
+
reconnectPeriod: opts.reconnectPeriod,
|
|
211
|
+
will: connectOpts.will
|
|
212
|
+
});
|
|
213
|
+
}, false, true);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// src/session/rateGate.ts
|
|
217
|
+
var RateGate = class {
|
|
218
|
+
intervalMs;
|
|
219
|
+
lastEmit = -Infinity;
|
|
220
|
+
pending;
|
|
221
|
+
timer;
|
|
222
|
+
constructor(maxHz) {
|
|
223
|
+
if (!(maxHz > 0) || !Number.isFinite(maxHz)) {
|
|
224
|
+
throw new Iso21423Error(`RateGate requires a finite maxHz > 0, got ${maxHz}`);
|
|
225
|
+
}
|
|
226
|
+
this.intervalMs = 1e3 / maxHz;
|
|
227
|
+
}
|
|
228
|
+
/** Offers a value for emission; emits now if the interval has elapsed, else schedules a trailing emit and discards any previously-pending value. */
|
|
229
|
+
offer(value, emit) {
|
|
230
|
+
const now = Date.now();
|
|
231
|
+
if (now - this.lastEmit >= this.intervalMs) {
|
|
232
|
+
this.lastEmit = now;
|
|
233
|
+
emit(value);
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
this.pending = { value, emit };
|
|
237
|
+
if (this.timer === void 0) {
|
|
238
|
+
const wait = this.intervalMs - (now - this.lastEmit);
|
|
239
|
+
this.timer = setTimeout(() => {
|
|
240
|
+
this.timer = void 0;
|
|
241
|
+
const p = this.pending;
|
|
242
|
+
this.pending = void 0;
|
|
243
|
+
if (p) {
|
|
244
|
+
this.lastEmit = Date.now();
|
|
245
|
+
p.emit(p.value);
|
|
246
|
+
}
|
|
247
|
+
}, wait);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
/** Cancels any pending trailing emit. The pending value is dropped, not flushed. */
|
|
251
|
+
dispose() {
|
|
252
|
+
if (this.timer !== void 0) clearTimeout(this.timer);
|
|
253
|
+
this.timer = void 0;
|
|
254
|
+
this.pending = void 0;
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
// src/topics/resources.ts
|
|
259
|
+
var RESOURCE_CONFIG = {
|
|
260
|
+
identity: { qos: 1, retain: true },
|
|
261
|
+
status: { qos: 1, retain: true },
|
|
262
|
+
batteryStatus: { qos: 0, retain: true },
|
|
263
|
+
footprint: { qos: 1, retain: true },
|
|
264
|
+
odometry: { qos: 0, retain: false, minHz: 0.5, maxHz: 30 },
|
|
265
|
+
localTrajectory: { qos: 0, retain: false, minHz: 1, maxHz: 10 },
|
|
266
|
+
globalPath: { qos: 1, retain: true },
|
|
267
|
+
globalPlan: { qos: 1, retain: true },
|
|
268
|
+
request: { qos: 2, retain: true },
|
|
269
|
+
requestStatus: { qos: 2, retain: true },
|
|
270
|
+
activeRequestsStatus: { qos: 1, retain: true },
|
|
271
|
+
disconnection: { qos: 1, retain: true }
|
|
272
|
+
// B.4 LWT parameters
|
|
273
|
+
};
|
|
274
|
+
var STANDARD_RESOURCES = new Set(Object.keys(RESOURCE_CONFIG));
|
|
275
|
+
|
|
276
|
+
// src/types/constants.ts
|
|
277
|
+
var ROOT_NAMESPACE = "/ISO_21423/v1";
|
|
278
|
+
var PROTOCOL_VERSION = "1.0";
|
|
279
|
+
var KNOWN_OPERATING_STATES = [
|
|
280
|
+
"STOP_CATEGORY_0",
|
|
281
|
+
"STOP_CATEGORY_1",
|
|
282
|
+
"STOP_CATEGORY_2",
|
|
283
|
+
"PAUSED",
|
|
284
|
+
"WAIT_FOR_RESET",
|
|
285
|
+
"MAPPING",
|
|
286
|
+
"LOST",
|
|
287
|
+
"WAIT_FOR_ATTACHMENT",
|
|
288
|
+
"WAIT_FOR_EVENT",
|
|
289
|
+
"BLOCKED",
|
|
290
|
+
"ATTACHMENT_ACTIVE",
|
|
291
|
+
"STOPPED",
|
|
292
|
+
"DOCKING",
|
|
293
|
+
"SLOWING",
|
|
294
|
+
"ACCELERATING",
|
|
295
|
+
"LEFT_TURN",
|
|
296
|
+
"RIGHT_TURN",
|
|
297
|
+
"REVERSE",
|
|
298
|
+
"FORWARD",
|
|
299
|
+
"LINE_FOLLOWING",
|
|
300
|
+
"CHARGING",
|
|
301
|
+
"LOW_BATTERY",
|
|
302
|
+
"IDLE",
|
|
303
|
+
"PARKED",
|
|
304
|
+
"OFFLINE",
|
|
305
|
+
"READY",
|
|
306
|
+
"NOT_READY",
|
|
307
|
+
"MODE_AUTO",
|
|
308
|
+
"MODE_SEMIAUTO",
|
|
309
|
+
"MODE_TELEOP",
|
|
310
|
+
"MODE_MANUAL",
|
|
311
|
+
"MODE_MAINTENANCE"
|
|
312
|
+
];
|
|
313
|
+
var LOST_CONNECTION_STATE = "LOST_CONNECTION";
|
|
314
|
+
|
|
315
|
+
// src/topics/topics.ts
|
|
316
|
+
function topicFor(ref, resource) {
|
|
317
|
+
return `${ROOT_NAMESPACE}/${ref.entityType}/${ref.entityUuid}/${resource}`;
|
|
318
|
+
}
|
|
319
|
+
function requestTopic(ref, requestUuid) {
|
|
320
|
+
return `${topicFor(ref, "request")}/${requestUuid}`;
|
|
321
|
+
}
|
|
322
|
+
function requestStatusTopic(ref, requestUuid) {
|
|
323
|
+
return `${requestTopic(ref, requestUuid)}/status`;
|
|
324
|
+
}
|
|
325
|
+
function disconnectionTopic(ref) {
|
|
326
|
+
return topicFor(ref, "disconnection");
|
|
327
|
+
}
|
|
328
|
+
function parseTopic(topic) {
|
|
329
|
+
if (!topic.startsWith(`${ROOT_NAMESPACE}/`)) return null;
|
|
330
|
+
const rest = topic.slice(ROOT_NAMESPACE.length + 1).split("/");
|
|
331
|
+
const [entityType, entityUuid, resource, ...tail] = rest;
|
|
332
|
+
if (!entityType || !entityUuid || !resource) return null;
|
|
333
|
+
if (resource === "request" && tail.length >= 1) {
|
|
334
|
+
const [requestUuid, maybeStatus] = tail;
|
|
335
|
+
if (!requestUuid || maybeStatus !== void 0 && maybeStatus !== "status" || tail.length > 2) return null;
|
|
336
|
+
return { entityType, entityUuid, resource, requestUuid, isRequestStatus: maybeStatus === "status" };
|
|
337
|
+
}
|
|
338
|
+
if (tail.length > 0) return null;
|
|
339
|
+
return { entityType, entityUuid, resource, isRequestStatus: false };
|
|
340
|
+
}
|
|
341
|
+
function topicFilterMatches(filter, topic) {
|
|
342
|
+
const f = filter.split("/");
|
|
343
|
+
const t = topic.split("/");
|
|
344
|
+
for (let i = 0; i < f.length; i++) {
|
|
345
|
+
const seg = f[i];
|
|
346
|
+
if (seg === "#") return true;
|
|
347
|
+
if (i >= t.length) return false;
|
|
348
|
+
if (seg !== "+" && seg !== t[i]) return false;
|
|
349
|
+
}
|
|
350
|
+
return f.length === t.length;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// src/types/common.ts
|
|
354
|
+
function nowTimestamp(date = /* @__PURE__ */ new Date()) {
|
|
355
|
+
return date.toISOString();
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// src/schema/validators.ts
|
|
359
|
+
var import__ = require("ajv/dist/2020.js");
|
|
360
|
+
var import_ajv_formats = __toESM(require("ajv-formats"), 1);
|
|
361
|
+
|
|
362
|
+
// src/schema/iso21423.schema.json
|
|
363
|
+
var iso21423_schema_default = {
|
|
364
|
+
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
365
|
+
$id: "https://openrobops.org/schemas/iso21423/v1.json",
|
|
366
|
+
$defs: {
|
|
367
|
+
uuid: { type: "string", pattern: "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$" },
|
|
368
|
+
timestamp: { type: "string", format: "date-time" },
|
|
369
|
+
point: {
|
|
370
|
+
type: "object",
|
|
371
|
+
required: ["x", "y"],
|
|
372
|
+
properties: { x: { type: "number" }, y: { type: "number" } }
|
|
373
|
+
},
|
|
374
|
+
locationPoint: {
|
|
375
|
+
type: "object",
|
|
376
|
+
required: ["ccsId", "x", "y", "z"],
|
|
377
|
+
properties: {
|
|
378
|
+
ccsId: { $ref: "#/$defs/uuid" },
|
|
379
|
+
x: { type: "number" },
|
|
380
|
+
y: { type: "number" },
|
|
381
|
+
z: { type: "number" }
|
|
382
|
+
}
|
|
383
|
+
},
|
|
384
|
+
orientation: {
|
|
385
|
+
type: "object",
|
|
386
|
+
required: ["yaw", "pitch", "roll"],
|
|
387
|
+
properties: { yaw: { type: "number" }, pitch: { type: "number" }, roll: { type: "number" } }
|
|
388
|
+
},
|
|
389
|
+
capabilities: {
|
|
390
|
+
type: "object",
|
|
391
|
+
required: ["provides", "accepts"],
|
|
392
|
+
properties: {
|
|
393
|
+
provides: { type: "array", items: { type: "string" } },
|
|
394
|
+
accepts: {
|
|
395
|
+
type: "object",
|
|
396
|
+
required: ["requests"],
|
|
397
|
+
properties: { requests: { type: "array", items: { type: "string" } } }
|
|
398
|
+
},
|
|
399
|
+
manages: { type: "array", items: { $ref: "#/$defs/uuid" } },
|
|
400
|
+
managedBy: { $ref: "#/$defs/uuid" }
|
|
401
|
+
}
|
|
402
|
+
},
|
|
403
|
+
softwareVersion: {
|
|
404
|
+
type: "object",
|
|
405
|
+
required: ["moduleName", "moduleVersion"],
|
|
406
|
+
properties: { moduleName: { type: "string" }, moduleVersion: { type: "string" } }
|
|
407
|
+
},
|
|
408
|
+
locationPointStamped: {
|
|
409
|
+
type: "object",
|
|
410
|
+
required: ["timestamp", "locationPoint"],
|
|
411
|
+
properties: {
|
|
412
|
+
timestamp: { $ref: "#/$defs/timestamp" },
|
|
413
|
+
locationPoint: { $ref: "#/$defs/locationPoint" }
|
|
414
|
+
}
|
|
415
|
+
},
|
|
416
|
+
requestDetail: {
|
|
417
|
+
type: "object",
|
|
418
|
+
required: ["type", "version"],
|
|
419
|
+
properties: {
|
|
420
|
+
type: { type: "string" },
|
|
421
|
+
version: { type: "string" },
|
|
422
|
+
format: { type: "string" },
|
|
423
|
+
blocking: { type: "boolean" },
|
|
424
|
+
atomic: { type: "boolean" },
|
|
425
|
+
properties: { type: "object" }
|
|
426
|
+
}
|
|
427
|
+
},
|
|
428
|
+
requestDetailStatus: {
|
|
429
|
+
type: "object",
|
|
430
|
+
required: ["type", "version", "status"],
|
|
431
|
+
properties: {
|
|
432
|
+
type: { type: "string" },
|
|
433
|
+
version: { type: "string" },
|
|
434
|
+
blocking: { type: "boolean" },
|
|
435
|
+
status: {
|
|
436
|
+
type: "object",
|
|
437
|
+
required: ["code"],
|
|
438
|
+
properties: {
|
|
439
|
+
code: { enum: ["RECEIVED", "ACCEPTED", "EXECUTING", "CANCELED", "SUCCEEDED", "ABORTED"] },
|
|
440
|
+
reason: { type: "string" },
|
|
441
|
+
message: { type: "string" }
|
|
442
|
+
}
|
|
443
|
+
},
|
|
444
|
+
properties: { type: "object" }
|
|
445
|
+
}
|
|
446
|
+
},
|
|
447
|
+
entityIdentity: {
|
|
448
|
+
type: "object",
|
|
449
|
+
required: ["id", "timestamp", "entityType", "manufacturerName", "capabilities", "details"],
|
|
450
|
+
properties: {
|
|
451
|
+
id: { $ref: "#/$defs/uuid" },
|
|
452
|
+
timestamp: { $ref: "#/$defs/timestamp" },
|
|
453
|
+
entityType: { type: "string" },
|
|
454
|
+
manufacturerName: { type: "string" },
|
|
455
|
+
iso21423Version: { type: "string" },
|
|
456
|
+
capabilities: { $ref: "#/$defs/capabilities" },
|
|
457
|
+
details: { type: "object" }
|
|
458
|
+
}
|
|
459
|
+
},
|
|
460
|
+
entityStatus: {
|
|
461
|
+
type: "object",
|
|
462
|
+
required: ["entityId", "timestamp", "states"],
|
|
463
|
+
properties: {
|
|
464
|
+
entityId: { $ref: "#/$defs/uuid" },
|
|
465
|
+
timestamp: { $ref: "#/$defs/timestamp" },
|
|
466
|
+
states: { type: "array", items: { type: "string", pattern: "^[A-Z0-9_]+$" } },
|
|
467
|
+
disabledCapabilities: { $ref: "#/$defs/capabilities" }
|
|
468
|
+
}
|
|
469
|
+
},
|
|
470
|
+
batteryStatus: {
|
|
471
|
+
type: "object",
|
|
472
|
+
required: ["timestamp", "batterySoc"],
|
|
473
|
+
properties: {
|
|
474
|
+
timestamp: { $ref: "#/$defs/timestamp" },
|
|
475
|
+
batterySoc: { type: "number", minimum: 0, maximum: 1 },
|
|
476
|
+
batteryHealth: { type: "string" },
|
|
477
|
+
batteryTemperature: { type: "number" },
|
|
478
|
+
batteryVoltage: { type: "number" },
|
|
479
|
+
batteryCurrent: { type: "number" },
|
|
480
|
+
batteryChargingState: { type: "string" }
|
|
481
|
+
}
|
|
482
|
+
},
|
|
483
|
+
odometry: {
|
|
484
|
+
type: "object",
|
|
485
|
+
required: ["timestamp", "pose", "velocity"],
|
|
486
|
+
properties: {
|
|
487
|
+
timestamp: { $ref: "#/$defs/timestamp" },
|
|
488
|
+
pose: {
|
|
489
|
+
type: "object",
|
|
490
|
+
required: ["locationPoint", "orientation"],
|
|
491
|
+
properties: {
|
|
492
|
+
locationPoint: { $ref: "#/$defs/locationPoint" },
|
|
493
|
+
orientation: { $ref: "#/$defs/orientation" }
|
|
494
|
+
}
|
|
495
|
+
},
|
|
496
|
+
velocity: {
|
|
497
|
+
type: "object",
|
|
498
|
+
required: ["linear", "angular"],
|
|
499
|
+
properties: { linear: { type: "number" }, angular: { type: "number" } }
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
},
|
|
503
|
+
localTrajectory: {
|
|
504
|
+
type: "object",
|
|
505
|
+
required: ["timestamp", "localTrajectory"],
|
|
506
|
+
properties: {
|
|
507
|
+
timestamp: { $ref: "#/$defs/timestamp" },
|
|
508
|
+
localTrajectory: { type: "array", items: { $ref: "#/$defs/locationPointStamped" } }
|
|
509
|
+
}
|
|
510
|
+
},
|
|
511
|
+
globalPath: {
|
|
512
|
+
type: "object",
|
|
513
|
+
required: ["timestamp", "globalPath"],
|
|
514
|
+
properties: {
|
|
515
|
+
timestamp: { $ref: "#/$defs/timestamp" },
|
|
516
|
+
globalPath: {
|
|
517
|
+
type: "object",
|
|
518
|
+
required: ["degree", "controlPoints", "knots"],
|
|
519
|
+
properties: {
|
|
520
|
+
degree: { type: "integer", minimum: 1 },
|
|
521
|
+
controlPoints: {
|
|
522
|
+
type: "array",
|
|
523
|
+
items: {
|
|
524
|
+
type: "object",
|
|
525
|
+
required: ["locationPoint"],
|
|
526
|
+
properties: {
|
|
527
|
+
locationPoint: { $ref: "#/$defs/locationPoint" },
|
|
528
|
+
weight: { type: "number" }
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
},
|
|
532
|
+
knots: { type: "array", items: { type: "number" }, minItems: 4 }
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
},
|
|
537
|
+
globalPlan: {
|
|
538
|
+
type: "object",
|
|
539
|
+
required: ["timestamp", "globalPlan"],
|
|
540
|
+
properties: {
|
|
541
|
+
timestamp: { $ref: "#/$defs/timestamp" },
|
|
542
|
+
globalPlan: { type: "array", items: { $ref: "#/$defs/locationPointStamped" } }
|
|
543
|
+
}
|
|
544
|
+
},
|
|
545
|
+
request: {
|
|
546
|
+
type: "object",
|
|
547
|
+
required: ["destination", "source", "sequenceId", "timestamp", "details"],
|
|
548
|
+
properties: {
|
|
549
|
+
destination: { anyOf: [{ $ref: "#/$defs/uuid" }, { const: "" }] },
|
|
550
|
+
source: { $ref: "#/$defs/uuid" },
|
|
551
|
+
sequenceId: { type: "integer", minimum: 0 },
|
|
552
|
+
timestamp: { $ref: "#/$defs/timestamp" },
|
|
553
|
+
priority: { type: "integer", minimum: 0, maximum: 255 },
|
|
554
|
+
atomic: { type: "boolean" },
|
|
555
|
+
details: { type: "array", minItems: 1, items: { $ref: "#/$defs/requestDetail" } },
|
|
556
|
+
recoveries: { type: "array", items: { $ref: "#/$defs/requestDetail" } }
|
|
557
|
+
}
|
|
558
|
+
},
|
|
559
|
+
requestStatus: {
|
|
560
|
+
type: "object",
|
|
561
|
+
required: ["source", "destination", "sequenceId", "requestSequenceId", "timestamp", "status", "detailStatuses"],
|
|
562
|
+
properties: {
|
|
563
|
+
source: { $ref: "#/$defs/uuid" },
|
|
564
|
+
destination: { $ref: "#/$defs/uuid" },
|
|
565
|
+
sequenceId: { type: "integer", minimum: 0 },
|
|
566
|
+
requestSequenceId: { type: "integer", minimum: 0 },
|
|
567
|
+
timestamp: { $ref: "#/$defs/timestamp" },
|
|
568
|
+
status: { enum: ["RECEIVED", "ACCEPTED", "EXECUTING", "CANCELED", "SUCCEEDED", "ABORTED", "RECOVERY"] },
|
|
569
|
+
detailStatuses: { type: "array", items: { $ref: "#/$defs/requestDetailStatus" } },
|
|
570
|
+
recoveryStatuses: { type: "array", items: { $ref: "#/$defs/requestDetailStatus" } }
|
|
571
|
+
}
|
|
572
|
+
},
|
|
573
|
+
requestStatusArray: { type: "array", items: { $ref: "#/$defs/requestStatus" } }
|
|
574
|
+
}
|
|
575
|
+
};
|
|
576
|
+
|
|
577
|
+
// src/schema/normalize.ts
|
|
578
|
+
var TIMESTAMP_KEYS = /* @__PURE__ */ new Set(["timestamp", "arrivalTime"]);
|
|
579
|
+
var COMMA_TS = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}),(\d+)(Z|[+-]\d{2}:?\d{2})$/;
|
|
580
|
+
function fixTimestamps(value, warnings, path) {
|
|
581
|
+
if (Array.isArray(value)) return value.map((v, i) => fixTimestamps(v, warnings, `${path}[${i}]`));
|
|
582
|
+
if (value === null || typeof value !== "object") return value;
|
|
583
|
+
const out = {};
|
|
584
|
+
for (const [k, v] of Object.entries(value)) {
|
|
585
|
+
if (TIMESTAMP_KEYS.has(k) && typeof v === "string" && COMMA_TS.test(v)) {
|
|
586
|
+
out[k] = v.replace(COMMA_TS, "$1.$2$3");
|
|
587
|
+
warnings.push(`${path}.${k}: comma-decimal timestamp normalized to dot form`);
|
|
588
|
+
} else {
|
|
589
|
+
out[k] = fixTimestamps(v, warnings, `${path}.${k}`);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
return out;
|
|
593
|
+
}
|
|
594
|
+
function normalizeInbound(kind, value) {
|
|
595
|
+
const warnings = [];
|
|
596
|
+
let v = fixTimestamps(value, warnings, kind);
|
|
597
|
+
if (kind === "entityStatus" && v !== null && typeof v === "object" && !Array.isArray(v)) {
|
|
598
|
+
const o = v;
|
|
599
|
+
if (o.entityId === void 0 && typeof o.id === "string") {
|
|
600
|
+
const { id, ...rest } = o;
|
|
601
|
+
v = { ...rest, entityId: id };
|
|
602
|
+
warnings.push('entityStatus: legacy field "id" renamed to "entityId" (spec \xA73.1)');
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
return { value: v, warnings };
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// src/schema/validators.ts
|
|
609
|
+
var ajv = new import__.Ajv2020({ allErrors: true, strict: false });
|
|
610
|
+
(0, import_ajv_formats.default)(ajv);
|
|
611
|
+
ajv.addSchema(iso21423_schema_default);
|
|
612
|
+
var KNOWN_STATES = new Set(KNOWN_OPERATING_STATES);
|
|
613
|
+
function collectWarnings(kind, value, warnings) {
|
|
614
|
+
if (kind !== "entityStatus") return;
|
|
615
|
+
const states = value?.states;
|
|
616
|
+
if (!Array.isArray(states)) return;
|
|
617
|
+
for (const s of states) {
|
|
618
|
+
if (typeof s === "string" && !KNOWN_STATES.has(s)) {
|
|
619
|
+
warnings.push(`entityStatus: unknown operating state "${s}" (deployment extension?)`);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
function validateMessage(kind, raw) {
|
|
624
|
+
const { value, warnings } = normalizeInbound(kind, raw);
|
|
625
|
+
const validate = ajv.getSchema(`https://openrobops.org/schemas/iso21423/v1.json#/$defs/${kind}`);
|
|
626
|
+
if (!validate) throw new Error(`No schema for message kind: ${kind}`);
|
|
627
|
+
const ok = validate(value);
|
|
628
|
+
collectWarnings(kind, value, warnings);
|
|
629
|
+
return ok ? { ok: true, value, warnings } : { ok: false, value, warnings, errors: validate.errors ?? [] };
|
|
630
|
+
}
|
|
631
|
+
function assertValid(kind, value) {
|
|
632
|
+
const r = validateMessage(kind, value);
|
|
633
|
+
if (!r.ok) {
|
|
634
|
+
throw new ValidationError(`outbound ${kind} message is not ISO 21423 conformant`, r.errors ?? []);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// src/session/session.ts
|
|
639
|
+
var Iso21423Session = class _Iso21423Session {
|
|
640
|
+
constructor(transport, entity, validateOutbound, armWill) {
|
|
641
|
+
this.transport = transport;
|
|
642
|
+
this.entity = entity;
|
|
643
|
+
this.validateOutbound = validateOutbound;
|
|
644
|
+
this.armWill = armWill;
|
|
645
|
+
}
|
|
646
|
+
transport;
|
|
647
|
+
entity;
|
|
648
|
+
validateOutbound;
|
|
649
|
+
armWill;
|
|
650
|
+
retainedOwned = /* @__PURE__ */ new Map();
|
|
651
|
+
rateGates = /* @__PURE__ */ new Map();
|
|
652
|
+
topicSubs = [];
|
|
653
|
+
listeners = {
|
|
654
|
+
connection: [],
|
|
655
|
+
"validation-warning": [],
|
|
656
|
+
error: []
|
|
657
|
+
};
|
|
658
|
+
wasConnected = false;
|
|
659
|
+
state = "closed";
|
|
660
|
+
/**
|
|
661
|
+
* Connects the transport and, unless `armWill` is false, arms the B.4 Last Will and clears any
|
|
662
|
+
* stale retained LOST_CONNECTION left over from a prior ungraceful disconnect (spec §4).
|
|
663
|
+
*/
|
|
664
|
+
static async connect(opts) {
|
|
665
|
+
const armWill = opts.armWill ?? true;
|
|
666
|
+
const session = new _Iso21423Session(opts.transport, opts.entity, opts.validateOutbound ?? true, armWill);
|
|
667
|
+
opts.transport.onMessage((m) => session.dispatch(m.topic, m.payload));
|
|
668
|
+
opts.transport.onConnectionState((s) => session.handleConnectionState(s));
|
|
669
|
+
await opts.transport.connect({
|
|
670
|
+
clientId: `iso21423-${opts.entity.entityType}-${opts.entity.entityUuid}`,
|
|
671
|
+
cleanSession: false,
|
|
672
|
+
keepalive: 60,
|
|
673
|
+
username: opts.credentials?.username,
|
|
674
|
+
password: opts.credentials?.password,
|
|
675
|
+
will: armWill ? {
|
|
676
|
+
topic: disconnectionTopic(opts.entity),
|
|
677
|
+
payload: JSON.stringify({ states: [LOST_CONNECTION_STATE] }),
|
|
678
|
+
qos: 1,
|
|
679
|
+
retain: true
|
|
680
|
+
} : void 0
|
|
681
|
+
});
|
|
682
|
+
if (armWill) await session.clearRetained(disconnectionTopic(opts.entity));
|
|
683
|
+
return session;
|
|
684
|
+
}
|
|
685
|
+
/** Passthrough so `/core` never rebuilds topics itself (Task 3 implementer note). */
|
|
686
|
+
topicFor(ref, resource) {
|
|
687
|
+
return topicFor(ref, resource);
|
|
688
|
+
}
|
|
689
|
+
on(event, cb) {
|
|
690
|
+
this.listeners[event].push(cb);
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* Publishes a known resource (looked up in {@link RESOURCE_CONFIG} for its QoS/retain/rate).
|
|
694
|
+
* Retained resources are deduped on-change (a re-publish with identical body is a no-op) and
|
|
695
|
+
* rolled back from the dedup cache if the publish itself fails. Rate-limited (streaming)
|
|
696
|
+
* resources go through a per-topic {@link RateGate} and are fire-and-forget: publish failures
|
|
697
|
+
* there are reported via the `error` event, not thrown.
|
|
698
|
+
*/
|
|
699
|
+
async publishResource(ref, resource, kind, payload) {
|
|
700
|
+
const config = RESOURCE_CONFIG[resource];
|
|
701
|
+
if (!config) throw new Iso21423Error(`unknown resource "${resource}"`);
|
|
702
|
+
if (kind && this.validateOutbound) assertValid(kind, payload);
|
|
703
|
+
const topic = topicFor(ref, resource);
|
|
704
|
+
const body = JSON.stringify(payload);
|
|
705
|
+
if (config.retain) {
|
|
706
|
+
if (this.retainedOwned.get(topic)?.payload === body) return;
|
|
707
|
+
this.retainedOwned.set(topic, { payload: body, qos: config.qos });
|
|
708
|
+
try {
|
|
709
|
+
await this.transport.publish(topic, body, { qos: config.qos, retain: true });
|
|
710
|
+
} catch (err) {
|
|
711
|
+
this.retainedOwned.delete(topic);
|
|
712
|
+
throw err;
|
|
713
|
+
}
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
if (config.maxHz !== void 0) {
|
|
717
|
+
let gate = this.rateGates.get(topic);
|
|
718
|
+
if (!gate) {
|
|
719
|
+
gate = new RateGate(config.maxHz);
|
|
720
|
+
this.rateGates.set(topic, gate);
|
|
721
|
+
}
|
|
722
|
+
gate.offer(body, (b) => {
|
|
723
|
+
this.transport.publish(topic, b, { qos: config.qos, retain: false }).catch((err) => this.emitError(err));
|
|
724
|
+
});
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
await this.transport.publish(topic, body, { qos: config.qos, retain: false });
|
|
728
|
+
}
|
|
729
|
+
/** Last non-wildcard resource segment → Table B.1 QoS, defaulting to QoS 1 when unknown. */
|
|
730
|
+
qosForFilter(filter) {
|
|
731
|
+
const parsed = parseTopic(filter);
|
|
732
|
+
if (!parsed) return 1;
|
|
733
|
+
const key = parsed.isRequestStatus ? "requestStatus" : parsed.resource;
|
|
734
|
+
return RESOURCE_CONFIG[key]?.qos ?? 1;
|
|
735
|
+
}
|
|
736
|
+
/**
|
|
737
|
+
* Always issues a broker SUBSCRIBE (a real broker redelivers retained messages on every
|
|
738
|
+
* SUBSCRIBE, so a late second handler must see the current retained value); the broker-side
|
|
739
|
+
* unsubscribe still only fires once the last local listener on the filter leaves (ND-17).
|
|
740
|
+
*/
|
|
741
|
+
async subscribeTopic(topicFilter, kind, handler, opts = {}) {
|
|
742
|
+
const qos = opts.qos ?? this.qosForFilter(topicFilter);
|
|
743
|
+
const { granted } = await this.transport.subscribe(topicFilter, { qos });
|
|
744
|
+
if (!granted) {
|
|
745
|
+
throw new AuthorizationDenied(`subscription denied by broker: ${topicFilter}`, topicFilter);
|
|
746
|
+
}
|
|
747
|
+
const sub = { filter: topicFilter, kind, handler };
|
|
748
|
+
this.topicSubs.push(sub);
|
|
749
|
+
return {
|
|
750
|
+
unsubscribe: async () => {
|
|
751
|
+
this.topicSubs = this.topicSubs.filter((s) => s !== sub);
|
|
752
|
+
if (!this.topicSubs.some((s) => s.filter === topicFilter)) {
|
|
753
|
+
await this.transport.unsubscribe(topicFilter);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
/** Publish to an exact topic (request / requestStatus topics are not plain resources). */
|
|
759
|
+
async publishTopic(topic, kind, payload, opts) {
|
|
760
|
+
if (kind && this.validateOutbound) assertValid(kind, payload);
|
|
761
|
+
await this.transport.publish(topic, JSON.stringify(payload), opts);
|
|
762
|
+
}
|
|
763
|
+
get connectionState() {
|
|
764
|
+
return this.state;
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Subscribe to a resource topic with optional validation.
|
|
768
|
+
* When kind is null, handler receives raw payload text without parsing or validation.
|
|
769
|
+
*/
|
|
770
|
+
async subscribeResource(filter, resource, kind, handler) {
|
|
771
|
+
const config = RESOURCE_CONFIG[resource];
|
|
772
|
+
if (!config) throw new Iso21423Error(`unknown resource "${resource}"`);
|
|
773
|
+
const topicFilter = `${ROOT_NAMESPACE}/${filter.entityType ?? "+"}/${filter.entityUuid ?? "+"}/${resource}`;
|
|
774
|
+
const sub = await this.subscribeTopic(topicFilter, kind, handler, { qos: config.qos });
|
|
775
|
+
return { unsubscribe: sub.unsubscribe, [Symbol.asyncDispose]: sub.unsubscribe };
|
|
776
|
+
}
|
|
777
|
+
/** For subscribers that opt out of schema routing (kind: null) but still want to surface a
|
|
778
|
+
* malformed payload as the usual 'validation-warning' event (D-13's RequestServer). */
|
|
779
|
+
reportValidationWarning(w) {
|
|
780
|
+
this.emitWarning(w);
|
|
781
|
+
}
|
|
782
|
+
async publishRaw(topic, payload, opts) {
|
|
783
|
+
await this.transport.publish(topic, payload, opts);
|
|
784
|
+
}
|
|
785
|
+
/** Clears a retained topic by publishing an empty retained payload, and drops it from the owned-retained dedup cache. */
|
|
786
|
+
async clearRetained(topic) {
|
|
787
|
+
this.retainedOwned.delete(topic);
|
|
788
|
+
await this.transport.publish(topic, "", { qos: 1, retain: true });
|
|
789
|
+
}
|
|
790
|
+
/** Optionally publishes a final status, disposes all rate gates, then ends the transport. */
|
|
791
|
+
async close(finalStates) {
|
|
792
|
+
if (finalStates) {
|
|
793
|
+
await this.publishResource(this.entity, "status", "entityStatus", {
|
|
794
|
+
entityId: this.entity.entityUuid,
|
|
795
|
+
timestamp: nowTimestamp(),
|
|
796
|
+
states: finalStates
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
for (const gate of this.rateGates.values()) gate.dispose();
|
|
800
|
+
await this.transport.end();
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* Routes an inbound message to every registered {@link TopicSub} whose filter matches the
|
|
804
|
+
* topic. `kind: null` subscribers get the raw text with no parsing; typed subscribers get an
|
|
805
|
+
* empty payload treated as a retained-clear (skipped silently) and malformed/non-conformant
|
|
806
|
+
* payloads reported via `emitWarning` rather than delivered to the handler.
|
|
807
|
+
*/
|
|
808
|
+
dispatch(topic, payload) {
|
|
809
|
+
const parsed = parseTopic(topic);
|
|
810
|
+
if (!parsed) return;
|
|
811
|
+
const text = payload.toString();
|
|
812
|
+
const meta = {
|
|
813
|
+
topic,
|
|
814
|
+
entityType: parsed.entityType,
|
|
815
|
+
entityUuid: parsed.entityUuid,
|
|
816
|
+
resource: parsed.resource,
|
|
817
|
+
requestUuid: parsed.requestUuid,
|
|
818
|
+
isRequestStatus: parsed.isRequestStatus
|
|
819
|
+
};
|
|
820
|
+
for (const sub of this.topicSubs) {
|
|
821
|
+
if (!topicFilterMatches(sub.filter, topic)) continue;
|
|
822
|
+
if (!sub.kind) {
|
|
823
|
+
sub.handler(text, meta);
|
|
824
|
+
continue;
|
|
825
|
+
}
|
|
826
|
+
if (text === "") continue;
|
|
827
|
+
let value;
|
|
828
|
+
try {
|
|
829
|
+
value = JSON.parse(text);
|
|
830
|
+
} catch {
|
|
831
|
+
this.emitWarning({ topic, payload: text, errors: ["invalid JSON"] });
|
|
832
|
+
continue;
|
|
833
|
+
}
|
|
834
|
+
const result = validateMessage(sub.kind, value);
|
|
835
|
+
if (!result.ok) {
|
|
836
|
+
this.emitWarning({ topic, payload: text, errors: result.errors ?? [] });
|
|
837
|
+
continue;
|
|
838
|
+
}
|
|
839
|
+
sub.handler(result.value, meta);
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
handleConnectionState(s) {
|
|
843
|
+
this.state = s;
|
|
844
|
+
for (const cb of this.listeners.connection) cb(s);
|
|
845
|
+
if (s === "connected" && this.wasConnected) {
|
|
846
|
+
for (const [topic, { payload, qos }] of this.retainedOwned) {
|
|
847
|
+
this.transport.publish(topic, payload, { qos, retain: true }).catch((err) => this.emitError(err));
|
|
848
|
+
}
|
|
849
|
+
if (this.armWill) {
|
|
850
|
+
this.clearRetained(disconnectionTopic(this.entity)).catch((err) => this.emitError(err));
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
if (s === "connected") this.wasConnected = true;
|
|
854
|
+
}
|
|
855
|
+
emitWarning(w) {
|
|
856
|
+
for (const cb of this.listeners["validation-warning"]) cb(w);
|
|
857
|
+
}
|
|
858
|
+
emitError(err) {
|
|
859
|
+
const errorListeners = this.listeners.error;
|
|
860
|
+
if (errorListeners.length > 0) {
|
|
861
|
+
for (const cb of errorListeners) cb(err);
|
|
862
|
+
} else {
|
|
863
|
+
console.error("[Iso21423Session] async publish failed:", err);
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
};
|
|
867
|
+
|
|
868
|
+
// src/core/sequence.ts
|
|
869
|
+
var import_promises = require("fs/promises");
|
|
870
|
+
var import_node_os = require("os");
|
|
871
|
+
var import_node_path = require("path");
|
|
872
|
+
function defaultStateDir() {
|
|
873
|
+
return process.env.ISO21423_STATE_DIR ?? (0, import_node_path.join)((0, import_node_os.homedir)(), ".iso21423");
|
|
874
|
+
}
|
|
875
|
+
var FileSequenceStore = class {
|
|
876
|
+
constructor(dir = defaultStateDir()) {
|
|
877
|
+
this.dir = dir;
|
|
878
|
+
this.file = (0, import_node_path.join)(this.dir, "sequence.json");
|
|
879
|
+
}
|
|
880
|
+
dir;
|
|
881
|
+
file;
|
|
882
|
+
// ponytail: in-process serialization only; use a per-file lock if multiple processes share ISO21423_STATE_DIR
|
|
883
|
+
#queue = Promise.resolve();
|
|
884
|
+
async read() {
|
|
885
|
+
try {
|
|
886
|
+
return JSON.parse(await (0, import_promises.readFile)(this.file, "utf8"));
|
|
887
|
+
} catch {
|
|
888
|
+
return {};
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
async load(entityUuid) {
|
|
892
|
+
return (await this.read())[entityUuid];
|
|
893
|
+
}
|
|
894
|
+
/** Queued so concurrent saves in one process read-modify-write the file one at a time. */
|
|
895
|
+
save(entityUuid, value) {
|
|
896
|
+
const result = this.#queue.then(() => this.writeOne(entityUuid, value));
|
|
897
|
+
this.#queue = result.then(() => void 0, () => void 0);
|
|
898
|
+
return result;
|
|
899
|
+
}
|
|
900
|
+
async writeOne(entityUuid, value) {
|
|
901
|
+
const all = await this.read();
|
|
902
|
+
all[entityUuid] = value;
|
|
903
|
+
await (0, import_promises.mkdir)(this.dir, { recursive: true });
|
|
904
|
+
const tmp = `${this.file}.${process.pid}.tmp`;
|
|
905
|
+
await (0, import_promises.writeFile)(tmp, JSON.stringify(all), "utf8");
|
|
906
|
+
await (0, import_promises.rename)(tmp, this.file);
|
|
907
|
+
}
|
|
908
|
+
};
|
|
909
|
+
var BLOCK = 1e3;
|
|
910
|
+
var SequenceCounter = class _SequenceCounter {
|
|
911
|
+
constructor(entityUuid, store, counter, reservedThrough) {
|
|
912
|
+
this.entityUuid = entityUuid;
|
|
913
|
+
this.store = store;
|
|
914
|
+
this.counter = counter;
|
|
915
|
+
this.reservedThrough = reservedThrough;
|
|
916
|
+
}
|
|
917
|
+
entityUuid;
|
|
918
|
+
store;
|
|
919
|
+
counter;
|
|
920
|
+
reservedThrough;
|
|
921
|
+
static async open(entityUuid, store, onFallback) {
|
|
922
|
+
if (!store) return new _SequenceCounter(entityUuid, void 0, 0, Number.MAX_SAFE_INTEGER);
|
|
923
|
+
try {
|
|
924
|
+
const seed = await store.load(entityUuid) ?? 0;
|
|
925
|
+
await store.save(entityUuid, seed + BLOCK);
|
|
926
|
+
return new _SequenceCounter(entityUuid, store, seed, seed + BLOCK);
|
|
927
|
+
} catch (err) {
|
|
928
|
+
onFallback?.(err);
|
|
929
|
+
return new _SequenceCounter(entityUuid, void 0, Date.now(), Number.MAX_SAFE_INTEGER);
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
/** Returns the next sequenceId, persisting a fresh reservation block when the current one is exhausted. */
|
|
933
|
+
async next() {
|
|
934
|
+
this.counter += 1;
|
|
935
|
+
if (this.counter > this.reservedThrough && this.store) {
|
|
936
|
+
this.reservedThrough = this.counter + BLOCK;
|
|
937
|
+
await this.store.save(this.entityUuid, this.reservedThrough);
|
|
938
|
+
}
|
|
939
|
+
return this.counter;
|
|
940
|
+
}
|
|
941
|
+
};
|
|
942
|
+
|
|
943
|
+
// src/core/entityCache.ts
|
|
944
|
+
var EntityCache = class {
|
|
945
|
+
constructor(session) {
|
|
946
|
+
this.session = session;
|
|
947
|
+
}
|
|
948
|
+
session;
|
|
949
|
+
byUuid = /* @__PURE__ */ new Map();
|
|
950
|
+
listeners = { entity: [], lost: [], gone: [] };
|
|
951
|
+
disconnectionSubscribed = false;
|
|
952
|
+
/** Subscribed once per client session (decision 3): identities are cheap and always needed. */
|
|
953
|
+
async start() {
|
|
954
|
+
await this.session.subscribeTopic(
|
|
955
|
+
`${ROOT_NAMESPACE}/+/+/identity`,
|
|
956
|
+
null,
|
|
957
|
+
(raw, meta) => this.onIdentity(raw, meta),
|
|
958
|
+
{ qos: 1 }
|
|
959
|
+
);
|
|
960
|
+
}
|
|
961
|
+
/** Disconnection tracking is only wired when someone actually calls discover(). */
|
|
962
|
+
async watchDisconnections() {
|
|
963
|
+
if (this.disconnectionSubscribed) return;
|
|
964
|
+
this.disconnectionSubscribed = true;
|
|
965
|
+
await this.session.subscribeTopic(
|
|
966
|
+
`${ROOT_NAMESPACE}/+/+/disconnection`,
|
|
967
|
+
null,
|
|
968
|
+
(raw, meta) => this.onDisconnection(raw, meta),
|
|
969
|
+
{ qos: 1 }
|
|
970
|
+
);
|
|
971
|
+
}
|
|
972
|
+
entities() {
|
|
973
|
+
return [...this.byUuid.values()];
|
|
974
|
+
}
|
|
975
|
+
get(uuid) {
|
|
976
|
+
return this.byUuid.get(uuid);
|
|
977
|
+
}
|
|
978
|
+
managedBy(uuid) {
|
|
979
|
+
return this.entities().filter((e) => e.managedBy === uuid);
|
|
980
|
+
}
|
|
981
|
+
on(event, cb) {
|
|
982
|
+
this.listeners[event].push(cb);
|
|
983
|
+
}
|
|
984
|
+
/** Removal path for `on()` — not part of the public `EntityCatalog` interface (D-18 consumers
|
|
985
|
+
* never unsubscribe from discovery), but used internally so per-call listeners don't leak. */
|
|
986
|
+
off(event, cb) {
|
|
987
|
+
const arr = this.listeners[event];
|
|
988
|
+
const i = arr.indexOf(cb);
|
|
989
|
+
if (i !== -1) arr.splice(i, 1);
|
|
990
|
+
}
|
|
991
|
+
/** Destination entityType resolution for request topics (decision 2). */
|
|
992
|
+
entityTypeOf(uuid) {
|
|
993
|
+
return this.byUuid.get(uuid)?.entityType;
|
|
994
|
+
}
|
|
995
|
+
/** Known-accepts lookup for NotCapableError (decision 4); undefined = unknown entity. */
|
|
996
|
+
acceptsOf(uuid) {
|
|
997
|
+
const entry = this.byUuid.get(uuid);
|
|
998
|
+
if (!entry) return void 0;
|
|
999
|
+
return entry.identity.capabilities?.accepts?.requests;
|
|
1000
|
+
}
|
|
1001
|
+
onIdentity(raw, meta) {
|
|
1002
|
+
const text = typeof raw === "string" ? raw : "";
|
|
1003
|
+
if (text.length === 0) {
|
|
1004
|
+
const gone = this.byUuid.get(meta.entityUuid);
|
|
1005
|
+
if (gone) {
|
|
1006
|
+
this.byUuid.delete(meta.entityUuid);
|
|
1007
|
+
this.emit("gone", gone);
|
|
1008
|
+
}
|
|
1009
|
+
return;
|
|
1010
|
+
}
|
|
1011
|
+
let parsed;
|
|
1012
|
+
try {
|
|
1013
|
+
parsed = JSON.parse(text);
|
|
1014
|
+
} catch {
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
const result = validateMessage("entityIdentity", parsed);
|
|
1018
|
+
if (!result.ok) return;
|
|
1019
|
+
const identity = result.value;
|
|
1020
|
+
const now = /* @__PURE__ */ new Date();
|
|
1021
|
+
const prev = this.byUuid.get(meta.entityUuid);
|
|
1022
|
+
const entry = {
|
|
1023
|
+
entityUuid: meta.entityUuid,
|
|
1024
|
+
entityType: identity.entityType ?? meta.entityType,
|
|
1025
|
+
identity,
|
|
1026
|
+
manages: identity.capabilities?.manages ?? [],
|
|
1027
|
+
managedBy: identity.capabilities?.managedBy,
|
|
1028
|
+
// Preserve connectivity status across an identity re-publish (e.g. an owned-retained
|
|
1029
|
+
// resend after the transport reconnects, session.ts's handleConnectionState): only a
|
|
1030
|
+
// disconnection message (onDisconnection) or a real reconnect-clear should change this.
|
|
1031
|
+
lost: prev?.lost ?? false,
|
|
1032
|
+
firstSeen: prev?.firstSeen ?? now,
|
|
1033
|
+
lastSeen: now
|
|
1034
|
+
};
|
|
1035
|
+
this.byUuid.set(entry.entityUuid, entry);
|
|
1036
|
+
this.emit("entity", entry);
|
|
1037
|
+
}
|
|
1038
|
+
onDisconnection(raw, meta) {
|
|
1039
|
+
const entry = this.byUuid.get(meta.entityUuid);
|
|
1040
|
+
if (!entry) return;
|
|
1041
|
+
const text = typeof raw === "string" ? raw : "";
|
|
1042
|
+
const lost = text.length > 0 && text.includes(LOST_CONNECTION_STATE);
|
|
1043
|
+
if (lost === entry.lost) return;
|
|
1044
|
+
const updated = { ...entry, lost, lastSeen: /* @__PURE__ */ new Date() };
|
|
1045
|
+
this.byUuid.set(entry.entityUuid, updated);
|
|
1046
|
+
if (lost) this.emit("lost", updated);
|
|
1047
|
+
}
|
|
1048
|
+
emit(event, e) {
|
|
1049
|
+
for (const cb of this.listeners[event]) cb(e);
|
|
1050
|
+
}
|
|
1051
|
+
};
|
|
1052
|
+
|
|
1053
|
+
// src/core/entityHandle.ts
|
|
1054
|
+
var import_node_crypto = require("crypto");
|
|
1055
|
+
|
|
1056
|
+
// src/core/resources.ts
|
|
1057
|
+
var RESOURCE_MESSAGE_KIND = {
|
|
1058
|
+
identity: "entityIdentity",
|
|
1059
|
+
status: "entityStatus",
|
|
1060
|
+
batteryStatus: "batteryStatus",
|
|
1061
|
+
odometry: "odometry",
|
|
1062
|
+
localTrajectory: "localTrajectory",
|
|
1063
|
+
globalPath: "globalPath",
|
|
1064
|
+
globalPlan: "globalPlan",
|
|
1065
|
+
request: "request",
|
|
1066
|
+
requestStatus: "requestStatus",
|
|
1067
|
+
activeRequestsStatus: "requestStatusArray",
|
|
1068
|
+
disconnection: null,
|
|
1069
|
+
footprint: null
|
|
1070
|
+
};
|
|
1071
|
+
function messageKindFor(resource) {
|
|
1072
|
+
return RESOURCE_MESSAGE_KIND[resource] ?? null;
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
// src/core/types.ts
|
|
1076
|
+
function toTimestamp(t) {
|
|
1077
|
+
if (typeof t === "string") return t;
|
|
1078
|
+
return nowTimestamp(t ?? /* @__PURE__ */ new Date());
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
// src/requests/stateMachine.ts
|
|
1082
|
+
var REQUEST_TRANSITIONS = {
|
|
1083
|
+
RECEIVED: [
|
|
1084
|
+
"ACCEPTED",
|
|
1085
|
+
"CANCELED",
|
|
1086
|
+
// NP-2: RECEIVED→CANCELED disputed vs shared interaction model (Figure C.3 final artwork may differ)
|
|
1087
|
+
"ABORTED"
|
|
1088
|
+
],
|
|
1089
|
+
ACCEPTED: [
|
|
1090
|
+
"EXECUTING",
|
|
1091
|
+
"CANCELED",
|
|
1092
|
+
"ABORTED",
|
|
1093
|
+
// NP-2: ACCEPTED→ABORTED disputed vs shared interaction model (Figure C.3 final artwork may differ)
|
|
1094
|
+
"RECOVERY"
|
|
1095
|
+
// NP-2: ACCEPTED→RECOVERY disputed vs shared interaction model (Figure C.3 final artwork may differ)
|
|
1096
|
+
],
|
|
1097
|
+
EXECUTING: ["SUCCEEDED", "CANCELED", "ABORTED", "RECOVERY"],
|
|
1098
|
+
RECOVERY: ["CANCELED", "ABORTED"],
|
|
1099
|
+
// NP-2: no RECOVERY→SUCCEEDED (disputed vs shared interaction model, Figure C.3 final artwork may differ)
|
|
1100
|
+
CANCELED: [],
|
|
1101
|
+
SUCCEEDED: [],
|
|
1102
|
+
ABORTED: []
|
|
1103
|
+
};
|
|
1104
|
+
var DETAIL_TRANSITIONS = {
|
|
1105
|
+
RECEIVED: ["ACCEPTED", "CANCELED", "ABORTED"],
|
|
1106
|
+
ACCEPTED: ["EXECUTING", "CANCELED", "ABORTED"],
|
|
1107
|
+
EXECUTING: ["SUCCEEDED", "CANCELED", "ABORTED"],
|
|
1108
|
+
CANCELED: [],
|
|
1109
|
+
SUCCEEDED: [],
|
|
1110
|
+
ABORTED: []
|
|
1111
|
+
};
|
|
1112
|
+
function isTerminalRequestState(s) {
|
|
1113
|
+
return REQUEST_TRANSITIONS[s].length === 0;
|
|
1114
|
+
}
|
|
1115
|
+
var Lifecycle = class {
|
|
1116
|
+
constructor(table, initial) {
|
|
1117
|
+
this.table = table;
|
|
1118
|
+
this.#state = initial;
|
|
1119
|
+
}
|
|
1120
|
+
table;
|
|
1121
|
+
#state;
|
|
1122
|
+
get state() {
|
|
1123
|
+
return this.#state;
|
|
1124
|
+
}
|
|
1125
|
+
canTransition(to) {
|
|
1126
|
+
return this.table[this.#state].includes(to);
|
|
1127
|
+
}
|
|
1128
|
+
/** Moves to `to` if legal; throws {@link IllegalTransition} otherwise. */
|
|
1129
|
+
transition(to) {
|
|
1130
|
+
if (!this.canTransition(to)) {
|
|
1131
|
+
throw new IllegalTransition(`illegal transition ${this.#state} \u2192 ${to}`);
|
|
1132
|
+
}
|
|
1133
|
+
this.#state = to;
|
|
1134
|
+
}
|
|
1135
|
+
isTerminal() {
|
|
1136
|
+
return this.table[this.#state].length === 0;
|
|
1137
|
+
}
|
|
1138
|
+
};
|
|
1139
|
+
var RequestLifecycle = class extends Lifecycle {
|
|
1140
|
+
constructor() {
|
|
1141
|
+
super(REQUEST_TRANSITIONS, "RECEIVED");
|
|
1142
|
+
}
|
|
1143
|
+
};
|
|
1144
|
+
var DetailLifecycle = class extends Lifecycle {
|
|
1145
|
+
constructor() {
|
|
1146
|
+
super(DETAIL_TRANSITIONS, "RECEIVED");
|
|
1147
|
+
}
|
|
1148
|
+
};
|
|
1149
|
+
|
|
1150
|
+
// src/core/subscription.ts
|
|
1151
|
+
function composeSubscription(topicFilters, parts) {
|
|
1152
|
+
let live = true;
|
|
1153
|
+
const sub = {
|
|
1154
|
+
topicFilters: Object.freeze([...topicFilters]),
|
|
1155
|
+
get active() {
|
|
1156
|
+
return live;
|
|
1157
|
+
},
|
|
1158
|
+
async unsubscribe() {
|
|
1159
|
+
if (!live) return;
|
|
1160
|
+
live = false;
|
|
1161
|
+
await Promise.all(parts.map((p) => p.unsubscribe()));
|
|
1162
|
+
},
|
|
1163
|
+
async [Symbol.asyncDispose]() {
|
|
1164
|
+
await sub.unsubscribe();
|
|
1165
|
+
}
|
|
1166
|
+
};
|
|
1167
|
+
return sub;
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
// src/core/requestHandle.ts
|
|
1171
|
+
var RequestHandle = class {
|
|
1172
|
+
/** @internal */
|
|
1173
|
+
constructor(ctx, destRef, requestUuid, sourceUuid, sequenceId, destination, timeoutMs) {
|
|
1174
|
+
this.ctx = ctx;
|
|
1175
|
+
this.destRef = destRef;
|
|
1176
|
+
this.requestUuid = requestUuid;
|
|
1177
|
+
this.sourceUuid = sourceUuid;
|
|
1178
|
+
this.sequenceId = sequenceId;
|
|
1179
|
+
this.destination = destination;
|
|
1180
|
+
this.timeoutMs = timeoutMs;
|
|
1181
|
+
this.#completion = new Promise((resolve, reject) => {
|
|
1182
|
+
this.#resolve = resolve;
|
|
1183
|
+
this.#reject = reject;
|
|
1184
|
+
});
|
|
1185
|
+
this.#completion.catch(() => void 0);
|
|
1186
|
+
}
|
|
1187
|
+
ctx;
|
|
1188
|
+
destRef;
|
|
1189
|
+
requestUuid;
|
|
1190
|
+
sourceUuid;
|
|
1191
|
+
sequenceId;
|
|
1192
|
+
destination;
|
|
1193
|
+
timeoutMs;
|
|
1194
|
+
createdAt = /* @__PURE__ */ new Date();
|
|
1195
|
+
#latest;
|
|
1196
|
+
#listeners = [];
|
|
1197
|
+
#settled = false;
|
|
1198
|
+
#resolve;
|
|
1199
|
+
#reject;
|
|
1200
|
+
#completion;
|
|
1201
|
+
#timer;
|
|
1202
|
+
#statusSub;
|
|
1203
|
+
/** @internal — called by sendRequest once the status subscription is live. */
|
|
1204
|
+
armTimeout(sub) {
|
|
1205
|
+
this.#statusSub = sub;
|
|
1206
|
+
this.#timer = setTimeout(() => {
|
|
1207
|
+
this.settle(new RequestTimeout(
|
|
1208
|
+
`no RECEIVED for request ${this.requestUuid} within ${this.timeoutMs} ms`
|
|
1209
|
+
));
|
|
1210
|
+
}, this.timeoutMs);
|
|
1211
|
+
this.#timer.unref?.();
|
|
1212
|
+
}
|
|
1213
|
+
/** @internal — one inbound requestStatus message. */
|
|
1214
|
+
ingest(status) {
|
|
1215
|
+
if (status.requestSequenceId !== this.sequenceId) return;
|
|
1216
|
+
this.#latest = status;
|
|
1217
|
+
if (this.#timer) {
|
|
1218
|
+
clearTimeout(this.#timer);
|
|
1219
|
+
this.#timer = void 0;
|
|
1220
|
+
}
|
|
1221
|
+
for (const cb of this.#listeners) cb(status);
|
|
1222
|
+
if (!isTerminalRequestState(status.status)) return;
|
|
1223
|
+
void this.clearRetainedRequest();
|
|
1224
|
+
if (status.status === "SUCCEEDED") this.settle(void 0, status);
|
|
1225
|
+
else this.settle(new RequestFailed(`request ${this.requestUuid} ended ${status.status}`, status));
|
|
1226
|
+
}
|
|
1227
|
+
/** @internal — connection lost while in flight (nodejs_api.md §12). */
|
|
1228
|
+
failFast() {
|
|
1229
|
+
this.settle(new BrokerUnavailable(`broker unavailable during request ${this.requestUuid}`));
|
|
1230
|
+
}
|
|
1231
|
+
latestStatus() {
|
|
1232
|
+
return this.#latest;
|
|
1233
|
+
}
|
|
1234
|
+
/** @internal — the resolved topic ref (post R3 empty-destination resolution), for sendCancel. */
|
|
1235
|
+
internalDestRef() {
|
|
1236
|
+
return this.destRef;
|
|
1237
|
+
}
|
|
1238
|
+
/** Registers a callback for every inbound status update on this request (not just the terminal one); returns a token to stop receiving them. */
|
|
1239
|
+
onStatus(handler) {
|
|
1240
|
+
this.#listeners.push(handler);
|
|
1241
|
+
return composeSubscription([requestStatusTopic(this.destRef, this.requestUuid)], [{
|
|
1242
|
+
unsubscribe: async () => {
|
|
1243
|
+
this.#listeners = this.#listeners.filter((h) => h !== handler);
|
|
1244
|
+
}
|
|
1245
|
+
}]);
|
|
1246
|
+
}
|
|
1247
|
+
/** Resolves with the terminal SUCCEEDED status, or rejects with {@link RequestFailed}/{@link RequestTimeout}/{@link BrokerUnavailable} — never both. */
|
|
1248
|
+
completion() {
|
|
1249
|
+
return this.#completion;
|
|
1250
|
+
}
|
|
1251
|
+
/** Sends a cancelRequest for this request (or one action within it, via `actionId`); a no-op once the request has already settled. */
|
|
1252
|
+
async cancel(opts = {}) {
|
|
1253
|
+
if (this.#settled) return;
|
|
1254
|
+
await this.ctx.sendCancel(this, opts.actionId);
|
|
1255
|
+
}
|
|
1256
|
+
settle(error, status) {
|
|
1257
|
+
if (this.#settled) return;
|
|
1258
|
+
this.#settled = true;
|
|
1259
|
+
if (this.#timer) {
|
|
1260
|
+
clearTimeout(this.#timer);
|
|
1261
|
+
this.#timer = void 0;
|
|
1262
|
+
}
|
|
1263
|
+
void this.#statusSub?.unsubscribe().catch(() => {
|
|
1264
|
+
});
|
|
1265
|
+
if (error) this.#reject(error);
|
|
1266
|
+
else this.#resolve(status);
|
|
1267
|
+
}
|
|
1268
|
+
/** Sender duty: clear the retained request on a terminal status (ND-10). Never throws — if the
|
|
1269
|
+
* broker publish fails, Task 8's janitor is the backstop that eventually clears stale
|
|
1270
|
+
* retained requests. */
|
|
1271
|
+
async clearRetainedRequest() {
|
|
1272
|
+
try {
|
|
1273
|
+
await this.ctx.session.clearRetained(requestTopic(this.destRef, this.requestUuid));
|
|
1274
|
+
} catch {
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
};
|
|
1278
|
+
|
|
1279
|
+
// src/core/incomingRequest.ts
|
|
1280
|
+
var IncomingRequest = class {
|
|
1281
|
+
/** @internal */
|
|
1282
|
+
constructor(request, requestUuid, sink) {
|
|
1283
|
+
this.request = request;
|
|
1284
|
+
this.requestUuid = requestUuid;
|
|
1285
|
+
this.sink = sink;
|
|
1286
|
+
this.#details = request.details.map(() => new DetailLifecycle());
|
|
1287
|
+
this.#detailStatuses = request.details.map((d) => ({
|
|
1288
|
+
type: d.type,
|
|
1289
|
+
version: d.version,
|
|
1290
|
+
...d.blocking !== void 0 ? { blocking: d.blocking } : {},
|
|
1291
|
+
status: { code: "RECEIVED" }
|
|
1292
|
+
}));
|
|
1293
|
+
}
|
|
1294
|
+
request;
|
|
1295
|
+
requestUuid;
|
|
1296
|
+
sink;
|
|
1297
|
+
#lifecycle = new RequestLifecycle();
|
|
1298
|
+
#details;
|
|
1299
|
+
#detailStatuses;
|
|
1300
|
+
#recoveries;
|
|
1301
|
+
#recoveryStatuses;
|
|
1302
|
+
get source() {
|
|
1303
|
+
return this.request.source;
|
|
1304
|
+
}
|
|
1305
|
+
get sequenceId() {
|
|
1306
|
+
return this.request.sequenceId;
|
|
1307
|
+
}
|
|
1308
|
+
get state() {
|
|
1309
|
+
return this.#lifecycle.state;
|
|
1310
|
+
}
|
|
1311
|
+
get isTerminal() {
|
|
1312
|
+
return this.#lifecycle.isTerminal();
|
|
1313
|
+
}
|
|
1314
|
+
/** @internal — D-12: RECEIVED is published by the server before the handler sees this. */
|
|
1315
|
+
async publishReceived() {
|
|
1316
|
+
await this.emit();
|
|
1317
|
+
}
|
|
1318
|
+
async accept() {
|
|
1319
|
+
await this.transitionTo("ACCEPTED");
|
|
1320
|
+
}
|
|
1321
|
+
/** Transitions straight to ABORTED with the given reason (e.g. for pre-flight rejections that never reach ACCEPTED). */
|
|
1322
|
+
async reject(reason) {
|
|
1323
|
+
await this.transitionTo("ABORTED", reason);
|
|
1324
|
+
}
|
|
1325
|
+
async updateStatus(update) {
|
|
1326
|
+
await this.transitionTo(update.status, update.reason, update.message);
|
|
1327
|
+
}
|
|
1328
|
+
async updateDetailStatus(update) {
|
|
1329
|
+
const lifecycle = this.#details[update.index];
|
|
1330
|
+
const entry = this.#detailStatuses[update.index];
|
|
1331
|
+
if (!lifecycle || !entry) {
|
|
1332
|
+
throw new IllegalTransition(`no request detail at index ${update.index}`);
|
|
1333
|
+
}
|
|
1334
|
+
if (lifecycle.state !== update.status) lifecycle.transition(update.status);
|
|
1335
|
+
entry.status = {
|
|
1336
|
+
code: update.status,
|
|
1337
|
+
...update.reason ? { reason: update.reason } : {},
|
|
1338
|
+
...update.message ? { message: update.message } : {}
|
|
1339
|
+
};
|
|
1340
|
+
if (update.properties) entry.properties = { ...entry.properties, ...update.properties };
|
|
1341
|
+
await this.emit();
|
|
1342
|
+
}
|
|
1343
|
+
async complete(terminal) {
|
|
1344
|
+
await this.transitionTo(terminal.status, terminal.reason, terminal.message);
|
|
1345
|
+
}
|
|
1346
|
+
/** @internal — used by the executor for the RECOVERY phase: transitions the request to
|
|
1347
|
+
* RECOVERY and seeds `recoveryStatuses` from the request's declared `recoveries`, mirroring
|
|
1348
|
+
* how the constructor seeds `detailStatuses` from `request.details`. */
|
|
1349
|
+
async enterRecovery(recoveries, reason) {
|
|
1350
|
+
this.#recoveries = recoveries.map(() => new DetailLifecycle());
|
|
1351
|
+
this.#recoveryStatuses = recoveries.map((d) => ({
|
|
1352
|
+
type: d.type,
|
|
1353
|
+
version: d.version,
|
|
1354
|
+
...d.blocking !== void 0 ? { blocking: d.blocking } : {},
|
|
1355
|
+
status: { code: "RECEIVED" }
|
|
1356
|
+
}));
|
|
1357
|
+
await this.transitionTo("RECOVERY", reason);
|
|
1358
|
+
}
|
|
1359
|
+
/** @internal — used by the executor to report a recovery detail's progress/outcome. Unlike
|
|
1360
|
+
* `updateDetailStatus`, recovery entries are never cascaded by a terminal request transition
|
|
1361
|
+
* (RECOVERY has no detail-level equivalent — see cascadeDetails), so the executor must call
|
|
1362
|
+
* this for every recovery detail as it finishes, not just the non-last ones. */
|
|
1363
|
+
async updateRecoveryStatus(update) {
|
|
1364
|
+
const lifecycle = this.#recoveries?.[update.index];
|
|
1365
|
+
const entry = this.#recoveryStatuses?.[update.index];
|
|
1366
|
+
if (!lifecycle || !entry) {
|
|
1367
|
+
throw new IllegalTransition(`no recovery detail at index ${update.index}`);
|
|
1368
|
+
}
|
|
1369
|
+
if (update.status === "EXECUTING" && lifecycle.state === "RECEIVED") lifecycle.transition("ACCEPTED");
|
|
1370
|
+
if (lifecycle.state !== update.status) lifecycle.transition(update.status);
|
|
1371
|
+
entry.status = {
|
|
1372
|
+
code: update.status,
|
|
1373
|
+
...update.reason ? { reason: update.reason } : {},
|
|
1374
|
+
...update.message ? { message: update.message } : {}
|
|
1375
|
+
};
|
|
1376
|
+
if (update.properties) entry.properties = { ...entry.properties, ...update.properties };
|
|
1377
|
+
await this.emit();
|
|
1378
|
+
}
|
|
1379
|
+
async transitionTo(to, reason, message) {
|
|
1380
|
+
this.#lifecycle.transition(to);
|
|
1381
|
+
this.cascadeDetails(to);
|
|
1382
|
+
await this.emit(reason, message);
|
|
1383
|
+
}
|
|
1384
|
+
// ponytail: a request-level transition implies at least that much progress on every detail
|
|
1385
|
+
// still in flight — an app that only calls accept()/updateStatus()/complete() and never
|
|
1386
|
+
// updateDetailStatus() for a given detail shouldn't leave it stuck at RECEIVED (or, worse,
|
|
1387
|
+
// publish a dead request with a still-live detail underneath it). Details already at or past
|
|
1388
|
+
// `to`, already terminal, or for which `to` has no detail-level equivalent (RECOVERY) are left
|
|
1389
|
+
// untouched; explicit updateDetailStatus() calls after this are then no-ops state-wise. Mirrors
|
|
1390
|
+
// onto the wire-visible #detailStatuses entry too (preserving any reason/message already set),
|
|
1391
|
+
// not just the internal DetailLifecycle guard.
|
|
1392
|
+
cascadeDetails(to) {
|
|
1393
|
+
const target = to;
|
|
1394
|
+
this.#details.forEach((lifecycle, i) => {
|
|
1395
|
+
if (lifecycle.isTerminal() || lifecycle.state === target) return;
|
|
1396
|
+
if (!lifecycle.canTransition(target)) return;
|
|
1397
|
+
lifecycle.transition(target);
|
|
1398
|
+
const entry = this.#detailStatuses[i];
|
|
1399
|
+
entry.status = { ...entry.status, code: target };
|
|
1400
|
+
});
|
|
1401
|
+
}
|
|
1402
|
+
/**
|
|
1403
|
+
* Builds and publishes the current requestStatus snapshot. A `reason`/`message` passed here
|
|
1404
|
+
* (from a request-level transition) is attached to the first detail status entry, not stored
|
|
1405
|
+
* at the request level — the wire schema carries reason/message per-detail, not on the request.
|
|
1406
|
+
*/
|
|
1407
|
+
async emit(reason, message) {
|
|
1408
|
+
const status = {
|
|
1409
|
+
source: this.sink.ownerUuid,
|
|
1410
|
+
// decision 5
|
|
1411
|
+
destination: this.request.source,
|
|
1412
|
+
sequenceId: await this.sink.nextStatusSequenceId(),
|
|
1413
|
+
requestSequenceId: this.request.sequenceId,
|
|
1414
|
+
timestamp: toTimestamp(),
|
|
1415
|
+
status: this.#lifecycle.state,
|
|
1416
|
+
detailStatuses: this.#detailStatuses.map((d) => ({ ...d })),
|
|
1417
|
+
...this.#recoveryStatuses ? { recoveryStatuses: this.#recoveryStatuses.map((d) => ({ ...d })) } : {}
|
|
1418
|
+
};
|
|
1419
|
+
if (reason || message) {
|
|
1420
|
+
const first = status.detailStatuses[0];
|
|
1421
|
+
if (first) {
|
|
1422
|
+
first.status = {
|
|
1423
|
+
...first.status,
|
|
1424
|
+
...reason ? { reason } : {},
|
|
1425
|
+
...message ? { message } : {}
|
|
1426
|
+
};
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
await this.sink.publishStatus(this, status);
|
|
1430
|
+
}
|
|
1431
|
+
};
|
|
1432
|
+
|
|
1433
|
+
// src/core/policies.ts
|
|
1434
|
+
var DEFAULT_PRIORITY = 100;
|
|
1435
|
+
var priorityOf = (r) => r.priority ?? DEFAULT_PRIORITY;
|
|
1436
|
+
var keyOf = (s) => ({ source: s.destination, sequenceId: s.requestSequenceId });
|
|
1437
|
+
var policies = {
|
|
1438
|
+
/** Only one active request at a time; any new request while one is active is rejected outright (no buffering). */
|
|
1439
|
+
abortNew() {
|
|
1440
|
+
return {
|
|
1441
|
+
admit: (_pending, active) => active.length === 0 ? { action: "accept" } : { action: "reject", reason: "REJECTED" }
|
|
1442
|
+
};
|
|
1443
|
+
},
|
|
1444
|
+
/** One active + one queued slot; the server aborts the displaced queue entry with REJECTED. */
|
|
1445
|
+
queueReplace() {
|
|
1446
|
+
const policy = {
|
|
1447
|
+
admit: (_pending, active) => active.length === 0 ? { action: "accept" } : { action: "buffer" }
|
|
1448
|
+
};
|
|
1449
|
+
Object.assign(policy, { bufferLimit: 1 });
|
|
1450
|
+
return policy;
|
|
1451
|
+
},
|
|
1452
|
+
/** One active request; unlimited FIFO queueing behind it. */
|
|
1453
|
+
queueAfter() {
|
|
1454
|
+
const policy = {
|
|
1455
|
+
admit: (_pending, active) => active.length === 0 ? { action: "accept" } : { action: "buffer" }
|
|
1456
|
+
};
|
|
1457
|
+
Object.assign(policy, { bufferLimit: Number.POSITIVE_INFINITY });
|
|
1458
|
+
return policy;
|
|
1459
|
+
},
|
|
1460
|
+
/** Up to `max` concurrently active requests (unbounded by default); beyond that, buffer FIFO. */
|
|
1461
|
+
parallel(max = Number.POSITIVE_INFINITY) {
|
|
1462
|
+
const policy = {
|
|
1463
|
+
admit: (_pending, active) => active.length < max ? { action: "accept" } : { action: "buffer" }
|
|
1464
|
+
};
|
|
1465
|
+
Object.assign(policy, { bufferLimit: Number.POSITIVE_INFINITY });
|
|
1466
|
+
return policy;
|
|
1467
|
+
},
|
|
1468
|
+
/** A pending request with strictly lower `priority` (Table C.1: lower number = higher priority) than every active request preempts all of them; otherwise it buffers, and the buffer drains by priority. */
|
|
1469
|
+
priority() {
|
|
1470
|
+
const policy = {
|
|
1471
|
+
admit: (pending, active) => {
|
|
1472
|
+
if (active.length === 0) return { action: "accept" };
|
|
1473
|
+
const mine = priorityOf(pending);
|
|
1474
|
+
const beatsAll = active.every(
|
|
1475
|
+
(s) => mine < priorityOf(s)
|
|
1476
|
+
);
|
|
1477
|
+
return beatsAll ? { action: "preempt", preempt: active.map(keyOf) } : { action: "buffer" };
|
|
1478
|
+
}
|
|
1479
|
+
};
|
|
1480
|
+
Object.assign(policy, { bufferLimit: Number.POSITIVE_INFINITY, drainByPriority: true });
|
|
1481
|
+
return policy;
|
|
1482
|
+
}
|
|
1483
|
+
};
|
|
1484
|
+
var DEFAULT_EXECUTION_POLICY = policies.parallel();
|
|
1485
|
+
|
|
1486
|
+
// src/core/executor.ts
|
|
1487
|
+
var BLOCKING_STATES = ["STOP_CATEGORY_0", "STOP_CATEGORY_1", "STOP_CATEGORY_2", "WAIT_FOR_RESET"];
|
|
1488
|
+
var STATE_EXEMPT_TYPES = /* @__PURE__ */ new Set(["cancelRequest", "pauseImr", "resumeImr"]);
|
|
1489
|
+
var majorOf = (version) => version.split(".")[0] ?? version;
|
|
1490
|
+
function groupSteps(details) {
|
|
1491
|
+
const steps = [];
|
|
1492
|
+
let i = 0;
|
|
1493
|
+
while (i < details.length) {
|
|
1494
|
+
if (details[i].blocking === false) {
|
|
1495
|
+
const group = [];
|
|
1496
|
+
while (i < details.length && details[i].blocking === false) {
|
|
1497
|
+
group.push(i);
|
|
1498
|
+
i++;
|
|
1499
|
+
}
|
|
1500
|
+
steps.push(group);
|
|
1501
|
+
} else {
|
|
1502
|
+
steps.push([i]);
|
|
1503
|
+
i++;
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
return steps;
|
|
1507
|
+
}
|
|
1508
|
+
var ActionExecutor = class {
|
|
1509
|
+
handlers = /* @__PURE__ */ new Map();
|
|
1510
|
+
runs = /* @__PURE__ */ new Map();
|
|
1511
|
+
/** Registers a handler for `type`; throws if one is already registered unless `override: true`. */
|
|
1512
|
+
register(type, handler, opts) {
|
|
1513
|
+
if (this.handlers.has(type) && !opts?.override) {
|
|
1514
|
+
throw new Iso21423Error(
|
|
1515
|
+
`onRequest: a handler for "${type}" is already registered \u2014 pass { override: true } to replace it`
|
|
1516
|
+
);
|
|
1517
|
+
}
|
|
1518
|
+
this.handlers.set(type, handler);
|
|
1519
|
+
}
|
|
1520
|
+
hasHandlers() {
|
|
1521
|
+
return this.handlers.size > 0;
|
|
1522
|
+
}
|
|
1523
|
+
runKey(source, sequenceId) {
|
|
1524
|
+
return `${source}:${sequenceId}`;
|
|
1525
|
+
}
|
|
1526
|
+
/** Fires the AbortController for an admitted request the policy is preempting (Task 7 seam). */
|
|
1527
|
+
cancel(key) {
|
|
1528
|
+
const run = this.runs.get(this.runKey(key.source, key.sequenceId));
|
|
1529
|
+
if (!run) return false;
|
|
1530
|
+
run.cancelRequested = true;
|
|
1531
|
+
run.controller.abort();
|
|
1532
|
+
return true;
|
|
1533
|
+
}
|
|
1534
|
+
/** Entry point called once a request is admitted (RequestServer step 6 fallback). The run stays
|
|
1535
|
+
* registered in `this.runs` (so a cancelRequest can still find it) until the request is fully
|
|
1536
|
+
* terminal — including through the RECOVERY phase (controller ruling: RECOVERY→CANCELED is
|
|
1537
|
+
* legal, so a cancel arriving mid-recovery must still resolve). */
|
|
1538
|
+
async run(incoming, entity) {
|
|
1539
|
+
const request = incoming.request;
|
|
1540
|
+
const preflight = this.preflightReject(request, entity);
|
|
1541
|
+
if (preflight) {
|
|
1542
|
+
await incoming.reject(preflight);
|
|
1543
|
+
return;
|
|
1544
|
+
}
|
|
1545
|
+
await incoming.accept();
|
|
1546
|
+
await incoming.updateStatus({ status: "EXECUTING" });
|
|
1547
|
+
const key = this.runKey(request.source, request.sequenceId);
|
|
1548
|
+
const run = { controller: new AbortController(), cancelRequested: false };
|
|
1549
|
+
this.runs.set(key, run);
|
|
1550
|
+
try {
|
|
1551
|
+
const outcome = await this.runSequence(
|
|
1552
|
+
request.details,
|
|
1553
|
+
request,
|
|
1554
|
+
entity,
|
|
1555
|
+
run,
|
|
1556
|
+
true,
|
|
1557
|
+
false,
|
|
1558
|
+
(index, patch) => incoming.updateDetailStatus({ index, ...patch })
|
|
1559
|
+
);
|
|
1560
|
+
if (outcome.trigger === "success") {
|
|
1561
|
+
await incoming.complete({ status: "SUCCEEDED" });
|
|
1562
|
+
return;
|
|
1563
|
+
}
|
|
1564
|
+
let trigger = outcome.trigger;
|
|
1565
|
+
let reason = outcome.reason;
|
|
1566
|
+
let message = outcome.message;
|
|
1567
|
+
if (request.recoveries && request.recoveries.length > 0) {
|
|
1568
|
+
await incoming.enterRecovery(request.recoveries, reason);
|
|
1569
|
+
run.controller = new AbortController();
|
|
1570
|
+
run.cancelRequested = false;
|
|
1571
|
+
const recoveryOutcome = await this.runSequence(
|
|
1572
|
+
request.recoveries,
|
|
1573
|
+
request,
|
|
1574
|
+
entity,
|
|
1575
|
+
run,
|
|
1576
|
+
false,
|
|
1577
|
+
true,
|
|
1578
|
+
(index, patch) => incoming.updateRecoveryStatus({ index, ...patch })
|
|
1579
|
+
);
|
|
1580
|
+
if (recoveryOutcome.trigger !== "success") {
|
|
1581
|
+
if (recoveryOutcome.trigger === "cancel") trigger = "cancel";
|
|
1582
|
+
reason = recoveryOutcome.reason ?? reason;
|
|
1583
|
+
message = recoveryOutcome.message ?? message;
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
const finalStatus = trigger === "cancel" ? "CANCELED" : "ABORTED";
|
|
1587
|
+
await incoming.complete({ status: finalStatus, reason, message });
|
|
1588
|
+
} finally {
|
|
1589
|
+
this.runs.delete(key);
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
/** Runs one detail array (main details or recoveries) under the shared sequencing rules
|
|
1593
|
+
* (item 3), atomic protection (item 4) and outcome mapping (item 5).
|
|
1594
|
+
* - `allowSkipLastSuccess` lets the caller rely on the request-level terminal cascade for the
|
|
1595
|
+
* very last detail of a clean success run (main details only).
|
|
1596
|
+
* - `markRemainingCanceled`: recoveryStatuses is never cascaded by the request's terminal
|
|
1597
|
+
* transition (unlike detailStatuses), so when the sequence stops early the caller must ask
|
|
1598
|
+
* us to explicitly mark every not-yet-started item CANCELED (main details rely on the
|
|
1599
|
+
* cascade instead and pass false here). */
|
|
1600
|
+
async runSequence(items, request, entity, run, allowSkipLastSuccess, markRemainingCanceled, update) {
|
|
1601
|
+
const steps = groupSteps(items);
|
|
1602
|
+
for (let s = 0; s < steps.length; s++) {
|
|
1603
|
+
const group = steps[s];
|
|
1604
|
+
const results = await Promise.all(
|
|
1605
|
+
group.map((index) => this.runOneDetail(index, items[index], request, entity, run, update))
|
|
1606
|
+
);
|
|
1607
|
+
const batchHasAbort = results.some((r) => r.outcome === "aborted");
|
|
1608
|
+
const cancelledNow = run.controller.signal.aborted || run.cancelRequested;
|
|
1609
|
+
for (let k = 0; k < group.length; k++) {
|
|
1610
|
+
const index = group[k];
|
|
1611
|
+
const result = results[k];
|
|
1612
|
+
const isLastOverall = index === items.length - 1;
|
|
1613
|
+
if (result.outcome === "succeeded") {
|
|
1614
|
+
const skip = allowSkipLastSuccess && isLastOverall && !batchHasAbort && !cancelledNow;
|
|
1615
|
+
if (!skip) {
|
|
1616
|
+
await update(index, { status: "SUCCEEDED", ...result.properties ? { properties: result.properties } : {} });
|
|
1617
|
+
}
|
|
1618
|
+
} else {
|
|
1619
|
+
await update(index, { status: "ABORTED", reason: result.reason, ...result.message ? { message: result.message } : {} });
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
if (batchHasAbort || cancelledNow) {
|
|
1623
|
+
if (markRemainingCanceled) {
|
|
1624
|
+
for (const index of steps.slice(s + 1).flat()) {
|
|
1625
|
+
await update(index, { status: "CANCELED" });
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
const aborted = results.find((r) => r.outcome === "aborted");
|
|
1629
|
+
return cancelledNow ? { trigger: "cancel", reason: aborted?.reason, message: aborted?.message } : { trigger: "abort", reason: aborted?.reason, message: aborted?.message };
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
return { trigger: "success" };
|
|
1633
|
+
}
|
|
1634
|
+
/**
|
|
1635
|
+
* Runs a single detail's handler: publishes an EXECUTING status first, then invokes the
|
|
1636
|
+
* registered handler (or produces an ACTION_NOT_IMPLEMENTED result if none exists), catching any
|
|
1637
|
+
* thrown error as a GENERAL_FAILURE abort. Waits for any `ctx.progress()` updates issued during
|
|
1638
|
+
* the handler call to finish publishing before returning.
|
|
1639
|
+
*/
|
|
1640
|
+
async runOneDetail(index, detail2, request, entity, run, update) {
|
|
1641
|
+
const atomic = (detail2.atomic ?? false) || (request.atomic ?? false);
|
|
1642
|
+
const signal = atomic ? new AbortController().signal : run.controller.signal;
|
|
1643
|
+
await update(index, { status: "EXECUTING" });
|
|
1644
|
+
const pending = [];
|
|
1645
|
+
const ctx = {
|
|
1646
|
+
entity,
|
|
1647
|
+
request,
|
|
1648
|
+
signal,
|
|
1649
|
+
progress: (properties) => {
|
|
1650
|
+
pending.push(update(index, { status: "EXECUTING", properties }));
|
|
1651
|
+
},
|
|
1652
|
+
succeeded: (properties) => properties !== void 0 ? { outcome: "succeeded", properties } : { outcome: "succeeded" },
|
|
1653
|
+
aborted: (reason, message) => message !== void 0 ? { outcome: "aborted", reason, message } : { outcome: "aborted", reason }
|
|
1654
|
+
};
|
|
1655
|
+
const typed = { ...detail2, properties: detail2.properties ?? {} };
|
|
1656
|
+
const handler = this.handlers.get(detail2.type);
|
|
1657
|
+
let result;
|
|
1658
|
+
try {
|
|
1659
|
+
if (!handler) {
|
|
1660
|
+
result = { outcome: "aborted", reason: "ACTION_NOT_IMPLEMENTED" };
|
|
1661
|
+
} else {
|
|
1662
|
+
result = await handler(typed, ctx);
|
|
1663
|
+
}
|
|
1664
|
+
} catch (err) {
|
|
1665
|
+
result = { outcome: "aborted", reason: "GENERAL_FAILURE", message: err instanceof Error ? err.message : String(err) };
|
|
1666
|
+
}
|
|
1667
|
+
await Promise.all(pending);
|
|
1668
|
+
return result;
|
|
1669
|
+
}
|
|
1670
|
+
/** Item 1: pre-flight rejection, first match wins across the four rule categories, each
|
|
1671
|
+
* scanned over every detail in order. */
|
|
1672
|
+
preflightReject(request, entity) {
|
|
1673
|
+
for (const d of request.details) {
|
|
1674
|
+
if (d.format !== void 0 && d.format !== "ISO-21423") return "FORMAT_NOT_SUPPORTED";
|
|
1675
|
+
}
|
|
1676
|
+
for (const d of request.details) {
|
|
1677
|
+
if (majorOf(d.version) !== majorOf(PROTOCOL_VERSION)) return "VERSION_NOT_SUPPORTED";
|
|
1678
|
+
}
|
|
1679
|
+
for (const d of request.details) {
|
|
1680
|
+
if (d.type !== "cancelRequest" && !this.handlers.has(d.type)) return "ACTION_NOT_IMPLEMENTED";
|
|
1681
|
+
}
|
|
1682
|
+
const states = entity.lastStates();
|
|
1683
|
+
if (BLOCKING_STATES.some((s) => states.includes(s))) {
|
|
1684
|
+
for (const d of request.details) {
|
|
1685
|
+
if (!STATE_EXEMPT_TYPES.has(d.type)) return "INVALID_IMR_STATE_FOR_ACTION";
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
return void 0;
|
|
1689
|
+
}
|
|
1690
|
+
};
|
|
1691
|
+
async function resolveCancelRequest(cancelReq, executors) {
|
|
1692
|
+
const props = cancelReq.request.details[0]?.properties;
|
|
1693
|
+
const key = props?.source !== void 0 && props.requestId !== void 0 ? { source: props.source, sequenceId: props.requestId } : void 0;
|
|
1694
|
+
const found = key !== void 0 && [...executors].some((ex) => ex.cancel(key));
|
|
1695
|
+
if (found) {
|
|
1696
|
+
await cancelReq.accept();
|
|
1697
|
+
await cancelReq.updateStatus({ status: "EXECUTING" });
|
|
1698
|
+
await cancelReq.complete({ status: "SUCCEEDED" });
|
|
1699
|
+
} else {
|
|
1700
|
+
await cancelReq.reject("REJECTED");
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1704
|
+
// src/core/requestServer.ts
|
|
1705
|
+
var RequestServer = class {
|
|
1706
|
+
constructor(ctx) {
|
|
1707
|
+
this.ctx = ctx;
|
|
1708
|
+
this.sink = {
|
|
1709
|
+
ownerUuid: ctx.ref.entityUuid,
|
|
1710
|
+
nextStatusSequenceId: () => ctx.sequence.next(),
|
|
1711
|
+
// D-15: same SequenceCounter as sendRequest
|
|
1712
|
+
publishStatus: (req, status) => this.publishStatus(req, status)
|
|
1713
|
+
};
|
|
1714
|
+
}
|
|
1715
|
+
ctx;
|
|
1716
|
+
sessionSub;
|
|
1717
|
+
registrations = [];
|
|
1718
|
+
// ponytail: in-memory only — a process restart re-executes requests still retained on the
|
|
1719
|
+
// broker; persist the key set alongside the sequence seed if that ever bites.
|
|
1720
|
+
seen = /* @__PURE__ */ new Set();
|
|
1721
|
+
activeStatuses = /* @__PURE__ */ new Map();
|
|
1722
|
+
pendingRequests = [];
|
|
1723
|
+
sink;
|
|
1724
|
+
// Task 7: the executor is the fallback consumer once no acceptRequests filter matches — see
|
|
1725
|
+
// handleAcceptedRequest / the cancelRequest branch of handleInbound below.
|
|
1726
|
+
executor;
|
|
1727
|
+
// Task 8 (FleetGateway) seams — both optional, set only by EntityHandle.setDispatchInterceptor /
|
|
1728
|
+
// onRequestSettled when a gateway wires them; a plain client never touches either.
|
|
1729
|
+
dispatchInterceptor;
|
|
1730
|
+
requestSettledHook;
|
|
1731
|
+
// ND-12 cancel-resolution seam: every managed handle's executor, consulted when a cancelRequest
|
|
1732
|
+
// doesn't name a run in this server's own executor — a dispatched request actually runs in the
|
|
1733
|
+
// target robot's executor, not the IMRFM's own.
|
|
1734
|
+
managedExecutorsHook;
|
|
1735
|
+
/** Idempotent: a second acceptRequests() on the same handle reuses the live subscription. */
|
|
1736
|
+
async ensureStarted() {
|
|
1737
|
+
if (this.sessionSub) return;
|
|
1738
|
+
const filter = `${this.ctx.session.topicFor(this.ctx.ref, "request")}/+`;
|
|
1739
|
+
this.sessionSub = await this.ctx.session.subscribeTopic(
|
|
1740
|
+
filter,
|
|
1741
|
+
null,
|
|
1742
|
+
(msg, meta) => {
|
|
1743
|
+
this.handleInbound(msg, meta).catch((err) => this.ctx.diagnostic("dispatch-rejected", { reason: "GENERAL_FAILURE", error: err }));
|
|
1744
|
+
},
|
|
1745
|
+
{ qos: 2 }
|
|
1746
|
+
);
|
|
1747
|
+
}
|
|
1748
|
+
/** @internal — EntityHandle.onRequest wires the executor in here once, the first time it's used. */
|
|
1749
|
+
setExecutor(executor, entity) {
|
|
1750
|
+
this.executor = { executor, entity };
|
|
1751
|
+
}
|
|
1752
|
+
/** @internal — EntityHandle.setDispatchInterceptor (ND-12, IMRFM handle only). */
|
|
1753
|
+
setDispatchInterceptor(cb) {
|
|
1754
|
+
this.dispatchInterceptor = cb;
|
|
1755
|
+
}
|
|
1756
|
+
/** @internal — EntityHandle.setManagedExecutorsHook (ND-12 cancel resolution, IMRFM handle
|
|
1757
|
+
* only). */
|
|
1758
|
+
setManagedExecutorsHook(cb) {
|
|
1759
|
+
this.managedExecutorsHook = cb;
|
|
1760
|
+
}
|
|
1761
|
+
/** @internal — EntityHandle.onRequestSettled (ND-10 janitor feed). */
|
|
1762
|
+
setRequestSettledHook(cb) {
|
|
1763
|
+
this.requestSettledHook = cb;
|
|
1764
|
+
}
|
|
1765
|
+
/** Adds a low-level request handler for `filter`; returns a deregistration function (not itself async — callers unsubscribe/teardown separately once `handlerCount` hits 0). */
|
|
1766
|
+
register(filter, handler) {
|
|
1767
|
+
const reg = { filter, handler };
|
|
1768
|
+
this.registrations.push(reg);
|
|
1769
|
+
return () => {
|
|
1770
|
+
this.registrations = this.registrations.filter((r) => r !== reg);
|
|
1771
|
+
};
|
|
1772
|
+
}
|
|
1773
|
+
get handlerCount() {
|
|
1774
|
+
return this.registrations.length;
|
|
1775
|
+
}
|
|
1776
|
+
/** ND-18: count of admitted (handed to a handler), still-non-terminal requests — what
|
|
1777
|
+
* ClientHealth.activeRequests.serving sums across every handle. */
|
|
1778
|
+
get servingCount() {
|
|
1779
|
+
let n = 0;
|
|
1780
|
+
for (const data of this.activeStatuses.values()) if (data.admitted) n++;
|
|
1781
|
+
return n;
|
|
1782
|
+
}
|
|
1783
|
+
async teardown() {
|
|
1784
|
+
await this.sessionSub?.unsubscribe();
|
|
1785
|
+
this.sessionSub = void 0;
|
|
1786
|
+
}
|
|
1787
|
+
/**
|
|
1788
|
+
* Top-level inbound message handler for this entity's `request/+` subscription: parses and
|
|
1789
|
+
* schema-validates the payload (rejecting/warning on failure), drops retained clears and
|
|
1790
|
+
* already-seen duplicates, publishes RECEIVED, then routes the request — dispatch interception
|
|
1791
|
+
* (ND-12) first, then cancelRequest resolution, then normal admission-policy handling.
|
|
1792
|
+
*/
|
|
1793
|
+
async handleInbound(text, meta) {
|
|
1794
|
+
if (text === "") return;
|
|
1795
|
+
const requestUuid = meta.requestUuid;
|
|
1796
|
+
if (!requestUuid) return;
|
|
1797
|
+
let parsed;
|
|
1798
|
+
try {
|
|
1799
|
+
parsed = JSON.parse(text);
|
|
1800
|
+
} catch {
|
|
1801
|
+
await this.rejectOrWarn(meta.topic, text, void 0, ["invalid JSON"], requestUuid);
|
|
1802
|
+
return;
|
|
1803
|
+
}
|
|
1804
|
+
const result = validateMessage("request", parsed);
|
|
1805
|
+
if (!result.ok) {
|
|
1806
|
+
await this.rejectOrWarn(meta.topic, text, result.value, result.errors ?? [], requestUuid);
|
|
1807
|
+
return;
|
|
1808
|
+
}
|
|
1809
|
+
const request = result.value;
|
|
1810
|
+
const dupKey = `${request.source}:${request.sequenceId}`;
|
|
1811
|
+
if (this.seen.has(dupKey)) {
|
|
1812
|
+
this.ctx.diagnostic("duplicate-request-ignored", { source: request.source, sequenceId: request.sequenceId });
|
|
1813
|
+
this.requestSettledHook?.(meta.topic);
|
|
1814
|
+
return;
|
|
1815
|
+
}
|
|
1816
|
+
this.seen.add(dupKey);
|
|
1817
|
+
const req = new IncomingRequest(request, requestUuid, this.sink);
|
|
1818
|
+
await req.publishReceived();
|
|
1819
|
+
if (this.dispatchInterceptor && request.destination === "") {
|
|
1820
|
+
const target = this.dispatchInterceptor(request);
|
|
1821
|
+
if (target) {
|
|
1822
|
+
void target.executor.run(req, target.entity).catch((err) => this.ctx.diagnostic("dispatch-rejected", { reason: "GENERAL_FAILURE", error: err }));
|
|
1823
|
+
} else {
|
|
1824
|
+
this.ctx.diagnostic("dispatch-rejected", { reason: "REJECTED" });
|
|
1825
|
+
await req.reject("REJECTED");
|
|
1826
|
+
}
|
|
1827
|
+
return;
|
|
1828
|
+
}
|
|
1829
|
+
const firstDetail = request.details[0];
|
|
1830
|
+
if (firstDetail && firstDetail.type === "cancel") {
|
|
1831
|
+
this.ctx.diagnostic("legacy-cancel-normalized", { source: request.source, sequenceId: request.sequenceId });
|
|
1832
|
+
firstDetail.type = "cancelRequest";
|
|
1833
|
+
}
|
|
1834
|
+
const isCancelRequest = request.details.length > 0 && request.details[0].type === "cancelRequest";
|
|
1835
|
+
if (isCancelRequest) {
|
|
1836
|
+
const matching = this.registrations.filter((r) => r.filter.matches(request));
|
|
1837
|
+
if (matching.length > 0) {
|
|
1838
|
+
for (const r of matching) r.handler(req);
|
|
1839
|
+
} else {
|
|
1840
|
+
const executors = this.cancelExecutors();
|
|
1841
|
+
if (executors.length > 0) {
|
|
1842
|
+
await resolveCancelRequest(req, executors);
|
|
1843
|
+
} else {
|
|
1844
|
+
this.ctx.diagnostic("dispatch-rejected", { reason: "ACTION_NOT_IMPLEMENTED" });
|
|
1845
|
+
await req.reject("ACTION_NOT_IMPLEMENTED");
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
return;
|
|
1849
|
+
}
|
|
1850
|
+
const policy = this.ctx.getExecutionPolicy();
|
|
1851
|
+
const decision = policy.admit(request, this.buildActiveStatuses());
|
|
1852
|
+
await this.applyAdmissionDecision(request, req, decision, policy);
|
|
1853
|
+
}
|
|
1854
|
+
/** Controller ruling R2: build a minimal one-detail IncomingRequest and reject it with
|
|
1855
|
+
* MALFORMED_REQUEST when (source, sequenceId) can still be read; otherwise surface the usual
|
|
1856
|
+
* 'validation-warning' event and drop, same as any other schema-routed subscription would. */
|
|
1857
|
+
async rejectOrWarn(topic, raw, parsed, errors, requestUuid) {
|
|
1858
|
+
const obj = parsed && typeof parsed === "object" ? parsed : void 0;
|
|
1859
|
+
const source = typeof obj?.source === "string" ? obj.source : void 0;
|
|
1860
|
+
const sequenceId = typeof obj?.sequenceId === "number" ? obj.sequenceId : void 0;
|
|
1861
|
+
if (source === void 0 || sequenceId === void 0) {
|
|
1862
|
+
this.ctx.session.reportValidationWarning({ topic, payload: raw, errors });
|
|
1863
|
+
this.requestSettledHook?.(topic);
|
|
1864
|
+
return;
|
|
1865
|
+
}
|
|
1866
|
+
const minimal = {
|
|
1867
|
+
destination: this.ctx.ref.entityUuid,
|
|
1868
|
+
source,
|
|
1869
|
+
sequenceId,
|
|
1870
|
+
timestamp: toTimestamp(),
|
|
1871
|
+
details: [{ type: this.inferDetailType(obj), version: "1.0" }]
|
|
1872
|
+
};
|
|
1873
|
+
const req = new IncomingRequest(minimal, requestUuid, this.sink);
|
|
1874
|
+
this.ctx.diagnostic("dispatch-rejected", { reason: "MALFORMED_REQUEST" });
|
|
1875
|
+
await req.reject("MALFORMED_REQUEST");
|
|
1876
|
+
}
|
|
1877
|
+
inferDetailType(obj) {
|
|
1878
|
+
const details = obj.details;
|
|
1879
|
+
if (Array.isArray(details) && details.length > 0) {
|
|
1880
|
+
const first = details[0];
|
|
1881
|
+
if (first && typeof first === "object" && typeof first.type === "string") {
|
|
1882
|
+
return first.type;
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
return "unknown";
|
|
1886
|
+
}
|
|
1887
|
+
/** The StatusSink: publish the requestStatus, then republish activeRequestsStatus (point 7). */
|
|
1888
|
+
async publishStatus(req, status) {
|
|
1889
|
+
const topic = requestStatusTopic(this.ctx.ref, req.requestUuid);
|
|
1890
|
+
const { qos, retain } = RESOURCE_CONFIG.requestStatus;
|
|
1891
|
+
await this.ctx.session.publishTopic(topic, "requestStatus", status, { qos, retain });
|
|
1892
|
+
this.ctx.countPublish();
|
|
1893
|
+
if (isTerminalRequestState(status.status)) {
|
|
1894
|
+
this.activeStatuses.delete(req.requestUuid);
|
|
1895
|
+
this.requestSettledHook?.(requestTopic(this.ctx.ref, req.requestUuid));
|
|
1896
|
+
setImmediate(() => {
|
|
1897
|
+
this.reAdmitPending().catch((err) => this.ctx.diagnostic("dispatch-rejected", { reason: "GENERAL_FAILURE", error: err }));
|
|
1898
|
+
});
|
|
1899
|
+
} else {
|
|
1900
|
+
this.activeStatuses.set(req.requestUuid, {
|
|
1901
|
+
req,
|
|
1902
|
+
status,
|
|
1903
|
+
priority: req.request.priority,
|
|
1904
|
+
admitted: this.activeStatuses.get(req.requestUuid)?.admitted ?? false
|
|
1905
|
+
});
|
|
1906
|
+
}
|
|
1907
|
+
const statusArray = [...this.activeStatuses.values()].map((data) => data.status);
|
|
1908
|
+
await this.ctx.session.publishResource(
|
|
1909
|
+
this.ctx.ref,
|
|
1910
|
+
"activeRequestsStatus",
|
|
1911
|
+
"requestStatusArray",
|
|
1912
|
+
statusArray
|
|
1913
|
+
);
|
|
1914
|
+
this.ctx.countPublish();
|
|
1915
|
+
}
|
|
1916
|
+
/** The admission view (R7: augmented with priority): only requests a policy decision has
|
|
1917
|
+
* already admitted. Buffered requests — and the pending request itself, which is entered as
|
|
1918
|
+
* admitted:false by its own RECEIVED — never appear here. */
|
|
1919
|
+
buildActiveStatuses() {
|
|
1920
|
+
return [...this.activeStatuses.values()].filter((data) => data.admitted).map((data) => ({
|
|
1921
|
+
...data.status,
|
|
1922
|
+
...data.priority !== void 0 ? { priority: data.priority } : {}
|
|
1923
|
+
}));
|
|
1924
|
+
}
|
|
1925
|
+
/** Apply an admission decision: accept, reject, buffer, or preempt. */
|
|
1926
|
+
async applyAdmissionDecision(request, req, decision, policy) {
|
|
1927
|
+
if (decision.action === "reject") {
|
|
1928
|
+
this.ctx.diagnostic("dispatch-rejected", { reason: decision.reason });
|
|
1929
|
+
await req.reject(decision.reason);
|
|
1930
|
+
} else if (decision.action === "buffer") {
|
|
1931
|
+
this.pendingRequests.push({ request, req });
|
|
1932
|
+
await this.enforceBufferLimit(policy);
|
|
1933
|
+
} else {
|
|
1934
|
+
if (decision.action === "preempt") {
|
|
1935
|
+
for (const key of decision.preempt) {
|
|
1936
|
+
for (const data of this.activeStatuses.values()) {
|
|
1937
|
+
if (!data.admitted) continue;
|
|
1938
|
+
if (data.status.destination === key.source && data.status.requestSequenceId === key.sequenceId) {
|
|
1939
|
+
const executorOwned = this.executor?.executor.cancel(key) ?? false;
|
|
1940
|
+
if (!executorOwned) await data.req.complete({ status: "CANCELED", reason: "PREEMPTED" });
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
await this.handleAcceptedRequest(request, req);
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
/** Handle an accepted request: mark as admitted, route to matching handlers. */
|
|
1949
|
+
async handleAcceptedRequest(request, req) {
|
|
1950
|
+
const existing = this.activeStatuses.get(req.requestUuid);
|
|
1951
|
+
if (existing) existing.admitted = true;
|
|
1952
|
+
const matching = this.registrations.filter((r) => r.filter.matches(request));
|
|
1953
|
+
if (matching.length > 0) {
|
|
1954
|
+
for (const r of matching) r.handler(req);
|
|
1955
|
+
return;
|
|
1956
|
+
}
|
|
1957
|
+
if (this.executor && this.executor.executor.hasHandlers()) {
|
|
1958
|
+
void this.executor.executor.run(req, this.executor.entity).catch((err) => this.ctx.diagnostic("dispatch-rejected", { reason: "GENERAL_FAILURE", error: err }));
|
|
1959
|
+
return;
|
|
1960
|
+
}
|
|
1961
|
+
this.ctx.diagnostic("dispatch-rejected", { reason: "ACTION_NOT_IMPLEMENTED" });
|
|
1962
|
+
await req.reject("ACTION_NOT_IMPLEMENTED");
|
|
1963
|
+
}
|
|
1964
|
+
/** Every executor a cancelRequest should be resolved against: this server's own first (if any),
|
|
1965
|
+
* then every managed handle's (ND-12, IMRFM only). */
|
|
1966
|
+
cancelExecutors() {
|
|
1967
|
+
const list = [];
|
|
1968
|
+
if (this.executor) list.push(this.executor.executor);
|
|
1969
|
+
if (this.managedExecutorsHook) list.push(...this.managedExecutorsHook());
|
|
1970
|
+
return list;
|
|
1971
|
+
}
|
|
1972
|
+
/** Enforce bufferLimit: if the buffer exceeds the limit, displace the oldest request with REJECTED. */
|
|
1973
|
+
async enforceBufferLimit(policy) {
|
|
1974
|
+
const limit = policy.bufferLimit ?? Number.POSITIVE_INFINITY;
|
|
1975
|
+
while (this.pendingRequests.length > limit) {
|
|
1976
|
+
const displaced = this.pendingRequests.shift();
|
|
1977
|
+
this.ctx.diagnostic("dispatch-rejected", { reason: "REJECTED" });
|
|
1978
|
+
await displaced.req.reject("REJECTED");
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
/** Re-admit buffered requests after a terminal transition, one at a time: each admitted request
|
|
1982
|
+
* is marked admitted before the next decision is taken, so the drain stops as soon as the
|
|
1983
|
+
* policy buffers again. Removal from the queue happens before any await, so two overlapping
|
|
1984
|
+
* drains can never hand the same request to a handler twice. */
|
|
1985
|
+
async reAdmitPending() {
|
|
1986
|
+
while (this.pendingRequests.length > 0) {
|
|
1987
|
+
const policy = this.ctx.getExecutionPolicy();
|
|
1988
|
+
const index = this.selectNextPending(policy);
|
|
1989
|
+
const pending = this.pendingRequests[index];
|
|
1990
|
+
const decision = policy.admit(pending.request, this.buildActiveStatuses());
|
|
1991
|
+
if (decision.action === "buffer") break;
|
|
1992
|
+
this.pendingRequests.splice(index, 1);
|
|
1993
|
+
await this.applyAdmissionDecision(pending.request, pending.req, decision, policy);
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
/** Next buffered request to drain: lowest numeric priority first when the policy asks for a
|
|
1997
|
+
* priority drain (arrival order breaking ties), plain FIFO otherwise. */
|
|
1998
|
+
selectNextPending(policy) {
|
|
1999
|
+
if (!policy.drainByPriority) return 0;
|
|
2000
|
+
const pri = (i) => this.pendingRequests[i].request.priority ?? DEFAULT_PRIORITY;
|
|
2001
|
+
let best = 0;
|
|
2002
|
+
for (let i = 1; i < this.pendingRequests.length; i++) if (pri(i) < pri(best)) best = i;
|
|
2003
|
+
return best;
|
|
2004
|
+
}
|
|
2005
|
+
};
|
|
2006
|
+
|
|
2007
|
+
// src/core/entityHandle.ts
|
|
2008
|
+
var RETAINED_RESOURCES = [
|
|
2009
|
+
"identity",
|
|
2010
|
+
"batteryStatus",
|
|
2011
|
+
"globalPath",
|
|
2012
|
+
"globalPlan",
|
|
2013
|
+
"activeRequestsStatus",
|
|
2014
|
+
"disconnection"
|
|
2015
|
+
];
|
|
2016
|
+
var EntityHandle = class {
|
|
2017
|
+
/** @internal — constructed by Iso21423Client.registerSelfEntity/registerManagedEntity. */
|
|
2018
|
+
constructor(ctx, ownershipMode, registration) {
|
|
2019
|
+
this.ctx = ctx;
|
|
2020
|
+
this.ownershipMode = ownershipMode;
|
|
2021
|
+
this.#identity = {
|
|
2022
|
+
id: registration.entityUuid,
|
|
2023
|
+
timestamp: toTimestamp(),
|
|
2024
|
+
entityType: registration.entityType,
|
|
2025
|
+
manufacturerName: registration.manufacturerName,
|
|
2026
|
+
iso21423Version: registration.iso21423Version ?? PROTOCOL_VERSION,
|
|
2027
|
+
capabilities: {
|
|
2028
|
+
provides: registration.capabilities?.provides ?? [],
|
|
2029
|
+
accepts: { requests: registration.capabilities?.accepts ?? [] }
|
|
2030
|
+
},
|
|
2031
|
+
details: registration.details ?? {}
|
|
2032
|
+
};
|
|
2033
|
+
this.#registrationPolicy = registration.executionPolicy;
|
|
2034
|
+
}
|
|
2035
|
+
ctx;
|
|
2036
|
+
ownershipMode;
|
|
2037
|
+
#identity;
|
|
2038
|
+
#states = [];
|
|
2039
|
+
#requestServer;
|
|
2040
|
+
#executor;
|
|
2041
|
+
#executionPolicy;
|
|
2042
|
+
#registrationPolicy;
|
|
2043
|
+
get entityUuid() {
|
|
2044
|
+
return this.ctx.ref.entityUuid;
|
|
2045
|
+
}
|
|
2046
|
+
get entityType() {
|
|
2047
|
+
return this.ctx.ref.entityType;
|
|
2048
|
+
}
|
|
2049
|
+
/** Last states this handle published — feeds the automatic INVALID_IMR_STATE_FOR_ACTION rule. */
|
|
2050
|
+
lastStates() {
|
|
2051
|
+
return this.#states;
|
|
2052
|
+
}
|
|
2053
|
+
identity() {
|
|
2054
|
+
return this.#identity;
|
|
2055
|
+
}
|
|
2056
|
+
async publishIdentity(identity) {
|
|
2057
|
+
this.#identity = { ...identity, timestamp: toTimestamp(identity.timestamp) };
|
|
2058
|
+
await this.publish("identity", this.#identity);
|
|
2059
|
+
}
|
|
2060
|
+
/** Shallow-merges `partial` onto the current identity (top-level fields only — e.g. a partial `capabilities` replaces the whole object) and republishes it with a fresh timestamp. */
|
|
2061
|
+
async updateIdentity(partial) {
|
|
2062
|
+
await this.publishIdentity({ ...this.#identity, ...partial, timestamp: toTimestamp() });
|
|
2063
|
+
}
|
|
2064
|
+
/** Set a per-handle execution policy override (P-2). */
|
|
2065
|
+
setExecutionPolicy(policy) {
|
|
2066
|
+
this.#executionPolicy = policy;
|
|
2067
|
+
}
|
|
2068
|
+
/** Get the resolved execution policy (per-handle > registration > client default > DEFAULT_EXECUTION_POLICY). */
|
|
2069
|
+
getExecutionPolicy() {
|
|
2070
|
+
return this.#executionPolicy ?? this.#registrationPolicy ?? this.ctx.getDefaultExecutionPolicy();
|
|
2071
|
+
}
|
|
2072
|
+
async publishStatus(update) {
|
|
2073
|
+
this.#states = [...update.states];
|
|
2074
|
+
await this.publish("status", {
|
|
2075
|
+
entityId: this.entityUuid,
|
|
2076
|
+
timestamp: toTimestamp(update.timestamp),
|
|
2077
|
+
states: update.states,
|
|
2078
|
+
...update.disabledCapabilities ? { disabledCapabilities: update.disabledCapabilities } : {}
|
|
2079
|
+
});
|
|
2080
|
+
}
|
|
2081
|
+
async publishBatteryStatus(update) {
|
|
2082
|
+
await this.publish("batteryStatus", { ...update, timestamp: toTimestamp(update.timestamp) });
|
|
2083
|
+
}
|
|
2084
|
+
async publishOdometry(sample) {
|
|
2085
|
+
await this.publish("odometry", { ...sample, timestamp: toTimestamp(sample.timestamp) });
|
|
2086
|
+
}
|
|
2087
|
+
async publishLocalTrajectory(sample) {
|
|
2088
|
+
await this.publish("localTrajectory", {
|
|
2089
|
+
timestamp: toTimestamp(sample.timestamp),
|
|
2090
|
+
localTrajectory: sample.points
|
|
2091
|
+
});
|
|
2092
|
+
}
|
|
2093
|
+
async publishGlobalPath(snapshot) {
|
|
2094
|
+
await this.publish("globalPath", { ...snapshot, timestamp: toTimestamp(snapshot.timestamp) });
|
|
2095
|
+
}
|
|
2096
|
+
async publishGlobalPlan(snapshot) {
|
|
2097
|
+
await this.publish("globalPlan", { ...snapshot, timestamp: toTimestamp(snapshot.timestamp) });
|
|
2098
|
+
}
|
|
2099
|
+
/**
|
|
2100
|
+
* Publishes a deployment-defined resource previously declared with `registerExtensionResource`
|
|
2101
|
+
* (throws for an undeclared name). No schema applies: `payload` is JSON-serialized as given, so
|
|
2102
|
+
* include your own `timestamp` if the resource needs one.
|
|
2103
|
+
*/
|
|
2104
|
+
async publishExtension(resource, payload) {
|
|
2105
|
+
await this.publish(resource, payload);
|
|
2106
|
+
}
|
|
2107
|
+
/**
|
|
2108
|
+
* Sends a request to `cmd.destination` (or resolves an empty destination via
|
|
2109
|
+
* {@link resolveDestRef}, R3). Unless `requireCapability: false`, checks the destination's
|
|
2110
|
+
* known `accepts` capability list first and throws {@link NotCapableError} for any detail type
|
|
2111
|
+
* it doesn't advertise — skipped entirely for an unknown (not-yet-discovered) destination.
|
|
2112
|
+
* Subscribes to the status topic before publishing the request, so no status can be missed.
|
|
2113
|
+
*/
|
|
2114
|
+
async sendRequest(cmd) {
|
|
2115
|
+
const destRef = this.resolveDestRef(cmd);
|
|
2116
|
+
if (cmd.requireCapability !== false && cmd.destination) {
|
|
2117
|
+
const accepts = this.ctx.catalog.acceptsOf(cmd.destination);
|
|
2118
|
+
const missing = accepts && cmd.details.map((d) => d.type).filter((t) => !accepts.includes(t));
|
|
2119
|
+
if (missing && missing.length > 0) {
|
|
2120
|
+
throw new NotCapableError(
|
|
2121
|
+
`entity ${cmd.destination} does not accept: ${missing.join(", ")} (pass requireCapability: false to send anyway)`
|
|
2122
|
+
);
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
const sequenceId = await this.ctx.sequence.next();
|
|
2126
|
+
const requestUuid = cmd.requestUuid ?? (0, import_node_crypto.randomUUID)();
|
|
2127
|
+
const request = {
|
|
2128
|
+
destination: cmd.destination,
|
|
2129
|
+
source: this.entityUuid,
|
|
2130
|
+
sequenceId,
|
|
2131
|
+
timestamp: toTimestamp(),
|
|
2132
|
+
...cmd.priority !== void 0 ? { priority: cmd.priority } : {},
|
|
2133
|
+
...cmd.atomic !== void 0 ? { atomic: cmd.atomic } : {},
|
|
2134
|
+
details: cmd.details,
|
|
2135
|
+
...cmd.recoveries ? { recoveries: cmd.recoveries } : {}
|
|
2136
|
+
};
|
|
2137
|
+
const handle = new RequestHandle(
|
|
2138
|
+
this.ctx,
|
|
2139
|
+
destRef,
|
|
2140
|
+
requestUuid,
|
|
2141
|
+
this.entityUuid,
|
|
2142
|
+
sequenceId,
|
|
2143
|
+
cmd.destination,
|
|
2144
|
+
cmd.timeoutMs ?? this.ctx.requestTimeoutMs
|
|
2145
|
+
);
|
|
2146
|
+
const sub = await this.ctx.session.subscribeTopic(
|
|
2147
|
+
requestStatusTopic(destRef, requestUuid),
|
|
2148
|
+
"requestStatus",
|
|
2149
|
+
(msg) => handle.ingest(msg),
|
|
2150
|
+
{ qos: 2 }
|
|
2151
|
+
);
|
|
2152
|
+
this.ctx.trackInFlight(handle);
|
|
2153
|
+
handle.armTimeout(sub);
|
|
2154
|
+
await this.ctx.session.publishTopic(
|
|
2155
|
+
requestTopic(destRef, requestUuid),
|
|
2156
|
+
"request",
|
|
2157
|
+
request,
|
|
2158
|
+
{ qos: 2, retain: true }
|
|
2159
|
+
);
|
|
2160
|
+
this.ctx.countPublish();
|
|
2161
|
+
return handle;
|
|
2162
|
+
}
|
|
2163
|
+
/** Registers a low-level request handler (Task 5); Tasks 6/7 add admission and the executor
|
|
2164
|
+
* hand-off on top of the same `RequestServer`. */
|
|
2165
|
+
async acceptRequests(filter, handler) {
|
|
2166
|
+
const server = this.ensureRequestServer();
|
|
2167
|
+
await server.ensureStarted();
|
|
2168
|
+
const deregister = server.register(filter, handler);
|
|
2169
|
+
const requestFilterTopic = `${this.ctx.session.topicFor(this.ctx.ref, "request")}/+`;
|
|
2170
|
+
return composeSubscription([requestFilterTopic], [{
|
|
2171
|
+
unsubscribe: async () => {
|
|
2172
|
+
deregister();
|
|
2173
|
+
if (server.handlerCount === 0) {
|
|
2174
|
+
await server.teardown();
|
|
2175
|
+
if (this.#requestServer === server) this.#requestServer = void 0;
|
|
2176
|
+
}
|
|
2177
|
+
}
|
|
2178
|
+
}]);
|
|
2179
|
+
}
|
|
2180
|
+
/**
|
|
2181
|
+
* Registers a per-action handler (Task 7, ND-11.1): the `ActionExecutor` becomes the fallback
|
|
2182
|
+
* consumer on this handle's `RequestServer` — low-level `acceptRequests` filters still win when
|
|
2183
|
+
* they match, otherwise any request whose details this executor recognizes is driven through
|
|
2184
|
+
* the executor's sequencing/atomic/recovery/cancelRequest logic. Registering a second handler
|
|
2185
|
+
* for the same `type` without `override: true` throws.
|
|
2186
|
+
*/
|
|
2187
|
+
onRequest(type, handler, opts) {
|
|
2188
|
+
if (!this.#executor) {
|
|
2189
|
+
this.#executor = new ActionExecutor();
|
|
2190
|
+
const server = this.ensureRequestServer();
|
|
2191
|
+
server.setExecutor(this.#executor, this);
|
|
2192
|
+
void server.ensureStarted().catch((err) => this.ctx.diagnostic("dispatch-rejected", { reason: "GENERAL_FAILURE", error: err }));
|
|
2193
|
+
}
|
|
2194
|
+
this.#executor.register(type, handler, opts);
|
|
2195
|
+
}
|
|
2196
|
+
/**
|
|
2197
|
+
* @internal — FleetGateway janitor seam (ND-10): `cb` fires with this handle's request topic
|
|
2198
|
+
* whenever its `RequestServer` publishes a terminal status, or drops a duplicate/unroutable
|
|
2199
|
+
* retained request. Force-creates and starts the `RequestServer` so the hook is live even
|
|
2200
|
+
* before any `onRequest`/`acceptRequests` call.
|
|
2201
|
+
*/
|
|
2202
|
+
async onRequestSettled(cb) {
|
|
2203
|
+
const server = this.ensureRequestServer();
|
|
2204
|
+
await server.ensureStarted();
|
|
2205
|
+
server.setRequestSettledHook(cb);
|
|
2206
|
+
}
|
|
2207
|
+
/**
|
|
2208
|
+
* @internal — FleetGateway dispatch seam (ND-12): wires the empty-destination interceptor onto
|
|
2209
|
+
* this handle's `RequestServer` (the IMRFM handle, wired once at `FleetGateway.connect()`).
|
|
2210
|
+
*/
|
|
2211
|
+
async setDispatchInterceptor(cb) {
|
|
2212
|
+
const server = this.ensureRequestServer();
|
|
2213
|
+
await server.ensureStarted();
|
|
2214
|
+
server.setDispatchInterceptor(cb);
|
|
2215
|
+
}
|
|
2216
|
+
/**
|
|
2217
|
+
* @internal — FleetGateway cancel-resolution seam (ND-12): wires the managed-handles executor
|
|
2218
|
+
* lookup onto this handle's `RequestServer` (the IMRFM handle, wired once at
|
|
2219
|
+
* `FleetGateway.connect()`) so a cancelRequest for a dispatched request can find the run in the
|
|
2220
|
+
* robot's executor instead of the IMRFM's own.
|
|
2221
|
+
*/
|
|
2222
|
+
async setManagedExecutorsHook(cb) {
|
|
2223
|
+
const server = this.ensureRequestServer();
|
|
2224
|
+
await server.ensureStarted();
|
|
2225
|
+
server.setManagedExecutorsHook(cb);
|
|
2226
|
+
}
|
|
2227
|
+
/** @internal — ND-12 retarget seam: this handle's executor, if an `onRequest` handler is
|
|
2228
|
+
* registered on it; used to hand a dispatched request off to a managed handle. A valid,
|
|
2229
|
+
* registered robot with no `onRequest` handler yields `undefined` here too — the dispatch
|
|
2230
|
+
* callback rejects it the same as an unknown uuid (there is nothing to run the request). */
|
|
2231
|
+
dispatchTarget() {
|
|
2232
|
+
return this.#executor ? { executor: this.#executor, entity: this } : void 0;
|
|
2233
|
+
}
|
|
2234
|
+
/** ND-18: requests this handle's RequestServer is currently serving (0 if it never started). */
|
|
2235
|
+
servingCount() {
|
|
2236
|
+
return this.#requestServer?.servingCount ?? 0;
|
|
2237
|
+
}
|
|
2238
|
+
ensureRequestServer() {
|
|
2239
|
+
if (!this.#requestServer) this.#requestServer = new RequestServer(this.ctx);
|
|
2240
|
+
return this.#requestServer;
|
|
2241
|
+
}
|
|
2242
|
+
/**
|
|
2243
|
+
* Controller ruling R3: an empty `destination` (spec §3.1 "IMRFM picks the robot") is not a
|
|
2244
|
+
* literal topic segment — resolve the actual target from the identity catalog by
|
|
2245
|
+
* `destinationType` (default `'IMRFM'`). Exactly one match is required; the wire `Request`
|
|
2246
|
+
* still carries `destination: ''` (only the topic ref is resolved).
|
|
2247
|
+
*/
|
|
2248
|
+
resolveDestRef(cmd) {
|
|
2249
|
+
if (cmd.destination !== "") {
|
|
2250
|
+
const destinationType = cmd.destinationType ?? this.ctx.catalog.entityTypeOf(cmd.destination) ?? "IMR";
|
|
2251
|
+
return { entityType: destinationType, entityUuid: cmd.destination };
|
|
2252
|
+
}
|
|
2253
|
+
const entityType = cmd.destinationType ?? "IMRFM";
|
|
2254
|
+
const candidates = this.ctx.catalog.entities().filter((e) => e.entityType === entityType);
|
|
2255
|
+
if (candidates.length !== 1) {
|
|
2256
|
+
throw new Iso21423Error(
|
|
2257
|
+
`sendRequest: cannot resolve an empty destination to exactly one "${entityType}" entity (found ${candidates.length}) \u2014 pass destinationType and ensure exactly one such entity is discoverable`
|
|
2258
|
+
);
|
|
2259
|
+
}
|
|
2260
|
+
return { entityType, entityUuid: candidates[0].entityUuid };
|
|
2261
|
+
}
|
|
2262
|
+
/** Final OFFLINE status stays as the tombstone; every other retained topic is cleared. */
|
|
2263
|
+
async unregister() {
|
|
2264
|
+
await this.publishStatus({ states: ["OFFLINE"] });
|
|
2265
|
+
for (const resource of RETAINED_RESOURCES) {
|
|
2266
|
+
await this.ctx.session.clearRetained(
|
|
2267
|
+
this.ctx.session.topicFor(this.ctx.ref, resource)
|
|
2268
|
+
);
|
|
2269
|
+
}
|
|
2270
|
+
}
|
|
2271
|
+
async publish(resource, payload) {
|
|
2272
|
+
await this.ctx.session.publishResource(
|
|
2273
|
+
this.ctx.ref,
|
|
2274
|
+
resource,
|
|
2275
|
+
messageKindFor(resource),
|
|
2276
|
+
payload
|
|
2277
|
+
);
|
|
2278
|
+
this.ctx.countPublish();
|
|
2279
|
+
}
|
|
2280
|
+
};
|
|
2281
|
+
|
|
2282
|
+
// src/types/actions.ts
|
|
2283
|
+
function detail(type, properties, opts = {}) {
|
|
2284
|
+
return {
|
|
2285
|
+
type,
|
|
2286
|
+
version: opts.version ?? PROTOCOL_VERSION,
|
|
2287
|
+
format: "ISO-21423",
|
|
2288
|
+
blocking: opts.blocking ?? true,
|
|
2289
|
+
atomic: opts.atomic ?? false,
|
|
2290
|
+
properties
|
|
2291
|
+
};
|
|
2292
|
+
}
|
|
2293
|
+
var cancelRequest = (props, opts) => detail("cancelRequest", { ...props }, opts);
|
|
2294
|
+
|
|
2295
|
+
// src/core/selfCheck.ts
|
|
2296
|
+
async function publishSelfCheck(session, ref, timeoutMs = 2e3) {
|
|
2297
|
+
const topic = session.topicFor(ref, "identity");
|
|
2298
|
+
let seen = false;
|
|
2299
|
+
let resolveEcho = () => {
|
|
2300
|
+
};
|
|
2301
|
+
const echo = new Promise((resolve) => {
|
|
2302
|
+
resolveEcho = resolve;
|
|
2303
|
+
});
|
|
2304
|
+
const sub = await session.subscribeTopic(topic, null, (raw) => {
|
|
2305
|
+
if (typeof raw === "string" && raw.length > 0) {
|
|
2306
|
+
seen = true;
|
|
2307
|
+
resolveEcho();
|
|
2308
|
+
}
|
|
2309
|
+
}, { qos: 1 });
|
|
2310
|
+
try {
|
|
2311
|
+
const timer = new Promise((resolve) => {
|
|
2312
|
+
const t = setTimeout(resolve, timeoutMs);
|
|
2313
|
+
t.unref?.();
|
|
2314
|
+
});
|
|
2315
|
+
await Promise.race([echo, timer]);
|
|
2316
|
+
if (!seen) {
|
|
2317
|
+
throw new AuthorizationDenied(
|
|
2318
|
+
`publish self-check failed: no retained identity echo on ${topic} \u2014 the broker ACL probably denies write access to this namespace (ND-15)`,
|
|
2319
|
+
topic
|
|
2320
|
+
);
|
|
2321
|
+
}
|
|
2322
|
+
} finally {
|
|
2323
|
+
await sub.unsubscribe();
|
|
2324
|
+
}
|
|
2325
|
+
}
|
|
2326
|
+
|
|
2327
|
+
// src/core/client.ts
|
|
2328
|
+
var sharedSequenceStore;
|
|
2329
|
+
function defaultSequenceStore() {
|
|
2330
|
+
return sharedSequenceStore ??= new FileSequenceStore();
|
|
2331
|
+
}
|
|
2332
|
+
var Iso21423Client = class _Iso21423Client {
|
|
2333
|
+
transport;
|
|
2334
|
+
security;
|
|
2335
|
+
validateOutbound;
|
|
2336
|
+
sourceId;
|
|
2337
|
+
sequenceStore;
|
|
2338
|
+
requestTimeoutMs;
|
|
2339
|
+
sessionPromise;
|
|
2340
|
+
session;
|
|
2341
|
+
cache;
|
|
2342
|
+
pendingCatalogListeners = [];
|
|
2343
|
+
defaultExecutionPolicy;
|
|
2344
|
+
selfEntities = /* @__PURE__ */ new Map();
|
|
2345
|
+
managedEntities = /* @__PURE__ */ new Map();
|
|
2346
|
+
trackedSubs = /* @__PURE__ */ new Set();
|
|
2347
|
+
inFlightRequests = /* @__PURE__ */ new Set();
|
|
2348
|
+
since;
|
|
2349
|
+
lastConnectionChange;
|
|
2350
|
+
subscriptionCount = 0;
|
|
2351
|
+
closed = false;
|
|
2352
|
+
counters = { published: 0, received: 0, validationWarnings: 0, rejections: 0 };
|
|
2353
|
+
listeners = {
|
|
2354
|
+
connection: [],
|
|
2355
|
+
"validation-warning": [],
|
|
2356
|
+
diagnostic: []
|
|
2357
|
+
};
|
|
2358
|
+
constructor(transport, opts) {
|
|
2359
|
+
this.transport = transport;
|
|
2360
|
+
this.security = opts.security;
|
|
2361
|
+
this.validateOutbound = opts.validateOutbound;
|
|
2362
|
+
this.sourceId = opts.sourceId;
|
|
2363
|
+
this.sequenceStore = opts.sequenceStore === null ? null : opts.sequenceStore ?? defaultSequenceStore();
|
|
2364
|
+
this.requestTimeoutMs = opts.requestTimeoutMs ?? 5e3;
|
|
2365
|
+
}
|
|
2366
|
+
static async connect(opts) {
|
|
2367
|
+
const hasTransport = opts.transport !== void 0;
|
|
2368
|
+
const hasUrl = opts.url !== void 0;
|
|
2369
|
+
if (hasTransport === hasUrl) {
|
|
2370
|
+
throw new Iso21423Error('Iso21423Client.connect requires exactly one of "transport" or "url"');
|
|
2371
|
+
}
|
|
2372
|
+
const transport = opts.transport ?? createMqttTransport(opts.url, { ...opts.security });
|
|
2373
|
+
return new _Iso21423Client(transport, opts);
|
|
2374
|
+
}
|
|
2375
|
+
// ---- registration -------------------------------------------------------
|
|
2376
|
+
/**
|
|
2377
|
+
* Registers this process's own entity: opens the session (arming the B.4 Last Will) if it
|
|
2378
|
+
* isn't open yet, and publishes the resulting identity. Must be the first operation on the
|
|
2379
|
+
* client (P-4) — if a session is already open under a different entity, throws rather than
|
|
2380
|
+
* silently registering under the wrong identity/will.
|
|
2381
|
+
*/
|
|
2382
|
+
async registerSelfEntity(reg) {
|
|
2383
|
+
const ref = { entityType: reg.entityType, entityUuid: reg.entityUuid };
|
|
2384
|
+
const session = await this.ensureSession(ref);
|
|
2385
|
+
if (session.entity.entityType !== ref.entityType || session.entity.entityUuid !== ref.entityUuid) {
|
|
2386
|
+
throw new Iso21423Error(
|
|
2387
|
+
"register the self entity before any other operation, so the B.4 Last Will can be armed at connect time (P-4)"
|
|
2388
|
+
);
|
|
2389
|
+
}
|
|
2390
|
+
const sequence = await this.openSequence(reg.entityUuid);
|
|
2391
|
+
const { ctx, bindSelf } = this.contextFor(ref, sequence);
|
|
2392
|
+
const handle = new EntityHandle(ctx, "self", reg);
|
|
2393
|
+
bindSelf(handle);
|
|
2394
|
+
await handle.publishIdentity(handle.identity());
|
|
2395
|
+
if (this.security?.selfCheck) await this.runSelfCheck(handle);
|
|
2396
|
+
this.selfEntities.set(reg.entityUuid, handle);
|
|
2397
|
+
return handle;
|
|
2398
|
+
}
|
|
2399
|
+
/**
|
|
2400
|
+
* Registers an entity managed on behalf of `managerUuid` (an already-registered self entity,
|
|
2401
|
+
* per B.5.2.4): publishes the managed entity's identity with `managedBy` set, and updates the
|
|
2402
|
+
* manager's own retained identity to include it in `manages`.
|
|
2403
|
+
*/
|
|
2404
|
+
async registerManagedEntity(managerUuid, reg) {
|
|
2405
|
+
const manager = this.selfEntities.get(managerUuid);
|
|
2406
|
+
if (!manager) {
|
|
2407
|
+
throw new Iso21423Error(
|
|
2408
|
+
`registerManagedEntity: "${managerUuid}" is not a registered self entity`
|
|
2409
|
+
);
|
|
2410
|
+
}
|
|
2411
|
+
const entityType = reg.entityType ?? "IMR";
|
|
2412
|
+
const ref = { entityType, entityUuid: reg.entityUuid };
|
|
2413
|
+
const sequence = await this.openSequence(reg.entityUuid);
|
|
2414
|
+
const { ctx, bindSelf } = this.contextFor(ref, sequence);
|
|
2415
|
+
const handle = new EntityHandle(ctx, "managed", { ...reg, entityType });
|
|
2416
|
+
bindSelf(handle);
|
|
2417
|
+
const identity = handle.identity();
|
|
2418
|
+
identity.capabilities.managedBy = managerUuid;
|
|
2419
|
+
await handle.publishIdentity(identity);
|
|
2420
|
+
const managerIdentity = manager.identity();
|
|
2421
|
+
const manages = [...managerIdentity.capabilities.manages ?? [], reg.entityUuid];
|
|
2422
|
+
await manager.updateIdentity({ capabilities: { ...managerIdentity.capabilities, manages } });
|
|
2423
|
+
const list = this.managedEntities.get(managerUuid) ?? [];
|
|
2424
|
+
list.push(handle);
|
|
2425
|
+
this.managedEntities.set(managerUuid, list);
|
|
2426
|
+
return handle;
|
|
2427
|
+
}
|
|
2428
|
+
listManagedEntities(managerUuid) {
|
|
2429
|
+
return [...this.managedEntities.get(managerUuid) ?? []];
|
|
2430
|
+
}
|
|
2431
|
+
/** @internal — FleetGateway.registerImr rollback (ND-15 self-check failure): drops a managed
|
|
2432
|
+
* entity's handle so listManagedEntities()/health() stop reporting it. */
|
|
2433
|
+
removeManagedEntity(managerUuid, entityUuid) {
|
|
2434
|
+
const list = this.managedEntities.get(managerUuid);
|
|
2435
|
+
if (!list) return;
|
|
2436
|
+
this.managedEntities.set(managerUuid, list.filter((h) => h.entityUuid !== entityUuid));
|
|
2437
|
+
}
|
|
2438
|
+
/** Set the client-wide default execution policy (P-2), overridable per entity handle. */
|
|
2439
|
+
setDefaultExecutionPolicy(policy) {
|
|
2440
|
+
this.defaultExecutionPolicy = policy;
|
|
2441
|
+
}
|
|
2442
|
+
// ---- observation --------------------------------------------------------
|
|
2443
|
+
/**
|
|
2444
|
+
* Deliberately does NOT go through `subscribeResource('identity', ...)`: the shared
|
|
2445
|
+
* `EntityCache` already owns the one identity-wildcard subscription (every client needs it,
|
|
2446
|
+
* per decision 3). A second, independent subscribeTopic() to the same filter would make the
|
|
2447
|
+
* fake broker (and a real one) redeliver retained identities twice over — this taps the
|
|
2448
|
+
* cache's own stream instead, replaying what it already knows plus every future update.
|
|
2449
|
+
*/
|
|
2450
|
+
async subscribeEntities(filter, handler) {
|
|
2451
|
+
await this.ensureSession();
|
|
2452
|
+
const cache = this.cache;
|
|
2453
|
+
const matches = (e) => filter.matches({ entityType: e.entityType, entityUuid: e.entityUuid });
|
|
2454
|
+
let active = true;
|
|
2455
|
+
for (const entry of cache.entities()) {
|
|
2456
|
+
if (matches(entry)) handler(entry.identity);
|
|
2457
|
+
}
|
|
2458
|
+
const listener = (entry) => {
|
|
2459
|
+
if (!active || !matches(entry)) return;
|
|
2460
|
+
this.counters.received++;
|
|
2461
|
+
handler(entry.identity);
|
|
2462
|
+
};
|
|
2463
|
+
cache.on("entity", listener);
|
|
2464
|
+
const topicFilters = Object.freeze(filter.topicFiltersFor("identity"));
|
|
2465
|
+
const sub = {
|
|
2466
|
+
topicFilters,
|
|
2467
|
+
get active() {
|
|
2468
|
+
return active;
|
|
2469
|
+
},
|
|
2470
|
+
async unsubscribe() {
|
|
2471
|
+
active = false;
|
|
2472
|
+
cache.off("entity", listener);
|
|
2473
|
+
},
|
|
2474
|
+
async [Symbol.asyncDispose]() {
|
|
2475
|
+
await sub.unsubscribe();
|
|
2476
|
+
}
|
|
2477
|
+
};
|
|
2478
|
+
return this.trackSubscription(sub);
|
|
2479
|
+
}
|
|
2480
|
+
/** Subscribes to a raw resource (not identity — see {@link subscribeEntities}) across every entity `filter` selects. */
|
|
2481
|
+
async subscribeResource(kind, filter, handler) {
|
|
2482
|
+
const session = await this.ensureSession();
|
|
2483
|
+
const topicFilters = filter.topicFiltersFor(kind);
|
|
2484
|
+
const parts = await Promise.all(topicFilters.map((f) => session.subscribeTopic(
|
|
2485
|
+
f,
|
|
2486
|
+
messageKindFor(kind),
|
|
2487
|
+
(msg, meta) => {
|
|
2488
|
+
this.counters.received++;
|
|
2489
|
+
handler({
|
|
2490
|
+
entityType: meta.entityType,
|
|
2491
|
+
entityUuid: meta.entityUuid,
|
|
2492
|
+
kind,
|
|
2493
|
+
topic: meta.topic,
|
|
2494
|
+
message: msg
|
|
2495
|
+
});
|
|
2496
|
+
}
|
|
2497
|
+
)));
|
|
2498
|
+
return this.trackSubscription(composeSubscription(topicFilters, parts));
|
|
2499
|
+
}
|
|
2500
|
+
/** Observes inbound requests matching `filter`, without participating in serving them (no admission/status effects). */
|
|
2501
|
+
async subscribeRequests(filter, handler) {
|
|
2502
|
+
const session = await this.ensureSession();
|
|
2503
|
+
const topicFilters = filter.topicFilters();
|
|
2504
|
+
const parts = await Promise.all(topicFilters.map((f) => session.subscribeTopic(
|
|
2505
|
+
f,
|
|
2506
|
+
"request",
|
|
2507
|
+
(msg, meta) => {
|
|
2508
|
+
if (!meta.requestUuid) return;
|
|
2509
|
+
this.counters.received++;
|
|
2510
|
+
handler({
|
|
2511
|
+
entityType: meta.entityType,
|
|
2512
|
+
entityUuid: meta.entityUuid,
|
|
2513
|
+
requestUuid: meta.requestUuid,
|
|
2514
|
+
request: msg,
|
|
2515
|
+
topic: meta.topic
|
|
2516
|
+
});
|
|
2517
|
+
}
|
|
2518
|
+
)));
|
|
2519
|
+
return this.trackSubscription(composeSubscription(topicFilters, parts));
|
|
2520
|
+
}
|
|
2521
|
+
/** Observes request status updates matching `filter`, e.g. for a fleet-wide activity dashboard. */
|
|
2522
|
+
async subscribeRequestStatus(filter, handler) {
|
|
2523
|
+
const session = await this.ensureSession();
|
|
2524
|
+
const topicFilters = filter.topicFilters();
|
|
2525
|
+
const parts = await Promise.all(topicFilters.map((f) => session.subscribeTopic(
|
|
2526
|
+
f,
|
|
2527
|
+
"requestStatus",
|
|
2528
|
+
(msg, meta) => {
|
|
2529
|
+
this.counters.received++;
|
|
2530
|
+
handler({
|
|
2531
|
+
entityType: meta.entityType,
|
|
2532
|
+
entityUuid: meta.entityUuid,
|
|
2533
|
+
kind: "requestStatus",
|
|
2534
|
+
topic: meta.topic,
|
|
2535
|
+
message: msg
|
|
2536
|
+
});
|
|
2537
|
+
}
|
|
2538
|
+
)));
|
|
2539
|
+
return this.trackSubscription(composeSubscription(topicFilters, parts));
|
|
2540
|
+
}
|
|
2541
|
+
/**
|
|
2542
|
+
* Retained-identity-only catalog (D-18). Deliberately await-free: callers get a live handle
|
|
2543
|
+
* immediately, and the graph fills in as retained `identity`/`disconnection` messages arrive
|
|
2544
|
+
* (opening the session — identity-less if none is open yet — happens in the background).
|
|
2545
|
+
*/
|
|
2546
|
+
discover() {
|
|
2547
|
+
void this.ensureSession().then(() => this.cache.watchDisconnections()).catch((err) => console.error("[Iso21423Client] discover(): failed to open session", err));
|
|
2548
|
+
return {
|
|
2549
|
+
entities: () => this.cache?.entities() ?? [],
|
|
2550
|
+
get: (uuid) => this.cache?.get(uuid),
|
|
2551
|
+
managedBy: (uuid) => this.cache?.managedBy(uuid) ?? [],
|
|
2552
|
+
on: (event, cb) => {
|
|
2553
|
+
if (this.cache) {
|
|
2554
|
+
this.cache.on(event, cb);
|
|
2555
|
+
} else {
|
|
2556
|
+
this.pendingCatalogListeners.push([event, cb]);
|
|
2557
|
+
}
|
|
2558
|
+
}
|
|
2559
|
+
};
|
|
2560
|
+
}
|
|
2561
|
+
// ---- misc -----------------------------------------------------------------
|
|
2562
|
+
/** Point-in-time snapshot of connection state, registered entities, subscription/traffic counters — see {@link ClientHealth}. */
|
|
2563
|
+
health() {
|
|
2564
|
+
return {
|
|
2565
|
+
connection: this.session?.connectionState ?? "closed",
|
|
2566
|
+
since: this.since ?? /* @__PURE__ */ new Date(0),
|
|
2567
|
+
lastConnectionChange: this.lastConnectionChange ?? this.since ?? /* @__PURE__ */ new Date(0),
|
|
2568
|
+
entities: {
|
|
2569
|
+
self: [...this.selfEntities.keys()],
|
|
2570
|
+
managed: [...this.managedEntities.values()].flat().map((h) => h.entityUuid)
|
|
2571
|
+
},
|
|
2572
|
+
subscriptions: this.subscriptionCount,
|
|
2573
|
+
activeRequests: { sent: this.inFlightRequests.size, serving: this.servingCount() },
|
|
2574
|
+
counters: { ...this.counters }
|
|
2575
|
+
};
|
|
2576
|
+
}
|
|
2577
|
+
on(event, cb) {
|
|
2578
|
+
this.listeners[event].push(cb);
|
|
2579
|
+
}
|
|
2580
|
+
/** Graceful shutdown: the will never fires (MemoryTransport.end() reports ungraceful:false). */
|
|
2581
|
+
async close(opts) {
|
|
2582
|
+
if (this.closed) return;
|
|
2583
|
+
this.closed = true;
|
|
2584
|
+
if (!this.sessionPromise) return;
|
|
2585
|
+
this.failAllInFlight();
|
|
2586
|
+
await Promise.all([...this.trackedSubs].map((s) => s.unsubscribe().catch(() => {
|
|
2587
|
+
})));
|
|
2588
|
+
const session = await this.sessionPromise;
|
|
2589
|
+
const timeoutMs = opts?.timeout ?? 5e3;
|
|
2590
|
+
await Promise.race([
|
|
2591
|
+
session.close(),
|
|
2592
|
+
new Promise((resolve) => {
|
|
2593
|
+
setTimeout(resolve, timeoutMs).unref?.();
|
|
2594
|
+
})
|
|
2595
|
+
]);
|
|
2596
|
+
}
|
|
2597
|
+
// ---- internals --------------------------------------------------------
|
|
2598
|
+
identitylessRef() {
|
|
2599
|
+
return { entityType: "client", entityUuid: this.sourceId ?? (0, import_node_crypto2.randomUUID)() };
|
|
2600
|
+
}
|
|
2601
|
+
async ensureSession(self) {
|
|
2602
|
+
if (!this.sessionPromise) this.sessionPromise = this.openSession(self);
|
|
2603
|
+
return this.sessionPromise;
|
|
2604
|
+
}
|
|
2605
|
+
async openSession(self) {
|
|
2606
|
+
const armWill = self !== void 0;
|
|
2607
|
+
const entity = self ?? this.identitylessRef();
|
|
2608
|
+
const session = await Iso21423Session.connect({
|
|
2609
|
+
transport: this.transport,
|
|
2610
|
+
entity,
|
|
2611
|
+
credentials: this.security && {
|
|
2612
|
+
username: this.security.username,
|
|
2613
|
+
password: this.security.password
|
|
2614
|
+
},
|
|
2615
|
+
validateOutbound: this.validateOutbound,
|
|
2616
|
+
armWill
|
|
2617
|
+
});
|
|
2618
|
+
if (!armWill) this.diagnostic("will-not-armed");
|
|
2619
|
+
this.session = session;
|
|
2620
|
+
this.since = /* @__PURE__ */ new Date();
|
|
2621
|
+
this.lastConnectionChange = this.since;
|
|
2622
|
+
session.on("connection", (s) => {
|
|
2623
|
+
this.lastConnectionChange = /* @__PURE__ */ new Date();
|
|
2624
|
+
if (s === "offline") this.failAllInFlight();
|
|
2625
|
+
for (const cb of this.listeners.connection) cb(s);
|
|
2626
|
+
});
|
|
2627
|
+
session.on("validation-warning", (w) => {
|
|
2628
|
+
this.counters.validationWarnings++;
|
|
2629
|
+
for (const cb of this.listeners["validation-warning"]) cb(w);
|
|
2630
|
+
});
|
|
2631
|
+
this.cache = new EntityCache(session);
|
|
2632
|
+
await this.cache.start();
|
|
2633
|
+
for (const [event, cb] of this.pendingCatalogListeners) this.cache.on(event, cb);
|
|
2634
|
+
this.pendingCatalogListeners = [];
|
|
2635
|
+
return session;
|
|
2636
|
+
}
|
|
2637
|
+
async openSequence(entityUuid) {
|
|
2638
|
+
const store = this.sequenceStore === null ? void 0 : this.sequenceStore;
|
|
2639
|
+
return SequenceCounter.open(entityUuid, store, () => this.diagnostic("sequence-store-unavailable"));
|
|
2640
|
+
}
|
|
2641
|
+
/**
|
|
2642
|
+
* `bindSelf` must be called with the `EntityHandle` built from the returned `ctx`, right after
|
|
2643
|
+
* construction — `sendCancel` re-enters `EntityHandle.sendRequest` (cancel = a new request,
|
|
2644
|
+
* D-02) and `contextFor` necessarily runs before that `EntityHandle` exists.
|
|
2645
|
+
*/
|
|
2646
|
+
contextFor(ref, sequence) {
|
|
2647
|
+
const box = {};
|
|
2648
|
+
const ctx = {
|
|
2649
|
+
session: this.session,
|
|
2650
|
+
ref,
|
|
2651
|
+
sequence,
|
|
2652
|
+
catalog: this.cache,
|
|
2653
|
+
diagnostic: (code, detail2) => this.diagnostic(code, detail2),
|
|
2654
|
+
countPublish: () => {
|
|
2655
|
+
this.counters.published++;
|
|
2656
|
+
},
|
|
2657
|
+
requestTimeoutMs: this.requestTimeoutMs,
|
|
2658
|
+
sendCancel: async (handle, actionId) => {
|
|
2659
|
+
const destRef = handle.internalDestRef();
|
|
2660
|
+
await box.handle.sendRequest({
|
|
2661
|
+
destination: destRef.entityUuid,
|
|
2662
|
+
destinationType: destRef.entityType,
|
|
2663
|
+
details: [cancelRequest({
|
|
2664
|
+
source: handle.sourceUuid,
|
|
2665
|
+
requestId: handle.sequenceId,
|
|
2666
|
+
...actionId !== void 0 ? { actionId } : {}
|
|
2667
|
+
})],
|
|
2668
|
+
requireCapability: false
|
|
2669
|
+
});
|
|
2670
|
+
},
|
|
2671
|
+
trackInFlight: (handle) => {
|
|
2672
|
+
this.inFlightRequests.add(handle);
|
|
2673
|
+
const drop = () => {
|
|
2674
|
+
this.inFlightRequests.delete(handle);
|
|
2675
|
+
};
|
|
2676
|
+
handle.completion().then(drop, drop);
|
|
2677
|
+
},
|
|
2678
|
+
getDefaultExecutionPolicy: () => {
|
|
2679
|
+
return this.defaultExecutionPolicy ?? DEFAULT_EXECUTION_POLICY;
|
|
2680
|
+
},
|
|
2681
|
+
getExecutionPolicy: () => {
|
|
2682
|
+
return box.handle.getExecutionPolicy();
|
|
2683
|
+
}
|
|
2684
|
+
};
|
|
2685
|
+
return { ctx, bindSelf: (handle) => {
|
|
2686
|
+
box.handle = handle;
|
|
2687
|
+
} };
|
|
2688
|
+
}
|
|
2689
|
+
failAllInFlight() {
|
|
2690
|
+
for (const handle of [...this.inFlightRequests]) handle.failFast();
|
|
2691
|
+
}
|
|
2692
|
+
/** Identity-echo publish self-check (ND-15): confirms our own retained identity round-trips.
|
|
2693
|
+
* Shares its implementation with FleetGateway's self-check (default ON there, OFF here). */
|
|
2694
|
+
async runSelfCheck(handle) {
|
|
2695
|
+
await publishSelfCheck(this.session, handle.ctx.ref, this.security?.selfCheckTimeoutMs);
|
|
2696
|
+
}
|
|
2697
|
+
diagnostic(code, detail2) {
|
|
2698
|
+
if (code === "dispatch-rejected") this.counters.rejections++;
|
|
2699
|
+
const event = { code, detail: detail2, at: /* @__PURE__ */ new Date() };
|
|
2700
|
+
for (const cb of this.listeners.diagnostic) cb(event);
|
|
2701
|
+
}
|
|
2702
|
+
/** ND-18: sum of servingCount() across every self and managed handle. */
|
|
2703
|
+
servingCount() {
|
|
2704
|
+
let n = 0;
|
|
2705
|
+
for (const handle of this.selfEntities.values()) n += handle.servingCount();
|
|
2706
|
+
for (const list of this.managedEntities.values()) for (const handle of list) n += handle.servingCount();
|
|
2707
|
+
return n;
|
|
2708
|
+
}
|
|
2709
|
+
/** Wraps a raw {@link Subscription} to maintain `subscriptionCount` and the tracked-subs set that `close()` drains. */
|
|
2710
|
+
trackSubscription(sub) {
|
|
2711
|
+
this.subscriptionCount += sub.topicFilters.length;
|
|
2712
|
+
let counted = true;
|
|
2713
|
+
const wrapped = {
|
|
2714
|
+
topicFilters: sub.topicFilters,
|
|
2715
|
+
get active() {
|
|
2716
|
+
return sub.active;
|
|
2717
|
+
},
|
|
2718
|
+
unsubscribe: async () => {
|
|
2719
|
+
this.trackedSubs.delete(wrapped);
|
|
2720
|
+
await sub.unsubscribe();
|
|
2721
|
+
if (counted) {
|
|
2722
|
+
counted = false;
|
|
2723
|
+
this.subscriptionCount -= sub.topicFilters.length;
|
|
2724
|
+
}
|
|
2725
|
+
},
|
|
2726
|
+
[Symbol.asyncDispose]: async () => {
|
|
2727
|
+
await wrapped.unsubscribe();
|
|
2728
|
+
}
|
|
2729
|
+
};
|
|
2730
|
+
this.trackedSubs.add(wrapped);
|
|
2731
|
+
return wrapped;
|
|
2732
|
+
}
|
|
2733
|
+
};
|
|
2734
|
+
|
|
2735
|
+
// src/gateway/janitor.ts
|
|
2736
|
+
var RetainedRequestJanitor = class {
|
|
2737
|
+
constructor(session, graceMs, onCleared) {
|
|
2738
|
+
this.session = session;
|
|
2739
|
+
this.graceMs = graceMs;
|
|
2740
|
+
this.onCleared = onCleared;
|
|
2741
|
+
}
|
|
2742
|
+
session;
|
|
2743
|
+
graceMs;
|
|
2744
|
+
onCleared;
|
|
2745
|
+
timers = /* @__PURE__ */ new Set();
|
|
2746
|
+
/** Schedules `requestTopic` to be force-cleared after the grace period; the clear itself is idempotent, so overlapping/duplicate `note()` calls are harmless. */
|
|
2747
|
+
note(requestTopic2) {
|
|
2748
|
+
const timer = setTimeout(() => {
|
|
2749
|
+
this.timers.delete(timer);
|
|
2750
|
+
void this.session.clearRetained(requestTopic2).then(() => this.onCleared(requestTopic2)).catch(() => {
|
|
2751
|
+
});
|
|
2752
|
+
}, this.graceMs);
|
|
2753
|
+
timer.unref?.();
|
|
2754
|
+
this.timers.add(timer);
|
|
2755
|
+
}
|
|
2756
|
+
dispose() {
|
|
2757
|
+
for (const t of this.timers) clearTimeout(t);
|
|
2758
|
+
this.timers.clear();
|
|
2759
|
+
}
|
|
2760
|
+
};
|
|
2761
|
+
|
|
2762
|
+
// src/gateway/fleetGateway.ts
|
|
2763
|
+
var DEFAULT_JANITOR_GRACE_MS = 3e4;
|
|
2764
|
+
var FleetGateway = class _FleetGateway {
|
|
2765
|
+
constructor(client, imrfm, selfCheckEnabled, selfCheckTimeoutMs) {
|
|
2766
|
+
this.client = client;
|
|
2767
|
+
this.imrfm = imrfm;
|
|
2768
|
+
this.selfCheckEnabled = selfCheckEnabled;
|
|
2769
|
+
this.selfCheckTimeoutMs = selfCheckTimeoutMs;
|
|
2770
|
+
}
|
|
2771
|
+
client;
|
|
2772
|
+
imrfm;
|
|
2773
|
+
selfCheckEnabled;
|
|
2774
|
+
selfCheckTimeoutMs;
|
|
2775
|
+
imrHandles = /* @__PURE__ */ new Map();
|
|
2776
|
+
// Provenance tracking for R6: the core-level ActionExecutor only knows "a handler for this type
|
|
2777
|
+
// exists or not" — it has no notion of "fleet-wide" vs "per-imr" scope. These two maps let the
|
|
2778
|
+
// gateway apply its own override rule (same-scope re-registration needs override:true; a
|
|
2779
|
+
// per-imr registration shadowing a fleet-wide one never does) while always calling the
|
|
2780
|
+
// underlying `EntityHandle.onRequest` with `override: true` so the core-level guard never trips
|
|
2781
|
+
// on the gateway's own layering.
|
|
2782
|
+
fleetHandlers = /* @__PURE__ */ new Map();
|
|
2783
|
+
perImrHandlerTypes = /* @__PURE__ */ new Set();
|
|
2784
|
+
janitor;
|
|
2785
|
+
dispatchCb;
|
|
2786
|
+
/**
|
|
2787
|
+
* Connects the underlying client, registers the IMRFM's own identity (arming its Last Will,
|
|
2788
|
+
* decision 1), runs the gateway's own publish self-check (default on, ND-15) unless
|
|
2789
|
+
* `security.selfCheck` is false, and — unless `janitor.enabled` is false — starts the
|
|
2790
|
+
* retained-request janitor and wires the empty-destination dispatch interceptor (ND-12).
|
|
2791
|
+
*/
|
|
2792
|
+
static async connect(opts) {
|
|
2793
|
+
const client = await Iso21423Client.connect({
|
|
2794
|
+
transport: opts.transport,
|
|
2795
|
+
url: opts.url,
|
|
2796
|
+
// Deliberately NOT forwarding security.selfCheck/selfCheckTimeoutMs: the gateway runs its
|
|
2797
|
+
// own self-check below (default ON) instead of the client's own (default OFF) — running
|
|
2798
|
+
// both would just double the identity-echo round trip.
|
|
2799
|
+
security: opts.security && {
|
|
2800
|
+
username: opts.security.username,
|
|
2801
|
+
password: opts.security.password,
|
|
2802
|
+
tls: opts.security.tls
|
|
2803
|
+
},
|
|
2804
|
+
validateOutbound: opts.validateOutbound,
|
|
2805
|
+
sequenceStore: opts.sequenceStore,
|
|
2806
|
+
requestTimeoutMs: opts.requestTimeoutMs
|
|
2807
|
+
});
|
|
2808
|
+
const imrfm = await client.registerSelfEntity({
|
|
2809
|
+
entityUuid: opts.imrfm.id,
|
|
2810
|
+
entityType: "IMRFM",
|
|
2811
|
+
manufacturerName: opts.imrfm.manufacturerName,
|
|
2812
|
+
details: opts.imrfm.details,
|
|
2813
|
+
capabilities: { provides: opts.imrfm.provides ?? [], accepts: opts.imrfm.accepts ?? [] }
|
|
2814
|
+
});
|
|
2815
|
+
const gateway = new _FleetGateway(
|
|
2816
|
+
client,
|
|
2817
|
+
imrfm,
|
|
2818
|
+
opts.security?.selfCheck !== false,
|
|
2819
|
+
opts.security?.selfCheckTimeoutMs
|
|
2820
|
+
);
|
|
2821
|
+
if (gateway.selfCheckEnabled) {
|
|
2822
|
+
await publishSelfCheck(imrfm.ctx.session, imrfm.ctx.ref, gateway.selfCheckTimeoutMs);
|
|
2823
|
+
}
|
|
2824
|
+
if (opts.janitor?.enabled !== false) {
|
|
2825
|
+
const graceMs = opts.janitor?.graceMs ?? DEFAULT_JANITOR_GRACE_MS;
|
|
2826
|
+
gateway.janitor = new RetainedRequestJanitor(
|
|
2827
|
+
imrfm.ctx.session,
|
|
2828
|
+
graceMs,
|
|
2829
|
+
(topic) => imrfm.ctx.diagnostic("janitor-cleared", { topic })
|
|
2830
|
+
);
|
|
2831
|
+
await imrfm.onRequestSettled((topic) => gateway.janitor.note(topic));
|
|
2832
|
+
}
|
|
2833
|
+
await imrfm.setDispatchInterceptor((request) => gateway.resolveDispatch(request));
|
|
2834
|
+
await imrfm.setManagedExecutorsHook(() => gateway.imrs().map((h) => h.dispatchTarget()?.executor).filter((e) => e !== void 0));
|
|
2835
|
+
return gateway;
|
|
2836
|
+
}
|
|
2837
|
+
/**
|
|
2838
|
+
* Registers a new managed IMR under this IMRFM: creates its `EntityHandle`, wires it into the
|
|
2839
|
+
* janitor, replays every fleet-wide `onRequest` handler onto it, and (if the gateway's self-check
|
|
2840
|
+
* is enabled) publishes a self-check for it. On self-check failure, rolls back the local
|
|
2841
|
+
* bookkeeping (handle map and the manager's `manages` list) before rethrowing — nothing is
|
|
2842
|
+
* retained on the broker to undo, since a denied publish never lands there (ND-15).
|
|
2843
|
+
*/
|
|
2844
|
+
async registerImr(reg) {
|
|
2845
|
+
const handle = await this.client.registerManagedEntity(this.imrfm.entityUuid, {
|
|
2846
|
+
entityUuid: reg.id,
|
|
2847
|
+
entityType: "IMR",
|
|
2848
|
+
manufacturerName: reg.manufacturerName ?? this.imrfm.identity().manufacturerName,
|
|
2849
|
+
details: reg.identity,
|
|
2850
|
+
capabilities: { accepts: reg.accepts ?? [], provides: reg.provides ?? [] },
|
|
2851
|
+
executionPolicy: reg.executionPolicy
|
|
2852
|
+
});
|
|
2853
|
+
if (this.janitor) await handle.onRequestSettled((topic) => this.janitor.note(topic));
|
|
2854
|
+
for (const [type, handler] of this.fleetHandlers) handle.onRequest(type, handler, { override: true });
|
|
2855
|
+
this.imrHandles.set(reg.id, handle);
|
|
2856
|
+
if (this.selfCheckEnabled) {
|
|
2857
|
+
try {
|
|
2858
|
+
await publishSelfCheck(handle.ctx.session, handle.ctx.ref, this.selfCheckTimeoutMs);
|
|
2859
|
+
} catch (err) {
|
|
2860
|
+
this.imrHandles.delete(reg.id);
|
|
2861
|
+
this.client.removeManagedEntity(this.imrfm.entityUuid, reg.id);
|
|
2862
|
+
const identity = this.imrfm.identity();
|
|
2863
|
+
const manages = (identity.capabilities.manages ?? []).filter((uuid) => uuid !== reg.id);
|
|
2864
|
+
await this.imrfm.updateIdentity({ capabilities: { ...identity.capabilities, manages } });
|
|
2865
|
+
throw err;
|
|
2866
|
+
}
|
|
2867
|
+
}
|
|
2868
|
+
return handle;
|
|
2869
|
+
}
|
|
2870
|
+
/** Unregisters and removes a managed IMR (no-op if unknown), and drops it from the IMRFM's `manages` list. */
|
|
2871
|
+
async unregisterImr(id) {
|
|
2872
|
+
const handle = this.imrHandles.get(id);
|
|
2873
|
+
if (!handle) return;
|
|
2874
|
+
await handle.unregister();
|
|
2875
|
+
this.imrHandles.delete(id);
|
|
2876
|
+
const identity = this.imrfm.identity();
|
|
2877
|
+
const manages = (identity.capabilities.manages ?? []).filter((uuid) => uuid !== id);
|
|
2878
|
+
await this.imrfm.updateIdentity({ capabilities: { ...identity.capabilities, manages } });
|
|
2879
|
+
}
|
|
2880
|
+
imrs() {
|
|
2881
|
+
return [...this.imrHandles.values()];
|
|
2882
|
+
}
|
|
2883
|
+
/**
|
|
2884
|
+
* Registers an action handler either fleet-wide (default: applied to every current and future
|
|
2885
|
+
* IMR, R6) or scoped to one `imr`, where it shadows a fleet-wide handler for the same type.
|
|
2886
|
+
* Re-registering the same scope for the same type throws unless `override: true` is passed.
|
|
2887
|
+
*/
|
|
2888
|
+
onRequest(type, handler, opts) {
|
|
2889
|
+
const asHandler = handler;
|
|
2890
|
+
if (opts?.imr) {
|
|
2891
|
+
const handle = this.imrHandles.get(opts.imr);
|
|
2892
|
+
if (!handle) throw new Iso21423Error(`FleetGateway.onRequest: unknown imr "${opts.imr}"`);
|
|
2893
|
+
const key = `${opts.imr}:${type}`;
|
|
2894
|
+
if (this.perImrHandlerTypes.has(key) && !opts.override) {
|
|
2895
|
+
throw new Iso21423Error(
|
|
2896
|
+
`FleetGateway.onRequest: a per-imr handler for "${type}" on "${opts.imr}" is already registered \u2014 pass { override: true } to replace it`
|
|
2897
|
+
);
|
|
2898
|
+
}
|
|
2899
|
+
this.perImrHandlerTypes.add(key);
|
|
2900
|
+
handle.onRequest(type, asHandler, { override: true });
|
|
2901
|
+
return;
|
|
2902
|
+
}
|
|
2903
|
+
if (this.fleetHandlers.has(type) && !opts?.override) {
|
|
2904
|
+
throw new Iso21423Error(
|
|
2905
|
+
`FleetGateway.onRequest: a fleet-wide handler for "${type}" is already registered \u2014 pass { override: true } to replace it`
|
|
2906
|
+
);
|
|
2907
|
+
}
|
|
2908
|
+
this.fleetHandlers.set(type, asHandler);
|
|
2909
|
+
this.imrfm.onRequest(type, asHandler, { override: true });
|
|
2910
|
+
for (const handle of this.imrHandles.values()) handle.onRequest(type, asHandler, { override: true });
|
|
2911
|
+
}
|
|
2912
|
+
/** Sets the callback used to pick a target IMR for a request with an empty `destination` (ND-12); return `null` to decline dispatch. */
|
|
2913
|
+
onDispatch(cb) {
|
|
2914
|
+
this.dispatchCb = cb;
|
|
2915
|
+
}
|
|
2916
|
+
/** Graceful shutdown: managed handles are NOT unregistered — a fleet restart should not erase
|
|
2917
|
+
* the fleet's retained state; call `unregisterImr` explicitly for that. */
|
|
2918
|
+
async close(opts) {
|
|
2919
|
+
this.janitor?.dispose();
|
|
2920
|
+
await this.client.close(opts);
|
|
2921
|
+
}
|
|
2922
|
+
/** Invokes the `onDispatch` callback (if set) and resolves its chosen uuid to a live IMR's dispatch target. */
|
|
2923
|
+
resolveDispatch(request) {
|
|
2924
|
+
if (!this.dispatchCb) return null;
|
|
2925
|
+
const uuid = this.dispatchCb(request, this.imrs());
|
|
2926
|
+
if (!uuid) return null;
|
|
2927
|
+
const handle = this.imrHandles.get(uuid);
|
|
2928
|
+
return handle?.dispatchTarget() ?? null;
|
|
2929
|
+
}
|
|
2930
|
+
};
|
|
2931
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
2932
|
+
0 && (module.exports = {
|
|
2933
|
+
FleetGateway,
|
|
2934
|
+
RetainedRequestJanitor,
|
|
2935
|
+
publishSelfCheck
|
|
2936
|
+
});
|
|
2937
|
+
//# sourceMappingURL=gateway.cjs.map
|