iii-browser-sdk 0.25.0 → 0.26.0-rc.2
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 +186 -49
- package/dist/helpers.cjs +1 -5
- package/dist/helpers.cjs.map +1 -1
- package/dist/helpers.d.cts +1 -5
- package/dist/helpers.d.cts.map +1 -1
- package/dist/helpers.d.mts +1 -5
- package/dist/helpers.d.mts.map +1 -1
- package/dist/helpers.mjs +1 -5
- package/dist/helpers.mjs.map +1 -1
- package/dist/index.cjs +1764 -1028
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +33 -9
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +33 -9
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1763 -1028
- package/dist/index.mjs.map +1 -1
- package/dist/stream.d.cts +2 -26
- package/dist/stream.d.cts.map +1 -1
- package/dist/stream.d.mts +2 -26
- package/dist/stream.d.mts.map +1 -1
- package/dist/{types-BGYN2Z4E.d.cts → types-DqyCQ8JS.d.mts} +631 -621
- package/dist/types-DqyCQ8JS.d.mts.map +1 -0
- package/dist/{types-Crw4auK5.d.mts → types-KMHoWM6-.d.cts} +631 -621
- package/dist/types-KMHoWM6-.d.cts.map +1 -0
- package/dist/{utils-BUI0XQTZ.cjs → utils-Cy-Lu8WQ.cjs} +22 -5
- package/dist/utils-Cy-Lu8WQ.cjs.map +1 -0
- package/dist/{utils-Bz5eP_hN.mjs → utils-CyT9CwWA.mjs} +22 -5
- package/dist/utils-CyT9CwWA.mjs.map +1 -0
- package/package.json +2 -2
- package/dist/types-BGYN2Z4E.d.cts.map +0 -1
- package/dist/types-Crw4auK5.d.mts.map +0 -1
- package/dist/utils-BUI0XQTZ.cjs.map +0 -1
- package/dist/utils-Bz5eP_hN.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as utf8ByteLength, c as ChannelReader, i as unrefTimer, l as ChannelWriter, n as isChannelRef, r as randomUUID } from "./utils-
|
|
1
|
+
import { a as utf8ByteLength, c as ChannelReader, i as unrefTimer, l as ChannelWriter, n as isChannelRef, r as randomUUID } from "./utils-CyT9CwWA.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/errors.ts
|
|
4
4
|
/**
|
|
@@ -19,14 +19,13 @@ var RegistrationRejectedError = class extends Error {
|
|
|
19
19
|
};
|
|
20
20
|
/**
|
|
21
21
|
* An error the SDK raises itself for an invocation, with a machine-readable
|
|
22
|
-
* `code`:
|
|
23
|
-
*
|
|
24
|
-
* descriptor (`INVALID_OBSERVE_DESCRIPTOR`). Mirrors the Node SDK.
|
|
22
|
+
* `code`: `LOCAL_DEPTH_EXCEEDED` (a local call nested too deep while the
|
|
23
|
+
* socket is closed) and `payload_too_large`. Mirrors the Node SDK.
|
|
25
24
|
*
|
|
26
|
-
* A call the engine answers with an error
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
25
|
+
* A call the engine answers with an error rejects with the engine's error
|
|
26
|
+
* body (`{ code, message, stacktrace? }`), and so does a locally dispatched
|
|
27
|
+
* call whose handler or deliver hook throws: both paths reject with the same
|
|
28
|
+
* value.
|
|
30
29
|
*/
|
|
31
30
|
var InvocationError = class extends Error {
|
|
32
31
|
constructor(init) {
|
|
@@ -38,6 +37,110 @@ var InvocationError = class extends Error {
|
|
|
38
37
|
}
|
|
39
38
|
};
|
|
40
39
|
/**
|
|
40
|
+
* The error a call that timed out rejects with, on the remote and the local
|
|
41
|
+
* path: an `Error` (its message unchanged from earlier releases) that also
|
|
42
|
+
* carries `code: 'TIMEOUT'` and the `function_id`, like the Node SDK's.
|
|
43
|
+
*/
|
|
44
|
+
var InvocationTimeoutError = class extends Error {
|
|
45
|
+
constructor(ms, functionId) {
|
|
46
|
+
super(`Invocation timeout after ${ms}ms: ${functionId}`);
|
|
47
|
+
this.code = "TIMEOUT";
|
|
48
|
+
this.function_id = functionId;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
/** What a failure reports when the thrown value cannot even be read (a getter or `toString` that throws). */
|
|
52
|
+
const UNREADABLE_FAILURE = "the handler failed with a value that cannot be read";
|
|
53
|
+
function safeString(value) {
|
|
54
|
+
try {
|
|
55
|
+
return String(value);
|
|
56
|
+
} catch {
|
|
57
|
+
return UNREADABLE_FAILURE;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* An error body as the engine sends it, and as this SDK's own calls reject
|
|
62
|
+
* with: a plain (JSON-parsed) object with a string `code`, a string `message`
|
|
63
|
+
* and, optionally, a string `stacktrace`. A class instance or anything else
|
|
64
|
+
* with such fields is not one: it is reported through `String()`.
|
|
65
|
+
*/
|
|
66
|
+
function isEngineErrorBody(value) {
|
|
67
|
+
if (value === null || typeof value !== "object") return false;
|
|
68
|
+
const proto = Object.getPrototypeOf(value);
|
|
69
|
+
if (proto !== Object.prototype && proto !== null) return false;
|
|
70
|
+
const body = value;
|
|
71
|
+
return typeof body.code === "string" && typeof body.message === "string" && (body.stacktrace === void 0 || typeof body.stacktrace === "string");
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* The error a handler's failure becomes, the same on the local and the remote
|
|
75
|
+
* path (code `invocation_failed`):
|
|
76
|
+
* - an `Error`, from any realm (an iframe's too): its message and stack;
|
|
77
|
+
* - an engine error body (a failed call's rejection, rethrown): its message and stacktrace;
|
|
78
|
+
* - anything else: `String(value)`.
|
|
79
|
+
* Never throws: when reading the value throws, a fixed message is reported, so
|
|
80
|
+
* the caller always gets its answer.
|
|
81
|
+
*/
|
|
82
|
+
function handlerErrorBody(error) {
|
|
83
|
+
try {
|
|
84
|
+
if (error instanceof Error || Object.prototype.toString.call(error) === "[object Error]") {
|
|
85
|
+
const { message, stack } = error;
|
|
86
|
+
return {
|
|
87
|
+
code: "invocation_failed",
|
|
88
|
+
message: typeof message === "string" ? message : safeString(message),
|
|
89
|
+
stacktrace: typeof stack === "string" ? stack : void 0
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
if (isEngineErrorBody(error)) return {
|
|
93
|
+
code: "invocation_failed",
|
|
94
|
+
message: error.message,
|
|
95
|
+
stacktrace: error.stacktrace
|
|
96
|
+
};
|
|
97
|
+
return {
|
|
98
|
+
code: "invocation_failed",
|
|
99
|
+
message: String(error),
|
|
100
|
+
stacktrace: void 0
|
|
101
|
+
};
|
|
102
|
+
} catch {
|
|
103
|
+
return {
|
|
104
|
+
code: "invocation_failed",
|
|
105
|
+
message: safeString(error),
|
|
106
|
+
stacktrace: void 0
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* The error a deliver hook's failure becomes: an {@link ObserveRejection}, an
|
|
112
|
+
* {@link InvocationError}, a call that timed out ({@link InvocationTimeoutError})
|
|
113
|
+
* or an engine error body (a failed call's rejection, rethrown) keeps its code
|
|
114
|
+
* and message; anything else is a handler failure ({@link handlerErrorBody}).
|
|
115
|
+
* Never throws.
|
|
116
|
+
*/
|
|
117
|
+
function deliverErrorBody(error) {
|
|
118
|
+
try {
|
|
119
|
+
if (error instanceof ObserveRejection) return {
|
|
120
|
+
code: error.code,
|
|
121
|
+
message: error.message
|
|
122
|
+
};
|
|
123
|
+
if (error instanceof InvocationError) {
|
|
124
|
+
const prefix = `${error.code}: `;
|
|
125
|
+
return {
|
|
126
|
+
code: error.code,
|
|
127
|
+
message: error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message,
|
|
128
|
+
stacktrace: error.stacktrace
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
if (error instanceof InvocationTimeoutError) return {
|
|
132
|
+
code: error.code,
|
|
133
|
+
message: error.message
|
|
134
|
+
};
|
|
135
|
+
if (isEngineErrorBody(error)) return {
|
|
136
|
+
code: error.code,
|
|
137
|
+
message: error.message,
|
|
138
|
+
stacktrace: error.stacktrace
|
|
139
|
+
};
|
|
140
|
+
} catch {}
|
|
141
|
+
return handlerErrorBody(error);
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
41
144
|
* Thrown by an `onObserverAdded` hook to reject an observer with a code of
|
|
42
145
|
* its own (`HTTP_ROUTE_CONFLICT`, `INVALID_CRON_EXPRESSION`, ...); any other
|
|
43
146
|
* error rejects it with `OBSERVE_REJECTED`. Also the error `ObserverHandle.ready()`
|
|
@@ -45,11 +148,11 @@ var InvocationError = class extends Error {
|
|
|
45
148
|
*
|
|
46
149
|
* @example
|
|
47
150
|
* ```typescript
|
|
48
|
-
* onObserverAdded(obs) {
|
|
151
|
+
* iii.onObserverAdded('cron::on-tick', (obs) => {
|
|
49
152
|
* if (!isValidCron(obs.args.expression)) {
|
|
50
153
|
* throw new ObserveRejection('INVALID_CRON_EXPRESSION', 'invalid day-of-week field')
|
|
51
154
|
* }
|
|
52
|
-
* }
|
|
155
|
+
* })
|
|
53
156
|
* ```
|
|
54
157
|
*/
|
|
55
158
|
var ObserveRejection = class extends Error {
|
|
@@ -60,44 +163,6 @@ var ObserveRejection = class extends Error {
|
|
|
60
163
|
}
|
|
61
164
|
};
|
|
62
165
|
|
|
63
|
-
//#endregion
|
|
64
|
-
//#region src/iii-constants.ts
|
|
65
|
-
/**
|
|
66
|
-
* Constants for the III module.
|
|
67
|
-
*/
|
|
68
|
-
/**
|
|
69
|
-
* Engine function paths for internal operations.
|
|
70
|
-
*
|
|
71
|
-
* Naming note: `LIST_TRIGGERS` / `INFO_TRIGGERS` cover trigger TYPES
|
|
72
|
-
* (templates). `LIST_REGISTERED_TRIGGERS` / `INFO_REGISTERED_TRIGGERS`
|
|
73
|
-
* cover trigger INSTANCES (subscriber rows). The old
|
|
74
|
-
* `engine::trigger-types::list` builtin has been removed and is now
|
|
75
|
-
* served by `engine::triggers::list`.
|
|
76
|
-
*/
|
|
77
|
-
const EngineFunctions = {
|
|
78
|
-
LIST_FUNCTIONS: "engine::functions::list",
|
|
79
|
-
INFO_FUNCTIONS: "engine::functions::info",
|
|
80
|
-
LIST_WORKERS: "engine::workers::list",
|
|
81
|
-
INFO_WORKERS: "engine::workers::info",
|
|
82
|
-
LIST_TRIGGERS: "engine::triggers::list",
|
|
83
|
-
INFO_TRIGGERS: "engine::triggers::info",
|
|
84
|
-
LIST_REGISTERED_TRIGGERS: "engine::registered-triggers::list",
|
|
85
|
-
INFO_REGISTERED_TRIGGERS: "engine::registered-triggers::info",
|
|
86
|
-
REGISTER_WORKER: "engine::workers::register"
|
|
87
|
-
};
|
|
88
|
-
/** Engine trigger types */
|
|
89
|
-
const EngineTriggers = { FUNCTIONS_AVAILABLE: "engine::functions-available" };
|
|
90
|
-
/** Default reconnection configuration */
|
|
91
|
-
const DEFAULT_BRIDGE_RECONNECTION_CONFIG = {
|
|
92
|
-
initialDelayMs: 1e3,
|
|
93
|
-
maxDelayMs: 3e4,
|
|
94
|
-
backoffMultiplier: 2,
|
|
95
|
-
jitterFactor: .3,
|
|
96
|
-
maxRetries: -1
|
|
97
|
-
};
|
|
98
|
-
/** Default invocation timeout in milliseconds */
|
|
99
|
-
const DEFAULT_INVOCATION_TIMEOUT_MS = 3e4;
|
|
100
|
-
|
|
101
166
|
//#endregion
|
|
102
167
|
//#region ../iii/src/filter/errors.ts
|
|
103
168
|
const MAX_ENCODED_BYTES = 8192;
|
|
@@ -144,7 +209,7 @@ function checkString(s, at, what) {
|
|
|
144
209
|
}
|
|
145
210
|
}
|
|
146
211
|
/** An object JSON writes member by member: a prototype-less object or one whose prototype is a realm's `Object.prototype`. */
|
|
147
|
-
function isPlainObject(v) {
|
|
212
|
+
function isPlainObject$1(v) {
|
|
148
213
|
const proto = Object.getPrototypeOf(v);
|
|
149
214
|
return proto === null || Object.getPrototypeOf(proto) === null;
|
|
150
215
|
}
|
|
@@ -208,7 +273,7 @@ function checkJson(src) {
|
|
|
208
273
|
}
|
|
209
274
|
continue;
|
|
210
275
|
}
|
|
211
|
-
if (!isPlainObject(value)) throw FilterError.invalid(`${where(at)}: ${describe(value)} is not a JSON object (use a plain object)`);
|
|
276
|
+
if (!isPlainObject$1(value)) throw FilterError.invalid(`${where(at)}: ${describe(value)} is not a JSON object (use a plain object)`);
|
|
212
277
|
if (Object.getOwnPropertySymbols(value).length > 0) throw FilterError.invalid(`${where(at)}: symbol keys are not JSON`);
|
|
213
278
|
for (const key of Object.getOwnPropertyNames(value)) {
|
|
214
279
|
const member = at === "" ? key : `${at}.${key}`;
|
|
@@ -759,6 +824,221 @@ function checkLiteralDepth(path, name, literal) {
|
|
|
759
824
|
}
|
|
760
825
|
}
|
|
761
826
|
|
|
827
|
+
//#endregion
|
|
828
|
+
//#region ../iii/src/filter/filter-index.ts
|
|
829
|
+
function isScalar(value) {
|
|
830
|
+
return value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string";
|
|
831
|
+
}
|
|
832
|
+
/**
|
|
833
|
+
* The equality conditions of `source`, a filter that compiled: for each
|
|
834
|
+
* clause of its top-level `$and` (its keys and those of the filters its
|
|
835
|
+
* `$and`s hold, never inside `$or`, `$not` or `$any`), its `$eq` operand or
|
|
836
|
+
* its `$in` operands, when they are scalars. `path` is the parsed path,
|
|
837
|
+
* spelled one way whatever escapes the filter used.
|
|
838
|
+
*/
|
|
839
|
+
function conditionsOf(source) {
|
|
840
|
+
const out = [];
|
|
841
|
+
const pending = [source];
|
|
842
|
+
while (pending.length > 0) {
|
|
843
|
+
const current = pending.pop();
|
|
844
|
+
for (const key of Object.keys(current)) {
|
|
845
|
+
const value = current[key];
|
|
846
|
+
if (key === "$and") {
|
|
847
|
+
for (const item of value) pending.push(item);
|
|
848
|
+
continue;
|
|
849
|
+
}
|
|
850
|
+
if (key.startsWith("$")) continue;
|
|
851
|
+
const ops = value;
|
|
852
|
+
const eq = ops.$eq;
|
|
853
|
+
const inItems = ops.$in;
|
|
854
|
+
const hasEq = Object.prototype.hasOwnProperty.call(ops, "$eq");
|
|
855
|
+
if (!hasEq && !Array.isArray(inItems)) continue;
|
|
856
|
+
const parsed = parsePath(key, false);
|
|
857
|
+
const path = JSON.stringify([parsed.root, ...parsed.segments.map((s) => s.key)]);
|
|
858
|
+
if (hasEq && isScalar(eq)) out.push({
|
|
859
|
+
path,
|
|
860
|
+
raw: key,
|
|
861
|
+
values: [eq]
|
|
862
|
+
});
|
|
863
|
+
if (Array.isArray(inItems) && inItems.length > 0 && inItems.every(isScalar)) out.push({
|
|
864
|
+
path,
|
|
865
|
+
raw: key,
|
|
866
|
+
values: [...new Set(inItems)]
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
return out;
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* Filters, each with a value and an order, matched against a document by an
|
|
874
|
+
* index of their equality conditions (see the module docs).
|
|
875
|
+
* {@link FilterIndex.matches} returns exactly the values whose filter
|
|
876
|
+
* matches the document (and that `accept` accepts), by ascending `order`.
|
|
877
|
+
*/
|
|
878
|
+
var FilterIndex = class {
|
|
879
|
+
constructor() {
|
|
880
|
+
this.filed = /* @__PURE__ */ new Map();
|
|
881
|
+
this.scanned = /* @__PURE__ */ new Set();
|
|
882
|
+
this.paths = /* @__PURE__ */ new Map();
|
|
883
|
+
this.indexed = 0;
|
|
884
|
+
}
|
|
885
|
+
/** Entries held. */
|
|
886
|
+
get size() {
|
|
887
|
+
return this.filed.size;
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Whether {@link FilterIndex.matches} can evaluate fewer filters than
|
|
891
|
+
* evaluating each entry's would. Looking a document's value up at an
|
|
892
|
+
* indexed path costs about one evaluation, and rules out the entries filed
|
|
893
|
+
* there under other values, so it can only when some indexed path files
|
|
894
|
+
* more than one entry. Otherwise evaluating each filter in order costs less
|
|
895
|
+
* and yields the same matches.
|
|
896
|
+
*/
|
|
897
|
+
get narrows() {
|
|
898
|
+
return this.indexed > this.paths.size;
|
|
899
|
+
}
|
|
900
|
+
has(value) {
|
|
901
|
+
return this.filed.has(value);
|
|
902
|
+
}
|
|
903
|
+
/**
|
|
904
|
+
* Files `value` with `filter`, in place of the entry `value` had. `order`
|
|
905
|
+
* sorts the matches. The condition it is filed under is the one of the
|
|
906
|
+
* filter's top-level `$and` that the fewest entries share now (an `$eq`
|
|
907
|
+
* before an `$in` of several values).
|
|
908
|
+
*/
|
|
909
|
+
insert(value, filter, order) {
|
|
910
|
+
this.remove(value);
|
|
911
|
+
const entry = {
|
|
912
|
+
value,
|
|
913
|
+
filter,
|
|
914
|
+
order
|
|
915
|
+
};
|
|
916
|
+
const condition = this.conditionFor(filter);
|
|
917
|
+
if (!condition) {
|
|
918
|
+
this.scanned.add(entry);
|
|
919
|
+
this.filed.set(value, { entry });
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
let index = this.paths.get(condition.path);
|
|
923
|
+
if (!index) {
|
|
924
|
+
index = {
|
|
925
|
+
resolve: compilePath(parsePath(condition.raw, false)),
|
|
926
|
+
buckets: /* @__PURE__ */ new Map(),
|
|
927
|
+
entries: 0
|
|
928
|
+
};
|
|
929
|
+
this.paths.set(condition.path, index);
|
|
930
|
+
}
|
|
931
|
+
for (const scalar of condition.values) {
|
|
932
|
+
const bucket = index.buckets.get(scalar);
|
|
933
|
+
if (bucket) bucket.add(entry);
|
|
934
|
+
else index.buckets.set(scalar, new Set([entry]));
|
|
935
|
+
}
|
|
936
|
+
index.entries++;
|
|
937
|
+
this.indexed++;
|
|
938
|
+
this.filed.set(value, {
|
|
939
|
+
entry,
|
|
940
|
+
path: condition.path,
|
|
941
|
+
values: condition.values
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
/** Takes the entry of `value` out. */
|
|
945
|
+
remove(value) {
|
|
946
|
+
const filed = this.filed.get(value);
|
|
947
|
+
if (!filed) return;
|
|
948
|
+
this.filed.delete(value);
|
|
949
|
+
if (filed.path === void 0 || filed.values === void 0) {
|
|
950
|
+
this.scanned.delete(filed.entry);
|
|
951
|
+
return;
|
|
952
|
+
}
|
|
953
|
+
const index = this.paths.get(filed.path);
|
|
954
|
+
if (!index) return;
|
|
955
|
+
this.indexed--;
|
|
956
|
+
for (const scalar of filed.values) {
|
|
957
|
+
const bucket = index.buckets.get(scalar);
|
|
958
|
+
if (!bucket) continue;
|
|
959
|
+
bucket.delete(filed.entry);
|
|
960
|
+
if (bucket.size === 0) index.buckets.delete(scalar);
|
|
961
|
+
}
|
|
962
|
+
if (--index.entries === 0) this.paths.delete(filed.path);
|
|
963
|
+
}
|
|
964
|
+
/**
|
|
965
|
+
* The values whose filter matches `doc`, by ascending order. Resolves each
|
|
966
|
+
* indexed path of `doc` once, and evaluates the filters of the entries
|
|
967
|
+
* filed under the value found there and of the scanned entries
|
|
968
|
+
* ({@link FilterIndex.candidates} counts them); every other entry has a
|
|
969
|
+
* condition `doc` fails. `accept` is asked first, for each candidate.
|
|
970
|
+
*/
|
|
971
|
+
matches(doc, accept) {
|
|
972
|
+
const found = [];
|
|
973
|
+
let sorted = true;
|
|
974
|
+
let last = -Infinity;
|
|
975
|
+
if (this.paths.size > 0) for (const index of this.paths.values()) {
|
|
976
|
+
const bucket = this.bucket(index, doc);
|
|
977
|
+
if (bucket === void 0) continue;
|
|
978
|
+
for (const entry of bucket) if ((accept === void 0 || accept(entry.value)) && entry.filter.matches(doc)) {
|
|
979
|
+
if (entry.order < last) sorted = false;
|
|
980
|
+
last = entry.order;
|
|
981
|
+
found.push(entry);
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
if (this.scanned.size > 0) {
|
|
985
|
+
for (const entry of this.scanned) if ((accept === void 0 || accept(entry.value)) && entry.filter.matches(doc)) {
|
|
986
|
+
if (entry.order < last) sorted = false;
|
|
987
|
+
last = entry.order;
|
|
988
|
+
found.push(entry);
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
if (!sorted) found.sort((a, b) => a.order - b.order);
|
|
992
|
+
const values = new Array(found.length);
|
|
993
|
+
for (let i = 0; i < found.length; i++) values[i] = found[i].value;
|
|
994
|
+
return values;
|
|
995
|
+
}
|
|
996
|
+
/** How many filters a match of `doc` evaluates: the entries filed under its values, and the scanned ones. */
|
|
997
|
+
candidates(doc) {
|
|
998
|
+
let n = this.scanned.size;
|
|
999
|
+
for (const index of this.paths.values()) n += this.bucket(index, doc)?.size ?? 0;
|
|
1000
|
+
return n;
|
|
1001
|
+
}
|
|
1002
|
+
/**
|
|
1003
|
+
* The entries filed under `doc`'s value at the path. A value an index
|
|
1004
|
+
* cannot hold (absent, an array, an object) matches no condition, and
|
|
1005
|
+
* neither does a path whose reading throws: each filter filed under it
|
|
1006
|
+
* holds a clause on that path, and a filter whose reading throws does not
|
|
1007
|
+
* match.
|
|
1008
|
+
*/
|
|
1009
|
+
bucket(index, doc) {
|
|
1010
|
+
let value;
|
|
1011
|
+
try {
|
|
1012
|
+
value = index.resolve(doc !== null && typeof doc === "object" ? doc : {}, void 0);
|
|
1013
|
+
} catch {
|
|
1014
|
+
return;
|
|
1015
|
+
}
|
|
1016
|
+
return isScalar(value) ? index.buckets.get(value) : void 0;
|
|
1017
|
+
}
|
|
1018
|
+
conditionFor(filter) {
|
|
1019
|
+
let best;
|
|
1020
|
+
for (const condition of conditionsOf(filter.source)) {
|
|
1021
|
+
const held = this.paths.get(condition.path);
|
|
1022
|
+
let sharing = 0;
|
|
1023
|
+
if (held) for (const scalar of condition.values) sharing += held.buckets.get(scalar)?.size ?? 0;
|
|
1024
|
+
const score = [
|
|
1025
|
+
condition.values.length > 1 ? 1 : 0,
|
|
1026
|
+
sharing,
|
|
1027
|
+
condition.values.length
|
|
1028
|
+
];
|
|
1029
|
+
if (best === void 0 || lessThan(score, best.score)) best = {
|
|
1030
|
+
condition,
|
|
1031
|
+
score
|
|
1032
|
+
};
|
|
1033
|
+
}
|
|
1034
|
+
return best?.condition;
|
|
1035
|
+
}
|
|
1036
|
+
};
|
|
1037
|
+
function lessThan(a, b) {
|
|
1038
|
+
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return a[i] < b[i];
|
|
1039
|
+
return false;
|
|
1040
|
+
}
|
|
1041
|
+
|
|
762
1042
|
//#endregion
|
|
763
1043
|
//#region ../iii/src/filter/index.ts
|
|
764
1044
|
/**
|
|
@@ -796,6 +1076,55 @@ function compileFilter(src, options) {
|
|
|
796
1076
|
/** The filter that matches every document (`{}`). */
|
|
797
1077
|
const MATCH_ALL = compileFilter({});
|
|
798
1078
|
|
|
1079
|
+
//#endregion
|
|
1080
|
+
//#region src/iii-constants.ts
|
|
1081
|
+
/**
|
|
1082
|
+
* Constants for the III module.
|
|
1083
|
+
*/
|
|
1084
|
+
/** Engine function paths for internal operations. */
|
|
1085
|
+
const EngineFunctions = {
|
|
1086
|
+
LIST_FUNCTIONS: "engine::functions::list",
|
|
1087
|
+
INFO_FUNCTIONS: "engine::functions::info",
|
|
1088
|
+
LIST_WORKERS: "engine::workers::list",
|
|
1089
|
+
INFO_WORKERS: "engine::workers::info",
|
|
1090
|
+
REGISTER_WORKER: "engine::workers::register"
|
|
1091
|
+
};
|
|
1092
|
+
/**
|
|
1093
|
+
* The event sources the engine hosts: private functions whose handler
|
|
1094
|
+
* returns the event, observed with `iii.observe(EngineSources.X, target)`.
|
|
1095
|
+
* None takes args; filter on the event (`input`) instead.
|
|
1096
|
+
*/
|
|
1097
|
+
const EngineSources = {
|
|
1098
|
+
/** A function was registered or unregistered; each row carries `observer_count`. */
|
|
1099
|
+
FUNCTIONS_CHANGED: "engine::on-functions-changed",
|
|
1100
|
+
/** A worker connected or left. */
|
|
1101
|
+
WORKERS_CHANGED: "engine::on-workers-changed",
|
|
1102
|
+
/** An observer changed state: `{ observer_id, function_id, target, state, reason? }`. */
|
|
1103
|
+
OBSERVERS_CHANGED: "engine::on-observers-changed",
|
|
1104
|
+
/** A log record. */
|
|
1105
|
+
LOG: "observability::on-log",
|
|
1106
|
+
/** A finished span. */
|
|
1107
|
+
SPAN: "observability::on-span",
|
|
1108
|
+
/** The engine's configuration was reloaded. */
|
|
1109
|
+
CONFIGURATION_UPDATED: "configuration::on-updated",
|
|
1110
|
+
/** A stream item changed; filter on `input.stream_name`, `input.group_id`. */
|
|
1111
|
+
STREAM_CHANGED: "stream::on-changed",
|
|
1112
|
+
/** A client joined a stream group. */
|
|
1113
|
+
STREAM_JOIN: "stream::on-join",
|
|
1114
|
+
/** A client left a stream group. */
|
|
1115
|
+
STREAM_LEAVE: "stream::on-leave"
|
|
1116
|
+
};
|
|
1117
|
+
/** Default reconnection configuration */
|
|
1118
|
+
const DEFAULT_BRIDGE_RECONNECTION_CONFIG = {
|
|
1119
|
+
initialDelayMs: 1e3,
|
|
1120
|
+
maxDelayMs: 3e4,
|
|
1121
|
+
backoffMultiplier: 2,
|
|
1122
|
+
jitterFactor: .3,
|
|
1123
|
+
maxRetries: -1
|
|
1124
|
+
};
|
|
1125
|
+
/** Default invocation timeout in milliseconds */
|
|
1126
|
+
const DEFAULT_INVOCATION_TIMEOUT_MS = 3e4;
|
|
1127
|
+
|
|
799
1128
|
//#endregion
|
|
800
1129
|
//#region src/iii-types.ts
|
|
801
1130
|
/**
|
|
@@ -803,13 +1132,23 @@ const MATCH_ALL = compileFilter({});
|
|
|
803
1132
|
* `engine::workers::register` `features` from the SDK).
|
|
804
1133
|
*/
|
|
805
1134
|
const FEATURE_OBSERVE_V1 = "observe.v1";
|
|
1135
|
+
/**
|
|
1136
|
+
* The host delivers the calls of its functions (routed ones included), and
|
|
1137
|
+
* functions may set `args_format`, `private`, `observable: false` and
|
|
1138
|
+
* `onObserverDeliver`. Includes `observe.v1`.
|
|
1139
|
+
*/
|
|
1140
|
+
const FEATURE_OBSERVE_V2 = "observe.v2";
|
|
806
1141
|
const FEATURE_LOCAL_DISPATCH_V1 = "local-dispatch.v1";
|
|
807
1142
|
/**
|
|
808
1143
|
* What this SDK declares in `engine::workers::register`. Not
|
|
809
1144
|
* `large-messages.v1`, unlike the other SDKs: a browser receives one 16 MiB
|
|
810
1145
|
* WebSocket frame at most.
|
|
811
1146
|
*/
|
|
812
|
-
const SDK_FEATURES = [
|
|
1147
|
+
const SDK_FEATURES = [
|
|
1148
|
+
FEATURE_OBSERVE_V1,
|
|
1149
|
+
FEATURE_OBSERVE_V2,
|
|
1150
|
+
FEATURE_LOCAL_DISPATCH_V1
|
|
1151
|
+
];
|
|
813
1152
|
|
|
814
1153
|
//#endregion
|
|
815
1154
|
//#region src/invocation-context.ts
|
|
@@ -832,10 +1171,10 @@ const MAX_RUNNING_INVOCATION_MS = 600 * 1e3;
|
|
|
832
1171
|
*
|
|
833
1172
|
* One scope for the whole page, like the Node SDK's one `AsyncLocalStorage`
|
|
834
1173
|
* per process: a handler of one worker that calls another worker's
|
|
835
|
-
* `
|
|
1174
|
+
* `call()` is that call's caller.
|
|
836
1175
|
*/
|
|
837
1176
|
let current;
|
|
838
|
-
/** The public views handed out, so `withInvocation(view, fn)` restores
|
|
1177
|
+
/** The public views handed out, so `withInvocation(view, fn)` restores the invocation they were taken from. */
|
|
839
1178
|
const views = /* @__PURE__ */ new WeakMap();
|
|
840
1179
|
function currentContext() {
|
|
841
1180
|
return current;
|
|
@@ -879,33 +1218,37 @@ function live() {
|
|
|
879
1218
|
}
|
|
880
1219
|
return out;
|
|
881
1220
|
}
|
|
882
|
-
/**
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
1221
|
+
/**
|
|
1222
|
+
* The invocations whose function's deliver hook is running: code after the
|
|
1223
|
+
* hook's `await`s falls back to them (see {@link callContext}).
|
|
1224
|
+
*/
|
|
1225
|
+
const delivering = /* @__PURE__ */ new WeakSet();
|
|
1226
|
+
/**
|
|
1227
|
+
* Marks `ctx` as delivering (its function's deliver hook is running); call
|
|
1228
|
+
* the returned function when the hook settles.
|
|
1229
|
+
*/
|
|
1230
|
+
function trackDelivering(ctx) {
|
|
1231
|
+
delivering.add(ctx);
|
|
1232
|
+
return () => {
|
|
1233
|
+
delivering.delete(ctx);
|
|
1234
|
+
};
|
|
892
1235
|
}
|
|
893
1236
|
/**
|
|
894
|
-
* The invocation a call
|
|
895
|
-
* scope
|
|
896
|
-
*
|
|
897
|
-
*
|
|
898
|
-
*
|
|
899
|
-
* Otherwise none, and the call carries no
|
|
900
|
-
* handler, if any, made it.
|
|
1237
|
+
* The invocation a call or a report made now belongs to. Inside a scope, the
|
|
1238
|
+
* scope's. Outside any scope (code after an `await`), the running invocation
|
|
1239
|
+
* when that is unambiguous: it is the only one running, and it is an observe
|
|
1240
|
+
* activation or its function's deliver hook is running (the calls the hook
|
|
1241
|
+
* makes after an `await`, through its observers or not). It lends its ids,
|
|
1242
|
+
* caller and trace context. Otherwise none, and the call carries no
|
|
1243
|
+
* `caller`: the SDK cannot tell which handler, if any, made it.
|
|
901
1244
|
*/
|
|
902
1245
|
function callContext() {
|
|
903
1246
|
if (current) return current;
|
|
904
1247
|
const all = live();
|
|
905
|
-
return all.length === 1 && all[0].activation
|
|
1248
|
+
return all.length === 1 && (all[0].activation || delivering.has(all[0])) ? all[0] : void 0;
|
|
906
1249
|
}
|
|
907
1250
|
/**
|
|
908
|
-
* The `observe_depth` a call
|
|
1251
|
+
* The `observe_depth` a call or a report made now carries. Inside a
|
|
909
1252
|
* scope, the scope's. Outside any scope, the deepest running invocation's:
|
|
910
1253
|
* the engine's loop guard counts on this depth, so code after an `await`
|
|
911
1254
|
* over-counts (a chain may stop earlier than `max_observe_depth`) rather than
|
|
@@ -972,7 +1315,7 @@ function runInContext(ctx, fn) {
|
|
|
972
1315
|
current = previous;
|
|
973
1316
|
}
|
|
974
1317
|
}
|
|
975
|
-
/** The public view of the current invocation
|
|
1318
|
+
/** The public view of the current invocation. */
|
|
976
1319
|
function publicContext(ctx) {
|
|
977
1320
|
if (!ctx) return void 0;
|
|
978
1321
|
const view = {
|
|
@@ -1017,278 +1360,123 @@ function contextFromView(view) {
|
|
|
1017
1360
|
}
|
|
1018
1361
|
|
|
1019
1362
|
//#endregion
|
|
1020
|
-
//#region src/
|
|
1021
|
-
/**
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1363
|
+
//#region src/observable.ts
|
|
1364
|
+
/**
|
|
1365
|
+
* The host side of observe (v2 §4): per-function observer state, the
|
|
1366
|
+
* observer hooks of the worker and of the function, the `Observer` object
|
|
1367
|
+
* handed to them, matching (the key index, and the index of the filters'
|
|
1368
|
+
* equality conditions), and the delivery of each call of a hosted function.
|
|
1369
|
+
*/
|
|
1370
|
+
/** CONTRACT D11: an observer hook still running after this is `OWNER_TIMEOUT`. */
|
|
1371
|
+
const OBSERVE_HOOK_TIMEOUT_MS = 3e4;
|
|
1372
|
+
function sameJson(a, b) {
|
|
1373
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
1029
1374
|
}
|
|
1030
|
-
|
|
1031
|
-
|
|
1375
|
+
/** Whether `obs` is served with the view `info` announces: its filters, target, capture and `on`. */
|
|
1376
|
+
function sameView(obs, info) {
|
|
1377
|
+
return obs.target === info.target && obs.on === info.on && sameJson(obs.capture, info.capture) && sameJson(obs.filters, info.filters);
|
|
1032
1378
|
}
|
|
1033
|
-
function
|
|
1034
|
-
|
|
1379
|
+
function rejectionBody(error) {
|
|
1380
|
+
if (error instanceof ObserveRejection) return {
|
|
1381
|
+
code: error.code,
|
|
1382
|
+
message: error.message
|
|
1383
|
+
};
|
|
1384
|
+
return {
|
|
1385
|
+
code: "OBSERVE_REJECTED",
|
|
1386
|
+
message: error instanceof Error ? error.message : String(error)
|
|
1387
|
+
};
|
|
1035
1388
|
}
|
|
1036
|
-
function
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1389
|
+
function onAccepts(on, ok) {
|
|
1390
|
+
return on === "complete" || (on === "success" ? ok : on === "error" ? !ok : false);
|
|
1391
|
+
}
|
|
1392
|
+
/**
|
|
1393
|
+
* Whether two copies of a value hold the same JSON data: primitives, arrays
|
|
1394
|
+
* and plain objects, compared member by member in one walk. Any other object
|
|
1395
|
+
* (a `Date`, a class instance, a channel reader) is the same only as itself,
|
|
1396
|
+
* and so is an object the walk reaches twice (a shared member or a cycle).
|
|
1397
|
+
* A local call compares the handler's copy of its input with the copy the
|
|
1398
|
+
* delivery took when the call started.
|
|
1399
|
+
*/
|
|
1400
|
+
function sameData(a, b) {
|
|
1401
|
+
const left = [a];
|
|
1402
|
+
const right = [b];
|
|
1403
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1404
|
+
while (left.length > 0) {
|
|
1405
|
+
const x = left.pop();
|
|
1406
|
+
const y = right.pop();
|
|
1407
|
+
if (x === y || Number.isNaN(x) && Number.isNaN(y)) continue;
|
|
1408
|
+
if (x === null || y === null || typeof x !== "object" || typeof y !== "object" || seen.has(x)) return false;
|
|
1409
|
+
seen.add(x);
|
|
1410
|
+
if (Array.isArray(x)) {
|
|
1411
|
+
if (!Array.isArray(y) || x.length !== y.length) return false;
|
|
1412
|
+
for (let i = 0; i < x.length; i++) {
|
|
1413
|
+
left.push(x[i]);
|
|
1414
|
+
right.push(y[i]);
|
|
1415
|
+
}
|
|
1416
|
+
continue;
|
|
1417
|
+
}
|
|
1418
|
+
if (Array.isArray(y) || !isPlainObject(x) || !isPlainObject(y)) return false;
|
|
1419
|
+
const keys = Object.keys(x);
|
|
1420
|
+
if (keys.length !== Object.keys(y).length) return false;
|
|
1421
|
+
for (const key of keys) {
|
|
1422
|
+
if (!Object.prototype.hasOwnProperty.call(y, key)) return false;
|
|
1423
|
+
left.push(x[key]);
|
|
1424
|
+
right.push(y[key]);
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
return true;
|
|
1428
|
+
}
|
|
1429
|
+
function isPlainObject(value) {
|
|
1430
|
+
const proto = Object.getPrototypeOf(value);
|
|
1431
|
+
return proto === Object.prototype || proto === null;
|
|
1432
|
+
}
|
|
1433
|
+
/** What filters read from a call; a call without `status` reads as a successful one. */
|
|
1434
|
+
function filterDoc(call) {
|
|
1435
|
+
const doc = {
|
|
1436
|
+
input: call.input,
|
|
1437
|
+
caller: call.caller,
|
|
1438
|
+
metadata: call.metadata
|
|
1041
1439
|
};
|
|
1042
|
-
if (
|
|
1043
|
-
|
|
1440
|
+
if (call.status === "error") doc.error = call.error;
|
|
1441
|
+
else doc.output = call.output;
|
|
1442
|
+
return doc;
|
|
1044
1443
|
}
|
|
1045
|
-
/** Copies the wire caller, dropping `null`s and a `parent` inside `parent`. */
|
|
1046
|
-
function decodeCaller(v, depth = 0) {
|
|
1047
|
-
if (!isRecord(v)) return void 0;
|
|
1048
|
-
const caller = {};
|
|
1049
|
-
for (const key of [
|
|
1050
|
-
"worker_id",
|
|
1051
|
-
"worker_name",
|
|
1052
|
-
"function_id",
|
|
1053
|
-
"invocation_id"
|
|
1054
|
-
]) {
|
|
1055
|
-
const value = str(v[key]);
|
|
1056
|
-
if (value !== void 0) caller[key] = value;
|
|
1057
|
-
}
|
|
1058
|
-
if (depth === 0) {
|
|
1059
|
-
const parent = decodeCaller(v.parent, 1);
|
|
1060
|
-
if (parent) caller.parent = parent;
|
|
1061
|
-
}
|
|
1062
|
-
return caller;
|
|
1063
|
-
}
|
|
1064
|
-
function decodeActivation(v) {
|
|
1065
|
-
if (!isRecord(v) || typeof v.observer_id !== "string") return void 0;
|
|
1066
|
-
const activation = { observer_id: v.observer_id };
|
|
1067
|
-
if (typeof v.activation_id === "string") activation.activation_id = v.activation_id;
|
|
1068
|
-
return activation;
|
|
1069
|
-
}
|
|
1070
|
-
/** An observer as the owner sees it (`observeradded.observer`, `functionregistered.observers[]`). */
|
|
1071
|
-
function decodeObserverInfo(v) {
|
|
1072
|
-
const raw = isRecord(v) ? v : {};
|
|
1073
|
-
const info = {
|
|
1074
|
-
id: String(raw.id ?? ""),
|
|
1075
|
-
args: isRecord(raw.args) ? raw.args : {},
|
|
1076
|
-
filters: raw.filters === void 0 ? {} : raw.filters,
|
|
1077
|
-
target: String(raw.target ?? ""),
|
|
1078
|
-
capture: Array.isArray(raw.capture) ? raw.capture.filter((c) => typeof c === "string") : [...DEFAULT_CAPTURE],
|
|
1079
|
-
on: str(raw.on) ?? "success"
|
|
1080
|
-
};
|
|
1081
|
-
if (isRecord(raw.legacy) && typeof raw.legacy.trigger_type === "string") info.legacy = {
|
|
1082
|
-
trigger_type: raw.legacy.trigger_type,
|
|
1083
|
-
config: raw.legacy.config ?? null
|
|
1084
|
-
};
|
|
1085
|
-
return info;
|
|
1086
|
-
}
|
|
1087
|
-
function decodeFunctionRegistered(v) {
|
|
1088
|
-
return {
|
|
1089
|
-
id: String(v.id ?? ""),
|
|
1090
|
-
namespace: String(v.namespace ?? ""),
|
|
1091
|
-
revision: num(v.revision) ?? 0,
|
|
1092
|
-
local_dispatch: v.local_dispatch === true,
|
|
1093
|
-
observers: Array.isArray(v.observers) ? v.observers.map(decodeObserverInfo) : []
|
|
1094
|
-
};
|
|
1095
|
-
}
|
|
1096
|
-
function decodeObserverAdded(v) {
|
|
1097
|
-
return {
|
|
1098
|
-
function_id: String(v.function_id ?? ""),
|
|
1099
|
-
namespace: String(v.namespace ?? ""),
|
|
1100
|
-
revision: num(v.revision) ?? 0,
|
|
1101
|
-
observer: decodeObserverInfo(v.observer)
|
|
1102
|
-
};
|
|
1103
|
-
}
|
|
1104
|
-
function decodeObserverRemoved(v) {
|
|
1105
|
-
return {
|
|
1106
|
-
function_id: String(v.function_id ?? ""),
|
|
1107
|
-
namespace: String(v.namespace ?? ""),
|
|
1108
|
-
revision: num(v.revision) ?? 0,
|
|
1109
|
-
id: String(v.id ?? "")
|
|
1110
|
-
};
|
|
1111
|
-
}
|
|
1112
|
-
function decodeObserveResult(v) {
|
|
1113
|
-
const msg = {
|
|
1114
|
-
id: String(v.id ?? ""),
|
|
1115
|
-
state: String(v.state ?? "")
|
|
1116
|
-
};
|
|
1117
|
-
const error = errorBody(v.error);
|
|
1118
|
-
if (error) msg.error = error;
|
|
1119
|
-
if (Array.isArray(v.warnings)) msg.warnings = v.warnings.filter((w) => typeof w === "string");
|
|
1120
|
-
return msg;
|
|
1121
|
-
}
|
|
1122
|
-
function decodeObserverStateChanged(v) {
|
|
1123
|
-
const msg = {
|
|
1124
|
-
id: String(v.id ?? ""),
|
|
1125
|
-
state: String(v.state ?? ""),
|
|
1126
|
-
fires: num(v.fires) ?? 0
|
|
1127
|
-
};
|
|
1128
|
-
const reason = errorBody(v.reason);
|
|
1129
|
-
if (reason) msg.reason = reason;
|
|
1130
|
-
return msg;
|
|
1131
|
-
}
|
|
1132
|
-
function decodeWorkerRegistered(v) {
|
|
1133
|
-
const msg = { worker_id: String(v.worker_id ?? "") };
|
|
1134
|
-
if (typeof v.reattach_token === "string") msg.reattach_token = v.reattach_token;
|
|
1135
|
-
if (Array.isArray(v.features)) msg.features = v.features.filter((f) => typeof f === "string");
|
|
1136
|
-
return msg;
|
|
1137
|
-
}
|
|
1138
|
-
/** The observe fields of an inbound `invokefunction` (`caller`, `observe_depth`, `activation`). */
|
|
1139
|
-
function decodeInvokeFunction(v) {
|
|
1140
|
-
const msg = {
|
|
1141
|
-
function_id: String(v.function_id ?? ""),
|
|
1142
|
-
data: v.data
|
|
1143
|
-
};
|
|
1144
|
-
if (typeof v.invocation_id === "string") msg.invocation_id = v.invocation_id;
|
|
1145
|
-
if (typeof v.traceparent === "string") msg.traceparent = v.traceparent;
|
|
1146
|
-
if (typeof v.baggage === "string") msg.baggage = v.baggage;
|
|
1147
|
-
if (isRecord(v.action)) msg.action = v.action;
|
|
1148
|
-
if (v.metadata !== void 0 && v.metadata !== null) msg.metadata = v.metadata;
|
|
1149
|
-
if (typeof v.namespace === "string") msg.namespace = v.namespace;
|
|
1150
|
-
const caller = decodeCaller(v.caller);
|
|
1151
|
-
if (caller) msg.caller = caller;
|
|
1152
|
-
const depth = num(v.observe_depth);
|
|
1153
|
-
if (depth !== void 0 && depth > 0) msg.observe_depth = depth;
|
|
1154
|
-
const activation = decodeActivation(v.activation);
|
|
1155
|
-
if (activation) msg.activation = activation;
|
|
1156
|
-
return msg;
|
|
1157
|
-
}
|
|
1158
|
-
/** Drops `parent` (one level only). */
|
|
1159
|
-
function stripCaller(caller) {
|
|
1160
|
-
if (!caller) return void 0;
|
|
1161
|
-
const { parent: _, ...rest } = caller;
|
|
1162
|
-
return rest;
|
|
1163
|
-
}
|
|
1164
|
-
/** JSON's view of a message: `undefined` fields left out, no caller-owned objects retained. */
|
|
1165
|
-
function snapshot(value) {
|
|
1166
|
-
return JSON.parse(JSON.stringify(value));
|
|
1167
|
-
}
|
|
1168
|
-
/**
|
|
1169
|
-
* `observe { id, source, target, ... }` from the three arguments of
|
|
1170
|
-
* `iii.observe`. Only what the caller set is sent; the engine applies the
|
|
1171
|
-
* defaults. `resolveNamespace` gives the namespace of an unqualified id (this
|
|
1172
|
-
* worker's, `default` for `engine::*`).
|
|
1173
|
-
*/
|
|
1174
|
-
function buildObserveMessage(id, source, target, options, resolveNamespace) {
|
|
1175
|
-
const targetRef = typeof target === "string" ? { function_id: target } : target;
|
|
1176
|
-
const sourceNamespace = resolveNamespace(source.namespace, source.function_id, "ObserveSource.namespace");
|
|
1177
|
-
const targetNamespace = resolveNamespace(targetRef.namespace, targetRef.function_id, "Target.namespace");
|
|
1178
|
-
return snapshot({
|
|
1179
|
-
id,
|
|
1180
|
-
source: {
|
|
1181
|
-
function_id: source.function_id,
|
|
1182
|
-
namespace: sourceNamespace,
|
|
1183
|
-
args: source.args,
|
|
1184
|
-
filters: source.filters,
|
|
1185
|
-
capture: source.capture,
|
|
1186
|
-
on: source.on,
|
|
1187
|
-
deliver: source.deliver
|
|
1188
|
-
},
|
|
1189
|
-
target: {
|
|
1190
|
-
function_id: targetRef.function_id,
|
|
1191
|
-
namespace: targetNamespace
|
|
1192
|
-
},
|
|
1193
|
-
metadata: options?.metadata,
|
|
1194
|
-
max_fires: options?.max_fires,
|
|
1195
|
-
expires_in_ms: options?.expires_in_ms,
|
|
1196
|
-
max_in_flight: options?.max_in_flight
|
|
1197
|
-
});
|
|
1198
|
-
}
|
|
1199
|
-
/** `registerfunction.observe`: the four fields that travel, or `undefined` when none is set. */
|
|
1200
|
-
function observeDescriptor(hooks) {
|
|
1201
|
-
if (!hooks) return void 0;
|
|
1202
|
-
const descriptor = snapshot({
|
|
1203
|
-
delivery: hooks.delivery,
|
|
1204
|
-
args_format: hooks.args_format,
|
|
1205
|
-
legacy_trigger_type: hooks.legacy_trigger_type,
|
|
1206
|
-
allow: hooks.allow
|
|
1207
|
-
});
|
|
1208
|
-
return Object.keys(descriptor).length > 0 ? descriptor : void 0;
|
|
1209
|
-
}
|
|
1210
|
-
function buildObserverAck(ack) {
|
|
1211
|
-
const msg = {
|
|
1212
|
-
function_id: ack.function_id,
|
|
1213
|
-
id: ack.id,
|
|
1214
|
-
revision: ack.revision
|
|
1215
|
-
};
|
|
1216
|
-
if (ack.namespace !== void 0) msg.namespace = ack.namespace;
|
|
1217
|
-
if (ack.error) msg.error = {
|
|
1218
|
-
code: ack.error.code,
|
|
1219
|
-
message: ack.error.message
|
|
1220
|
-
};
|
|
1221
|
-
return msg;
|
|
1222
|
-
}
|
|
1223
|
-
/**
|
|
1224
|
-
* An outbound `invokefunction`. `observe_depth` is left out when 0, and every
|
|
1225
|
-
* optional field when unset.
|
|
1226
|
-
*/
|
|
1227
|
-
function buildInvokeFunction(init) {
|
|
1228
|
-
const msg = {};
|
|
1229
|
-
if (init.invocation_id !== void 0) msg.invocation_id = init.invocation_id;
|
|
1230
|
-
msg.function_id = init.function_id;
|
|
1231
|
-
msg.data = init.data;
|
|
1232
|
-
if (init.traceparent !== void 0) msg.traceparent = init.traceparent;
|
|
1233
|
-
if (init.baggage !== void 0) msg.baggage = init.baggage;
|
|
1234
|
-
if (init.action !== void 0) msg.action = init.action;
|
|
1235
|
-
if (init.metadata !== void 0) msg.metadata = init.metadata;
|
|
1236
|
-
if (init.namespace !== void 0) msg.namespace = init.namespace;
|
|
1237
|
-
if (init.caller !== void 0) msg.caller = init.caller;
|
|
1238
|
-
if (init.observe_depth !== void 0 && init.observe_depth > 0) msg.observe_depth = init.observe_depth;
|
|
1239
|
-
if (init.activation !== void 0) msg.activation = init.activation;
|
|
1240
|
-
return msg;
|
|
1241
|
-
}
|
|
1242
|
-
/** The caller an outbound call asserts from inside a handler: that handler, and its own caller one level up. */
|
|
1243
|
-
function callerFor(ctx) {
|
|
1244
|
-
const caller = {
|
|
1245
|
-
function_id: ctx.function_id,
|
|
1246
|
-
invocation_id: ctx.invocation_id
|
|
1247
|
-
};
|
|
1248
|
-
const parent = stripCaller(ctx.caller);
|
|
1249
|
-
if (parent && Object.keys(parent).length > 0) caller.parent = parent;
|
|
1250
|
-
return caller;
|
|
1251
|
-
}
|
|
1252
|
-
|
|
1253
|
-
//#endregion
|
|
1254
|
-
//#region src/observable.ts
|
|
1255
1444
|
/**
|
|
1256
|
-
* The
|
|
1257
|
-
*
|
|
1258
|
-
*
|
|
1445
|
+
* The caller a report item carries: the engine sets `worker_id` and
|
|
1446
|
+
* `worker_name` itself, so they are left out (a `parent` keeps its own).
|
|
1447
|
+
* Nothing for a call made outside any handler.
|
|
1259
1448
|
*/
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
return
|
|
1449
|
+
function reportCaller(caller) {
|
|
1450
|
+
if (!caller) return void 0;
|
|
1451
|
+
const { worker_id: _, worker_name: __, ...rest } = caller;
|
|
1452
|
+
return Object.keys(rest).length > 0 ? rest : void 0;
|
|
1264
1453
|
}
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
message: error.message
|
|
1269
|
-
};
|
|
1270
|
-
return {
|
|
1271
|
-
code: "OBSERVE_REJECTED",
|
|
1272
|
-
message: error instanceof Error ? error.message : String(error)
|
|
1273
|
-
};
|
|
1454
|
+
/** The key functions of a match hook given as keys, if it is one. */
|
|
1455
|
+
function matchKeysOf(hook) {
|
|
1456
|
+
return hook !== void 0 && typeof hook !== "function" ? hook : void 0;
|
|
1274
1457
|
}
|
|
1275
|
-
function
|
|
1276
|
-
return
|
|
1458
|
+
function keyList(keys) {
|
|
1459
|
+
return typeof keys === "string" ? [keys] : keys;
|
|
1277
1460
|
}
|
|
1278
|
-
/** The `Observer`
|
|
1461
|
+
/** The `Observer` a host receives. Its identity is stable while the observer lives. */
|
|
1279
1462
|
var ObserverImpl = class {
|
|
1280
1463
|
constructor(owner, info, filter, revision) {
|
|
1281
1464
|
this.owner = owner;
|
|
1282
1465
|
this.active = false;
|
|
1466
|
+
this.activatedSeq = 0;
|
|
1283
1467
|
this.adding = false;
|
|
1468
|
+
this.levels = {
|
|
1469
|
+
worker: "none",
|
|
1470
|
+
fn: "none"
|
|
1471
|
+
};
|
|
1472
|
+
this.acceptance = "pending";
|
|
1284
1473
|
this.id = info.id;
|
|
1285
1474
|
this.function_id = owner.functionId;
|
|
1286
1475
|
this.args = info.args;
|
|
1287
1476
|
this.filters = info.filters;
|
|
1288
1477
|
this.target = info.target;
|
|
1289
|
-
this.capture = info.capture;
|
|
1290
1478
|
this.on = info.on;
|
|
1291
|
-
|
|
1479
|
+
this.capture = info.capture;
|
|
1292
1480
|
this.filter = filter;
|
|
1293
1481
|
this.revision = revision;
|
|
1294
1482
|
}
|
|
@@ -1297,21 +1485,36 @@ var ObserverImpl = class {
|
|
|
1297
1485
|
this.filters = info.filters;
|
|
1298
1486
|
this.filter = filter;
|
|
1299
1487
|
this.target = info.target;
|
|
1300
|
-
this.capture = info.capture;
|
|
1301
1488
|
this.on = info.on;
|
|
1489
|
+
this.capture = info.capture;
|
|
1302
1490
|
}
|
|
1303
|
-
matches(
|
|
1304
|
-
return this.filter.matches(
|
|
1305
|
-
}
|
|
1306
|
-
emit(event) {
|
|
1307
|
-
return this.owner.emit(this, event);
|
|
1491
|
+
matches(call) {
|
|
1492
|
+
return onAccepts(this.on, call.status !== "error") && this.filter.matches(filterDoc(call));
|
|
1308
1493
|
}
|
|
1309
|
-
|
|
1310
|
-
|
|
1494
|
+
accepted() {
|
|
1495
|
+
const state = this.acceptance;
|
|
1496
|
+
if (state === "accepted") return Promise.resolve();
|
|
1497
|
+
if (state !== "pending") return Promise.reject(new ObserveRejection(state.code, state.message));
|
|
1498
|
+
return new Promise((resolve, reject) => {
|
|
1499
|
+
this.waiters ?? (this.waiters = []);
|
|
1500
|
+
this.waiters.push({
|
|
1501
|
+
resolve,
|
|
1502
|
+
reject
|
|
1503
|
+
});
|
|
1504
|
+
});
|
|
1311
1505
|
}
|
|
1312
1506
|
reject(code, message) {
|
|
1313
1507
|
this.owner.reject(this, code, message);
|
|
1314
1508
|
}
|
|
1509
|
+
/** @internal Acked (`accepted`) or never to be: settles `accepted()`, once. */
|
|
1510
|
+
settleAcceptance(outcome) {
|
|
1511
|
+
if (this.acceptance !== "pending") return;
|
|
1512
|
+
this.acceptance = outcome;
|
|
1513
|
+
const waiters = this.waiters ?? [];
|
|
1514
|
+
this.waiters = void 0;
|
|
1515
|
+
for (const waiter of waiters) if (outcome === "accepted") waiter.resolve();
|
|
1516
|
+
else waiter.reject(new ObserveRejection(outcome.code, outcome.message));
|
|
1517
|
+
}
|
|
1315
1518
|
toJSON() {
|
|
1316
1519
|
return {
|
|
1317
1520
|
id: this.id,
|
|
@@ -1319,21 +1522,19 @@ var ObserverImpl = class {
|
|
|
1319
1522
|
args: this.args,
|
|
1320
1523
|
filters: this.filters,
|
|
1321
1524
|
target: this.target,
|
|
1322
|
-
capture: this.capture,
|
|
1323
1525
|
on: this.on,
|
|
1324
|
-
|
|
1526
|
+
capture: this.capture
|
|
1325
1527
|
};
|
|
1326
1528
|
}
|
|
1327
1529
|
};
|
|
1328
1530
|
/**
|
|
1329
1531
|
* One registered function's observers, as the engine pushed them
|
|
1330
1532
|
* (`functionregistered`, `observeradded`, `observerremoved`). Hooks run one
|
|
1331
|
-
* at a time, in
|
|
1533
|
+
* at a time, in the order the engine announced the observers.
|
|
1332
1534
|
*/
|
|
1333
1535
|
var FunctionObservers = class {
|
|
1334
|
-
constructor(functionId,
|
|
1536
|
+
constructor(functionId, localDispatchOption, hasHandler, host) {
|
|
1335
1537
|
this.functionId = functionId;
|
|
1336
|
-
this.hooks = hooks;
|
|
1337
1538
|
this.localDispatchOption = localDispatchOption;
|
|
1338
1539
|
this.hasHandler = hasHandler;
|
|
1339
1540
|
this.host = host;
|
|
@@ -1343,17 +1544,79 @@ var FunctionObservers = class {
|
|
|
1343
1544
|
this.revision = -1;
|
|
1344
1545
|
this.known = /* @__PURE__ */ new Map();
|
|
1345
1546
|
this.compiled = [];
|
|
1547
|
+
this.activations = 0;
|
|
1346
1548
|
this.queue = Promise.resolve();
|
|
1347
1549
|
this.disposed = false;
|
|
1348
1550
|
this.releases = 0;
|
|
1349
|
-
this.
|
|
1551
|
+
this.filterIndex = new FilterIndex();
|
|
1552
|
+
this.matchFailureLogged = false;
|
|
1553
|
+
this.matchChanged();
|
|
1554
|
+
}
|
|
1555
|
+
get reporter() {
|
|
1556
|
+
return this.host.reporter;
|
|
1557
|
+
}
|
|
1558
|
+
/** @internal */
|
|
1559
|
+
observeV2() {
|
|
1560
|
+
return this.host.observeV2();
|
|
1561
|
+
}
|
|
1562
|
+
/**
|
|
1563
|
+
* Whether a call would reach anyone. Without a call: any active observer
|
|
1564
|
+
* (one load). With a call, on a function matched by keys: an observer filed
|
|
1565
|
+
* under one of its keys (one lookup per key). Otherwise the call is not read.
|
|
1566
|
+
*/
|
|
1567
|
+
isObserved(call) {
|
|
1568
|
+
if (this.compiled.length === 0) return false;
|
|
1569
|
+
const keys = this.matchKeys;
|
|
1570
|
+
const index = this.index;
|
|
1571
|
+
if (call === void 0 || !keys || !index) return true;
|
|
1572
|
+
for (const key of this.callKeys(keys, call)) if (index.has(key)) return true;
|
|
1573
|
+
return false;
|
|
1574
|
+
}
|
|
1575
|
+
/**
|
|
1576
|
+
* The observers of the call's snapshot that want `call` (`onObserverMatch`):
|
|
1577
|
+
* all of `snapshot` without a match hook, those of it the predicate accepts,
|
|
1578
|
+
* or those filed under one of the call's keys that joined the active set no
|
|
1579
|
+
* later than `activations` (the count when the call started), each once. A
|
|
1580
|
+
* match hook that throws matches nothing.
|
|
1581
|
+
*/
|
|
1582
|
+
matching(call, snapshot, activations) {
|
|
1583
|
+
const hook = this.host.hooks(this.functionId).match;
|
|
1584
|
+
if (hook === void 0) return snapshot;
|
|
1585
|
+
if (typeof hook === "function") return snapshot.filter((obs) => {
|
|
1586
|
+
try {
|
|
1587
|
+
return hook(obs, call) === true;
|
|
1588
|
+
} catch (error) {
|
|
1589
|
+
this.matchFailed(error);
|
|
1590
|
+
return false;
|
|
1591
|
+
}
|
|
1592
|
+
});
|
|
1593
|
+
const index = this.index;
|
|
1594
|
+
if (this.matchKeys !== hook || !index) return [];
|
|
1595
|
+
const found = /* @__PURE__ */ new Set();
|
|
1596
|
+
for (const key of this.callKeys(hook, call)) {
|
|
1597
|
+
const filed = index.get(key);
|
|
1598
|
+
if (!filed) continue;
|
|
1599
|
+
for (const obs of filed) if (obs.activatedSeq <= activations) found.add(obs);
|
|
1600
|
+
}
|
|
1601
|
+
return [...found];
|
|
1350
1602
|
}
|
|
1351
|
-
/**
|
|
1352
|
-
|
|
1353
|
-
return this.
|
|
1603
|
+
/** The function has a match hook (`onObserverMatch`) now. */
|
|
1604
|
+
hasMatchHook() {
|
|
1605
|
+
return this.host.hooks(this.functionId).match !== void 0;
|
|
1354
1606
|
}
|
|
1355
|
-
|
|
1356
|
-
|
|
1607
|
+
/**
|
|
1608
|
+
* The active observers whose `on` accepts a call that succeeded (`ok`) or
|
|
1609
|
+
* failed and whose filters match `doc`, in the order of `compiled`. Matched
|
|
1610
|
+
* through the index of their filters' equality conditions when it narrows
|
|
1611
|
+
* them (`FilterIndex.narrows`): the call evaluates the filters of the
|
|
1612
|
+
* observers the index does not rule out. Otherwise each observer of
|
|
1613
|
+
* `compiled` is evaluated in order, which costs less and yields the same
|
|
1614
|
+
* observers in the same order.
|
|
1615
|
+
*/
|
|
1616
|
+
selectActive(doc, ok) {
|
|
1617
|
+
const index = this.filterIndex;
|
|
1618
|
+
if (!index.narrows) return this.compiled.filter((obs) => onAccepts(obs.on, ok) && obs.filter.matches(doc));
|
|
1619
|
+
return index.matches(doc, (obs) => onAccepts(obs.on, ok));
|
|
1357
1620
|
}
|
|
1358
1621
|
observers() {
|
|
1359
1622
|
return [...this.compiled];
|
|
@@ -1366,9 +1629,10 @@ var FunctionObservers = class {
|
|
|
1366
1629
|
this.localDispatch = msg.local_dispatch && this.localDispatchOption && this.hasHandler;
|
|
1367
1630
|
this.namespace = msg.namespace;
|
|
1368
1631
|
this.revision = msg.revision;
|
|
1632
|
+
const releases = this.releases;
|
|
1369
1633
|
this.enqueue(async () => {
|
|
1370
1634
|
try {
|
|
1371
|
-
await this.applySet(msg.observers, msg.revision, msg.namespace);
|
|
1635
|
+
if (this.releases === releases) await this.applySet(msg.observers, msg.revision, msg.namespace);
|
|
1372
1636
|
} finally {
|
|
1373
1637
|
this.confirmedEpoch = epoch;
|
|
1374
1638
|
this.host.reporter.flush();
|
|
@@ -1378,8 +1642,12 @@ var FunctionObservers = class {
|
|
|
1378
1642
|
onObserverAdded(msg) {
|
|
1379
1643
|
if (this.disposed || msg.revision <= this.revision) return;
|
|
1380
1644
|
this.revision = msg.revision;
|
|
1645
|
+
const releases = this.releases;
|
|
1381
1646
|
this.enqueue(async () => {
|
|
1382
|
-
if (this.
|
|
1647
|
+
if (this.disposed || this.releases !== releases || this.releasedEpoch !== void 0) return;
|
|
1648
|
+
const held = this.known.get(msg.observer.id);
|
|
1649
|
+
if (held && this.reack(held, msg.observer, msg.revision, msg.namespace, false)) return;
|
|
1650
|
+
if (held) await this.remove(held.id);
|
|
1383
1651
|
await this.add(msg.observer, msg.revision, msg.namespace);
|
|
1384
1652
|
});
|
|
1385
1653
|
}
|
|
@@ -1389,9 +1657,10 @@ var FunctionObservers = class {
|
|
|
1389
1657
|
this.enqueue(() => this.remove(msg.id));
|
|
1390
1658
|
}
|
|
1391
1659
|
/**
|
|
1392
|
-
*
|
|
1393
|
-
*
|
|
1394
|
-
* confirmed, and would starve
|
|
1660
|
+
* The engine refused the function (`registrationrejected`), or it no
|
|
1661
|
+
* longer holds it here: no local dispatch, no observers, and its held
|
|
1662
|
+
* reports are discarded (they could never be confirmed, and would starve
|
|
1663
|
+
* other functions of buffer).
|
|
1395
1664
|
*/
|
|
1396
1665
|
onRegistrationRejected(epoch) {
|
|
1397
1666
|
this.confirmed = false;
|
|
@@ -1408,30 +1677,134 @@ var FunctionObservers = class {
|
|
|
1408
1677
|
this.onRegistrationRejected(-1);
|
|
1409
1678
|
}
|
|
1410
1679
|
/**
|
|
1680
|
+
* An `onObserverAdded` was set at `level` (the worker's, or this
|
|
1681
|
+
* function's): the active observers that were set up without one there are
|
|
1682
|
+
* caught up. It runs for each of them, in the hook queue; a throw
|
|
1683
|
+
* late-rejects that observer. One warning names the function and how many
|
|
1684
|
+
* observers were active without the hook.
|
|
1685
|
+
*/
|
|
1686
|
+
catchUp(level) {
|
|
1687
|
+
if (this.disposed) return;
|
|
1688
|
+
this.enqueue(async () => {
|
|
1689
|
+
const behind = this.compiled.filter((obs) => obs.levels[level] === "bare");
|
|
1690
|
+
if (behind.length === 0) return;
|
|
1691
|
+
this.host.logWarn(`onObserverAdded was set for ${this.functionId} while ${behind.length} observer(s) were active without it; it runs for each of them now`);
|
|
1692
|
+
for (const obs of behind) {
|
|
1693
|
+
const hook = this.addedHook(level);
|
|
1694
|
+
if (!hook) return;
|
|
1695
|
+
if (!obs.active || obs.levels[level] !== "bare") continue;
|
|
1696
|
+
const outcome = await this.runHook(() => hook(obs));
|
|
1697
|
+
if (outcome.ok) {
|
|
1698
|
+
obs.levels[level] = "hooked";
|
|
1699
|
+
continue;
|
|
1700
|
+
}
|
|
1701
|
+
obs.levels[level] = "none";
|
|
1702
|
+
if (outcome.timedOut) this.undoLate(outcome.late, obs, level);
|
|
1703
|
+
this.reject(obs, outcome.code, outcome.message);
|
|
1704
|
+
}
|
|
1705
|
+
});
|
|
1706
|
+
}
|
|
1707
|
+
/**
|
|
1708
|
+
* The function's match hook was set or removed (decision 45). Matching by
|
|
1709
|
+
* keys rebuilds the index from the active observers; an observer whose keys
|
|
1710
|
+
* cannot be computed is late-rejected.
|
|
1711
|
+
*/
|
|
1712
|
+
matchChanged() {
|
|
1713
|
+
const keys = matchKeysOf(this.host.hooks(this.functionId).match);
|
|
1714
|
+
if (keys === this.matchKeys) return;
|
|
1715
|
+
this.matchKeys = keys;
|
|
1716
|
+
this.index = keys ? /* @__PURE__ */ new Map() : void 0;
|
|
1717
|
+
for (const obs of this.known.values()) obs.keys = void 0;
|
|
1718
|
+
for (const obs of this.compiled) {
|
|
1719
|
+
const failure = this.prepareKeys(obs);
|
|
1720
|
+
if (failure) this.reject(obs, failure.code, failure.message);
|
|
1721
|
+
else this.file(obs);
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
/** The keys of a call; a key function that throws gives none. */
|
|
1725
|
+
callKeys(keys, call) {
|
|
1726
|
+
try {
|
|
1727
|
+
return keyList(keys.call(call));
|
|
1728
|
+
} catch (error) {
|
|
1729
|
+
this.matchFailed(error);
|
|
1730
|
+
return [];
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
matchFailed(error) {
|
|
1734
|
+
if (this.matchFailureLogged) return;
|
|
1735
|
+
this.matchFailureLogged = true;
|
|
1736
|
+
this.host.logError(`onObserverMatch of ${this.functionId} threw; the call matches no observer`, error);
|
|
1737
|
+
}
|
|
1738
|
+
/**
|
|
1411
1739
|
* Stops delivery at once, then removes every observer through the hook
|
|
1412
1740
|
* queue, after the adds queued before it (which undo themselves: `add`).
|
|
1413
1741
|
*/
|
|
1414
1742
|
dropAll() {
|
|
1415
|
-
for (const obs of this.compiled) obs
|
|
1416
|
-
this.compiled = [];
|
|
1743
|
+
for (const obs of this.compiled) this.deactivate(obs);
|
|
1417
1744
|
this.enqueue(async () => {
|
|
1418
1745
|
for (const id of [...this.known.keys()]) await this.remove(id);
|
|
1419
1746
|
});
|
|
1420
1747
|
}
|
|
1421
1748
|
enqueue(task) {
|
|
1422
1749
|
this.queue = this.queue.then(task).catch((error) => {
|
|
1423
|
-
this.host.logError(`
|
|
1750
|
+
this.host.logError(`Observer hook failed for ${this.functionId}`, error);
|
|
1424
1751
|
});
|
|
1425
1752
|
}
|
|
1426
|
-
|
|
1753
|
+
addedHook(level) {
|
|
1754
|
+
const hooks = this.host.hooks(this.functionId);
|
|
1755
|
+
return level === "worker" ? hooks.workerAdded : hooks.added;
|
|
1756
|
+
}
|
|
1757
|
+
removedHook(level) {
|
|
1758
|
+
const hooks = this.host.hooks(this.functionId);
|
|
1759
|
+
return level === "worker" ? hooks.workerRemoved : hooks.removed;
|
|
1760
|
+
}
|
|
1761
|
+
activate(obs) {
|
|
1427
1762
|
if (obs.active) return;
|
|
1428
1763
|
obs.active = true;
|
|
1764
|
+
obs.activatedSeq = ++this.activations;
|
|
1429
1765
|
this.compiled = [...this.compiled, obs];
|
|
1766
|
+
this.filterIndex.insert(obs, obs.filter, obs.activatedSeq);
|
|
1767
|
+
this.file(obs);
|
|
1430
1768
|
}
|
|
1431
1769
|
deactivate(obs) {
|
|
1432
1770
|
if (!obs.active) return;
|
|
1433
1771
|
obs.active = false;
|
|
1434
1772
|
this.compiled = this.compiled.filter((o) => o !== obs);
|
|
1773
|
+
this.filterIndex.remove(obs);
|
|
1774
|
+
this.unfile(obs);
|
|
1775
|
+
}
|
|
1776
|
+
/** Computes the keys `obs` is filed under, once, when the function is matched by keys. */
|
|
1777
|
+
prepareKeys(obs) {
|
|
1778
|
+
const keys = this.matchKeys;
|
|
1779
|
+
if (!keys || obs.keys) return void 0;
|
|
1780
|
+
try {
|
|
1781
|
+
obs.keys = [...new Set(keyList(keys.observer(obs)))];
|
|
1782
|
+
return;
|
|
1783
|
+
} catch (error) {
|
|
1784
|
+
return {
|
|
1785
|
+
code: "OBSERVE_REJECTED",
|
|
1786
|
+
message: `the keys of observer ${obs.id} of ${this.functionId} could not be computed: ${error instanceof Error ? error.message : String(error)}`
|
|
1787
|
+
};
|
|
1788
|
+
}
|
|
1789
|
+
}
|
|
1790
|
+
file(obs) {
|
|
1791
|
+
const index = this.index;
|
|
1792
|
+
if (!index || !obs.keys) return;
|
|
1793
|
+
for (const key of obs.keys) {
|
|
1794
|
+
const filed = index.get(key);
|
|
1795
|
+
if (filed) filed.add(obs);
|
|
1796
|
+
else index.set(key, new Set([obs]));
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
unfile(obs) {
|
|
1800
|
+
const index = this.index;
|
|
1801
|
+
if (!index || !obs.keys) return;
|
|
1802
|
+
for (const key of obs.keys) {
|
|
1803
|
+
const filed = index.get(key);
|
|
1804
|
+
if (!filed) continue;
|
|
1805
|
+
filed.delete(obs);
|
|
1806
|
+
if (filed.size === 0) index.delete(key);
|
|
1807
|
+
}
|
|
1435
1808
|
}
|
|
1436
1809
|
ack(info, revision, namespace, error) {
|
|
1437
1810
|
this.host.sendAck({
|
|
@@ -1442,55 +1815,82 @@ var FunctionObservers = class {
|
|
|
1442
1815
|
...error ? { error } : {}
|
|
1443
1816
|
});
|
|
1444
1817
|
}
|
|
1445
|
-
/**
|
|
1818
|
+
/**
|
|
1819
|
+
* Diffs the engine's full set against what this SDK holds: the ones it no
|
|
1820
|
+
* longer lists are removed, the ones it holds are acked again
|
|
1821
|
+
* ({@link FunctionObservers.reack}), and the others are added.
|
|
1822
|
+
*/
|
|
1446
1823
|
async applySet(list, revision, namespace) {
|
|
1447
1824
|
const incoming = new Set(list.map((o) => o.id));
|
|
1448
1825
|
for (const id of [...this.known.keys()]) if (!incoming.has(id)) await this.remove(id);
|
|
1449
1826
|
for (const info of list) {
|
|
1450
|
-
const
|
|
1451
|
-
if (
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
await this.add(info, revision, namespace);
|
|
1455
|
-
}
|
|
1827
|
+
const held = this.known.get(info.id);
|
|
1828
|
+
if (held && this.reack(held, info, revision, namespace, true)) continue;
|
|
1829
|
+
if (held) await this.remove(info.id);
|
|
1830
|
+
await this.add(info, revision, namespace);
|
|
1456
1831
|
}
|
|
1457
1832
|
}
|
|
1458
1833
|
/**
|
|
1459
|
-
*
|
|
1460
|
-
*
|
|
1834
|
+
* Acks again, at `revision` and without running any hook, an observer this
|
|
1835
|
+
* SDK holds that the engine announced again (decision 44): one with the
|
|
1836
|
+
* same args, served from now on with the filters, target, capture and `on`
|
|
1837
|
+
* it was announced with (its keys computed again when they changed), or,
|
|
1838
|
+
* when `listed` by `functionregistered`, one rejected late, whose rejection
|
|
1839
|
+
* is sent again. `false` for an observer to add as a new one after removing
|
|
1840
|
+
* the one held: other args, a late rejection announced by `observeradded`,
|
|
1841
|
+
* or a view this SDK cannot serve (filters that do not compile, keys that
|
|
1842
|
+
* throw).
|
|
1461
1843
|
*/
|
|
1462
|
-
|
|
1463
|
-
if (
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1844
|
+
reack(held, info, revision, namespace, listed) {
|
|
1845
|
+
if (held.rejection) {
|
|
1846
|
+
if (!listed) return false;
|
|
1847
|
+
held.revision = revision;
|
|
1848
|
+
this.ack(info, revision, namespace, held.rejection);
|
|
1849
|
+
return true;
|
|
1467
1850
|
}
|
|
1468
|
-
|
|
1469
|
-
if (!
|
|
1470
|
-
filter =
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1851
|
+
if (!sameJson(held.args, info.args)) return false;
|
|
1852
|
+
if (!sameView(held, info)) {
|
|
1853
|
+
let filter = held.filter;
|
|
1854
|
+
if (!sameJson(held.filters, info.filters)) try {
|
|
1855
|
+
filter = compileFilter(info.filters, { trusted: true });
|
|
1856
|
+
} catch {
|
|
1857
|
+
return false;
|
|
1858
|
+
}
|
|
1859
|
+
const keys = this.viewKeys(held, info, filter);
|
|
1860
|
+
if (keys === null) return false;
|
|
1861
|
+
if (held.active) this.unfile(held);
|
|
1862
|
+
held.update(info, filter);
|
|
1863
|
+
if (keys !== void 0) held.keys = keys;
|
|
1864
|
+
if (held.active) {
|
|
1865
|
+
this.file(held);
|
|
1866
|
+
this.filterIndex.insert(held, held.filter, held.activatedSeq);
|
|
1867
|
+
}
|
|
1479
1868
|
}
|
|
1480
|
-
|
|
1481
|
-
obs.revision = revision;
|
|
1482
|
-
this.activate(obs);
|
|
1869
|
+
held.revision = revision;
|
|
1483
1870
|
this.ack(info, revision, namespace);
|
|
1871
|
+
return true;
|
|
1484
1872
|
}
|
|
1485
|
-
/**
|
|
1873
|
+
/**
|
|
1874
|
+
* The keys `held` is filed under once it takes the view `info` (with
|
|
1875
|
+
* `filter`), on a function matched by keys: computed on a copy, so a key
|
|
1876
|
+
* function that throws (`null`) leaves `held` as it was. `undefined` when
|
|
1877
|
+
* the function is not matched by keys.
|
|
1878
|
+
*/
|
|
1879
|
+
viewKeys(held, info, filter) {
|
|
1880
|
+
const keys = this.matchKeys;
|
|
1881
|
+
if (!keys) return void 0;
|
|
1882
|
+
const view = Object.assign(Object.create(Object.getPrototypeOf(held)), held);
|
|
1883
|
+
view.update(info, filter);
|
|
1884
|
+
try {
|
|
1885
|
+
return [...new Set(keyList(keys.observer(view)))];
|
|
1886
|
+
} catch {
|
|
1887
|
+
return null;
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
/** handleAdded (§4.3): the hooks of both levels, then the active set, then the ack. */
|
|
1486
1891
|
async add(info, revision, namespace) {
|
|
1487
1892
|
if (this.disposed || this.releasedEpoch !== void 0) return;
|
|
1488
1893
|
const releases = this.releases;
|
|
1489
|
-
const existing = this.known.get(info.id);
|
|
1490
|
-
if (existing) {
|
|
1491
|
-
this.keep(existing, info, revision, namespace);
|
|
1492
|
-
return;
|
|
1493
|
-
}
|
|
1494
1894
|
let filter;
|
|
1495
1895
|
try {
|
|
1496
1896
|
filter = compileFilter(info.filters, { trusted: true });
|
|
@@ -1502,43 +1902,91 @@ var FunctionObservers = class {
|
|
|
1502
1902
|
return;
|
|
1503
1903
|
}
|
|
1504
1904
|
const obs = new ObserverImpl(this, info, filter, revision);
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
code: outcome.code,
|
|
1513
|
-
message: outcome.message
|
|
1514
|
-
});
|
|
1515
|
-
if (outcome.timedOut) outcome.late.then(() => this.enqueue(() => this.callRemoved(obs)), () => void 0);
|
|
1516
|
-
return;
|
|
1517
|
-
}
|
|
1905
|
+
obs.adding = true;
|
|
1906
|
+
const failure = await this.setUp(obs);
|
|
1907
|
+
obs.adding = false;
|
|
1908
|
+
if (failure) {
|
|
1909
|
+
this.ack(info, revision, namespace, failure);
|
|
1910
|
+
obs.settleAcceptance(failure);
|
|
1911
|
+
return;
|
|
1518
1912
|
}
|
|
1519
1913
|
if (this.disposed || this.releases !== releases) {
|
|
1520
|
-
await this.
|
|
1914
|
+
await this.unwind(obs);
|
|
1915
|
+
obs.settleAcceptance({
|
|
1916
|
+
code: "OBSERVER_NOT_ACTIVE",
|
|
1917
|
+
message: `${this.functionId} was released before observer ${obs.id} was accepted`
|
|
1918
|
+
});
|
|
1521
1919
|
return;
|
|
1522
1920
|
}
|
|
1523
1921
|
this.known.set(obs.id, obs);
|
|
1524
|
-
|
|
1525
|
-
|
|
1922
|
+
const rejection = obs.rejection ?? this.prepareKeys(obs);
|
|
1923
|
+
if (rejection) {
|
|
1924
|
+
obs.rejection = rejection;
|
|
1925
|
+
this.ack(info, revision, namespace, rejection);
|
|
1926
|
+
obs.settleAcceptance(rejection);
|
|
1927
|
+
await this.unwind(obs);
|
|
1526
1928
|
return;
|
|
1527
1929
|
}
|
|
1528
1930
|
this.activate(obs);
|
|
1529
1931
|
this.ack(info, revision, namespace);
|
|
1932
|
+
obs.settleAcceptance("accepted");
|
|
1933
|
+
}
|
|
1934
|
+
/**
|
|
1935
|
+
* Runs `onObserverAdded` of the worker, then of the function. When one
|
|
1936
|
+
* fails, the levels whose `onObserverAdded` resolved are torn down, and the
|
|
1937
|
+
* rejection is returned.
|
|
1938
|
+
*/
|
|
1939
|
+
async setUp(obs) {
|
|
1940
|
+
for (const level of ["worker", "fn"]) {
|
|
1941
|
+
const hook = this.addedHook(level);
|
|
1942
|
+
if (!hook) {
|
|
1943
|
+
obs.levels[level] = "bare";
|
|
1944
|
+
continue;
|
|
1945
|
+
}
|
|
1946
|
+
const outcome = await this.runHook(() => hook(obs));
|
|
1947
|
+
if (!outcome.ok) {
|
|
1948
|
+
if (outcome.timedOut) this.undoLate(outcome.late, obs, level);
|
|
1949
|
+
await this.unwind(obs);
|
|
1950
|
+
return {
|
|
1951
|
+
code: outcome.code,
|
|
1952
|
+
message: outcome.message
|
|
1953
|
+
};
|
|
1954
|
+
}
|
|
1955
|
+
obs.levels[level] = "hooked";
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
/**
|
|
1959
|
+
* Undoes the setup of an observer that is not accepted: `onObserverRemoved`
|
|
1960
|
+
* runs only at the levels whose `onObserverAdded` resolved (§4.3), never at
|
|
1961
|
+
* a level set up without one.
|
|
1962
|
+
*/
|
|
1963
|
+
async unwind(obs) {
|
|
1964
|
+
for (const level of ["worker", "fn"]) if (obs.levels[level] === "bare") obs.levels[level] = "none";
|
|
1965
|
+
await this.tearDown(obs);
|
|
1966
|
+
}
|
|
1967
|
+
/** Runs `onObserverRemoved` of the function, then of the worker, for each level set up, once. */
|
|
1968
|
+
async tearDown(obs) {
|
|
1969
|
+
for (const level of ["fn", "worker"]) {
|
|
1970
|
+
if (obs.levels[level] === "none") continue;
|
|
1971
|
+
obs.levels[level] = "none";
|
|
1972
|
+
await this.runRemoved(obs, level);
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
/** A timed-out `onObserverAdded` that resolves later is undone by its level's `onObserverRemoved`. */
|
|
1976
|
+
undoLate(late, obs, level) {
|
|
1977
|
+
late.then(() => this.enqueue(() => this.runRemoved(obs, level)), () => void 0);
|
|
1530
1978
|
}
|
|
1531
1979
|
async remove(id) {
|
|
1532
1980
|
const obs = this.known.get(id);
|
|
1533
1981
|
if (!obs) return;
|
|
1534
1982
|
this.known.delete(id);
|
|
1535
1983
|
this.deactivate(obs);
|
|
1536
|
-
await this.
|
|
1984
|
+
await this.tearDown(obs);
|
|
1537
1985
|
}
|
|
1538
|
-
async
|
|
1539
|
-
const
|
|
1540
|
-
if (!
|
|
1541
|
-
const outcome = await this.runHook(() =>
|
|
1986
|
+
async runRemoved(obs, level) {
|
|
1987
|
+
const hook = this.removedHook(level);
|
|
1988
|
+
if (!hook) return;
|
|
1989
|
+
const outcome = await this.runHook(() => hook(obs));
|
|
1542
1990
|
if (!outcome.ok) this.host.logError(`onObserverRemoved failed for observer ${obs.id} of ${this.functionId}: ${outcome.message}`);
|
|
1543
1991
|
}
|
|
1544
1992
|
async runHook(fn) {
|
|
@@ -1553,7 +2001,7 @@ var FunctionObservers = class {
|
|
|
1553
2001
|
if (await Promise.race([run.then(() => "done"), timeout]) === "timeout") return {
|
|
1554
2002
|
ok: false,
|
|
1555
2003
|
code: "OWNER_TIMEOUT",
|
|
1556
|
-
message: `
|
|
2004
|
+
message: `observer hook of ${this.functionId} still running after ${timeoutMs}ms`,
|
|
1557
2005
|
timedOut: true,
|
|
1558
2006
|
late: run
|
|
1559
2007
|
};
|
|
@@ -1569,103 +2017,7 @@ var FunctionObservers = class {
|
|
|
1569
2017
|
if (timer) clearTimeout(timer);
|
|
1570
2018
|
}
|
|
1571
2019
|
}
|
|
1572
|
-
|
|
1573
|
-
if (this.delivery !== "owner") throw new InvocationError({
|
|
1574
|
-
code: "NOT_OWNER_DELIVERED",
|
|
1575
|
-
message: `obs.${what}() needs an owner-delivered function; ${this.functionId} is auto-delivered (observe.delivery)`,
|
|
1576
|
-
function_id: this.functionId
|
|
1577
|
-
});
|
|
1578
|
-
}
|
|
1579
|
-
isActive(obs) {
|
|
1580
|
-
return obs.active && this.known.get(obs.id) === obs;
|
|
1581
|
-
}
|
|
1582
|
-
/**
|
|
1583
|
-
* The caller an event carries (sdk.md §1): inside the function's own
|
|
1584
|
-
* handler, that invocation's caller; inside another handler, that handler;
|
|
1585
|
-
* outside any handler, this worker only.
|
|
1586
|
-
*/
|
|
1587
|
-
eventCaller(cur) {
|
|
1588
|
-
if (cur && cur.function_id === this.functionId) return {
|
|
1589
|
-
caller: cur.caller,
|
|
1590
|
-
own: true
|
|
1591
|
-
};
|
|
1592
|
-
const { worker_id, worker_name } = this.host.identity();
|
|
1593
|
-
const caller = worker_id !== void 0 ? {
|
|
1594
|
-
worker_id,
|
|
1595
|
-
worker_name
|
|
1596
|
-
} : { worker_name };
|
|
1597
|
-
if (cur) {
|
|
1598
|
-
caller.function_id = cur.function_id;
|
|
1599
|
-
caller.invocation_id = cur.invocation_id;
|
|
1600
|
-
const parent = stripCaller(cur.caller);
|
|
1601
|
-
if (parent && Object.keys(parent).length > 0) caller.parent = parent;
|
|
1602
|
-
}
|
|
1603
|
-
return {
|
|
1604
|
-
caller,
|
|
1605
|
-
own: false
|
|
1606
|
-
};
|
|
1607
|
-
}
|
|
1608
|
-
/**
|
|
1609
|
-
* Hands `event` to one observer. `false`, and nothing sent, when its
|
|
1610
|
-
* filters reject the event or it is no longer active (removed or rejected
|
|
1611
|
-
* meanwhile): an owner's fan-out loop must not stop for one observer.
|
|
1612
|
-
*/
|
|
1613
|
-
emit(obs, event) {
|
|
1614
|
-
this.requireOwnerDelivery("emit");
|
|
1615
|
-
if (!this.isActive(obs)) return false;
|
|
1616
|
-
const cur = callContext();
|
|
1617
|
-
const { caller, own } = this.eventCaller(cur);
|
|
1618
|
-
const metadata = cur?.metadata;
|
|
1619
|
-
if (!obs.filter.matches({
|
|
1620
|
-
input: event,
|
|
1621
|
-
caller,
|
|
1622
|
-
metadata
|
|
1623
|
-
})) return false;
|
|
1624
|
-
const values = { input: event };
|
|
1625
|
-
if (caller !== void 0) values.caller = caller;
|
|
1626
|
-
if (metadata !== void 0) values.metadata = metadata;
|
|
1627
|
-
const trace = cur ? {
|
|
1628
|
-
traceparent: cur.traceparent,
|
|
1629
|
-
baggage: cur.baggage
|
|
1630
|
-
} : this.host.traceContext();
|
|
1631
|
-
this.host.reporter.pushEmit({
|
|
1632
|
-
function_id: this.functionId,
|
|
1633
|
-
namespace: this.namespace,
|
|
1634
|
-
invocation_id: own && cur ? cur.invocation_id : randomUUID(),
|
|
1635
|
-
status: "success",
|
|
1636
|
-
values,
|
|
1637
|
-
captures: obs.capture,
|
|
1638
|
-
started_at_ms: Date.now(),
|
|
1639
|
-
duration_ms: 0,
|
|
1640
|
-
observe_depth: cur ? cur.observe_depth : callDepth(),
|
|
1641
|
-
traceparent: trace.traceparent,
|
|
1642
|
-
baggage: trace.baggage,
|
|
1643
|
-
observer_id: obs.id,
|
|
1644
|
-
event,
|
|
1645
|
-
context: cur
|
|
1646
|
-
});
|
|
1647
|
-
return true;
|
|
1648
|
-
}
|
|
1649
|
-
async call(obs, payload, timeoutMs) {
|
|
1650
|
-
this.requireOwnerDelivery("call");
|
|
1651
|
-
if (!this.isActive(obs)) throw new InvocationError({
|
|
1652
|
-
code: "OBSERVER_NOT_ACTIVE",
|
|
1653
|
-
message: `observer ${obs.id} of ${this.functionId} is not active`,
|
|
1654
|
-
function_id: this.functionId
|
|
1655
|
-
});
|
|
1656
|
-
const cur = callContext();
|
|
1657
|
-
const { caller } = this.eventCaller(cur);
|
|
1658
|
-
if (!obs.filter.matches({
|
|
1659
|
-
input: payload,
|
|
1660
|
-
caller,
|
|
1661
|
-
metadata: cur?.metadata
|
|
1662
|
-
})) throw new InvocationError({
|
|
1663
|
-
code: "FILTERS_NOT_MATCHED",
|
|
1664
|
-
message: `the filters of observer ${obs.id} reject this payload`,
|
|
1665
|
-
function_id: this.functionId
|
|
1666
|
-
});
|
|
1667
|
-
return this.host.callTarget(obs.target, obs.id, payload, timeoutMs);
|
|
1668
|
-
}
|
|
2020
|
+
/** @internal Late rejection (`obs.reject`, a failed catch-up): inactive at once, then torn down. */
|
|
1669
2021
|
reject(obs, code, message) {
|
|
1670
2022
|
if (obs.adding) {
|
|
1671
2023
|
obs.rejection = {
|
|
@@ -1674,7 +2026,7 @@ var FunctionObservers = class {
|
|
|
1674
2026
|
};
|
|
1675
2027
|
return;
|
|
1676
2028
|
}
|
|
1677
|
-
if (this.known.get(obs.id) !== obs) return;
|
|
2029
|
+
if (this.known.get(obs.id) !== obs || obs.rejection) return;
|
|
1678
2030
|
obs.rejection = {
|
|
1679
2031
|
code,
|
|
1680
2032
|
message
|
|
@@ -1690,52 +2042,343 @@ var FunctionObservers = class {
|
|
|
1690
2042
|
message
|
|
1691
2043
|
}
|
|
1692
2044
|
});
|
|
2045
|
+
this.enqueue(() => this.tearDown(obs));
|
|
2046
|
+
}
|
|
2047
|
+
};
|
|
2048
|
+
/**
|
|
2049
|
+
* The delivery of one call (v2 §4.4–§4.6, decisions 20, 36, 38, 45, 55): the
|
|
2050
|
+
* observers are matched (`onObserverMatch`), then the function's
|
|
2051
|
+
* `onObserverDeliver` delivers the call itself, or iii delivers it to the
|
|
2052
|
+
* matched observers whose `on` and filters accept it. For a local call the
|
|
2053
|
+
* host evaluates `on` and filters and reports the observers delivered in
|
|
2054
|
+
* one report item. For a routed call the engine evaluates them: the answer
|
|
2055
|
+
* carries the observers the match hook matched (`matched`), or says that
|
|
2056
|
+
* the deliver hook delivered the call (`delivered`), or neither for a
|
|
2057
|
+
* function with no match hook and no deliver hook.
|
|
2058
|
+
*/
|
|
2059
|
+
var Delivery = class {
|
|
2060
|
+
constructor(owner, init) {
|
|
2061
|
+
this.owner = owner;
|
|
2062
|
+
this.init = init;
|
|
2063
|
+
this.delivered = false;
|
|
2064
|
+
}
|
|
2065
|
+
/** Resolves to what the caller gets back, or rejects with what it gets thrown. */
|
|
2066
|
+
async run(deliver) {
|
|
2067
|
+
const { call, snapshot, activations, thrown, routed } = this.init;
|
|
2068
|
+
const matched = this.owner.matching(call, snapshot, activations);
|
|
2069
|
+
if (deliver !== void 0) {
|
|
2070
|
+
if (routed) this.delivered = true;
|
|
2071
|
+
return deliver(call, matched);
|
|
2072
|
+
}
|
|
2073
|
+
if (routed) {
|
|
2074
|
+
if (this.owner.hasMatchHook()) this.matched = matched.map((obs) => obs.id);
|
|
2075
|
+
} else {
|
|
2076
|
+
const selected = this.select(call, matched);
|
|
2077
|
+
if (selected.length > 0) this.owner.reporter.push(this.item(call, selected));
|
|
2078
|
+
}
|
|
2079
|
+
if (call.status === "error") throw thrown;
|
|
2080
|
+
return call.output;
|
|
1693
2081
|
}
|
|
1694
2082
|
/**
|
|
1695
|
-
*
|
|
1696
|
-
*
|
|
1697
|
-
* observer matches. Never throws.
|
|
2083
|
+
* The error body a call answers with for `error`: the handler's own, or
|
|
2084
|
+
* what the deliver hook threw ({@link deliverErrorBody}).
|
|
1698
2085
|
*/
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
2086
|
+
errorBody(error) {
|
|
2087
|
+
const { call, thrown } = this.init;
|
|
2088
|
+
return error === thrown && call.error ? call.error : deliverErrorBody(error);
|
|
2089
|
+
}
|
|
2090
|
+
/**
|
|
2091
|
+
* The matched observers whose `on` and filters accept `call`, in the order
|
|
2092
|
+
* of `matched`. Without a match hook `matched` is the call's snapshot; while
|
|
2093
|
+
* it is also the active set (no observer joined or left since the call
|
|
2094
|
+
* started), {@link FunctionObservers.selectActive} selects them, through
|
|
2095
|
+
* the index of the filters' equality conditions when it narrows them.
|
|
2096
|
+
* Otherwise each matched observer's filters are evaluated.
|
|
2097
|
+
*/
|
|
2098
|
+
select(call, matched) {
|
|
2099
|
+
const ok = call.status !== "error";
|
|
2100
|
+
const doc = filterDoc(call);
|
|
2101
|
+
if (matched === this.init.snapshot && matched === this.owner.compiled) return this.owner.selectActive(doc, ok);
|
|
2102
|
+
return matched.filter((obs) => onAccepts(obs.on, ok) && obs.filter.matches(doc));
|
|
2103
|
+
}
|
|
2104
|
+
/** The report item of a local call delivered to `selected`. */
|
|
2105
|
+
item(call, selected) {
|
|
2106
|
+
const init = this.init;
|
|
1709
2107
|
const captures = /* @__PURE__ */ new Set();
|
|
1710
|
-
for (const obs of
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
if (
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
namespace: this.namespace,
|
|
1725
|
-
invocation_id: init.invocation_id,
|
|
1726
|
-
matched,
|
|
1727
|
-
status: init.ok ? "success" : "error",
|
|
2108
|
+
for (const obs of selected) for (const c of obs.capture) captures.add(c);
|
|
2109
|
+
const ok = call.status !== "error";
|
|
2110
|
+
const values = { input: call.input };
|
|
2111
|
+
if (ok) values.output = call.output;
|
|
2112
|
+
else values.error = call.error;
|
|
2113
|
+
const caller = reportCaller(call.caller);
|
|
2114
|
+
if (caller !== void 0) values.caller = caller;
|
|
2115
|
+
if (call.metadata !== void 0) values.metadata = call.metadata;
|
|
2116
|
+
return {
|
|
2117
|
+
function_id: this.owner.functionId,
|
|
2118
|
+
namespace: this.owner.namespace,
|
|
2119
|
+
invocation_id: call.invocation_id,
|
|
2120
|
+
matched: selected.map((obs) => obs.id),
|
|
2121
|
+
status: ok ? "success" : "error",
|
|
1728
2122
|
values,
|
|
1729
2123
|
captures,
|
|
2124
|
+
output_is_input: ok && call.output === call.input && this.owner.observeV2(),
|
|
1730
2125
|
started_at_ms: init.started_at_ms,
|
|
1731
2126
|
duration_ms: init.duration_ms,
|
|
1732
2127
|
observe_depth: init.observe_depth,
|
|
1733
2128
|
traceparent: init.traceparent,
|
|
1734
2129
|
baggage: init.baggage
|
|
1735
|
-
}
|
|
2130
|
+
};
|
|
1736
2131
|
}
|
|
1737
2132
|
};
|
|
1738
2133
|
|
|
2134
|
+
//#endregion
|
|
2135
|
+
//#region src/observe-wire.ts
|
|
2136
|
+
/** CONTRACT D1: what an absent `capture` means. */
|
|
2137
|
+
const DEFAULT_CAPTURE = [
|
|
2138
|
+
"input",
|
|
2139
|
+
"output",
|
|
2140
|
+
"caller"
|
|
2141
|
+
];
|
|
2142
|
+
function isRecord(v) {
|
|
2143
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
2144
|
+
}
|
|
2145
|
+
function str(v) {
|
|
2146
|
+
return typeof v === "string" ? v : void 0;
|
|
2147
|
+
}
|
|
2148
|
+
function num(v) {
|
|
2149
|
+
return typeof v === "number" ? v : void 0;
|
|
2150
|
+
}
|
|
2151
|
+
function errorBody(v) {
|
|
2152
|
+
if (!isRecord(v)) return void 0;
|
|
2153
|
+
const body = {
|
|
2154
|
+
code: String(v.code ?? ""),
|
|
2155
|
+
message: String(v.message ?? "")
|
|
2156
|
+
};
|
|
2157
|
+
if (typeof v.stacktrace === "string") body.stacktrace = v.stacktrace;
|
|
2158
|
+
return body;
|
|
2159
|
+
}
|
|
2160
|
+
/** Copies the wire caller, dropping `null`s and a `parent` inside `parent`. */
|
|
2161
|
+
function decodeCaller(v, depth = 0) {
|
|
2162
|
+
if (!isRecord(v)) return void 0;
|
|
2163
|
+
const caller = {};
|
|
2164
|
+
for (const key of [
|
|
2165
|
+
"worker_id",
|
|
2166
|
+
"worker_name",
|
|
2167
|
+
"function_id",
|
|
2168
|
+
"invocation_id"
|
|
2169
|
+
]) {
|
|
2170
|
+
const value = str(v[key]);
|
|
2171
|
+
if (value !== void 0) caller[key] = value;
|
|
2172
|
+
}
|
|
2173
|
+
if (depth === 0) {
|
|
2174
|
+
const parent = decodeCaller(v.parent, 1);
|
|
2175
|
+
if (parent) caller.parent = parent;
|
|
2176
|
+
}
|
|
2177
|
+
return caller;
|
|
2178
|
+
}
|
|
2179
|
+
function decodeActivation(v) {
|
|
2180
|
+
if (!isRecord(v) || typeof v.observer_id !== "string") return void 0;
|
|
2181
|
+
const activation = { observer_id: v.observer_id };
|
|
2182
|
+
if (typeof v.activation_id === "string") activation.activation_id = v.activation_id;
|
|
2183
|
+
return activation;
|
|
2184
|
+
}
|
|
2185
|
+
/** An observer as its host sees it (`observeradded.observer`, `functionregistered.observers[]`). */
|
|
2186
|
+
function decodeObserverInfo(v) {
|
|
2187
|
+
const raw = isRecord(v) ? v : {};
|
|
2188
|
+
return {
|
|
2189
|
+
id: String(raw.id ?? ""),
|
|
2190
|
+
args: isRecord(raw.args) ? raw.args : {},
|
|
2191
|
+
filters: raw.filters === void 0 ? {} : raw.filters,
|
|
2192
|
+
target: String(raw.target ?? ""),
|
|
2193
|
+
capture: Array.isArray(raw.capture) ? raw.capture.filter((c) => typeof c === "string") : [...DEFAULT_CAPTURE],
|
|
2194
|
+
on: str(raw.on) ?? "success"
|
|
2195
|
+
};
|
|
2196
|
+
}
|
|
2197
|
+
function decodeFunctionRegistered(v) {
|
|
2198
|
+
return {
|
|
2199
|
+
id: String(v.id ?? ""),
|
|
2200
|
+
namespace: String(v.namespace ?? ""),
|
|
2201
|
+
revision: num(v.revision) ?? 0,
|
|
2202
|
+
local_dispatch: v.local_dispatch === true,
|
|
2203
|
+
observers: Array.isArray(v.observers) ? v.observers.map(decodeObserverInfo) : []
|
|
2204
|
+
};
|
|
2205
|
+
}
|
|
2206
|
+
function decodeObserverAdded(v) {
|
|
2207
|
+
return {
|
|
2208
|
+
function_id: String(v.function_id ?? ""),
|
|
2209
|
+
namespace: String(v.namespace ?? ""),
|
|
2210
|
+
revision: num(v.revision) ?? 0,
|
|
2211
|
+
observer: decodeObserverInfo(v.observer)
|
|
2212
|
+
};
|
|
2213
|
+
}
|
|
2214
|
+
function decodeObserverRemoved(v) {
|
|
2215
|
+
return {
|
|
2216
|
+
function_id: String(v.function_id ?? ""),
|
|
2217
|
+
namespace: String(v.namespace ?? ""),
|
|
2218
|
+
revision: num(v.revision) ?? 0,
|
|
2219
|
+
id: String(v.id ?? "")
|
|
2220
|
+
};
|
|
2221
|
+
}
|
|
2222
|
+
function decodeObserveResult(v) {
|
|
2223
|
+
const msg = {
|
|
2224
|
+
id: String(v.id ?? ""),
|
|
2225
|
+
state: String(v.state ?? "")
|
|
2226
|
+
};
|
|
2227
|
+
const error = errorBody(v.error);
|
|
2228
|
+
if (error) msg.error = error;
|
|
2229
|
+
if (Array.isArray(v.warnings)) msg.warnings = v.warnings.filter((w) => typeof w === "string");
|
|
2230
|
+
return msg;
|
|
2231
|
+
}
|
|
2232
|
+
function decodeObserverStateChanged(v) {
|
|
2233
|
+
const msg = {
|
|
2234
|
+
id: String(v.id ?? ""),
|
|
2235
|
+
state: String(v.state ?? ""),
|
|
2236
|
+
fires: num(v.fires) ?? 0
|
|
2237
|
+
};
|
|
2238
|
+
const reason = errorBody(v.reason);
|
|
2239
|
+
if (reason) msg.reason = reason;
|
|
2240
|
+
return msg;
|
|
2241
|
+
}
|
|
2242
|
+
function decodeWorkerRegistered(v) {
|
|
2243
|
+
const msg = { worker_id: String(v.worker_id ?? "") };
|
|
2244
|
+
if (typeof v.reattach_token === "string") msg.reattach_token = v.reattach_token;
|
|
2245
|
+
if (Array.isArray(v.features)) msg.features = v.features.filter((f) => typeof f === "string");
|
|
2246
|
+
return msg;
|
|
2247
|
+
}
|
|
2248
|
+
/** The observe fields of an inbound `invokefunction` (`caller`, `observe_depth`, `activation`). */
|
|
2249
|
+
function decodeInvokeFunction(v) {
|
|
2250
|
+
const msg = {
|
|
2251
|
+
function_id: String(v.function_id ?? ""),
|
|
2252
|
+
data: v.data
|
|
2253
|
+
};
|
|
2254
|
+
if (typeof v.invocation_id === "string") msg.invocation_id = v.invocation_id;
|
|
2255
|
+
if (typeof v.traceparent === "string") msg.traceparent = v.traceparent;
|
|
2256
|
+
if (typeof v.baggage === "string") msg.baggage = v.baggage;
|
|
2257
|
+
if (isRecord(v.action)) msg.action = v.action;
|
|
2258
|
+
if (v.metadata !== void 0 && v.metadata !== null) msg.metadata = v.metadata;
|
|
2259
|
+
if (typeof v.namespace === "string") msg.namespace = v.namespace;
|
|
2260
|
+
const caller = decodeCaller(v.caller);
|
|
2261
|
+
if (caller) msg.caller = caller;
|
|
2262
|
+
const depth = num(v.observe_depth);
|
|
2263
|
+
if (depth !== void 0 && depth > 0) msg.observe_depth = depth;
|
|
2264
|
+
const activation = decodeActivation(v.activation);
|
|
2265
|
+
if (activation) msg.activation = activation;
|
|
2266
|
+
return msg;
|
|
2267
|
+
}
|
|
2268
|
+
function decodeRegistrationRejected(v) {
|
|
2269
|
+
const msg = {
|
|
2270
|
+
code: String(v.code ?? ""),
|
|
2271
|
+
namespace: String(v.namespace ?? ""),
|
|
2272
|
+
owner_worker_id: String(v.owner_worker_id ?? "")
|
|
2273
|
+
};
|
|
2274
|
+
if (typeof v.worker_name === "string") msg.worker_name = v.worker_name;
|
|
2275
|
+
if (typeof v.function_id === "string") msg.function_id = v.function_id;
|
|
2276
|
+
return msg;
|
|
2277
|
+
}
|
|
2278
|
+
/** Drops `parent` (one level only). */
|
|
2279
|
+
function stripCaller(caller) {
|
|
2280
|
+
if (!caller) return void 0;
|
|
2281
|
+
const { parent: _, ...rest } = caller;
|
|
2282
|
+
return rest;
|
|
2283
|
+
}
|
|
2284
|
+
/** JSON's view of a message: `undefined` fields left out, no caller-owned objects retained. */
|
|
2285
|
+
function snapshot(value) {
|
|
2286
|
+
return JSON.parse(JSON.stringify(value));
|
|
2287
|
+
}
|
|
2288
|
+
/**
|
|
2289
|
+
* `observe { id, source, target, ... }` from the three arguments of
|
|
2290
|
+
* `iii.observe`. Only what the caller set is sent; the engine applies the
|
|
2291
|
+
* defaults. `resolveNamespace` gives the namespace of an unqualified id (this
|
|
2292
|
+
* worker's, `default` for `engine::*`).
|
|
2293
|
+
*/
|
|
2294
|
+
function buildObserveMessage(id, source, target, options, resolveNamespace) {
|
|
2295
|
+
const targetRef = typeof target === "string" ? { function_id: target } : target;
|
|
2296
|
+
const sourceNamespace = resolveNamespace(source.namespace, source.function_id, "ObserveSource.namespace");
|
|
2297
|
+
const targetNamespace = resolveNamespace(targetRef.namespace, targetRef.function_id, "Target.namespace");
|
|
2298
|
+
return snapshot({
|
|
2299
|
+
id,
|
|
2300
|
+
source: {
|
|
2301
|
+
function_id: source.function_id,
|
|
2302
|
+
namespace: sourceNamespace,
|
|
2303
|
+
args: source.args,
|
|
2304
|
+
filters: source.filters,
|
|
2305
|
+
capture: source.capture,
|
|
2306
|
+
on: source.on,
|
|
2307
|
+
deliver: source.deliver
|
|
2308
|
+
},
|
|
2309
|
+
target: {
|
|
2310
|
+
function_id: targetRef.function_id,
|
|
2311
|
+
namespace: targetNamespace
|
|
2312
|
+
},
|
|
2313
|
+
metadata: options?.metadata,
|
|
2314
|
+
max_fires: options?.max_fires,
|
|
2315
|
+
expires_in_ms: options?.expires_in_ms,
|
|
2316
|
+
max_in_flight: options?.max_in_flight
|
|
2317
|
+
});
|
|
2318
|
+
}
|
|
2319
|
+
function buildObserverAck(ack) {
|
|
2320
|
+
const msg = {
|
|
2321
|
+
function_id: ack.function_id,
|
|
2322
|
+
id: ack.id,
|
|
2323
|
+
revision: ack.revision
|
|
2324
|
+
};
|
|
2325
|
+
if (ack.namespace !== void 0) msg.namespace = ack.namespace;
|
|
2326
|
+
if (ack.error) msg.error = {
|
|
2327
|
+
code: ack.error.code,
|
|
2328
|
+
message: ack.error.message
|
|
2329
|
+
};
|
|
2330
|
+
return msg;
|
|
2331
|
+
}
|
|
2332
|
+
/**
|
|
2333
|
+
* An outbound `invokefunction`. `observe_depth` is left out when 0, and every
|
|
2334
|
+
* optional field when unset.
|
|
2335
|
+
*/
|
|
2336
|
+
function buildInvokeFunction(init) {
|
|
2337
|
+
const msg = {};
|
|
2338
|
+
if (init.invocation_id !== void 0) msg.invocation_id = init.invocation_id;
|
|
2339
|
+
msg.function_id = init.function_id;
|
|
2340
|
+
msg.data = init.data;
|
|
2341
|
+
if (init.traceparent !== void 0) msg.traceparent = init.traceparent;
|
|
2342
|
+
if (init.baggage !== void 0) msg.baggage = init.baggage;
|
|
2343
|
+
if (init.action !== void 0) msg.action = init.action;
|
|
2344
|
+
if (init.metadata !== void 0) msg.metadata = init.metadata;
|
|
2345
|
+
if (init.namespace !== void 0) msg.namespace = init.namespace;
|
|
2346
|
+
if (init.caller !== void 0) msg.caller = init.caller;
|
|
2347
|
+
if (init.observe_depth !== void 0 && init.observe_depth > 0) msg.observe_depth = init.observe_depth;
|
|
2348
|
+
if (init.activation !== void 0) msg.activation = init.activation;
|
|
2349
|
+
return msg;
|
|
2350
|
+
}
|
|
2351
|
+
/**
|
|
2352
|
+
* An outbound `invocationresult`: `result` is left out when the function
|
|
2353
|
+
* returned nothing (`undefined`). A routed call's answer says how the call
|
|
2354
|
+
* is delivered (decision 55): `delivered: true` (its deliver hook delivered
|
|
2355
|
+
* it), or `matched` (the observers its match hook matched, `[]` when none),
|
|
2356
|
+
* or neither; `delivered` outweighs `matched`, and only one is sent.
|
|
2357
|
+
*/
|
|
2358
|
+
function buildInvocationResult(init) {
|
|
2359
|
+
const msg = {
|
|
2360
|
+
invocation_id: init.invocation_id,
|
|
2361
|
+
function_id: init.function_id
|
|
2362
|
+
};
|
|
2363
|
+
if (init.result !== void 0) msg.result = init.result;
|
|
2364
|
+
if (init.error !== void 0) msg.error = init.error;
|
|
2365
|
+
if (init.traceparent !== void 0) msg.traceparent = init.traceparent;
|
|
2366
|
+
if (init.baggage !== void 0) msg.baggage = init.baggage;
|
|
2367
|
+
if (init.delivered === true) msg.delivered = true;
|
|
2368
|
+
else if (init.matched !== void 0) msg.matched = [...init.matched];
|
|
2369
|
+
return msg;
|
|
2370
|
+
}
|
|
2371
|
+
/** The caller an outbound call asserts from inside a handler: that handler, and its own caller one level up. */
|
|
2372
|
+
function callerFor(ctx) {
|
|
2373
|
+
const caller = {
|
|
2374
|
+
function_id: ctx.function_id,
|
|
2375
|
+
invocation_id: ctx.invocation_id
|
|
2376
|
+
};
|
|
2377
|
+
const parent = stripCaller(ctx.caller);
|
|
2378
|
+
if (parent && Object.keys(parent).length > 0) caller.parent = parent;
|
|
2379
|
+
return caller;
|
|
2380
|
+
}
|
|
2381
|
+
|
|
1739
2382
|
//#endregion
|
|
1740
2383
|
//#region src/observer-handle.ts
|
|
1741
2384
|
/**
|
|
@@ -1764,6 +2407,8 @@ var ObserverHandleImpl = class {
|
|
|
1764
2407
|
this.undelivered = [];
|
|
1765
2408
|
this.delivering = false;
|
|
1766
2409
|
this.sent = false;
|
|
2410
|
+
this.answered = false;
|
|
2411
|
+
this.refused = false;
|
|
1767
2412
|
}
|
|
1768
2413
|
get state() {
|
|
1769
2414
|
return this.currentState;
|
|
@@ -1851,47 +2496,27 @@ const DEFAULT_REPORTER_LIMITS = {
|
|
|
1851
2496
|
statsIntervalMs: 1e4
|
|
1852
2497
|
};
|
|
1853
2498
|
var ReportItem = class {
|
|
1854
|
-
constructor(init
|
|
2499
|
+
constructor(init) {
|
|
1855
2500
|
this.init = init;
|
|
1856
|
-
this.emit = emit;
|
|
1857
|
-
this.coalesceKey = coalesceKey;
|
|
1858
|
-
this.context = context;
|
|
1859
2501
|
this.parts = /* @__PURE__ */ new Map();
|
|
1860
|
-
this.
|
|
2502
|
+
this.outputIsInput = false;
|
|
1861
2503
|
this.json = "";
|
|
1862
2504
|
this.bytes = 0;
|
|
1863
2505
|
}
|
|
1864
|
-
/**
|
|
2506
|
+
/** Encodes the parts `captures` asks for. */
|
|
1865
2507
|
capture(captures) {
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
if (!
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
2508
|
+
const wanted = new Set(captures);
|
|
2509
|
+
const values = this.init.values;
|
|
2510
|
+
for (const part of PART_ORDER) {
|
|
2511
|
+
if (!wanted.has(part) || !(part in values)) continue;
|
|
2512
|
+
if (part === "output" && this.init.output_is_input && this.parts.has("input")) {
|
|
2513
|
+
this.outputIsInput = true;
|
|
2514
|
+
continue;
|
|
2515
|
+
}
|
|
2516
|
+
const encoded = encodeJson(values[part]);
|
|
1873
2517
|
if (encoded !== void 0) this.parts.set(part, encoded);
|
|
1874
2518
|
}
|
|
1875
2519
|
}
|
|
1876
|
-
/** What a merge can change, to undo it. */
|
|
1877
|
-
save() {
|
|
1878
|
-
return {
|
|
1879
|
-
matched: this.init.matched.length,
|
|
1880
|
-
captured: [...this.captured],
|
|
1881
|
-
parts: [...this.parts],
|
|
1882
|
-
json: this.json,
|
|
1883
|
-
bytes: this.bytes
|
|
1884
|
-
};
|
|
1885
|
-
}
|
|
1886
|
-
restore(state) {
|
|
1887
|
-
this.init.matched.length = state.matched;
|
|
1888
|
-
this.captured.clear();
|
|
1889
|
-
for (const c of state.captured) this.captured.add(c);
|
|
1890
|
-
this.parts.clear();
|
|
1891
|
-
for (const [part, encoded] of state.parts) this.parts.set(part, encoded);
|
|
1892
|
-
this.json = state.json;
|
|
1893
|
-
this.bytes = state.bytes;
|
|
1894
|
-
}
|
|
1895
2520
|
/** Assembles the wire JSON from the pre-encoded parts. */
|
|
1896
2521
|
render() {
|
|
1897
2522
|
const i = this.init;
|
|
@@ -1902,6 +2527,7 @@ var ReportItem = class {
|
|
|
1902
2527
|
for (const part of PART_ORDER) {
|
|
1903
2528
|
const encoded = this.parts.get(part);
|
|
1904
2529
|
if (encoded !== void 0) s += `,"${part}":${encoded}`;
|
|
2530
|
+
if (part === "input" && this.outputIsInput) s += ",\"output_is_input\":true";
|
|
1905
2531
|
}
|
|
1906
2532
|
s += `,"started_at_ms":${finite(i.started_at_ms)},"duration_ms":${finite(i.duration_ms)}`;
|
|
1907
2533
|
s += `,"observe_depth":${finite(i.observe_depth)}`;
|
|
@@ -1946,7 +2572,6 @@ var Reporter = class {
|
|
|
1946
2572
|
this.items = [];
|
|
1947
2573
|
this.bytes = 0;
|
|
1948
2574
|
this.perFunction = /* @__PURE__ */ new Map();
|
|
1949
|
-
this.openEmits = /* @__PURE__ */ new Map();
|
|
1950
2575
|
this.stats = /* @__PURE__ */ new Map();
|
|
1951
2576
|
this.drops = /* @__PURE__ */ new Map();
|
|
1952
2577
|
this.windowStart = Date.now();
|
|
@@ -1973,59 +2598,13 @@ var Reporter = class {
|
|
|
1973
2598
|
get size() {
|
|
1974
2599
|
return this.items.length;
|
|
1975
2600
|
}
|
|
1976
|
-
/** A
|
|
2601
|
+
/** A local call that observers matched. */
|
|
1977
2602
|
push(init) {
|
|
1978
2603
|
const { captures, ...rest } = init;
|
|
1979
|
-
const item = new ReportItem(rest
|
|
1980
|
-
if (!this.build(item, captures)) return false;
|
|
1981
|
-
return this.enqueue(item);
|
|
1982
|
-
}
|
|
1983
|
-
/**
|
|
1984
|
-
* An `obs.emit` event. The same event value emitted to several observers
|
|
1985
|
-
* from the same invocation context, before the buffer is flushed, becomes
|
|
1986
|
-
* one item whose `matched` lists them all.
|
|
1987
|
-
*/
|
|
1988
|
-
pushEmit(init) {
|
|
1989
|
-
const { observer_id, event, context, captures, ...rest } = init;
|
|
1990
|
-
const merge = this.openEmits.get(event)?.find((it) => it.init.function_id === rest.function_id && it.context === context && !it.init.matched.includes(observer_id));
|
|
1991
|
-
if (merge) return this.merge(merge, observer_id, captures);
|
|
1992
|
-
const item = new ReportItem({
|
|
1993
|
-
...rest,
|
|
1994
|
-
matched: [observer_id]
|
|
1995
|
-
}, true, event, context);
|
|
2604
|
+
const item = new ReportItem(rest);
|
|
1996
2605
|
if (!this.build(item, captures)) return false;
|
|
1997
2606
|
return this.enqueue(item);
|
|
1998
2607
|
}
|
|
1999
|
-
/** Makes a buffered emit item a merge target. Only items in the buffer are: a flush re-indexes. */
|
|
2000
|
-
index(item) {
|
|
2001
|
-
if (!item.emit) return;
|
|
2002
|
-
const list = this.openEmits.get(item.coalesceKey);
|
|
2003
|
-
if (list) list.push(item);
|
|
2004
|
-
else this.openEmits.set(item.coalesceKey, [item]);
|
|
2005
|
-
}
|
|
2006
|
-
/** Adds an observer (and its captures) to a buffered emit item, within the same bounds as a new item. */
|
|
2007
|
-
merge(item, observerId, captures) {
|
|
2008
|
-
const fn = item.init.function_id;
|
|
2009
|
-
const before = item.save();
|
|
2010
|
-
try {
|
|
2011
|
-
item.init.matched.push(observerId);
|
|
2012
|
-
item.capture(captures);
|
|
2013
|
-
item.render();
|
|
2014
|
-
} catch (error) {
|
|
2015
|
-
item.restore(before);
|
|
2016
|
-
this.logUnencodable(fn, error);
|
|
2017
|
-
return false;
|
|
2018
|
-
}
|
|
2019
|
-
const growth = item.bytes - before.bytes;
|
|
2020
|
-
const reason = this.tooLarge(item) ? "TOO_LARGE" : growth > 0 && this.bytes + this.host.pendingBytes() + growth > this.limits.maxBytes ? "BUFFER_FULL" : void 0;
|
|
2021
|
-
if (reason) {
|
|
2022
|
-
item.restore(before);
|
|
2023
|
-
this.drop(fn, reason);
|
|
2024
|
-
return false;
|
|
2025
|
-
}
|
|
2026
|
-
this.bytes += growth;
|
|
2027
|
-
return true;
|
|
2028
|
-
}
|
|
2029
2608
|
build(item, captures) {
|
|
2030
2609
|
try {
|
|
2031
2610
|
item.capture(captures);
|
|
@@ -2061,7 +2640,6 @@ var Reporter = class {
|
|
|
2061
2640
|
this.items.push(item);
|
|
2062
2641
|
this.bytes += item.bytes;
|
|
2063
2642
|
this.perFunction.set(fn, (this.perFunction.get(fn) ?? 0) + 1);
|
|
2064
|
-
this.index(item);
|
|
2065
2643
|
if (this.items.length >= this.limits.batchItems) this.flush();
|
|
2066
2644
|
else this.arm(this.limits.lingerMs);
|
|
2067
2645
|
return true;
|
|
@@ -2163,17 +2741,15 @@ var Reporter = class {
|
|
|
2163
2741
|
if (this.host.online()) this.arm(this.limits.lingerMs * 20);
|
|
2164
2742
|
}
|
|
2165
2743
|
}
|
|
2166
|
-
/** Replaces the buffer, keeping the per-function counts
|
|
2744
|
+
/** Replaces the buffer, keeping the per-function counts in step. */
|
|
2167
2745
|
setItems(items) {
|
|
2168
2746
|
this.items = items;
|
|
2169
2747
|
this.bytes = 0;
|
|
2170
2748
|
this.perFunction.clear();
|
|
2171
|
-
this.openEmits.clear();
|
|
2172
2749
|
for (const item of items) {
|
|
2173
2750
|
this.bytes += item.bytes;
|
|
2174
2751
|
const fn = item.init.function_id;
|
|
2175
2752
|
this.perFunction.set(fn, (this.perFunction.get(fn) ?? 0) + 1);
|
|
2176
|
-
this.index(item);
|
|
2177
2753
|
}
|
|
2178
2754
|
}
|
|
2179
2755
|
/** Puts items back at the front of the buffer, within its bounds. */
|
|
@@ -2250,6 +2826,28 @@ function createPayloadTooLargeError(size, functionId) {
|
|
|
2250
2826
|
function isPayloadTooLargeError(error) {
|
|
2251
2827
|
return error instanceof Error && "code" in error && error.code === "payload_too_large";
|
|
2252
2828
|
}
|
|
2829
|
+
/**
|
|
2830
|
+
* `registrationrejected` code (engine `protocol.rs`): another live worker
|
|
2831
|
+
* already holds this `(namespace, worker_name)`. The engine closes the
|
|
2832
|
+
* connection -- fatal.
|
|
2833
|
+
*/
|
|
2834
|
+
const WORKER_NAMESPACE_CONFLICT = "WORKER_NAMESPACE_CONFLICT";
|
|
2835
|
+
/**
|
|
2836
|
+
* `registrationrejected` code (engine `protocol.rs`): another live worker in
|
|
2837
|
+
* this namespace already exports this one function id. The connection stays
|
|
2838
|
+
* open -- non-fatal.
|
|
2839
|
+
*/
|
|
2840
|
+
const FUNCTION_NAMESPACE_CONFLICT = "FUNCTION_NAMESPACE_CONFLICT";
|
|
2841
|
+
/**
|
|
2842
|
+
* `registrationrejected` codes that refuse one function only (decisions 1,
|
|
2843
|
+
* 11): its `args_format` is not a valid JSON Schema, or the engine does not
|
|
2844
|
+
* support what it declares. The connection stays open -- non-fatal.
|
|
2845
|
+
*/
|
|
2846
|
+
const FUNCTION_REJECTIONS = new Set(["INVALID_ARGS_FORMAT", "UNSUPPORTED"]);
|
|
2847
|
+
/** A standby function retries its registration this often (decision 21), ±20 %. */
|
|
2848
|
+
const STANDBY_RETRY_MS = 1e3;
|
|
2849
|
+
/** Why `call` refuses a call through an observer that names metadata (v2 §4.6, decision 53); the same in every SDK. */
|
|
2850
|
+
const OBSERVER_CALL_METADATA = "a call through an observer takes no metadata; its target receives the observer's metadata";
|
|
2253
2851
|
/** Short random suffix; `crypto.randomUUID` is unavailable on insecure origins. */
|
|
2254
2852
|
function randomId() {
|
|
2255
2853
|
const c = globalThis.crypto;
|
|
@@ -2258,20 +2856,6 @@ function randomId() {
|
|
|
2258
2856
|
return Math.random().toString(16).slice(2, 10);
|
|
2259
2857
|
}
|
|
2260
2858
|
/**
|
|
2261
|
-
* The worker's namespace, refusing one that was named and left blank.
|
|
2262
|
-
*
|
|
2263
|
-
* Absent and blank mean opposite things. Absent asks for the engine's
|
|
2264
|
-
* `default`; blank names a namespace and gives nothing to name it with. Read as
|
|
2265
|
-
* absent, the worker registers in `default`, and since a worker's calls and
|
|
2266
|
-
* triggers follow its namespace, the whole project quietly serves from a place
|
|
2267
|
-
* its declaration never named -- the one thing an operator cannot see by
|
|
2268
|
-
* reading the declaration.
|
|
2269
|
-
*
|
|
2270
|
-
* The browser has no `III_NAMESPACE` to fall back to, so unlike the other SDKs
|
|
2271
|
-
* there is only the option here, and an option that was written and left empty
|
|
2272
|
-
* is never what someone meant.
|
|
2273
|
-
*/
|
|
2274
|
-
/**
|
|
2275
2859
|
* The namespace one call or one binding resolves in.
|
|
2276
2860
|
*
|
|
2277
2861
|
* `undefined` inherits the worker's. A blank one is refused: named and left
|
|
@@ -2284,17 +2868,10 @@ function callNamespace(explicit, worker, source) {
|
|
|
2284
2868
|
return explicit ?? worker;
|
|
2285
2869
|
}
|
|
2286
2870
|
/** Resolve one function invocation without leaking engine and configuration builtins into a worker namespace. */
|
|
2287
|
-
function invocationNamespace(explicit, worker, functionId, source = "
|
|
2871
|
+
function invocationNamespace(explicit, worker, functionId, source = "CallRequest.namespace") {
|
|
2288
2872
|
const namespace = callNamespace(explicit, worker, source);
|
|
2289
2873
|
return explicit === void 0 && (functionId.startsWith("engine::") || functionId.startsWith("configuration::")) ? "default" : namespace;
|
|
2290
2874
|
}
|
|
2291
|
-
const MIGRATION_GUIDE = "https://iii.dev/docs/upgrading/from-0-24-x";
|
|
2292
|
-
/** CONTRACT §5: one warning per page per deprecated API. */
|
|
2293
|
-
const DEPRECATIONS = {
|
|
2294
|
-
registerTrigger: `registerTrigger is deprecated and will be removed in a future release. Use iii.observe(source, target) instead. Migration guide: ${MIGRATION_GUIDE}`,
|
|
2295
|
-
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}`
|
|
2296
|
-
};
|
|
2297
|
-
const deprecationsWarned = /* @__PURE__ */ new Set();
|
|
2298
2875
|
/**
|
|
2299
2876
|
* Local dispatch hands the handler a copy of the caller's payload and the
|
|
2300
2877
|
* caller a copy of the result (value semantics, as over the wire):
|
|
@@ -2313,91 +2890,6 @@ const UNSUPPORTED_REASON = {
|
|
|
2313
2890
|
code: "UNSUPPORTED",
|
|
2314
2891
|
message: "the engine does not support observe (no observe.v1 in its features); upgrade it to 0.25 or later"
|
|
2315
2892
|
};
|
|
2316
|
-
/** `args_format` needs `delivery: 'owner'`: an auto function's events are its invocations, offered to every observer. */
|
|
2317
|
-
function validateObserveHooks(functionId, hooks) {
|
|
2318
|
-
if (!hooks) return;
|
|
2319
|
-
const delivery = hooks.delivery;
|
|
2320
|
-
if (delivery !== void 0 && delivery !== "auto" && delivery !== "owner") throw new InvocationError({
|
|
2321
|
-
code: "INVALID_OBSERVE_DESCRIPTOR",
|
|
2322
|
-
message: `observe.delivery must be 'auto' or 'owner', got ${JSON.stringify(delivery)}`,
|
|
2323
|
-
function_id: functionId
|
|
2324
|
-
});
|
|
2325
|
-
if (hooks.args_format !== void 0 && delivery !== "owner") throw new InvocationError({
|
|
2326
|
-
code: "INVALID_OBSERVE_DESCRIPTOR",
|
|
2327
|
-
message: "observe.args_format requires delivery: 'owner' (an auto function takes no args)",
|
|
2328
|
-
function_id: functionId
|
|
2329
|
-
});
|
|
2330
|
-
}
|
|
2331
|
-
/**
|
|
2332
|
-
* The error a call that timed out rejects with, on the remote and the local
|
|
2333
|
-
* path: an `Error` (its message unchanged from earlier releases) that also
|
|
2334
|
-
* carries `code: 'TIMEOUT'` and the `function_id`, like the Node SDK's.
|
|
2335
|
-
*/
|
|
2336
|
-
function timeoutError(ms, functionId) {
|
|
2337
|
-
return Object.assign(/* @__PURE__ */ new Error(`Invocation timeout after ${ms}ms: ${functionId}`), {
|
|
2338
|
-
code: "TIMEOUT",
|
|
2339
|
-
function_id: functionId
|
|
2340
|
-
});
|
|
2341
|
-
}
|
|
2342
|
-
/** What a handler failure reports when the thrown value cannot even be read (a getter or `toString` that throws). */
|
|
2343
|
-
const UNREADABLE_FAILURE = "the handler failed with a value that cannot be read";
|
|
2344
|
-
function safeString(value) {
|
|
2345
|
-
try {
|
|
2346
|
-
return String(value);
|
|
2347
|
-
} catch {
|
|
2348
|
-
return UNREADABLE_FAILURE;
|
|
2349
|
-
}
|
|
2350
|
-
}
|
|
2351
|
-
/**
|
|
2352
|
-
* An error body as the engine sends it, and as this SDK's own calls reject
|
|
2353
|
-
* with: a plain (JSON-parsed) object with a string `code`, a string `message`
|
|
2354
|
-
* and, optionally, a string `stacktrace`. A class instance or anything else
|
|
2355
|
-
* with such fields is not one: it is reported through `String()`.
|
|
2356
|
-
*/
|
|
2357
|
-
function isEngineErrorBody(value) {
|
|
2358
|
-
if (value === null || typeof value !== "object") return false;
|
|
2359
|
-
const proto = Object.getPrototypeOf(value);
|
|
2360
|
-
if (proto !== Object.prototype && proto !== null) return false;
|
|
2361
|
-
const body = value;
|
|
2362
|
-
return typeof body.code === "string" && typeof body.message === "string" && (body.stacktrace === void 0 || typeof body.stacktrace === "string");
|
|
2363
|
-
}
|
|
2364
|
-
/**
|
|
2365
|
-
* The error a handler's failure becomes, the same on the local and the remote
|
|
2366
|
-
* path (code `invocation_failed`):
|
|
2367
|
-
* - an `Error`, from any realm (an iframe's too): its message and stack;
|
|
2368
|
-
* - an engine error body (a failed call's rejection, rethrown): its message and stacktrace;
|
|
2369
|
-
* - anything else: `String(value)`.
|
|
2370
|
-
* Never throws: when reading the value throws, a fixed message is reported, so
|
|
2371
|
-
* the caller always gets its answer.
|
|
2372
|
-
*/
|
|
2373
|
-
function handlerErrorBody(error) {
|
|
2374
|
-
try {
|
|
2375
|
-
if (error instanceof Error || Object.prototype.toString.call(error) === "[object Error]") {
|
|
2376
|
-
const { message, stack } = error;
|
|
2377
|
-
return {
|
|
2378
|
-
code: "invocation_failed",
|
|
2379
|
-
message: typeof message === "string" ? message : safeString(message),
|
|
2380
|
-
stacktrace: typeof stack === "string" ? stack : void 0
|
|
2381
|
-
};
|
|
2382
|
-
}
|
|
2383
|
-
if (isEngineErrorBody(error)) return {
|
|
2384
|
-
code: "invocation_failed",
|
|
2385
|
-
message: error.message,
|
|
2386
|
-
stacktrace: error.stacktrace
|
|
2387
|
-
};
|
|
2388
|
-
return {
|
|
2389
|
-
code: "invocation_failed",
|
|
2390
|
-
message: String(error),
|
|
2391
|
-
stacktrace: void 0
|
|
2392
|
-
};
|
|
2393
|
-
} catch {
|
|
2394
|
-
return {
|
|
2395
|
-
code: "invocation_failed",
|
|
2396
|
-
message: safeString(error),
|
|
2397
|
-
stacktrace: void 0
|
|
2398
|
-
};
|
|
2399
|
-
}
|
|
2400
|
-
}
|
|
2401
2893
|
function resolveNamespace(optionNamespace) {
|
|
2402
2894
|
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\`.`);
|
|
2403
2895
|
return optionNamespace;
|
|
@@ -2405,130 +2897,109 @@ function resolveNamespace(optionNamespace) {
|
|
|
2405
2897
|
var Sdk = class {
|
|
2406
2898
|
constructor(address, options) {
|
|
2407
2899
|
this.address = address;
|
|
2408
|
-
this.options = options;
|
|
2409
2900
|
this.functions = /* @__PURE__ */ new Map();
|
|
2410
2901
|
this.invocations = /* @__PURE__ */ new Map();
|
|
2411
|
-
this.triggers = /* @__PURE__ */ new Map();
|
|
2412
|
-
this.triggerTypes = /* @__PURE__ */ new Map();
|
|
2413
2902
|
this.messagesToSend = [];
|
|
2414
2903
|
this.reconnectAttempt = 0;
|
|
2415
2904
|
this.connectionState = "disconnected";
|
|
2416
2905
|
this.connectionListeners = /* @__PURE__ */ new Set();
|
|
2417
2906
|
this.isShuttingDown = false;
|
|
2418
|
-
this.
|
|
2907
|
+
this.observerHandles = /* @__PURE__ */ new Map();
|
|
2908
|
+
this.observesSent = /* @__PURE__ */ new Map();
|
|
2419
2909
|
this.engineFeatures = /* @__PURE__ */ new Set();
|
|
2420
2910
|
this.registeredOnConnection = false;
|
|
2421
2911
|
this.connectionEpoch = 0;
|
|
2912
|
+
this.workerHooks = {};
|
|
2913
|
+
this.functionHooks = /* @__PURE__ */ new Map();
|
|
2422
2914
|
this.hooksInactiveWarned = /* @__PURE__ */ new Set();
|
|
2915
|
+
this.unsupportedWarned = /* @__PURE__ */ new Set();
|
|
2916
|
+
this.unregisteredHooksWarned = /* @__PURE__ */ new Set();
|
|
2917
|
+
this.standbyTimers = /* @__PURE__ */ new Map();
|
|
2423
2918
|
this.observeQueue = [];
|
|
2424
|
-
this.
|
|
2425
|
-
this.warnDeprecated("registerTriggerType");
|
|
2426
|
-
const message = this.snapshotRegistration({
|
|
2427
|
-
...triggerType,
|
|
2428
|
-
message_type: "registertriggertype"
|
|
2429
|
-
});
|
|
2430
|
-
this.sendMessage("registertriggertype", message, true);
|
|
2431
|
-
this.triggerTypes.set(message.id, {
|
|
2432
|
-
message,
|
|
2433
|
-
handler
|
|
2434
|
-
});
|
|
2435
|
-
return {
|
|
2436
|
-
id: message.id,
|
|
2437
|
-
registerTrigger: (functionId, config) => {
|
|
2438
|
-
return this.registerTrigger({
|
|
2439
|
-
type: message.id,
|
|
2440
|
-
function_id: functionId,
|
|
2441
|
-
config,
|
|
2442
|
-
namespace: this.namespace
|
|
2443
|
-
});
|
|
2444
|
-
},
|
|
2445
|
-
registerFunction: (functionId, handler, config) => {
|
|
2446
|
-
const ref = this.registerFunction(functionId, handler);
|
|
2447
|
-
this.registerTrigger({
|
|
2448
|
-
type: message.id,
|
|
2449
|
-
function_id: functionId,
|
|
2450
|
-
config,
|
|
2451
|
-
namespace: this.namespace
|
|
2452
|
-
});
|
|
2453
|
-
return ref;
|
|
2454
|
-
},
|
|
2455
|
-
unregister: () => {
|
|
2456
|
-
this.unregisterTriggerType(message);
|
|
2457
|
-
}
|
|
2458
|
-
};
|
|
2459
|
-
};
|
|
2460
|
-
this.unregisterTriggerType = (triggerType) => {
|
|
2461
|
-
const { id, namespace } = triggerType;
|
|
2462
|
-
this.sendMessage("unregistertriggertype", namespace !== void 0 ? {
|
|
2463
|
-
id,
|
|
2464
|
-
namespace
|
|
2465
|
-
} : { id }, true);
|
|
2466
|
-
this.triggerTypes.delete(id);
|
|
2467
|
-
};
|
|
2468
|
-
this.registerTrigger = (trigger) => {
|
|
2469
|
-
this.warnDeprecated("registerTrigger");
|
|
2470
|
-
const id = randomUUID();
|
|
2471
|
-
const fullTrigger = this.snapshotRegistration({
|
|
2472
|
-
...trigger,
|
|
2473
|
-
id,
|
|
2474
|
-
message_type: "registertrigger",
|
|
2475
|
-
...(() => {
|
|
2476
|
-
const namespace = callNamespace(trigger.namespace, this.namespace, "RegisterTriggerInput.namespace");
|
|
2477
|
-
return namespace !== void 0 ? { namespace } : {};
|
|
2478
|
-
})()
|
|
2479
|
-
});
|
|
2480
|
-
this.sendMessage("registertrigger", fullTrigger, true);
|
|
2481
|
-
this.triggers.set(id, fullTrigger);
|
|
2482
|
-
return { unregister: () => {
|
|
2483
|
-
this.sendMessage("unregistertrigger", {
|
|
2484
|
-
id,
|
|
2485
|
-
message_type: "unregistertrigger",
|
|
2486
|
-
type: fullTrigger.type
|
|
2487
|
-
});
|
|
2488
|
-
this.triggers.delete(id);
|
|
2489
|
-
} };
|
|
2490
|
-
};
|
|
2491
|
-
this.registerFunction = (functionId, handlerOrInvocation, options) => {
|
|
2919
|
+
this.registerFunction = (functionId, handler, options) => {
|
|
2492
2920
|
if (!functionId || functionId.trim() === "") throw new Error("id is required");
|
|
2493
2921
|
if (this.functions.has(functionId)) throw new Error(`function id already registered: ${functionId}`);
|
|
2494
|
-
const {
|
|
2495
|
-
validateObserveHooks(functionId, hooks);
|
|
2496
|
-
const descriptor = observeDescriptor(hooks);
|
|
2922
|
+
const { standby, localDispatch, private: isPrivate, observable, ...wireOptions } = options ?? {};
|
|
2497
2923
|
const fullMessage = this.snapshotRegistration({
|
|
2498
2924
|
...wireOptions,
|
|
2499
|
-
...
|
|
2925
|
+
...isPrivate === true ? { private: true } : {},
|
|
2926
|
+
...observable === false ? { observable: false } : {},
|
|
2500
2927
|
id: functionId,
|
|
2501
2928
|
message_type: "registerfunction"
|
|
2502
2929
|
});
|
|
2503
|
-
this.
|
|
2504
|
-
const observe = new FunctionObservers(functionId,
|
|
2505
|
-
|
|
2506
|
-
const handler = handlerOrInvocation;
|
|
2507
|
-
this.functions.set(functionId, {
|
|
2930
|
+
const frame = this.prepareJson(this.toWireFormat("registerfunction", fullMessage));
|
|
2931
|
+
const observe = new FunctionObservers(functionId, localDispatch !== false, true, this.observeHost);
|
|
2932
|
+
const fn = {
|
|
2508
2933
|
message: fullMessage,
|
|
2509
2934
|
observe,
|
|
2935
|
+
standby: standby === true,
|
|
2510
2936
|
handler: async (input, metadata) => {
|
|
2511
2937
|
return await handler(input, metadata);
|
|
2512
2938
|
}
|
|
2513
|
-
}
|
|
2514
|
-
|
|
2939
|
+
};
|
|
2940
|
+
this.functions.set(functionId, fn);
|
|
2941
|
+
if (this.mayRegister(functionId, fn)) {
|
|
2942
|
+
this.sendMessageRaw(frame);
|
|
2943
|
+
fn.sentEpoch = this.connectionEpoch;
|
|
2944
|
+
}
|
|
2945
|
+
if (this.registeredOnConnection && !this.engineFeatures.has("observe.v1") && this.hasObserverHooks(functionId)) this.warnHooksInactive(functionId);
|
|
2946
|
+
const ref = {
|
|
2515
2947
|
id: functionId,
|
|
2948
|
+
onObserverAdded: (hook) => {
|
|
2949
|
+
this.onObserverAdded(functionId, hook);
|
|
2950
|
+
return ref;
|
|
2951
|
+
},
|
|
2952
|
+
onObserverRemoved: (hook) => {
|
|
2953
|
+
this.onObserverRemoved(functionId, hook);
|
|
2954
|
+
return ref;
|
|
2955
|
+
},
|
|
2956
|
+
onObserverMatch: (hook) => {
|
|
2957
|
+
this.onObserverMatch(functionId, hook);
|
|
2958
|
+
return ref;
|
|
2959
|
+
},
|
|
2960
|
+
onObserverDeliver: (hook) => {
|
|
2961
|
+
this.onObserverDeliver(functionId, hook);
|
|
2962
|
+
return ref;
|
|
2963
|
+
},
|
|
2964
|
+
observers: () => observe.observers(),
|
|
2965
|
+
isObserved: (call) => observe.isObserved(call),
|
|
2516
2966
|
unregister: () => {
|
|
2517
|
-
if (this.functions.get(functionId)
|
|
2967
|
+
if (this.functions.get(functionId) !== fn) return;
|
|
2518
2968
|
this.sendMessage("unregisterfunction", { id: functionId }, true);
|
|
2519
2969
|
this.functions.delete(functionId);
|
|
2970
|
+
this.stopStandby(functionId);
|
|
2520
2971
|
observe.dispose();
|
|
2521
|
-
}
|
|
2522
|
-
isObserved: () => observe.isObserved(),
|
|
2523
|
-
observers: () => observe.observers()
|
|
2972
|
+
}
|
|
2524
2973
|
};
|
|
2974
|
+
return ref;
|
|
2975
|
+
};
|
|
2976
|
+
this.onObserverAdded = (a, b) => {
|
|
2977
|
+
if (typeof a === "string") this.setFunctionHook(a, "added", b);
|
|
2978
|
+
else this.setWorkerHook("added", a);
|
|
2979
|
+
return this;
|
|
2980
|
+
};
|
|
2981
|
+
this.onObserverRemoved = (a, b) => {
|
|
2982
|
+
if (typeof a === "string") this.setFunctionHook(a, "removed", b);
|
|
2983
|
+
else this.setWorkerHook("removed", a);
|
|
2984
|
+
return this;
|
|
2985
|
+
};
|
|
2986
|
+
this.onObserverMatch = (functionId, hook) => {
|
|
2987
|
+
this.setFunctionHook(functionId, "match", hook);
|
|
2988
|
+
return this;
|
|
2989
|
+
};
|
|
2990
|
+
this.onObserverDeliver = (functionId, hook) => {
|
|
2991
|
+
this.setFunctionHook(functionId, "deliver", hook);
|
|
2992
|
+
return this;
|
|
2525
2993
|
};
|
|
2526
|
-
this.
|
|
2994
|
+
this.observers = (functionId) => this.functions.get(functionId)?.observe.observers() ?? [];
|
|
2995
|
+
this.isObserved = (functionId, call) => this.functions.get(functionId)?.observe.isObserved(call) ?? false;
|
|
2996
|
+
this.observe = (sourceOrId, target, options) => {
|
|
2997
|
+
const source = typeof sourceOrId === "string" ? { function_id: sourceOrId } : sourceOrId;
|
|
2527
2998
|
if (!source || typeof source.function_id !== "string" || source.function_id.trim() === "") throw new Error("observe: source.function_id is required");
|
|
2528
2999
|
const targetId = typeof target === "string" ? target : target?.function_id;
|
|
2529
3000
|
if (typeof targetId !== "string" || targetId.trim() === "") throw new Error("observe: target is required (the id of a registered function)");
|
|
2530
3001
|
const id = options?.id ?? randomUUID();
|
|
2531
|
-
if (this.
|
|
3002
|
+
if (this.observerHandles.has(id)) throw new ObserveRejection("OBSERVER_ID_CONFLICT", `observe: observer id already in use: ${id}`);
|
|
2532
3003
|
const onDispose = (h) => this.disposeObserver(h);
|
|
2533
3004
|
const logError = (msg, error) => this.logError(msg, error);
|
|
2534
3005
|
const refused = (reason) => {
|
|
@@ -2560,7 +3031,7 @@ var Sdk = class {
|
|
|
2560
3031
|
});
|
|
2561
3032
|
}
|
|
2562
3033
|
const handle = new ObserverHandleImpl(id, message, onDispose, logError);
|
|
2563
|
-
this.
|
|
3034
|
+
this.observerHandles.set(id, handle);
|
|
2564
3035
|
if (this.registeredOnConnection && this.isOpen()) if (this.engineFeatures.has("observe.v1")) this.sendObserve(handle);
|
|
2565
3036
|
else handle.setState("error", UNSUPPORTED_REASON);
|
|
2566
3037
|
return handle;
|
|
@@ -2568,7 +3039,7 @@ var Sdk = class {
|
|
|
2568
3039
|
this.currentInvocation = () => publicContext(currentContext());
|
|
2569
3040
|
this.withInvocation = (invocation, fn) => enterInvocation(contextFromView(invocation), fn, MAX_RUNNING_INVOCATION_MS);
|
|
2570
3041
|
this.__helpers_create_channel = async (bufferSize) => {
|
|
2571
|
-
const result = await this.
|
|
3042
|
+
const result = await this.call({
|
|
2572
3043
|
function_id: "engine::channels::create",
|
|
2573
3044
|
payload: { buffer_size: bufferSize }
|
|
2574
3045
|
});
|
|
@@ -2579,17 +3050,31 @@ var Sdk = class {
|
|
|
2579
3050
|
readerRef: result.reader
|
|
2580
3051
|
};
|
|
2581
3052
|
};
|
|
2582
|
-
this.
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
|
|
3053
|
+
this.call = async (request) => {
|
|
3054
|
+
if (request.observer !== void 0) {
|
|
3055
|
+
const { observer, payload, action, timeoutMs } = request;
|
|
3056
|
+
if (request.metadata != null) throw new Error(OBSERVER_CALL_METADATA);
|
|
3057
|
+
return this.invokeRemote({
|
|
3058
|
+
function_id: observer.target,
|
|
3059
|
+
payload,
|
|
3060
|
+
action,
|
|
3061
|
+
timeoutMs
|
|
3062
|
+
}, void 0, { observer_id: observer.id });
|
|
3063
|
+
}
|
|
3064
|
+
const req = request.metadata === null ? {
|
|
3065
|
+
...request,
|
|
3066
|
+
metadata: void 0
|
|
3067
|
+
} : request;
|
|
3068
|
+
const { function_id, action } = req;
|
|
3069
|
+
const namespace = invocationNamespace(req.namespace, this.namespace, function_id);
|
|
3070
|
+
if (req.dispatch !== "remote" && action?.type !== "enqueue") {
|
|
2586
3071
|
const fn = this.functions.get(function_id);
|
|
2587
3072
|
const observe = fn?.observe;
|
|
2588
3073
|
if (fn?.handler && observe?.localDispatch && (namespace === void 0 || namespace === observe.namespace)) {
|
|
2589
3074
|
const depth = callLocalDepth();
|
|
2590
|
-
if (depth < 64) return this.invokeLocal(function_id, fn
|
|
3075
|
+
if (depth < 64) return this.invokeLocal(function_id, fn, req);
|
|
2591
3076
|
if (!this.isOpen()) {
|
|
2592
|
-
if (depth < 256) return this.invokeLocal(function_id, fn
|
|
3077
|
+
if (depth < 256) return this.invokeLocal(function_id, fn, req);
|
|
2593
3078
|
throw new InvocationError({
|
|
2594
3079
|
code: "LOCAL_DEPTH_EXCEEDED",
|
|
2595
3080
|
message: `${function_id} is called ${depth} local calls deep: past ${64} the call needs the engine, and the socket is closed`,
|
|
@@ -2598,8 +3083,9 @@ var Sdk = class {
|
|
|
2598
3083
|
}
|
|
2599
3084
|
}
|
|
2600
3085
|
}
|
|
2601
|
-
return this.invokeRemote(
|
|
3086
|
+
return this.invokeRemote(req, namespace);
|
|
2602
3087
|
};
|
|
3088
|
+
this.trigger = this.call;
|
|
2603
3089
|
this.__helpers_create_stream = (streamName, stream) => {
|
|
2604
3090
|
this.registerFunction(`stream::get(${streamName})`, stream.get.bind(stream));
|
|
2605
3091
|
this.registerFunction(`stream::set(${streamName})`, stream.set.bind(stream));
|
|
@@ -2618,6 +3104,7 @@ var Sdk = class {
|
|
|
2618
3104
|
}
|
|
2619
3105
|
this.reporter.stop();
|
|
2620
3106
|
this.clearReconnectTimeout();
|
|
3107
|
+
for (const functionId of [...this.standbyTimers.keys()]) this.stopStandby(functionId);
|
|
2621
3108
|
for (const [_id, invocation] of this.invocations) {
|
|
2622
3109
|
if (invocation.timeout) clearTimeout(invocation.timeout);
|
|
2623
3110
|
invocation.reject(/* @__PURE__ */ new Error("iii is shutting down"));
|
|
@@ -2669,39 +3156,146 @@ var Sdk = class {
|
|
|
2669
3156
|
logError: (message, error) => this.logError(message, error)
|
|
2670
3157
|
}, options?.observe?.reporter);
|
|
2671
3158
|
this.observeHost = {
|
|
2672
|
-
identity: () => this.workerId !== void 0 ? {
|
|
2673
|
-
worker_id: this.workerId,
|
|
2674
|
-
worker_name: this.workerName
|
|
2675
|
-
} : { worker_name: this.workerName },
|
|
2676
3159
|
sendAck: (ack) => this.sendMessage("observerack", buildObserverAck(ack), true),
|
|
2677
3160
|
reporter: this.reporter,
|
|
2678
|
-
|
|
2679
|
-
function_id: target,
|
|
2680
|
-
payload,
|
|
2681
|
-
timeoutMs
|
|
2682
|
-
}, void 0, { observer_id: observerId }),
|
|
3161
|
+
hooks: (functionId) => this.hooksOf(functionId),
|
|
2683
3162
|
logError: (message, error) => this.logError(message, error),
|
|
3163
|
+
logWarn: (message) => this.logWarn(message),
|
|
2684
3164
|
hookTimeoutMs: () => options?.observe?.hookTimeoutMs ?? 3e4,
|
|
2685
|
-
|
|
3165
|
+
observeV2: () => this.engineFeatures.has(FEATURE_OBSERVE_V2)
|
|
2686
3166
|
};
|
|
2687
3167
|
this.reporter.start();
|
|
2688
3168
|
this.connect();
|
|
2689
3169
|
}
|
|
2690
|
-
warnDeprecated(api) {
|
|
2691
|
-
if (deprecationsWarned.has(api)) return;
|
|
2692
|
-
deprecationsWarned.add(api);
|
|
2693
|
-
console.warn(`[iii] ${DEPRECATIONS[api]}`);
|
|
2694
|
-
}
|
|
2695
3170
|
logError(message, error) {
|
|
2696
3171
|
if (error === void 0) console.error(`[iii] ${message}`);
|
|
2697
3172
|
else console.error(`[iii] ${message}`, error);
|
|
2698
3173
|
}
|
|
3174
|
+
logWarn(message) {
|
|
3175
|
+
console.warn(`[iii] ${message}`);
|
|
3176
|
+
}
|
|
3177
|
+
logInfo(message) {
|
|
3178
|
+
console.info(`[iii] ${message}`);
|
|
3179
|
+
}
|
|
3180
|
+
/**
|
|
3181
|
+
* What a function needs `observe.v2` for (decision 18): `args_format`,
|
|
3182
|
+
* `private`, `observable: false`, a match hook or a deliver hook.
|
|
3183
|
+
*/
|
|
3184
|
+
needsObserveV2(functionId, fn) {
|
|
3185
|
+
const { message } = fn;
|
|
3186
|
+
const hooks = this.functionHooks.get(functionId);
|
|
3187
|
+
return message.args_format !== void 0 || message.private === true || message.observable === false || hooks?.match !== void 0 || hooks?.deliver !== void 0;
|
|
3188
|
+
}
|
|
3189
|
+
/**
|
|
3190
|
+
* Whether the function's `registerfunction` may go out on the current
|
|
3191
|
+
* connection now. One that needs `observe.v2` waits for this connection's
|
|
3192
|
+
* `WorkerRegistered`, and stays unregistered (`holdUnsupported`) when the
|
|
3193
|
+
* engine does not advertise it (decision 41).
|
|
3194
|
+
*/
|
|
3195
|
+
mayRegister(functionId, fn) {
|
|
3196
|
+
if (!this.isOpen()) return false;
|
|
3197
|
+
if (!this.needsObserveV2(functionId, fn)) return true;
|
|
3198
|
+
if (!this.registeredOnConnection) return false;
|
|
3199
|
+
if (this.engineFeatures.has("observe.v2")) return true;
|
|
3200
|
+
this.holdUnsupported(functionId, fn);
|
|
3201
|
+
return false;
|
|
3202
|
+
}
|
|
3203
|
+
/**
|
|
3204
|
+
* A function that needs `observe.v2` on a connection whose engine does not
|
|
3205
|
+
* advertise it: the engine does not hold it here, so what it kept from an
|
|
3206
|
+
* earlier connection is released once per connection (local dispatch, its
|
|
3207
|
+
* observers through `onObserverRemoved`, held reports), and `UNSUPPORTED`
|
|
3208
|
+
* is logged once per function.
|
|
3209
|
+
*/
|
|
3210
|
+
holdUnsupported(functionId, fn) {
|
|
3211
|
+
if (fn.observe.releasedEpoch !== this.connectionEpoch) fn.observe.onRegistrationRejected(this.connectionEpoch);
|
|
3212
|
+
this.warnUnsupported(functionId);
|
|
3213
|
+
}
|
|
3214
|
+
/** Sends the registrations that may go out now and have not on this connection. */
|
|
3215
|
+
sendRegistrations() {
|
|
3216
|
+
for (const [functionId, fn] of this.functions) {
|
|
3217
|
+
if (fn.sentEpoch === this.connectionEpoch || !this.mayRegister(functionId, fn)) continue;
|
|
3218
|
+
this.replayRegistration("registerfunction", fn.message);
|
|
3219
|
+
fn.sentEpoch = this.connectionEpoch;
|
|
3220
|
+
}
|
|
3221
|
+
}
|
|
3222
|
+
/**
|
|
3223
|
+
* Decides the registration again once a match or deliver hook may have
|
|
3224
|
+
* changed whether the function needs `observe.v2` (set or removed, or set
|
|
3225
|
+
* before `WorkerRegistered`): against an engine without it, a registered
|
|
3226
|
+
* function is unregistered (and one held back is registered once it no
|
|
3227
|
+
* longer needs it).
|
|
3228
|
+
*/
|
|
3229
|
+
reconcileRegistration(functionId) {
|
|
3230
|
+
const fn = this.functions.get(functionId);
|
|
3231
|
+
if (!fn || !this.isOpen() || !this.registeredOnConnection) return;
|
|
3232
|
+
const sent = fn.sentEpoch === this.connectionEpoch;
|
|
3233
|
+
const allowed = this.engineFeatures.has("observe.v2") || !this.needsObserveV2(functionId, fn);
|
|
3234
|
+
if (sent && !allowed) {
|
|
3235
|
+
this.sendMessage("unregisterfunction", { id: functionId }, true);
|
|
3236
|
+
fn.sentEpoch = void 0;
|
|
3237
|
+
this.holdUnsupported(functionId, fn);
|
|
3238
|
+
} else if (!sent && allowed) {
|
|
3239
|
+
this.replayRegistration("registerfunction", fn.message);
|
|
3240
|
+
fn.sentEpoch = this.connectionEpoch;
|
|
3241
|
+
}
|
|
3242
|
+
}
|
|
3243
|
+
warnUnsupported(functionId) {
|
|
3244
|
+
if (this.unsupportedWarned.has(functionId)) return;
|
|
3245
|
+
this.unsupportedWarned.add(functionId);
|
|
3246
|
+
this.logWarn(`UNSUPPORTED: function "${functionId}" needs observe.v2 (args_format, private, observable: false, onObserverMatch or onObserverDeliver), which this engine does not advertise; it stays unregistered until the worker connects to an engine with observe.v2.`);
|
|
3247
|
+
}
|
|
3248
|
+
/** The hooks that apply to one function now: the worker's, and those set for its id. */
|
|
3249
|
+
hooksOf(functionId) {
|
|
3250
|
+
const own = this.functionHooks.get(functionId);
|
|
3251
|
+
return {
|
|
3252
|
+
workerAdded: this.workerHooks.added,
|
|
3253
|
+
workerRemoved: this.workerHooks.removed,
|
|
3254
|
+
added: own?.added,
|
|
3255
|
+
removed: own?.removed,
|
|
3256
|
+
match: own?.match,
|
|
3257
|
+
deliver: own?.deliver
|
|
3258
|
+
};
|
|
3259
|
+
}
|
|
3260
|
+
hasObserverHooks(functionId) {
|
|
3261
|
+
const own = this.functionHooks.get(functionId);
|
|
3262
|
+
return !!(this.workerHooks.added || this.workerHooks.removed || own?.added || own?.removed || own?.match || own?.deliver);
|
|
3263
|
+
}
|
|
3264
|
+
setFunctionHook(functionId, kind, hook) {
|
|
3265
|
+
if (typeof functionId !== "string" || functionId.trim() === "") throw new TypeError("the function id of an observer hook is required");
|
|
3266
|
+
const keys = kind === "match" && hook !== null && typeof hook === "object" && typeof hook.observer === "function" && typeof hook.call === "function";
|
|
3267
|
+
if (hook !== null && typeof hook !== "function" && !keys) throw new TypeError(kind === "match" ? `the match hook of ${functionId} must be a predicate, { observer, call } key functions, or null to remove it` : `the ${kind} hook of ${functionId} must be a function, or null to remove it`);
|
|
3268
|
+
const hooks = {
|
|
3269
|
+
...this.functionHooks.get(functionId),
|
|
3270
|
+
[kind]: hook ?? void 0
|
|
3271
|
+
};
|
|
3272
|
+
if (hooks.added || hooks.removed || hooks.match || hooks.deliver) this.functionHooks.set(functionId, hooks);
|
|
3273
|
+
else this.functionHooks.delete(functionId);
|
|
3274
|
+
const fn = this.functions.get(functionId);
|
|
3275
|
+
if (!fn) return;
|
|
3276
|
+
if (kind === "added" && hook) fn.observe.catchUp("fn");
|
|
3277
|
+
if (kind === "match") fn.observe.matchChanged();
|
|
3278
|
+
if (kind === "match" || kind === "deliver") this.reconcileRegistration(functionId);
|
|
3279
|
+
}
|
|
3280
|
+
setWorkerHook(kind, hook) {
|
|
3281
|
+
if (hook !== null && typeof hook !== "function") throw new TypeError(`the worker's ${kind} hook must be a function, or null to remove it`);
|
|
3282
|
+
this.workerHooks = {
|
|
3283
|
+
...this.workerHooks,
|
|
3284
|
+
[kind]: hook ?? void 0
|
|
3285
|
+
};
|
|
3286
|
+
if (kind === "added" && hook) for (const fn of this.functions.values()) fn.observe.catchUp("worker");
|
|
3287
|
+
}
|
|
2699
3288
|
sendObserve(handle) {
|
|
2700
3289
|
this.sendMessage("observe", handle.message, true);
|
|
2701
3290
|
handle.sent = true;
|
|
3291
|
+
handle.answered = false;
|
|
3292
|
+
const sent = this.observesSent.get(handle.id);
|
|
3293
|
+
if (sent) sent.push(handle);
|
|
3294
|
+
else this.observesSent.set(handle.id, [handle]);
|
|
2702
3295
|
}
|
|
2703
3296
|
disposeObserver(handle) {
|
|
2704
|
-
if (this.
|
|
3297
|
+
if (this.observerHandles.get(handle.id) === handle) this.observerHandles.delete(handle.id);
|
|
3298
|
+
if (handle.answered) this.unlistObserve(handle);
|
|
2705
3299
|
if (!handle.sent) return;
|
|
2706
3300
|
this.sendObserveFamily("unobserve", { id: handle.id });
|
|
2707
3301
|
}
|
|
@@ -2721,7 +3315,15 @@ var Sdk = class {
|
|
|
2721
3315
|
warnHooksInactive(functionId) {
|
|
2722
3316
|
if (this.hooksInactiveWarned.has(functionId)) return;
|
|
2723
3317
|
this.hooksInactiveWarned.add(functionId);
|
|
2724
|
-
|
|
3318
|
+
this.logWarn(`Function "${functionId}" has observer hooks, but the engine does not support observe (observe.v1): it is registered as a plain function and its observer hooks are inactive.`);
|
|
3319
|
+
}
|
|
3320
|
+
/** Once the connection is registered: a hook set for an id this worker has not registered (a mistyped id?). */
|
|
3321
|
+
warnUnregisteredHookIds() {
|
|
3322
|
+
for (const functionId of this.functionHooks.keys()) {
|
|
3323
|
+
if (this.functions.has(functionId) || this.unregisteredHooksWarned.has(functionId)) continue;
|
|
3324
|
+
this.unregisteredHooksWarned.add(functionId);
|
|
3325
|
+
this.logWarn(`Observer hooks are set for "${functionId}", which this worker has not registered; check the function id.`);
|
|
3326
|
+
}
|
|
2725
3327
|
}
|
|
2726
3328
|
/** Connected to an engine that advertised `observe.v1`. */
|
|
2727
3329
|
observeOnline() {
|
|
@@ -2749,6 +3351,7 @@ var Sdk = class {
|
|
|
2749
3351
|
}
|
|
2750
3352
|
/** The routed path: an `InvokeFunction` through the engine. */
|
|
2751
3353
|
invokeRemote(request, namespace, activation) {
|
|
3354
|
+
if (this.fatalError) return Promise.reject(this.fatalError);
|
|
2752
3355
|
const { function_id, payload, action, timeoutMs, metadata } = request;
|
|
2753
3356
|
const effectiveTimeout = timeoutMs ?? this.invocationTimeoutMs;
|
|
2754
3357
|
const outgoing = this.outgoingFields(request);
|
|
@@ -2769,7 +3372,7 @@ var Sdk = class {
|
|
|
2769
3372
|
const timeout = setTimeout(() => {
|
|
2770
3373
|
if (this.invocations.get(invocation_id)) {
|
|
2771
3374
|
this.invocations.delete(invocation_id);
|
|
2772
|
-
reject(
|
|
3375
|
+
reject(new InvocationTimeoutError(effectiveTimeout, function_id));
|
|
2773
3376
|
}
|
|
2774
3377
|
}, effectiveTimeout);
|
|
2775
3378
|
this.invocations.set(invocation_id, {
|
|
@@ -2796,13 +3399,30 @@ var Sdk = class {
|
|
|
2796
3399
|
});
|
|
2797
3400
|
}
|
|
2798
3401
|
/**
|
|
2799
|
-
*
|
|
2800
|
-
*
|
|
2801
|
-
*
|
|
2802
|
-
*
|
|
2803
|
-
*
|
|
3402
|
+
* Runs a call's delivery inside `ctx`: the function's deliver hook, or
|
|
3403
|
+
* iii's delivery to its observers. The hook sees the invocation up to its
|
|
3404
|
+
* first `await`, and counts as delivering until it settles, so the calls it
|
|
3405
|
+
* makes after an `await` fall back to the invocation while it is the only
|
|
3406
|
+
* one running (`callContext`).
|
|
3407
|
+
*/
|
|
3408
|
+
deliverIn(ctx, delivery, hook) {
|
|
3409
|
+
if (hook === void 0) return delivery.run(void 0);
|
|
3410
|
+
const untrack = trackDelivering(ctx);
|
|
3411
|
+
return runInContext(ctx, () => delivery.run(hook)).finally(untrack);
|
|
3412
|
+
}
|
|
3413
|
+
/**
|
|
3414
|
+
* The local path (sdk.md §4.3): runs the handler in-process inside a new
|
|
3415
|
+
* invocation context, then delivers the call (the function's deliver hook,
|
|
3416
|
+
* or iii's delivery to its observers); the same timeout and the same
|
|
3417
|
+
* rejection value as the remote path. A call of a function nobody observes
|
|
3418
|
+
* and without a deliver hook puts nothing on the wire.
|
|
3419
|
+
*
|
|
3420
|
+
* The handler gets a copy of the payload and the caller a copy of the
|
|
3421
|
+
* result; a private function's input and result pass by reference.
|
|
2804
3422
|
*/
|
|
2805
|
-
invokeLocal(function_id,
|
|
3423
|
+
invokeLocal(function_id, fn, request) {
|
|
3424
|
+
const { observe } = fn;
|
|
3425
|
+
const handler = fn.handler;
|
|
2806
3426
|
const parent = callContext();
|
|
2807
3427
|
const caller = this.workerId !== void 0 ? {
|
|
2808
3428
|
worker_id: this.workerId,
|
|
@@ -2819,51 +3439,62 @@ var Sdk = class {
|
|
|
2819
3439
|
invocation_id: randomUUID(),
|
|
2820
3440
|
caller,
|
|
2821
3441
|
observe_depth: parent ? parent.observe_depth : callDepth(),
|
|
2822
|
-
metadata: request.metadata,
|
|
2823
3442
|
localDepth: callLocalDepth() + 1
|
|
2824
3443
|
};
|
|
2825
3444
|
const traceparent = request.traceparent ?? parent?.traceparent;
|
|
2826
3445
|
const baggage = request.baggage ?? parent?.baggage;
|
|
2827
3446
|
if (traceparent !== void 0) ctx.traceparent = traceparent;
|
|
2828
3447
|
if (baggage !== void 0) ctx.baggage = baggage;
|
|
2829
|
-
const
|
|
3448
|
+
const snapshot = observe.compiled;
|
|
3449
|
+
const activations = observe.activations;
|
|
3450
|
+
const hook = this.functionHooks.get(function_id)?.deliver;
|
|
3451
|
+
const delivering = hook !== void 0 || snapshot.length > 0;
|
|
3452
|
+
const byReference = fn.message.private === true;
|
|
2830
3453
|
let input;
|
|
2831
|
-
let observedInput;
|
|
2832
|
-
let observedMetadata;
|
|
2833
3454
|
let metadata;
|
|
3455
|
+
let callInput;
|
|
3456
|
+
let callMetadata;
|
|
2834
3457
|
try {
|
|
2835
|
-
if (
|
|
2836
|
-
|
|
2837
|
-
|
|
3458
|
+
if (byReference) {
|
|
3459
|
+
callInput = request.payload;
|
|
3460
|
+
callMetadata = request.metadata;
|
|
3461
|
+
input = this.resolveChannelValue(request.payload);
|
|
3462
|
+
metadata = request.metadata;
|
|
3463
|
+
} else {
|
|
3464
|
+
if (delivering) {
|
|
3465
|
+
callInput = cloneValue(request.payload);
|
|
3466
|
+
callMetadata = request.metadata === void 0 ? void 0 : cloneValue(request.metadata);
|
|
3467
|
+
}
|
|
3468
|
+
input = this.resolveChannelValue(cloneValue(request.payload));
|
|
3469
|
+
metadata = request.metadata === void 0 ? void 0 : cloneValue(request.metadata);
|
|
2838
3470
|
}
|
|
2839
|
-
input = this.resolveChannelValue(cloneValue(request.payload));
|
|
2840
|
-
metadata = request.metadata === void 0 ? void 0 : cloneValue(request.metadata);
|
|
2841
3471
|
} catch (error) {
|
|
2842
3472
|
return Promise.reject(error);
|
|
2843
3473
|
}
|
|
2844
3474
|
const startedAt = Date.now();
|
|
2845
3475
|
const t0 = performance.now();
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
input: observedInput,
|
|
2854
|
-
output,
|
|
2855
|
-
error,
|
|
2856
|
-
caller: ctx.caller,
|
|
2857
|
-
metadata: observedMetadata,
|
|
2858
|
-
started_at_ms: startedAt,
|
|
2859
|
-
duration_ms: duration,
|
|
2860
|
-
observe_depth: ctx.observe_depth,
|
|
2861
|
-
traceparent,
|
|
2862
|
-
baggage
|
|
2863
|
-
});
|
|
2864
|
-
} catch (reportError) {
|
|
2865
|
-
this.logError(`Failed to report a local invocation of ${function_id}`, reportError);
|
|
3476
|
+
let delivery;
|
|
3477
|
+
const settle = (handled) => {
|
|
3478
|
+
const duration = performance.now() - t0;
|
|
3479
|
+
this.reporter.recordLocal(function_id, handled.ok, duration);
|
|
3480
|
+
if (!delivering) {
|
|
3481
|
+
if (handled.ok) return handled.value;
|
|
3482
|
+
throw handled.error;
|
|
2866
3483
|
}
|
|
3484
|
+
const outcome = byReference ? handled : this.deliveredOutcome(handled, input, callInput);
|
|
3485
|
+
delivery = new Delivery(observe, {
|
|
3486
|
+
call: this.callOf(function_id, ctx.invocation_id, outcome, callInput, ctx.caller, callMetadata),
|
|
3487
|
+
thrown: outcome.ok ? void 0 : outcome.error,
|
|
3488
|
+
snapshot,
|
|
3489
|
+
activations,
|
|
3490
|
+
started_at_ms: startedAt,
|
|
3491
|
+
duration_ms: duration,
|
|
3492
|
+
observe_depth: ctx.observe_depth,
|
|
3493
|
+
traceparent,
|
|
3494
|
+
baggage,
|
|
3495
|
+
routed: false
|
|
3496
|
+
});
|
|
3497
|
+
return this.deliverIn(ctx, delivery, hook);
|
|
2867
3498
|
};
|
|
2868
3499
|
const effectiveTimeout = request.timeoutMs ?? this.invocationTimeoutMs;
|
|
2869
3500
|
const untrack = trackRunning(ctx, effectiveTimeout);
|
|
@@ -2873,15 +3504,18 @@ var Sdk = class {
|
|
|
2873
3504
|
} catch (error) {
|
|
2874
3505
|
started = Promise.reject(error);
|
|
2875
3506
|
}
|
|
2876
|
-
const done = started.then((
|
|
3507
|
+
const done = started.then((value) => settle({
|
|
3508
|
+
ok: true,
|
|
3509
|
+
value
|
|
3510
|
+
}), (error) => settle({
|
|
3511
|
+
ok: false,
|
|
3512
|
+
error
|
|
3513
|
+
})).then((output) => {
|
|
2877
3514
|
untrack();
|
|
2878
|
-
finish(true, output, void 0);
|
|
2879
3515
|
return output;
|
|
2880
3516
|
}, (error) => {
|
|
2881
3517
|
untrack();
|
|
2882
|
-
|
|
2883
|
-
finish(false, void 0, body);
|
|
2884
|
-
throw body;
|
|
3518
|
+
throw delivery ? delivery.errorBody(error) : handlerErrorBody(error);
|
|
2885
3519
|
});
|
|
2886
3520
|
if (request.action?.type === "void") {
|
|
2887
3521
|
done.catch((error) => this.logError(`Error invoking function ${function_id}`, error));
|
|
@@ -2892,7 +3526,7 @@ var Sdk = class {
|
|
|
2892
3526
|
done.then((output) => {
|
|
2893
3527
|
if (timeout !== void 0) clearTimeout(timeout);
|
|
2894
3528
|
try {
|
|
2895
|
-
resolve(cloneValue(output));
|
|
3529
|
+
resolve(byReference ? output : cloneValue(output));
|
|
2896
3530
|
} catch (error) {
|
|
2897
3531
|
reject(error);
|
|
2898
3532
|
}
|
|
@@ -2901,10 +3535,37 @@ var Sdk = class {
|
|
|
2901
3535
|
reject(error);
|
|
2902
3536
|
});
|
|
2903
3537
|
timeout = setTimeout(() => {
|
|
2904
|
-
reject(
|
|
3538
|
+
reject(new InvocationTimeoutError(effectiveTimeout, function_id));
|
|
2905
3539
|
}, effectiveTimeout);
|
|
2906
3540
|
});
|
|
2907
3541
|
}
|
|
3542
|
+
/**
|
|
3543
|
+
* The outcome a local call of a function that is not private is delivered
|
|
3544
|
+
* with: a handler that returns its own input unchanged is delivered with
|
|
3545
|
+
* the input the call started with as its output, so the report carries the
|
|
3546
|
+
* value once (`output_is_input`, decision 4).
|
|
3547
|
+
*/
|
|
3548
|
+
deliveredOutcome(outcome, input, callInput) {
|
|
3549
|
+
if (!outcome.ok) return outcome;
|
|
3550
|
+
return outcome.value === input && input !== null && typeof input === "object" && sameData(callInput, input) ? {
|
|
3551
|
+
ok: true,
|
|
3552
|
+
value: callInput
|
|
3553
|
+
} : outcome;
|
|
3554
|
+
}
|
|
3555
|
+
/** The {@link Call} a finished handler made: what it was called with, and what it returned or threw. */
|
|
3556
|
+
callOf(function_id, invocation_id, outcome, input, caller, metadata) {
|
|
3557
|
+
const call = {
|
|
3558
|
+
function_id,
|
|
3559
|
+
invocation_id,
|
|
3560
|
+
status: outcome.ok ? "success" : "error",
|
|
3561
|
+
input
|
|
3562
|
+
};
|
|
3563
|
+
if (outcome.ok) call.output = outcome.value;
|
|
3564
|
+
else call.error = handlerErrorBody(outcome.error);
|
|
3565
|
+
if (caller !== void 0) call.caller = caller;
|
|
3566
|
+
if (metadata !== void 0) call.metadata = metadata;
|
|
3567
|
+
return call;
|
|
3568
|
+
}
|
|
2908
3569
|
setConnectionState(state) {
|
|
2909
3570
|
if (this.connectionState !== state) {
|
|
2910
3571
|
this.connectionState = state;
|
|
@@ -2962,6 +3623,8 @@ var Sdk = class {
|
|
|
2962
3623
|
}
|
|
2963
3624
|
this.ws = void 0;
|
|
2964
3625
|
this.registeredOnConnection = false;
|
|
3626
|
+
this.observesSent.clear();
|
|
3627
|
+
for (const functionId of [...this.standbyTimers.keys()]) this.stopStandby(functionId);
|
|
2965
3628
|
if (this.isShuttingDown) return;
|
|
2966
3629
|
this.setConnectionState("disconnected");
|
|
2967
3630
|
this.scheduleReconnect();
|
|
@@ -2972,6 +3635,7 @@ var Sdk = class {
|
|
|
2972
3635
|
this.setConnectionState("connected");
|
|
2973
3636
|
this.connectionEpoch++;
|
|
2974
3637
|
this.registeredOnConnection = false;
|
|
3638
|
+
this.observesSent.clear();
|
|
2975
3639
|
if (this.ws) this.ws.onmessage = this.onMessage.bind(this);
|
|
2976
3640
|
if (this.workerId) try {
|
|
2977
3641
|
this.sendMessageRaw(JSON.stringify({
|
|
@@ -2984,15 +3648,7 @@ var Sdk = class {
|
|
|
2984
3648
|
console.error("[iii] Reattach JSON envelope rejected", error);
|
|
2985
3649
|
}
|
|
2986
3650
|
this.registerWorkerMetadata();
|
|
2987
|
-
this.
|
|
2988
|
-
this.replayRegistration("registertriggertype", message);
|
|
2989
|
-
});
|
|
2990
|
-
this.functions.forEach(({ message }) => {
|
|
2991
|
-
this.replayRegistration("registerfunction", message);
|
|
2992
|
-
});
|
|
2993
|
-
this.triggers.forEach((trigger) => {
|
|
2994
|
-
this.replayRegistration("registertrigger", trigger);
|
|
2995
|
-
});
|
|
3651
|
+
this.sendRegistrations();
|
|
2996
3652
|
const pending = this.messagesToSend;
|
|
2997
3653
|
this.messagesToSend = [];
|
|
2998
3654
|
for (const message of pending) {
|
|
@@ -3019,13 +3675,31 @@ var Sdk = class {
|
|
|
3019
3675
|
console.error("[iii] Registration JSON envelope rejected", error);
|
|
3020
3676
|
}
|
|
3021
3677
|
}
|
|
3678
|
+
/**
|
|
3679
|
+
* The `payload_too_large` error that replaces an answer too large to send
|
|
3680
|
+
* is not the handler's outcome, so it activates no observer: to an engine
|
|
3681
|
+
* with `observe.v2` it says `delivered` when the deliver hook delivered the
|
|
3682
|
+
* call (`answer.delivered`), and `matched: []` otherwise, whatever the
|
|
3683
|
+
* function's hooks. An engine without `observe.v2` gets the bare error.
|
|
3684
|
+
*/
|
|
3685
|
+
oversizedAnswer(answer, fallback) {
|
|
3686
|
+
if (!this.engineFeatures.has("observe.v2")) return fallback;
|
|
3687
|
+
if (answer.delivered === true) return {
|
|
3688
|
+
...fallback,
|
|
3689
|
+
delivered: true
|
|
3690
|
+
};
|
|
3691
|
+
return {
|
|
3692
|
+
...fallback,
|
|
3693
|
+
matched: []
|
|
3694
|
+
};
|
|
3695
|
+
}
|
|
3022
3696
|
prepareJson(message) {
|
|
3023
3697
|
const data = JSON.stringify(message);
|
|
3024
3698
|
const size = JSON_ENCODER.encode(data).byteLength;
|
|
3025
3699
|
if (size <= MAX_JSON_FRAME_BYTES) return data;
|
|
3026
3700
|
const error = createPayloadTooLargeError(size, typeof message.function_id === "string" ? message.function_id : void 0);
|
|
3027
3701
|
if (message.type === "invocationresult") {
|
|
3028
|
-
const fallback = JSON.stringify({
|
|
3702
|
+
const fallback = JSON.stringify(this.oversizedAnswer(message, {
|
|
3029
3703
|
type: "invocationresult",
|
|
3030
3704
|
invocation_id: message.invocation_id,
|
|
3031
3705
|
function_id: message.function_id,
|
|
@@ -3033,7 +3707,7 @@ var Sdk = class {
|
|
|
3033
3707
|
code: error.code,
|
|
3034
3708
|
message: payloadTooLargeMessage(size)
|
|
3035
3709
|
}
|
|
3036
|
-
});
|
|
3710
|
+
}));
|
|
3037
3711
|
if (JSON_ENCODER.encode(fallback).byteLength <= MAX_JSON_FRAME_BYTES) return fallback;
|
|
3038
3712
|
}
|
|
3039
3713
|
if (typeof message.invocation_id === "string") {
|
|
@@ -3053,30 +3727,6 @@ var Sdk = class {
|
|
|
3053
3727
|
}
|
|
3054
3728
|
toWireFormat(messageType, message) {
|
|
3055
3729
|
const { message_type: _, ...rest } = message;
|
|
3056
|
-
if (messageType === "registertrigger" && "type" in message) {
|
|
3057
|
-
const { type: triggerType, ...triggerRest } = message;
|
|
3058
|
-
return {
|
|
3059
|
-
type: messageType,
|
|
3060
|
-
...triggerRest,
|
|
3061
|
-
trigger_type: triggerType
|
|
3062
|
-
};
|
|
3063
|
-
}
|
|
3064
|
-
if (messageType === "unregistertrigger" && "type" in message) {
|
|
3065
|
-
const { type: triggerType, ...triggerRest } = message;
|
|
3066
|
-
return {
|
|
3067
|
-
type: messageType,
|
|
3068
|
-
...triggerRest,
|
|
3069
|
-
trigger_type: triggerType
|
|
3070
|
-
};
|
|
3071
|
-
}
|
|
3072
|
-
if (messageType === "triggerregistrationresult" && "type" in message) {
|
|
3073
|
-
const { type: triggerType, ...resultRest } = message;
|
|
3074
|
-
return {
|
|
3075
|
-
type: messageType,
|
|
3076
|
-
...resultRest,
|
|
3077
|
-
trigger_type: triggerType
|
|
3078
|
-
};
|
|
3079
|
-
}
|
|
3080
3730
|
return {
|
|
3081
3731
|
type: messageType,
|
|
3082
3732
|
...rest
|
|
@@ -3150,23 +3800,60 @@ var Sdk = class {
|
|
|
3150
3800
|
}
|
|
3151
3801
|
async onInvokeFunction(invocation_id, function_id, input, metadata, traceparent, baggage, observeFields = {}) {
|
|
3152
3802
|
const fn = this.functions.get(function_id);
|
|
3153
|
-
const resolvedInput = this.resolveChannelValue(input);
|
|
3154
3803
|
if (fn?.handler) {
|
|
3155
3804
|
const handler = fn.handler;
|
|
3156
3805
|
const ctx = {
|
|
3157
3806
|
function_id,
|
|
3158
3807
|
invocation_id: invocation_id ?? randomUUID(),
|
|
3159
|
-
observe_depth: observeFields.observe_depth ?? 0
|
|
3160
|
-
metadata
|
|
3808
|
+
observe_depth: observeFields.observe_depth ?? 0
|
|
3161
3809
|
};
|
|
3162
3810
|
if (observeFields.caller) ctx.caller = observeFields.caller;
|
|
3163
3811
|
if (observeFields.activation) ctx.activation = observeFields.activation;
|
|
3164
3812
|
if (traceparent !== void 0) ctx.traceparent = traceparent;
|
|
3165
3813
|
if (baggage !== void 0) ctx.baggage = baggage;
|
|
3814
|
+
const snapshot = fn.observe.compiled;
|
|
3815
|
+
const activations = fn.observe.activations;
|
|
3816
|
+
const hook = this.functionHooks.get(function_id)?.deliver;
|
|
3817
|
+
const answering = this.engineFeatures.has(FEATURE_OBSERVE_V2);
|
|
3818
|
+
const startedAt = Date.now();
|
|
3819
|
+
const t0 = performance.now();
|
|
3820
|
+
let delivery;
|
|
3821
|
+
let matched;
|
|
3822
|
+
const resolvedInput = this.resolveChannelValue(input);
|
|
3166
3823
|
const run = async () => {
|
|
3167
3824
|
const untrack = trackRunning(ctx, MAX_RUNNING_INVOCATION_MS);
|
|
3168
3825
|
try {
|
|
3169
|
-
|
|
3826
|
+
let outcome;
|
|
3827
|
+
try {
|
|
3828
|
+
outcome = {
|
|
3829
|
+
ok: true,
|
|
3830
|
+
value: await runInContext(ctx, () => handler(resolvedInput, metadata))
|
|
3831
|
+
};
|
|
3832
|
+
} catch (error) {
|
|
3833
|
+
outcome = {
|
|
3834
|
+
ok: false,
|
|
3835
|
+
error
|
|
3836
|
+
};
|
|
3837
|
+
}
|
|
3838
|
+
const narrowed = answering && hook === void 0 && fn.observe.hasMatchHook();
|
|
3839
|
+
if (!answering || hook === void 0 && (!narrowed || snapshot.length === 0)) {
|
|
3840
|
+
if (narrowed) matched = [];
|
|
3841
|
+
if (outcome.ok) return outcome.value;
|
|
3842
|
+
throw outcome.error;
|
|
3843
|
+
}
|
|
3844
|
+
delivery = new Delivery(fn.observe, {
|
|
3845
|
+
call: this.callOf(function_id, ctx.invocation_id, outcome, input, ctx.caller, metadata),
|
|
3846
|
+
thrown: outcome.ok ? void 0 : outcome.error,
|
|
3847
|
+
snapshot,
|
|
3848
|
+
activations,
|
|
3849
|
+
started_at_ms: startedAt,
|
|
3850
|
+
duration_ms: performance.now() - t0,
|
|
3851
|
+
observe_depth: ctx.observe_depth,
|
|
3852
|
+
traceparent,
|
|
3853
|
+
baggage,
|
|
3854
|
+
routed: true
|
|
3855
|
+
});
|
|
3856
|
+
return await this.deliverIn(ctx, delivery, hook);
|
|
3170
3857
|
} finally {
|
|
3171
3858
|
untrack();
|
|
3172
3859
|
}
|
|
@@ -3181,26 +3868,30 @@ var Sdk = class {
|
|
|
3181
3868
|
}
|
|
3182
3869
|
try {
|
|
3183
3870
|
const result = await run();
|
|
3184
|
-
this.sendMessage("invocationresult", {
|
|
3871
|
+
this.sendMessage("invocationresult", buildInvocationResult({
|
|
3185
3872
|
invocation_id,
|
|
3186
3873
|
function_id,
|
|
3187
3874
|
result,
|
|
3188
3875
|
traceparent,
|
|
3189
|
-
baggage
|
|
3190
|
-
|
|
3876
|
+
baggage,
|
|
3877
|
+
matched: delivery ? delivery.matched : matched,
|
|
3878
|
+
delivered: delivery?.delivered
|
|
3879
|
+
}));
|
|
3191
3880
|
} catch (error) {
|
|
3192
|
-
this.sendMessage("invocationresult", {
|
|
3881
|
+
this.sendMessage("invocationresult", buildInvocationResult({
|
|
3193
3882
|
invocation_id,
|
|
3194
3883
|
function_id,
|
|
3195
|
-
error: handlerErrorBody(error),
|
|
3884
|
+
error: delivery ? delivery.errorBody(error) : handlerErrorBody(error),
|
|
3196
3885
|
traceparent,
|
|
3197
|
-
baggage
|
|
3198
|
-
|
|
3886
|
+
baggage,
|
|
3887
|
+
matched: delivery ? delivery.matched : matched,
|
|
3888
|
+
delivered: delivery?.delivered
|
|
3889
|
+
}));
|
|
3199
3890
|
}
|
|
3200
3891
|
} else {
|
|
3201
3892
|
const errorCode = fn ? "function_not_invokable" : "function_not_found";
|
|
3202
3893
|
const errorMessage = fn ? "Function is HTTP-invoked and cannot be invoked locally" : "Function not found";
|
|
3203
|
-
if (invocation_id) this.sendMessage("invocationresult", {
|
|
3894
|
+
if (invocation_id) this.sendMessage("invocationresult", buildInvocationResult({
|
|
3204
3895
|
invocation_id,
|
|
3205
3896
|
function_id,
|
|
3206
3897
|
error: {
|
|
@@ -3209,62 +3900,7 @@ var Sdk = class {
|
|
|
3209
3900
|
},
|
|
3210
3901
|
traceparent,
|
|
3211
3902
|
baggage
|
|
3212
|
-
});
|
|
3213
|
-
}
|
|
3214
|
-
}
|
|
3215
|
-
async onRegisterTrigger(message) {
|
|
3216
|
-
const { trigger_type, id, function_id, config, namespace } = message;
|
|
3217
|
-
const triggerTypeData = this.triggerTypes.get(trigger_type);
|
|
3218
|
-
if (triggerTypeData) try {
|
|
3219
|
-
await triggerTypeData.handler.registerTrigger({
|
|
3220
|
-
id,
|
|
3221
|
-
function_id,
|
|
3222
|
-
config,
|
|
3223
|
-
namespace
|
|
3224
|
-
});
|
|
3225
|
-
this.sendMessage("triggerregistrationresult", {
|
|
3226
|
-
id,
|
|
3227
|
-
message_type: "triggerregistrationresult",
|
|
3228
|
-
type: trigger_type,
|
|
3229
|
-
function_id
|
|
3230
|
-
});
|
|
3231
|
-
} catch (error) {
|
|
3232
|
-
this.sendMessage("triggerregistrationresult", {
|
|
3233
|
-
id,
|
|
3234
|
-
message_type: "triggerregistrationresult",
|
|
3235
|
-
type: trigger_type,
|
|
3236
|
-
function_id,
|
|
3237
|
-
error: {
|
|
3238
|
-
code: "trigger_registration_failed",
|
|
3239
|
-
message: error.message
|
|
3240
|
-
}
|
|
3241
|
-
});
|
|
3242
|
-
}
|
|
3243
|
-
else this.sendMessage("triggerregistrationresult", {
|
|
3244
|
-
id,
|
|
3245
|
-
message_type: "triggerregistrationresult",
|
|
3246
|
-
type: trigger_type,
|
|
3247
|
-
function_id,
|
|
3248
|
-
error: {
|
|
3249
|
-
code: "trigger_type_not_found",
|
|
3250
|
-
message: "Trigger type not found"
|
|
3251
|
-
}
|
|
3252
|
-
});
|
|
3253
|
-
}
|
|
3254
|
-
async onUnregisterTrigger(message) {
|
|
3255
|
-
const trigger_type = message.trigger_type;
|
|
3256
|
-
if (!trigger_type) return;
|
|
3257
|
-
const triggerTypeData = this.triggerTypes.get(trigger_type);
|
|
3258
|
-
if (!triggerTypeData) return;
|
|
3259
|
-
const { id, function_id = "", config } = message;
|
|
3260
|
-
try {
|
|
3261
|
-
await triggerTypeData.handler.unregisterTrigger({
|
|
3262
|
-
id,
|
|
3263
|
-
function_id,
|
|
3264
|
-
config
|
|
3265
|
-
});
|
|
3266
|
-
} catch (error) {
|
|
3267
|
-
console.error(`[iii] Error unregistering trigger ${id}`, error);
|
|
3903
|
+
}));
|
|
3268
3904
|
}
|
|
3269
3905
|
}
|
|
3270
3906
|
onMessage(event) {
|
|
@@ -3291,23 +3927,27 @@ var Sdk = class {
|
|
|
3291
3927
|
});
|
|
3292
3928
|
} else if (msgType === "functionregistered") {
|
|
3293
3929
|
const msg = decodeFunctionRegistered(message);
|
|
3294
|
-
this.functions.get(msg.id)
|
|
3930
|
+
const fn = this.functions.get(msg.id);
|
|
3931
|
+
if (fn && fn.sentEpoch === this.connectionEpoch) {
|
|
3932
|
+
this.stopStandby(msg.id);
|
|
3933
|
+
fn.standingBy = false;
|
|
3934
|
+
fn.observe.onFunctionRegistered(msg, this.connectionEpoch);
|
|
3935
|
+
}
|
|
3295
3936
|
} else if (msgType === "observeradded") {
|
|
3296
3937
|
const msg = decodeObserverAdded(message);
|
|
3297
|
-
this.functions.get(msg.function_id)
|
|
3938
|
+
const fn = this.functions.get(msg.function_id);
|
|
3939
|
+
if (fn && fn.sentEpoch === this.connectionEpoch) fn.observe.onObserverAdded(msg);
|
|
3298
3940
|
} else if (msgType === "observerremoved") {
|
|
3299
3941
|
const msg = decodeObserverRemoved(message);
|
|
3300
|
-
this.functions.get(msg.function_id)?.observe
|
|
3942
|
+
this.functions.get(msg.function_id)?.observe.onObserverRemoved(msg);
|
|
3301
3943
|
} else if (msgType === "observeresult") {
|
|
3302
3944
|
const msg = decodeObserveResult(message);
|
|
3303
|
-
if (msg.warnings && msg.warnings.length > 0)
|
|
3304
|
-
this.
|
|
3945
|
+
if (msg.warnings && msg.warnings.length > 0) this.logWarn(`Observer ${msg.id}: ${msg.warnings.join("; ")}`);
|
|
3946
|
+
this.onObserveResult(msg.id, msg.state, msg.error);
|
|
3305
3947
|
} else if (msgType === "observerstatechanged") {
|
|
3306
3948
|
const msg = decodeObserverStateChanged(message);
|
|
3307
|
-
this.
|
|
3308
|
-
} else if (msgType === "
|
|
3309
|
-
else if (msgType === "unregistertrigger") this.onUnregisterTrigger(message);
|
|
3310
|
-
else if (msgType === "registrationrejected") this.onRegistrationRejected(message);
|
|
3949
|
+
this.onObserverStateChanged(msg.id, msg.state, msg.reason);
|
|
3950
|
+
} else if (msgType === "registrationrejected") this.onRegistrationRejected(decodeRegistrationRejected(message));
|
|
3311
3951
|
else if (msgType === "workerregistered") {
|
|
3312
3952
|
const { worker_id, reattach_token, features } = decodeWorkerRegistered(message);
|
|
3313
3953
|
this.workerId = worker_id;
|
|
@@ -3316,51 +3956,118 @@ var Sdk = class {
|
|
|
3316
3956
|
}
|
|
3317
3957
|
}
|
|
3318
3958
|
/**
|
|
3319
|
-
* `WorkerRegistered` told this connection what the engine supports.
|
|
3320
|
-
* `observe.
|
|
3321
|
-
*
|
|
3322
|
-
*
|
|
3959
|
+
* `WorkerRegistered` told this connection what the engine supports. The
|
|
3960
|
+
* functions that need `observe.v2` go out now, or stay unregistered without
|
|
3961
|
+
* it; without it, one sent earlier on this connection that has gained a
|
|
3962
|
+
* match or deliver hook since is unregistered. With `observe.v1` the observers the
|
|
3963
|
+
* engine has not refused are replayed (after the functions) and held reports flushed; without it
|
|
3964
|
+
* `observe()` fails with `UNSUPPORTED` and observer hooks are inactive.
|
|
3323
3965
|
*/
|
|
3324
3966
|
onEngineFeatures(features) {
|
|
3325
3967
|
this.engineFeatures = new Set(features);
|
|
3326
3968
|
this.registeredOnConnection = true;
|
|
3969
|
+
this.sendRegistrations();
|
|
3970
|
+
for (const [functionId, fn] of this.functions) if (fn.sentEpoch === this.connectionEpoch) this.reconcileRegistration(functionId);
|
|
3971
|
+
this.warnUnregisteredHookIds();
|
|
3327
3972
|
const queued = this.observeQueue;
|
|
3328
3973
|
this.observeQueue = [];
|
|
3329
3974
|
if (this.engineFeatures.has("observe.v1")) {
|
|
3330
3975
|
for (const frame of queued) this.sendMessageRaw(JSON.stringify(frame));
|
|
3331
|
-
for (const handle of this.
|
|
3976
|
+
for (const handle of this.observerHandles.values()) if (!handle.refused) this.sendObserve(handle);
|
|
3332
3977
|
this.reporter.flush();
|
|
3333
3978
|
return;
|
|
3334
3979
|
}
|
|
3335
|
-
for (const handle of this.
|
|
3336
|
-
for (const
|
|
3980
|
+
for (const handle of this.observerHandles.values()) if (!handle.refused) handle.setState("error", UNSUPPORTED_REASON);
|
|
3981
|
+
for (const functionId of this.functions.keys()) if (this.hasObserverHooks(functionId)) this.warnHooksInactive(functionId);
|
|
3337
3982
|
this.reporter.clear();
|
|
3338
3983
|
}
|
|
3339
|
-
|
|
3340
|
-
|
|
3984
|
+
/**
|
|
3985
|
+
* An `observeresult`: the answer to the oldest `observe` of the id sent on
|
|
3986
|
+
* this connection that has none yet. The engine answers every `observe`
|
|
3987
|
+
* once, in the order it read them (decision 56).
|
|
3988
|
+
*/
|
|
3989
|
+
onObserveResult(id, wireState, reason) {
|
|
3990
|
+
const handle = this.observesSent.get(id)?.find((h) => !h.answered);
|
|
3341
3991
|
if (!handle) return;
|
|
3992
|
+
handle.answered = true;
|
|
3993
|
+
if (toObserverState(wireState) === "error") {
|
|
3994
|
+
handle.sent = false;
|
|
3995
|
+
handle.refused = true;
|
|
3996
|
+
this.unlistObserve(handle);
|
|
3997
|
+
handle.setState("error", reason ? {
|
|
3998
|
+
code: reason.code,
|
|
3999
|
+
message: reason.message
|
|
4000
|
+
} : void 0);
|
|
4001
|
+
return;
|
|
4002
|
+
}
|
|
4003
|
+
if (handle.state === "disposed") this.unlistObserve(handle);
|
|
4004
|
+
else this.applyObserverState(handle, wireState, reason);
|
|
4005
|
+
}
|
|
4006
|
+
/**
|
|
4007
|
+
* An `observerstatechanged`: about the newest observer of the id whose
|
|
4008
|
+
* `observeresult` arrived on this connection. One that arrives before any
|
|
4009
|
+
* did is dropped: a reattached connection hears its observers resume
|
|
4010
|
+
* before its replayed `observe`s are answered, and each answer carries the
|
|
4011
|
+
* current state (decision 56).
|
|
4012
|
+
*/
|
|
4013
|
+
onObserverStateChanged(id, wireState, reason) {
|
|
4014
|
+
const sent = this.observesSent.get(id);
|
|
4015
|
+
if (!sent) return;
|
|
4016
|
+
for (let at = sent.length - 1; at >= 0; at--) if (sent[at].answered) {
|
|
4017
|
+
this.applyObserverState(sent[at], wireState, reason);
|
|
4018
|
+
return;
|
|
4019
|
+
}
|
|
4020
|
+
}
|
|
4021
|
+
/** A state from the engine for `handle`; `disposed` frees its id. */
|
|
4022
|
+
applyObserverState(handle, wireState, reason) {
|
|
3342
4023
|
const state = toObserverState(wireState);
|
|
3343
4024
|
handle.setState(state, reason ? {
|
|
3344
4025
|
code: reason.code,
|
|
3345
4026
|
message: reason.message
|
|
3346
4027
|
} : void 0);
|
|
3347
|
-
if (state
|
|
4028
|
+
if (state !== "disposed") return;
|
|
4029
|
+
this.unlistObserve(handle);
|
|
4030
|
+
if (this.observerHandles.get(handle.id) === handle) this.observerHandles.delete(handle.id);
|
|
4031
|
+
}
|
|
4032
|
+
unlistObserve(handle) {
|
|
4033
|
+
const sent = this.observesSent.get(handle.id);
|
|
4034
|
+
const at = sent ? sent.indexOf(handle) : -1;
|
|
4035
|
+
if (!sent || at < 0) return;
|
|
4036
|
+
sent.splice(at, 1);
|
|
4037
|
+
if (sent.length === 0) this.observesSent.delete(handle.id);
|
|
3348
4038
|
}
|
|
3349
4039
|
/**
|
|
3350
|
-
* The engine rejected a registration.
|
|
3351
|
-
*
|
|
3352
|
-
*
|
|
3353
|
-
*
|
|
3354
|
-
*
|
|
3355
|
-
*
|
|
4040
|
+
* The engine rejected a registration. The `code` decides the severity:
|
|
4041
|
+
*
|
|
4042
|
+
* - {@link FUNCTION_NAMESPACE_CONFLICT}: another live worker in this
|
|
4043
|
+
* namespace already exports this one function id. Only that registration
|
|
4044
|
+
* is refused; the connection stays open and the worker keeps serving its
|
|
4045
|
+
* other functions. A `standby` function retries its registration until
|
|
4046
|
+
* the id is free.
|
|
4047
|
+
* - {@link FUNCTION_REJECTIONS} on one function: only that function is
|
|
4048
|
+
* refused. Logged; the worker keeps serving.
|
|
4049
|
+
* - {@link WORKER_NAMESPACE_CONFLICT}, or any other code: terminal — stop and
|
|
4050
|
+
* do not reconnect (otherwise the engine would only reject the same name
|
|
4051
|
+
* again, which with `maxRetries: -1` loops forever).
|
|
3356
4052
|
*/
|
|
3357
4053
|
onRegistrationRejected(init) {
|
|
3358
|
-
if (init.code ===
|
|
3359
|
-
|
|
3360
|
-
|
|
4054
|
+
if (init.code === FUNCTION_NAMESPACE_CONFLICT) {
|
|
4055
|
+
const fn = init.function_id !== void 0 ? this.functions.get(init.function_id) : void 0;
|
|
4056
|
+
fn?.observe.onRegistrationRejected(this.connectionEpoch);
|
|
4057
|
+
if (fn?.standby && init.function_id !== void 0) {
|
|
4058
|
+
this.standBy(init.function_id, fn, init.owner_worker_id);
|
|
4059
|
+
return;
|
|
4060
|
+
}
|
|
4061
|
+
this.logWarn(`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.`);
|
|
4062
|
+
return;
|
|
4063
|
+
}
|
|
4064
|
+
if (FUNCTION_REJECTIONS.has(init.code) && init.function_id !== void 0) {
|
|
4065
|
+
this.functions.get(init.function_id)?.observe.onRegistrationRejected(this.connectionEpoch);
|
|
4066
|
+
this.logError(`Function registration rejected with ${init.code}: function "${init.function_id}" in namespace "${init.namespace}" is not registered. Staying connected and serving the rest.`);
|
|
3361
4067
|
return;
|
|
3362
4068
|
}
|
|
3363
|
-
|
|
4069
|
+
if (init.code === WORKER_NAMESPACE_CONFLICT) this.logError(`Registration rejected (${init.code}): worker "${init.worker_name}" in namespace "${init.namespace}" is already owned by ${init.owner_worker_id}. Not reconnecting.`);
|
|
4070
|
+
else this.logError(`Registration rejected by engine with unknown code "${init.code}"; treating as fatal. Not reconnecting.`);
|
|
3364
4071
|
this.isShuttingDown = true;
|
|
3365
4072
|
this.clearReconnectTimeout();
|
|
3366
4073
|
const error = new RegistrationRejectedError(init);
|
|
@@ -3373,30 +4080,56 @@ var Sdk = class {
|
|
|
3373
4080
|
this.setConnectionState("failed");
|
|
3374
4081
|
this.ws?.close();
|
|
3375
4082
|
}
|
|
4083
|
+
/**
|
|
4084
|
+
* A `standby` function whose id another connection hosts (decision 21): its
|
|
4085
|
+
* registration is retried every second (±20 %) until the engine accepts it
|
|
4086
|
+
* (`functionregistered`, whose observers then run their hooks here) or the
|
|
4087
|
+
* function is unregistered.
|
|
4088
|
+
*/
|
|
4089
|
+
standBy(functionId, fn, owner) {
|
|
4090
|
+
if (this.standbyTimers.has(functionId)) return;
|
|
4091
|
+
if (!fn.standingBy) this.logInfo(`Function "${functionId}" is hosted by worker ${owner}; standing by to take it over when it leaves.`);
|
|
4092
|
+
fn.standingBy = true;
|
|
4093
|
+
const delay = Math.floor(STANDBY_RETRY_MS * (.8 + .4 * Math.random()));
|
|
4094
|
+
const timer = setTimeout(() => {
|
|
4095
|
+
this.standbyTimers.delete(functionId);
|
|
4096
|
+
if (this.functions.get(functionId) !== fn || !this.mayRegister(functionId, fn)) return;
|
|
4097
|
+
this.replayRegistration("registerfunction", fn.message);
|
|
4098
|
+
fn.sentEpoch = this.connectionEpoch;
|
|
4099
|
+
}, delay);
|
|
4100
|
+
unrefTimer(timer);
|
|
4101
|
+
this.standbyTimers.set(functionId, timer);
|
|
4102
|
+
}
|
|
4103
|
+
stopStandby(functionId) {
|
|
4104
|
+
const timer = this.standbyTimers.get(functionId);
|
|
4105
|
+
if (!timer) return;
|
|
4106
|
+
clearTimeout(timer);
|
|
4107
|
+
this.standbyTimers.delete(functionId);
|
|
4108
|
+
}
|
|
3376
4109
|
};
|
|
3377
4110
|
/**
|
|
3378
|
-
* Factory object that constructs routing actions for {@link ISdk.
|
|
4111
|
+
* Factory object that constructs routing actions for {@link ISdk.call}.
|
|
3379
4112
|
*
|
|
3380
4113
|
* @example
|
|
3381
4114
|
* ```typescript
|
|
3382
|
-
* import {
|
|
4115
|
+
* import { CallAction } from 'iii-browser-sdk'
|
|
3383
4116
|
*
|
|
3384
4117
|
* // Enqueue to a named queue
|
|
3385
|
-
* worker.
|
|
4118
|
+
* worker.call({
|
|
3386
4119
|
* function_id: 'process',
|
|
3387
4120
|
* payload: { data: 'hello' },
|
|
3388
|
-
* action:
|
|
4121
|
+
* action: CallAction.Enqueue({ queue: 'jobs' }),
|
|
3389
4122
|
* })
|
|
3390
4123
|
*
|
|
3391
4124
|
* // Fire-and-forget
|
|
3392
|
-
* worker.
|
|
4125
|
+
* worker.call({
|
|
3393
4126
|
* function_id: 'notify',
|
|
3394
4127
|
* payload: {},
|
|
3395
|
-
* action:
|
|
4128
|
+
* action: CallAction.Void(),
|
|
3396
4129
|
* })
|
|
3397
4130
|
* ```
|
|
3398
4131
|
*/
|
|
3399
|
-
const
|
|
4132
|
+
const CallAction = {
|
|
3400
4133
|
/**
|
|
3401
4134
|
* Routes the invocation through a named queue. The engine enqueues the job,
|
|
3402
4135
|
* acknowledges the caller with `{ messageReceiptId }`, and processes it
|
|
@@ -3415,6 +4148,8 @@ const TriggerAction = {
|
|
|
3415
4148
|
*/
|
|
3416
4149
|
Void: () => ({ type: "void" })
|
|
3417
4150
|
};
|
|
4151
|
+
/** @deprecated Use {@link CallAction}, the same object. */
|
|
4152
|
+
const TriggerAction = CallAction;
|
|
3418
4153
|
/**
|
|
3419
4154
|
* Register the worker with a iii instance, returns a connected worker client.
|
|
3420
4155
|
* The WebSocket connection is established automatically.
|
|
@@ -3433,5 +4168,5 @@ const TriggerAction = {
|
|
|
3433
4168
|
const registerWorker = (address, options) => new Sdk(address, options);
|
|
3434
4169
|
|
|
3435
4170
|
//#endregion
|
|
3436
|
-
export { ChannelReader, ChannelWriter, EngineFunctions,
|
|
4171
|
+
export { CallAction, ChannelReader, ChannelWriter, EngineFunctions, EngineSources, InvocationError, ObserveRejection, RegistrationRejectedError, TriggerAction, registerWorker };
|
|
3437
4172
|
//# sourceMappingURL=index.mjs.map
|