iii-browser-sdk 0.24.6 → 0.25.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +111 -11
- package/dist/helpers.cjs +3 -1
- package/dist/helpers.cjs.map +1 -1
- package/dist/helpers.d.cts +3 -1
- package/dist/helpers.d.cts.map +1 -1
- package/dist/helpers.d.mts +3 -1
- package/dist/helpers.d.mts.map +1 -1
- package/dist/helpers.mjs +3 -1
- package/dist/helpers.mjs.map +1 -1
- package/dist/index.cjs +2872 -119
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +18 -4
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +18 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2871 -120
- package/dist/index.mjs.map +1 -1
- package/dist/stream.d.cts +87 -17
- package/dist/stream.d.cts.map +1 -1
- package/dist/stream.d.mts +87 -17
- package/dist/stream.d.mts.map +1 -1
- package/dist/{types-DeNafz-M.d.mts → types-BVi8fWCt.d.cts} +501 -7
- package/dist/types-BVi8fWCt.d.cts.map +1 -0
- package/dist/{types-fqr5SRfu.d.cts → types-D9XSr_QK.d.mts} +501 -7
- package/dist/types-D9XSr_QK.d.mts.map +1 -0
- package/dist/{utils-CJV1pMqe.cjs → utils-Cy-Lu8WQ.cjs} +60 -8
- package/dist/utils-Cy-Lu8WQ.cjs.map +1 -0
- package/dist/{utils-nQQPFFRM.mjs → utils-CyT9CwWA.mjs} +49 -9
- package/dist/utils-CyT9CwWA.mjs.map +1 -0
- package/package.json +3 -3
- package/dist/types-DeNafz-M.d.mts.map +0 -1
- package/dist/types-fqr5SRfu.d.cts.map +0 -1
- package/dist/utils-CJV1pMqe.cjs.map +0 -1
- package/dist/utils-nQQPFFRM.mjs.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_utils = require('./utils-
|
|
2
|
+
const require_utils = require('./utils-Cy-Lu8WQ.cjs');
|
|
3
3
|
|
|
4
4
|
//#region src/errors.ts
|
|
5
5
|
/**
|
|
@@ -18,6 +18,48 @@ var RegistrationRejectedError = class extends Error {
|
|
|
18
18
|
this.owner_worker_id = init.owner_worker_id;
|
|
19
19
|
}
|
|
20
20
|
};
|
|
21
|
+
/**
|
|
22
|
+
* An error the SDK raises itself for an invocation, with a machine-readable
|
|
23
|
+
* `code`: observe delivery errors (`NOT_OWNER_DELIVERED`,
|
|
24
|
+
* `OBSERVER_NOT_ACTIVE`, `FILTERS_NOT_MATCHED`) and an invalid observe
|
|
25
|
+
* descriptor (`INVALID_OBSERVE_DESCRIPTOR`). Mirrors the Node SDK.
|
|
26
|
+
*
|
|
27
|
+
* A call the engine answers with an error still rejects with the engine's
|
|
28
|
+
* error body (`{ code, message, stacktrace? }`), as in earlier releases, and
|
|
29
|
+
* so does a locally dispatched call whose handler throws: both paths reject
|
|
30
|
+
* with the same value.
|
|
31
|
+
*/
|
|
32
|
+
var InvocationError = class extends Error {
|
|
33
|
+
constructor(init) {
|
|
34
|
+
super(`${init.code}: ${init.message}`);
|
|
35
|
+
this.name = "InvocationError";
|
|
36
|
+
this.code = init.code;
|
|
37
|
+
this.function_id = init.function_id;
|
|
38
|
+
this.stacktrace = init.stacktrace;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Thrown by an `onObserverAdded` hook to reject an observer with a code of
|
|
43
|
+
* its own (`HTTP_ROUTE_CONFLICT`, `INVALID_CRON_EXPRESSION`, ...); any other
|
|
44
|
+
* error rejects it with `OBSERVE_REJECTED`. Also the error `ObserverHandle.ready()`
|
|
45
|
+
* rejects with when the observer turns `error` or `disposed`.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```typescript
|
|
49
|
+
* onObserverAdded(obs) {
|
|
50
|
+
* if (!isValidCron(obs.args.expression)) {
|
|
51
|
+
* throw new ObserveRejection('INVALID_CRON_EXPRESSION', 'invalid day-of-week field')
|
|
52
|
+
* }
|
|
53
|
+
* }
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
var ObserveRejection = class extends Error {
|
|
57
|
+
constructor(code, message) {
|
|
58
|
+
super(message);
|
|
59
|
+
this.name = "ObserveRejection";
|
|
60
|
+
this.code = code;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
21
63
|
|
|
22
64
|
//#endregion
|
|
23
65
|
//#region src/iii-constants.ts
|
|
@@ -25,40 +67,2190 @@ var RegistrationRejectedError = class extends Error {
|
|
|
25
67
|
* Constants for the III module.
|
|
26
68
|
*/
|
|
27
69
|
/**
|
|
28
|
-
* Engine function paths for internal operations.
|
|
29
|
-
*
|
|
30
|
-
* Naming note: `LIST_TRIGGERS` / `INFO_TRIGGERS` cover trigger TYPES
|
|
31
|
-
* (templates). `LIST_REGISTERED_TRIGGERS` / `INFO_REGISTERED_TRIGGERS`
|
|
32
|
-
* cover trigger INSTANCES (subscriber rows). The old
|
|
33
|
-
* `engine::trigger-types::list` builtin has been removed and is now
|
|
34
|
-
* served by `engine::triggers::list`.
|
|
70
|
+
* Engine function paths for internal operations.
|
|
71
|
+
*
|
|
72
|
+
* Naming note: `LIST_TRIGGERS` / `INFO_TRIGGERS` cover trigger TYPES
|
|
73
|
+
* (templates). `LIST_REGISTERED_TRIGGERS` / `INFO_REGISTERED_TRIGGERS`
|
|
74
|
+
* cover trigger INSTANCES (subscriber rows). The old
|
|
75
|
+
* `engine::trigger-types::list` builtin has been removed and is now
|
|
76
|
+
* served by `engine::triggers::list`.
|
|
77
|
+
*/
|
|
78
|
+
const EngineFunctions = {
|
|
79
|
+
LIST_FUNCTIONS: "engine::functions::list",
|
|
80
|
+
INFO_FUNCTIONS: "engine::functions::info",
|
|
81
|
+
LIST_WORKERS: "engine::workers::list",
|
|
82
|
+
INFO_WORKERS: "engine::workers::info",
|
|
83
|
+
LIST_TRIGGERS: "engine::triggers::list",
|
|
84
|
+
INFO_TRIGGERS: "engine::triggers::info",
|
|
85
|
+
LIST_REGISTERED_TRIGGERS: "engine::registered-triggers::list",
|
|
86
|
+
INFO_REGISTERED_TRIGGERS: "engine::registered-triggers::info",
|
|
87
|
+
REGISTER_WORKER: "engine::workers::register"
|
|
88
|
+
};
|
|
89
|
+
/** Engine trigger types */
|
|
90
|
+
const EngineTriggers = { FUNCTIONS_AVAILABLE: "engine::functions-available" };
|
|
91
|
+
/** Default reconnection configuration */
|
|
92
|
+
const DEFAULT_BRIDGE_RECONNECTION_CONFIG = {
|
|
93
|
+
initialDelayMs: 1e3,
|
|
94
|
+
maxDelayMs: 3e4,
|
|
95
|
+
backoffMultiplier: 2,
|
|
96
|
+
jitterFactor: .3,
|
|
97
|
+
maxRetries: -1
|
|
98
|
+
};
|
|
99
|
+
/** Default invocation timeout in milliseconds */
|
|
100
|
+
const DEFAULT_INVOCATION_TIMEOUT_MS = 3e4;
|
|
101
|
+
|
|
102
|
+
//#endregion
|
|
103
|
+
//#region ../iii/src/filter/errors.ts
|
|
104
|
+
const MAX_ENCODED_BYTES = 8192;
|
|
105
|
+
/** Numeric literals in a filter must satisfy `|n| <= 2^53`. */
|
|
106
|
+
const MAX_SAFE_LITERAL = 2 ** 53;
|
|
107
|
+
/** A filter the language rejects. `code` is the protocol error code (protocol.md §4). */
|
|
108
|
+
var FilterError = class FilterError extends Error {
|
|
109
|
+
constructor(code, message) {
|
|
110
|
+
super(message);
|
|
111
|
+
this.name = "FilterError";
|
|
112
|
+
this.code = code;
|
|
113
|
+
}
|
|
114
|
+
static invalid(message) {
|
|
115
|
+
return new FilterError("INVALID_FILTER", message);
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
//#endregion
|
|
120
|
+
//#region ../iii/src/filter/json.ts
|
|
121
|
+
/**
|
|
122
|
+
* The filter as JSON. A filter written in JavaScript must already be JSON:
|
|
123
|
+
* `JSON.stringify` would silently drop or rewrite what is not (an `undefined`
|
|
124
|
+
* clause disappears, a `Map` or a class instance becomes `{}`, `NaN` becomes
|
|
125
|
+
* `null`), and a dropped clause turns a filter into one that matches more.
|
|
126
|
+
* So every value is checked first, and anything JSON would not carry as it is
|
|
127
|
+
* is `INVALID_FILTER`, naming where it is.
|
|
128
|
+
*
|
|
129
|
+
* Pure TypeScript with no Node.js APIs: the browser SDK uses this file too.
|
|
130
|
+
*/
|
|
131
|
+
function where(at) {
|
|
132
|
+
return at === "" ? "the filter" : `\`${at}\``;
|
|
133
|
+
}
|
|
134
|
+
/** A string serde_json would refuse (a lone surrogate) is refused here too. */
|
|
135
|
+
function checkString(s, at, what) {
|
|
136
|
+
for (let i = 0; i < s.length; i++) {
|
|
137
|
+
const c = s.charCodeAt(i);
|
|
138
|
+
if (c < 55296 || c > 57343) continue;
|
|
139
|
+
const next = s.charCodeAt(i + 1);
|
|
140
|
+
if (c <= 56319 && next >= 56320 && next <= 57343) {
|
|
141
|
+
i++;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
throw FilterError.invalid(`${where(at)}: ${what} holds a lone UTF-16 surrogate, which is not valid Unicode`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/** An object JSON writes member by member: a prototype-less object or one whose prototype is a realm's `Object.prototype`. */
|
|
148
|
+
function isPlainObject(v) {
|
|
149
|
+
const proto = Object.getPrototypeOf(v);
|
|
150
|
+
return proto === null || Object.getPrototypeOf(proto) === null;
|
|
151
|
+
}
|
|
152
|
+
function describe(v) {
|
|
153
|
+
if (typeof v === "number") return String(v);
|
|
154
|
+
if (typeof v !== "object" || v === null) return typeof v;
|
|
155
|
+
const name = Object.getPrototypeOf(v)?.constructor?.name;
|
|
156
|
+
return typeof name === "string" && name !== "" ? `a ${name}` : "an object";
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Checks that `src` is JSON as it stands: plain objects (own enumerable data
|
|
160
|
+
* properties, string keys) and dense arrays of strings, finite numbers within
|
|
161
|
+
* ±2^53, booleans and `null`, without cycles (a value shared by two members
|
|
162
|
+
* is fine), nested at most MAX_JSON_DEPTH arrays / objects. Iterative, and
|
|
163
|
+
* bounded by the encoded size limit (every JSON value takes at least one
|
|
164
|
+
* byte, so a value shared many times over is refused quickly).
|
|
165
|
+
*/
|
|
166
|
+
function checkJson(src) {
|
|
167
|
+
const stack = [{
|
|
168
|
+
value: src,
|
|
169
|
+
at: "",
|
|
170
|
+
depth: 1
|
|
171
|
+
}];
|
|
172
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
173
|
+
let visited = 0;
|
|
174
|
+
while (stack.length > 0) {
|
|
175
|
+
const { value, at, depth, leave } = stack.pop();
|
|
176
|
+
if (leave) {
|
|
177
|
+
ancestors.delete(value);
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
if (++visited > 8192) throw FilterError.invalid(`the filter encodes to more than ${MAX_ENCODED_BYTES} bytes`);
|
|
181
|
+
switch (typeof value) {
|
|
182
|
+
case "boolean": continue;
|
|
183
|
+
case "string":
|
|
184
|
+
checkString(value, at, "a string");
|
|
185
|
+
continue;
|
|
186
|
+
case "number":
|
|
187
|
+
if (!Number.isFinite(value)) throw FilterError.invalid(`${where(at)}: ${value} is not a JSON number`);
|
|
188
|
+
if (Math.abs(value) > MAX_SAFE_LITERAL) throw FilterError.invalid(`${where(at)}: the number ${value} is outside ±2^53`);
|
|
189
|
+
continue;
|
|
190
|
+
case "object":
|
|
191
|
+
if (value === null) continue;
|
|
192
|
+
if (ancestors.has(value)) throw FilterError.invalid(`${where(at)}: a cycle (the value contains itself)`);
|
|
193
|
+
if (depth > 120) throw FilterError.invalid(`${where(at)}: the filter nests deeper than ${120} arrays / objects`);
|
|
194
|
+
ancestors.add(value);
|
|
195
|
+
stack.push({
|
|
196
|
+
value,
|
|
197
|
+
at,
|
|
198
|
+
depth,
|
|
199
|
+
leave: true
|
|
200
|
+
});
|
|
201
|
+
if (Array.isArray(value)) {
|
|
202
|
+
for (let i = 0; i < value.length; i++) {
|
|
203
|
+
if (!(i in value)) throw FilterError.invalid(`${where(at)}: the array has a hole at ${i}`);
|
|
204
|
+
stack.push({
|
|
205
|
+
value: value[i],
|
|
206
|
+
at: `${at}[${i}]`,
|
|
207
|
+
depth: depth + 1
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (!isPlainObject(value)) throw FilterError.invalid(`${where(at)}: ${describe(value)} is not a JSON object (use a plain object)`);
|
|
213
|
+
if (Object.getOwnPropertySymbols(value).length > 0) throw FilterError.invalid(`${where(at)}: symbol keys are not JSON`);
|
|
214
|
+
for (const key of Object.getOwnPropertyNames(value)) {
|
|
215
|
+
const member = at === "" ? key : `${at}.${key}`;
|
|
216
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
217
|
+
if (!descriptor?.enumerable) throw FilterError.invalid(`${where(member)}: a non-enumerable property is not JSON`);
|
|
218
|
+
if (!("value" in descriptor)) throw FilterError.invalid(`${where(member)}: an accessor property is not JSON`);
|
|
219
|
+
checkString(key, member, "the key");
|
|
220
|
+
stack.push({
|
|
221
|
+
value: descriptor.value,
|
|
222
|
+
at: member,
|
|
223
|
+
depth: depth + 1
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
continue;
|
|
227
|
+
default: throw FilterError.invalid(`${where(at)}: ${describe(value)} is not JSON`);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
/** Freezes a parsed JSON value (iteratively): the closures compiled from it share its operands. */
|
|
232
|
+
function deepFreeze(value) {
|
|
233
|
+
const stack = [value];
|
|
234
|
+
while (stack.length > 0) {
|
|
235
|
+
const v = stack.pop();
|
|
236
|
+
if (v === null || typeof v !== "object" || Object.isFrozen(v)) continue;
|
|
237
|
+
Object.freeze(v);
|
|
238
|
+
for (const member of Object.values(v)) stack.push(member);
|
|
239
|
+
}
|
|
240
|
+
return value;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
//#endregion
|
|
244
|
+
//#region ../iii/src/filter/value.ts
|
|
245
|
+
const hasEnumerable = Object.prototype.propertyIsEnumerable;
|
|
246
|
+
const toStringTag = Object.prototype.toString;
|
|
247
|
+
/** A `BigInt` read through its JSON encoding (its decimal digits) as a double; beyond the double range, `null`. */
|
|
248
|
+
function bigintView(b) {
|
|
249
|
+
const n = Number(b);
|
|
250
|
+
return Number.isFinite(n) ? n : null;
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Unwraps a boxed primitive (`new Number(1)`), also one from another realm,
|
|
254
|
+
* by its internal slot rather than `instanceof`. Anything else is an object.
|
|
255
|
+
*/
|
|
256
|
+
function unbox(v) {
|
|
257
|
+
try {
|
|
258
|
+
switch (toStringTag.call(v)) {
|
|
259
|
+
case "[object Number]": {
|
|
260
|
+
const n = Number.prototype.valueOf.call(v);
|
|
261
|
+
return Number.isFinite(n) ? n : null;
|
|
262
|
+
}
|
|
263
|
+
case "[object String]": return String.prototype.valueOf.call(v);
|
|
264
|
+
case "[object Boolean]": return Boolean.prototype.valueOf.call(v);
|
|
265
|
+
case "[object BigInt]": return bigintView(BigInt.prototype.valueOf.call(v));
|
|
266
|
+
}
|
|
267
|
+
} catch {}
|
|
268
|
+
return v;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* One step of `JSON.stringify` (SerializeJSONProperty): `toJSON`, boxed
|
|
272
|
+
* primitives, non-finite numbers, and the values JSON drops. `BigInt` is read
|
|
273
|
+
* through its JSON encoding (its decimal digits), as a double, unless the
|
|
274
|
+
* program installed `BigInt.prototype.toJSON`. Objects and arrays are
|
|
275
|
+
* returned as they are; their members are mapped when a path steps into them.
|
|
276
|
+
*
|
|
277
|
+
* Host code runs here (`toJSON`, getters, Proxy traps) and may throw: the
|
|
278
|
+
* caller of the whole evaluation turns that into a non-match.
|
|
279
|
+
*/
|
|
280
|
+
function jsonView(value, key) {
|
|
281
|
+
let v = value;
|
|
282
|
+
if (v !== null && (typeof v === "object" || typeof v === "function" || typeof v === "bigint")) {
|
|
283
|
+
const toJSON = v.toJSON;
|
|
284
|
+
if (typeof toJSON === "function") v = toJSON.call(v, key);
|
|
285
|
+
}
|
|
286
|
+
switch (typeof v) {
|
|
287
|
+
case "string":
|
|
288
|
+
case "boolean": return v;
|
|
289
|
+
case "number": return Number.isFinite(v) ? v : null;
|
|
290
|
+
case "bigint": return bigintView(v);
|
|
291
|
+
case "object": {
|
|
292
|
+
if (v === null) return null;
|
|
293
|
+
if (Array.isArray(v)) return v;
|
|
294
|
+
const proto = Object.getPrototypeOf(v);
|
|
295
|
+
if (proto === Object.prototype || proto === null) return v;
|
|
296
|
+
return unbox(v);
|
|
297
|
+
}
|
|
298
|
+
default: return;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/** Element `index` of an array, as JSON writes it: a member JSON drops is `null`. */
|
|
302
|
+
function arrayElement(array, index) {
|
|
303
|
+
const v = jsonView(array[index], String(index));
|
|
304
|
+
return v === void 0 ? null : v;
|
|
305
|
+
}
|
|
306
|
+
/** Own enumerable key `key` of an object; inherited properties do not exist. */
|
|
307
|
+
function objectMember(object, key) {
|
|
308
|
+
if (!hasEnumerable.call(object, key)) return void 0;
|
|
309
|
+
return jsonView(object[key], key);
|
|
310
|
+
}
|
|
311
|
+
function isObject(v) {
|
|
312
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* JSON deep equality between a mapped host value and a filter literal (plain
|
|
316
|
+
* JSON). Numbers compare as doubles (`1 == 1.0`, `-0 == 0`), object key order
|
|
317
|
+
* is ignored, array order is not, and there is no coercion between types.
|
|
318
|
+
* Iterative, so a deeply nested literal cannot overflow the stack.
|
|
319
|
+
*/
|
|
320
|
+
function jsonEquals(host, literal) {
|
|
321
|
+
if (literal === null || typeof literal !== "object") return scalarEquals(host, literal);
|
|
322
|
+
const stack = [[host, literal]];
|
|
323
|
+
while (stack.length > 0) {
|
|
324
|
+
const [h, l] = stack.pop();
|
|
325
|
+
if (l === null || typeof l !== "object") {
|
|
326
|
+
if (!scalarEquals(h, l)) return false;
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
if (Array.isArray(l)) {
|
|
330
|
+
if (!Array.isArray(h) || h.length !== l.length) return false;
|
|
331
|
+
for (let i = 0; i < l.length; i++) stack.push([arrayElement(h, i), l[i]]);
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
if (!isObject(h)) return false;
|
|
335
|
+
const lit = l;
|
|
336
|
+
const keys = Object.keys(lit);
|
|
337
|
+
for (const k of keys) {
|
|
338
|
+
const member = objectMember(h, k);
|
|
339
|
+
if (member === void 0) return false;
|
|
340
|
+
stack.push([member, lit[k]]);
|
|
341
|
+
}
|
|
342
|
+
let present = 0;
|
|
343
|
+
for (const k of Object.keys(h)) if (jsonView(h[k], k) !== void 0) {
|
|
344
|
+
present++;
|
|
345
|
+
if (present > keys.length) return false;
|
|
346
|
+
}
|
|
347
|
+
if (present !== keys.length) return false;
|
|
348
|
+
}
|
|
349
|
+
return true;
|
|
350
|
+
}
|
|
351
|
+
function scalarEquals(host, literal) {
|
|
352
|
+
if (literal === null) return host === null;
|
|
353
|
+
switch (typeof literal) {
|
|
354
|
+
case "number":
|
|
355
|
+
case "string":
|
|
356
|
+
case "boolean": return host === literal;
|
|
357
|
+
default: return false;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Compares two strings by Unicode code point (UTF-8 byte order), not by
|
|
362
|
+
* UTF-16 code unit as `<` does: a surrogate pair (a code point above U+FFFF)
|
|
363
|
+
* sorts after every BMP character, including U+E000..U+FFFF.
|
|
364
|
+
*/
|
|
365
|
+
function compareCodePoints(a, b) {
|
|
366
|
+
if (a === b) return 0;
|
|
367
|
+
const n = a.length < b.length ? a.length : b.length;
|
|
368
|
+
for (let i = 0; i < n; i++) {
|
|
369
|
+
let ca = a.charCodeAt(i);
|
|
370
|
+
let cb = b.charCodeAt(i);
|
|
371
|
+
if (ca !== cb) {
|
|
372
|
+
if (ca >= 55296 && cb >= 55296) {
|
|
373
|
+
ca = ca >= 57344 ? ca - 2048 : ca + 8192;
|
|
374
|
+
cb = cb >= 57344 ? cb - 2048 : cb + 8192;
|
|
375
|
+
}
|
|
376
|
+
return ca < cb ? -1 : 1;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
return a.length < b.length ? -1 : a.length > b.length ? 1 : 0;
|
|
380
|
+
}
|
|
381
|
+
/** `$prefix`: code point by code point, so a prefix never ends inside a surrogate pair. */
|
|
382
|
+
function hasCodePointPrefix(s, prefix) {
|
|
383
|
+
if (!s.startsWith(prefix)) return false;
|
|
384
|
+
if (prefix.length === 0 || prefix.length === s.length) return true;
|
|
385
|
+
const last = prefix.charCodeAt(prefix.length - 1);
|
|
386
|
+
if (last < 55296 || last > 56319) return true;
|
|
387
|
+
const next = s.charCodeAt(prefix.length);
|
|
388
|
+
return next < 56320 || next > 57343;
|
|
389
|
+
}
|
|
390
|
+
/** UTF-8 byte length of a string, without `Buffer` or `TextEncoder`. */
|
|
391
|
+
function utf8Length(s) {
|
|
392
|
+
let bytes = 0;
|
|
393
|
+
for (let i = 0; i < s.length; i++) {
|
|
394
|
+
const c = s.charCodeAt(i);
|
|
395
|
+
if (c < 128) bytes += 1;
|
|
396
|
+
else if (c < 2048) bytes += 2;
|
|
397
|
+
else if (c >= 55296 && c <= 56319 && i + 1 < s.length) {
|
|
398
|
+
const d = s.charCodeAt(i + 1);
|
|
399
|
+
if (d >= 56320 && d <= 57343) {
|
|
400
|
+
bytes += 4;
|
|
401
|
+
i++;
|
|
402
|
+
} else bytes += 3;
|
|
403
|
+
} else bytes += 3;
|
|
404
|
+
}
|
|
405
|
+
return bytes;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
//#endregion
|
|
409
|
+
//#region ../iii/src/filter/path.ts
|
|
410
|
+
const ROOTS = new Set([
|
|
411
|
+
"input",
|
|
412
|
+
"output",
|
|
413
|
+
"error",
|
|
414
|
+
"caller",
|
|
415
|
+
"metadata",
|
|
416
|
+
"@"
|
|
417
|
+
]);
|
|
418
|
+
const CANONICAL_INDEX = /^(?:0|[1-9][0-9]*)$/;
|
|
419
|
+
function canonicalIndex(segment) {
|
|
420
|
+
if (segment.length > 15 || !CANONICAL_INDEX.test(segment)) return void 0;
|
|
421
|
+
return Number(segment);
|
|
422
|
+
}
|
|
423
|
+
function emptySegment(raw) {
|
|
424
|
+
return FilterError.invalid(raw === "" ? "empty path" : `path \`${raw}\`: empty segment`);
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Parses `root ("." segment)*`. `\.` and `\\` escape inside keys; any other
|
|
428
|
+
* backslash sequence, an empty segment or an unknown root is
|
|
429
|
+
* `INVALID_FILTER`. `@` is a root only inside `$any`, where it is the only
|
|
430
|
+
* root allowed.
|
|
431
|
+
*/
|
|
432
|
+
function parsePath(raw, inAny) {
|
|
433
|
+
const parts = [];
|
|
434
|
+
let current = "";
|
|
435
|
+
for (let i = 0; i < raw.length; i++) {
|
|
436
|
+
const c = raw[i];
|
|
437
|
+
if (c === "\\") {
|
|
438
|
+
const next = raw[i + 1];
|
|
439
|
+
if (next === "." || next === "\\") {
|
|
440
|
+
current += next;
|
|
441
|
+
i++;
|
|
442
|
+
} else if (next === void 0) throw FilterError.invalid(`path \`${raw}\`: dangling \`\\\` at the end`);
|
|
443
|
+
else throw FilterError.invalid(`path \`${raw}\`: invalid escape \`\\${next}\` (only \`\\.\` and \`\\\\\` are allowed)`);
|
|
444
|
+
} else if (c === ".") {
|
|
445
|
+
if (current === "") throw emptySegment(raw);
|
|
446
|
+
parts.push(current);
|
|
447
|
+
current = "";
|
|
448
|
+
} else current += c;
|
|
449
|
+
}
|
|
450
|
+
if (current === "") throw emptySegment(raw);
|
|
451
|
+
parts.push(current);
|
|
452
|
+
const first = parts[0];
|
|
453
|
+
if (!ROOTS.has(first)) throw FilterError.invalid(inAny ? `path \`${raw}\`: inside \`$any\` paths start at \`@\`, the current element` : `path \`${raw}\`: unknown root \`${first}\` (expected input, output, error, caller or metadata)`);
|
|
454
|
+
if (first === "@" && !inAny) throw FilterError.invalid(`path \`${raw}\`: \`@\` paths are only allowed inside \`$any\``);
|
|
455
|
+
if (first !== "@" && inAny) throw FilterError.invalid(`path \`${raw}\`: inside \`$any\` paths start at \`@\`, the current element`);
|
|
456
|
+
const segments = parts.slice(1).map((key) => ({
|
|
457
|
+
key,
|
|
458
|
+
index: canonicalIndex(key)
|
|
459
|
+
}));
|
|
460
|
+
if (segments.length > 16) throw FilterError.invalid(`path \`${raw}\`: ${segments.length} segments after the root (limit ${16})`);
|
|
461
|
+
return {
|
|
462
|
+
root: first,
|
|
463
|
+
segments
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
/** Compiles the path into a resolver; `undefined` means absent. */
|
|
467
|
+
function compilePath(path) {
|
|
468
|
+
const { root, segments } = path;
|
|
469
|
+
const step = (start) => {
|
|
470
|
+
let current = start;
|
|
471
|
+
for (let i = 0; i < segments.length; i++) {
|
|
472
|
+
if (current === void 0 || current === null || typeof current !== "object") return void 0;
|
|
473
|
+
const segment = segments[i];
|
|
474
|
+
if (Array.isArray(current)) {
|
|
475
|
+
const index = segment.index;
|
|
476
|
+
if (index === void 0 || index >= current.length) return void 0;
|
|
477
|
+
current = arrayElement(current, index);
|
|
478
|
+
} else current = objectMember(current, segment.key);
|
|
479
|
+
}
|
|
480
|
+
return current;
|
|
481
|
+
};
|
|
482
|
+
if (root === "@") return (_doc, element) => step(element);
|
|
483
|
+
return (doc) => step(objectMember(doc, root));
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
//#endregion
|
|
487
|
+
//#region ../iii/src/filter/compile.ts
|
|
488
|
+
/**
|
|
489
|
+
* Validation (filters.md §2, §4) and compilation into closures, in one pass.
|
|
490
|
+
*
|
|
491
|
+
* Mirrors `crates/iii-filter` (`parse.rs`, `eval.rs`): the same limits, the
|
|
492
|
+
* same error code (`INVALID_FILTER`) and the same semantics, so a filter
|
|
493
|
+
* evaluated here, in the engine or in another SDK answers the same. The
|
|
494
|
+
* filter must already be JSON (`checkJson`); it is then copied through
|
|
495
|
+
* `JSON.stringify` (also what the encoded size limit is measured on), so
|
|
496
|
+
* what is validated is exactly what travels on the wire.
|
|
497
|
+
*
|
|
498
|
+
* Limits, as the vectors define them:
|
|
499
|
+
* - depth: the top-level filter is at depth 1; the filters of a `$or`, the
|
|
500
|
+
* operand of `$not` and the operand of `$any` are one level deeper than the
|
|
501
|
+
* object holding them; the filters of a `$and` stay at the same level;
|
|
502
|
+
* - nodes: every operator (`$eq` ... `$any`) and every `$or` / `$not` counts
|
|
503
|
+
* one; paths and `$and` are free;
|
|
504
|
+
* - encoded size: the compact JSON of the filter as given, in UTF-8 bytes.
|
|
505
|
+
*
|
|
506
|
+
* Pure TypeScript with no Node.js APIs: the browser SDK uses this file too.
|
|
507
|
+
*/
|
|
508
|
+
const VALUE_OPERATORS = new Set([
|
|
509
|
+
"$eq",
|
|
510
|
+
"$ne",
|
|
511
|
+
"$in",
|
|
512
|
+
"$nin",
|
|
513
|
+
"$gt",
|
|
514
|
+
"$gte",
|
|
515
|
+
"$lt",
|
|
516
|
+
"$lte",
|
|
517
|
+
"$exists",
|
|
518
|
+
"$prefix",
|
|
519
|
+
"$any"
|
|
520
|
+
]);
|
|
521
|
+
var Budget = class {
|
|
522
|
+
constructor() {
|
|
523
|
+
this.used = 0;
|
|
524
|
+
}
|
|
525
|
+
take() {
|
|
526
|
+
this.used++;
|
|
527
|
+
if (this.used > 64) throw FilterError.invalid(`more than ${64} operator / clause nodes`);
|
|
528
|
+
}
|
|
529
|
+
};
|
|
530
|
+
function isJsonObject(v) {
|
|
531
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
532
|
+
}
|
|
533
|
+
function kind(v) {
|
|
534
|
+
if (v === null) return "null";
|
|
535
|
+
if (Array.isArray(v)) return "an array";
|
|
536
|
+
switch (typeof v) {
|
|
537
|
+
case "boolean": return "a boolean";
|
|
538
|
+
case "number": return "a number";
|
|
539
|
+
case "string": return "a string";
|
|
540
|
+
default: return "an object";
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Validates `src` and compiles it. Throws {@link FilterError} with code
|
|
545
|
+
* `INVALID_FILTER` when the filter is not valid.
|
|
546
|
+
*
|
|
547
|
+
* `trusted` skips the encoded size limit, for filters the engine already
|
|
548
|
+
* validated (the normal form it pushes to owners): normalizing can make a
|
|
549
|
+
* filter a little longer than the one written, and JavaScript spells some
|
|
550
|
+
* numbers longer than serde_json, so near the limit the two measurements can
|
|
551
|
+
* disagree, and the engine's is the one that counts.
|
|
552
|
+
*/
|
|
553
|
+
function compile(src, trusted = false) {
|
|
554
|
+
let text;
|
|
555
|
+
try {
|
|
556
|
+
if (src === null || typeof src !== "object" || Array.isArray(src)) throw FilterError.invalid(`a filter must be a JSON object, found ${src === void 0 ? "nothing" : kind(src)}`);
|
|
557
|
+
checkJson(src);
|
|
558
|
+
text = JSON.stringify(src);
|
|
559
|
+
} catch (error) {
|
|
560
|
+
if (error instanceof FilterError) throw error;
|
|
561
|
+
throw FilterError.invalid(`the filter cannot be read: ${error instanceof Error ? error.message : String(error)}`);
|
|
562
|
+
}
|
|
563
|
+
if (!trusted && utf8Length(text) > 8192) throw FilterError.invalid(`the filter encodes to more than ${MAX_ENCODED_BYTES} bytes`);
|
|
564
|
+
const json = deepFreeze(JSON.parse(text));
|
|
565
|
+
const roots = /* @__PURE__ */ new Set();
|
|
566
|
+
const clauses = [];
|
|
567
|
+
collectClauses(json, 1, false, new Budget(), roots, clauses);
|
|
568
|
+
return {
|
|
569
|
+
pred: and(clauses),
|
|
570
|
+
roots,
|
|
571
|
+
json,
|
|
572
|
+
matchAll: clauses.length === 0
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
function parseFilter(src, depth, inAny, budget, roots) {
|
|
576
|
+
const clauses = [];
|
|
577
|
+
collectClauses(src, depth, inAny, budget, roots, clauses);
|
|
578
|
+
return and(clauses);
|
|
579
|
+
}
|
|
580
|
+
function and(clauses) {
|
|
581
|
+
switch (clauses.length) {
|
|
582
|
+
case 0: return () => true;
|
|
583
|
+
case 1: return clauses[0];
|
|
584
|
+
case 2: {
|
|
585
|
+
const [a, b] = clauses;
|
|
586
|
+
return (doc, el) => a(doc, el) && b(doc, el);
|
|
587
|
+
}
|
|
588
|
+
default: return (doc, el) => {
|
|
589
|
+
for (let i = 0; i < clauses.length; i++) if (!clauses[i](doc, el)) return false;
|
|
590
|
+
return true;
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* Collects the clauses of `src` and of every filter its `$and`s hold. `$and`
|
|
596
|
+
* adds no depth, so it is walked with an explicit stack.
|
|
597
|
+
*/
|
|
598
|
+
function collectClauses(src, depth, inAny, budget, roots, out) {
|
|
599
|
+
if (depth > 8) throw FilterError.invalid(`filters nested deeper than ${8} levels`);
|
|
600
|
+
const pending = [src];
|
|
601
|
+
while (pending.length > 0) {
|
|
602
|
+
const current = pending.pop();
|
|
603
|
+
if (!isJsonObject(current)) throw FilterError.invalid(`a filter must be a JSON object, found ${kind(current)}`);
|
|
604
|
+
for (const key of Object.keys(current)) {
|
|
605
|
+
const value = current[key];
|
|
606
|
+
if (key === "$and") {
|
|
607
|
+
const items = filterList("$and", value);
|
|
608
|
+
for (let i = items.length - 1; i >= 0; i--) pending.push(items[i]);
|
|
609
|
+
} else if (key === "$or") {
|
|
610
|
+
budget.take();
|
|
611
|
+
const children = filterList("$or", value).map((item) => parseFilter(item, depth + 1, inAny, budget, roots));
|
|
612
|
+
out.push((doc, el) => {
|
|
613
|
+
for (let i = 0; i < children.length; i++) if (children[i](doc, el)) return true;
|
|
614
|
+
return false;
|
|
615
|
+
});
|
|
616
|
+
} else if (key === "$not") {
|
|
617
|
+
budget.take();
|
|
618
|
+
if (!isJsonObject(value)) throw FilterError.invalid(`\`$not\` takes a filter object, found ${kind(value)}`);
|
|
619
|
+
const child = parseFilter(value, depth + 1, inAny, budget, roots);
|
|
620
|
+
out.push((doc, el) => !child(doc, el));
|
|
621
|
+
} else if (VALUE_OPERATORS.has(key)) throw FilterError.invalid(`\`${key}\` needs a path: write {"<path>": {"${key}": ...}}`);
|
|
622
|
+
else if (key.startsWith("$")) throw FilterError.invalid(`unknown operator \`${key}\` (a filter holds paths, \`$and\`, \`$or\` and \`$not\`)`);
|
|
623
|
+
else {
|
|
624
|
+
const path = parsePath(key, inAny);
|
|
625
|
+
if (path.root !== "@") roots.add(path.root);
|
|
626
|
+
const ops = parseOperatorObject(key, value, depth, budget);
|
|
627
|
+
const resolve = compilePath(path);
|
|
628
|
+
out.push(pathClause(resolve, ops));
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
function pathClause(resolve, ops) {
|
|
634
|
+
if (ops.length === 1) {
|
|
635
|
+
const op = ops[0];
|
|
636
|
+
return (doc, el) => op(resolve(doc, el), doc);
|
|
637
|
+
}
|
|
638
|
+
return (doc, el) => {
|
|
639
|
+
const value = resolve(doc, el);
|
|
640
|
+
for (let i = 0; i < ops.length; i++) if (!ops[i](value, doc)) return false;
|
|
641
|
+
return true;
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
function filterList(name, value) {
|
|
645
|
+
if (!Array.isArray(value)) throw FilterError.invalid(`\`${name}\` takes an array of filters, found ${kind(value)}`);
|
|
646
|
+
if (value.length === 0) throw FilterError.invalid(`\`${name}\` takes a non-empty array of filters`);
|
|
647
|
+
return value;
|
|
648
|
+
}
|
|
649
|
+
function parseOperatorObject(path, value, depth, budget) {
|
|
650
|
+
const shorthand = () => FilterError.invalid(`\`${path}\`: expected an operator object such as {"$eq": ...}; literal values are not allowed`);
|
|
651
|
+
if (!isJsonObject(value)) throw shorthand();
|
|
652
|
+
const names = Object.keys(value);
|
|
653
|
+
if (names.length === 0) throw FilterError.invalid(`\`${path}\`: empty operator object`);
|
|
654
|
+
if (names.some((k) => !k.startsWith("$"))) throw shorthand();
|
|
655
|
+
return parseOperators(path, value, depth, budget);
|
|
656
|
+
}
|
|
657
|
+
/** The operators of an operator object; `depth` is the level of the object holding them. */
|
|
658
|
+
function parseOperators(path, map, depth, budget) {
|
|
659
|
+
return Object.keys(map).map((name) => {
|
|
660
|
+
budget.take();
|
|
661
|
+
return parseOperator(path, name, map[name], depth, budget);
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
function parseOperator(path, name, operand, depth, budget) {
|
|
665
|
+
const wrong = (expected) => FilterError.invalid(`\`${path}\`: \`${name}\` takes ${expected}, found ${kind(operand)}`);
|
|
666
|
+
switch (name) {
|
|
667
|
+
case "$eq":
|
|
668
|
+
checkLiteralDepth(path, name, operand);
|
|
669
|
+
return (v) => v !== void 0 && jsonEquals(v, operand);
|
|
670
|
+
case "$ne":
|
|
671
|
+
checkLiteralDepth(path, name, operand);
|
|
672
|
+
return (v) => v === void 0 || !jsonEquals(v, operand);
|
|
673
|
+
case "$in":
|
|
674
|
+
case "$nin": {
|
|
675
|
+
if (!Array.isArray(operand)) throw wrong("an array");
|
|
676
|
+
if (operand.length > 256) throw FilterError.invalid(`\`${path}\`: \`${name}\` has ${operand.length} items (limit ${256})`);
|
|
677
|
+
for (const item of operand) checkLiteralDepth(path, name, item);
|
|
678
|
+
const items = operand;
|
|
679
|
+
const member = (v) => {
|
|
680
|
+
for (let i = 0; i < items.length; i++) if (jsonEquals(v, items[i])) return true;
|
|
681
|
+
return false;
|
|
682
|
+
};
|
|
683
|
+
return name === "$in" ? (v) => v !== void 0 && member(v) : (v) => v === void 0 || !member(v);
|
|
684
|
+
}
|
|
685
|
+
case "$gt":
|
|
686
|
+
case "$gte":
|
|
687
|
+
case "$lt":
|
|
688
|
+
case "$lte": {
|
|
689
|
+
const accept = name === "$gt" ? (c) => c > 0 : name === "$gte" ? (c) => c >= 0 : name === "$lt" ? (c) => c < 0 : (c) => c <= 0;
|
|
690
|
+
if (typeof operand === "number") {
|
|
691
|
+
const bound = operand;
|
|
692
|
+
return (v) => typeof v === "number" && accept(v < bound ? -1 : v > bound ? 1 : 0);
|
|
693
|
+
}
|
|
694
|
+
if (typeof operand === "string") {
|
|
695
|
+
const bound = operand;
|
|
696
|
+
return (v) => typeof v === "string" && accept(compareCodePoints(v, bound));
|
|
697
|
+
}
|
|
698
|
+
throw wrong("a number or a string");
|
|
699
|
+
}
|
|
700
|
+
case "$exists": {
|
|
701
|
+
if (typeof operand !== "boolean") throw wrong("a boolean");
|
|
702
|
+
const expected = operand;
|
|
703
|
+
return (v) => v !== void 0 === expected;
|
|
704
|
+
}
|
|
705
|
+
case "$prefix": {
|
|
706
|
+
if (typeof operand !== "string") throw wrong("a string");
|
|
707
|
+
const prefix = operand;
|
|
708
|
+
return (v) => typeof v === "string" && hasCodePointPrefix(v, prefix);
|
|
709
|
+
}
|
|
710
|
+
case "$any": return parseAny(path, operand, depth, budget);
|
|
711
|
+
case "$and":
|
|
712
|
+
case "$or":
|
|
713
|
+
case "$not": throw FilterError.invalid(`\`${path}\`: \`${name}\` combines filters and is not a value operator`);
|
|
714
|
+
default: throw FilterError.invalid(`\`${path}\`: unknown operator \`${name}\``);
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* `$any` takes an operator object (all keys are value operators) or a filter
|
|
719
|
+
* over the element (`@` paths, `$and`, `$or`, `$not`). `{}` is the empty
|
|
720
|
+
* filter: it matches any non-empty array.
|
|
721
|
+
*/
|
|
722
|
+
function parseAny(path, operand, depth, budget) {
|
|
723
|
+
if (!isJsonObject(operand)) throw FilterError.invalid(`\`${path}\`: \`$any\` takes an operator object or a filter over \`@\`, found ${kind(operand)}`);
|
|
724
|
+
if (depth + 1 > 8) throw FilterError.invalid(`filters nested deeper than ${8} levels`);
|
|
725
|
+
const names = Object.keys(operand);
|
|
726
|
+
if (names.length > 0 && names.every((k) => VALUE_OPERATORS.has(k))) {
|
|
727
|
+
const ops = parseOperators(path, operand, depth + 1, budget);
|
|
728
|
+
return (v, doc) => {
|
|
729
|
+
if (!Array.isArray(v)) return false;
|
|
730
|
+
for (let i = 0; i < v.length; i++) {
|
|
731
|
+
const item = arrayElement(v, i);
|
|
732
|
+
let all = true;
|
|
733
|
+
for (let j = 0; j < ops.length; j++) if (!ops[j](item, doc)) {
|
|
734
|
+
all = false;
|
|
735
|
+
break;
|
|
736
|
+
}
|
|
737
|
+
if (all) return true;
|
|
738
|
+
}
|
|
739
|
+
return false;
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
const node = parseFilter(operand, depth + 1, true, budget, /* @__PURE__ */ new Set());
|
|
743
|
+
return (v, doc) => {
|
|
744
|
+
if (!Array.isArray(v)) return false;
|
|
745
|
+
for (let i = 0; i < v.length; i++) if (node(doc, arrayElement(v, i))) return true;
|
|
746
|
+
return false;
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
750
|
+
* A literal (an `$eq` / `$ne` operand, an `$in` / `$nin` item) nests at most
|
|
751
|
+
* MAX_LITERAL_DEPTH arrays / objects: a scalar is 0, `[]` and `[1]` are 1.
|
|
752
|
+
*/
|
|
753
|
+
function checkLiteralDepth(path, name, literal) {
|
|
754
|
+
const stack = [[literal, 1]];
|
|
755
|
+
while (stack.length > 0) {
|
|
756
|
+
const [value, level] = stack.pop();
|
|
757
|
+
if (value === null || typeof value !== "object") continue;
|
|
758
|
+
if (level > 32) throw FilterError.invalid(`\`${path}\`: \`${name}\` nests a literal deeper than ${32} arrays / objects`);
|
|
759
|
+
for (const member of Object.values(value)) stack.push([member, level + 1]);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
//#endregion
|
|
764
|
+
//#region ../iii/src/filter/index.ts
|
|
765
|
+
/**
|
|
766
|
+
* The observer filter language (`iii-filter` v1, filters.md): validation and
|
|
767
|
+
* evaluation for the SDKs, with the same semantics as the engine's Rust
|
|
768
|
+
* evaluator (`crates/iii-filter`).
|
|
769
|
+
*
|
|
770
|
+
* Pure TypeScript with no Node.js APIs: the browser SDK uses these files too.
|
|
771
|
+
*/
|
|
772
|
+
/**
|
|
773
|
+
* Validates and compiles a filter. Throws {@link FilterError}
|
|
774
|
+
* (`INVALID_FILTER`) when it is not valid.
|
|
775
|
+
*
|
|
776
|
+
* @example
|
|
777
|
+
* ```typescript
|
|
778
|
+
* const f = compileFilter({ 'input.amount': { $gte: 500 } })
|
|
779
|
+
* f.matches({ input: { amount: 750 } }) // true
|
|
780
|
+
* ```
|
|
781
|
+
*/
|
|
782
|
+
function compileFilter(src, options) {
|
|
783
|
+
const { pred, roots, json, matchAll } = compile(src, options?.trusted === true);
|
|
784
|
+
return {
|
|
785
|
+
source: json,
|
|
786
|
+
matchAll,
|
|
787
|
+
roots,
|
|
788
|
+
matches: (doc) => {
|
|
789
|
+
try {
|
|
790
|
+
return pred(doc !== null && typeof doc === "object" ? doc : {}, void 0);
|
|
791
|
+
} catch {
|
|
792
|
+
return false;
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
/** The filter that matches every document (`{}`). */
|
|
798
|
+
const MATCH_ALL = compileFilter({});
|
|
799
|
+
|
|
800
|
+
//#endregion
|
|
801
|
+
//#region src/iii-types.ts
|
|
802
|
+
/**
|
|
803
|
+
* Protocol features (`WorkerRegistered.features` from the engine,
|
|
804
|
+
* `engine::workers::register` `features` from the SDK).
|
|
805
|
+
*/
|
|
806
|
+
const FEATURE_OBSERVE_V1 = "observe.v1";
|
|
807
|
+
const FEATURE_LOCAL_DISPATCH_V1 = "local-dispatch.v1";
|
|
808
|
+
/**
|
|
809
|
+
* What this SDK declares in `engine::workers::register`. Not
|
|
810
|
+
* `large-messages.v1`, unlike the other SDKs: a browser receives one 16 MiB
|
|
811
|
+
* WebSocket frame at most.
|
|
812
|
+
*/
|
|
813
|
+
const SDK_FEATURES = [FEATURE_OBSERVE_V1, FEATURE_LOCAL_DISPATCH_V1];
|
|
814
|
+
|
|
815
|
+
//#endregion
|
|
816
|
+
//#region src/invocation-context.ts
|
|
817
|
+
/**
|
|
818
|
+
* How long an invocation that came over the wire (and one re-entered with
|
|
819
|
+
* `withInvocation`) counts as running at most, when it never settles. An
|
|
820
|
+
* observer chain's hops may await far longer than this SDK's own call
|
|
821
|
+
* timeout, and their depth must still reach the calls they make afterwards
|
|
822
|
+
* (the engine's loop guard counts on it). A local call counts as running until
|
|
823
|
+
* its caller's timeout instead.
|
|
824
|
+
*/
|
|
825
|
+
const MAX_RUNNING_INVOCATION_MS = 600 * 1e3;
|
|
826
|
+
/**
|
|
827
|
+
* Browsers have no `AsyncLocalStorage` (and `AsyncContext` is not shipped
|
|
828
|
+
* yet), so the context is a synchronous scope: {@link runInContext} sets it
|
|
829
|
+
* while `fn` runs and restores the previous one when `fn` returns. An async
|
|
830
|
+
* handler sees it up to its first `await`; the continuation after an `await`
|
|
831
|
+
* runs from the event loop, outside any scope, so it never sees another
|
|
832
|
+
* invocation's context, only none. `withInvocation` re-enters a captured one.
|
|
833
|
+
*
|
|
834
|
+
* One scope for the whole page, like the Node SDK's one `AsyncLocalStorage`
|
|
835
|
+
* per process: a handler of one worker that calls another worker's
|
|
836
|
+
* `trigger()` is that call's caller.
|
|
837
|
+
*/
|
|
838
|
+
let current;
|
|
839
|
+
/** The public views handed out, so `withInvocation(view, fn)` restores everything (metadata included). */
|
|
840
|
+
const views = /* @__PURE__ */ new WeakMap();
|
|
841
|
+
function currentContext() {
|
|
842
|
+
return current;
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
845
|
+
* Every invocation whose work is running on this page (handlers, remote and
|
|
846
|
+
* local, and the async `fn` of `withInvocation`), until it settles: one lease
|
|
847
|
+
* per piece of work, because an async `withInvocation` keeps an invocation
|
|
848
|
+
* running alongside its handler. A lease is forgotten at its deadline, so work
|
|
849
|
+
* that never settles does not lend its depth to every later call made on the
|
|
850
|
+
* page; settling one lease never ends another (a late one, after its deadline
|
|
851
|
+
* passed and the invocation was entered again, ends only itself).
|
|
852
|
+
*/
|
|
853
|
+
const running = /* @__PURE__ */ new Map();
|
|
854
|
+
/**
|
|
855
|
+
* Marks `ctx` as running for at most `maxAgeMs`; call the returned function
|
|
856
|
+
* when the work settles.
|
|
857
|
+
*/
|
|
858
|
+
function trackRunning(ctx, maxAgeMs) {
|
|
859
|
+
const lease = { deadline: Date.now() + maxAgeMs };
|
|
860
|
+
let leases = running.get(ctx);
|
|
861
|
+
if (!leases) {
|
|
862
|
+
leases = /* @__PURE__ */ new Set();
|
|
863
|
+
running.set(ctx, leases);
|
|
864
|
+
}
|
|
865
|
+
leases.add(lease);
|
|
866
|
+
return () => {
|
|
867
|
+
const current = running.get(ctx);
|
|
868
|
+
if (!current?.delete(lease)) return;
|
|
869
|
+
if (current.size === 0) running.delete(ctx);
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
/** The running invocations; leases past their deadline are forgotten here. */
|
|
873
|
+
function live() {
|
|
874
|
+
const now = Date.now();
|
|
875
|
+
const out = [];
|
|
876
|
+
for (const [ctx, leases] of running) {
|
|
877
|
+
for (const lease of leases) if (lease.deadline <= now) leases.delete(lease);
|
|
878
|
+
if (leases.size === 0) running.delete(ctx);
|
|
879
|
+
else out.push(ctx);
|
|
880
|
+
}
|
|
881
|
+
return out;
|
|
882
|
+
}
|
|
883
|
+
/** What a fallback attribution lends: the invocation without its metadata sidecar (one object per invocation). */
|
|
884
|
+
const lent = /* @__PURE__ */ new WeakMap();
|
|
885
|
+
function lend(ctx) {
|
|
886
|
+
let view = lent.get(ctx);
|
|
887
|
+
if (!view) {
|
|
888
|
+
const { metadata: _, ...rest } = ctx;
|
|
889
|
+
view = rest;
|
|
890
|
+
lent.set(ctx, view);
|
|
891
|
+
}
|
|
892
|
+
return view;
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* The invocation a call, an emit or a report made now belongs to. Inside a
|
|
896
|
+
* scope, the scope's. Outside any scope (code after an `await`), the running
|
|
897
|
+
* invocation when that is unambiguous: it is the only one running and it is
|
|
898
|
+
* an observe activation. It lends its ids, caller and trace context, never its
|
|
899
|
+
* metadata: filters on `metadata.*` see only what a real scope carries.
|
|
900
|
+
* Otherwise none, and the call carries no `caller`: the SDK cannot tell which
|
|
901
|
+
* handler, if any, made it.
|
|
902
|
+
*/
|
|
903
|
+
function callContext() {
|
|
904
|
+
if (current) return current;
|
|
905
|
+
const all = live();
|
|
906
|
+
return all.length === 1 && all[0].activation ? lend(all[0]) : void 0;
|
|
907
|
+
}
|
|
908
|
+
/**
|
|
909
|
+
* The `observe_depth` a call, an emit or a report made now carries. Inside a
|
|
910
|
+
* scope, the scope's. Outside any scope, the deepest running invocation's:
|
|
911
|
+
* the engine's loop guard counts on this depth, so code after an `await`
|
|
912
|
+
* over-counts (a chain may stop earlier than `max_observe_depth`) rather than
|
|
913
|
+
* restart the chain at 0 (an observer cycle would never stop).
|
|
914
|
+
*/
|
|
915
|
+
function callDepth() {
|
|
916
|
+
if (current) return current.observe_depth;
|
|
917
|
+
let depth = 0;
|
|
918
|
+
for (const ctx of live()) if (ctx.observe_depth > depth) depth = ctx.observe_depth;
|
|
919
|
+
return depth;
|
|
920
|
+
}
|
|
921
|
+
/**
|
|
922
|
+
* The local depth that calls started outside any scope in the current
|
|
923
|
+
* synchronous run share (see {@link callLocalDepth}); cleared on a microtask.
|
|
924
|
+
*/
|
|
925
|
+
let unscopedLocalDepth;
|
|
926
|
+
/**
|
|
927
|
+
* How many local calls deep a local call made now is nested (decision 20,
|
|
928
|
+
* {@link MAX_LOCAL_DEPTH}). Inside a scope, the scope's. Outside any scope, the
|
|
929
|
+
* deepest running local call's, so a self-recursion that awaits before each
|
|
930
|
+
* call still reaches the engine at the limit. That value is taken once per
|
|
931
|
+
* synchronous run: calls started together outside any scope (a fan-out, from
|
|
932
|
+
* a loop or `Promise.all`) are siblings at one depth; only code after an
|
|
933
|
+
* `await`, which runs later, sees them running and goes one level deeper.
|
|
934
|
+
*/
|
|
935
|
+
function callLocalDepth() {
|
|
936
|
+
if (current) return current.localDepth ?? 0;
|
|
937
|
+
if (unscopedLocalDepth === void 0) {
|
|
938
|
+
let depth = 0;
|
|
939
|
+
for (const ctx of live()) if ((ctx.localDepth ?? 0) > depth) depth = ctx.localDepth ?? 0;
|
|
940
|
+
unscopedLocalDepth = depth;
|
|
941
|
+
queueMicrotask(() => {
|
|
942
|
+
unscopedLocalDepth = void 0;
|
|
943
|
+
});
|
|
944
|
+
}
|
|
945
|
+
return unscopedLocalDepth;
|
|
946
|
+
}
|
|
947
|
+
/**
|
|
948
|
+
* `withInvocation`: runs `fn` inside `ctx`. When `fn` returns a promise, `ctx`
|
|
949
|
+
* counts as running until it settles (at most `maxAgeMs`), so `fn`'s code after
|
|
950
|
+
* its own `await`s falls back to it (see {@link callContext}, {@link callDepth}),
|
|
951
|
+
* and the caller gets a promise that settles the same way: a rejection the
|
|
952
|
+
* caller does not handle is still reported as unhandled.
|
|
953
|
+
*/
|
|
954
|
+
function enterInvocation(ctx, fn, maxAgeMs) {
|
|
955
|
+
const result = runInContext(ctx, fn);
|
|
956
|
+
if (!ctx || result === null || typeof result?.then !== "function") return result;
|
|
957
|
+
const untrack = trackRunning(ctx, maxAgeMs);
|
|
958
|
+
return result.then((value) => {
|
|
959
|
+
untrack();
|
|
960
|
+
return value;
|
|
961
|
+
}, (error) => {
|
|
962
|
+
untrack();
|
|
963
|
+
throw error;
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
/** Runs `fn` synchronously inside `ctx` (`undefined`: outside any invocation). */
|
|
967
|
+
function runInContext(ctx, fn) {
|
|
968
|
+
const previous = current;
|
|
969
|
+
current = ctx;
|
|
970
|
+
try {
|
|
971
|
+
return fn();
|
|
972
|
+
} finally {
|
|
973
|
+
current = previous;
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
/** The public view of the current invocation (without the metadata sidecar). */
|
|
977
|
+
function publicContext(ctx) {
|
|
978
|
+
if (!ctx) return void 0;
|
|
979
|
+
const view = {
|
|
980
|
+
function_id: ctx.function_id,
|
|
981
|
+
invocation_id: ctx.invocation_id,
|
|
982
|
+
observe_depth: ctx.observe_depth
|
|
983
|
+
};
|
|
984
|
+
if (ctx.caller) view.caller = ctx.caller;
|
|
985
|
+
if (ctx.activation) view.activation = ctx.activation;
|
|
986
|
+
if (ctx.traceparent !== void 0) view.traceparent = ctx.traceparent;
|
|
987
|
+
if (ctx.baggage !== void 0) view.baggage = ctx.baggage;
|
|
988
|
+
views.set(view, ctx);
|
|
989
|
+
return view;
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* The context `withInvocation` re-enters: the one a view of
|
|
993
|
+
* `currentInvocation()` was taken from, or one built from a context the
|
|
994
|
+
* caller assembled itself or copied (at the local depth of the code entering it).
|
|
995
|
+
*/
|
|
996
|
+
function contextFromView(view) {
|
|
997
|
+
if (view === void 0 || view === null) return void 0;
|
|
998
|
+
const known = views.get(view);
|
|
999
|
+
if (known) {
|
|
1000
|
+
const depth = callLocalDepth();
|
|
1001
|
+
return depth > (known.localDepth ?? 0) ? {
|
|
1002
|
+
...known,
|
|
1003
|
+
localDepth: depth
|
|
1004
|
+
} : known;
|
|
1005
|
+
}
|
|
1006
|
+
if (typeof view.function_id !== "string" || typeof view.invocation_id !== "string") throw new Error("withInvocation: expected the value iii.currentInvocation() returned");
|
|
1007
|
+
const ctx = {
|
|
1008
|
+
function_id: view.function_id,
|
|
1009
|
+
invocation_id: view.invocation_id,
|
|
1010
|
+
observe_depth: typeof view.observe_depth === "number" && view.observe_depth > 0 ? view.observe_depth : 0,
|
|
1011
|
+
localDepth: callLocalDepth()
|
|
1012
|
+
};
|
|
1013
|
+
if (view.caller) ctx.caller = view.caller;
|
|
1014
|
+
if (view.activation) ctx.activation = view.activation;
|
|
1015
|
+
if (typeof view.traceparent === "string") ctx.traceparent = view.traceparent;
|
|
1016
|
+
if (typeof view.baggage === "string") ctx.baggage = view.baggage;
|
|
1017
|
+
return ctx;
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
//#endregion
|
|
1021
|
+
//#region src/observe-wire.ts
|
|
1022
|
+
/** CONTRACT D1: what an absent `capture` means. */
|
|
1023
|
+
const DEFAULT_CAPTURE = [
|
|
1024
|
+
"input",
|
|
1025
|
+
"output",
|
|
1026
|
+
"caller"
|
|
1027
|
+
];
|
|
1028
|
+
function isRecord(v) {
|
|
1029
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
1030
|
+
}
|
|
1031
|
+
function str(v) {
|
|
1032
|
+
return typeof v === "string" ? v : void 0;
|
|
1033
|
+
}
|
|
1034
|
+
function num(v) {
|
|
1035
|
+
return typeof v === "number" ? v : void 0;
|
|
1036
|
+
}
|
|
1037
|
+
function errorBody(v) {
|
|
1038
|
+
if (!isRecord(v)) return void 0;
|
|
1039
|
+
const body = {
|
|
1040
|
+
code: String(v.code ?? ""),
|
|
1041
|
+
message: String(v.message ?? "")
|
|
1042
|
+
};
|
|
1043
|
+
if (typeof v.stacktrace === "string") body.stacktrace = v.stacktrace;
|
|
1044
|
+
return body;
|
|
1045
|
+
}
|
|
1046
|
+
/** Copies the wire caller, dropping `null`s and a `parent` inside `parent`. */
|
|
1047
|
+
function decodeCaller(v, depth = 0) {
|
|
1048
|
+
if (!isRecord(v)) return void 0;
|
|
1049
|
+
const caller = {};
|
|
1050
|
+
for (const key of [
|
|
1051
|
+
"worker_id",
|
|
1052
|
+
"worker_name",
|
|
1053
|
+
"function_id",
|
|
1054
|
+
"invocation_id"
|
|
1055
|
+
]) {
|
|
1056
|
+
const value = str(v[key]);
|
|
1057
|
+
if (value !== void 0) caller[key] = value;
|
|
1058
|
+
}
|
|
1059
|
+
if (depth === 0) {
|
|
1060
|
+
const parent = decodeCaller(v.parent, 1);
|
|
1061
|
+
if (parent) caller.parent = parent;
|
|
1062
|
+
}
|
|
1063
|
+
return caller;
|
|
1064
|
+
}
|
|
1065
|
+
function decodeActivation(v) {
|
|
1066
|
+
if (!isRecord(v) || typeof v.observer_id !== "string") return void 0;
|
|
1067
|
+
const activation = { observer_id: v.observer_id };
|
|
1068
|
+
if (typeof v.activation_id === "string") activation.activation_id = v.activation_id;
|
|
1069
|
+
return activation;
|
|
1070
|
+
}
|
|
1071
|
+
/** An observer as the owner sees it (`observeradded.observer`, `functionregistered.observers[]`). */
|
|
1072
|
+
function decodeObserverInfo(v) {
|
|
1073
|
+
const raw = isRecord(v) ? v : {};
|
|
1074
|
+
const info = {
|
|
1075
|
+
id: String(raw.id ?? ""),
|
|
1076
|
+
args: isRecord(raw.args) ? raw.args : {},
|
|
1077
|
+
filters: raw.filters === void 0 ? {} : raw.filters,
|
|
1078
|
+
target: String(raw.target ?? ""),
|
|
1079
|
+
capture: Array.isArray(raw.capture) ? raw.capture.filter((c) => typeof c === "string") : [...DEFAULT_CAPTURE],
|
|
1080
|
+
on: str(raw.on) ?? "success"
|
|
1081
|
+
};
|
|
1082
|
+
if (isRecord(raw.legacy) && typeof raw.legacy.trigger_type === "string") info.legacy = {
|
|
1083
|
+
trigger_type: raw.legacy.trigger_type,
|
|
1084
|
+
config: raw.legacy.config ?? null
|
|
1085
|
+
};
|
|
1086
|
+
return info;
|
|
1087
|
+
}
|
|
1088
|
+
function decodeFunctionRegistered(v) {
|
|
1089
|
+
return {
|
|
1090
|
+
id: String(v.id ?? ""),
|
|
1091
|
+
namespace: String(v.namespace ?? ""),
|
|
1092
|
+
revision: num(v.revision) ?? 0,
|
|
1093
|
+
local_dispatch: v.local_dispatch === true,
|
|
1094
|
+
observers: Array.isArray(v.observers) ? v.observers.map(decodeObserverInfo) : []
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
function decodeObserverAdded(v) {
|
|
1098
|
+
return {
|
|
1099
|
+
function_id: String(v.function_id ?? ""),
|
|
1100
|
+
namespace: String(v.namespace ?? ""),
|
|
1101
|
+
revision: num(v.revision) ?? 0,
|
|
1102
|
+
observer: decodeObserverInfo(v.observer)
|
|
1103
|
+
};
|
|
1104
|
+
}
|
|
1105
|
+
function decodeObserverRemoved(v) {
|
|
1106
|
+
return {
|
|
1107
|
+
function_id: String(v.function_id ?? ""),
|
|
1108
|
+
namespace: String(v.namespace ?? ""),
|
|
1109
|
+
revision: num(v.revision) ?? 0,
|
|
1110
|
+
id: String(v.id ?? "")
|
|
1111
|
+
};
|
|
1112
|
+
}
|
|
1113
|
+
function decodeObserveResult(v) {
|
|
1114
|
+
const msg = {
|
|
1115
|
+
id: String(v.id ?? ""),
|
|
1116
|
+
state: String(v.state ?? "")
|
|
1117
|
+
};
|
|
1118
|
+
const error = errorBody(v.error);
|
|
1119
|
+
if (error) msg.error = error;
|
|
1120
|
+
if (Array.isArray(v.warnings)) msg.warnings = v.warnings.filter((w) => typeof w === "string");
|
|
1121
|
+
return msg;
|
|
1122
|
+
}
|
|
1123
|
+
function decodeObserverStateChanged(v) {
|
|
1124
|
+
const msg = {
|
|
1125
|
+
id: String(v.id ?? ""),
|
|
1126
|
+
state: String(v.state ?? ""),
|
|
1127
|
+
fires: num(v.fires) ?? 0
|
|
1128
|
+
};
|
|
1129
|
+
const reason = errorBody(v.reason);
|
|
1130
|
+
if (reason) msg.reason = reason;
|
|
1131
|
+
return msg;
|
|
1132
|
+
}
|
|
1133
|
+
function decodeWorkerRegistered(v) {
|
|
1134
|
+
const msg = { worker_id: String(v.worker_id ?? "") };
|
|
1135
|
+
if (typeof v.reattach_token === "string") msg.reattach_token = v.reattach_token;
|
|
1136
|
+
if (Array.isArray(v.features)) msg.features = v.features.filter((f) => typeof f === "string");
|
|
1137
|
+
return msg;
|
|
1138
|
+
}
|
|
1139
|
+
/** The observe fields of an inbound `invokefunction` (`caller`, `observe_depth`, `activation`). */
|
|
1140
|
+
function decodeInvokeFunction(v) {
|
|
1141
|
+
const msg = {
|
|
1142
|
+
function_id: String(v.function_id ?? ""),
|
|
1143
|
+
data: v.data
|
|
1144
|
+
};
|
|
1145
|
+
if (typeof v.invocation_id === "string") msg.invocation_id = v.invocation_id;
|
|
1146
|
+
if (typeof v.traceparent === "string") msg.traceparent = v.traceparent;
|
|
1147
|
+
if (typeof v.baggage === "string") msg.baggage = v.baggage;
|
|
1148
|
+
if (isRecord(v.action)) msg.action = v.action;
|
|
1149
|
+
if (v.metadata !== void 0 && v.metadata !== null) msg.metadata = v.metadata;
|
|
1150
|
+
if (typeof v.namespace === "string") msg.namespace = v.namespace;
|
|
1151
|
+
const caller = decodeCaller(v.caller);
|
|
1152
|
+
if (caller) msg.caller = caller;
|
|
1153
|
+
const depth = num(v.observe_depth);
|
|
1154
|
+
if (depth !== void 0 && depth > 0) msg.observe_depth = depth;
|
|
1155
|
+
const activation = decodeActivation(v.activation);
|
|
1156
|
+
if (activation) msg.activation = activation;
|
|
1157
|
+
return msg;
|
|
1158
|
+
}
|
|
1159
|
+
/** Drops `parent` (one level only). */
|
|
1160
|
+
function stripCaller(caller) {
|
|
1161
|
+
if (!caller) return void 0;
|
|
1162
|
+
const { parent: _, ...rest } = caller;
|
|
1163
|
+
return rest;
|
|
1164
|
+
}
|
|
1165
|
+
/** JSON's view of a message: `undefined` fields left out, no caller-owned objects retained. */
|
|
1166
|
+
function snapshot(value) {
|
|
1167
|
+
return JSON.parse(JSON.stringify(value));
|
|
1168
|
+
}
|
|
1169
|
+
/**
|
|
1170
|
+
* `observe { id, source, target, ... }` from the three arguments of
|
|
1171
|
+
* `iii.observe`. Only what the caller set is sent; the engine applies the
|
|
1172
|
+
* defaults. `resolveNamespace` gives the namespace of an unqualified id (this
|
|
1173
|
+
* worker's, `default` for `engine::*`).
|
|
1174
|
+
*/
|
|
1175
|
+
function buildObserveMessage(id, source, target, options, resolveNamespace) {
|
|
1176
|
+
const targetRef = typeof target === "string" ? { function_id: target } : target;
|
|
1177
|
+
const sourceNamespace = resolveNamespace(source.namespace, source.function_id, "ObserveSource.namespace");
|
|
1178
|
+
const targetNamespace = resolveNamespace(targetRef.namespace, targetRef.function_id, "Target.namespace");
|
|
1179
|
+
return snapshot({
|
|
1180
|
+
id,
|
|
1181
|
+
source: {
|
|
1182
|
+
function_id: source.function_id,
|
|
1183
|
+
namespace: sourceNamespace,
|
|
1184
|
+
args: source.args,
|
|
1185
|
+
filters: source.filters,
|
|
1186
|
+
capture: source.capture,
|
|
1187
|
+
on: source.on,
|
|
1188
|
+
deliver: source.deliver
|
|
1189
|
+
},
|
|
1190
|
+
target: {
|
|
1191
|
+
function_id: targetRef.function_id,
|
|
1192
|
+
namespace: targetNamespace
|
|
1193
|
+
},
|
|
1194
|
+
metadata: options?.metadata,
|
|
1195
|
+
max_fires: options?.max_fires,
|
|
1196
|
+
expires_in_ms: options?.expires_in_ms,
|
|
1197
|
+
max_in_flight: options?.max_in_flight
|
|
1198
|
+
});
|
|
1199
|
+
}
|
|
1200
|
+
/** `registerfunction.observe`: the four fields that travel, or `undefined` when none is set. */
|
|
1201
|
+
function observeDescriptor(hooks) {
|
|
1202
|
+
if (!hooks) return void 0;
|
|
1203
|
+
const descriptor = snapshot({
|
|
1204
|
+
delivery: hooks.delivery,
|
|
1205
|
+
args_format: hooks.args_format,
|
|
1206
|
+
legacy_trigger_type: hooks.legacy_trigger_type,
|
|
1207
|
+
allow: hooks.allow
|
|
1208
|
+
});
|
|
1209
|
+
return Object.keys(descriptor).length > 0 ? descriptor : void 0;
|
|
1210
|
+
}
|
|
1211
|
+
function buildObserverAck(ack) {
|
|
1212
|
+
const msg = {
|
|
1213
|
+
function_id: ack.function_id,
|
|
1214
|
+
id: ack.id,
|
|
1215
|
+
revision: ack.revision
|
|
1216
|
+
};
|
|
1217
|
+
if (ack.namespace !== void 0) msg.namespace = ack.namespace;
|
|
1218
|
+
if (ack.error) msg.error = {
|
|
1219
|
+
code: ack.error.code,
|
|
1220
|
+
message: ack.error.message
|
|
1221
|
+
};
|
|
1222
|
+
return msg;
|
|
1223
|
+
}
|
|
1224
|
+
/**
|
|
1225
|
+
* An outbound `invokefunction`. `observe_depth` is left out when 0, and every
|
|
1226
|
+
* optional field when unset.
|
|
1227
|
+
*/
|
|
1228
|
+
function buildInvokeFunction(init) {
|
|
1229
|
+
const msg = {};
|
|
1230
|
+
if (init.invocation_id !== void 0) msg.invocation_id = init.invocation_id;
|
|
1231
|
+
msg.function_id = init.function_id;
|
|
1232
|
+
msg.data = init.data;
|
|
1233
|
+
if (init.traceparent !== void 0) msg.traceparent = init.traceparent;
|
|
1234
|
+
if (init.baggage !== void 0) msg.baggage = init.baggage;
|
|
1235
|
+
if (init.action !== void 0) msg.action = init.action;
|
|
1236
|
+
if (init.metadata !== void 0) msg.metadata = init.metadata;
|
|
1237
|
+
if (init.namespace !== void 0) msg.namespace = init.namespace;
|
|
1238
|
+
if (init.caller !== void 0) msg.caller = init.caller;
|
|
1239
|
+
if (init.observe_depth !== void 0 && init.observe_depth > 0) msg.observe_depth = init.observe_depth;
|
|
1240
|
+
if (init.activation !== void 0) msg.activation = init.activation;
|
|
1241
|
+
return msg;
|
|
1242
|
+
}
|
|
1243
|
+
/** The caller an outbound call asserts from inside a handler: that handler, and its own caller one level up. */
|
|
1244
|
+
function callerFor(ctx) {
|
|
1245
|
+
const caller = {
|
|
1246
|
+
function_id: ctx.function_id,
|
|
1247
|
+
invocation_id: ctx.invocation_id
|
|
1248
|
+
};
|
|
1249
|
+
const parent = stripCaller(ctx.caller);
|
|
1250
|
+
if (parent && Object.keys(parent).length > 0) caller.parent = parent;
|
|
1251
|
+
return caller;
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
//#endregion
|
|
1255
|
+
//#region src/observable.ts
|
|
1256
|
+
/**
|
|
1257
|
+
* The owner side of observe (sdk.md §1, §4.1–§4.3): per-function observer
|
|
1258
|
+
* state, the observe hooks, the `Observer` object handed to them, and the
|
|
1259
|
+
* reports of local invocations and `obs.emit` events.
|
|
1260
|
+
*/
|
|
1261
|
+
/** CONTRACT D11: `onObserverAdded` (and `onObserverRemoved`) still running after this is `OWNER_TIMEOUT`. */
|
|
1262
|
+
const OBSERVE_HOOK_TIMEOUT_MS = 3e4;
|
|
1263
|
+
function sameJson(a, b) {
|
|
1264
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
1265
|
+
}
|
|
1266
|
+
function rejectionBody(error) {
|
|
1267
|
+
if (error instanceof ObserveRejection) return {
|
|
1268
|
+
code: error.code,
|
|
1269
|
+
message: error.message
|
|
1270
|
+
};
|
|
1271
|
+
return {
|
|
1272
|
+
code: "OBSERVE_REJECTED",
|
|
1273
|
+
message: error instanceof Error ? error.message : String(error)
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1276
|
+
function onAccepts(on, ok) {
|
|
1277
|
+
return on === "complete" || (on === "success" ? ok : on === "error" ? !ok : false);
|
|
1278
|
+
}
|
|
1279
|
+
/** The `Observer` an owner receives. Its identity is stable while the observer lives. */
|
|
1280
|
+
var ObserverImpl = class {
|
|
1281
|
+
constructor(owner, info, filter, revision) {
|
|
1282
|
+
this.owner = owner;
|
|
1283
|
+
this.active = false;
|
|
1284
|
+
this.adding = false;
|
|
1285
|
+
this.id = info.id;
|
|
1286
|
+
this.function_id = owner.functionId;
|
|
1287
|
+
this.args = info.args;
|
|
1288
|
+
this.filters = info.filters;
|
|
1289
|
+
this.target = info.target;
|
|
1290
|
+
this.capture = info.capture;
|
|
1291
|
+
this.on = info.on;
|
|
1292
|
+
if (info.legacy) this.legacy = info.legacy;
|
|
1293
|
+
this.filter = filter;
|
|
1294
|
+
this.revision = revision;
|
|
1295
|
+
}
|
|
1296
|
+
/** @internal Takes the engine's current view of a kept observer. */
|
|
1297
|
+
update(info, filter) {
|
|
1298
|
+
this.filters = info.filters;
|
|
1299
|
+
this.filter = filter;
|
|
1300
|
+
this.target = info.target;
|
|
1301
|
+
this.capture = info.capture;
|
|
1302
|
+
this.on = info.on;
|
|
1303
|
+
}
|
|
1304
|
+
matches(doc) {
|
|
1305
|
+
return this.filter.matches(doc);
|
|
1306
|
+
}
|
|
1307
|
+
emit(event) {
|
|
1308
|
+
return this.owner.emit(this, event);
|
|
1309
|
+
}
|
|
1310
|
+
call(payload, opts) {
|
|
1311
|
+
return this.owner.call(this, payload, opts?.timeoutMs);
|
|
1312
|
+
}
|
|
1313
|
+
reject(code, message) {
|
|
1314
|
+
this.owner.reject(this, code, message);
|
|
1315
|
+
}
|
|
1316
|
+
toJSON() {
|
|
1317
|
+
return {
|
|
1318
|
+
id: this.id,
|
|
1319
|
+
function_id: this.function_id,
|
|
1320
|
+
args: this.args,
|
|
1321
|
+
filters: this.filters,
|
|
1322
|
+
target: this.target,
|
|
1323
|
+
capture: this.capture,
|
|
1324
|
+
on: this.on,
|
|
1325
|
+
...this.legacy ? { legacy: this.legacy } : {}
|
|
1326
|
+
};
|
|
1327
|
+
}
|
|
1328
|
+
};
|
|
1329
|
+
/**
|
|
1330
|
+
* One registered function's observers, as the engine pushed them
|
|
1331
|
+
* (`functionregistered`, `observeradded`, `observerremoved`). Hooks run one
|
|
1332
|
+
* at a time, in revision order.
|
|
1333
|
+
*/
|
|
1334
|
+
var FunctionObservers = class {
|
|
1335
|
+
constructor(functionId, hooks, localDispatchOption, hasHandler, host) {
|
|
1336
|
+
this.functionId = functionId;
|
|
1337
|
+
this.hooks = hooks;
|
|
1338
|
+
this.localDispatchOption = localDispatchOption;
|
|
1339
|
+
this.hasHandler = hasHandler;
|
|
1340
|
+
this.host = host;
|
|
1341
|
+
this.confirmed = false;
|
|
1342
|
+
this.confirmedEpoch = -1;
|
|
1343
|
+
this.localDispatch = false;
|
|
1344
|
+
this.revision = -1;
|
|
1345
|
+
this.known = /* @__PURE__ */ new Map();
|
|
1346
|
+
this.compiled = [];
|
|
1347
|
+
this.queue = Promise.resolve();
|
|
1348
|
+
this.disposed = false;
|
|
1349
|
+
this.releases = 0;
|
|
1350
|
+
this.delivery = hooks?.delivery === "owner" ? "owner" : "auto";
|
|
1351
|
+
}
|
|
1352
|
+
/** Callbacks or owner delivery: what needs `observe.v1` on both sides. */
|
|
1353
|
+
get needsObserve() {
|
|
1354
|
+
return this.delivery === "owner" || !!this.hooks?.onObserverAdded || !!this.hooks?.onObserverRemoved;
|
|
1355
|
+
}
|
|
1356
|
+
isObserved() {
|
|
1357
|
+
return this.compiled.length > 0;
|
|
1358
|
+
}
|
|
1359
|
+
observers() {
|
|
1360
|
+
return [...this.compiled];
|
|
1361
|
+
}
|
|
1362
|
+
/** `functionregistered`: always accepted; replaces the set (§4.2). */
|
|
1363
|
+
onFunctionRegistered(msg, epoch) {
|
|
1364
|
+
if (this.disposed) return;
|
|
1365
|
+
this.confirmed = true;
|
|
1366
|
+
this.releasedEpoch = void 0;
|
|
1367
|
+
this.localDispatch = msg.local_dispatch && this.localDispatchOption && this.hasHandler;
|
|
1368
|
+
this.namespace = msg.namespace;
|
|
1369
|
+
this.revision = msg.revision;
|
|
1370
|
+
this.enqueue(async () => {
|
|
1371
|
+
try {
|
|
1372
|
+
await this.applySet(msg.observers, msg.revision, msg.namespace);
|
|
1373
|
+
} finally {
|
|
1374
|
+
this.confirmedEpoch = epoch;
|
|
1375
|
+
this.host.reporter.flush();
|
|
1376
|
+
}
|
|
1377
|
+
});
|
|
1378
|
+
}
|
|
1379
|
+
onObserverAdded(msg) {
|
|
1380
|
+
if (this.disposed || msg.revision <= this.revision) return;
|
|
1381
|
+
this.revision = msg.revision;
|
|
1382
|
+
this.enqueue(async () => {
|
|
1383
|
+
if (this.known.get(msg.observer.id)?.rejection) await this.remove(msg.observer.id);
|
|
1384
|
+
await this.add(msg.observer, msg.revision, msg.namespace);
|
|
1385
|
+
});
|
|
1386
|
+
}
|
|
1387
|
+
onObserverRemoved(msg) {
|
|
1388
|
+
if (this.disposed || msg.revision <= this.revision) return;
|
|
1389
|
+
this.revision = msg.revision;
|
|
1390
|
+
this.enqueue(() => this.remove(msg.id));
|
|
1391
|
+
}
|
|
1392
|
+
/**
|
|
1393
|
+
* `RegistrationRejected{FUNCTION_NAMESPACE_CONFLICT}`: no local dispatch, no
|
|
1394
|
+
* observers, and its held reports are discarded (they could never be
|
|
1395
|
+
* confirmed, and would starve other functions of buffer).
|
|
1396
|
+
*/
|
|
1397
|
+
onRegistrationRejected(epoch) {
|
|
1398
|
+
this.confirmed = false;
|
|
1399
|
+
this.confirmedEpoch = -1;
|
|
1400
|
+
this.localDispatch = false;
|
|
1401
|
+
this.releasedEpoch = epoch;
|
|
1402
|
+
this.releases++;
|
|
1403
|
+
this.host.reporter.discard(this.functionId);
|
|
1404
|
+
this.dropAll();
|
|
1405
|
+
}
|
|
1406
|
+
/** The function was unregistered. */
|
|
1407
|
+
dispose() {
|
|
1408
|
+
this.disposed = true;
|
|
1409
|
+
this.onRegistrationRejected(-1);
|
|
1410
|
+
}
|
|
1411
|
+
/**
|
|
1412
|
+
* Stops delivery at once, then removes every observer through the hook
|
|
1413
|
+
* queue, after the adds queued before it (which undo themselves: `add`).
|
|
1414
|
+
*/
|
|
1415
|
+
dropAll() {
|
|
1416
|
+
for (const obs of this.compiled) obs.active = false;
|
|
1417
|
+
this.compiled = [];
|
|
1418
|
+
this.enqueue(async () => {
|
|
1419
|
+
for (const id of [...this.known.keys()]) await this.remove(id);
|
|
1420
|
+
});
|
|
1421
|
+
}
|
|
1422
|
+
enqueue(task) {
|
|
1423
|
+
this.queue = this.queue.then(task).catch((error) => {
|
|
1424
|
+
this.host.logError(`Observe hook failed for ${this.functionId}`, error);
|
|
1425
|
+
});
|
|
1426
|
+
}
|
|
1427
|
+
activate(obs) {
|
|
1428
|
+
if (obs.active) return;
|
|
1429
|
+
obs.active = true;
|
|
1430
|
+
this.compiled = [...this.compiled, obs];
|
|
1431
|
+
}
|
|
1432
|
+
deactivate(obs) {
|
|
1433
|
+
if (!obs.active) return;
|
|
1434
|
+
obs.active = false;
|
|
1435
|
+
this.compiled = this.compiled.filter((o) => o !== obs);
|
|
1436
|
+
}
|
|
1437
|
+
ack(info, revision, namespace, error) {
|
|
1438
|
+
this.host.sendAck({
|
|
1439
|
+
function_id: this.functionId,
|
|
1440
|
+
namespace,
|
|
1441
|
+
id: info.id,
|
|
1442
|
+
revision,
|
|
1443
|
+
...error ? { error } : {}
|
|
1444
|
+
});
|
|
1445
|
+
}
|
|
1446
|
+
/** Diffs the engine's full set against what this SDK holds. */
|
|
1447
|
+
async applySet(list, revision, namespace) {
|
|
1448
|
+
const incoming = new Set(list.map((o) => o.id));
|
|
1449
|
+
for (const id of [...this.known.keys()]) if (!incoming.has(id)) await this.remove(id);
|
|
1450
|
+
for (const info of list) {
|
|
1451
|
+
const existing = this.known.get(info.id);
|
|
1452
|
+
if (existing && sameJson(existing.args, info.args) && sameJson(existing.legacy, info.legacy)) this.keep(existing, info, revision, namespace);
|
|
1453
|
+
else {
|
|
1454
|
+
if (existing) await this.remove(info.id);
|
|
1455
|
+
await this.add(info, revision, namespace);
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
/**
|
|
1460
|
+
* A kept observer: the hook already ran for it; take the engine's filters
|
|
1461
|
+
* and ack it again, or repeat the owner's late rejection of it.
|
|
1462
|
+
*/
|
|
1463
|
+
keep(obs, info, revision, namespace) {
|
|
1464
|
+
if (obs.rejection) {
|
|
1465
|
+
obs.revision = revision;
|
|
1466
|
+
this.ack(info, revision, namespace, obs.rejection);
|
|
1467
|
+
return;
|
|
1468
|
+
}
|
|
1469
|
+
let filter = obs.filter;
|
|
1470
|
+
if (!sameJson(obs.filters, info.filters)) try {
|
|
1471
|
+
filter = compileFilter(info.filters, { trusted: true });
|
|
1472
|
+
} catch (error) {
|
|
1473
|
+
obs.revision = revision;
|
|
1474
|
+
this.deactivate(obs);
|
|
1475
|
+
this.ack(info, revision, namespace, {
|
|
1476
|
+
code: "INVALID_FILTER",
|
|
1477
|
+
message: error.message
|
|
1478
|
+
});
|
|
1479
|
+
return;
|
|
1480
|
+
}
|
|
1481
|
+
obs.update(info, filter);
|
|
1482
|
+
obs.revision = revision;
|
|
1483
|
+
this.activate(obs);
|
|
1484
|
+
this.ack(info, revision, namespace);
|
|
1485
|
+
}
|
|
1486
|
+
/** handleAdded (§4.2): hook, then the compiled set, then the ack. */
|
|
1487
|
+
async add(info, revision, namespace) {
|
|
1488
|
+
if (this.disposed || this.releasedEpoch !== void 0) return;
|
|
1489
|
+
const releases = this.releases;
|
|
1490
|
+
const existing = this.known.get(info.id);
|
|
1491
|
+
if (existing) {
|
|
1492
|
+
this.keep(existing, info, revision, namespace);
|
|
1493
|
+
return;
|
|
1494
|
+
}
|
|
1495
|
+
let filter;
|
|
1496
|
+
try {
|
|
1497
|
+
filter = compileFilter(info.filters, { trusted: true });
|
|
1498
|
+
} catch (error) {
|
|
1499
|
+
this.ack(info, revision, namespace, {
|
|
1500
|
+
code: "INVALID_FILTER",
|
|
1501
|
+
message: error.message
|
|
1502
|
+
});
|
|
1503
|
+
return;
|
|
1504
|
+
}
|
|
1505
|
+
const obs = new ObserverImpl(this, info, filter, revision);
|
|
1506
|
+
const onAdded = this.hooks?.onObserverAdded;
|
|
1507
|
+
if (onAdded) {
|
|
1508
|
+
obs.adding = true;
|
|
1509
|
+
const outcome = await this.runHook(() => onAdded.call(this.hooks, obs));
|
|
1510
|
+
obs.adding = false;
|
|
1511
|
+
if (!outcome.ok) {
|
|
1512
|
+
this.ack(info, revision, namespace, {
|
|
1513
|
+
code: outcome.code,
|
|
1514
|
+
message: outcome.message
|
|
1515
|
+
});
|
|
1516
|
+
if (outcome.timedOut) outcome.late.then(() => this.enqueue(() => this.callRemoved(obs)), () => void 0);
|
|
1517
|
+
return;
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
if (this.disposed || this.releases !== releases) {
|
|
1521
|
+
await this.callRemoved(obs);
|
|
1522
|
+
return;
|
|
1523
|
+
}
|
|
1524
|
+
this.known.set(obs.id, obs);
|
|
1525
|
+
if (obs.rejection) {
|
|
1526
|
+
this.ack(info, revision, namespace, obs.rejection);
|
|
1527
|
+
return;
|
|
1528
|
+
}
|
|
1529
|
+
this.activate(obs);
|
|
1530
|
+
this.ack(info, revision, namespace);
|
|
1531
|
+
}
|
|
1532
|
+
async remove(id) {
|
|
1533
|
+
const obs = this.known.get(id);
|
|
1534
|
+
if (!obs) return;
|
|
1535
|
+
this.known.delete(id);
|
|
1536
|
+
this.deactivate(obs);
|
|
1537
|
+
await this.callRemoved(obs);
|
|
1538
|
+
}
|
|
1539
|
+
async callRemoved(obs) {
|
|
1540
|
+
const onRemoved = this.hooks?.onObserverRemoved;
|
|
1541
|
+
if (!onRemoved) return;
|
|
1542
|
+
const outcome = await this.runHook(() => onRemoved.call(this.hooks, obs));
|
|
1543
|
+
if (!outcome.ok) this.host.logError(`onObserverRemoved failed for observer ${obs.id} of ${this.functionId}: ${outcome.message}`);
|
|
1544
|
+
}
|
|
1545
|
+
async runHook(fn) {
|
|
1546
|
+
const run = Promise.resolve().then(fn);
|
|
1547
|
+
let timer;
|
|
1548
|
+
const timeoutMs = this.host.hookTimeoutMs();
|
|
1549
|
+
const timeout = new Promise((resolve) => {
|
|
1550
|
+
timer = setTimeout(() => resolve("timeout"), timeoutMs);
|
|
1551
|
+
require_utils.unrefTimer(timer);
|
|
1552
|
+
});
|
|
1553
|
+
try {
|
|
1554
|
+
if (await Promise.race([run.then(() => "done"), timeout]) === "timeout") return {
|
|
1555
|
+
ok: false,
|
|
1556
|
+
code: "OWNER_TIMEOUT",
|
|
1557
|
+
message: `observe hook of ${this.functionId} still running after ${timeoutMs}ms`,
|
|
1558
|
+
timedOut: true,
|
|
1559
|
+
late: run
|
|
1560
|
+
};
|
|
1561
|
+
return { ok: true };
|
|
1562
|
+
} catch (error) {
|
|
1563
|
+
return {
|
|
1564
|
+
ok: false,
|
|
1565
|
+
...rejectionBody(error),
|
|
1566
|
+
timedOut: false,
|
|
1567
|
+
late: run
|
|
1568
|
+
};
|
|
1569
|
+
} finally {
|
|
1570
|
+
if (timer) clearTimeout(timer);
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
requireOwnerDelivery(what) {
|
|
1574
|
+
if (this.delivery !== "owner") throw new InvocationError({
|
|
1575
|
+
code: "NOT_OWNER_DELIVERED",
|
|
1576
|
+
message: `obs.${what}() needs an owner-delivered function; ${this.functionId} is auto-delivered (observe.delivery)`,
|
|
1577
|
+
function_id: this.functionId
|
|
1578
|
+
});
|
|
1579
|
+
}
|
|
1580
|
+
isActive(obs) {
|
|
1581
|
+
return obs.active && this.known.get(obs.id) === obs;
|
|
1582
|
+
}
|
|
1583
|
+
/**
|
|
1584
|
+
* The caller an event carries (sdk.md §1): inside the function's own
|
|
1585
|
+
* handler, that invocation's caller; inside another handler, that handler;
|
|
1586
|
+
* outside any handler, this worker only.
|
|
1587
|
+
*/
|
|
1588
|
+
eventCaller(cur) {
|
|
1589
|
+
if (cur && cur.function_id === this.functionId) return {
|
|
1590
|
+
caller: cur.caller,
|
|
1591
|
+
own: true
|
|
1592
|
+
};
|
|
1593
|
+
const { worker_id, worker_name } = this.host.identity();
|
|
1594
|
+
const caller = worker_id !== void 0 ? {
|
|
1595
|
+
worker_id,
|
|
1596
|
+
worker_name
|
|
1597
|
+
} : { worker_name };
|
|
1598
|
+
if (cur) {
|
|
1599
|
+
caller.function_id = cur.function_id;
|
|
1600
|
+
caller.invocation_id = cur.invocation_id;
|
|
1601
|
+
const parent = stripCaller(cur.caller);
|
|
1602
|
+
if (parent && Object.keys(parent).length > 0) caller.parent = parent;
|
|
1603
|
+
}
|
|
1604
|
+
return {
|
|
1605
|
+
caller,
|
|
1606
|
+
own: false
|
|
1607
|
+
};
|
|
1608
|
+
}
|
|
1609
|
+
/**
|
|
1610
|
+
* Hands `event` to one observer. `false`, and nothing sent, when its
|
|
1611
|
+
* filters reject the event or it is no longer active (removed or rejected
|
|
1612
|
+
* meanwhile): an owner's fan-out loop must not stop for one observer.
|
|
1613
|
+
*/
|
|
1614
|
+
emit(obs, event) {
|
|
1615
|
+
this.requireOwnerDelivery("emit");
|
|
1616
|
+
if (!this.isActive(obs)) return false;
|
|
1617
|
+
const cur = callContext();
|
|
1618
|
+
const { caller, own } = this.eventCaller(cur);
|
|
1619
|
+
const metadata = cur?.metadata;
|
|
1620
|
+
if (!obs.filter.matches({
|
|
1621
|
+
input: event,
|
|
1622
|
+
caller,
|
|
1623
|
+
metadata
|
|
1624
|
+
})) return false;
|
|
1625
|
+
const values = { input: event };
|
|
1626
|
+
if (caller !== void 0) values.caller = caller;
|
|
1627
|
+
if (metadata !== void 0) values.metadata = metadata;
|
|
1628
|
+
const trace = cur ? {
|
|
1629
|
+
traceparent: cur.traceparent,
|
|
1630
|
+
baggage: cur.baggage
|
|
1631
|
+
} : this.host.traceContext();
|
|
1632
|
+
this.host.reporter.pushEmit({
|
|
1633
|
+
function_id: this.functionId,
|
|
1634
|
+
namespace: this.namespace,
|
|
1635
|
+
invocation_id: own && cur ? cur.invocation_id : require_utils.randomUUID(),
|
|
1636
|
+
status: "success",
|
|
1637
|
+
values,
|
|
1638
|
+
captures: obs.capture,
|
|
1639
|
+
started_at_ms: Date.now(),
|
|
1640
|
+
duration_ms: 0,
|
|
1641
|
+
observe_depth: cur ? cur.observe_depth : callDepth(),
|
|
1642
|
+
traceparent: trace.traceparent,
|
|
1643
|
+
baggage: trace.baggage,
|
|
1644
|
+
observer_id: obs.id,
|
|
1645
|
+
event,
|
|
1646
|
+
context: cur
|
|
1647
|
+
});
|
|
1648
|
+
return true;
|
|
1649
|
+
}
|
|
1650
|
+
async call(obs, payload, timeoutMs) {
|
|
1651
|
+
this.requireOwnerDelivery("call");
|
|
1652
|
+
if (!this.isActive(obs)) throw new InvocationError({
|
|
1653
|
+
code: "OBSERVER_NOT_ACTIVE",
|
|
1654
|
+
message: `observer ${obs.id} of ${this.functionId} is not active`,
|
|
1655
|
+
function_id: this.functionId
|
|
1656
|
+
});
|
|
1657
|
+
const cur = callContext();
|
|
1658
|
+
const { caller } = this.eventCaller(cur);
|
|
1659
|
+
if (!obs.filter.matches({
|
|
1660
|
+
input: payload,
|
|
1661
|
+
caller,
|
|
1662
|
+
metadata: cur?.metadata
|
|
1663
|
+
})) throw new InvocationError({
|
|
1664
|
+
code: "FILTERS_NOT_MATCHED",
|
|
1665
|
+
message: `the filters of observer ${obs.id} reject this payload`,
|
|
1666
|
+
function_id: this.functionId
|
|
1667
|
+
});
|
|
1668
|
+
return this.host.callTarget(obs.target, obs.id, payload, timeoutMs);
|
|
1669
|
+
}
|
|
1670
|
+
reject(obs, code, message) {
|
|
1671
|
+
if (obs.adding) {
|
|
1672
|
+
obs.rejection = {
|
|
1673
|
+
code,
|
|
1674
|
+
message
|
|
1675
|
+
};
|
|
1676
|
+
return;
|
|
1677
|
+
}
|
|
1678
|
+
if (this.known.get(obs.id) !== obs) return;
|
|
1679
|
+
obs.rejection = {
|
|
1680
|
+
code,
|
|
1681
|
+
message
|
|
1682
|
+
};
|
|
1683
|
+
this.deactivate(obs);
|
|
1684
|
+
this.host.sendAck({
|
|
1685
|
+
function_id: this.functionId,
|
|
1686
|
+
namespace: this.namespace,
|
|
1687
|
+
id: obs.id,
|
|
1688
|
+
revision: obs.revision,
|
|
1689
|
+
error: {
|
|
1690
|
+
code,
|
|
1691
|
+
message
|
|
1692
|
+
}
|
|
1693
|
+
});
|
|
1694
|
+
}
|
|
1695
|
+
/**
|
|
1696
|
+
* Evaluates `set` (the compiled set captured when the call started) on a
|
|
1697
|
+
* finished local invocation of an auto function, and reports it when an
|
|
1698
|
+
* observer matches. Never throws.
|
|
1699
|
+
*/
|
|
1700
|
+
reportLocal(set, init) {
|
|
1701
|
+
if (this.delivery !== "auto" || set.length === 0) return;
|
|
1702
|
+
const doc = {
|
|
1703
|
+
input: init.input,
|
|
1704
|
+
caller: init.caller,
|
|
1705
|
+
metadata: init.metadata
|
|
1706
|
+
};
|
|
1707
|
+
if (init.ok) doc.output = init.output;
|
|
1708
|
+
else doc.error = init.error;
|
|
1709
|
+
const matched = [];
|
|
1710
|
+
const captures = /* @__PURE__ */ new Set();
|
|
1711
|
+
for (const obs of set) {
|
|
1712
|
+
if (!onAccepts(obs.on, init.ok)) continue;
|
|
1713
|
+
if (!obs.filter.matches(doc)) continue;
|
|
1714
|
+
matched.push(obs.id);
|
|
1715
|
+
for (const c of obs.capture) captures.add(c);
|
|
1716
|
+
}
|
|
1717
|
+
if (matched.length === 0) return;
|
|
1718
|
+
const values = { input: init.input };
|
|
1719
|
+
if (init.ok) values.output = init.output;
|
|
1720
|
+
else values.error = init.error;
|
|
1721
|
+
if (init.caller !== void 0) values.caller = init.caller;
|
|
1722
|
+
if (init.metadata !== void 0) values.metadata = init.metadata;
|
|
1723
|
+
this.host.reporter.push({
|
|
1724
|
+
function_id: this.functionId,
|
|
1725
|
+
namespace: this.namespace,
|
|
1726
|
+
invocation_id: init.invocation_id,
|
|
1727
|
+
matched,
|
|
1728
|
+
status: init.ok ? "success" : "error",
|
|
1729
|
+
values,
|
|
1730
|
+
captures,
|
|
1731
|
+
started_at_ms: init.started_at_ms,
|
|
1732
|
+
duration_ms: init.duration_ms,
|
|
1733
|
+
observe_depth: init.observe_depth,
|
|
1734
|
+
traceparent: init.traceparent,
|
|
1735
|
+
baggage: init.baggage
|
|
1736
|
+
});
|
|
1737
|
+
}
|
|
1738
|
+
};
|
|
1739
|
+
|
|
1740
|
+
//#endregion
|
|
1741
|
+
//#region src/observer-handle.ts
|
|
1742
|
+
/**
|
|
1743
|
+
* The observing side of observe (sdk.md §2): the handle `iii.observe`
|
|
1744
|
+
* returns, kept for replay until it is disposed.
|
|
1745
|
+
*/
|
|
1746
|
+
/** Active → resolved; error / disposed → rejected; otherwise still waiting. */
|
|
1747
|
+
function settlement(id, state, reason) {
|
|
1748
|
+
if (state === "active") return Promise.resolve();
|
|
1749
|
+
if (state === "error" || state === "disposed") {
|
|
1750
|
+
const why = reason ?? {
|
|
1751
|
+
code: state === "error" ? "OBSERVE_FAILED" : "UNOBSERVED",
|
|
1752
|
+
message: `observer ${id} is ${state}`
|
|
1753
|
+
};
|
|
1754
|
+
return Promise.reject(new ObserveRejection(why.code, why.message));
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
var ObserverHandleImpl = class {
|
|
1758
|
+
constructor(id, message, onDispose, logError) {
|
|
1759
|
+
this.id = id;
|
|
1760
|
+
this.message = message;
|
|
1761
|
+
this.onDispose = onDispose;
|
|
1762
|
+
this.logError = logError;
|
|
1763
|
+
this.currentState = "pending";
|
|
1764
|
+
this.listeners = /* @__PURE__ */ new Set();
|
|
1765
|
+
this.undelivered = [];
|
|
1766
|
+
this.delivering = false;
|
|
1767
|
+
this.sent = false;
|
|
1768
|
+
}
|
|
1769
|
+
get state() {
|
|
1770
|
+
return this.currentState;
|
|
1771
|
+
}
|
|
1772
|
+
get reason() {
|
|
1773
|
+
return this.currentReason;
|
|
1774
|
+
}
|
|
1775
|
+
ready() {
|
|
1776
|
+
const settled = settlement(this.id, this.currentState, this.currentReason);
|
|
1777
|
+
if (settled) return settled;
|
|
1778
|
+
return new Promise((resolve, reject) => {
|
|
1779
|
+
const off = this.onStateChange((state, reason) => {
|
|
1780
|
+
const result = settlement(this.id, state, reason);
|
|
1781
|
+
if (!result) return;
|
|
1782
|
+
off();
|
|
1783
|
+
result.then(resolve, reject);
|
|
1784
|
+
});
|
|
1785
|
+
});
|
|
1786
|
+
}
|
|
1787
|
+
onStateChange(listener) {
|
|
1788
|
+
this.listeners.add(listener);
|
|
1789
|
+
return () => {
|
|
1790
|
+
this.listeners.delete(listener);
|
|
1791
|
+
};
|
|
1792
|
+
}
|
|
1793
|
+
async dispose() {
|
|
1794
|
+
if (this.currentState === "disposed") return;
|
|
1795
|
+
this.onDispose(this);
|
|
1796
|
+
this.setState("disposed", {
|
|
1797
|
+
code: "UNOBSERVED",
|
|
1798
|
+
message: "disposed by the observing worker"
|
|
1799
|
+
});
|
|
1800
|
+
}
|
|
1801
|
+
/** @internal A state from the engine (`observeresult`, `observerstatechanged`) or the SDK. */
|
|
1802
|
+
setState(state, reason) {
|
|
1803
|
+
if (this.currentState === "disposed") return;
|
|
1804
|
+
const changed = state !== this.currentState || reason?.code !== this.currentReason?.code || reason?.message !== this.currentReason?.message;
|
|
1805
|
+
this.currentState = state;
|
|
1806
|
+
this.currentReason = reason;
|
|
1807
|
+
if (!changed) return;
|
|
1808
|
+
this.undelivered.push([state, reason]);
|
|
1809
|
+
if (this.delivering) return;
|
|
1810
|
+
this.delivering = true;
|
|
1811
|
+
queueMicrotask(() => this.deliver());
|
|
1812
|
+
}
|
|
1813
|
+
deliver() {
|
|
1814
|
+
for (let next = this.undelivered.shift(); next; next = this.undelivered.shift()) {
|
|
1815
|
+
const [state, reason] = next;
|
|
1816
|
+
for (const listener of [...this.listeners]) try {
|
|
1817
|
+
listener(state, reason);
|
|
1818
|
+
} catch (error) {
|
|
1819
|
+
this.logError(`Observer ${this.id} state listener threw`, error);
|
|
1820
|
+
}
|
|
1821
|
+
}
|
|
1822
|
+
this.delivering = false;
|
|
1823
|
+
}
|
|
1824
|
+
};
|
|
1825
|
+
const STATES = new Set([
|
|
1826
|
+
"pending",
|
|
1827
|
+
"active",
|
|
1828
|
+
"suspended",
|
|
1829
|
+
"error",
|
|
1830
|
+
"disposed"
|
|
1831
|
+
]);
|
|
1832
|
+
/** A wire state this SDK does not know (a newer engine) reads as `pending`. */
|
|
1833
|
+
function toObserverState(state) {
|
|
1834
|
+
return STATES.has(state) ? state : "pending";
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1837
|
+
//#endregion
|
|
1838
|
+
//#region src/reporter.ts
|
|
1839
|
+
const PART_ORDER = [
|
|
1840
|
+
"input",
|
|
1841
|
+
"output",
|
|
1842
|
+
"error",
|
|
1843
|
+
"caller",
|
|
1844
|
+
"metadata"
|
|
1845
|
+
];
|
|
1846
|
+
const DEFAULT_REPORTER_LIMITS = {
|
|
1847
|
+
batchItems: 256,
|
|
1848
|
+
lingerMs: 5,
|
|
1849
|
+
maxItems: 1e4,
|
|
1850
|
+
maxBytes: 8 * 1024 * 1024,
|
|
1851
|
+
maxFrameBytes: 16 * 1024 * 1024,
|
|
1852
|
+
statsIntervalMs: 1e4
|
|
1853
|
+
};
|
|
1854
|
+
var ReportItem = class {
|
|
1855
|
+
constructor(init, emit, coalesceKey, context) {
|
|
1856
|
+
this.init = init;
|
|
1857
|
+
this.emit = emit;
|
|
1858
|
+
this.coalesceKey = coalesceKey;
|
|
1859
|
+
this.context = context;
|
|
1860
|
+
this.parts = /* @__PURE__ */ new Map();
|
|
1861
|
+
this.captured = /* @__PURE__ */ new Set();
|
|
1862
|
+
this.json = "";
|
|
1863
|
+
this.bytes = 0;
|
|
1864
|
+
}
|
|
1865
|
+
/** Adds the parts `captures` asks for that are not in the item yet. */
|
|
1866
|
+
capture(captures) {
|
|
1867
|
+
for (const c of captures) {
|
|
1868
|
+
if (this.captured.has(c)) continue;
|
|
1869
|
+
this.captured.add(c);
|
|
1870
|
+
if (!PART_ORDER.includes(c)) continue;
|
|
1871
|
+
const part = c;
|
|
1872
|
+
if (!(part in this.init.values)) continue;
|
|
1873
|
+
const encoded = encodeJson(this.init.values[part]);
|
|
1874
|
+
if (encoded !== void 0) this.parts.set(part, encoded);
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
/** What a merge can change, to undo it. */
|
|
1878
|
+
save() {
|
|
1879
|
+
return {
|
|
1880
|
+
matched: this.init.matched.length,
|
|
1881
|
+
captured: [...this.captured],
|
|
1882
|
+
parts: [...this.parts],
|
|
1883
|
+
json: this.json,
|
|
1884
|
+
bytes: this.bytes
|
|
1885
|
+
};
|
|
1886
|
+
}
|
|
1887
|
+
restore(state) {
|
|
1888
|
+
this.init.matched.length = state.matched;
|
|
1889
|
+
this.captured.clear();
|
|
1890
|
+
for (const c of state.captured) this.captured.add(c);
|
|
1891
|
+
this.parts.clear();
|
|
1892
|
+
for (const [part, encoded] of state.parts) this.parts.set(part, encoded);
|
|
1893
|
+
this.json = state.json;
|
|
1894
|
+
this.bytes = state.bytes;
|
|
1895
|
+
}
|
|
1896
|
+
/** Assembles the wire JSON from the pre-encoded parts. */
|
|
1897
|
+
render() {
|
|
1898
|
+
const i = this.init;
|
|
1899
|
+
let s = `{"function_id":${JSON.stringify(i.function_id)}`;
|
|
1900
|
+
if (i.namespace !== void 0) s += `,"namespace":${JSON.stringify(i.namespace)}`;
|
|
1901
|
+
s += `,"invocation_id":${JSON.stringify(i.invocation_id)},"matched":${JSON.stringify(i.matched)}`;
|
|
1902
|
+
s += `,"status":${JSON.stringify(i.status)}`;
|
|
1903
|
+
for (const part of PART_ORDER) {
|
|
1904
|
+
const encoded = this.parts.get(part);
|
|
1905
|
+
if (encoded !== void 0) s += `,"${part}":${encoded}`;
|
|
1906
|
+
}
|
|
1907
|
+
s += `,"started_at_ms":${finite(i.started_at_ms)},"duration_ms":${finite(i.duration_ms)}`;
|
|
1908
|
+
s += `,"observe_depth":${finite(i.observe_depth)}`;
|
|
1909
|
+
if (i.traceparent !== void 0) s += `,"traceparent":${JSON.stringify(i.traceparent)}`;
|
|
1910
|
+
if (i.baggage !== void 0) s += `,"baggage":${JSON.stringify(i.baggage)}`;
|
|
1911
|
+
this.json = wellFormed(`${s}}`);
|
|
1912
|
+
this.bytes = byteLength(this.json);
|
|
1913
|
+
}
|
|
1914
|
+
};
|
|
1915
|
+
/**
|
|
1916
|
+
* Replaces lone surrogates with U+FFFD (CONTRACT parity 32): `JSON.stringify`
|
|
1917
|
+
* writes one as `\ud800`, which the engine's strict decoder refuses, and it
|
|
1918
|
+
* would take the whole batch down with it. `JSON.stringify` escapes nothing
|
|
1919
|
+
* else in that range (a valid pair is written as is), so every `\udXXX`
|
|
1920
|
+
* escape it produced is a lone surrogate. Fast path: no `\ud` at all.
|
|
35
1921
|
*/
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
1922
|
+
function wellFormed(json) {
|
|
1923
|
+
if (!json.includes("\\ud")) return json;
|
|
1924
|
+
return json.replace(/(\\+)u(d[89a-f][0-9a-f]{2})/g, (match, slashes) => slashes.length % 2 === 1 ? `${slashes.slice(0, -1)}\\ufffd` : match);
|
|
1925
|
+
}
|
|
1926
|
+
function finite(n) {
|
|
1927
|
+
return Number.isFinite(n) ? n : 0;
|
|
1928
|
+
}
|
|
1929
|
+
function byteLength(s) {
|
|
1930
|
+
return require_utils.utf8ByteLength(s);
|
|
1931
|
+
}
|
|
1932
|
+
/** JSON text of a value as the remote path would send it; `BigInt` is written as its number. */
|
|
1933
|
+
function encodeJson(value) {
|
|
1934
|
+
try {
|
|
1935
|
+
return JSON.stringify(value);
|
|
1936
|
+
} catch (error) {
|
|
1937
|
+
if (!(error instanceof TypeError)) throw error;
|
|
1938
|
+
return JSON.stringify(value, (_k, v) => typeof v === "bigint" ? Number(v) : v);
|
|
1939
|
+
}
|
|
1940
|
+
}
|
|
1941
|
+
const FRAME_HEAD = `{"type":"${"invocationsobserved"}","items":[`;
|
|
1942
|
+
const FRAME_TAIL = "]}";
|
|
1943
|
+
const FRAME_OVERHEAD = byteLength(FRAME_HEAD) + byteLength(FRAME_TAIL);
|
|
1944
|
+
var Reporter = class {
|
|
1945
|
+
constructor(host, limits) {
|
|
1946
|
+
this.host = host;
|
|
1947
|
+
this.items = [];
|
|
1948
|
+
this.bytes = 0;
|
|
1949
|
+
this.perFunction = /* @__PURE__ */ new Map();
|
|
1950
|
+
this.openEmits = /* @__PURE__ */ new Map();
|
|
1951
|
+
this.stats = /* @__PURE__ */ new Map();
|
|
1952
|
+
this.drops = /* @__PURE__ */ new Map();
|
|
1953
|
+
this.windowStart = Date.now();
|
|
1954
|
+
this.unencodable = /* @__PURE__ */ new Set();
|
|
1955
|
+
this.limits = {
|
|
1956
|
+
...DEFAULT_REPORTER_LIMITS,
|
|
1957
|
+
...limits
|
|
1958
|
+
};
|
|
1959
|
+
}
|
|
1960
|
+
/** Starts the `localinvocationstats` timer. */
|
|
1961
|
+
start() {
|
|
1962
|
+
if (this.statsTimer) return;
|
|
1963
|
+
this.windowStart = Date.now();
|
|
1964
|
+
this.statsTimer = setInterval(() => this.sendStats(), this.limits.statsIntervalMs);
|
|
1965
|
+
require_utils.unrefTimer(this.statsTimer);
|
|
1966
|
+
}
|
|
1967
|
+
stop() {
|
|
1968
|
+
if (this.statsTimer) clearInterval(this.statsTimer);
|
|
1969
|
+
this.statsTimer = void 0;
|
|
1970
|
+
if (this.lingerTimer) clearTimeout(this.lingerTimer);
|
|
1971
|
+
this.lingerTimer = void 0;
|
|
1972
|
+
}
|
|
1973
|
+
/** Buffered items (for tests and diagnostics). */
|
|
1974
|
+
get size() {
|
|
1975
|
+
return this.items.length;
|
|
1976
|
+
}
|
|
1977
|
+
/** A matched local invocation of an auto function. */
|
|
1978
|
+
push(init) {
|
|
1979
|
+
const { captures, ...rest } = init;
|
|
1980
|
+
const item = new ReportItem(rest, false, void 0, void 0);
|
|
1981
|
+
if (!this.build(item, captures)) return false;
|
|
1982
|
+
return this.enqueue(item);
|
|
1983
|
+
}
|
|
1984
|
+
/**
|
|
1985
|
+
* An `obs.emit` event. The same event value emitted to several observers
|
|
1986
|
+
* from the same invocation context, before the buffer is flushed, becomes
|
|
1987
|
+
* one item whose `matched` lists them all.
|
|
1988
|
+
*/
|
|
1989
|
+
pushEmit(init) {
|
|
1990
|
+
const { observer_id, event, context, captures, ...rest } = init;
|
|
1991
|
+
const merge = this.openEmits.get(event)?.find((it) => it.init.function_id === rest.function_id && it.context === context && !it.init.matched.includes(observer_id));
|
|
1992
|
+
if (merge) return this.merge(merge, observer_id, captures);
|
|
1993
|
+
const item = new ReportItem({
|
|
1994
|
+
...rest,
|
|
1995
|
+
matched: [observer_id]
|
|
1996
|
+
}, true, event, context);
|
|
1997
|
+
if (!this.build(item, captures)) return false;
|
|
1998
|
+
return this.enqueue(item);
|
|
1999
|
+
}
|
|
2000
|
+
/** Makes a buffered emit item a merge target. Only items in the buffer are: a flush re-indexes. */
|
|
2001
|
+
index(item) {
|
|
2002
|
+
if (!item.emit) return;
|
|
2003
|
+
const list = this.openEmits.get(item.coalesceKey);
|
|
2004
|
+
if (list) list.push(item);
|
|
2005
|
+
else this.openEmits.set(item.coalesceKey, [item]);
|
|
2006
|
+
}
|
|
2007
|
+
/** Adds an observer (and its captures) to a buffered emit item, within the same bounds as a new item. */
|
|
2008
|
+
merge(item, observerId, captures) {
|
|
2009
|
+
const fn = item.init.function_id;
|
|
2010
|
+
const before = item.save();
|
|
2011
|
+
try {
|
|
2012
|
+
item.init.matched.push(observerId);
|
|
2013
|
+
item.capture(captures);
|
|
2014
|
+
item.render();
|
|
2015
|
+
} catch (error) {
|
|
2016
|
+
item.restore(before);
|
|
2017
|
+
this.logUnencodable(fn, error);
|
|
2018
|
+
return false;
|
|
2019
|
+
}
|
|
2020
|
+
const growth = item.bytes - before.bytes;
|
|
2021
|
+
const reason = this.tooLarge(item) ? "TOO_LARGE" : growth > 0 && this.bytes + this.host.pendingBytes() + growth > this.limits.maxBytes ? "BUFFER_FULL" : void 0;
|
|
2022
|
+
if (reason) {
|
|
2023
|
+
item.restore(before);
|
|
2024
|
+
this.drop(fn, reason);
|
|
2025
|
+
return false;
|
|
2026
|
+
}
|
|
2027
|
+
this.bytes += growth;
|
|
2028
|
+
return true;
|
|
2029
|
+
}
|
|
2030
|
+
build(item, captures) {
|
|
2031
|
+
try {
|
|
2032
|
+
item.capture(captures);
|
|
2033
|
+
item.render();
|
|
2034
|
+
return true;
|
|
2035
|
+
} catch (error) {
|
|
2036
|
+
this.logUnencodable(item.init.function_id, error);
|
|
2037
|
+
return false;
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
logUnencodable(functionId, error) {
|
|
2041
|
+
if (this.unencodable.has(functionId)) return;
|
|
2042
|
+
this.unencodable.add(functionId);
|
|
2043
|
+
this.host.logError(`Cannot encode an observed invocation of ${functionId} as JSON; it is not reported`, error);
|
|
2044
|
+
}
|
|
2045
|
+
/**
|
|
2046
|
+
* TOO_LARGE is measured against the buffer (8 MiB), the smaller of the two
|
|
2047
|
+
* limits: an item that can never be buffered. It also always fits a 16 MiB frame.
|
|
2048
|
+
*/
|
|
2049
|
+
tooLarge(item) {
|
|
2050
|
+
return item.bytes > this.limits.maxBytes || item.bytes + FRAME_OVERHEAD > this.limits.maxFrameBytes;
|
|
2051
|
+
}
|
|
2052
|
+
enqueue(item) {
|
|
2053
|
+
const fn = item.init.function_id;
|
|
2054
|
+
if (this.tooLarge(item)) {
|
|
2055
|
+
this.drop(fn, "TOO_LARGE");
|
|
2056
|
+
return false;
|
|
2057
|
+
}
|
|
2058
|
+
if (this.items.length >= this.limits.maxItems || this.bytes + this.host.pendingBytes() + item.bytes > this.limits.maxBytes) {
|
|
2059
|
+
this.drop(fn, "BUFFER_FULL");
|
|
2060
|
+
return false;
|
|
2061
|
+
}
|
|
2062
|
+
this.items.push(item);
|
|
2063
|
+
this.bytes += item.bytes;
|
|
2064
|
+
this.perFunction.set(fn, (this.perFunction.get(fn) ?? 0) + 1);
|
|
2065
|
+
this.index(item);
|
|
2066
|
+
if (this.items.length >= this.limits.batchItems) this.flush();
|
|
2067
|
+
else this.arm(this.limits.lingerMs);
|
|
2068
|
+
return true;
|
|
2069
|
+
}
|
|
2070
|
+
arm(ms) {
|
|
2071
|
+
if (this.lingerTimer) return;
|
|
2072
|
+
this.lingerTimer = setTimeout(() => {
|
|
2073
|
+
this.lingerTimer = void 0;
|
|
2074
|
+
this.flush();
|
|
2075
|
+
}, ms);
|
|
2076
|
+
require_utils.unrefTimer(this.lingerTimer);
|
|
2077
|
+
}
|
|
2078
|
+
/** Counts a report the SDK dropped (`BUFFER_FULL`, `TOO_LARGE`, `INACTIVE`). */
|
|
2079
|
+
drop(functionId, reason, count = 1) {
|
|
2080
|
+
let byReason = this.drops.get(functionId);
|
|
2081
|
+
if (!byReason) {
|
|
2082
|
+
byReason = /* @__PURE__ */ new Map();
|
|
2083
|
+
this.drops.set(functionId, byReason);
|
|
2084
|
+
}
|
|
2085
|
+
byReason.set(reason, (byReason.get(reason) ?? 0) + count);
|
|
2086
|
+
}
|
|
2087
|
+
/** Counts one local invocation (for `localinvocationstats`). */
|
|
2088
|
+
recordLocal(functionId, ok, durationMs) {
|
|
2089
|
+
let s = this.stats.get(functionId);
|
|
2090
|
+
if (!s) {
|
|
2091
|
+
s = {
|
|
2092
|
+
count: 0,
|
|
2093
|
+
errors: 0,
|
|
2094
|
+
duration_ms_sum: 0
|
|
2095
|
+
};
|
|
2096
|
+
this.stats.set(functionId, s);
|
|
2097
|
+
}
|
|
2098
|
+
s.count++;
|
|
2099
|
+
if (!ok) s.errors++;
|
|
2100
|
+
s.duration_ms_sum += durationMs;
|
|
2101
|
+
}
|
|
2102
|
+
/**
|
|
2103
|
+
* Discards a function's buffered items, counted as `INACTIVE`: the
|
|
2104
|
+
* function is unregistered, or the engine refused it
|
|
2105
|
+
* (`FUNCTION_NAMESPACE_CONFLICT`), so they could never be confirmed.
|
|
2106
|
+
*/
|
|
2107
|
+
discard(functionId) {
|
|
2108
|
+
const count = this.perFunction.get(functionId);
|
|
2109
|
+
if (!count) return;
|
|
2110
|
+
this.drop(functionId, "INACTIVE", count);
|
|
2111
|
+
this.setItems(this.items.filter((it) => it.init.function_id !== functionId));
|
|
2112
|
+
}
|
|
2113
|
+
/**
|
|
2114
|
+
* Sends what can be sent: items whose function the engine confirmed on the
|
|
2115
|
+
* current connection, in frames under the frame limit, while the socket's
|
|
2116
|
+
* unwritten bytes stay within the buffer bound. The rest stays.
|
|
2117
|
+
*/
|
|
2118
|
+
flush() {
|
|
2119
|
+
if (this.lingerTimer) {
|
|
2120
|
+
clearTimeout(this.lingerTimer);
|
|
2121
|
+
this.lingerTimer = void 0;
|
|
2122
|
+
}
|
|
2123
|
+
if (this.items.length === 0 || !this.host.online()) return;
|
|
2124
|
+
const status = /* @__PURE__ */ new Map();
|
|
2125
|
+
for (const fn of this.perFunction.keys()) status.set(fn, this.host.status(fn));
|
|
2126
|
+
if (![...status.values()].some((s) => s !== "wait")) return;
|
|
2127
|
+
const ready = [];
|
|
2128
|
+
const held = [];
|
|
2129
|
+
for (const item of this.items) {
|
|
2130
|
+
const st = status.get(item.init.function_id);
|
|
2131
|
+
if (st === "ready") ready.push(item);
|
|
2132
|
+
else if (st === "wait") held.push(item);
|
|
2133
|
+
else this.drop(item.init.function_id, "INACTIVE");
|
|
2134
|
+
}
|
|
2135
|
+
this.setItems(held);
|
|
2136
|
+
let frame = [];
|
|
2137
|
+
let frameBytes = FRAME_OVERHEAD;
|
|
2138
|
+
let blocked = false;
|
|
2139
|
+
const unsent = [];
|
|
2140
|
+
const send = () => {
|
|
2141
|
+
if (frame.length === 0) return;
|
|
2142
|
+
const data = `${FRAME_HEAD}${frame.map((it) => it.json).join(",")}${FRAME_TAIL}`;
|
|
2143
|
+
const pending = blocked ? 0 : this.host.pendingBytes();
|
|
2144
|
+
if (blocked || pending > 0 && pending + frameBytes > this.limits.maxBytes || !this.host.sendFrame(data)) {
|
|
2145
|
+
blocked = true;
|
|
2146
|
+
unsent.push(...frame);
|
|
2147
|
+
}
|
|
2148
|
+
frame = [];
|
|
2149
|
+
frameBytes = FRAME_OVERHEAD;
|
|
2150
|
+
};
|
|
2151
|
+
for (const item of ready) {
|
|
2152
|
+
if (item.bytes + FRAME_OVERHEAD > this.limits.maxFrameBytes) {
|
|
2153
|
+
this.drop(item.init.function_id, "TOO_LARGE");
|
|
2154
|
+
continue;
|
|
2155
|
+
}
|
|
2156
|
+
const separator = frame.length > 0 ? 1 : 0;
|
|
2157
|
+
if (frameBytes + separator + item.bytes > this.limits.maxFrameBytes) send();
|
|
2158
|
+
frameBytes += (frame.length > 0 ? 1 : 0) + item.bytes;
|
|
2159
|
+
frame.push(item);
|
|
2160
|
+
}
|
|
2161
|
+
send();
|
|
2162
|
+
if (unsent.length > 0) {
|
|
2163
|
+
this.requeue(unsent);
|
|
2164
|
+
if (this.host.online()) this.arm(this.limits.lingerMs * 20);
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
/** Replaces the buffer, keeping the per-function counts and the emit coalescing index in step. */
|
|
2168
|
+
setItems(items) {
|
|
2169
|
+
this.items = items;
|
|
2170
|
+
this.bytes = 0;
|
|
2171
|
+
this.perFunction.clear();
|
|
2172
|
+
this.openEmits.clear();
|
|
2173
|
+
for (const item of items) {
|
|
2174
|
+
this.bytes += item.bytes;
|
|
2175
|
+
const fn = item.init.function_id;
|
|
2176
|
+
this.perFunction.set(fn, (this.perFunction.get(fn) ?? 0) + 1);
|
|
2177
|
+
this.index(item);
|
|
2178
|
+
}
|
|
2179
|
+
}
|
|
2180
|
+
/** Puts items back at the front of the buffer, within its bounds. */
|
|
2181
|
+
requeue(items) {
|
|
2182
|
+
const kept = [];
|
|
2183
|
+
let bytes = this.bytes;
|
|
2184
|
+
let count = this.items.length;
|
|
2185
|
+
for (const item of items) {
|
|
2186
|
+
if (count >= this.limits.maxItems || bytes + item.bytes > this.limits.maxBytes) {
|
|
2187
|
+
this.drop(item.init.function_id, "BUFFER_FULL");
|
|
2188
|
+
continue;
|
|
2189
|
+
}
|
|
2190
|
+
kept.push(item);
|
|
2191
|
+
bytes += item.bytes;
|
|
2192
|
+
count++;
|
|
2193
|
+
}
|
|
2194
|
+
this.setItems([...kept, ...this.items]);
|
|
2195
|
+
}
|
|
2196
|
+
/** Sends `localinvocationstats` when there is anything to report; keeps counting while offline. */
|
|
2197
|
+
sendStats(now = Date.now()) {
|
|
2198
|
+
if (this.stats.size === 0 && this.drops.size === 0) {
|
|
2199
|
+
this.windowStart = now;
|
|
2200
|
+
return false;
|
|
2201
|
+
}
|
|
2202
|
+
if (!this.host.online()) return false;
|
|
2203
|
+
const message = buildLocalInvocationStats(now - this.windowStart, this.stats, this.drops);
|
|
2204
|
+
if (!this.host.sendFrame(JSON.stringify({
|
|
2205
|
+
type: "localinvocationstats",
|
|
2206
|
+
...message
|
|
2207
|
+
}))) return false;
|
|
2208
|
+
this.stats.clear();
|
|
2209
|
+
this.drops.clear();
|
|
2210
|
+
this.windowStart = now;
|
|
2211
|
+
return true;
|
|
2212
|
+
}
|
|
2213
|
+
/** Forgets everything buffered (the engine does not support observe). */
|
|
2214
|
+
clear() {
|
|
2215
|
+
this.setItems([]);
|
|
2216
|
+
}
|
|
56
2217
|
};
|
|
57
|
-
/**
|
|
58
|
-
|
|
2218
|
+
/** `localinvocationstats` from the counters, in insertion order. */
|
|
2219
|
+
function buildLocalInvocationStats(windowMs, stats, drops) {
|
|
2220
|
+
return {
|
|
2221
|
+
window_ms: Math.max(0, Math.round(windowMs)),
|
|
2222
|
+
functions: [...stats].map(([function_id, s]) => ({
|
|
2223
|
+
function_id,
|
|
2224
|
+
count: s.count,
|
|
2225
|
+
errors: s.errors,
|
|
2226
|
+
duration_ms_sum: s.duration_ms_sum
|
|
2227
|
+
})),
|
|
2228
|
+
dropped_reports: [...drops].flatMap(([function_id, byReason]) => [...byReason].map(([reason, count]) => ({
|
|
2229
|
+
function_id,
|
|
2230
|
+
reason,
|
|
2231
|
+
count
|
|
2232
|
+
})))
|
|
2233
|
+
};
|
|
2234
|
+
}
|
|
59
2235
|
|
|
60
2236
|
//#endregion
|
|
61
2237
|
//#region src/iii.ts
|
|
2238
|
+
const MAX_JSON_FRAME_BYTES = 16 * 1024 * 1024;
|
|
2239
|
+
const JSON_ENCODER = new TextEncoder();
|
|
2240
|
+
const PAYLOAD_SIZE_DOCS = "https://iii.dev/docs/creating-workers/channels#payload-size";
|
|
2241
|
+
function payloadTooLargeMessage(size) {
|
|
2242
|
+
return `Serialized JSON envelope is ${size} bytes; limit is ${MAX_JSON_FRAME_BYTES} bytes. Use channels for larger payloads: ${PAYLOAD_SIZE_DOCS}`;
|
|
2243
|
+
}
|
|
2244
|
+
function createPayloadTooLargeError(size, functionId) {
|
|
2245
|
+
return new InvocationError({
|
|
2246
|
+
code: "payload_too_large",
|
|
2247
|
+
message: payloadTooLargeMessage(size),
|
|
2248
|
+
function_id: functionId
|
|
2249
|
+
});
|
|
2250
|
+
}
|
|
2251
|
+
function isPayloadTooLargeError(error) {
|
|
2252
|
+
return error instanceof Error && "code" in error && error.code === "payload_too_large";
|
|
2253
|
+
}
|
|
62
2254
|
/** Short random suffix; `crypto.randomUUID` is unavailable on insecure origins. */
|
|
63
2255
|
function randomId() {
|
|
64
2256
|
const c = globalThis.crypto;
|
|
@@ -93,10 +2285,120 @@ function callNamespace(explicit, worker, source) {
|
|
|
93
2285
|
return explicit ?? worker;
|
|
94
2286
|
}
|
|
95
2287
|
/** Resolve one function invocation without leaking engine and configuration builtins into a worker namespace. */
|
|
96
|
-
function invocationNamespace(explicit, worker, functionId) {
|
|
97
|
-
const namespace = callNamespace(explicit, worker,
|
|
2288
|
+
function invocationNamespace(explicit, worker, functionId, source = "TriggerRequest.namespace") {
|
|
2289
|
+
const namespace = callNamespace(explicit, worker, source);
|
|
98
2290
|
return explicit === void 0 && (functionId.startsWith("engine::") || functionId.startsWith("configuration::")) ? "default" : namespace;
|
|
99
2291
|
}
|
|
2292
|
+
const MIGRATION_GUIDE = "https://iii.dev/docs/upgrading/from-0-24-x";
|
|
2293
|
+
/** CONTRACT §5: one warning per page per deprecated API. */
|
|
2294
|
+
const DEPRECATIONS = {
|
|
2295
|
+
registerTrigger: `registerTrigger is deprecated and will be removed in a future release. Use iii.observe(source, target) instead. Migration guide: ${MIGRATION_GUIDE}`,
|
|
2296
|
+
registerTriggerType: `registerTriggerType is deprecated and will be removed in a future release. Register a function with an observe descriptor (registerFunction(id, handler, { observe: { ... } })) instead. Migration guide: ${MIGRATION_GUIDE}`
|
|
2297
|
+
};
|
|
2298
|
+
const deprecationsWarned = /* @__PURE__ */ new Set();
|
|
2299
|
+
/**
|
|
2300
|
+
* Local dispatch hands the handler a copy of the caller's payload and the
|
|
2301
|
+
* caller a copy of the result (value semantics, as over the wire):
|
|
2302
|
+
* `structuredClone`, or JSON for what it cannot clone (functions, class
|
|
2303
|
+
* instances with methods the clone would drop).
|
|
2304
|
+
*/
|
|
2305
|
+
function cloneValue(value) {
|
|
2306
|
+
if (value === null || typeof value !== "object") return typeof value === "function" || typeof value === "symbol" ? void 0 : value;
|
|
2307
|
+
if (typeof structuredClone === "function") try {
|
|
2308
|
+
return structuredClone(value);
|
|
2309
|
+
} catch {}
|
|
2310
|
+
const text = JSON.stringify(value);
|
|
2311
|
+
return text === void 0 ? void 0 : JSON.parse(text);
|
|
2312
|
+
}
|
|
2313
|
+
const UNSUPPORTED_REASON = {
|
|
2314
|
+
code: "UNSUPPORTED",
|
|
2315
|
+
message: "the engine does not support observe (no observe.v1 in its features); upgrade it to 0.25 or later"
|
|
2316
|
+
};
|
|
2317
|
+
/** `args_format` needs `delivery: 'owner'`: an auto function's events are its invocations, offered to every observer. */
|
|
2318
|
+
function validateObserveHooks(functionId, hooks) {
|
|
2319
|
+
if (!hooks) return;
|
|
2320
|
+
const delivery = hooks.delivery;
|
|
2321
|
+
if (delivery !== void 0 && delivery !== "auto" && delivery !== "owner") throw new InvocationError({
|
|
2322
|
+
code: "INVALID_OBSERVE_DESCRIPTOR",
|
|
2323
|
+
message: `observe.delivery must be 'auto' or 'owner', got ${JSON.stringify(delivery)}`,
|
|
2324
|
+
function_id: functionId
|
|
2325
|
+
});
|
|
2326
|
+
if (hooks.args_format !== void 0 && delivery !== "owner") throw new InvocationError({
|
|
2327
|
+
code: "INVALID_OBSERVE_DESCRIPTOR",
|
|
2328
|
+
message: "observe.args_format requires delivery: 'owner' (an auto function takes no args)",
|
|
2329
|
+
function_id: functionId
|
|
2330
|
+
});
|
|
2331
|
+
}
|
|
2332
|
+
/**
|
|
2333
|
+
* The error a call that timed out rejects with, on the remote and the local
|
|
2334
|
+
* path: an `Error` (its message unchanged from earlier releases) that also
|
|
2335
|
+
* carries `code: 'TIMEOUT'` and the `function_id`, like the Node SDK's.
|
|
2336
|
+
*/
|
|
2337
|
+
function timeoutError(ms, functionId) {
|
|
2338
|
+
return Object.assign(/* @__PURE__ */ new Error(`Invocation timeout after ${ms}ms: ${functionId}`), {
|
|
2339
|
+
code: "TIMEOUT",
|
|
2340
|
+
function_id: functionId
|
|
2341
|
+
});
|
|
2342
|
+
}
|
|
2343
|
+
/** What a handler failure reports when the thrown value cannot even be read (a getter or `toString` that throws). */
|
|
2344
|
+
const UNREADABLE_FAILURE = "the handler failed with a value that cannot be read";
|
|
2345
|
+
function safeString(value) {
|
|
2346
|
+
try {
|
|
2347
|
+
return String(value);
|
|
2348
|
+
} catch {
|
|
2349
|
+
return UNREADABLE_FAILURE;
|
|
2350
|
+
}
|
|
2351
|
+
}
|
|
2352
|
+
/**
|
|
2353
|
+
* An error body as the engine sends it, and as this SDK's own calls reject
|
|
2354
|
+
* with: a plain (JSON-parsed) object with a string `code`, a string `message`
|
|
2355
|
+
* and, optionally, a string `stacktrace`. A class instance or anything else
|
|
2356
|
+
* with such fields is not one: it is reported through `String()`.
|
|
2357
|
+
*/
|
|
2358
|
+
function isEngineErrorBody(value) {
|
|
2359
|
+
if (value === null || typeof value !== "object") return false;
|
|
2360
|
+
const proto = Object.getPrototypeOf(value);
|
|
2361
|
+
if (proto !== Object.prototype && proto !== null) return false;
|
|
2362
|
+
const body = value;
|
|
2363
|
+
return typeof body.code === "string" && typeof body.message === "string" && (body.stacktrace === void 0 || typeof body.stacktrace === "string");
|
|
2364
|
+
}
|
|
2365
|
+
/**
|
|
2366
|
+
* The error a handler's failure becomes, the same on the local and the remote
|
|
2367
|
+
* path (code `invocation_failed`):
|
|
2368
|
+
* - an `Error`, from any realm (an iframe's too): its message and stack;
|
|
2369
|
+
* - an engine error body (a failed call's rejection, rethrown): its message and stacktrace;
|
|
2370
|
+
* - anything else: `String(value)`.
|
|
2371
|
+
* Never throws: when reading the value throws, a fixed message is reported, so
|
|
2372
|
+
* the caller always gets its answer.
|
|
2373
|
+
*/
|
|
2374
|
+
function handlerErrorBody(error) {
|
|
2375
|
+
try {
|
|
2376
|
+
if (error instanceof Error || Object.prototype.toString.call(error) === "[object Error]") {
|
|
2377
|
+
const { message, stack } = error;
|
|
2378
|
+
return {
|
|
2379
|
+
code: "invocation_failed",
|
|
2380
|
+
message: typeof message === "string" ? message : safeString(message),
|
|
2381
|
+
stacktrace: typeof stack === "string" ? stack : void 0
|
|
2382
|
+
};
|
|
2383
|
+
}
|
|
2384
|
+
if (isEngineErrorBody(error)) return {
|
|
2385
|
+
code: "invocation_failed",
|
|
2386
|
+
message: error.message,
|
|
2387
|
+
stacktrace: error.stacktrace
|
|
2388
|
+
};
|
|
2389
|
+
return {
|
|
2390
|
+
code: "invocation_failed",
|
|
2391
|
+
message: String(error),
|
|
2392
|
+
stacktrace: void 0
|
|
2393
|
+
};
|
|
2394
|
+
} catch {
|
|
2395
|
+
return {
|
|
2396
|
+
code: "invocation_failed",
|
|
2397
|
+
message: safeString(error),
|
|
2398
|
+
stacktrace: void 0
|
|
2399
|
+
};
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
100
2402
|
function resolveNamespace(optionNamespace) {
|
|
101
2403
|
if (optionNamespace !== void 0 && optionNamespace.trim() === "") throw new Error(`namespace is empty: options.namespace was set to ${JSON.stringify(optionNamespace)}. Give it a name, or leave it unset to register in \`default\`.`);
|
|
102
2404
|
return optionNamespace;
|
|
@@ -114,20 +2416,28 @@ var Sdk = class {
|
|
|
114
2416
|
this.connectionState = "disconnected";
|
|
115
2417
|
this.connectionListeners = /* @__PURE__ */ new Set();
|
|
116
2418
|
this.isShuttingDown = false;
|
|
2419
|
+
this.observers = /* @__PURE__ */ new Map();
|
|
2420
|
+
this.engineFeatures = /* @__PURE__ */ new Set();
|
|
2421
|
+
this.registeredOnConnection = false;
|
|
2422
|
+
this.connectionEpoch = 0;
|
|
2423
|
+
this.hooksInactiveWarned = /* @__PURE__ */ new Set();
|
|
2424
|
+
this.observeQueue = [];
|
|
117
2425
|
this.registerTriggerType = (triggerType, handler) => {
|
|
118
|
-
this.
|
|
119
|
-
this.
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
2426
|
+
this.warnDeprecated("registerTriggerType");
|
|
2427
|
+
const message = this.snapshotRegistration({
|
|
2428
|
+
...triggerType,
|
|
2429
|
+
message_type: "registertriggertype"
|
|
2430
|
+
});
|
|
2431
|
+
this.sendMessage("registertriggertype", message, true);
|
|
2432
|
+
this.triggerTypes.set(message.id, {
|
|
2433
|
+
message,
|
|
124
2434
|
handler
|
|
125
2435
|
});
|
|
126
2436
|
return {
|
|
127
|
-
id:
|
|
2437
|
+
id: message.id,
|
|
128
2438
|
registerTrigger: (functionId, config) => {
|
|
129
2439
|
return this.registerTrigger({
|
|
130
|
-
type:
|
|
2440
|
+
type: message.id,
|
|
131
2441
|
function_id: functionId,
|
|
132
2442
|
config,
|
|
133
2443
|
namespace: this.namespace
|
|
@@ -136,7 +2446,7 @@ var Sdk = class {
|
|
|
136
2446
|
registerFunction: (functionId, handler, config) => {
|
|
137
2447
|
const ref = this.registerFunction(functionId, handler);
|
|
138
2448
|
this.registerTrigger({
|
|
139
|
-
type:
|
|
2449
|
+
type: message.id,
|
|
140
2450
|
function_id: functionId,
|
|
141
2451
|
config,
|
|
142
2452
|
namespace: this.namespace
|
|
@@ -144,17 +2454,22 @@ var Sdk = class {
|
|
|
144
2454
|
return ref;
|
|
145
2455
|
},
|
|
146
2456
|
unregister: () => {
|
|
147
|
-
this.unregisterTriggerType(
|
|
2457
|
+
this.unregisterTriggerType(message);
|
|
148
2458
|
}
|
|
149
2459
|
};
|
|
150
2460
|
};
|
|
151
2461
|
this.unregisterTriggerType = (triggerType) => {
|
|
152
|
-
|
|
153
|
-
this.
|
|
2462
|
+
const { id, namespace } = triggerType;
|
|
2463
|
+
this.sendMessage("unregistertriggertype", namespace !== void 0 ? {
|
|
2464
|
+
id,
|
|
2465
|
+
namespace
|
|
2466
|
+
} : { id }, true);
|
|
2467
|
+
this.triggerTypes.delete(id);
|
|
154
2468
|
};
|
|
155
2469
|
this.registerTrigger = (trigger) => {
|
|
2470
|
+
this.warnDeprecated("registerTrigger");
|
|
156
2471
|
const id = require_utils.randomUUID();
|
|
157
|
-
const fullTrigger = {
|
|
2472
|
+
const fullTrigger = this.snapshotRegistration({
|
|
158
2473
|
...trigger,
|
|
159
2474
|
id,
|
|
160
2475
|
message_type: "registertrigger",
|
|
@@ -162,7 +2477,7 @@ var Sdk = class {
|
|
|
162
2477
|
const namespace = callNamespace(trigger.namespace, this.namespace, "RegisterTriggerInput.namespace");
|
|
163
2478
|
return namespace !== void 0 ? { namespace } : {};
|
|
164
2479
|
})()
|
|
165
|
-
};
|
|
2480
|
+
});
|
|
166
2481
|
this.sendMessage("registertrigger", fullTrigger, true);
|
|
167
2482
|
this.triggers.set(id, fullTrigger);
|
|
168
2483
|
return { unregister: () => {
|
|
@@ -177,27 +2492,82 @@ var Sdk = class {
|
|
|
177
2492
|
this.registerFunction = (functionId, handlerOrInvocation, options) => {
|
|
178
2493
|
if (!functionId || functionId.trim() === "") throw new Error("id is required");
|
|
179
2494
|
if (this.functions.has(functionId)) throw new Error(`function id already registered: ${functionId}`);
|
|
180
|
-
const
|
|
181
|
-
|
|
2495
|
+
const { observe: hooks, localDispatch, ...wireOptions } = options ?? {};
|
|
2496
|
+
validateObserveHooks(functionId, hooks);
|
|
2497
|
+
const descriptor = observeDescriptor(hooks);
|
|
2498
|
+
const fullMessage = this.snapshotRegistration({
|
|
2499
|
+
...wireOptions,
|
|
2500
|
+
...descriptor ? { observe: descriptor } : {},
|
|
182
2501
|
id: functionId,
|
|
183
2502
|
message_type: "registerfunction"
|
|
184
|
-
};
|
|
2503
|
+
});
|
|
185
2504
|
this.sendMessage("registerfunction", fullMessage, true);
|
|
2505
|
+
const observe = new FunctionObservers(functionId, hooks, localDispatch !== false, true, this.observeHost);
|
|
2506
|
+
if (observe.needsObserve && this.registeredOnConnection && !this.engineFeatures.has("observe.v1")) this.warnHooksInactive(functionId);
|
|
186
2507
|
const handler = handlerOrInvocation;
|
|
187
2508
|
this.functions.set(functionId, {
|
|
188
2509
|
message: fullMessage,
|
|
189
|
-
|
|
190
|
-
|
|
2510
|
+
observe,
|
|
2511
|
+
handler: async (input, metadata) => {
|
|
2512
|
+
return await handler(input, metadata);
|
|
191
2513
|
}
|
|
192
2514
|
});
|
|
193
2515
|
return {
|
|
194
2516
|
id: functionId,
|
|
195
2517
|
unregister: () => {
|
|
2518
|
+
if (this.functions.get(functionId)?.observe !== observe) return;
|
|
196
2519
|
this.sendMessage("unregisterfunction", { id: functionId }, true);
|
|
197
2520
|
this.functions.delete(functionId);
|
|
198
|
-
|
|
2521
|
+
observe.dispose();
|
|
2522
|
+
},
|
|
2523
|
+
isObserved: () => observe.isObserved(),
|
|
2524
|
+
observers: () => observe.observers()
|
|
199
2525
|
};
|
|
200
2526
|
};
|
|
2527
|
+
this.observe = (source, target, options) => {
|
|
2528
|
+
if (!source || typeof source.function_id !== "string" || source.function_id.trim() === "") throw new Error("observe: source.function_id is required");
|
|
2529
|
+
const targetId = typeof target === "string" ? target : target?.function_id;
|
|
2530
|
+
if (typeof targetId !== "string" || targetId.trim() === "") throw new Error("observe: target is required (the id of a registered function)");
|
|
2531
|
+
const id = options?.id ?? require_utils.randomUUID();
|
|
2532
|
+
if (this.observers.has(id)) throw new Error(`observe: observer id already in use: ${id}`);
|
|
2533
|
+
const onDispose = (h) => this.disposeObserver(h);
|
|
2534
|
+
const logError = (msg, error) => this.logError(msg, error);
|
|
2535
|
+
const refused = (reason) => {
|
|
2536
|
+
const handle = new ObserverHandleImpl(id, {
|
|
2537
|
+
id,
|
|
2538
|
+
source: { function_id: source.function_id },
|
|
2539
|
+
target: { function_id: targetId }
|
|
2540
|
+
}, onDispose, logError);
|
|
2541
|
+
handle.setState("error", reason);
|
|
2542
|
+
return handle;
|
|
2543
|
+
};
|
|
2544
|
+
if (source.filters !== void 0) try {
|
|
2545
|
+
compileFilter(source.filters);
|
|
2546
|
+
} catch (error) {
|
|
2547
|
+
if (!(error instanceof FilterError)) throw error;
|
|
2548
|
+
return refused({
|
|
2549
|
+
code: error.code,
|
|
2550
|
+
message: error.message
|
|
2551
|
+
});
|
|
2552
|
+
}
|
|
2553
|
+
let message;
|
|
2554
|
+
try {
|
|
2555
|
+
message = buildObserveMessage(id, source, target, options, (explicit, functionId, field) => invocationNamespace(explicit, this.namespace, functionId, field));
|
|
2556
|
+
} catch (error) {
|
|
2557
|
+
if (!(error instanceof TypeError)) throw error;
|
|
2558
|
+
return refused({
|
|
2559
|
+
code: "INVALID_ARGS",
|
|
2560
|
+
message: `observe: the source or options are not JSON: ${error.message}`
|
|
2561
|
+
});
|
|
2562
|
+
}
|
|
2563
|
+
const handle = new ObserverHandleImpl(id, message, onDispose, logError);
|
|
2564
|
+
this.observers.set(id, handle);
|
|
2565
|
+
if (this.registeredOnConnection && this.isOpen()) if (this.engineFeatures.has("observe.v1")) this.sendObserve(handle);
|
|
2566
|
+
else handle.setState("error", UNSUPPORTED_REASON);
|
|
2567
|
+
return handle;
|
|
2568
|
+
};
|
|
2569
|
+
this.currentInvocation = () => publicContext(currentContext());
|
|
2570
|
+
this.withInvocation = (invocation, fn) => enterInvocation(contextFromView(invocation), fn, MAX_RUNNING_INVOCATION_MS);
|
|
201
2571
|
this.__helpers_create_channel = async (bufferSize) => {
|
|
202
2572
|
const result = await this.trigger({
|
|
203
2573
|
function_id: "engine::channels::create",
|
|
@@ -211,45 +2581,25 @@ var Sdk = class {
|
|
|
211
2581
|
};
|
|
212
2582
|
};
|
|
213
2583
|
this.trigger = async (request) => {
|
|
214
|
-
const { function_id,
|
|
2584
|
+
const { function_id, action } = request;
|
|
215
2585
|
const namespace = invocationNamespace(request.namespace, this.namespace, function_id);
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
if (this.invocations.get(invocation_id)) {
|
|
230
|
-
this.invocations.delete(invocation_id);
|
|
231
|
-
reject(/* @__PURE__ */ new Error(`Invocation timeout after ${effectiveTimeout}ms: ${function_id}`));
|
|
2586
|
+
if (request.dispatch !== "remote" && action?.type !== "enqueue") {
|
|
2587
|
+
const fn = this.functions.get(function_id);
|
|
2588
|
+
const observe = fn?.observe;
|
|
2589
|
+
if (fn?.handler && observe?.localDispatch && (namespace === void 0 || namespace === observe.namespace)) {
|
|
2590
|
+
const depth = callLocalDepth();
|
|
2591
|
+
if (depth < 64) return this.invokeLocal(function_id, fn.handler, observe, request);
|
|
2592
|
+
if (!this.isOpen()) {
|
|
2593
|
+
if (depth < 256) return this.invokeLocal(function_id, fn.handler, observe, request);
|
|
2594
|
+
throw new InvocationError({
|
|
2595
|
+
code: "LOCAL_DEPTH_EXCEEDED",
|
|
2596
|
+
message: `${function_id} is called ${depth} local calls deep: past ${64} the call needs the engine, and the socket is closed`,
|
|
2597
|
+
function_id
|
|
2598
|
+
});
|
|
232
2599
|
}
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
clearTimeout(timeout);
|
|
237
|
-
resolve(result);
|
|
238
|
-
},
|
|
239
|
-
reject: (error) => {
|
|
240
|
-
clearTimeout(timeout);
|
|
241
|
-
reject(error);
|
|
242
|
-
},
|
|
243
|
-
timeout
|
|
244
|
-
});
|
|
245
|
-
this.sendMessage("invokefunction", {
|
|
246
|
-
invocation_id,
|
|
247
|
-
function_id,
|
|
248
|
-
data: payload,
|
|
249
|
-
action,
|
|
250
|
-
...namespace !== void 0 ? { namespace } : {}
|
|
251
|
-
});
|
|
252
|
-
});
|
|
2600
|
+
}
|
|
2601
|
+
}
|
|
2602
|
+
return this.invokeRemote(request, namespace);
|
|
253
2603
|
};
|
|
254
2604
|
this.__helpers_create_stream = (streamName, stream) => {
|
|
255
2605
|
this.registerFunction(`stream::get(${streamName})`, stream.get.bind(stream));
|
|
@@ -261,6 +2611,13 @@ var Sdk = class {
|
|
|
261
2611
|
this.getFatalError = () => this.fatalError;
|
|
262
2612
|
this.shutdown = async () => {
|
|
263
2613
|
this.isShuttingDown = true;
|
|
2614
|
+
try {
|
|
2615
|
+
this.reporter.flush();
|
|
2616
|
+
this.reporter.sendStats();
|
|
2617
|
+
} catch (error) {
|
|
2618
|
+
this.logError("Failed to flush observed invocations on shutdown", error);
|
|
2619
|
+
}
|
|
2620
|
+
this.reporter.stop();
|
|
264
2621
|
this.clearReconnectTimeout();
|
|
265
2622
|
for (const [_id, invocation] of this.invocations) {
|
|
266
2623
|
if (invocation.timeout) clearTimeout(invocation.timeout);
|
|
@@ -270,9 +2627,11 @@ var Sdk = class {
|
|
|
270
2627
|
if (this.ws) {
|
|
271
2628
|
this.ws.onopen = null;
|
|
272
2629
|
this.ws.onclose = null;
|
|
273
|
-
this.ws.onerror =
|
|
2630
|
+
this.ws.onerror = () => void 0;
|
|
274
2631
|
this.ws.onmessage = null;
|
|
275
|
-
|
|
2632
|
+
try {
|
|
2633
|
+
this.ws.close();
|
|
2634
|
+
} catch {}
|
|
276
2635
|
this.ws = void 0;
|
|
277
2636
|
}
|
|
278
2637
|
this.setConnectionState("disconnected");
|
|
@@ -295,8 +2654,258 @@ var Sdk = class {
|
|
|
295
2654
|
...DEFAULT_BRIDGE_RECONNECTION_CONFIG,
|
|
296
2655
|
...options?.reconnectionConfig
|
|
297
2656
|
};
|
|
2657
|
+
this.reporter = new Reporter({
|
|
2658
|
+
online: () => this.observeOnline(),
|
|
2659
|
+
status: (functionId) => {
|
|
2660
|
+
const state = this.functions.get(functionId)?.observe;
|
|
2661
|
+
if (!state || state.releasedEpoch === this.connectionEpoch) return "gone";
|
|
2662
|
+
return state.confirmedEpoch === this.connectionEpoch ? "ready" : "wait";
|
|
2663
|
+
},
|
|
2664
|
+
sendFrame: (data) => {
|
|
2665
|
+
if (!this.isOpen()) return false;
|
|
2666
|
+
this.sendMessageRaw(data);
|
|
2667
|
+
return true;
|
|
2668
|
+
},
|
|
2669
|
+
pendingBytes: () => this.ws?.bufferedAmount ?? 0,
|
|
2670
|
+
logError: (message, error) => this.logError(message, error)
|
|
2671
|
+
}, options?.observe?.reporter);
|
|
2672
|
+
this.observeHost = {
|
|
2673
|
+
identity: () => this.workerId !== void 0 ? {
|
|
2674
|
+
worker_id: this.workerId,
|
|
2675
|
+
worker_name: this.workerName
|
|
2676
|
+
} : { worker_name: this.workerName },
|
|
2677
|
+
sendAck: (ack) => this.sendMessage("observerack", buildObserverAck(ack), true),
|
|
2678
|
+
reporter: this.reporter,
|
|
2679
|
+
callTarget: (target, observerId, payload, timeoutMs) => this.invokeRemote({
|
|
2680
|
+
function_id: target,
|
|
2681
|
+
payload,
|
|
2682
|
+
timeoutMs
|
|
2683
|
+
}, void 0, { observer_id: observerId }),
|
|
2684
|
+
logError: (message, error) => this.logError(message, error),
|
|
2685
|
+
hookTimeoutMs: () => options?.observe?.hookTimeoutMs ?? 3e4,
|
|
2686
|
+
traceContext: () => ({})
|
|
2687
|
+
};
|
|
2688
|
+
this.reporter.start();
|
|
298
2689
|
this.connect();
|
|
299
2690
|
}
|
|
2691
|
+
warnDeprecated(api) {
|
|
2692
|
+
if (deprecationsWarned.has(api)) return;
|
|
2693
|
+
deprecationsWarned.add(api);
|
|
2694
|
+
console.warn(`[iii] ${DEPRECATIONS[api]}`);
|
|
2695
|
+
}
|
|
2696
|
+
logError(message, error) {
|
|
2697
|
+
if (error === void 0) console.error(`[iii] ${message}`);
|
|
2698
|
+
else console.error(`[iii] ${message}`, error);
|
|
2699
|
+
}
|
|
2700
|
+
sendObserve(handle) {
|
|
2701
|
+
this.sendMessage("observe", handle.message, true);
|
|
2702
|
+
handle.sent = true;
|
|
2703
|
+
}
|
|
2704
|
+
disposeObserver(handle) {
|
|
2705
|
+
if (this.observers.get(handle.id) === handle) this.observers.delete(handle.id);
|
|
2706
|
+
if (!handle.sent) return;
|
|
2707
|
+
this.sendObserveFamily("unobserve", { id: handle.id });
|
|
2708
|
+
}
|
|
2709
|
+
/**
|
|
2710
|
+
* An observe-family frame that must not be lost to a disconnect (`unobserve`:
|
|
2711
|
+
* a reattach would otherwise keep the observer alive). Without a registered
|
|
2712
|
+
* connection it waits for the next `WorkerRegistered`, and goes out only if
|
|
2713
|
+
* that engine advertises `observe.v1`.
|
|
2714
|
+
*/
|
|
2715
|
+
sendObserveFamily(type, message) {
|
|
2716
|
+
if (!this.isOpen() || !this.registeredOnConnection) this.observeQueue.push({
|
|
2717
|
+
type,
|
|
2718
|
+
...message
|
|
2719
|
+
});
|
|
2720
|
+
else if (this.engineFeatures.has("observe.v1")) this.sendMessage(type, message, true);
|
|
2721
|
+
}
|
|
2722
|
+
warnHooksInactive(functionId) {
|
|
2723
|
+
if (this.hooksInactiveWarned.has(functionId)) return;
|
|
2724
|
+
this.hooksInactiveWarned.add(functionId);
|
|
2725
|
+
console.warn(`[iii] Function "${functionId}" declares observe hooks or owner delivery, but the engine does not support observe (observe.v1): it is registered as a plain function and its observe hooks are inactive.`);
|
|
2726
|
+
}
|
|
2727
|
+
/** Connected to an engine that advertised `observe.v1`. */
|
|
2728
|
+
observeOnline() {
|
|
2729
|
+
return this.isOpen() && this.registeredOnConnection && this.engineFeatures.has("observe.v1");
|
|
2730
|
+
}
|
|
2731
|
+
/**
|
|
2732
|
+
* What an outgoing call carries from the invocation it is made in: `caller`
|
|
2733
|
+
* and `observe_depth` (engines with `observe.v1` only), and the trace
|
|
2734
|
+
* context. The browser has no OpenTelemetry, so `traceparent` / `baggage`
|
|
2735
|
+
* are the request's own, else the invocation's (see `callContext`), else
|
|
2736
|
+
* none. Outside any scope `observe_depth` is the deepest running
|
|
2737
|
+
* invocation's (`callDepth`), so the loop guard holds after an `await`.
|
|
2738
|
+
*/
|
|
2739
|
+
outgoingFields(request) {
|
|
2740
|
+
const cur = callContext();
|
|
2741
|
+
const fields = {
|
|
2742
|
+
traceparent: request.traceparent ?? cur?.traceparent,
|
|
2743
|
+
baggage: request.baggage ?? cur?.baggage
|
|
2744
|
+
};
|
|
2745
|
+
if (this.engineFeatures.has("observe.v1")) {
|
|
2746
|
+
if (cur) fields.caller = callerFor(cur);
|
|
2747
|
+
fields.observe_depth = cur ? cur.observe_depth : callDepth();
|
|
2748
|
+
}
|
|
2749
|
+
return fields;
|
|
2750
|
+
}
|
|
2751
|
+
/** The routed path: an `InvokeFunction` through the engine. */
|
|
2752
|
+
invokeRemote(request, namespace, activation) {
|
|
2753
|
+
const { function_id, payload, action, timeoutMs, metadata } = request;
|
|
2754
|
+
const effectiveTimeout = timeoutMs ?? this.invocationTimeoutMs;
|
|
2755
|
+
const outgoing = this.outgoingFields(request);
|
|
2756
|
+
if (action?.type === "void") {
|
|
2757
|
+
this.sendMessage("invokefunction", buildInvokeFunction({
|
|
2758
|
+
function_id,
|
|
2759
|
+
data: payload,
|
|
2760
|
+
action,
|
|
2761
|
+
metadata,
|
|
2762
|
+
namespace,
|
|
2763
|
+
...outgoing,
|
|
2764
|
+
activation
|
|
2765
|
+
}));
|
|
2766
|
+
return Promise.resolve(void 0);
|
|
2767
|
+
}
|
|
2768
|
+
const invocation_id = require_utils.randomUUID();
|
|
2769
|
+
return new Promise((resolve, reject) => {
|
|
2770
|
+
const timeout = setTimeout(() => {
|
|
2771
|
+
if (this.invocations.get(invocation_id)) {
|
|
2772
|
+
this.invocations.delete(invocation_id);
|
|
2773
|
+
reject(timeoutError(effectiveTimeout, function_id));
|
|
2774
|
+
}
|
|
2775
|
+
}, effectiveTimeout);
|
|
2776
|
+
this.invocations.set(invocation_id, {
|
|
2777
|
+
resolve: (result) => {
|
|
2778
|
+
clearTimeout(timeout);
|
|
2779
|
+
resolve(result);
|
|
2780
|
+
},
|
|
2781
|
+
reject: (error) => {
|
|
2782
|
+
clearTimeout(timeout);
|
|
2783
|
+
reject(error);
|
|
2784
|
+
},
|
|
2785
|
+
timeout
|
|
2786
|
+
});
|
|
2787
|
+
this.sendMessage("invokefunction", buildInvokeFunction({
|
|
2788
|
+
invocation_id,
|
|
2789
|
+
function_id,
|
|
2790
|
+
data: payload,
|
|
2791
|
+
action,
|
|
2792
|
+
metadata,
|
|
2793
|
+
namespace,
|
|
2794
|
+
...outgoing,
|
|
2795
|
+
activation
|
|
2796
|
+
}));
|
|
2797
|
+
});
|
|
2798
|
+
}
|
|
2799
|
+
/**
|
|
2800
|
+
* The local path (sdk.md §4.3): runs the handler in-process, with a copy of
|
|
2801
|
+
* the payload, inside a new invocation context; the same timeout and the
|
|
2802
|
+
* same rejection value as the remote path; reports the call when an
|
|
2803
|
+
* observer matches. Puts nothing on the wire when nobody observes the
|
|
2804
|
+
* function.
|
|
2805
|
+
*/
|
|
2806
|
+
invokeLocal(function_id, handler, observe, request) {
|
|
2807
|
+
const parent = callContext();
|
|
2808
|
+
const caller = this.workerId !== void 0 ? {
|
|
2809
|
+
worker_id: this.workerId,
|
|
2810
|
+
worker_name: this.workerName
|
|
2811
|
+
} : { worker_name: this.workerName };
|
|
2812
|
+
if (parent) {
|
|
2813
|
+
caller.function_id = parent.function_id;
|
|
2814
|
+
caller.invocation_id = parent.invocation_id;
|
|
2815
|
+
const grandparent = stripCaller(parent.caller);
|
|
2816
|
+
if (grandparent && Object.keys(grandparent).length > 0) caller.parent = grandparent;
|
|
2817
|
+
}
|
|
2818
|
+
const ctx = {
|
|
2819
|
+
function_id,
|
|
2820
|
+
invocation_id: require_utils.randomUUID(),
|
|
2821
|
+
caller,
|
|
2822
|
+
observe_depth: parent ? parent.observe_depth : callDepth(),
|
|
2823
|
+
metadata: request.metadata,
|
|
2824
|
+
localDepth: callLocalDepth() + 1
|
|
2825
|
+
};
|
|
2826
|
+
const traceparent = request.traceparent ?? parent?.traceparent;
|
|
2827
|
+
const baggage = request.baggage ?? parent?.baggage;
|
|
2828
|
+
if (traceparent !== void 0) ctx.traceparent = traceparent;
|
|
2829
|
+
if (baggage !== void 0) ctx.baggage = baggage;
|
|
2830
|
+
const set = observe.delivery === "auto" ? observe.compiled : [];
|
|
2831
|
+
let input;
|
|
2832
|
+
let observedInput;
|
|
2833
|
+
let observedMetadata;
|
|
2834
|
+
let metadata;
|
|
2835
|
+
try {
|
|
2836
|
+
if (set.length > 0) {
|
|
2837
|
+
observedInput = cloneValue(request.payload);
|
|
2838
|
+
observedMetadata = request.metadata === void 0 ? void 0 : cloneValue(request.metadata);
|
|
2839
|
+
}
|
|
2840
|
+
input = this.resolveChannelValue(cloneValue(request.payload));
|
|
2841
|
+
metadata = request.metadata === void 0 ? void 0 : cloneValue(request.metadata);
|
|
2842
|
+
} catch (error) {
|
|
2843
|
+
return Promise.reject(error);
|
|
2844
|
+
}
|
|
2845
|
+
const startedAt = Date.now();
|
|
2846
|
+
const t0 = performance.now();
|
|
2847
|
+
const finish = (ok, output, error) => {
|
|
2848
|
+
try {
|
|
2849
|
+
const duration = performance.now() - t0;
|
|
2850
|
+
this.reporter.recordLocal(function_id, ok, duration);
|
|
2851
|
+
observe.reportLocal(set, {
|
|
2852
|
+
invocation_id: ctx.invocation_id,
|
|
2853
|
+
ok,
|
|
2854
|
+
input: observedInput,
|
|
2855
|
+
output,
|
|
2856
|
+
error,
|
|
2857
|
+
caller: ctx.caller,
|
|
2858
|
+
metadata: observedMetadata,
|
|
2859
|
+
started_at_ms: startedAt,
|
|
2860
|
+
duration_ms: duration,
|
|
2861
|
+
observe_depth: ctx.observe_depth,
|
|
2862
|
+
traceparent,
|
|
2863
|
+
baggage
|
|
2864
|
+
});
|
|
2865
|
+
} catch (reportError) {
|
|
2866
|
+
this.logError(`Failed to report a local invocation of ${function_id}`, reportError);
|
|
2867
|
+
}
|
|
2868
|
+
};
|
|
2869
|
+
const effectiveTimeout = request.timeoutMs ?? this.invocationTimeoutMs;
|
|
2870
|
+
const untrack = trackRunning(ctx, effectiveTimeout);
|
|
2871
|
+
let started;
|
|
2872
|
+
try {
|
|
2873
|
+
started = runInContext(ctx, () => handler(input, metadata));
|
|
2874
|
+
} catch (error) {
|
|
2875
|
+
started = Promise.reject(error);
|
|
2876
|
+
}
|
|
2877
|
+
const done = started.then((output) => {
|
|
2878
|
+
untrack();
|
|
2879
|
+
finish(true, output, void 0);
|
|
2880
|
+
return output;
|
|
2881
|
+
}, (error) => {
|
|
2882
|
+
untrack();
|
|
2883
|
+
const body = handlerErrorBody(error);
|
|
2884
|
+
finish(false, void 0, body);
|
|
2885
|
+
throw body;
|
|
2886
|
+
});
|
|
2887
|
+
if (request.action?.type === "void") {
|
|
2888
|
+
done.catch((error) => this.logError(`Error invoking function ${function_id}`, error));
|
|
2889
|
+
return Promise.resolve(void 0);
|
|
2890
|
+
}
|
|
2891
|
+
return new Promise((resolve, reject) => {
|
|
2892
|
+
let timeout;
|
|
2893
|
+
done.then((output) => {
|
|
2894
|
+
if (timeout !== void 0) clearTimeout(timeout);
|
|
2895
|
+
try {
|
|
2896
|
+
resolve(cloneValue(output));
|
|
2897
|
+
} catch (error) {
|
|
2898
|
+
reject(error);
|
|
2899
|
+
}
|
|
2900
|
+
}, (error) => {
|
|
2901
|
+
if (timeout !== void 0) clearTimeout(timeout);
|
|
2902
|
+
reject(error);
|
|
2903
|
+
});
|
|
2904
|
+
timeout = setTimeout(() => {
|
|
2905
|
+
reject(timeoutError(effectiveTimeout, function_id));
|
|
2906
|
+
}, effectiveTimeout);
|
|
2907
|
+
});
|
|
2908
|
+
}
|
|
300
2909
|
setConnectionState(state) {
|
|
301
2910
|
if (this.connectionState !== state) {
|
|
302
2911
|
this.connectionState = state;
|
|
@@ -353,6 +2962,7 @@ var Sdk = class {
|
|
|
353
2962
|
this.ws.onmessage = null;
|
|
354
2963
|
}
|
|
355
2964
|
this.ws = void 0;
|
|
2965
|
+
this.registeredOnConnection = false;
|
|
356
2966
|
if (this.isShuttingDown) return;
|
|
357
2967
|
this.setConnectionState("disconnected");
|
|
358
2968
|
this.scheduleReconnect();
|
|
@@ -361,33 +2971,81 @@ var Sdk = class {
|
|
|
361
2971
|
this.clearReconnectTimeout();
|
|
362
2972
|
this.reconnectAttempt = 0;
|
|
363
2973
|
this.setConnectionState("connected");
|
|
2974
|
+
this.connectionEpoch++;
|
|
2975
|
+
this.registeredOnConnection = false;
|
|
364
2976
|
if (this.ws) this.ws.onmessage = this.onMessage.bind(this);
|
|
365
|
-
if (this.workerId)
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
2977
|
+
if (this.workerId) try {
|
|
2978
|
+
this.sendMessageRaw(JSON.stringify({
|
|
2979
|
+
type: "reattach",
|
|
2980
|
+
previous_worker_id: this.workerId,
|
|
2981
|
+
reattach_token: this.reattachToken
|
|
2982
|
+
}));
|
|
2983
|
+
} catch (error) {
|
|
2984
|
+
if (!isPayloadTooLargeError(error)) throw error;
|
|
2985
|
+
console.error("[iii] Reattach JSON envelope rejected", error);
|
|
2986
|
+
}
|
|
370
2987
|
this.registerWorkerMetadata();
|
|
371
2988
|
this.triggerTypes.forEach(({ message }) => {
|
|
372
|
-
this.
|
|
2989
|
+
this.replayRegistration("registertriggertype", message);
|
|
373
2990
|
});
|
|
374
2991
|
this.functions.forEach(({ message }) => {
|
|
375
|
-
this.
|
|
2992
|
+
this.replayRegistration("registerfunction", message);
|
|
376
2993
|
});
|
|
377
2994
|
this.triggers.forEach((trigger) => {
|
|
378
|
-
this.
|
|
2995
|
+
this.replayRegistration("registertrigger", trigger);
|
|
379
2996
|
});
|
|
380
2997
|
const pending = this.messagesToSend;
|
|
381
2998
|
this.messagesToSend = [];
|
|
382
2999
|
for (const message of pending) {
|
|
383
3000
|
if (message.type === "invokefunction" && typeof message.invocation_id === "string" && !this.invocations.has(message.invocation_id)) continue;
|
|
384
|
-
|
|
3001
|
+
try {
|
|
3002
|
+
this.sendMessageRaw(JSON.stringify(message));
|
|
3003
|
+
} catch (error) {
|
|
3004
|
+
if (!isPayloadTooLargeError(error)) throw error;
|
|
3005
|
+
console.error("[iii] Queued JSON envelope rejected", error);
|
|
3006
|
+
}
|
|
385
3007
|
}
|
|
386
3008
|
}
|
|
387
3009
|
isOpen() {
|
|
388
3010
|
return this.ws?.readyState === WebSocket.OPEN;
|
|
389
3011
|
}
|
|
3012
|
+
snapshotRegistration(message) {
|
|
3013
|
+
return JSON.parse(JSON.stringify(message));
|
|
3014
|
+
}
|
|
3015
|
+
replayRegistration(type, message) {
|
|
3016
|
+
try {
|
|
3017
|
+
this.sendMessage(type, message, true);
|
|
3018
|
+
} catch (error) {
|
|
3019
|
+
if (!isPayloadTooLargeError(error)) throw error;
|
|
3020
|
+
console.error("[iii] Registration JSON envelope rejected", error);
|
|
3021
|
+
}
|
|
3022
|
+
}
|
|
3023
|
+
prepareJson(message) {
|
|
3024
|
+
const data = JSON.stringify(message);
|
|
3025
|
+
const size = JSON_ENCODER.encode(data).byteLength;
|
|
3026
|
+
if (size <= MAX_JSON_FRAME_BYTES) return data;
|
|
3027
|
+
const error = createPayloadTooLargeError(size, typeof message.function_id === "string" ? message.function_id : void 0);
|
|
3028
|
+
if (message.type === "invocationresult") {
|
|
3029
|
+
const fallback = JSON.stringify({
|
|
3030
|
+
type: "invocationresult",
|
|
3031
|
+
invocation_id: message.invocation_id,
|
|
3032
|
+
function_id: message.function_id,
|
|
3033
|
+
error: {
|
|
3034
|
+
code: error.code,
|
|
3035
|
+
message: payloadTooLargeMessage(size)
|
|
3036
|
+
}
|
|
3037
|
+
});
|
|
3038
|
+
if (JSON_ENCODER.encode(fallback).byteLength <= MAX_JSON_FRAME_BYTES) return fallback;
|
|
3039
|
+
}
|
|
3040
|
+
if (typeof message.invocation_id === "string") {
|
|
3041
|
+
const pending = this.invocations.get(message.invocation_id);
|
|
3042
|
+
this.invocations.delete(message.invocation_id);
|
|
3043
|
+
pending?.reject(error);
|
|
3044
|
+
}
|
|
3045
|
+
throw error;
|
|
3046
|
+
}
|
|
390
3047
|
sendMessageRaw(data) {
|
|
3048
|
+
if (JSON_ENCODER.encode(data).byteLength > MAX_JSON_FRAME_BYTES) data = this.prepareJson(JSON.parse(data));
|
|
391
3049
|
if (this.ws && this.isOpen()) try {
|
|
392
3050
|
this.ws.send(data);
|
|
393
3051
|
} catch (error) {
|
|
@@ -437,15 +3095,17 @@ var Sdk = class {
|
|
|
437
3095
|
runtime: "browser",
|
|
438
3096
|
name: this.workerName,
|
|
439
3097
|
os: globalThis.navigator?.userAgent ?? "browser",
|
|
440
|
-
...this.namespace !== void 0 ? { namespace: this.namespace } : {}
|
|
3098
|
+
...this.namespace !== void 0 ? { namespace: this.namespace } : {},
|
|
3099
|
+
features: [...SDK_FEATURES]
|
|
441
3100
|
},
|
|
442
3101
|
action: { type: "void" }
|
|
443
3102
|
});
|
|
444
3103
|
}
|
|
445
3104
|
sendMessage(messageType, message, skipIfClosed = false) {
|
|
446
3105
|
const wireMessage = this.toWireFormat(messageType, message);
|
|
447
|
-
|
|
448
|
-
|
|
3106
|
+
const data = this.prepareJson(wireMessage);
|
|
3107
|
+
if (this.isOpen()) this.sendMessageRaw(data);
|
|
3108
|
+
else if (!skipIfClosed) this.messagesToSend.push(JSON.parse(data));
|
|
449
3109
|
}
|
|
450
3110
|
onInvocationResult(invocation_id, result, error) {
|
|
451
3111
|
const invocation = this.invocations.get(invocation_id);
|
|
@@ -455,30 +3115,73 @@ var Sdk = class {
|
|
|
455
3115
|
}
|
|
456
3116
|
this.invocations.delete(invocation_id);
|
|
457
3117
|
}
|
|
3118
|
+
/**
|
|
3119
|
+
* Replaces channel refs with readers / writers. Copy-on-write: a value
|
|
3120
|
+
* without refs is returned as it is. Only arrays and plain objects are
|
|
3121
|
+
* walked, so a locally dispatched payload keeps its `Date`s, `Map`s and
|
|
3122
|
+
* class instances.
|
|
3123
|
+
*/
|
|
458
3124
|
resolveChannelValue(value) {
|
|
459
3125
|
if (require_utils.isChannelRef(value)) return value.direction === "read" ? new require_utils.ChannelReader(this.address, value) : new require_utils.ChannelWriter(this.address, value);
|
|
460
|
-
if (Array.isArray(value))
|
|
3126
|
+
if (Array.isArray(value)) {
|
|
3127
|
+
let out;
|
|
3128
|
+
for (let i = 0; i < value.length; i++) {
|
|
3129
|
+
const resolved = this.resolveChannelValue(value[i]);
|
|
3130
|
+
if (resolved !== value[i]) {
|
|
3131
|
+
out ?? (out = value.slice());
|
|
3132
|
+
out[i] = resolved;
|
|
3133
|
+
}
|
|
3134
|
+
}
|
|
3135
|
+
return out ?? value;
|
|
3136
|
+
}
|
|
461
3137
|
if (value !== null && typeof value === "object") {
|
|
462
|
-
const
|
|
463
|
-
|
|
464
|
-
|
|
3138
|
+
const proto = Object.getPrototypeOf(value);
|
|
3139
|
+
if (proto !== Object.prototype && proto !== null) return value;
|
|
3140
|
+
let out;
|
|
3141
|
+
for (const [k, v] of Object.entries(value)) {
|
|
3142
|
+
const resolved = this.resolveChannelValue(v);
|
|
3143
|
+
if (resolved !== v) {
|
|
3144
|
+
out ?? (out = { ...value });
|
|
3145
|
+
out[k] = resolved;
|
|
3146
|
+
}
|
|
3147
|
+
}
|
|
3148
|
+
return out ?? value;
|
|
465
3149
|
}
|
|
466
3150
|
return value;
|
|
467
3151
|
}
|
|
468
|
-
async onInvokeFunction(invocation_id, function_id, input, traceparent, baggage) {
|
|
3152
|
+
async onInvokeFunction(invocation_id, function_id, input, metadata, traceparent, baggage, observeFields = {}) {
|
|
469
3153
|
const fn = this.functions.get(function_id);
|
|
470
3154
|
const resolvedInput = this.resolveChannelValue(input);
|
|
471
3155
|
if (fn?.handler) {
|
|
3156
|
+
const handler = fn.handler;
|
|
3157
|
+
const ctx = {
|
|
3158
|
+
function_id,
|
|
3159
|
+
invocation_id: invocation_id ?? require_utils.randomUUID(),
|
|
3160
|
+
observe_depth: observeFields.observe_depth ?? 0,
|
|
3161
|
+
metadata
|
|
3162
|
+
};
|
|
3163
|
+
if (observeFields.caller) ctx.caller = observeFields.caller;
|
|
3164
|
+
if (observeFields.activation) ctx.activation = observeFields.activation;
|
|
3165
|
+
if (traceparent !== void 0) ctx.traceparent = traceparent;
|
|
3166
|
+
if (baggage !== void 0) ctx.baggage = baggage;
|
|
3167
|
+
const run = async () => {
|
|
3168
|
+
const untrack = trackRunning(ctx, MAX_RUNNING_INVOCATION_MS);
|
|
3169
|
+
try {
|
|
3170
|
+
return await runInContext(ctx, () => handler(resolvedInput, metadata));
|
|
3171
|
+
} finally {
|
|
3172
|
+
untrack();
|
|
3173
|
+
}
|
|
3174
|
+
};
|
|
472
3175
|
if (!invocation_id) {
|
|
473
3176
|
try {
|
|
474
|
-
await
|
|
3177
|
+
await run();
|
|
475
3178
|
} catch (error) {
|
|
476
3179
|
console.error(`[iii] Error invoking function ${function_id}`, error);
|
|
477
3180
|
}
|
|
478
3181
|
return;
|
|
479
3182
|
}
|
|
480
3183
|
try {
|
|
481
|
-
const result = await
|
|
3184
|
+
const result = await run();
|
|
482
3185
|
this.sendMessage("invocationresult", {
|
|
483
3186
|
invocation_id,
|
|
484
3187
|
function_id,
|
|
@@ -487,15 +3190,10 @@ var Sdk = class {
|
|
|
487
3190
|
baggage
|
|
488
3191
|
});
|
|
489
3192
|
} catch (error) {
|
|
490
|
-
const isError = error instanceof Error;
|
|
491
3193
|
this.sendMessage("invocationresult", {
|
|
492
3194
|
invocation_id,
|
|
493
3195
|
function_id,
|
|
494
|
-
error:
|
|
495
|
-
code: "invocation_failed",
|
|
496
|
-
message: isError ? error.message : String(error),
|
|
497
|
-
stacktrace: isError ? error.stack : void 0
|
|
498
|
-
},
|
|
3196
|
+
error: handlerErrorBody(error),
|
|
499
3197
|
traceparent,
|
|
500
3198
|
baggage
|
|
501
3199
|
});
|
|
@@ -586,16 +3284,68 @@ var Sdk = class {
|
|
|
586
3284
|
const { invocation_id, result, error } = message;
|
|
587
3285
|
this.onInvocationResult(invocation_id, result, error);
|
|
588
3286
|
} else if (msgType === "invokefunction") {
|
|
589
|
-
const { invocation_id, function_id, data, traceparent, baggage } = message;
|
|
590
|
-
this.onInvokeFunction(invocation_id, function_id, data, traceparent, baggage
|
|
3287
|
+
const { invocation_id, function_id, data, metadata, traceparent, baggage, caller, observe_depth, activation } = decodeInvokeFunction(message);
|
|
3288
|
+
this.onInvokeFunction(invocation_id, function_id, data, metadata, traceparent, baggage, {
|
|
3289
|
+
caller,
|
|
3290
|
+
observe_depth,
|
|
3291
|
+
activation
|
|
3292
|
+
});
|
|
3293
|
+
} else if (msgType === "functionregistered") {
|
|
3294
|
+
const msg = decodeFunctionRegistered(message);
|
|
3295
|
+
this.functions.get(msg.id)?.observe?.onFunctionRegistered(msg, this.connectionEpoch);
|
|
3296
|
+
} else if (msgType === "observeradded") {
|
|
3297
|
+
const msg = decodeObserverAdded(message);
|
|
3298
|
+
this.functions.get(msg.function_id)?.observe?.onObserverAdded(msg);
|
|
3299
|
+
} else if (msgType === "observerremoved") {
|
|
3300
|
+
const msg = decodeObserverRemoved(message);
|
|
3301
|
+
this.functions.get(msg.function_id)?.observe?.onObserverRemoved(msg);
|
|
3302
|
+
} else if (msgType === "observeresult") {
|
|
3303
|
+
const msg = decodeObserveResult(message);
|
|
3304
|
+
if (msg.warnings && msg.warnings.length > 0) console.warn(`[iii] Observer ${msg.id}: ${msg.warnings.join("; ")}`);
|
|
3305
|
+
this.onObserverState(msg.id, msg.state, msg.error);
|
|
3306
|
+
} else if (msgType === "observerstatechanged") {
|
|
3307
|
+
const msg = decodeObserverStateChanged(message);
|
|
3308
|
+
this.onObserverState(msg.id, msg.state, msg.reason);
|
|
591
3309
|
} else if (msgType === "registertrigger") this.onRegisterTrigger(message);
|
|
592
3310
|
else if (msgType === "unregistertrigger") this.onUnregisterTrigger(message);
|
|
593
3311
|
else if (msgType === "registrationrejected") this.onRegistrationRejected(message);
|
|
594
3312
|
else if (msgType === "workerregistered") {
|
|
595
|
-
const { worker_id, reattach_token } = message;
|
|
3313
|
+
const { worker_id, reattach_token, features } = decodeWorkerRegistered(message);
|
|
596
3314
|
this.workerId = worker_id;
|
|
597
3315
|
this.reattachToken = reattach_token;
|
|
3316
|
+
this.onEngineFeatures(features ?? []);
|
|
3317
|
+
}
|
|
3318
|
+
}
|
|
3319
|
+
/**
|
|
3320
|
+
* `WorkerRegistered` told this connection what the engine supports. With
|
|
3321
|
+
* `observe.v1` the observers are replayed (after the functions, sent on
|
|
3322
|
+
* open) and held reports flushed; without it `observe()` fails with
|
|
3323
|
+
* `UNSUPPORTED` and observe hooks are inactive.
|
|
3324
|
+
*/
|
|
3325
|
+
onEngineFeatures(features) {
|
|
3326
|
+
this.engineFeatures = new Set(features);
|
|
3327
|
+
this.registeredOnConnection = true;
|
|
3328
|
+
const queued = this.observeQueue;
|
|
3329
|
+
this.observeQueue = [];
|
|
3330
|
+
if (this.engineFeatures.has("observe.v1")) {
|
|
3331
|
+
for (const frame of queued) this.sendMessageRaw(JSON.stringify(frame));
|
|
3332
|
+
for (const handle of this.observers.values()) this.sendObserve(handle);
|
|
3333
|
+
this.reporter.flush();
|
|
3334
|
+
return;
|
|
598
3335
|
}
|
|
3336
|
+
for (const handle of this.observers.values()) handle.setState("error", UNSUPPORTED_REASON);
|
|
3337
|
+
for (const [functionId, fn] of this.functions) if (fn.observe?.needsObserve) this.warnHooksInactive(functionId);
|
|
3338
|
+
this.reporter.clear();
|
|
3339
|
+
}
|
|
3340
|
+
onObserverState(id, wireState, reason) {
|
|
3341
|
+
const handle = this.observers.get(id);
|
|
3342
|
+
if (!handle) return;
|
|
3343
|
+
const state = toObserverState(wireState);
|
|
3344
|
+
handle.setState(state, reason ? {
|
|
3345
|
+
code: reason.code,
|
|
3346
|
+
message: reason.message
|
|
3347
|
+
} : void 0);
|
|
3348
|
+
if (state === "disposed") this.observers.delete(id);
|
|
599
3349
|
}
|
|
600
3350
|
/**
|
|
601
3351
|
* The engine rejected a registration. A `FUNCTION_NAMESPACE_CONFLICT` costs
|
|
@@ -607,6 +3357,7 @@ var Sdk = class {
|
|
|
607
3357
|
*/
|
|
608
3358
|
onRegistrationRejected(init) {
|
|
609
3359
|
if (init.code === "FUNCTION_NAMESPACE_CONFLICT") {
|
|
3360
|
+
if (init.function_id !== void 0) this.functions.get(init.function_id)?.observe?.onRegistrationRejected(this.connectionEpoch);
|
|
610
3361
|
console.warn(`[iii] Function registration rejected: function "${init.function_id ?? "<unknown>"}" in namespace "${init.namespace}" is already exported by worker ${init.owner_worker_id}. Staying connected and serving the rest.`);
|
|
611
3362
|
return;
|
|
612
3363
|
}
|
|
@@ -687,6 +3438,8 @@ exports.ChannelReader = require_utils.ChannelReader;
|
|
|
687
3438
|
exports.ChannelWriter = require_utils.ChannelWriter;
|
|
688
3439
|
exports.EngineFunctions = EngineFunctions;
|
|
689
3440
|
exports.EngineTriggers = EngineTriggers;
|
|
3441
|
+
exports.InvocationError = InvocationError;
|
|
3442
|
+
exports.ObserveRejection = ObserveRejection;
|
|
690
3443
|
exports.RegistrationRejectedError = RegistrationRejectedError;
|
|
691
3444
|
exports.TriggerAction = TriggerAction;
|
|
692
3445
|
exports.registerWorker = registerWorker;
|