@syntropika/tembra-sdk 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -17
- package/dist/authoring/types.d.ts +64 -3
- package/dist/authoring/wit.d.ts +6 -0
- package/dist/bridge/commands.d.ts +1190 -0
- package/dist/bridge/identifiers.d.ts +2 -0
- package/dist/bridge/kernel.d.ts +18 -107
- package/dist/bridge/protocol.d.ts +3 -138
- package/dist/browser.d.ts +14 -1
- package/dist/browser.js +141 -3298
- package/dist/chunks/browser-b8jamxw2.js +3399 -0
- package/dist/chunks/execution-nsqc6nrt.js +1419 -0
- package/dist/chunks/index-01zk0xqx.js +160 -0
- package/dist/chunks/index-3fjdfdfd.js +152 -0
- package/dist/chunks/index-aaymjn7v.js +787 -0
- package/dist/chunks/index-c1w7z9hx.js +356 -0
- package/dist/chunks/index-h8t0n42q.js +738 -0
- package/dist/chunks/index-hfds9mzp.js +308 -0
- package/dist/chunks/index-kr4x67wt.js +177 -0
- package/dist/chunks/index-kr6bnh34.js +117 -0
- package/dist/chunks/index-kyt9dj0a.js +1421 -0
- package/dist/chunks/index-n1wxzc9w.js +830 -0
- package/dist/chunks/index-pvac426d.js +74 -0
- package/dist/chunks/index-smyds5ce.js +3234 -0
- package/dist/chunks/index-sse8aapb.js +121 -0
- package/dist/chunks/index-v6heph77.js +643 -0
- package/dist/chunks/index-xrdvnv37.js +3448 -0
- package/dist/chunks/index-za4mg94e.js +26 -0
- package/dist/chunks/index-zkqmnjj8.js +167 -0
- package/dist/coordinator.js +9 -500
- package/dist/error.d.ts +2 -0
- package/dist/errors.d.ts +3 -0
- package/dist/guest.d.ts +173 -0
- package/dist/guest.js +26 -0
- package/dist/host.d.ts +36 -30
- package/dist/host.js +37 -3276
- package/dist/http/bytes.d.ts +8 -0
- package/dist/http/events.d.ts +7 -0
- package/dist/http.d.ts +45 -0
- package/dist/http.js +291 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +49 -862
- package/dist/infrastructure/rpc/client.d.ts +2 -1
- package/dist/infrastructure/rpc/resources.d.ts +28 -0
- package/dist/interpreter/abi.d.ts +54 -0
- package/dist/interpreter/acquire.d.ts +18 -0
- package/dist/interpreter/browser-network.d.ts +52 -0
- package/dist/interpreter/browser-port.d.ts +55 -0
- package/dist/interpreter/browser.d.ts +79 -0
- package/dist/interpreter/cli.d.ts +5 -0
- package/dist/interpreter/codec.d.ts +42 -0
- package/dist/interpreter/component/execution.d.ts +42 -0
- package/dist/interpreter/component/host.d.ts +69 -0
- package/dist/interpreter/component/instance.d.ts +40 -0
- package/dist/interpreter/component/kernel.d.ts +120 -0
- package/dist/interpreter/component/names.d.ts +5 -0
- package/dist/interpreter/component/port.d.ts +85 -0
- package/dist/interpreter/component/prepared.d.ts +97 -0
- package/dist/interpreter/component/resources.d.ts +45 -0
- package/dist/interpreter/component/revision.d.ts +87 -0
- package/dist/interpreter/component/scope.d.ts +116 -0
- package/dist/interpreter/component/streams.d.ts +28 -0
- package/dist/interpreter/component/values.d.ts +79 -0
- package/dist/interpreter/component/wasi-filesystem.d.ts +21 -0
- package/dist/interpreter/component/wasi-host.d.ts +64 -0
- package/dist/interpreter/component/wasi-http.d.ts +33 -0
- package/dist/interpreter/component/wasi-sockets.d.ts +183 -0
- package/dist/interpreter/component/wasi.d.ts +41 -0
- package/dist/interpreter/core.d.ts +64 -0
- package/dist/interpreter/fetch-http-provider.d.ts +17 -0
- package/dist/interpreter/filesystem/contract.d.ts +85 -0
- package/dist/interpreter/filesystem/memory.d.ts +3 -0
- package/dist/interpreter/filesystem/opfs.d.ts +3 -0
- package/dist/interpreter/filesystem/scope.d.ts +35 -0
- package/dist/interpreter/filesystem.d.ts +8 -0
- package/dist/interpreter/gate.d.ts +6 -0
- package/dist/interpreter/host-protocol.d.ts +100 -0
- package/dist/interpreter/http-ingress-fetch.d.ts +7 -0
- package/dist/interpreter/http-ingress.d.ts +96 -0
- package/dist/interpreter/http-provider.d.ts +85 -0
- package/dist/interpreter/io.d.ts +20 -0
- package/dist/interpreter/mobile.d.ts +149 -0
- package/dist/interpreter/native-ingress.d.ts +95 -0
- package/dist/interpreter/node-port.d.ts +25 -0
- package/dist/interpreter/node.d.ts +36 -0
- package/dist/interpreter/revision.d.ts +64 -0
- package/dist/interpreter/scope.d.ts +89 -0
- package/dist/interpreter/socket-addresses.d.ts +50 -0
- package/dist/interpreter/socket-provider.d.ts +110 -0
- package/dist/interpreter/standard-cli.d.ts +34 -0
- package/dist/interpreter/standard-codec.d.ts +96 -0
- package/dist/interpreter/standard-filesystem.d.ts +47 -0
- package/dist/interpreter/standard-host.d.ts +71 -0
- package/dist/interpreter/standard-http-values.d.ts +159 -0
- package/dist/interpreter/standard-http.d.ts +9 -0
- package/dist/interpreter/standard-ingress.d.ts +63 -0
- package/dist/interpreter/standard-sockets.d.ts +177 -0
- package/dist/interpreter/standard-streams.d.ts +218 -0
- package/dist/interpreter/standard-system.d.ts +35 -0
- package/dist/interpreter/standard-utf8.d.ts +4 -0
- package/dist/interpreter/standard.d.ts +18 -0
- package/dist/interpreter/types.d.ts +152 -0
- package/dist/interpreter/wit-shape.d.ts +92 -0
- package/dist/manager.js +5 -332
- package/dist/msgpack.js +9 -615
- package/dist/node.d.ts +8 -1
- package/dist/node.js +248 -3287
- package/dist/rpc.js +196 -699
- package/dist/runtime/adapters.d.ts +120 -0
- package/dist/runtime/adapters.js +38 -0
- package/dist/runtime/calls.d.ts +9 -3
- package/dist/runtime/lifecycle.d.ts +3 -1
- package/dist/runtime/orbs.d.ts +5 -4
- package/dist/runtime/references.d.ts +27 -1
- package/dist/runtime/reload.d.ts +5 -3
- package/dist/runtime/scopes.d.ts +1 -1
- package/dist/runtime/signals.d.ts +4 -0
- package/dist/runtime/wit-client.d.ts +38 -0
- package/dist/telemetry.js +4 -25
- package/dist/tooling/build.d.ts +2 -2
- package/dist/tooling/client-resources.d.ts +23 -0
- package/dist/tooling/client.d.ts +10 -0
- package/dist/tooling/component-glue.d.ts +17 -0
- package/dist/tooling/component.d.ts +11 -0
- package/dist/tooling/index.d.ts +3 -1
- package/dist/tooling/index.js +1155 -102
- package/dist/tooling/resolver.d.ts +4 -4
- package/dist/tooling/typecheck.d.ts +2 -1
- package/dist/tooling/types.d.ts +27 -12
- package/dist/tooling/wit.d.ts +9 -0
- package/dist/wasi/wasi-clocks-types.d.ts +2 -0
- package/dist/wasi/wasi-http-client.d.ts +5 -0
- package/dist/wasi/wasi-http-types.d.ts +285 -0
- package/dist/wasi/wasi-sockets-ip-name-lookup.d.ts +23 -0
- package/dist/wasi/wasi-sockets-types.d.ts +146 -0
- package/package.json +62 -35
- package/src/authoring/declaration.ts +1 -1
- package/src/authoring/types.ts +53 -3
- package/src/authoring/wit.ts +15 -0
- package/src/bridge/commands.ts +1105 -0
- package/src/bridge/identifiers.ts +2 -0
- package/src/bridge/kernel.ts +56 -98
- package/src/bridge/protocol.ts +3 -142
- package/src/browser.ts +90 -6
- package/src/context-key.ts +4 -7
- package/src/error.ts +1 -1
- package/src/errors.ts +7 -0
- package/src/guest.ts +327 -0
- package/src/host.ts +128 -23
- package/src/http/bytes.ts +87 -0
- package/src/http/events.ts +34 -0
- package/src/http.ts +272 -0
- package/src/index.ts +3 -0
- package/src/infrastructure/rpc/client.ts +136 -17
- package/src/infrastructure/rpc/resources.ts +123 -0
- package/src/interpreter/abi.ts +69 -0
- package/src/interpreter/acquire.ts +58 -0
- package/src/interpreter/browser-network.ts +170 -0
- package/src/interpreter/browser-port.ts +425 -0
- package/src/interpreter/browser.ts +340 -0
- package/src/interpreter/cli.ts +30 -0
- package/src/interpreter/codec.ts +298 -0
- package/src/interpreter/component/execution.ts +264 -0
- package/src/interpreter/component/host.ts +409 -0
- package/src/interpreter/component/instance.ts +138 -0
- package/src/interpreter/component/kernel.ts +611 -0
- package/src/interpreter/component/names.ts +13 -0
- package/src/interpreter/component/port.ts +598 -0
- package/src/interpreter/component/prepared.ts +194 -0
- package/src/interpreter/component/resources.ts +345 -0
- package/src/interpreter/component/revision.ts +702 -0
- package/src/interpreter/component/scope.ts +447 -0
- package/src/interpreter/component/streams.ts +180 -0
- package/src/interpreter/component/values.ts +254 -0
- package/src/interpreter/component/wasi-filesystem.ts +472 -0
- package/src/interpreter/component/wasi-host.ts +197 -0
- package/src/interpreter/component/wasi-http.ts +939 -0
- package/src/interpreter/component/wasi-sockets.ts +958 -0
- package/src/interpreter/component/wasi.ts +238 -0
- package/src/interpreter/core.ts +386 -0
- package/src/interpreter/fetch-http-provider.ts +98 -0
- package/src/interpreter/filesystem/contract.ts +138 -0
- package/src/interpreter/filesystem/memory.ts +180 -0
- package/src/interpreter/filesystem/opfs.ts +294 -0
- package/src/interpreter/filesystem/scope.ts +390 -0
- package/src/interpreter/filesystem.ts +20 -0
- package/src/interpreter/gate.ts +55 -0
- package/src/interpreter/host-protocol.ts +242 -0
- package/src/interpreter/http-ingress-fetch.ts +133 -0
- package/src/interpreter/http-ingress.ts +203 -0
- package/src/interpreter/http-provider.ts +105 -0
- package/src/interpreter/io.ts +66 -0
- package/src/interpreter/mobile.ts +385 -0
- package/src/interpreter/native-ingress.ts +550 -0
- package/src/interpreter/node-port.ts +218 -0
- package/src/interpreter/node.ts +114 -0
- package/src/interpreter/revision.ts +450 -0
- package/src/interpreter/scope.ts +453 -0
- package/src/interpreter/socket-addresses.ts +246 -0
- package/src/interpreter/socket-provider.ts +126 -0
- package/src/interpreter/standard-cli.ts +184 -0
- package/src/interpreter/standard-codec.ts +403 -0
- package/src/interpreter/standard-filesystem.ts +545 -0
- package/src/interpreter/standard-host.ts +840 -0
- package/src/interpreter/standard-http-values.ts +624 -0
- package/src/interpreter/standard-http.ts +622 -0
- package/src/interpreter/standard-ingress.ts +344 -0
- package/src/interpreter/standard-sockets.ts +847 -0
- package/src/interpreter/standard-streams.ts +710 -0
- package/src/interpreter/standard-system.ts +182 -0
- package/src/interpreter/standard-utf8.ts +72 -0
- package/src/interpreter/standard.ts +283 -0
- package/src/interpreter/types.ts +163 -0
- package/src/interpreter/wit-shape.ts +175 -0
- package/src/node.ts +43 -14
- package/src/runtime/activities.ts +6 -6
- package/src/runtime/adapters.ts +314 -0
- package/src/runtime/calls.ts +218 -56
- package/src/runtime/context.ts +7 -7
- package/src/runtime/lifecycle.ts +36 -17
- package/src/runtime/orbs.ts +81 -39
- package/src/runtime/programs.ts +16 -8
- package/src/runtime/references.ts +128 -11
- package/src/runtime/reload.ts +71 -30
- package/src/runtime/resources.ts +2 -2
- package/src/runtime/scopes.ts +17 -17
- package/src/runtime/session.ts +3 -1
- package/src/runtime/signals.ts +31 -0
- package/src/runtime/wit-client.ts +228 -0
- package/src/tooling/build.ts +152 -54
- package/src/tooling/client-resources.ts +74 -0
- package/src/tooling/client.ts +531 -0
- package/src/tooling/component-glue.ts +288 -0
- package/src/tooling/component.ts +225 -0
- package/src/tooling/index.ts +3 -7
- package/src/tooling/resolver.ts +42 -25
- package/src/tooling/typecheck.ts +59 -4
- package/src/tooling/types.ts +27 -12
- package/src/tooling/wit.ts +188 -0
- package/dist/embedded.d.ts +0 -1
- package/dist/embedded.js +0 -1
- package/src/embedded.ts +0 -293
|
@@ -0,0 +1,3448 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Code2,
|
|
3
|
+
Reason2,
|
|
4
|
+
Lifetime2,
|
|
5
|
+
Status2,
|
|
6
|
+
ReloadStatus2,
|
|
7
|
+
Errors2,
|
|
8
|
+
TembraError2,
|
|
9
|
+
failure,
|
|
10
|
+
refuse
|
|
11
|
+
} from "./index-c1w7z9hx.js";
|
|
12
|
+
import {
|
|
13
|
+
shapes,
|
|
14
|
+
lift,
|
|
15
|
+
VALUE_LIMIT,
|
|
16
|
+
Encoded,
|
|
17
|
+
encode,
|
|
18
|
+
check,
|
|
19
|
+
checkedResult,
|
|
20
|
+
reply,
|
|
21
|
+
refusal,
|
|
22
|
+
packet,
|
|
23
|
+
Context,
|
|
24
|
+
issuedContext,
|
|
25
|
+
context,
|
|
26
|
+
Values,
|
|
27
|
+
StateBinding,
|
|
28
|
+
validate,
|
|
29
|
+
Declaration,
|
|
30
|
+
deferred,
|
|
31
|
+
References,
|
|
32
|
+
checkSignal,
|
|
33
|
+
combinedSignal
|
|
34
|
+
} from "./index-kyt9dj0a.js";
|
|
35
|
+
import {
|
|
36
|
+
KernelOp,
|
|
37
|
+
OwnerKind,
|
|
38
|
+
ActionType,
|
|
39
|
+
EffectType,
|
|
40
|
+
EnvironmentPhase,
|
|
41
|
+
Outcome
|
|
42
|
+
} from "./index-kr4x67wt.js";
|
|
43
|
+
import {
|
|
44
|
+
jsonCodec2
|
|
45
|
+
} from "./index-sse8aapb.js";
|
|
46
|
+
import {
|
|
47
|
+
Telemetry2
|
|
48
|
+
} from "./index-za4mg94e.js";
|
|
49
|
+
import {
|
|
50
|
+
cliPacket,
|
|
51
|
+
bindCaptured2,
|
|
52
|
+
capturedMethod2,
|
|
53
|
+
capturedDataMethod2,
|
|
54
|
+
declareFactory2,
|
|
55
|
+
validateEnvironment2,
|
|
56
|
+
isolate2,
|
|
57
|
+
signature2,
|
|
58
|
+
signatures2,
|
|
59
|
+
disposeOrb2,
|
|
60
|
+
releaseEnvironment2,
|
|
61
|
+
isolatedRevision2,
|
|
62
|
+
admitFactory2,
|
|
63
|
+
prepareDefinitions2,
|
|
64
|
+
discardDefinitions2,
|
|
65
|
+
disposeDefinitions2,
|
|
66
|
+
captureEnvironment2
|
|
67
|
+
} from "./index-zkqmnjj8.js";
|
|
68
|
+
import {
|
|
69
|
+
HTTP_HANDLER,
|
|
70
|
+
HttpHandlerError2,
|
|
71
|
+
CONNECTION_TERMINATED,
|
|
72
|
+
IngressExchange,
|
|
73
|
+
checkedRequest,
|
|
74
|
+
byteString,
|
|
75
|
+
bytesOf,
|
|
76
|
+
answer,
|
|
77
|
+
query,
|
|
78
|
+
TYPES,
|
|
79
|
+
METHODS,
|
|
80
|
+
Reader,
|
|
81
|
+
decode
|
|
82
|
+
} from "./index-h8t0n42q.js";
|
|
83
|
+
import {
|
|
84
|
+
orb3,
|
|
85
|
+
series3,
|
|
86
|
+
waterfall3,
|
|
87
|
+
bail3
|
|
88
|
+
} from "./index-01zk0xqx.js";
|
|
89
|
+
|
|
90
|
+
// src/bridge/kernel.ts
|
|
91
|
+
var empty = Object.freeze({});
|
|
92
|
+
|
|
93
|
+
class Kernel {
|
|
94
|
+
port;
|
|
95
|
+
features;
|
|
96
|
+
constructor(port) {
|
|
97
|
+
this.port = port;
|
|
98
|
+
this.features = this.command(KernelOp.Features);
|
|
99
|
+
}
|
|
100
|
+
check(root, call) {
|
|
101
|
+
const error = this.port.check(root, call);
|
|
102
|
+
if (error !== undefined && error !== null)
|
|
103
|
+
throw new TembraError2(JSON.parse(error));
|
|
104
|
+
}
|
|
105
|
+
command(op, ...[input]) {
|
|
106
|
+
const outcome = this.port.command(op, input ?? empty);
|
|
107
|
+
if (outcome.error)
|
|
108
|
+
throw new TembraError2(outcome.error);
|
|
109
|
+
return outcome.ok;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// src/runtime/activities.ts
|
|
114
|
+
class Activities {
|
|
115
|
+
session;
|
|
116
|
+
tasks = new Map;
|
|
117
|
+
listeners = new Map;
|
|
118
|
+
#identities = new WeakMap;
|
|
119
|
+
constructor(session) {
|
|
120
|
+
this.session = session;
|
|
121
|
+
}
|
|
122
|
+
prepare(environment, previous) {
|
|
123
|
+
for (const definition of environment.listeners) {
|
|
124
|
+
const source = typeof definition.source === "function" ? definition.source() : definition.source;
|
|
125
|
+
if (!source || typeof source.subscribe !== "function")
|
|
126
|
+
refuse(Errors2.Invalid.EventSource);
|
|
127
|
+
const id = this.session.kernel.command(KernelOp.Listen, {
|
|
128
|
+
scope: environment.id,
|
|
129
|
+
previous: previous?.id,
|
|
130
|
+
name: definition.name,
|
|
131
|
+
source: this.identity(source),
|
|
132
|
+
sizing: definition.options.sizeOf ? this.identity(definition.options.sizeOf) : 0,
|
|
133
|
+
operation: this.session.kernel.command(KernelOp.Allocate),
|
|
134
|
+
maxPending: definition.options.maxPending ?? 64,
|
|
135
|
+
...definition.options.maxBytes ? { maxBytes: definition.options.maxBytes } : {},
|
|
136
|
+
coalesce: "select" in source
|
|
137
|
+
});
|
|
138
|
+
const existing = this.listeners.get(id);
|
|
139
|
+
if (existing) {
|
|
140
|
+
definition.running = existing;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
const record = {
|
|
144
|
+
id,
|
|
145
|
+
definition,
|
|
146
|
+
environment,
|
|
147
|
+
stopped: false,
|
|
148
|
+
detach() {}
|
|
149
|
+
};
|
|
150
|
+
definition.running = record;
|
|
151
|
+
this.listeners.set(id, record);
|
|
152
|
+
try {
|
|
153
|
+
record.detach = source.subscribe((value) => {
|
|
154
|
+
if (record.stopped)
|
|
155
|
+
return;
|
|
156
|
+
const payload = this.session.values.put(value);
|
|
157
|
+
try {
|
|
158
|
+
const bytes = definition.options.sizeOf?.(value) ?? 0;
|
|
159
|
+
if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > 4294967295)
|
|
160
|
+
throw new TembraError2(Errors2.Invalid.SubscriptionSize);
|
|
161
|
+
this.session.kernel.command(KernelOp.Enqueue, { subscription: id, payload, bytes });
|
|
162
|
+
} catch (error) {
|
|
163
|
+
this.session.values.drop(payload);
|
|
164
|
+
this.session.report(error);
|
|
165
|
+
this.failed(id);
|
|
166
|
+
}
|
|
167
|
+
this.session.lifecycle.flush();
|
|
168
|
+
});
|
|
169
|
+
if (record.stopped)
|
|
170
|
+
record.detach();
|
|
171
|
+
} catch (error) {
|
|
172
|
+
this.stopListener(record);
|
|
173
|
+
throw error;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
start(environment) {
|
|
178
|
+
environment.phase = EnvironmentPhase.Live;
|
|
179
|
+
for (const definition of environment.listeners) {
|
|
180
|
+
const record = definition.running;
|
|
181
|
+
record.environment = environment;
|
|
182
|
+
record.definition = definition;
|
|
183
|
+
}
|
|
184
|
+
for (const task of environment.tasks)
|
|
185
|
+
this.startTask(environment, task);
|
|
186
|
+
}
|
|
187
|
+
startTask(environment, definition) {
|
|
188
|
+
if (definition.running || environment.phase !== EnvironmentPhase.Live || this.session.closing)
|
|
189
|
+
return;
|
|
190
|
+
const id = this.session.kernel.command(KernelOp.Task, { owner: environment.owner });
|
|
191
|
+
const controller = new AbortController;
|
|
192
|
+
const operation = this.session.kernel.command(KernelOp.Allocate);
|
|
193
|
+
const record = { id, controller, done: Promise.resolve() };
|
|
194
|
+
definition.running = record;
|
|
195
|
+
this.tasks.set(id, record);
|
|
196
|
+
record.done = this.session.track(Promise.resolve().then(async () => {
|
|
197
|
+
try {
|
|
198
|
+
await definition.start({
|
|
199
|
+
signal: controller.signal,
|
|
200
|
+
root: (callback) => {
|
|
201
|
+
const root = this.session.kernel.command(KernelOp.TaskRoot, {
|
|
202
|
+
task: id,
|
|
203
|
+
principal: this.session.principalFor(environment.object?.id ?? 0)
|
|
204
|
+
});
|
|
205
|
+
return this.session.calls.root(() => this.session.calls.owned(environment, operation, callback, root), false, root);
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
} catch (error) {
|
|
209
|
+
if (!controller.signal.aborted)
|
|
210
|
+
this.session.report(error);
|
|
211
|
+
} finally {
|
|
212
|
+
this.session.kernel.command(KernelOp.Tick, { now: this.session.now() });
|
|
213
|
+
this.session.kernel.command(KernelOp.FinishTask, { task: id });
|
|
214
|
+
this.tasks.delete(id);
|
|
215
|
+
delete definition.running;
|
|
216
|
+
this.session.lifecycle.flush();
|
|
217
|
+
}
|
|
218
|
+
}));
|
|
219
|
+
}
|
|
220
|
+
identity(value) {
|
|
221
|
+
let id = this.#identities.get(value);
|
|
222
|
+
if (id === undefined) {
|
|
223
|
+
id = this.session.kernel.command(KernelOp.Allocate);
|
|
224
|
+
this.#identities.set(value, id);
|
|
225
|
+
}
|
|
226
|
+
return id;
|
|
227
|
+
}
|
|
228
|
+
deliver(subscription, payload, operation) {
|
|
229
|
+
const record = this.listeners.get(subscription);
|
|
230
|
+
const job = Promise.resolve().then(async () => {
|
|
231
|
+
try {
|
|
232
|
+
if (!record)
|
|
233
|
+
throw new TembraError2(Errors2.Gone.ListenerCallback);
|
|
234
|
+
await this.session.calls.owned(record.environment, operation, (ctx) => record.definition.handle(ctx, this.session.values.get(payload)));
|
|
235
|
+
} catch (error) {
|
|
236
|
+
this.session.report(error);
|
|
237
|
+
} finally {
|
|
238
|
+
this.session.kernel.command(KernelOp.FinishDelivery, { subscription });
|
|
239
|
+
this.session.lifecycle.flush();
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
if (record)
|
|
243
|
+
record.done = job;
|
|
244
|
+
this.session.track(job);
|
|
245
|
+
}
|
|
246
|
+
detach(id) {
|
|
247
|
+
const record = this.listeners.get(id);
|
|
248
|
+
if (record)
|
|
249
|
+
this.stopListener(record);
|
|
250
|
+
}
|
|
251
|
+
cancel(id) {
|
|
252
|
+
this.tasks.get(id)?.controller.abort(new TembraError2(Errors2.Cancelled.Task));
|
|
253
|
+
}
|
|
254
|
+
failed(id) {
|
|
255
|
+
const record = this.listeners.get(id);
|
|
256
|
+
if (!record)
|
|
257
|
+
return;
|
|
258
|
+
this.session.report(new TembraError2(Errors2.Exhausted.SubscriptionQueue));
|
|
259
|
+
this.stopListener(record);
|
|
260
|
+
}
|
|
261
|
+
stopListener(record) {
|
|
262
|
+
if (record.stopped)
|
|
263
|
+
return;
|
|
264
|
+
record.stopped = true;
|
|
265
|
+
try {
|
|
266
|
+
record.detach();
|
|
267
|
+
} catch (error) {
|
|
268
|
+
this.session.report(error);
|
|
269
|
+
}
|
|
270
|
+
this.session.kernel.command(KernelOp.Unsubscribe, { subscription: record.id });
|
|
271
|
+
this.listeners.delete(record.id);
|
|
272
|
+
this.session.lifecycle.flush();
|
|
273
|
+
}
|
|
274
|
+
async stop(environment) {
|
|
275
|
+
for (const definition of environment.tasks) {
|
|
276
|
+
if (definition.running)
|
|
277
|
+
this.session.kernel.command(KernelOp.StopTask, { task: definition.running.id });
|
|
278
|
+
}
|
|
279
|
+
this.session.lifecycle.flush();
|
|
280
|
+
await Promise.all(environment.tasks.map((task) => task.running?.done));
|
|
281
|
+
await Promise.all(environment.listeners.map((listener) => listener.running?.done));
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// src/runtime/calls.ts
|
|
286
|
+
class Calls {
|
|
287
|
+
session;
|
|
288
|
+
#rootCapabilities = new Map;
|
|
289
|
+
constructor(session) {
|
|
290
|
+
this.session = session;
|
|
291
|
+
}
|
|
292
|
+
execute(operation) {
|
|
293
|
+
return Promise.resolve().then(operation);
|
|
294
|
+
}
|
|
295
|
+
signal(root) {
|
|
296
|
+
const session = this.session;
|
|
297
|
+
let controller = session.controllers.get(root);
|
|
298
|
+
if (!controller) {
|
|
299
|
+
controller = new AbortController;
|
|
300
|
+
try {
|
|
301
|
+
session.kernel.command(KernelOp.CheckRoot, { root });
|
|
302
|
+
} catch (error) {
|
|
303
|
+
if (!(error instanceof TembraError2) || error.code !== Code2.Cancelled)
|
|
304
|
+
throw error;
|
|
305
|
+
controller.abort(error);
|
|
306
|
+
}
|
|
307
|
+
session.controllers.set(root, controller);
|
|
308
|
+
}
|
|
309
|
+
return controller.signal;
|
|
310
|
+
}
|
|
311
|
+
releaseRoot(root) {
|
|
312
|
+
for (const capability of this.#rootCapabilities.get(root) ?? [])
|
|
313
|
+
capability.close();
|
|
314
|
+
this.#rootCapabilities.delete(root);
|
|
315
|
+
for (const reference of this.session.rootReferences.get(root) ?? [])
|
|
316
|
+
this.session.handles.release(reference);
|
|
317
|
+
this.session.rootReferences.delete(root);
|
|
318
|
+
this.session.controllers.delete(root);
|
|
319
|
+
}
|
|
320
|
+
async root(operation, cleanup = false, issuedRoot, principal = this.session.principal) {
|
|
321
|
+
const session = this.session;
|
|
322
|
+
const root = issuedRoot ?? session.kernel.command(cleanup ? KernelOp.CleanupRoot : KernelOp.Root, {
|
|
323
|
+
principal
|
|
324
|
+
});
|
|
325
|
+
if (issuedRoot === undefined)
|
|
326
|
+
session.controllers.set(root, new AbortController);
|
|
327
|
+
const ctx = new Context(session, root);
|
|
328
|
+
try {
|
|
329
|
+
return await operation(ctx);
|
|
330
|
+
} finally {
|
|
331
|
+
this.releaseRoot(root);
|
|
332
|
+
session.options.native?.rootEnded?.(root);
|
|
333
|
+
if (!session.lifecycle.closedDiagnostics)
|
|
334
|
+
session.lifecycle.endRoot(root);
|
|
335
|
+
session.controllers.delete(root);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
async invoke(reference, method, arguments_, ctx, capture) {
|
|
339
|
+
context(ctx, this.session);
|
|
340
|
+
checkSignal(ctx.signal);
|
|
341
|
+
return this.observe(this.invokePhysical(reference, method, arguments_, ctx, capture), ctx.signal);
|
|
342
|
+
}
|
|
343
|
+
async invokePhysical(reference, method, arguments_, ctx, capture) {
|
|
344
|
+
const session = this.session;
|
|
345
|
+
try {
|
|
346
|
+
context(ctx, session);
|
|
347
|
+
if (reference.released)
|
|
348
|
+
throw new TembraError2(Errors2.Released.Reference);
|
|
349
|
+
await this.observe(reference.ready, ctx.signal);
|
|
350
|
+
const admission = session.options.native?.admit?.(reference.id, method, ctx);
|
|
351
|
+
let invocation;
|
|
352
|
+
if (admission)
|
|
353
|
+
invocation = admission.call;
|
|
354
|
+
else
|
|
355
|
+
invocation = session.kernel.command(KernelOp.AdmitCall, {
|
|
356
|
+
reference: reference.id,
|
|
357
|
+
root: ctx.root,
|
|
358
|
+
parent: ctx.invocation?.id,
|
|
359
|
+
context: ctx.frame || undefined,
|
|
360
|
+
method
|
|
361
|
+
});
|
|
362
|
+
const entered = new Context(session, ctx.root, invocation, ctx.frame);
|
|
363
|
+
const physical = session.track((async () => {
|
|
364
|
+
const sampled = session.telemetry?.sample();
|
|
365
|
+
const started = sampled ? session.now() : 0;
|
|
366
|
+
let outcome = Outcome.Ok;
|
|
367
|
+
let retainedSource;
|
|
368
|
+
let retained;
|
|
369
|
+
let physicalFailure;
|
|
370
|
+
let published = false;
|
|
371
|
+
let capabilities = [];
|
|
372
|
+
let reported = false;
|
|
373
|
+
const reportFailure = (error) => {
|
|
374
|
+
outcome = Outcome.Error;
|
|
375
|
+
if (reported)
|
|
376
|
+
return;
|
|
377
|
+
reported = true;
|
|
378
|
+
const stream = capabilities.find((capability) => capability.kind === "bytes");
|
|
379
|
+
if (stream?.kind === "bytes")
|
|
380
|
+
stream.reportFailure(error, (cause) => session.report(cause));
|
|
381
|
+
else
|
|
382
|
+
session.report(error);
|
|
383
|
+
};
|
|
384
|
+
const retain = (actual) => {
|
|
385
|
+
if (retainedSource) {
|
|
386
|
+
if (retainedSource !== actual)
|
|
387
|
+
throw new Error("One prepared invocation cannot retain different physical operations");
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
retainedSource = actual;
|
|
391
|
+
retained = actual.then(() => {}, (error) => {
|
|
392
|
+
outcome = Outcome.Error;
|
|
393
|
+
physicalFailure = { error };
|
|
394
|
+
});
|
|
395
|
+
};
|
|
396
|
+
const finish = () => {
|
|
397
|
+
if (sampled)
|
|
398
|
+
session.telemetry.record({
|
|
399
|
+
service: reference.address.service,
|
|
400
|
+
method,
|
|
401
|
+
root: invocation.root,
|
|
402
|
+
codeVersion: invocation.codeVersion,
|
|
403
|
+
duration: session.now() - started,
|
|
404
|
+
outcome
|
|
405
|
+
});
|
|
406
|
+
session.lifecycle.finishCall(invocation.id);
|
|
407
|
+
};
|
|
408
|
+
let unlend;
|
|
409
|
+
try {
|
|
410
|
+
const loan = capture?.receiver?.lend();
|
|
411
|
+
unlend = loan;
|
|
412
|
+
const native = session.options.native;
|
|
413
|
+
if (native && (admission?.native ?? native.hasOrb(invocation.orb))) {
|
|
414
|
+
if (capture && (!capture.dataResult || capture.receiver || capture.arguments?.owners.length))
|
|
415
|
+
throw new Error("Provider does not support the matching WIT capability signature");
|
|
416
|
+
return await native.invoke(invocation, arguments_, entered);
|
|
417
|
+
}
|
|
418
|
+
const object = session.objects.get(invocation.object);
|
|
419
|
+
const environment = object?.versions.get(invocation.orb);
|
|
420
|
+
const handle = environment?.orb.definition.services?.[reference.address.service]?.methods[method];
|
|
421
|
+
if (!environment || !handle)
|
|
422
|
+
throw new TembraError2(Errors2.Gone.Implementation);
|
|
423
|
+
const prepared = capture && capturedMethod2(handle, capture.signature);
|
|
424
|
+
if (prepared) {
|
|
425
|
+
const output = await this.execute(() => prepared.invoke(environment.value, entered, capture.input, loan?.receiver, retain, capture.arguments));
|
|
426
|
+
if (output instanceof Encoded)
|
|
427
|
+
capture.output = output;
|
|
428
|
+
else {
|
|
429
|
+
capabilities = output.capabilities ?? [];
|
|
430
|
+
published = true;
|
|
431
|
+
if (output.finished) {
|
|
432
|
+
session.track(output.finished.catch((error) => {
|
|
433
|
+
reportFailure(error);
|
|
434
|
+
throw error;
|
|
435
|
+
}));
|
|
436
|
+
if (!retainedSource) {
|
|
437
|
+
for (const capability of capabilities)
|
|
438
|
+
capability.close();
|
|
439
|
+
throw new Error("A prepared continuation must retain its actual physical operation");
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
try {
|
|
443
|
+
checkSignal(entered.signal);
|
|
444
|
+
for (const capability of capabilities) {
|
|
445
|
+
if (capability.kind === "resource")
|
|
446
|
+
capability.anchor(session, reference);
|
|
447
|
+
else {
|
|
448
|
+
capability.bind(entered);
|
|
449
|
+
let owned = this.#rootCapabilities.get(entered.root);
|
|
450
|
+
if (!owned)
|
|
451
|
+
this.#rootCapabilities.set(entered.root, owned = new Set);
|
|
452
|
+
owned.add(capability);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
capture.output = output.value;
|
|
456
|
+
capture.capabilities = capabilities;
|
|
457
|
+
} catch (error) {
|
|
458
|
+
for (const capability of capabilities)
|
|
459
|
+
capability.close();
|
|
460
|
+
throw error;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
if (capture && (!capture.dataResult || capture.receiver || capture.arguments?.owners.length))
|
|
466
|
+
throw new Error("Provider does not support the matching WIT capability signature");
|
|
467
|
+
const data = capturedDataMethod2(handle);
|
|
468
|
+
return await this.execute(() => data ? data(environment.value, entered, arguments_, retain) : handle(environment.value, entered, ...arguments_));
|
|
469
|
+
} catch (error) {
|
|
470
|
+
outcome = Outcome.Error;
|
|
471
|
+
throw error;
|
|
472
|
+
} finally {
|
|
473
|
+
if (retained) {
|
|
474
|
+
session.track(retained.then(() => {
|
|
475
|
+
if (published && physicalFailure)
|
|
476
|
+
reportFailure(physicalFailure.error);
|
|
477
|
+
}).finally(() => {
|
|
478
|
+
unlend?.();
|
|
479
|
+
finish();
|
|
480
|
+
}));
|
|
481
|
+
} else {
|
|
482
|
+
unlend?.();
|
|
483
|
+
finish();
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
})());
|
|
487
|
+
return await physical;
|
|
488
|
+
} finally {
|
|
489
|
+
if (capture?.arguments && !capture.arguments.accepted)
|
|
490
|
+
for (const owner of capture.arguments.owners)
|
|
491
|
+
owner.close();
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
async owned(environment, operation, handle, root) {
|
|
495
|
+
const session = this.session;
|
|
496
|
+
const execute = async (ctx) => {
|
|
497
|
+
const invocation = session.kernel.command(KernelOp.BeginOperation, {
|
|
498
|
+
orb: environment.orb.info.id,
|
|
499
|
+
root: ctx.root,
|
|
500
|
+
context: ctx.frame || undefined,
|
|
501
|
+
operation,
|
|
502
|
+
...environment.object ? { object: environment.object.id } : {}
|
|
503
|
+
});
|
|
504
|
+
try {
|
|
505
|
+
return await this.execute(() => handle(new Context(session, ctx.root, invocation, ctx.frame)));
|
|
506
|
+
} finally {
|
|
507
|
+
session.kernel.command(KernelOp.FinishCall, { call: invocation.id });
|
|
508
|
+
session.lifecycle.flush();
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
return root === undefined ? this.root(execute, false, undefined, session.principalFor(environment.object?.id ?? 0)) : execute(typeof root === "number" ? new Context(session, root) : root);
|
|
512
|
+
}
|
|
513
|
+
async observe(physical, signal) {
|
|
514
|
+
if (signal.aborted)
|
|
515
|
+
throw signal.reason ?? new TembraError2(Errors2.Cancelled.Root);
|
|
516
|
+
let abort;
|
|
517
|
+
const cancelled = new Promise((_, reject) => {
|
|
518
|
+
abort = () => reject(signal.reason ?? new TembraError2(Errors2.Cancelled.Root));
|
|
519
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
520
|
+
});
|
|
521
|
+
try {
|
|
522
|
+
return await Promise.race([physical, cancelled]);
|
|
523
|
+
} finally {
|
|
524
|
+
signal.removeEventListener("abort", abort);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// src/runtime/orbs.ts
|
|
530
|
+
class Orbs {
|
|
531
|
+
session;
|
|
532
|
+
records = new Map;
|
|
533
|
+
operations = new Map;
|
|
534
|
+
#ready = new Map;
|
|
535
|
+
#ordinals = new Map;
|
|
536
|
+
constructor(session) {
|
|
537
|
+
this.session = session;
|
|
538
|
+
}
|
|
539
|
+
declarations(definitions) {
|
|
540
|
+
const captured = definitions.map((definition) => orb3(definition));
|
|
541
|
+
const current = this.session.kernel.command(KernelOp.Orbs);
|
|
542
|
+
const lookup = (name) => captured.find((f) => f.name === name);
|
|
543
|
+
const metadata = captured.map((definition) => {
|
|
544
|
+
if (!this.session.kernel.features.views && Object.values(definition.services ?? {}).some((service) => service.access))
|
|
545
|
+
throw new TembraError2(Errors2.Unsupported.Views);
|
|
546
|
+
const requires = Object.entries(definition.requires ?? {}).map(([alias, requirement]) => {
|
|
547
|
+
const name = requirement.orb ?? alias;
|
|
548
|
+
const provider = lookup(name);
|
|
549
|
+
const info = current.find((f) => f.name === name);
|
|
550
|
+
const names = provider ? Object.keys(provider.services ?? {}) : info?.services.map((s) => s.name) ?? [];
|
|
551
|
+
const service = names.includes(alias) ? alias : names.length === 1 ? names[0] : undefined;
|
|
552
|
+
if (requirement.methods && !service)
|
|
553
|
+
refuse(Errors2.Invalid.DependencyService, `Use explicit services for ${name}`);
|
|
554
|
+
return {
|
|
555
|
+
orb: name,
|
|
556
|
+
apiVersion: requirement.apiVersion,
|
|
557
|
+
services: requirement.services ?? (requirement.methods ? { [service]: requirement.methods } : {}),
|
|
558
|
+
signatures: requirement[signatures2] ?? {},
|
|
559
|
+
hooks: requirement.hooks ?? [],
|
|
560
|
+
hookSignatures: requirement.hookSignatures ?? {}
|
|
561
|
+
};
|
|
562
|
+
});
|
|
563
|
+
for (const [alias, hooks] of Object.entries(definition.contributes ?? {})) {
|
|
564
|
+
const requirement = definition.requires?.[alias];
|
|
565
|
+
if (!requirement)
|
|
566
|
+
refuse(Errors2.Invalid.HookDependency, alias);
|
|
567
|
+
for (const [hook, contribution] of Object.entries(hooks)) {
|
|
568
|
+
if (!requirement.hooks?.includes(hook))
|
|
569
|
+
refuse(Errors2.Invalid.HookDependency, hook);
|
|
570
|
+
const priority = typeof contribution === "function" ? 0 : contribution.priority ?? 0;
|
|
571
|
+
if (!Number.isInteger(priority) || priority < -2147483648 || priority > 2147483647)
|
|
572
|
+
refuse(Errors2.Invalid.Priority);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
return {
|
|
576
|
+
name: definition.name,
|
|
577
|
+
apiVersion: definition.apiVersion,
|
|
578
|
+
requires,
|
|
579
|
+
hooks: Object.keys(definition.hooks ?? {}),
|
|
580
|
+
hookSignatures: Object.fromEntries(Object.entries(definition.hooks ?? {}).flatMap(([name, hook]) => {
|
|
581
|
+
const prepared = hook[signature2];
|
|
582
|
+
return prepared ? [[name, prepared]] : [];
|
|
583
|
+
})),
|
|
584
|
+
isolated: definition[isolatedRevision2] === true,
|
|
585
|
+
services: Object.entries(definition.services ?? {}).map(([name, service]) => ({
|
|
586
|
+
name,
|
|
587
|
+
methods: Object.keys(service.methods),
|
|
588
|
+
signature: service[signature2],
|
|
589
|
+
lifetime: service.lifetime ?? Lifetime2.Referenced,
|
|
590
|
+
linger: service.linger ?? 0
|
|
591
|
+
}))
|
|
592
|
+
};
|
|
593
|
+
});
|
|
594
|
+
return { definitions: captured, metadata };
|
|
595
|
+
}
|
|
596
|
+
async install(definitions) {
|
|
597
|
+
const candidates = prepareDefinitions2(definitions, this.session.options[isolate2]);
|
|
598
|
+
const materialized = Array.isArray(candidates) ? candidates : await candidates;
|
|
599
|
+
let prepared;
|
|
600
|
+
let reload;
|
|
601
|
+
try {
|
|
602
|
+
if (this.session.closing)
|
|
603
|
+
throw new TembraError2(Errors2.Closed.Host);
|
|
604
|
+
const current = this.session.kernel.command(KernelOp.Orbs);
|
|
605
|
+
if (materialized.some((candidate) => current.some((orb) => orb.name === candidate.name)))
|
|
606
|
+
refuse(Errors2.Invalid.OrbInstalled, "Use reload to replace an installed orb");
|
|
607
|
+
prepared = this.declarations(materialized);
|
|
608
|
+
reload = this.session.kernel.command(KernelOp.Prepare, { orbs: prepared.metadata });
|
|
609
|
+
this.session.kernel.command(KernelOp.Commit, { ticket: reload.id });
|
|
610
|
+
} catch (error) {
|
|
611
|
+
return discardDefinitions2(materialized, error);
|
|
612
|
+
}
|
|
613
|
+
const records = reload.orbs.map((info) => ({
|
|
614
|
+
info,
|
|
615
|
+
definition: prepared.definitions.find((f) => f.name === info.name)
|
|
616
|
+
}));
|
|
617
|
+
for (const record of records)
|
|
618
|
+
this.records.set(record.info.id, record);
|
|
619
|
+
for (const record of records)
|
|
620
|
+
this.registerContributions(record);
|
|
621
|
+
await Promise.all(records.map((record) => this.ready(record)));
|
|
622
|
+
for (const record of records) {
|
|
623
|
+
for (const service of record.info.services.filter((s) => s.lifetime === Lifetime2.Host)) {
|
|
624
|
+
const reference = await this.session.handles.get(service.name, "main", {
|
|
625
|
+
principal: "host"
|
|
626
|
+
});
|
|
627
|
+
reference.release();
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
this.session.lifecycle.flush();
|
|
631
|
+
}
|
|
632
|
+
scope(record) {
|
|
633
|
+
if (record.scope)
|
|
634
|
+
return record.scope;
|
|
635
|
+
const environment = this.session.scopes.environment({ kind: OwnerKind.Orb, id: record.info.owner }, record);
|
|
636
|
+
record.scope = environment;
|
|
637
|
+
return captureEnvironment2(record.definition, new Declaration(this.session, environment));
|
|
638
|
+
}
|
|
639
|
+
ready(record) {
|
|
640
|
+
if (record.scope?.phase === EnvironmentPhase.Live)
|
|
641
|
+
return Promise.resolve();
|
|
642
|
+
let ready = this.#ready.get(record.info.id);
|
|
643
|
+
if (!ready) {
|
|
644
|
+
ready = (async () => {
|
|
645
|
+
try {
|
|
646
|
+
await this.session.scopes.readyHostScope();
|
|
647
|
+
if (record.scope?.phase === EnvironmentPhase.Closed)
|
|
648
|
+
delete record.scope;
|
|
649
|
+
const release = await record.definition[admitFactory2]?.();
|
|
650
|
+
let scope;
|
|
651
|
+
try {
|
|
652
|
+
const prepared = this.scope(record);
|
|
653
|
+
scope = prepared instanceof Promise ? await prepared : prepared;
|
|
654
|
+
} finally {
|
|
655
|
+
release?.();
|
|
656
|
+
}
|
|
657
|
+
await this.session.programs.activate(scope.id);
|
|
658
|
+
} catch (error) {
|
|
659
|
+
if (record.scope) {
|
|
660
|
+
await this.session.programs.cleanup([record.scope]);
|
|
661
|
+
delete record.scope;
|
|
662
|
+
}
|
|
663
|
+
throw error;
|
|
664
|
+
}
|
|
665
|
+
})();
|
|
666
|
+
this.#ready.set(record.info.id, ready);
|
|
667
|
+
const clear = () => {
|
|
668
|
+
if (this.#ready.get(record.info.id) === ready)
|
|
669
|
+
this.#ready.delete(record.info.id);
|
|
670
|
+
};
|
|
671
|
+
ready.then(clear, clear);
|
|
672
|
+
}
|
|
673
|
+
return ready;
|
|
674
|
+
}
|
|
675
|
+
registerContributions(record) {
|
|
676
|
+
for (const [alias, hooks] of Object.entries(record.definition.contributes ?? {})) {
|
|
677
|
+
const requirement = record.definition.requires[alias];
|
|
678
|
+
const target = requirement.orb ?? alias;
|
|
679
|
+
for (const [hook, contribution] of Object.entries(hooks)) {
|
|
680
|
+
const operation = this.session.kernel.command(KernelOp.Allocate);
|
|
681
|
+
const key = JSON.stringify([record.info.name, target, hook]);
|
|
682
|
+
if (!this.#ordinals.has(key))
|
|
683
|
+
this.#ordinals.set(key, this.session.kernel.command(KernelOp.ContributionOrdinal));
|
|
684
|
+
this.operations.set(operation, {
|
|
685
|
+
orb: record,
|
|
686
|
+
handler: typeof contribution === "function" ? contribution : contribution.handle
|
|
687
|
+
});
|
|
688
|
+
this.session.kernel.command(KernelOp.Contribute, {
|
|
689
|
+
orb: record.info.id,
|
|
690
|
+
target,
|
|
691
|
+
hook,
|
|
692
|
+
operation,
|
|
693
|
+
priority: typeof contribution === "function" ? 0 : contribution.priority ?? 0,
|
|
694
|
+
ordinal: this.#ordinals.get(key)
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
async runHook(environment, name, context2, input) {
|
|
700
|
+
context2 = context(context2, this.session);
|
|
701
|
+
const definition = environment.orb.definition.hooks?.[name];
|
|
702
|
+
if (!definition)
|
|
703
|
+
refuse(Errors2.Invalid.Hook, name);
|
|
704
|
+
const plan = this.session.kernel.command(KernelOp.HookPlan, {
|
|
705
|
+
root: context2.root,
|
|
706
|
+
target: environment.orb.info.name,
|
|
707
|
+
hook: name
|
|
708
|
+
});
|
|
709
|
+
const participants = plan.map((operation) => async (ctx, input, next) => {
|
|
710
|
+
return this.runContribution(operation, ctx, input, next);
|
|
711
|
+
});
|
|
712
|
+
return definition.run(context2, input, participants);
|
|
713
|
+
}
|
|
714
|
+
async observe(environment, name, operation, source, input) {
|
|
715
|
+
source = issuedContext(source, this.session);
|
|
716
|
+
const definition = environment.orb.definition.hooks?.[name];
|
|
717
|
+
if (!definition)
|
|
718
|
+
refuse(Errors2.Invalid.Hook, name);
|
|
719
|
+
if (!source.invocation)
|
|
720
|
+
throw new TembraError2(Errors2.Forbidden.ObservationSource);
|
|
721
|
+
const admitted = this.session.kernel.command(KernelOp.BeginHookObservation, {
|
|
722
|
+
source: source.invocation.id,
|
|
723
|
+
orb: environment.orb.info.id,
|
|
724
|
+
operation,
|
|
725
|
+
...environment.object ? { object: environment.object.id } : {},
|
|
726
|
+
hook: name
|
|
727
|
+
});
|
|
728
|
+
await this.session.track(this.session.calls.root(async () => {
|
|
729
|
+
try {
|
|
730
|
+
const context = new Context(this.session, admitted.invocation.root, admitted.invocation);
|
|
731
|
+
const participants = admitted.plan.map((operation) => async (ctx, input, next) => this.runContribution(operation, ctx, input, next));
|
|
732
|
+
await definition.run(context, input, participants);
|
|
733
|
+
} finally {
|
|
734
|
+
this.session.lifecycle.finishCall(admitted.invocation.id);
|
|
735
|
+
}
|
|
736
|
+
}, false, admitted.invocation.root));
|
|
737
|
+
}
|
|
738
|
+
async runContribution(operation, ctx, input, next) {
|
|
739
|
+
ctx = context(ctx, this.session);
|
|
740
|
+
const contributor = this.operations.get(operation);
|
|
741
|
+
if (!contributor) {
|
|
742
|
+
const native = this.session.options.native;
|
|
743
|
+
if (native?.hasContribution?.(operation) && native.contribute)
|
|
744
|
+
return native.contribute(operation, ctx, input);
|
|
745
|
+
throw new TembraError2(Errors2.Gone.Contribution);
|
|
746
|
+
}
|
|
747
|
+
const scope = contributor.orb.scope;
|
|
748
|
+
if (!scope)
|
|
749
|
+
throw new TembraError2(Errors2.Unavailable.OrbScope);
|
|
750
|
+
return this.session.calls.owned(scope, operation, (entered) => contributor.handler(entered, input, next), ctx);
|
|
751
|
+
}
|
|
752
|
+
retire(id) {
|
|
753
|
+
const scopes = this.session.kernel.command(KernelOp.ScopesForOrb, { orb: id });
|
|
754
|
+
const cleanup = this.session.programs.cleanupScopes(scopes);
|
|
755
|
+
this.session.track(cleanup.finally(async () => {
|
|
756
|
+
try {
|
|
757
|
+
const record = this.records.get(id);
|
|
758
|
+
if (record)
|
|
759
|
+
await disposeDefinitions2([record.definition]);
|
|
760
|
+
} finally {
|
|
761
|
+
for (const [operation, contribution] of this.operations)
|
|
762
|
+
if (contribution.orb.info.id === id)
|
|
763
|
+
this.operations.delete(operation);
|
|
764
|
+
this.records.delete(id);
|
|
765
|
+
this.#ready.delete(id);
|
|
766
|
+
}
|
|
767
|
+
}), true);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
// src/runtime/lifecycle.ts
|
|
772
|
+
class Lifecycle {
|
|
773
|
+
session;
|
|
774
|
+
constructor(session) {
|
|
775
|
+
this.session = session;
|
|
776
|
+
}
|
|
777
|
+
get closedDiagnostics() {
|
|
778
|
+
return this.#finalDiagnostics;
|
|
779
|
+
}
|
|
780
|
+
#closed;
|
|
781
|
+
#flushing = false;
|
|
782
|
+
#linger;
|
|
783
|
+
#lingerDeadline;
|
|
784
|
+
#finalDiagnostics;
|
|
785
|
+
flush(initial) {
|
|
786
|
+
if (this.#flushing)
|
|
787
|
+
return;
|
|
788
|
+
this.#flushing = true;
|
|
789
|
+
try {
|
|
790
|
+
for (;; ) {
|
|
791
|
+
const actions = initial ?? this.session.kernel.command(KernelOp.Drain);
|
|
792
|
+
initial = undefined;
|
|
793
|
+
if (!actions.length)
|
|
794
|
+
break;
|
|
795
|
+
for (const action of actions) {
|
|
796
|
+
try {
|
|
797
|
+
this.action(action);
|
|
798
|
+
} catch (error) {
|
|
799
|
+
this.session.report(error);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
} finally {
|
|
804
|
+
this.#flushing = false;
|
|
805
|
+
this.scheduleLinger();
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
endRoot(root) {
|
|
809
|
+
if (this.#flushing) {
|
|
810
|
+
this.session.kernel.command(KernelOp.EndRoot, { root });
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
const batch = this.session.kernel.command(KernelOp.EndRootBatch, { root });
|
|
814
|
+
if (batch.actions.length)
|
|
815
|
+
this.flush(batch.actions);
|
|
816
|
+
else
|
|
817
|
+
this.scheduleLinger(batch.deadline);
|
|
818
|
+
}
|
|
819
|
+
finishCall(call) {
|
|
820
|
+
const session = this.session;
|
|
821
|
+
if (this.#flushing) {
|
|
822
|
+
session.kernel.command(KernelOp.Tick, { now: session.now() });
|
|
823
|
+
session.kernel.command(KernelOp.FinishCall, { call });
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
const batch = session.options.native?.finish ? session.options.native.finish(call, session.now()) : session.kernel.command(KernelOp.FinishCallBatch, { call, now: session.now() });
|
|
827
|
+
if (!batch.actions.length) {
|
|
828
|
+
this.scheduleLinger(batch.deadline);
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
this.flush(batch.actions);
|
|
832
|
+
}
|
|
833
|
+
action(action) {
|
|
834
|
+
const session = this.session;
|
|
835
|
+
const nativeHandled = session.options.native?.notify?.(action);
|
|
836
|
+
if (nativeHandled && !(action.type === ActionType.ProgramComplete && session.programs.pending(action.id)))
|
|
837
|
+
return;
|
|
838
|
+
switch (action.type) {
|
|
839
|
+
case ActionType.Execute:
|
|
840
|
+
case ActionType.CancelEffects:
|
|
841
|
+
case ActionType.ProgramPrepared:
|
|
842
|
+
case ActionType.ProgramComplete:
|
|
843
|
+
session.programs.dispatch(action);
|
|
844
|
+
break;
|
|
845
|
+
case ActionType.DropValue:
|
|
846
|
+
session.values.drop(action.id);
|
|
847
|
+
session.options.native?.dropValue?.(action.id);
|
|
848
|
+
break;
|
|
849
|
+
case ActionType.CancelRoot:
|
|
850
|
+
session.controllers.get(action.id)?.abort(new TembraError2(Errors2.Cancelled.Root));
|
|
851
|
+
break;
|
|
852
|
+
case ActionType.CancelTask:
|
|
853
|
+
session.activities.cancel(action.id);
|
|
854
|
+
break;
|
|
855
|
+
case ActionType.Deliver:
|
|
856
|
+
session.activities.deliver(action.id, action.payload, action.operation);
|
|
857
|
+
break;
|
|
858
|
+
case ActionType.DetachSubscription:
|
|
859
|
+
session.activities.detach(action.id);
|
|
860
|
+
break;
|
|
861
|
+
case ActionType.SubscriptionFailed:
|
|
862
|
+
session.activities.failed(action.id);
|
|
863
|
+
break;
|
|
864
|
+
case ActionType.Dispose:
|
|
865
|
+
session.track(this.dispose(action.id), true);
|
|
866
|
+
break;
|
|
867
|
+
case ActionType.CloseResource: {
|
|
868
|
+
break;
|
|
869
|
+
}
|
|
870
|
+
case ActionType.RetireOrb:
|
|
871
|
+
session.handles.retire(action.id);
|
|
872
|
+
session.orbs.retire(action.id);
|
|
873
|
+
break;
|
|
874
|
+
case ActionType.State: {
|
|
875
|
+
const object = session.objects.get(action.id);
|
|
876
|
+
if (!object?.binding)
|
|
877
|
+
break;
|
|
878
|
+
const snapshot = session.snapshot(action.id);
|
|
879
|
+
if (!session.values.has(snapshot.value)) {
|
|
880
|
+
const candidate = session.value(snapshot.value);
|
|
881
|
+
session.publish(object.binding.adopt(object.binding.prepare(candidate), candidate));
|
|
882
|
+
}
|
|
883
|
+
break;
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
async dispose(id) {
|
|
888
|
+
const session = this.session;
|
|
889
|
+
const object = session.objects.get(id);
|
|
890
|
+
if (!object) {
|
|
891
|
+
await session.options.native?.dispose(id);
|
|
892
|
+
session.kernel.command(KernelOp.Disposed, { object: id });
|
|
893
|
+
this.flush();
|
|
894
|
+
return;
|
|
895
|
+
}
|
|
896
|
+
object.disposing ??= (async () => {
|
|
897
|
+
const errors = [];
|
|
898
|
+
await object.activation.catch(() => {});
|
|
899
|
+
const scopes = session.kernel.command(KernelOp.ScopesForOwner, {
|
|
900
|
+
owner: { kind: OwnerKind.Object, id }
|
|
901
|
+
});
|
|
902
|
+
try {
|
|
903
|
+
await session.programs.cleanupScopes(scopes);
|
|
904
|
+
} catch (error) {
|
|
905
|
+
errors.push(error);
|
|
906
|
+
}
|
|
907
|
+
try {
|
|
908
|
+
if (session.options.native?.hasOrb(object.orb))
|
|
909
|
+
await session.options.native.dispose(id);
|
|
910
|
+
} catch (error) {
|
|
911
|
+
errors.push(error);
|
|
912
|
+
}
|
|
913
|
+
object.binding?.close();
|
|
914
|
+
session.kernel.command(KernelOp.Disposed, { object: id });
|
|
915
|
+
session.objects.delete(id);
|
|
916
|
+
this.flush();
|
|
917
|
+
if (errors.length)
|
|
918
|
+
throw new AggregateError(errors, "Object cleanup failed");
|
|
919
|
+
})();
|
|
920
|
+
return object.disposing;
|
|
921
|
+
}
|
|
922
|
+
scheduleLinger(known) {
|
|
923
|
+
const session = this.session;
|
|
924
|
+
if (session.closing)
|
|
925
|
+
return;
|
|
926
|
+
const deadline = (known === undefined ? session.kernel.command(KernelOp.NextDeadline) : known) ?? undefined;
|
|
927
|
+
if (deadline === this.#lingerDeadline)
|
|
928
|
+
return;
|
|
929
|
+
if (this.#linger !== undefined)
|
|
930
|
+
clearTimeout(this.#linger);
|
|
931
|
+
this.#linger = undefined;
|
|
932
|
+
this.#lingerDeadline = deadline;
|
|
933
|
+
if (deadline === undefined)
|
|
934
|
+
return;
|
|
935
|
+
this.#linger = setTimeout(() => {
|
|
936
|
+
if (this.#lingerDeadline !== deadline)
|
|
937
|
+
return;
|
|
938
|
+
this.#linger = undefined;
|
|
939
|
+
this.#lingerDeadline = undefined;
|
|
940
|
+
session.kernel.command(KernelOp.Tick, { now: session.now() });
|
|
941
|
+
this.flush();
|
|
942
|
+
}, Math.max(0, deadline - session.now()));
|
|
943
|
+
this.#linger.unref?.();
|
|
944
|
+
}
|
|
945
|
+
diagnostics() {
|
|
946
|
+
const session = this.session;
|
|
947
|
+
if (this.#finalDiagnostics)
|
|
948
|
+
return this.#finalDiagnostics;
|
|
949
|
+
return {
|
|
950
|
+
...session.kernel.command(KernelOp.Diagnostics),
|
|
951
|
+
values: session.values.size,
|
|
952
|
+
pendingJobs: session.jobs.size
|
|
953
|
+
};
|
|
954
|
+
}
|
|
955
|
+
close() {
|
|
956
|
+
const session = this.session;
|
|
957
|
+
this.#closed ??= (async () => {
|
|
958
|
+
session.closing = true;
|
|
959
|
+
clearTimeout(this.#linger);
|
|
960
|
+
this.#linger = undefined;
|
|
961
|
+
this.#lingerDeadline = undefined;
|
|
962
|
+
session.kernel.command(KernelOp.Close);
|
|
963
|
+
await session.replacements.cancel();
|
|
964
|
+
this.flush();
|
|
965
|
+
for (;; ) {
|
|
966
|
+
await session.options.native?.settled?.();
|
|
967
|
+
this.flush();
|
|
968
|
+
const pending = [...session.jobs];
|
|
969
|
+
if (!pending.length)
|
|
970
|
+
break;
|
|
971
|
+
await Promise.allSettled(pending);
|
|
972
|
+
this.flush();
|
|
973
|
+
}
|
|
974
|
+
session.kernel.command(KernelOp.FinishClose);
|
|
975
|
+
session.values.clear();
|
|
976
|
+
session.handles.clear();
|
|
977
|
+
try {
|
|
978
|
+
await disposeDefinitions2([...session.orbs.records.values()].map((record) => record.definition));
|
|
979
|
+
} catch (error) {
|
|
980
|
+
session.cleanupErrors.push(error);
|
|
981
|
+
}
|
|
982
|
+
session.orbs.records.clear();
|
|
983
|
+
session.scopes.clear();
|
|
984
|
+
this.#finalDiagnostics = this.diagnostics();
|
|
985
|
+
session.kernel.port.free?.();
|
|
986
|
+
if (session.cleanupErrors.length)
|
|
987
|
+
throw new AggregateError(session.cleanupErrors, "Host cleanup failed");
|
|
988
|
+
})();
|
|
989
|
+
return this.#closed;
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
// src/runtime/programs.ts
|
|
994
|
+
function errorText(value, limit) {
|
|
995
|
+
return value.slice(0, limit).replace(/[\uD800-\uDFFF]/gu, "�");
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
class Programs {
|
|
999
|
+
session;
|
|
1000
|
+
scopes = new Map;
|
|
1001
|
+
#pending = new Map;
|
|
1002
|
+
constructor(session) {
|
|
1003
|
+
this.session = session;
|
|
1004
|
+
}
|
|
1005
|
+
register(environment) {
|
|
1006
|
+
const parent = environment.owner.kind === OwnerKind.Host ? undefined : environment.object ? environment.orb.scope : this.session.hostScope;
|
|
1007
|
+
this.session.kernel.command(KernelOp.ScopeRegister, {
|
|
1008
|
+
scope: environment.id,
|
|
1009
|
+
owner: environment.owner,
|
|
1010
|
+
orb: environment.orb.info.id,
|
|
1011
|
+
parents: parent ? [parent.id] : [],
|
|
1012
|
+
dependencies: [...environment.dependencies.values()].map((reference) => this.session.handles.reference(reference).id),
|
|
1013
|
+
resources: [...environment.resources.values()].map((resource) => resource.id),
|
|
1014
|
+
stateVersion: environment.state?.options.version ?? (environment.state ? 1 : undefined),
|
|
1015
|
+
migrate: Boolean(environment.state?.options.migrate)
|
|
1016
|
+
});
|
|
1017
|
+
}
|
|
1018
|
+
activate(scope) {
|
|
1019
|
+
return this.run(this.session.kernel.command(KernelOp.ScopeActivate, { scope }));
|
|
1020
|
+
}
|
|
1021
|
+
cleanup(environments) {
|
|
1022
|
+
const scopes = environments.map((environment) => environment.id).filter((scope) => this.session.kernel.command(KernelOp.ScopeExists, { scope }));
|
|
1023
|
+
return this.cleanupScopes(scopes);
|
|
1024
|
+
}
|
|
1025
|
+
cleanupScopes(scopes) {
|
|
1026
|
+
return scopes.length ? this.run(this.session.kernel.command(KernelOp.ScopesCleanup, { scopes })) : Promise.resolve();
|
|
1027
|
+
}
|
|
1028
|
+
pending(program) {
|
|
1029
|
+
return this.#pending.has(program);
|
|
1030
|
+
}
|
|
1031
|
+
run(program) {
|
|
1032
|
+
const pending = this.#pending.get(program);
|
|
1033
|
+
if (pending)
|
|
1034
|
+
return pending.promise;
|
|
1035
|
+
const completion = deferred();
|
|
1036
|
+
this.#pending.set(program, completion);
|
|
1037
|
+
try {
|
|
1038
|
+
this.session.kernel.command(KernelOp.ProgramRun, { program });
|
|
1039
|
+
this.session.lifecycle.flush();
|
|
1040
|
+
} catch (error) {
|
|
1041
|
+
this.#pending.delete(program);
|
|
1042
|
+
completion.reject(error);
|
|
1043
|
+
}
|
|
1044
|
+
return completion.promise;
|
|
1045
|
+
}
|
|
1046
|
+
dispatch(action) {
|
|
1047
|
+
if (action.type === ActionType.Execute) {
|
|
1048
|
+
this.session.track(Promise.allSettled(action.effects.map((effect) => this.execute(effect))).then((settled) => {
|
|
1049
|
+
const limit = Math.max(0, Math.min(2048, Math.floor((1024 * 1024 - 128 - settled.length * 96) / (12 * settled.length))));
|
|
1050
|
+
const results = settled.map((result) => {
|
|
1051
|
+
if (result.status === "fulfilled")
|
|
1052
|
+
return { value: result.value ?? null };
|
|
1053
|
+
try {
|
|
1054
|
+
const { code, reason, message } = failure(result.reason);
|
|
1055
|
+
if (!Object.values(Code2).includes(code) || typeof reason !== "string" || typeof message !== "string")
|
|
1056
|
+
return { error: Errors2.Unavailable.Callback };
|
|
1057
|
+
return {
|
|
1058
|
+
error: {
|
|
1059
|
+
code,
|
|
1060
|
+
reason: errorText(reason, limit),
|
|
1061
|
+
message: errorText(message, limit)
|
|
1062
|
+
}
|
|
1063
|
+
};
|
|
1064
|
+
} catch {
|
|
1065
|
+
return { error: Errors2.Unavailable.Callback };
|
|
1066
|
+
}
|
|
1067
|
+
});
|
|
1068
|
+
this.session.kernel.command(KernelOp.ProgramCompleteStep, {
|
|
1069
|
+
program: action.id,
|
|
1070
|
+
results
|
|
1071
|
+
});
|
|
1072
|
+
this.session.lifecycle.flush();
|
|
1073
|
+
}));
|
|
1074
|
+
} else if (action.type === ActionType.CancelEffects) {
|
|
1075
|
+
for (const effect of action.effects) {
|
|
1076
|
+
if (effect.type !== EffectType.Open && effect.type !== EffectType.Restore)
|
|
1077
|
+
continue;
|
|
1078
|
+
const resource = this.session.resources.find(effect.resource);
|
|
1079
|
+
if (resource)
|
|
1080
|
+
resource.controller.abort(new TembraError2(Errors2.Cancelled.EngineEffect));
|
|
1081
|
+
else if (this.session.options.native?.cancelEffect) {
|
|
1082
|
+
const cancel = this.session.options.native.cancelEffect.bind(this.session.options.native);
|
|
1083
|
+
this.session.track(Promise.resolve().then(() => cancel(effect))).catch((error) => this.session.report(error));
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
} else {
|
|
1087
|
+
const completion = this.#pending.get(action.id);
|
|
1088
|
+
this.#pending.delete(action.id);
|
|
1089
|
+
const failed = action.type === ActionType.ProgramComplete ? action.error : null;
|
|
1090
|
+
if (failed) {
|
|
1091
|
+
const error = new TembraError2(failed);
|
|
1092
|
+
if (completion)
|
|
1093
|
+
completion.reject(error);
|
|
1094
|
+
else {
|
|
1095
|
+
this.session.cleanupErrors.push(error);
|
|
1096
|
+
this.session.report(error);
|
|
1097
|
+
}
|
|
1098
|
+
} else
|
|
1099
|
+
completion?.resolve();
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
resource(id) {
|
|
1103
|
+
const direct = this.session.resources.find(id);
|
|
1104
|
+
if (direct)
|
|
1105
|
+
return direct;
|
|
1106
|
+
throw new TembraError2(Errors2.Gone.Resource);
|
|
1107
|
+
}
|
|
1108
|
+
async execute(effect) {
|
|
1109
|
+
const scope = "scope" in effect ? effect.scope : undefined;
|
|
1110
|
+
const environment = scope === undefined ? undefined : this.scopes.get(scope);
|
|
1111
|
+
if (scope !== undefined && !environment && this.session.options.native)
|
|
1112
|
+
return this.session.options.native.effect(effect);
|
|
1113
|
+
if ((effect.type === EffectType.Close || effect.type === EffectType.Open) && !this.session.resources.find(effect.resource) && this.session.options.native)
|
|
1114
|
+
return this.session.options.native.effect(effect);
|
|
1115
|
+
switch (effect.type) {
|
|
1116
|
+
case EffectType.Open:
|
|
1117
|
+
await this.resource(effect.resource).start();
|
|
1118
|
+
break;
|
|
1119
|
+
case EffectType.Close:
|
|
1120
|
+
await this.session.resources.close(this.resource(effect.resource));
|
|
1121
|
+
break;
|
|
1122
|
+
case EffectType.Restore:
|
|
1123
|
+
await this.session.resources.reopen(this.resource(effect.previous), effect.resource);
|
|
1124
|
+
break;
|
|
1125
|
+
case EffectType.Stop:
|
|
1126
|
+
if (environment)
|
|
1127
|
+
await this.session.activities.stop(environment);
|
|
1128
|
+
break;
|
|
1129
|
+
case EffectType.Prepare: {
|
|
1130
|
+
if (!environment)
|
|
1131
|
+
throw new TembraError2(Errors2.Gone.Scope);
|
|
1132
|
+
this.session.activities.prepare(environment, effect.previous ? this.scopes.get(effect.previous) : undefined);
|
|
1133
|
+
break;
|
|
1134
|
+
}
|
|
1135
|
+
case EffectType.Validate:
|
|
1136
|
+
validate(this.session.value(effect.value), environment.state.options);
|
|
1137
|
+
await environment.orb.definition[validateEnvironment2]?.(environment, this.session.value(effect.value));
|
|
1138
|
+
break;
|
|
1139
|
+
case EffectType.Initialize:
|
|
1140
|
+
return this.candidate(environment, environment.state.initial);
|
|
1141
|
+
case EffectType.Migrate: {
|
|
1142
|
+
const state = environment.state;
|
|
1143
|
+
return this.candidate(environment, state.options.migrate(this.session.value(effect.value), effect.version));
|
|
1144
|
+
}
|
|
1145
|
+
case EffectType.Adopt: {
|
|
1146
|
+
const orbs = new Map;
|
|
1147
|
+
for (const pair of effect.replacements) {
|
|
1148
|
+
if (!pair.next)
|
|
1149
|
+
continue;
|
|
1150
|
+
const next = this.scopes.get(pair.next);
|
|
1151
|
+
for (const [resource, declaration] of next.resourceDeclarations ?? [])
|
|
1152
|
+
resource.options = declaration;
|
|
1153
|
+
delete next.resourceDeclarations;
|
|
1154
|
+
orbs.set(next.orb.info.id, next.orb);
|
|
1155
|
+
if (next.object) {
|
|
1156
|
+
if (next.state)
|
|
1157
|
+
next.object.binding = next.state.binding;
|
|
1158
|
+
next.object.orb = next.orb.info.id;
|
|
1159
|
+
next.object.versions.set(next.orb.info.id, next);
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
for (const record of orbs.values()) {
|
|
1163
|
+
this.session.orbs.records.set(record.info.id, record);
|
|
1164
|
+
this.session.orbs.registerContributions(record);
|
|
1165
|
+
}
|
|
1166
|
+
for (const pair of effect.replacements) {
|
|
1167
|
+
const next = pair.next ? this.scopes.get(pair.next) : undefined;
|
|
1168
|
+
if (next?.object)
|
|
1169
|
+
this.session.handles.refreshReferences(next.object, next.orb);
|
|
1170
|
+
}
|
|
1171
|
+
for (const pair of effect.replacements)
|
|
1172
|
+
if (pair.next)
|
|
1173
|
+
this.scopes.get(pair.next)?.state?.publish?.();
|
|
1174
|
+
break;
|
|
1175
|
+
}
|
|
1176
|
+
case EffectType.Start:
|
|
1177
|
+
if (environment) {
|
|
1178
|
+
this.session.activities.start(environment);
|
|
1179
|
+
if (environment.object)
|
|
1180
|
+
environment.object.live = true;
|
|
1181
|
+
}
|
|
1182
|
+
break;
|
|
1183
|
+
case EffectType.Drop: {
|
|
1184
|
+
if (!environment)
|
|
1185
|
+
break;
|
|
1186
|
+
for (const reference of environment.dependencies.values())
|
|
1187
|
+
this.session.handles.revoke(this.session.handles.reference(reference).id);
|
|
1188
|
+
environment.dependencies.clear();
|
|
1189
|
+
for (const resource of environment.resources.values())
|
|
1190
|
+
this.session.resources.closedRecords.delete(resource.id);
|
|
1191
|
+
environment.phase = EnvironmentPhase.Closed;
|
|
1192
|
+
if (environment.object)
|
|
1193
|
+
environment.object.versions.delete(environment.orb.info.id);
|
|
1194
|
+
this.scopes.delete(environment.id);
|
|
1195
|
+
await environment.orb.definition[releaseEnvironment2]?.(environment);
|
|
1196
|
+
break;
|
|
1197
|
+
}
|
|
1198
|
+
default:
|
|
1199
|
+
throw new TembraError2(Errors2.Unsupported.EngineEffect, effect.type);
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
candidate(environment, candidate) {
|
|
1203
|
+
const state = environment.state;
|
|
1204
|
+
const value = validate(candidate, state.options);
|
|
1205
|
+
const id = this.session.values.put(value);
|
|
1206
|
+
state.publish = () => this.session.publish(state.binding.adopt(state.binding.prepare(value), value));
|
|
1207
|
+
return id;
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
// src/runtime/reload.ts
|
|
1212
|
+
class Replacements {
|
|
1213
|
+
session;
|
|
1214
|
+
#pending;
|
|
1215
|
+
#program;
|
|
1216
|
+
#prepared;
|
|
1217
|
+
constructor(session) {
|
|
1218
|
+
this.session = session;
|
|
1219
|
+
}
|
|
1220
|
+
async replace(definitions, options = {}, remove = []) {
|
|
1221
|
+
return (await this.prepare(definitions, options, remove)).commit();
|
|
1222
|
+
}
|
|
1223
|
+
prepare(definitions, options = {}, remove = []) {
|
|
1224
|
+
if (this.session.closing)
|
|
1225
|
+
return Promise.reject(new TembraError2(Errors2.Closed.Host));
|
|
1226
|
+
if (this.#pending)
|
|
1227
|
+
return Promise.reject(new TembraError2(Errors2.Conflict.ReloadRunning));
|
|
1228
|
+
const pending = this.capture(definitions, options, remove);
|
|
1229
|
+
this.#pending = pending;
|
|
1230
|
+
pending.catch(() => {
|
|
1231
|
+
if (this.#pending === pending)
|
|
1232
|
+
this.#pending = undefined;
|
|
1233
|
+
});
|
|
1234
|
+
return pending;
|
|
1235
|
+
}
|
|
1236
|
+
async cancel() {
|
|
1237
|
+
if (this.#prepared?.status === ReloadStatus2.Prepared)
|
|
1238
|
+
return this.#prepared.abort();
|
|
1239
|
+
if (this.#program !== undefined) {
|
|
1240
|
+
this.session.kernel.command(KernelOp.ProgramAbort, { program: this.#program });
|
|
1241
|
+
const settled = this.session.programs.run(this.#program);
|
|
1242
|
+
this.session.lifecycle.flush();
|
|
1243
|
+
await settled.catch(() => {});
|
|
1244
|
+
}
|
|
1245
|
+
await this.#pending?.catch(() => {
|
|
1246
|
+
return;
|
|
1247
|
+
});
|
|
1248
|
+
}
|
|
1249
|
+
async settleAbort(program) {
|
|
1250
|
+
try {
|
|
1251
|
+
await this.session.programs.run(program);
|
|
1252
|
+
} catch (error) {
|
|
1253
|
+
if (!(error instanceof TembraError2) || error.reason !== Reason2.ReloadAborted)
|
|
1254
|
+
throw error;
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
async capture(definitions, options, remove) {
|
|
1258
|
+
const session = this.session;
|
|
1259
|
+
const candidates = prepareDefinitions2(definitions, session.options[isolate2]);
|
|
1260
|
+
const materialized = Array.isArray(candidates) ? candidates : await candidates;
|
|
1261
|
+
let declarations;
|
|
1262
|
+
let reload;
|
|
1263
|
+
try {
|
|
1264
|
+
if (session.closing)
|
|
1265
|
+
throw new TembraError2(Errors2.Closed.Host);
|
|
1266
|
+
declarations = session.orbs.declarations(materialized);
|
|
1267
|
+
reload = session.kernel.command(KernelOp.Prepare, {
|
|
1268
|
+
orbs: declarations.metadata,
|
|
1269
|
+
remove
|
|
1270
|
+
});
|
|
1271
|
+
} catch (error) {
|
|
1272
|
+
return discardDefinitions2(materialized, error);
|
|
1273
|
+
}
|
|
1274
|
+
const definitionsByName = new Map(declarations.definitions.map((definition) => [definition.name, definition]));
|
|
1275
|
+
const records = reload.orbs.map((info) => ({
|
|
1276
|
+
info,
|
|
1277
|
+
definition: definitionsByName.get(info.name),
|
|
1278
|
+
ticket: reload.id
|
|
1279
|
+
}));
|
|
1280
|
+
const recordsById = new Map(records.map((record) => [record.info.id, record]));
|
|
1281
|
+
let program;
|
|
1282
|
+
try {
|
|
1283
|
+
for (const record of records) {
|
|
1284
|
+
const prepared = session.orbs.scope(record);
|
|
1285
|
+
if (prepared instanceof Promise)
|
|
1286
|
+
await prepared;
|
|
1287
|
+
}
|
|
1288
|
+
for (const id of reload.objects) {
|
|
1289
|
+
const object = session.objects.get(id);
|
|
1290
|
+
if (!object)
|
|
1291
|
+
continue;
|
|
1292
|
+
const orb = reload.providers[object.address.service];
|
|
1293
|
+
const record = orb === undefined ? undefined : recordsById.get(orb);
|
|
1294
|
+
if (record) {
|
|
1295
|
+
const prepared = session.scopes.createEnvironment(object, record);
|
|
1296
|
+
if (prepared instanceof Promise)
|
|
1297
|
+
await prepared;
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
for (const record of records)
|
|
1301
|
+
record.ticket = undefined;
|
|
1302
|
+
program = session.kernel.command(KernelOp.ScopesReloadRegistered, {
|
|
1303
|
+
ticket: reload.id,
|
|
1304
|
+
deadline: options.deadline ?? 5000,
|
|
1305
|
+
now: session.now()
|
|
1306
|
+
});
|
|
1307
|
+
this.#program = program;
|
|
1308
|
+
await session.programs.run(program);
|
|
1309
|
+
if (session.closing)
|
|
1310
|
+
await session.programs.run(program);
|
|
1311
|
+
} catch (error) {
|
|
1312
|
+
this.#program = undefined;
|
|
1313
|
+
let failure = error;
|
|
1314
|
+
try {
|
|
1315
|
+
if (program === undefined) {
|
|
1316
|
+
session.kernel.command(KernelOp.Abort, { ticket: reload.id });
|
|
1317
|
+
const scopes = reload.orbs.flatMap((orb) => session.kernel.command(KernelOp.ScopesForOrb, { orb: orb.id }));
|
|
1318
|
+
await session.programs.cleanupScopes(scopes);
|
|
1319
|
+
}
|
|
1320
|
+
} catch (recovery) {
|
|
1321
|
+
failure = new AggregateError([error, recovery], "Orb preparation and recovery failed");
|
|
1322
|
+
}
|
|
1323
|
+
return discardDefinitions2(materialized, failure);
|
|
1324
|
+
}
|
|
1325
|
+
this.#program = undefined;
|
|
1326
|
+
const id = program;
|
|
1327
|
+
const report = {
|
|
1328
|
+
codeVersion: reload.codeVersion,
|
|
1329
|
+
orbs: records.map((record) => record.info.name)
|
|
1330
|
+
};
|
|
1331
|
+
let status = ReloadStatus2.Prepared;
|
|
1332
|
+
return this.#prepared = {
|
|
1333
|
+
report,
|
|
1334
|
+
get status() {
|
|
1335
|
+
return status;
|
|
1336
|
+
},
|
|
1337
|
+
commit: async () => {
|
|
1338
|
+
if (status !== ReloadStatus2.Prepared)
|
|
1339
|
+
throw new TembraError2(Errors2.Conflict.ReloadTicket);
|
|
1340
|
+
this.#prepared = undefined;
|
|
1341
|
+
try {
|
|
1342
|
+
session.kernel.command(KernelOp.ProgramCommit, { program: id });
|
|
1343
|
+
} catch (error) {
|
|
1344
|
+
let failure = error;
|
|
1345
|
+
try {
|
|
1346
|
+
session.kernel.command(KernelOp.ProgramAbort, { program: id });
|
|
1347
|
+
await this.settleAbort(id);
|
|
1348
|
+
} catch (recovery) {
|
|
1349
|
+
failure = new AggregateError([error, recovery], "Orb commit and recovery failed");
|
|
1350
|
+
}
|
|
1351
|
+
status = ReloadStatus2.Aborted;
|
|
1352
|
+
this.#pending = undefined;
|
|
1353
|
+
return discardDefinitions2(materialized, failure);
|
|
1354
|
+
}
|
|
1355
|
+
status = ReloadStatus2.Committed;
|
|
1356
|
+
this.#pending = undefined;
|
|
1357
|
+
await session.programs.run(id);
|
|
1358
|
+
return report;
|
|
1359
|
+
},
|
|
1360
|
+
abort: async () => {
|
|
1361
|
+
if (status === ReloadStatus2.Aborted)
|
|
1362
|
+
return;
|
|
1363
|
+
if (status !== ReloadStatus2.Prepared)
|
|
1364
|
+
throw new TembraError2(Errors2.Conflict.AlreadyCommitted);
|
|
1365
|
+
status = ReloadStatus2.Aborted;
|
|
1366
|
+
this.#prepared = undefined;
|
|
1367
|
+
this.#pending = undefined;
|
|
1368
|
+
try {
|
|
1369
|
+
session.kernel.command(KernelOp.ProgramAbort, { program: id });
|
|
1370
|
+
await this.settleAbort(id);
|
|
1371
|
+
} catch (error) {
|
|
1372
|
+
return discardDefinitions2(materialized, error);
|
|
1373
|
+
}
|
|
1374
|
+
await disposeDefinitions2(materialized);
|
|
1375
|
+
}
|
|
1376
|
+
};
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
// src/runtime/resources.ts
|
|
1381
|
+
var issued = new WeakMap;
|
|
1382
|
+
|
|
1383
|
+
class Resources {
|
|
1384
|
+
session;
|
|
1385
|
+
records = new Map;
|
|
1386
|
+
closedRecords = new Map;
|
|
1387
|
+
constructor(session) {
|
|
1388
|
+
this.session = session;
|
|
1389
|
+
}
|
|
1390
|
+
find(id) {
|
|
1391
|
+
return this.records.get(id) ?? this.closedRecords.get(id);
|
|
1392
|
+
}
|
|
1393
|
+
dependencyIds(options) {
|
|
1394
|
+
const dependencies = [];
|
|
1395
|
+
for (const dependency of options.deps ?? []) {
|
|
1396
|
+
const resource = typeof dependency === "object" && dependency !== null ? issued.get(dependency) : undefined;
|
|
1397
|
+
if (resource) {
|
|
1398
|
+
if (resource.session !== this.session)
|
|
1399
|
+
refuse(Errors2.Invalid.ResourceHost, "Resource dependencies must belong to the same host");
|
|
1400
|
+
dependencies.push(resource.id);
|
|
1401
|
+
} else {
|
|
1402
|
+
this.session.handles.reference(dependency);
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
return dependencies;
|
|
1406
|
+
}
|
|
1407
|
+
register(environment, name, options) {
|
|
1408
|
+
return this.session.kernel.command(KernelOp.Resource, {
|
|
1409
|
+
owner: environment.owner,
|
|
1410
|
+
name,
|
|
1411
|
+
version: options.version ?? 1,
|
|
1412
|
+
exclusive: options.exclusive ?? false,
|
|
1413
|
+
dependencies: this.dependencyIds(options)
|
|
1414
|
+
}).id;
|
|
1415
|
+
}
|
|
1416
|
+
redeclare(environment, previous) {
|
|
1417
|
+
for (const resource of previous.resources.values()) {
|
|
1418
|
+
this.records.delete(resource.id);
|
|
1419
|
+
this.closedRecords.delete(resource.id);
|
|
1420
|
+
resource.reset(this.register(environment, resource.name, resource.options));
|
|
1421
|
+
resource.dependencies = this.dependencyIds(resource.options);
|
|
1422
|
+
this.records.set(resource.id, resource);
|
|
1423
|
+
environment.resources.set(resource.name, resource);
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
declare(environment, name, options) {
|
|
1427
|
+
if (!name || typeof options.open !== "function")
|
|
1428
|
+
refuse(Errors2.Invalid.Resource);
|
|
1429
|
+
const id = this.register(environment, name, options);
|
|
1430
|
+
const reused = this.records.get(id);
|
|
1431
|
+
if (reused) {
|
|
1432
|
+
(environment.resourceDeclarations ??= new Map).set(reused, options);
|
|
1433
|
+
return reused;
|
|
1434
|
+
}
|
|
1435
|
+
const controller = new AbortController;
|
|
1436
|
+
const handle = Object.freeze({
|
|
1437
|
+
get value() {
|
|
1438
|
+
if (environment.phase === EnvironmentPhase.Declaring)
|
|
1439
|
+
refuse(Errors2.Invalid.ResourceInFactory, "Resources open after declaration");
|
|
1440
|
+
const value = record.session.kernel.command(KernelOp.ResourceValue, {
|
|
1441
|
+
resource: record.id
|
|
1442
|
+
});
|
|
1443
|
+
return record.session.value(value);
|
|
1444
|
+
},
|
|
1445
|
+
version: options.version ?? 1
|
|
1446
|
+
});
|
|
1447
|
+
const record = {
|
|
1448
|
+
id,
|
|
1449
|
+
name,
|
|
1450
|
+
options,
|
|
1451
|
+
handle,
|
|
1452
|
+
dependencies: this.dependencyIds(options),
|
|
1453
|
+
controller,
|
|
1454
|
+
session: this.session,
|
|
1455
|
+
reset: (id) => {
|
|
1456
|
+
record.id = id;
|
|
1457
|
+
record.controller = new AbortController;
|
|
1458
|
+
delete record.value;
|
|
1459
|
+
delete record.closed;
|
|
1460
|
+
delete record.started;
|
|
1461
|
+
},
|
|
1462
|
+
start: () => {
|
|
1463
|
+
record.started ??= (async () => {
|
|
1464
|
+
const declaration = record.options;
|
|
1465
|
+
const value = await declaration.open(record.controller.signal);
|
|
1466
|
+
const id = this.session.values.put(value);
|
|
1467
|
+
try {
|
|
1468
|
+
this.session.kernel.command(KernelOp.ResourceOpened, {
|
|
1469
|
+
resource: record.id,
|
|
1470
|
+
value: id
|
|
1471
|
+
});
|
|
1472
|
+
} catch (error) {
|
|
1473
|
+
this.session.values.drop(id);
|
|
1474
|
+
if (declaration.close)
|
|
1475
|
+
await this.session.calls.root((ctx) => declaration.close(value, ctx), true);
|
|
1476
|
+
throw error;
|
|
1477
|
+
}
|
|
1478
|
+
record.value = id;
|
|
1479
|
+
})();
|
|
1480
|
+
record.started.catch(() => {});
|
|
1481
|
+
return record.started;
|
|
1482
|
+
}
|
|
1483
|
+
};
|
|
1484
|
+
issued.set(handle, record);
|
|
1485
|
+
this.records.set(id, record);
|
|
1486
|
+
return record;
|
|
1487
|
+
}
|
|
1488
|
+
async close(record) {
|
|
1489
|
+
record.closed ??= (async () => {
|
|
1490
|
+
record.controller.abort(new TembraError2(Errors2.Cancelled.Resource));
|
|
1491
|
+
await record.started?.catch(() => {});
|
|
1492
|
+
try {
|
|
1493
|
+
if (record.value !== undefined && record.options.close) {
|
|
1494
|
+
const value = this.session.value(record.value);
|
|
1495
|
+
await this.session.calls.root((ctx) => record.options.close(value, ctx), true);
|
|
1496
|
+
}
|
|
1497
|
+
} finally {
|
|
1498
|
+
this.session.kernel.command(KernelOp.ResourceClosed, { resource: record.id });
|
|
1499
|
+
this.records.delete(record.id);
|
|
1500
|
+
this.closedRecords.set(record.id, record);
|
|
1501
|
+
this.session.lifecycle.flush();
|
|
1502
|
+
}
|
|
1503
|
+
})();
|
|
1504
|
+
return record.closed;
|
|
1505
|
+
}
|
|
1506
|
+
async reopen(record, id) {
|
|
1507
|
+
this.closedRecords.delete(record.id);
|
|
1508
|
+
record.reset(id);
|
|
1509
|
+
this.records.set(id, record);
|
|
1510
|
+
await record.start();
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
// src/runtime/scopes.ts
|
|
1515
|
+
class Scopes {
|
|
1516
|
+
session;
|
|
1517
|
+
constructor(session) {
|
|
1518
|
+
this.session = session;
|
|
1519
|
+
}
|
|
1520
|
+
#hostResources = new Map;
|
|
1521
|
+
#pendingHostScopes = new Set;
|
|
1522
|
+
#hostActivation;
|
|
1523
|
+
environment(owner, orb, object) {
|
|
1524
|
+
const environment = {
|
|
1525
|
+
id: this.session.kernel.command(KernelOp.Allocate),
|
|
1526
|
+
owner,
|
|
1527
|
+
orb,
|
|
1528
|
+
...object ? { object } : {},
|
|
1529
|
+
phase: EnvironmentPhase.Declaring,
|
|
1530
|
+
value: {},
|
|
1531
|
+
dependencies: new Map,
|
|
1532
|
+
resources: new Map,
|
|
1533
|
+
tasks: [],
|
|
1534
|
+
listeners: []
|
|
1535
|
+
};
|
|
1536
|
+
this.session.programs.scopes.set(environment.id, environment);
|
|
1537
|
+
return environment;
|
|
1538
|
+
}
|
|
1539
|
+
async activate(object, acquired) {
|
|
1540
|
+
const session = this.session;
|
|
1541
|
+
if (session.options.native?.hasOrb(acquired.orb)) {
|
|
1542
|
+
await session.options.native.activate(object.id, acquired.orb, object.address.service, object.address.key, object.address.principal);
|
|
1543
|
+
const scopes = session.kernel.command(KernelOp.ScopesForOwner, {
|
|
1544
|
+
owner: { kind: OwnerKind.Object, id: object.id }
|
|
1545
|
+
});
|
|
1546
|
+
await Promise.all(scopes.map((scope) => session.programs.activate(scope)));
|
|
1547
|
+
try {
|
|
1548
|
+
session.snapshot(object.id);
|
|
1549
|
+
object.binding = new StateBinding(session, object.id);
|
|
1550
|
+
} catch {}
|
|
1551
|
+
} else {
|
|
1552
|
+
const orb = session.orbs.records.get(acquired.orb);
|
|
1553
|
+
if (!orb)
|
|
1554
|
+
refuse(Errors2.Invalid.OrbGone);
|
|
1555
|
+
await session.orbs.ready(orb);
|
|
1556
|
+
const release = await orb.definition.services?.[object.address.service]?.[admitFactory2]?.();
|
|
1557
|
+
let environment;
|
|
1558
|
+
try {
|
|
1559
|
+
const prepared = this.createEnvironment(object, orb);
|
|
1560
|
+
environment = prepared instanceof Promise ? await prepared : prepared;
|
|
1561
|
+
} finally {
|
|
1562
|
+
release?.();
|
|
1563
|
+
}
|
|
1564
|
+
object.versions.set(orb.info.id, environment);
|
|
1565
|
+
await this.session.programs.activate(environment.id);
|
|
1566
|
+
}
|
|
1567
|
+
if (session.kernel.command(KernelOp.Status, { reference: acquired.reference }) === Status2.Loading)
|
|
1568
|
+
session.kernel.command(KernelOp.Ready, { object: object.id });
|
|
1569
|
+
object.live = true;
|
|
1570
|
+
session.lifecycle.flush();
|
|
1571
|
+
}
|
|
1572
|
+
createEnvironment(object, orb) {
|
|
1573
|
+
const definition = orb.definition.services?.[object.address.service];
|
|
1574
|
+
if (!definition)
|
|
1575
|
+
refuse(Errors2.Invalid.ServiceGone);
|
|
1576
|
+
const environment = this.environment({ kind: OwnerKind.Object, id: object.id }, orb, object);
|
|
1577
|
+
return captureEnvironment2(definition, new Declaration(this.session, environment));
|
|
1578
|
+
}
|
|
1579
|
+
readyHostScope() {
|
|
1580
|
+
const session = this.session;
|
|
1581
|
+
if (session.closing)
|
|
1582
|
+
return Promise.reject(new TembraError2(Errors2.Closed.Host));
|
|
1583
|
+
if (this.#hostActivation)
|
|
1584
|
+
return this.#hostActivation;
|
|
1585
|
+
const activation = (async () => {
|
|
1586
|
+
if (session.hostScope.phase === EnvironmentPhase.Closed)
|
|
1587
|
+
session.hostScope = await this.redeclareHostScope(session.hostScope);
|
|
1588
|
+
await this.session.programs.activate(session.hostScope.id);
|
|
1589
|
+
while (this.#pendingHostScopes.size) {
|
|
1590
|
+
let environment = this.#pendingHostScopes.values().next().value;
|
|
1591
|
+
if (environment.phase === EnvironmentPhase.Closed || [...environment.resources.values()].some((resource) => session.resources.dependencyIds(resource.options).some((id, index) => id !== resource.dependencies[index]))) {
|
|
1592
|
+
const previous = environment;
|
|
1593
|
+
environment = await this.redeclareHostScope(previous);
|
|
1594
|
+
this.#pendingHostScopes.delete(previous);
|
|
1595
|
+
this.#pendingHostScopes.add(environment);
|
|
1596
|
+
}
|
|
1597
|
+
await this.session.programs.activate(environment.id);
|
|
1598
|
+
this.#pendingHostScopes.delete(environment);
|
|
1599
|
+
}
|
|
1600
|
+
})();
|
|
1601
|
+
this.#hostActivation = activation;
|
|
1602
|
+
const clear = () => {
|
|
1603
|
+
if (this.#hostActivation === activation)
|
|
1604
|
+
this.#hostActivation = undefined;
|
|
1605
|
+
};
|
|
1606
|
+
activation.then(clear, clear);
|
|
1607
|
+
return activation;
|
|
1608
|
+
}
|
|
1609
|
+
async redeclareHostScope(previous) {
|
|
1610
|
+
const session = this.session;
|
|
1611
|
+
await session.programs.cleanup([previous]);
|
|
1612
|
+
const environment = this.environment({ kind: OwnerKind.Host }, previous.orb);
|
|
1613
|
+
session.resources.redeclare(environment, previous);
|
|
1614
|
+
environment.phase = EnvironmentPhase.Prepared;
|
|
1615
|
+
session.programs.register(environment);
|
|
1616
|
+
return environment;
|
|
1617
|
+
}
|
|
1618
|
+
requirement(environment, service) {
|
|
1619
|
+
const own = environment.orb.definition.services?.[service];
|
|
1620
|
+
if (own)
|
|
1621
|
+
return { service, apiVersion: environment.orb.info.apiVersion };
|
|
1622
|
+
for (const [alias, requirement] of Object.entries(environment.orb.definition.requires ?? {})) {
|
|
1623
|
+
let provider;
|
|
1624
|
+
try {
|
|
1625
|
+
provider = this.session.kernel.command(KernelOp.OrbNamed, {
|
|
1626
|
+
name: requirement.orb ?? alias,
|
|
1627
|
+
ticket: environment.orb.ticket
|
|
1628
|
+
});
|
|
1629
|
+
} catch (error) {
|
|
1630
|
+
if (error instanceof TembraError2 && error.code === Code2.Gone && error.reason === Reason2.Orb)
|
|
1631
|
+
continue;
|
|
1632
|
+
throw error;
|
|
1633
|
+
}
|
|
1634
|
+
const selected = alias === service ? provider.services.find((s) => s.name === alias) ?? (provider.services.length === 1 ? provider.services[0] : undefined) : provider.services.find((s) => s.name === service);
|
|
1635
|
+
if (!selected)
|
|
1636
|
+
continue;
|
|
1637
|
+
const methods = requirement.services?.[selected.name] ?? requirement.methods;
|
|
1638
|
+
if (!methods)
|
|
1639
|
+
throw new TembraError2(Errors2.Forbidden.UndeclaredService, service);
|
|
1640
|
+
return { service: selected.name, apiVersion: requirement.apiVersion, methods };
|
|
1641
|
+
}
|
|
1642
|
+
throw new TembraError2(Errors2.Forbidden.UndeclaredDependency, service);
|
|
1643
|
+
}
|
|
1644
|
+
hostResource(name) {
|
|
1645
|
+
const resource = this.#hostResources.get(name);
|
|
1646
|
+
if (!resource)
|
|
1647
|
+
throw new TembraError2(Errors2.Forbidden.HostResource, name);
|
|
1648
|
+
return resource.handle;
|
|
1649
|
+
}
|
|
1650
|
+
resource(name, options) {
|
|
1651
|
+
const session = this.session;
|
|
1652
|
+
if (session.closing)
|
|
1653
|
+
throw new TembraError2(Errors2.Closed.Host);
|
|
1654
|
+
if (this.#hostResources.has(name))
|
|
1655
|
+
refuse(Errors2.Invalid.DuplicateResource);
|
|
1656
|
+
const environment = this.environment({ kind: OwnerKind.Host }, session.hostScope.orb);
|
|
1657
|
+
try {
|
|
1658
|
+
const resource = new Declaration(session, environment).resource(name, options);
|
|
1659
|
+
this.#hostResources.set(name, environment.resources.get(name));
|
|
1660
|
+
environment.phase = EnvironmentPhase.Prepared;
|
|
1661
|
+
session.programs.register(environment);
|
|
1662
|
+
this.#pendingHostScopes.add(environment);
|
|
1663
|
+
session.track(this.readyHostScope()).catch((error) => session.report(error));
|
|
1664
|
+
return resource;
|
|
1665
|
+
} catch (error) {
|
|
1666
|
+
session.programs.scopes.delete(environment.id);
|
|
1667
|
+
throw error;
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
registerHost(environment) {
|
|
1671
|
+
for (const [name, resource] of environment.resources)
|
|
1672
|
+
this.#hostResources.set(name, resource);
|
|
1673
|
+
}
|
|
1674
|
+
clear() {
|
|
1675
|
+
this.#hostResources.clear();
|
|
1676
|
+
this.#pendingHostScopes.clear();
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
// src/runtime/session.ts
|
|
1681
|
+
class Session {
|
|
1682
|
+
options;
|
|
1683
|
+
contextTokens = new WeakMap;
|
|
1684
|
+
calls = new Calls(this);
|
|
1685
|
+
handles = new References(this);
|
|
1686
|
+
scopes = new Scopes(this);
|
|
1687
|
+
lifecycle = new Lifecycle(this);
|
|
1688
|
+
kernel;
|
|
1689
|
+
values;
|
|
1690
|
+
resources = new Resources(this);
|
|
1691
|
+
activities = new Activities(this);
|
|
1692
|
+
orbs = new Orbs(this);
|
|
1693
|
+
replacements = new Replacements(this);
|
|
1694
|
+
programs = new Programs(this);
|
|
1695
|
+
objects = new Map;
|
|
1696
|
+
references = new Map;
|
|
1697
|
+
rootReferences = new Map;
|
|
1698
|
+
controllers = new Map;
|
|
1699
|
+
jobs = new Set;
|
|
1700
|
+
cleanupErrors = [];
|
|
1701
|
+
hostScope;
|
|
1702
|
+
codec;
|
|
1703
|
+
name;
|
|
1704
|
+
principal;
|
|
1705
|
+
errors = [];
|
|
1706
|
+
now;
|
|
1707
|
+
telemetry;
|
|
1708
|
+
closing = false;
|
|
1709
|
+
#publishing = false;
|
|
1710
|
+
#publications = [];
|
|
1711
|
+
constructor(options) {
|
|
1712
|
+
this.options = options;
|
|
1713
|
+
this.kernel = new Kernel(options.kernel);
|
|
1714
|
+
if (options.telemetry && !this.kernel.features.telemetry)
|
|
1715
|
+
throw new TembraError2(Errors2.Unsupported.Telemetry);
|
|
1716
|
+
this.telemetry = options.telemetry ? new Telemetry2(options.telemetry.capacity, options.telemetry.sampleEvery) : undefined;
|
|
1717
|
+
this.values = new Values(() => this.kernel.command(KernelOp.Allocate));
|
|
1718
|
+
this.codec = options.serialization ?? jsonCodec2;
|
|
1719
|
+
this.name = options.name ?? "host";
|
|
1720
|
+
this.principal = options.principal ?? "host";
|
|
1721
|
+
const clock = options.now ?? (() => performance.now());
|
|
1722
|
+
const origin = options.clockOrigin ?? clock();
|
|
1723
|
+
this.now = () => Math.floor(clock() - origin);
|
|
1724
|
+
const hostOrb = {
|
|
1725
|
+
info: {
|
|
1726
|
+
isolated: false,
|
|
1727
|
+
id: 0,
|
|
1728
|
+
owner: 0,
|
|
1729
|
+
name: "$host",
|
|
1730
|
+
apiVersion: 1,
|
|
1731
|
+
codeVersion: 1,
|
|
1732
|
+
services: [],
|
|
1733
|
+
hooks: [],
|
|
1734
|
+
hookSignatures: {},
|
|
1735
|
+
requires: []
|
|
1736
|
+
},
|
|
1737
|
+
definition: { name: "$host", apiVersion: 1 }
|
|
1738
|
+
};
|
|
1739
|
+
this.hostScope = this.scopes.environment({ kind: OwnerKind.Host }, hostOrb);
|
|
1740
|
+
for (const [name, declaration] of Object.entries(options.resources ?? {})) {
|
|
1741
|
+
new Declaration(this, this.hostScope).resource(name, declaration);
|
|
1742
|
+
}
|
|
1743
|
+
this.scopes.registerHost(this.hostScope);
|
|
1744
|
+
this.hostScope.phase = EnvironmentPhase.Prepared;
|
|
1745
|
+
this.programs.register(this.hostScope);
|
|
1746
|
+
}
|
|
1747
|
+
principalFor(object) {
|
|
1748
|
+
return this.objects.get(object)?.address.principal ?? this.principal;
|
|
1749
|
+
}
|
|
1750
|
+
snapshot(object) {
|
|
1751
|
+
return this.kernel.command(KernelOp.Snapshot, { object });
|
|
1752
|
+
}
|
|
1753
|
+
value(id) {
|
|
1754
|
+
if (this.values.has(id))
|
|
1755
|
+
return this.values.get(id);
|
|
1756
|
+
if (!this.options.native)
|
|
1757
|
+
refuse(Errors2.Invalid.ValueGone);
|
|
1758
|
+
const value = this.options.native.value(id);
|
|
1759
|
+
this.values.set(id, value);
|
|
1760
|
+
return value;
|
|
1761
|
+
}
|
|
1762
|
+
check(value, object) {
|
|
1763
|
+
const ctx = context(value, this);
|
|
1764
|
+
if (!ctx.invocation || ctx.invocation.object !== object)
|
|
1765
|
+
throw new TembraError2(Errors2.Forbidden.StateOwner);
|
|
1766
|
+
return ctx.invocation;
|
|
1767
|
+
}
|
|
1768
|
+
adopt(object, value, revision, candidate) {
|
|
1769
|
+
const invocation = this.check(value, object);
|
|
1770
|
+
const id = this.values.put(candidate);
|
|
1771
|
+
try {
|
|
1772
|
+
return this.kernel.command(KernelOp.StateAdopt, {
|
|
1773
|
+
call: invocation.id,
|
|
1774
|
+
object,
|
|
1775
|
+
revision,
|
|
1776
|
+
value: id
|
|
1777
|
+
});
|
|
1778
|
+
} catch (error) {
|
|
1779
|
+
this.values.drop(id);
|
|
1780
|
+
throw error;
|
|
1781
|
+
} finally {
|
|
1782
|
+
this.lifecycle.flush();
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
publish(operation) {
|
|
1786
|
+
this.#publications.push(operation);
|
|
1787
|
+
if (this.#publishing)
|
|
1788
|
+
return;
|
|
1789
|
+
this.#publishing = true;
|
|
1790
|
+
try {
|
|
1791
|
+
while (this.#publications.length)
|
|
1792
|
+
this.#publications.shift()();
|
|
1793
|
+
} finally {
|
|
1794
|
+
this.#publishing = false;
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
report(error) {
|
|
1798
|
+
const reported = failure(error);
|
|
1799
|
+
if (this.errors.length === 64)
|
|
1800
|
+
this.errors.shift();
|
|
1801
|
+
this.errors.push(reported);
|
|
1802
|
+
try {
|
|
1803
|
+
this.options.onError?.(reported);
|
|
1804
|
+
} catch {}
|
|
1805
|
+
}
|
|
1806
|
+
track(job, cleanup = false) {
|
|
1807
|
+
this.jobs.add(job);
|
|
1808
|
+
job.then(() => {
|
|
1809
|
+
this.jobs.delete(job);
|
|
1810
|
+
}, (error) => {
|
|
1811
|
+
this.jobs.delete(job);
|
|
1812
|
+
if (cleanup) {
|
|
1813
|
+
this.cleanupErrors.push(error);
|
|
1814
|
+
this.report(error);
|
|
1815
|
+
}
|
|
1816
|
+
});
|
|
1817
|
+
return job;
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
// src/interpreter/http-ingress-fetch.ts
|
|
1822
|
+
var NULL_BODY = new Set([101, 103, 204, 205, 304]);
|
|
1823
|
+
function isFetchRequest(value) {
|
|
1824
|
+
return typeof Request === "function" && value instanceof Request;
|
|
1825
|
+
}
|
|
1826
|
+
function iterate(stream) {
|
|
1827
|
+
return {
|
|
1828
|
+
[Symbol.asyncIterator]() {
|
|
1829
|
+
const reader = stream.getReader();
|
|
1830
|
+
return {
|
|
1831
|
+
async next() {
|
|
1832
|
+
const next = await reader.read();
|
|
1833
|
+
return next.done ? { done: true, value: undefined } : { done: false, value: next.value };
|
|
1834
|
+
},
|
|
1835
|
+
async return() {
|
|
1836
|
+
await reader.cancel();
|
|
1837
|
+
return { done: true, value: undefined };
|
|
1838
|
+
}
|
|
1839
|
+
};
|
|
1840
|
+
}
|
|
1841
|
+
};
|
|
1842
|
+
}
|
|
1843
|
+
function fromFetchRequest(request) {
|
|
1844
|
+
if (typeof ReadableStream !== "function")
|
|
1845
|
+
throw new TypeError("WHATWG ReadableStream is unavailable on this host; pass an IncomingHttpRequest to receive raw parts");
|
|
1846
|
+
const body = request.body;
|
|
1847
|
+
if (body === undefined)
|
|
1848
|
+
throw new TypeError("WHATWG Request has no body stream on this host; pass an IncomingHttpRequest to receive raw parts");
|
|
1849
|
+
const url = new URL(request.url);
|
|
1850
|
+
return {
|
|
1851
|
+
method: request.method,
|
|
1852
|
+
scheme: url.protocol.slice(0, -1),
|
|
1853
|
+
authority: url.host,
|
|
1854
|
+
pathWithQuery: url.pathname + url.search,
|
|
1855
|
+
fields: [...request.headers].map(([name, value]) => [name, bytesOf(value)]),
|
|
1856
|
+
body: body ? iterate(body) : null
|
|
1857
|
+
};
|
|
1858
|
+
}
|
|
1859
|
+
function discard(response) {
|
|
1860
|
+
response.body[Symbol.asyncIterator]().return?.();
|
|
1861
|
+
}
|
|
1862
|
+
function toFetchResponse(response) {
|
|
1863
|
+
const refuse = (message) => {
|
|
1864
|
+
discard(response);
|
|
1865
|
+
return new TypeError(`${message}; pass an IncomingHttpRequest to receive raw parts`);
|
|
1866
|
+
};
|
|
1867
|
+
if (typeof Response !== "function" || typeof Headers !== "function")
|
|
1868
|
+
throw refuse("WHATWG Response is unavailable on this host");
|
|
1869
|
+
if (response.status < 200)
|
|
1870
|
+
throw refuse(`HTTP status ${response.status} has no WHATWG Response`);
|
|
1871
|
+
const headers = new Headers;
|
|
1872
|
+
try {
|
|
1873
|
+
for (const [name, value] of response.fields)
|
|
1874
|
+
headers.append(name, byteString(value));
|
|
1875
|
+
} catch (error) {
|
|
1876
|
+
throw refuse(error instanceof Error ? error.message : String(error));
|
|
1877
|
+
}
|
|
1878
|
+
const empty = NULL_BODY.has(response.status);
|
|
1879
|
+
if (!empty && typeof ReadableStream !== "function")
|
|
1880
|
+
throw refuse("WHATWG ReadableStream is unavailable on this host");
|
|
1881
|
+
const iterator = response.body[Symbol.asyncIterator]();
|
|
1882
|
+
const body = empty ? null : new ReadableStream({
|
|
1883
|
+
async pull(controller) {
|
|
1884
|
+
const next = await iterator.next();
|
|
1885
|
+
if (!next.done)
|
|
1886
|
+
return controller.enqueue(next.value);
|
|
1887
|
+
if ((await response.trailers)?.length)
|
|
1888
|
+
return controller.error(new TypeError("response trailers have no WHATWG representation"));
|
|
1889
|
+
controller.close();
|
|
1890
|
+
},
|
|
1891
|
+
async cancel() {
|
|
1892
|
+
await iterator.return?.();
|
|
1893
|
+
}
|
|
1894
|
+
}, { highWaterMark: 0 });
|
|
1895
|
+
const result = new Response(body, {
|
|
1896
|
+
status: response.status,
|
|
1897
|
+
headers
|
|
1898
|
+
});
|
|
1899
|
+
for (const [name] of response.fields)
|
|
1900
|
+
if (!result.headers.has(name)) {
|
|
1901
|
+
iterator.return?.();
|
|
1902
|
+
throw new TypeError(`the platform Response drops the ${name} field; pass an IncomingHttpRequest to receive raw parts`);
|
|
1903
|
+
}
|
|
1904
|
+
if (empty)
|
|
1905
|
+
drainEmpty(iterator);
|
|
1906
|
+
return result;
|
|
1907
|
+
}
|
|
1908
|
+
async function drainEmpty(iterator) {
|
|
1909
|
+
try {
|
|
1910
|
+
const next = await iterator.next();
|
|
1911
|
+
if (!next.done)
|
|
1912
|
+
await iterator.return?.();
|
|
1913
|
+
} catch {}
|
|
1914
|
+
}
|
|
1915
|
+
// src/interpreter/gate.ts
|
|
1916
|
+
class Gate {
|
|
1917
|
+
#busy = false;
|
|
1918
|
+
#queue = [];
|
|
1919
|
+
enter(milliseconds, signal) {
|
|
1920
|
+
return new Promise((resolve, reject) => {
|
|
1921
|
+
let timer;
|
|
1922
|
+
const detach = () => {
|
|
1923
|
+
clearTimeout(timer);
|
|
1924
|
+
signal?.removeEventListener("abort", cancel);
|
|
1925
|
+
};
|
|
1926
|
+
const remove = (error) => {
|
|
1927
|
+
const index = this.#queue.indexOf(acquire);
|
|
1928
|
+
if (index < 0)
|
|
1929
|
+
return;
|
|
1930
|
+
this.#queue.splice(index, 1);
|
|
1931
|
+
detach();
|
|
1932
|
+
reject(error);
|
|
1933
|
+
};
|
|
1934
|
+
const cancel = () => remove(new Error("Operation cancelled before interpreter admission"));
|
|
1935
|
+
const acquire = () => {
|
|
1936
|
+
detach();
|
|
1937
|
+
this.#busy = true;
|
|
1938
|
+
let released = false;
|
|
1939
|
+
resolve(() => {
|
|
1940
|
+
if (released)
|
|
1941
|
+
return;
|
|
1942
|
+
released = true;
|
|
1943
|
+
const next = this.#queue.shift();
|
|
1944
|
+
if (next)
|
|
1945
|
+
next();
|
|
1946
|
+
else
|
|
1947
|
+
this.#busy = false;
|
|
1948
|
+
});
|
|
1949
|
+
};
|
|
1950
|
+
if (signal?.aborted) {
|
|
1951
|
+
reject(new Error("Operation cancelled before interpreter admission"));
|
|
1952
|
+
return;
|
|
1953
|
+
}
|
|
1954
|
+
if (!this.#busy)
|
|
1955
|
+
acquire();
|
|
1956
|
+
else {
|
|
1957
|
+
this.#queue.push(acquire);
|
|
1958
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
1959
|
+
if (milliseconds !== undefined)
|
|
1960
|
+
timer = setTimeout(() => remove(new Error("Interpreter factory admission timed out while another callback held the VM")), milliseconds);
|
|
1961
|
+
}
|
|
1962
|
+
});
|
|
1963
|
+
}
|
|
1964
|
+
}
|
|
1965
|
+
|
|
1966
|
+
// src/interpreter/host-protocol.ts
|
|
1967
|
+
var REVISION_LENGTH = 20;
|
|
1968
|
+
var WAIT_LIMIT_MILLISECONDS = 5000;
|
|
1969
|
+
var HANDLE = { scope: "scope?", id: "u32" };
|
|
1970
|
+
var SNAPSHOT = { ...HANDLE, known: "revision?" };
|
|
1971
|
+
var SYNC = {
|
|
1972
|
+
console: { level: "level", message: "string" },
|
|
1973
|
+
address: {},
|
|
1974
|
+
orb: {},
|
|
1975
|
+
"signal.cancelled": {},
|
|
1976
|
+
"context.check": {},
|
|
1977
|
+
"context.principal": {},
|
|
1978
|
+
"context.cancel": {},
|
|
1979
|
+
"state.declare": { initial: "json?", version: "u32", validate: "callback?" },
|
|
1980
|
+
"state.read": SNAPSHOT,
|
|
1981
|
+
"state.update": { ...HANDLE, value: "json?" },
|
|
1982
|
+
"reference.declare": { service: "string", key: "keys" },
|
|
1983
|
+
"reference.release": HANDLE,
|
|
1984
|
+
"reference.status": HANDLE,
|
|
1985
|
+
"reference.state": SNAPSHOT,
|
|
1986
|
+
"resource.declare": {
|
|
1987
|
+
name: "string",
|
|
1988
|
+
version: "u32",
|
|
1989
|
+
open: "u32",
|
|
1990
|
+
close: "u32",
|
|
1991
|
+
dependencies: "handles?"
|
|
1992
|
+
},
|
|
1993
|
+
"resource.read": HANDLE,
|
|
1994
|
+
"hook.declare": { name: "string" }
|
|
1995
|
+
};
|
|
1996
|
+
var ASYNC = {
|
|
1997
|
+
"hook.run": { ...HANDLE, value: "json" },
|
|
1998
|
+
"reference.ready": HANDLE,
|
|
1999
|
+
"reference.acquire": { service: "string", key: "keys" },
|
|
2000
|
+
"reference.call": { ...HANDLE, method: "string", args: "json" },
|
|
2001
|
+
wait: { milliseconds: "u32" }
|
|
2002
|
+
};
|
|
2003
|
+
var LEVELS = ["log", "debug", "info", "warn", "error"];
|
|
2004
|
+
function decodeHostRequest(packet) {
|
|
2005
|
+
return decode2(packet, SYNC, "host request");
|
|
2006
|
+
}
|
|
2007
|
+
function decodeAsyncHostRequest(packet) {
|
|
2008
|
+
return decode2(packet, ASYNC, "asynchronous host request");
|
|
2009
|
+
}
|
|
2010
|
+
function survivesCancellation(request) {
|
|
2011
|
+
switch (request.operation) {
|
|
2012
|
+
case "console":
|
|
2013
|
+
case "signal.cancelled":
|
|
2014
|
+
case "state.read":
|
|
2015
|
+
case "resource.read":
|
|
2016
|
+
case "reference.state":
|
|
2017
|
+
case "reference.status":
|
|
2018
|
+
case "reference.release":
|
|
2019
|
+
return true;
|
|
2020
|
+
default:
|
|
2021
|
+
return false;
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
function decode2(packet, schemas, label) {
|
|
2025
|
+
const malformed = (reason) => new Error(`Malformed ${label}: ${reason}`);
|
|
2026
|
+
let raw;
|
|
2027
|
+
try {
|
|
2028
|
+
raw = JSON.parse(packet);
|
|
2029
|
+
} catch {
|
|
2030
|
+
throw malformed("invalid JSON");
|
|
2031
|
+
}
|
|
2032
|
+
if (!isRecord(raw))
|
|
2033
|
+
throw malformed("expected an object");
|
|
2034
|
+
const operation = raw.operation;
|
|
2035
|
+
if (typeof operation !== "string")
|
|
2036
|
+
throw malformed("expected string operation");
|
|
2037
|
+
if (!Object.hasOwn(schemas, operation))
|
|
2038
|
+
throw new Error(`Unsupported ${label} operation ${operation}`);
|
|
2039
|
+
const schema = schemas[operation];
|
|
2040
|
+
for (const key of Object.keys(raw))
|
|
2041
|
+
if (key !== "operation" && !Object.hasOwn(schema, key))
|
|
2042
|
+
throw malformed(`unknown field ${key}`);
|
|
2043
|
+
const request = { operation };
|
|
2044
|
+
for (const [key, kind] of Object.entries(schema)) {
|
|
2045
|
+
const value = field(raw[key], kind, () => malformed(`invalid field ${key}`));
|
|
2046
|
+
if (value !== undefined)
|
|
2047
|
+
request[key] = value;
|
|
2048
|
+
}
|
|
2049
|
+
return request;
|
|
2050
|
+
}
|
|
2051
|
+
function field(value, kind, invalid) {
|
|
2052
|
+
const absent = value === undefined || value === null;
|
|
2053
|
+
switch (kind) {
|
|
2054
|
+
case "u32":
|
|
2055
|
+
if (!isU32(value))
|
|
2056
|
+
throw invalid();
|
|
2057
|
+
return value;
|
|
2058
|
+
case "string":
|
|
2059
|
+
if (typeof value !== "string")
|
|
2060
|
+
throw invalid();
|
|
2061
|
+
return value;
|
|
2062
|
+
case "keys":
|
|
2063
|
+
if (!Array.isArray(value) || !value.every((item) => typeof item === "string"))
|
|
2064
|
+
throw invalid();
|
|
2065
|
+
return value;
|
|
2066
|
+
case "level":
|
|
2067
|
+
if (typeof value !== "string" || !LEVELS.includes(value))
|
|
2068
|
+
throw invalid();
|
|
2069
|
+
return value;
|
|
2070
|
+
case "json":
|
|
2071
|
+
if (value === undefined)
|
|
2072
|
+
throw invalid();
|
|
2073
|
+
return value;
|
|
2074
|
+
case "json?":
|
|
2075
|
+
return value ?? null;
|
|
2076
|
+
case "callback?":
|
|
2077
|
+
if (absent)
|
|
2078
|
+
return null;
|
|
2079
|
+
if (!isU32(value))
|
|
2080
|
+
throw invalid();
|
|
2081
|
+
return value;
|
|
2082
|
+
case "revision?":
|
|
2083
|
+
if (absent)
|
|
2084
|
+
return;
|
|
2085
|
+
if (typeof value !== "string" || value.length > REVISION_LENGTH || !/^\d+$/.test(value))
|
|
2086
|
+
throw invalid();
|
|
2087
|
+
return value;
|
|
2088
|
+
case "scope?":
|
|
2089
|
+
if (absent)
|
|
2090
|
+
return;
|
|
2091
|
+
if (!Number.isSafeInteger(value) || value < 0)
|
|
2092
|
+
throw invalid();
|
|
2093
|
+
return value;
|
|
2094
|
+
case "handles?":
|
|
2095
|
+
if (absent)
|
|
2096
|
+
return [];
|
|
2097
|
+
if (!Array.isArray(value))
|
|
2098
|
+
throw invalid();
|
|
2099
|
+
return value.map((item) => {
|
|
2100
|
+
if (!isRecord(item) || Object.keys(item).some((key) => key !== "scope" && key !== "id"))
|
|
2101
|
+
throw invalid();
|
|
2102
|
+
const scope = field(item.scope, "scope?", invalid);
|
|
2103
|
+
return scope === undefined ? { id: field(item.id, "u32", invalid) } : { scope, id: field(item.id, "u32", invalid) };
|
|
2104
|
+
});
|
|
2105
|
+
}
|
|
2106
|
+
}
|
|
2107
|
+
function isRecord(value) {
|
|
2108
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2109
|
+
}
|
|
2110
|
+
function isU32(value) {
|
|
2111
|
+
return Number.isInteger(value) && value >= 0 && value <= 4294967295;
|
|
2112
|
+
}
|
|
2113
|
+
|
|
2114
|
+
// src/interpreter/acquire.ts
|
|
2115
|
+
async function acquireReference(declaration, service, key, context, ended, publish) {
|
|
2116
|
+
context.check();
|
|
2117
|
+
if (!context.invocation)
|
|
2118
|
+
throw new Error("Reference acquisition requires an admitted invocation");
|
|
2119
|
+
const session = declaration.session;
|
|
2120
|
+
const requirement = session.scopes.requirement(declaration.environment, service);
|
|
2121
|
+
const reference = session.handles.hold(requirement.service, key, {
|
|
2122
|
+
...requirement.apiVersion ? { apiVersion: requirement.apiVersion } : {},
|
|
2123
|
+
...requirement.methods ? { methods: requirement.methods } : {}
|
|
2124
|
+
}, context);
|
|
2125
|
+
try {
|
|
2126
|
+
await session.calls.observe(reference.ready, combinedSignal(context.signal, ended));
|
|
2127
|
+
context.check();
|
|
2128
|
+
checkSignal(ended);
|
|
2129
|
+
return publish(reference);
|
|
2130
|
+
} catch (error) {
|
|
2131
|
+
try {
|
|
2132
|
+
reference.release();
|
|
2133
|
+
} catch (release) {
|
|
2134
|
+
session.report(release);
|
|
2135
|
+
}
|
|
2136
|
+
throw error;
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
// src/interpreter/scope.ts
|
|
2141
|
+
var scopeEnded = Object.freeze(new Error("Interpreter callback scope ended"));
|
|
2142
|
+
function authoritySignal(authority) {
|
|
2143
|
+
if ("context" in authority)
|
|
2144
|
+
return authority.context.signal;
|
|
2145
|
+
if ("signal" in authority)
|
|
2146
|
+
return authority.signal;
|
|
2147
|
+
return;
|
|
2148
|
+
}
|
|
2149
|
+
|
|
2150
|
+
class Scope {
|
|
2151
|
+
revision;
|
|
2152
|
+
declaration;
|
|
2153
|
+
service;
|
|
2154
|
+
id;
|
|
2155
|
+
parent;
|
|
2156
|
+
validators = [];
|
|
2157
|
+
states = new Map;
|
|
2158
|
+
references = new Map;
|
|
2159
|
+
resources = new Map;
|
|
2160
|
+
hooks = new Map;
|
|
2161
|
+
#next = 0;
|
|
2162
|
+
constructor(revision, declaration, service) {
|
|
2163
|
+
this.revision = revision;
|
|
2164
|
+
this.declaration = declaration;
|
|
2165
|
+
this.service = service;
|
|
2166
|
+
this.id = declaration.environment.id;
|
|
2167
|
+
const parent = service === null ? undefined : declaration.environment.orb.scope;
|
|
2168
|
+
this.parent = service === null || !parent ? undefined : revision.scopes.get(parent.id);
|
|
2169
|
+
if (service !== null && !this.parent)
|
|
2170
|
+
throw new Error("Missing interpreter Orb scope");
|
|
2171
|
+
}
|
|
2172
|
+
exchange(authority) {
|
|
2173
|
+
let ended;
|
|
2174
|
+
let cancelled = false;
|
|
2175
|
+
const signal = authoritySignal(authority);
|
|
2176
|
+
return {
|
|
2177
|
+
cancel: () => {
|
|
2178
|
+
if (cancelled)
|
|
2179
|
+
return;
|
|
2180
|
+
cancelled = true;
|
|
2181
|
+
ended?.abort(scopeEnded);
|
|
2182
|
+
},
|
|
2183
|
+
...signal ? { signal } : {},
|
|
2184
|
+
check: () => {
|
|
2185
|
+
if ("context" in authority)
|
|
2186
|
+
authority.context.check();
|
|
2187
|
+
if ("signal" in authority)
|
|
2188
|
+
checkSignal(authority.signal);
|
|
2189
|
+
},
|
|
2190
|
+
sync: (request) => this.sync(request, authority),
|
|
2191
|
+
async: (request) => {
|
|
2192
|
+
if (cancelled)
|
|
2193
|
+
return Promise.reject(scopeEnded);
|
|
2194
|
+
ended ??= new AbortController;
|
|
2195
|
+
return this.async(request, authority, ended.signal);
|
|
2196
|
+
},
|
|
2197
|
+
deliver: (request, value, publish) => {
|
|
2198
|
+
let accepted = false;
|
|
2199
|
+
try {
|
|
2200
|
+
accepted = publish(value);
|
|
2201
|
+
} finally {
|
|
2202
|
+
if (!accepted && request.operation === "reference.acquire" && this.revision.views.has(request.service) && typeof value === "number") {
|
|
2203
|
+
const table = this.parent ?? this;
|
|
2204
|
+
const slot = table.references.get(value);
|
|
2205
|
+
const root = "context" in authority ? authority.context.root : undefined;
|
|
2206
|
+
if (slot?.binding === request.service && slot.root === root) {
|
|
2207
|
+
table.references.delete(value);
|
|
2208
|
+
slot.reference.release();
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
}
|
|
2212
|
+
}
|
|
2213
|
+
};
|
|
2214
|
+
}
|
|
2215
|
+
context(authority) {
|
|
2216
|
+
if (!("context" in authority))
|
|
2217
|
+
throw new Error("Operation requires an admitted invocation");
|
|
2218
|
+
authority.context.check();
|
|
2219
|
+
return authority.context;
|
|
2220
|
+
}
|
|
2221
|
+
factory(authority) {
|
|
2222
|
+
if (!("declaration" in authority))
|
|
2223
|
+
throw new Error("Operation requires an active declaration");
|
|
2224
|
+
return authority.declaration;
|
|
2225
|
+
}
|
|
2226
|
+
selected(scope) {
|
|
2227
|
+
if (scope === undefined || scope === this.id)
|
|
2228
|
+
return this;
|
|
2229
|
+
if (this.parent !== undefined && scope === this.parent.id)
|
|
2230
|
+
return this.parent;
|
|
2231
|
+
throw new Error("Foreign environment handle");
|
|
2232
|
+
}
|
|
2233
|
+
handle(table, id, kind) {
|
|
2234
|
+
const value = table.get(id);
|
|
2235
|
+
if (value === undefined)
|
|
2236
|
+
throw new Error(`Unknown ${kind} handle`);
|
|
2237
|
+
return value;
|
|
2238
|
+
}
|
|
2239
|
+
allocate() {
|
|
2240
|
+
if (this.#next >= 4294967295)
|
|
2241
|
+
throw new Error("Scope handle space exhausted");
|
|
2242
|
+
return ++this.#next;
|
|
2243
|
+
}
|
|
2244
|
+
snapshot(value, object, known) {
|
|
2245
|
+
const snapshot = this.declaration.session.snapshot(object);
|
|
2246
|
+
return snapshot.revision === known ? { revision: snapshot.revision, version: snapshot.version } : { value, revision: snapshot.revision, version: snapshot.version };
|
|
2247
|
+
}
|
|
2248
|
+
sync(request, authority) {
|
|
2249
|
+
if (request.operation === "console")
|
|
2250
|
+
throw new Error("Console records are consumed by the interpreter port");
|
|
2251
|
+
if ("validation" in authority && request.operation !== "state.read")
|
|
2252
|
+
throw new Error("Validators may only read retained state");
|
|
2253
|
+
if (!survivesCancellation(request)) {
|
|
2254
|
+
if ("context" in authority)
|
|
2255
|
+
authority.context.check();
|
|
2256
|
+
if ("signal" in authority)
|
|
2257
|
+
checkSignal(authority.signal);
|
|
2258
|
+
}
|
|
2259
|
+
switch (request.operation) {
|
|
2260
|
+
case "address": {
|
|
2261
|
+
const declaration = this.factory(authority);
|
|
2262
|
+
return {
|
|
2263
|
+
key: this.service === null ? [] : declaration.key,
|
|
2264
|
+
principal: declaration.principal
|
|
2265
|
+
};
|
|
2266
|
+
}
|
|
2267
|
+
case "orb":
|
|
2268
|
+
this.factory(authority);
|
|
2269
|
+
return this.parent?.id ?? null;
|
|
2270
|
+
case "state.declare": {
|
|
2271
|
+
const declaration = this.factory(authority);
|
|
2272
|
+
const id = this.allocate();
|
|
2273
|
+
const state = declaration.state(request.initial, { version: request.version });
|
|
2274
|
+
this.states.set(id, state);
|
|
2275
|
+
if (request.validate !== null)
|
|
2276
|
+
this.validators.push(request.validate);
|
|
2277
|
+
return id;
|
|
2278
|
+
}
|
|
2279
|
+
case "state.read": {
|
|
2280
|
+
const selected = this.selected(request.scope);
|
|
2281
|
+
return selected.snapshot(this.handle(selected.states, request.id, "state").value, selected.declaration.environment.object.id, request.known);
|
|
2282
|
+
}
|
|
2283
|
+
case "state.update": {
|
|
2284
|
+
const selected = this.selected(request.scope);
|
|
2285
|
+
const state = this.handle(selected.states, request.id, "state");
|
|
2286
|
+
const value = state.update(this.context(authority), () => request.value);
|
|
2287
|
+
return selected.snapshot(value, selected.declaration.environment.object.id);
|
|
2288
|
+
}
|
|
2289
|
+
case "hook.declare": {
|
|
2290
|
+
const binding = this.revision.hooks.get(request.name);
|
|
2291
|
+
if (!binding)
|
|
2292
|
+
throw new Error("Hook is absent from the checked WIT declaration");
|
|
2293
|
+
const handle = this.factory(authority).hook(binding.name);
|
|
2294
|
+
const id = this.allocate();
|
|
2295
|
+
this.hooks.set(id, { handle, binding });
|
|
2296
|
+
return id;
|
|
2297
|
+
}
|
|
2298
|
+
case "reference.declare": {
|
|
2299
|
+
const service = this.revision.imports.get(request.service);
|
|
2300
|
+
if (!service)
|
|
2301
|
+
throw new Error("Reference is not a selected WIT Orb import");
|
|
2302
|
+
const reference = this.factory(authority).get(service, request.key);
|
|
2303
|
+
const id = this.allocate();
|
|
2304
|
+
this.references.set(id, { reference, binding: request.service });
|
|
2305
|
+
return id;
|
|
2306
|
+
}
|
|
2307
|
+
case "reference.release": {
|
|
2308
|
+
const slot = this.reference(request, authority);
|
|
2309
|
+
slot.reference.release();
|
|
2310
|
+
if (this.revision.views.has(slot.binding))
|
|
2311
|
+
this.selected(request.scope).references.delete(request.id);
|
|
2312
|
+
return null;
|
|
2313
|
+
}
|
|
2314
|
+
case "reference.status":
|
|
2315
|
+
return this.reference(request, authority).reference.status;
|
|
2316
|
+
case "reference.state": {
|
|
2317
|
+
const reference = this.reference(request, authority).reference;
|
|
2318
|
+
const record = this.declaration.session.handles.reference(reference);
|
|
2319
|
+
return this.snapshot(reference.state.value, record.object, request.known);
|
|
2320
|
+
}
|
|
2321
|
+
case "resource.declare": {
|
|
2322
|
+
const declaration = this.factory(authority);
|
|
2323
|
+
const dependencies = request.dependencies.map((dependency) => this.handle(this.selected(dependency.scope).resources, dependency.id, "resource dependency"));
|
|
2324
|
+
const { open, close } = request;
|
|
2325
|
+
const run = (callback, value, authority) => this.revision.execute(JSON.stringify({ kind: "callback", callback, value }), this.exchange(authority), authority);
|
|
2326
|
+
const options = {
|
|
2327
|
+
version: request.version,
|
|
2328
|
+
deps: dependencies,
|
|
2329
|
+
open: (signal) => run(open, null, { signal }),
|
|
2330
|
+
close: (value, context) => run(close, value, { context })
|
|
2331
|
+
};
|
|
2332
|
+
const resource = declaration.resource(request.name, options);
|
|
2333
|
+
const id = this.allocate();
|
|
2334
|
+
this.resources.set(id, resource);
|
|
2335
|
+
return id;
|
|
2336
|
+
}
|
|
2337
|
+
case "resource.read":
|
|
2338
|
+
return this.handle(this.selected(request.scope).resources, request.id, "resource").value;
|
|
2339
|
+
case "context.check":
|
|
2340
|
+
if (!("context" in authority))
|
|
2341
|
+
throw new Error("Operation requires an admitted invocation");
|
|
2342
|
+
return null;
|
|
2343
|
+
case "context.cancel":
|
|
2344
|
+
this.context(authority).cancel();
|
|
2345
|
+
return null;
|
|
2346
|
+
case "context.principal":
|
|
2347
|
+
return this.context(authority).principal;
|
|
2348
|
+
case "signal.cancelled":
|
|
2349
|
+
return authoritySignal(authority)?.aborted ?? false;
|
|
2350
|
+
}
|
|
2351
|
+
}
|
|
2352
|
+
reference(request, authority) {
|
|
2353
|
+
const selected = this.selected(request.scope);
|
|
2354
|
+
const slot = this.handle(selected.references, request.id, "reference");
|
|
2355
|
+
if (slot.root === undefined)
|
|
2356
|
+
return slot;
|
|
2357
|
+
const current = "context" in authority ? authority.context.root : undefined;
|
|
2358
|
+
const issued = selected === this || this.revision.views.has(slot.binding) && selected === this.parent;
|
|
2359
|
+
if (!issued || current !== slot.root)
|
|
2360
|
+
throw new Error("Reference belongs to another root");
|
|
2361
|
+
if (!this.declaration.session.rootReferences.has(slot.root))
|
|
2362
|
+
throw new Error("Reference expired with its root");
|
|
2363
|
+
return slot;
|
|
2364
|
+
}
|
|
2365
|
+
async acquire(request, authority, ended) {
|
|
2366
|
+
const context = this.context(authority);
|
|
2367
|
+
const binding = this.revision.imports.get(request.service);
|
|
2368
|
+
if (!binding)
|
|
2369
|
+
throw new Error("Reference is not a selected WIT Orb import");
|
|
2370
|
+
const session = this.declaration.session;
|
|
2371
|
+
const table = this.revision.views.has(request.service) ? this.parent ?? this : this;
|
|
2372
|
+
const { id, reference } = await acquireReference(this.declaration, binding, request.key, context, ended, (reference) => ({ id: table.allocate(), reference }));
|
|
2373
|
+
for (const [handle, slot] of table.references)
|
|
2374
|
+
if (slot.root !== undefined && !session.rootReferences.has(slot.root))
|
|
2375
|
+
table.references.delete(handle);
|
|
2376
|
+
table.references.set(id, { reference, binding: request.service, root: context.root });
|
|
2377
|
+
return id;
|
|
2378
|
+
}
|
|
2379
|
+
async async(request, authority, ended) {
|
|
2380
|
+
checkSignal(ended);
|
|
2381
|
+
switch (request.operation) {
|
|
2382
|
+
case "hook.run": {
|
|
2383
|
+
const context = this.context(authority);
|
|
2384
|
+
const { handle, binding } = this.handle(this.selected(request.scope).hooks, request.id, "hook");
|
|
2385
|
+
check(this.revision.contract, binding.slot, true, encode([request.value]));
|
|
2386
|
+
const shape = this.revision.signatures.get(binding.slot);
|
|
2387
|
+
const [input] = lift(shape?.params, [request.value]);
|
|
2388
|
+
const result = await handle.run(context, input) ?? null;
|
|
2389
|
+
return check(this.revision.contract, binding.slot, false, encode(result, VALUE_LIMIT, shape?.result));
|
|
2390
|
+
}
|
|
2391
|
+
case "reference.ready": {
|
|
2392
|
+
const owner = authoritySignal(authority);
|
|
2393
|
+
await this.declaration.session.calls.observe(this.reference(request, authority).reference.ready, owner ? combinedSignal(owner, ended) : ended);
|
|
2394
|
+
return null;
|
|
2395
|
+
}
|
|
2396
|
+
case "reference.acquire":
|
|
2397
|
+
return this.acquire(request, authority, ended);
|
|
2398
|
+
case "reference.call": {
|
|
2399
|
+
const context = this.context(authority);
|
|
2400
|
+
const { reference, binding } = this.reference(request, authority);
|
|
2401
|
+
const bound = this.revision.importMethods.get(binding)?.get(request.method);
|
|
2402
|
+
if (!bound)
|
|
2403
|
+
throw new Error("Unknown prepared import method");
|
|
2404
|
+
const method = bound.name;
|
|
2405
|
+
const input = check(this.revision.contract, bound.slot, true, encode(request.args));
|
|
2406
|
+
const signature = this.revision.importSignatures.get(binding);
|
|
2407
|
+
const capture = signature ? { signature, input, dataResult: true } : undefined;
|
|
2408
|
+
if (!Array.isArray(request.args))
|
|
2409
|
+
throw new Error("Import arguments must be a list");
|
|
2410
|
+
const record = this.declaration.session.handles.reference(reference);
|
|
2411
|
+
if (!record.methods.has(method))
|
|
2412
|
+
throw new Error("Reference does not expose this method");
|
|
2413
|
+
const shape = this.revision.signatures.get(bound.slot);
|
|
2414
|
+
const result = await this.declaration.session.calls.invokePhysical(record, method, lift(shape?.params, request.args), context, capture) ?? null;
|
|
2415
|
+
return capture?.output ?? check(this.revision.contract, bound.slot, false, encode(result, VALUE_LIMIT, shape?.result));
|
|
2416
|
+
}
|
|
2417
|
+
case "wait": {
|
|
2418
|
+
const { milliseconds } = request;
|
|
2419
|
+
if (milliseconds > WAIT_LIMIT_MILLISECONDS)
|
|
2420
|
+
throw new Error("Timer exceeds the callback wait limit");
|
|
2421
|
+
if ("context" in authority)
|
|
2422
|
+
this.context(authority);
|
|
2423
|
+
const ownerSignal = authoritySignal(authority);
|
|
2424
|
+
if (!ownerSignal)
|
|
2425
|
+
throw new Error("Timer requires an active callback");
|
|
2426
|
+
const signal = combinedSignal(ownerSignal, ended);
|
|
2427
|
+
checkSignal(signal);
|
|
2428
|
+
await new Promise((resolve, reject) => {
|
|
2429
|
+
const cancel = () => {
|
|
2430
|
+
clearTimeout(timer);
|
|
2431
|
+
signal.removeEventListener("abort", cancel);
|
|
2432
|
+
reject(new Error("Operation cancelled"));
|
|
2433
|
+
};
|
|
2434
|
+
const timer = setTimeout(() => {
|
|
2435
|
+
signal.removeEventListener("abort", cancel);
|
|
2436
|
+
resolve();
|
|
2437
|
+
}, milliseconds);
|
|
2438
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
2439
|
+
});
|
|
2440
|
+
return null;
|
|
2441
|
+
}
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
|
|
2446
|
+
// src/interpreter/revision.ts
|
|
2447
|
+
function exportedFunctions(description, contract) {
|
|
2448
|
+
const names = description.javascriptNames;
|
|
2449
|
+
const spelling = (name) => {
|
|
2450
|
+
const spelled = names[name];
|
|
2451
|
+
if (spelled === undefined)
|
|
2452
|
+
throw new Error(`Missing WIT JavaScript name for ${name}`);
|
|
2453
|
+
return spelled;
|
|
2454
|
+
};
|
|
2455
|
+
return description.exports.flatMap((item) => {
|
|
2456
|
+
const identity = item.contract;
|
|
2457
|
+
const functions = Object.keys(item.functions ?? {});
|
|
2458
|
+
if (!identity || !functions.length || identity === HTTP_HANDLER)
|
|
2459
|
+
return [];
|
|
2460
|
+
return [
|
|
2461
|
+
{
|
|
2462
|
+
interface: identity,
|
|
2463
|
+
service: spelling(identity.split("/").at(-1).split("@")[0]),
|
|
2464
|
+
functions: functions.map((name) => [contract.bind(identity, name, true), spelling(name)])
|
|
2465
|
+
}
|
|
2466
|
+
];
|
|
2467
|
+
});
|
|
2468
|
+
}
|
|
2469
|
+
function declaredHooks(bindings) {
|
|
2470
|
+
const hooks = {};
|
|
2471
|
+
for (const binding of bindings) {
|
|
2472
|
+
const hook = binding.composition === "series" ? series3() : binding.composition === "bail" ? bail3() : waterfall3();
|
|
2473
|
+
hooks[binding.name] = Object.assign(hook, { [signature2]: binding.signature });
|
|
2474
|
+
}
|
|
2475
|
+
return hooks;
|
|
2476
|
+
}
|
|
2477
|
+
|
|
2478
|
+
class Revision {
|
|
2479
|
+
port;
|
|
2480
|
+
contract;
|
|
2481
|
+
timeout;
|
|
2482
|
+
gate = new Gate;
|
|
2483
|
+
imports = new Map;
|
|
2484
|
+
views = new Map;
|
|
2485
|
+
importSignatures = new Map;
|
|
2486
|
+
importMethods = new Map;
|
|
2487
|
+
hooks = new Map;
|
|
2488
|
+
signatures = new Map;
|
|
2489
|
+
scopes = new Map;
|
|
2490
|
+
active = false;
|
|
2491
|
+
#closed = false;
|
|
2492
|
+
constructor(port, contract, timeout) {
|
|
2493
|
+
this.port = port;
|
|
2494
|
+
this.contract = contract;
|
|
2495
|
+
this.timeout = timeout;
|
|
2496
|
+
}
|
|
2497
|
+
async declare(command, scope) {
|
|
2498
|
+
this.active = true;
|
|
2499
|
+
try {
|
|
2500
|
+
return await this.port.declare(command, scope);
|
|
2501
|
+
} finally {
|
|
2502
|
+
scope.cancel();
|
|
2503
|
+
this.active = false;
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
async execute(command, scope) {
|
|
2507
|
+
return JSON.parse(await this.executeText(command, scope));
|
|
2508
|
+
}
|
|
2509
|
+
async executeText(command, scope) {
|
|
2510
|
+
const release = await this.gate.enter(undefined, scope.signal);
|
|
2511
|
+
this.active = true;
|
|
2512
|
+
try {
|
|
2513
|
+
scope.check();
|
|
2514
|
+
return await this.port.execute(command, scope);
|
|
2515
|
+
} finally {
|
|
2516
|
+
scope.cancel();
|
|
2517
|
+
this.active = false;
|
|
2518
|
+
release();
|
|
2519
|
+
}
|
|
2520
|
+
}
|
|
2521
|
+
ingress(contract, description, create) {
|
|
2522
|
+
if (contract !== HTTP_HANDLER)
|
|
2523
|
+
throw new Error(`Unsupported incoming HTTP export ${contract}`);
|
|
2524
|
+
const service = description.javascriptNames["handler"];
|
|
2525
|
+
const method = description.javascriptNames["handle"];
|
|
2526
|
+
if (!service || !method)
|
|
2527
|
+
throw new Error("Missing prepared incoming HTTP handler names");
|
|
2528
|
+
const declared = JSON.parse(this.port.description()).services[service];
|
|
2529
|
+
if (!declared?.methods.includes(method))
|
|
2530
|
+
throw new Error(`The Orb exports ${HTTP_HANDLER} without a ${service}.${method} handler`);
|
|
2531
|
+
return {
|
|
2532
|
+
[declareFactory2]: create(service),
|
|
2533
|
+
lifetime: declared.lifetime,
|
|
2534
|
+
linger: declared.linger,
|
|
2535
|
+
[admitFactory2]: () => this.gate.enter(Math.max(1, Math.floor(this.timeout / 2))),
|
|
2536
|
+
methods: {
|
|
2537
|
+
handle: async (environment, context, value) => {
|
|
2538
|
+
const exchange = IngressExchange.claim(value);
|
|
2539
|
+
if (!this.port.ingress)
|
|
2540
|
+
throw new Error("This host does not serve incoming HTTP for source Orbs yet");
|
|
2541
|
+
const entered = new Context(context.session, context.root, context.invocation, context.session.kernel.command(KernelOp.EnterExecution, {
|
|
2542
|
+
call: context.invocation.id,
|
|
2543
|
+
context: context.frame || undefined
|
|
2544
|
+
}));
|
|
2545
|
+
const scope = environment.exchange({ context: entered });
|
|
2546
|
+
const release = await this.gate.enter(undefined, scope.signal);
|
|
2547
|
+
this.active = true;
|
|
2548
|
+
try {
|
|
2549
|
+
scope.check();
|
|
2550
|
+
await this.port.ingress({ environment: environment.id, service, method }, exchange, scope);
|
|
2551
|
+
} finally {
|
|
2552
|
+
scope.cancel();
|
|
2553
|
+
this.active = false;
|
|
2554
|
+
release();
|
|
2555
|
+
}
|
|
2556
|
+
}
|
|
2557
|
+
}
|
|
2558
|
+
};
|
|
2559
|
+
}
|
|
2560
|
+
definition(identity, installation) {
|
|
2561
|
+
const { importServices: imports } = installation;
|
|
2562
|
+
const checked = query(this.contract, {
|
|
2563
|
+
kind: "implementation",
|
|
2564
|
+
name: identity.name,
|
|
2565
|
+
apiVersion: identity.apiVersion,
|
|
2566
|
+
value: JSON.parse(this.port.description()),
|
|
2567
|
+
bindings: installation.bindings
|
|
2568
|
+
});
|
|
2569
|
+
const { plan } = checked;
|
|
2570
|
+
const description = query(this.contract, { kind: "describe" });
|
|
2571
|
+
const compile = shapes(description);
|
|
2572
|
+
const names = description.javascriptNames;
|
|
2573
|
+
const callback = (contract, method) => {
|
|
2574
|
+
const exported = description.exports.find((item) => item.contract === contract);
|
|
2575
|
+
const found = Object.entries(exported?.functions ?? {}).find(([name]) => names[name] === method);
|
|
2576
|
+
if (!found)
|
|
2577
|
+
throw new Error(`Missing prepared signature for ${contract}#${method}`);
|
|
2578
|
+
return found[1];
|
|
2579
|
+
};
|
|
2580
|
+
for (const hook of checked.hooks.hooks) {
|
|
2581
|
+
this.hooks.set(hook.alias, hook);
|
|
2582
|
+
this.signatures.set(hook.slot, compile(callback(hook.name, hook.method)));
|
|
2583
|
+
}
|
|
2584
|
+
for (const [binding, service] of Object.entries(imports)) {
|
|
2585
|
+
if (checked.hooks.contributions.some((contribution) => contribution.binding === binding))
|
|
2586
|
+
continue;
|
|
2587
|
+
this.imports.set(binding, service);
|
|
2588
|
+
const provider = installation.bindings[binding];
|
|
2589
|
+
const requirement = provider?.kind === "orb" ? plan.orb.requires.find((item) => item.orb === provider.name) : undefined;
|
|
2590
|
+
const signature = requirement && Object.hasOwn(requirement.signatures, service) ? requirement.signatures[service] : undefined;
|
|
2591
|
+
if (signature)
|
|
2592
|
+
this.importSignatures.set(binding, signature);
|
|
2593
|
+
const selected = description.imports.find((item) => item.binding === binding);
|
|
2594
|
+
if (!selected?.functions)
|
|
2595
|
+
throw new Error("Missing prepared import signatures");
|
|
2596
|
+
const view = description.references[binding];
|
|
2597
|
+
if (view)
|
|
2598
|
+
this.views.set(binding, view);
|
|
2599
|
+
const methods = new Map;
|
|
2600
|
+
for (const [name, fn] of Object.entries(selected.functions)) {
|
|
2601
|
+
if (view?.acquire === name)
|
|
2602
|
+
continue;
|
|
2603
|
+
const spelling = description.javascriptNames[name];
|
|
2604
|
+
if (!spelling || methods.has(spelling))
|
|
2605
|
+
throw new Error("Ambiguous prepared import method");
|
|
2606
|
+
const slot = this.contract.bind(binding, name, false);
|
|
2607
|
+
this.signatures.set(slot, compile(view ? { ...fn, params: fn.params.slice(1) } : fn));
|
|
2608
|
+
methods.set(spelling, { name: view?.methods[name] ?? name, slot });
|
|
2609
|
+
}
|
|
2610
|
+
this.importMethods.set(binding, methods);
|
|
2611
|
+
}
|
|
2612
|
+
let rootScope;
|
|
2613
|
+
const create = (service) => async (declaration) => {
|
|
2614
|
+
const scope = new Scope(this, declaration, service);
|
|
2615
|
+
if (service === null)
|
|
2616
|
+
rootScope = scope;
|
|
2617
|
+
this.scopes.set(scope.id, scope);
|
|
2618
|
+
await this.declare(JSON.stringify({ kind: "create", environment: scope.id, service }), scope.exchange({ declaration }));
|
|
2619
|
+
return scope;
|
|
2620
|
+
};
|
|
2621
|
+
const services = {};
|
|
2622
|
+
for (const service of checked.services) {
|
|
2623
|
+
const { interface: binding, alias } = service;
|
|
2624
|
+
const exported = description.exports.find((item) => item.binding === binding)?.functions;
|
|
2625
|
+
services[service.name] = {
|
|
2626
|
+
[signature2]: service.signature,
|
|
2627
|
+
[declareFactory2]: create(alias),
|
|
2628
|
+
lifetime: service.lifetime,
|
|
2629
|
+
linger: service.linger,
|
|
2630
|
+
[admitFactory2]: () => this.gate.enter(Math.max(1, Math.floor(this.timeout / 2))),
|
|
2631
|
+
methods: Object.fromEntries(Object.keys(service.methods).map((method) => {
|
|
2632
|
+
const slot = this.contract.bind(binding, method, true);
|
|
2633
|
+
const fn = exported?.[method];
|
|
2634
|
+
if (!fn)
|
|
2635
|
+
throw new Error(`Missing prepared signature for ${binding}#${method}`);
|
|
2636
|
+
const shape = compile(fn);
|
|
2637
|
+
this.signatures.set(slot, shape);
|
|
2638
|
+
const invoke = async (environment, context, input) => {
|
|
2639
|
+
const entered = new Context(context.session, context.root, context.invocation, context.session.kernel.command(KernelOp.EnterExecution, {
|
|
2640
|
+
call: context.invocation.id,
|
|
2641
|
+
context: context.frame || undefined
|
|
2642
|
+
}));
|
|
2643
|
+
const text = await this.executeText(packet({ kind: "invoke", environment: environment.id, function: slot }, "args", input), environment.exchange({ context: entered }));
|
|
2644
|
+
return checkedResult(this.contract, slot, text);
|
|
2645
|
+
};
|
|
2646
|
+
return [
|
|
2647
|
+
method,
|
|
2648
|
+
bindCaptured2(async (environment, context, ...args) => {
|
|
2649
|
+
const input = check(this.contract, slot, true, encode(args, VALUE_LIMIT, shape.params));
|
|
2650
|
+
const text = (await invoke(environment, context, input)).text;
|
|
2651
|
+
return lift(shape.result, JSON.parse(text));
|
|
2652
|
+
}, service.signature, invoke)
|
|
2653
|
+
];
|
|
2654
|
+
}))
|
|
2655
|
+
};
|
|
2656
|
+
}
|
|
2657
|
+
if (plan.ingress)
|
|
2658
|
+
services[`${identity.name}::${HTTP_HANDLER}`] = this.ingress(plan.ingress, description, create);
|
|
2659
|
+
const hooks = declaredHooks(checked.hooks.hooks);
|
|
2660
|
+
const contributes = {};
|
|
2661
|
+
for (const binding of checked.hooks.contributions) {
|
|
2662
|
+
const shape = compile(callback(binding.name, binding.method));
|
|
2663
|
+
this.signatures.set(binding.slot, shape);
|
|
2664
|
+
(contributes[binding.target] ??= {})[binding.name] = {
|
|
2665
|
+
priority: binding.priority,
|
|
2666
|
+
handle: async (context, input) => {
|
|
2667
|
+
if (!rootScope || this.scopes.get(rootScope.id) !== rootScope)
|
|
2668
|
+
throw new Error("Contribution Orb scope is unavailable");
|
|
2669
|
+
const entered = new Context(context.session, context.root, context.invocation, context.session.kernel.command(KernelOp.EnterExecution, {
|
|
2670
|
+
call: context.invocation.id,
|
|
2671
|
+
context: context.frame || undefined
|
|
2672
|
+
}));
|
|
2673
|
+
const arguments_ = check(this.contract, binding.slot, true, encode([input], VALUE_LIMIT, shape.params));
|
|
2674
|
+
const result = await this.executeText(packet({ kind: "contribute", environment: rootScope.id, function: binding.slot }, "args", arguments_), rootScope.exchange({ context: entered }));
|
|
2675
|
+
const value = lift(shape.result, JSON.parse(checkedResult(this.contract, binding.slot, result).text));
|
|
2676
|
+
return binding.optional && value === null ? undefined : value;
|
|
2677
|
+
}
|
|
2678
|
+
};
|
|
2679
|
+
}
|
|
2680
|
+
return {
|
|
2681
|
+
name: identity.name,
|
|
2682
|
+
apiVersion: identity.apiVersion,
|
|
2683
|
+
services,
|
|
2684
|
+
hooks,
|
|
2685
|
+
contributes,
|
|
2686
|
+
requires: Object.fromEntries(plan.orb.requires.map((requirement) => [
|
|
2687
|
+
requirement.orb,
|
|
2688
|
+
{ ...requirement, [signatures2]: requirement.signatures }
|
|
2689
|
+
])),
|
|
2690
|
+
[isolatedRevision2]: true,
|
|
2691
|
+
[declareFactory2]: create(null),
|
|
2692
|
+
[validateEnvironment2]: async (environment, value) => {
|
|
2693
|
+
const scope = this.scopes.get(environment.id);
|
|
2694
|
+
if (!scope)
|
|
2695
|
+
throw new Error("Validator scope is gone");
|
|
2696
|
+
const release = await this.gate.enter();
|
|
2697
|
+
try {
|
|
2698
|
+
for (const callback of scope.validators)
|
|
2699
|
+
await this.declare(packet({ kind: "validate", callback }, "value", encode(value)), scope.exchange({ validation: true }));
|
|
2700
|
+
} finally {
|
|
2701
|
+
release();
|
|
2702
|
+
}
|
|
2703
|
+
},
|
|
2704
|
+
[admitFactory2]: () => this.gate.enter(Math.max(1, Math.floor(this.timeout / 2))),
|
|
2705
|
+
[releaseEnvironment2]: async (environment) => {
|
|
2706
|
+
const scope = this.scopes.get(environment.id);
|
|
2707
|
+
if (!scope)
|
|
2708
|
+
return;
|
|
2709
|
+
this.scopes.delete(scope.id);
|
|
2710
|
+
const release = await this.gate.enter();
|
|
2711
|
+
try {
|
|
2712
|
+
await this.port.release(scope.id);
|
|
2713
|
+
} finally {
|
|
2714
|
+
release();
|
|
2715
|
+
}
|
|
2716
|
+
},
|
|
2717
|
+
[disposeOrb2]: async () => {
|
|
2718
|
+
if (this.#closed)
|
|
2719
|
+
return;
|
|
2720
|
+
if (this.scopes.size)
|
|
2721
|
+
throw new Error("Interpreter still owns physical scopes");
|
|
2722
|
+
await this.port.close();
|
|
2723
|
+
this.#closed = true;
|
|
2724
|
+
}
|
|
2725
|
+
};
|
|
2726
|
+
}
|
|
2727
|
+
}
|
|
2728
|
+
|
|
2729
|
+
// src/interpreter/native-ingress.ts
|
|
2730
|
+
function ingressPacket(dispatch) {
|
|
2731
|
+
return JSON.stringify({
|
|
2732
|
+
kind: "ingress",
|
|
2733
|
+
environment: dispatch.environment,
|
|
2734
|
+
service: dispatch.service,
|
|
2735
|
+
method: dispatch.method
|
|
2736
|
+
});
|
|
2737
|
+
}
|
|
2738
|
+
function respond(operation) {
|
|
2739
|
+
try {
|
|
2740
|
+
return `{"ok":${reply(operation())}}`;
|
|
2741
|
+
} catch (error) {
|
|
2742
|
+
return refusal(error);
|
|
2743
|
+
}
|
|
2744
|
+
}
|
|
2745
|
+
var ERROR_CODE = (() => {
|
|
2746
|
+
const send = METHODS.find((method) => method.interface === "wasi:http/client@0.3.0" && method.name === "send");
|
|
2747
|
+
const result = send?.result === undefined ? undefined : TYPES[send.result];
|
|
2748
|
+
if (result?.[0] !== "result")
|
|
2749
|
+
throw new Error("generated tables lack wasi:http/client#send");
|
|
2750
|
+
return result[2];
|
|
2751
|
+
})();
|
|
2752
|
+
var NO_HANDLES = {
|
|
2753
|
+
handle() {
|
|
2754
|
+
throw new RangeError("an error code carries no handles");
|
|
2755
|
+
},
|
|
2756
|
+
value() {
|
|
2757
|
+
throw new RangeError("an error code carries no handles");
|
|
2758
|
+
}
|
|
2759
|
+
};
|
|
2760
|
+
function refusedCode(bytes) {
|
|
2761
|
+
if (!(bytes instanceof Uint8Array))
|
|
2762
|
+
throw new TypeError("a refused code must be bytes");
|
|
2763
|
+
const reader = new Reader(bytes);
|
|
2764
|
+
const code = decode(reader, ERROR_CODE, NO_HANDLES);
|
|
2765
|
+
reader.end();
|
|
2766
|
+
return code;
|
|
2767
|
+
}
|
|
2768
|
+
function deferred2() {
|
|
2769
|
+
let resolve;
|
|
2770
|
+
let reject;
|
|
2771
|
+
const promise = new Promise((done, fail) => {
|
|
2772
|
+
resolve = done;
|
|
2773
|
+
reject = fail;
|
|
2774
|
+
});
|
|
2775
|
+
promise.catch(() => {});
|
|
2776
|
+
return { promise, resolve, reject };
|
|
2777
|
+
}
|
|
2778
|
+
function quiet(value) {
|
|
2779
|
+
if (typeof value?.then === "function")
|
|
2780
|
+
Promise.resolve(value).catch(() => {});
|
|
2781
|
+
}
|
|
2782
|
+
function checkedFields(value) {
|
|
2783
|
+
if (value === undefined || value === null)
|
|
2784
|
+
return [];
|
|
2785
|
+
if (!Array.isArray(value))
|
|
2786
|
+
throw new TypeError("request trailers must be an array");
|
|
2787
|
+
return value.map((field) => {
|
|
2788
|
+
const [name, bytes] = Array.isArray(field) ? field : [];
|
|
2789
|
+
if (typeof name !== "string" || !(bytes instanceof Uint8Array))
|
|
2790
|
+
throw new TypeError("request trailers are [name, Uint8Array] pairs");
|
|
2791
|
+
return [name, bytes];
|
|
2792
|
+
});
|
|
2793
|
+
}
|
|
2794
|
+
var ABANDONED = Symbol("abandoned");
|
|
2795
|
+
|
|
2796
|
+
class NativeIngress {
|
|
2797
|
+
transport;
|
|
2798
|
+
exchange;
|
|
2799
|
+
scope;
|
|
2800
|
+
settled;
|
|
2801
|
+
#settle;
|
|
2802
|
+
#done = false;
|
|
2803
|
+
#failure;
|
|
2804
|
+
#pending = new Set;
|
|
2805
|
+
#detach = () => {};
|
|
2806
|
+
#iterator;
|
|
2807
|
+
#requestEnded = false;
|
|
2808
|
+
#requestClosed = false;
|
|
2809
|
+
#requestStop = deferred2();
|
|
2810
|
+
#pulls = 0;
|
|
2811
|
+
#pulling = false;
|
|
2812
|
+
#headed = false;
|
|
2813
|
+
#started = false;
|
|
2814
|
+
#ended = false;
|
|
2815
|
+
#bodyFailure;
|
|
2816
|
+
#trailerFields;
|
|
2817
|
+
#trailers = deferred2();
|
|
2818
|
+
#frame;
|
|
2819
|
+
#reading = Promise.resolve();
|
|
2820
|
+
constructor(transport, exchange, scope) {
|
|
2821
|
+
this.transport = transport;
|
|
2822
|
+
this.exchange = exchange;
|
|
2823
|
+
this.scope = scope;
|
|
2824
|
+
this.settled = new Promise((resolve, reject) => {
|
|
2825
|
+
this.#settle = { resolve, reject };
|
|
2826
|
+
});
|
|
2827
|
+
this.settled.catch(() => {});
|
|
2828
|
+
quiet(exchange.own().trailers);
|
|
2829
|
+
}
|
|
2830
|
+
get request() {
|
|
2831
|
+
return this.exchange.request;
|
|
2832
|
+
}
|
|
2833
|
+
begun() {
|
|
2834
|
+
const signal = this.scope.signal;
|
|
2835
|
+
if (!signal)
|
|
2836
|
+
return;
|
|
2837
|
+
const cancel = () => this.#cancel();
|
|
2838
|
+
this.#detach = () => signal.removeEventListener("abort", cancel);
|
|
2839
|
+
if (signal.aborted)
|
|
2840
|
+
cancel();
|
|
2841
|
+
else
|
|
2842
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
2843
|
+
}
|
|
2844
|
+
event(event) {
|
|
2845
|
+
if (this.#done)
|
|
2846
|
+
return;
|
|
2847
|
+
try {
|
|
2848
|
+
switch (event.kind) {
|
|
2849
|
+
case "host":
|
|
2850
|
+
return this.#host(event);
|
|
2851
|
+
case "request-pull":
|
|
2852
|
+
this.#pulls++;
|
|
2853
|
+
return void this.#serveRequest();
|
|
2854
|
+
case "head":
|
|
2855
|
+
return this.#head(event.status, event.fields);
|
|
2856
|
+
case "data":
|
|
2857
|
+
return this.#deliver({ kind: "data", data: event.data });
|
|
2858
|
+
case "trailers":
|
|
2859
|
+
this.#trailerFields = event.fields;
|
|
2860
|
+
return this.#deliver({ kind: "trailers" });
|
|
2861
|
+
case "end":
|
|
2862
|
+
this.#ended = true;
|
|
2863
|
+
this.#trailers.resolve(this.#trailerFields?.length ? this.#trailerFields : undefined);
|
|
2864
|
+
return this.#deliver({ kind: "end" });
|
|
2865
|
+
case "error": {
|
|
2866
|
+
const failure = new HttpHandlerError2({ tag: "internal-error", val: event.message }, event.message);
|
|
2867
|
+
this.#endDelivery(failure);
|
|
2868
|
+
return;
|
|
2869
|
+
}
|
|
2870
|
+
case "refused":
|
|
2871
|
+
if (this.#headed)
|
|
2872
|
+
throw new Error("a refused exchange cannot have a head");
|
|
2873
|
+
return this.exchange.refuse(refusedCode(event.code));
|
|
2874
|
+
case "complete":
|
|
2875
|
+
return void this.#complete(event.result).catch((error) => this.#settle.reject(error));
|
|
2876
|
+
default:
|
|
2877
|
+
throw new Error("Unknown incoming HTTP carrier event");
|
|
2878
|
+
}
|
|
2879
|
+
} catch (error) {
|
|
2880
|
+
this.#broken(error);
|
|
2881
|
+
}
|
|
2882
|
+
}
|
|
2883
|
+
async abandon(error) {
|
|
2884
|
+
if (this.#done)
|
|
2885
|
+
return;
|
|
2886
|
+
this.#done = true;
|
|
2887
|
+
this.#detach();
|
|
2888
|
+
this.#endDelivery(error);
|
|
2889
|
+
this.#closeRequest();
|
|
2890
|
+
this.scope.cancel();
|
|
2891
|
+
await Promise.allSettled([...this.#pending]);
|
|
2892
|
+
this.#settle.reject(error);
|
|
2893
|
+
}
|
|
2894
|
+
fail(error) {
|
|
2895
|
+
this.#broken(error);
|
|
2896
|
+
}
|
|
2897
|
+
#broken(error) {
|
|
2898
|
+
this.#failure ??= error;
|
|
2899
|
+
this.#endDelivery(error);
|
|
2900
|
+
this.#closeRequest();
|
|
2901
|
+
if (this.#done)
|
|
2902
|
+
return;
|
|
2903
|
+
for (const operation of [() => this.transport.disconnect(), () => this.transport.cancel()])
|
|
2904
|
+
try {
|
|
2905
|
+
operation();
|
|
2906
|
+
} catch {}
|
|
2907
|
+
}
|
|
2908
|
+
#cancel() {
|
|
2909
|
+
if (this.#done)
|
|
2910
|
+
return;
|
|
2911
|
+
try {
|
|
2912
|
+
this.transport.cancel();
|
|
2913
|
+
} catch (error) {
|
|
2914
|
+
this.#failure ??= error;
|
|
2915
|
+
}
|
|
2916
|
+
}
|
|
2917
|
+
#host(event) {
|
|
2918
|
+
const { id, packet } = event;
|
|
2919
|
+
if (!event.asynchronous) {
|
|
2920
|
+
this.transport.reply(id, respond(() => this.scope.sync(decodeHostRequest(packet))));
|
|
2921
|
+
return;
|
|
2922
|
+
}
|
|
2923
|
+
let request;
|
|
2924
|
+
const operation = Promise.resolve().then(() => {
|
|
2925
|
+
request = decodeAsyncHostRequest(packet);
|
|
2926
|
+
return this.scope.async(request);
|
|
2927
|
+
}).then((value) => this.scope.deliver(request, value, (value) => this.transport.reply(id, respond(() => value))), (error) => void this.transport.reply(id, respond(() => {
|
|
2928
|
+
throw error;
|
|
2929
|
+
}))).catch((error) => {
|
|
2930
|
+
this.#failure ??= error;
|
|
2931
|
+
});
|
|
2932
|
+
this.#pending.add(operation);
|
|
2933
|
+
operation.finally(() => this.#pending.delete(operation));
|
|
2934
|
+
}
|
|
2935
|
+
async#serveRequest() {
|
|
2936
|
+
if (this.#pulling)
|
|
2937
|
+
return;
|
|
2938
|
+
this.#pulling = true;
|
|
2939
|
+
try {
|
|
2940
|
+
while (this.#pulls > 0 && !this.#done) {
|
|
2941
|
+
this.#pulls--;
|
|
2942
|
+
const answer = await this.#nextRequest();
|
|
2943
|
+
if (answer === ABANDONED || this.#done)
|
|
2944
|
+
return;
|
|
2945
|
+
try {
|
|
2946
|
+
this.transport.supply(answer);
|
|
2947
|
+
} catch (error) {
|
|
2948
|
+
this.#broken(error);
|
|
2949
|
+
return;
|
|
2950
|
+
}
|
|
2951
|
+
}
|
|
2952
|
+
} finally {
|
|
2953
|
+
this.#pulling = false;
|
|
2954
|
+
}
|
|
2955
|
+
}
|
|
2956
|
+
async#nextRequest() {
|
|
2957
|
+
const stop = this.#requestStop.promise;
|
|
2958
|
+
try {
|
|
2959
|
+
if (this.#requestClosed)
|
|
2960
|
+
return ABANDONED;
|
|
2961
|
+
const { body, trailers } = this.request;
|
|
2962
|
+
if (body && !this.#requestEnded) {
|
|
2963
|
+
this.#iterator ??= body[Symbol.asyncIterator]();
|
|
2964
|
+
for (;; ) {
|
|
2965
|
+
const pending = this.#iterator.next();
|
|
2966
|
+
quiet(pending);
|
|
2967
|
+
const next = await Promise.race([pending, stop]);
|
|
2968
|
+
if (next === ABANDONED)
|
|
2969
|
+
return ABANDONED;
|
|
2970
|
+
if (next.done)
|
|
2971
|
+
break;
|
|
2972
|
+
if (!(next.value instanceof Uint8Array))
|
|
2973
|
+
throw new TypeError("incoming request chunks must be Uint8Array");
|
|
2974
|
+
if (next.value.byteLength)
|
|
2975
|
+
return { kind: "data", data: next.value };
|
|
2976
|
+
}
|
|
2977
|
+
}
|
|
2978
|
+
this.#requestEnded = true;
|
|
2979
|
+
this.#iterator = undefined;
|
|
2980
|
+
if (!trailers)
|
|
2981
|
+
return { kind: "end", trailers: [] };
|
|
2982
|
+
const pairs = await Promise.race([Promise.resolve(trailers), stop]);
|
|
2983
|
+
if (pairs === ABANDONED)
|
|
2984
|
+
return ABANDONED;
|
|
2985
|
+
return { kind: "end", trailers: checkedFields(pairs) };
|
|
2986
|
+
} catch (error) {
|
|
2987
|
+
this.#requestEnded = true;
|
|
2988
|
+
this.#iterator = undefined;
|
|
2989
|
+
return { kind: "error", message: error instanceof Error ? error.message : String(error) };
|
|
2990
|
+
}
|
|
2991
|
+
}
|
|
2992
|
+
#closeRequest() {
|
|
2993
|
+
if (this.#requestClosed)
|
|
2994
|
+
return;
|
|
2995
|
+
this.#requestClosed = true;
|
|
2996
|
+
this.#requestStop.resolve(ABANDONED);
|
|
2997
|
+
if (this.#requestEnded)
|
|
2998
|
+
return;
|
|
2999
|
+
const iterator = this.#iterator;
|
|
3000
|
+
this.#iterator = undefined;
|
|
3001
|
+
try {
|
|
3002
|
+
quiet((iterator ?? this.request.body?.[Symbol.asyncIterator]())?.return?.());
|
|
3003
|
+
} catch {}
|
|
3004
|
+
}
|
|
3005
|
+
#head(status, fields) {
|
|
3006
|
+
if (this.#headed)
|
|
3007
|
+
throw new Error("the response head was already published");
|
|
3008
|
+
this.#headed = true;
|
|
3009
|
+
const body = Object.freeze({
|
|
3010
|
+
[Symbol.asyncIterator]: () => this.#responseIterator()
|
|
3011
|
+
});
|
|
3012
|
+
const response = Object.freeze({
|
|
3013
|
+
status,
|
|
3014
|
+
fields: Object.freeze(fields.map((field) => Object.freeze(field))),
|
|
3015
|
+
body,
|
|
3016
|
+
trailers: this.#trailers.promise
|
|
3017
|
+
});
|
|
3018
|
+
this.exchange.respond(response);
|
|
3019
|
+
}
|
|
3020
|
+
#responseIterator() {
|
|
3021
|
+
if (this.#started)
|
|
3022
|
+
throw new TypeError("the response body is read once");
|
|
3023
|
+
this.#started = true;
|
|
3024
|
+
return {
|
|
3025
|
+
next: () => {
|
|
3026
|
+
const read = this.#reading.then(() => this.#next());
|
|
3027
|
+
this.#reading = read.catch(() => {});
|
|
3028
|
+
return read;
|
|
3029
|
+
},
|
|
3030
|
+
return: async () => {
|
|
3031
|
+
this.#disconnect();
|
|
3032
|
+
return { done: true, value: undefined };
|
|
3033
|
+
}
|
|
3034
|
+
};
|
|
3035
|
+
}
|
|
3036
|
+
async#next() {
|
|
3037
|
+
for (;; ) {
|
|
3038
|
+
if (this.#ended) {
|
|
3039
|
+
if (this.#bodyFailure !== undefined)
|
|
3040
|
+
throw this.#bodyFailure;
|
|
3041
|
+
return { done: true, value: undefined };
|
|
3042
|
+
}
|
|
3043
|
+
const frame = deferred2();
|
|
3044
|
+
this.#frame = frame;
|
|
3045
|
+
try {
|
|
3046
|
+
this.transport.pull();
|
|
3047
|
+
} catch (error) {
|
|
3048
|
+
this.#frame = undefined;
|
|
3049
|
+
this.#endDelivery(error);
|
|
3050
|
+
try {
|
|
3051
|
+
this.transport.disconnect();
|
|
3052
|
+
} catch {}
|
|
3053
|
+
throw error;
|
|
3054
|
+
}
|
|
3055
|
+
const next = await frame.promise;
|
|
3056
|
+
if (next.kind === "data")
|
|
3057
|
+
return { done: false, value: next.data };
|
|
3058
|
+
if (next.kind === "end")
|
|
3059
|
+
return { done: true, value: undefined };
|
|
3060
|
+
}
|
|
3061
|
+
}
|
|
3062
|
+
#deliver(frame) {
|
|
3063
|
+
const waiting = this.#frame;
|
|
3064
|
+
this.#frame = undefined;
|
|
3065
|
+
waiting?.resolve(frame);
|
|
3066
|
+
}
|
|
3067
|
+
#endDelivery(failure) {
|
|
3068
|
+
if (this.#ended)
|
|
3069
|
+
return;
|
|
3070
|
+
this.#ended = true;
|
|
3071
|
+
this.#bodyFailure = failure;
|
|
3072
|
+
this.#trailers.reject(failure);
|
|
3073
|
+
const waiting = this.#frame;
|
|
3074
|
+
this.#frame = undefined;
|
|
3075
|
+
waiting?.reject(failure);
|
|
3076
|
+
}
|
|
3077
|
+
#disconnect() {
|
|
3078
|
+
if (this.#ended)
|
|
3079
|
+
return;
|
|
3080
|
+
this.#endDelivery(new HttpHandlerError2(CONNECTION_TERMINATED));
|
|
3081
|
+
this.#closeRequest();
|
|
3082
|
+
if (this.#done)
|
|
3083
|
+
return;
|
|
3084
|
+
try {
|
|
3085
|
+
this.transport.disconnect();
|
|
3086
|
+
} catch (error) {
|
|
3087
|
+
this.#broken(error);
|
|
3088
|
+
}
|
|
3089
|
+
}
|
|
3090
|
+
async#complete(result) {
|
|
3091
|
+
this.#done = true;
|
|
3092
|
+
this.#detach();
|
|
3093
|
+
let envelope;
|
|
3094
|
+
let error;
|
|
3095
|
+
try {
|
|
3096
|
+
envelope = JSON.parse(result);
|
|
3097
|
+
if (Object.hasOwn(envelope, "ok")) {
|
|
3098
|
+
if (typeof envelope.ok !== "string")
|
|
3099
|
+
throw new Error("Invalid guest result packet");
|
|
3100
|
+
} else
|
|
3101
|
+
error = envelope.error ?? "Interpreter operation failed";
|
|
3102
|
+
} catch (invalid) {
|
|
3103
|
+
error = invalid;
|
|
3104
|
+
}
|
|
3105
|
+
const outcome = error !== undefined ? failure(error) : undefined;
|
|
3106
|
+
this.#endDelivery(outcome ?? new Error("the HTTP handler callback ended"));
|
|
3107
|
+
this.#closeRequest();
|
|
3108
|
+
this.scope.cancel();
|
|
3109
|
+
await Promise.allSettled([...this.#pending]);
|
|
3110
|
+
try {
|
|
3111
|
+
this.transport.finish();
|
|
3112
|
+
} catch (finishing) {
|
|
3113
|
+
this.#failure ??= finishing;
|
|
3114
|
+
}
|
|
3115
|
+
if (this.#failure !== undefined)
|
|
3116
|
+
return this.#settle.reject(this.#failure);
|
|
3117
|
+
if (outcome !== undefined)
|
|
3118
|
+
return this.#settle.reject(outcome);
|
|
3119
|
+
this.#settle.resolve();
|
|
3120
|
+
}
|
|
3121
|
+
}
|
|
3122
|
+
|
|
3123
|
+
// src/interpreter/mobile.ts
|
|
3124
|
+
class MobileDriver {
|
|
3125
|
+
port;
|
|
3126
|
+
dispose;
|
|
3127
|
+
constructor(port, dispose) {
|
|
3128
|
+
this.port = port;
|
|
3129
|
+
this.dispose = dispose;
|
|
3130
|
+
const carrier = port.ingress;
|
|
3131
|
+
if (carrier)
|
|
3132
|
+
this.ingress = (dispatch, exchange, scope) => this.serve(carrier, dispatch, exchange, scope);
|
|
3133
|
+
}
|
|
3134
|
+
description() {
|
|
3135
|
+
return this.port.description();
|
|
3136
|
+
}
|
|
3137
|
+
release(environment) {
|
|
3138
|
+
this.port.release(environment);
|
|
3139
|
+
}
|
|
3140
|
+
async declare(packet, scope) {
|
|
3141
|
+
return JSON.parse(await this.drive(packet, scope, true));
|
|
3142
|
+
}
|
|
3143
|
+
execute(packet, scope) {
|
|
3144
|
+
return this.drive(packet, scope, false);
|
|
3145
|
+
}
|
|
3146
|
+
close() {
|
|
3147
|
+
try {
|
|
3148
|
+
this.port.close();
|
|
3149
|
+
} finally {
|
|
3150
|
+
this.dispose();
|
|
3151
|
+
}
|
|
3152
|
+
}
|
|
3153
|
+
async serve(carrier, dispatch, exchange, scope) {
|
|
3154
|
+
const port = this.port;
|
|
3155
|
+
const exchanged = new NativeIngress({
|
|
3156
|
+
supply: (answer) => carrier.supplyRequest(answer.kind === "data" ? { kind: "data", bytes: answer.data } : answer.kind === "end" ? { kind: "end", trailers: answer.trailers.map(mobileField) } : answer),
|
|
3157
|
+
pull: () => carrier.pullResponse(),
|
|
3158
|
+
disconnect: () => carrier.disconnect(),
|
|
3159
|
+
cancel: () => port.cancel(),
|
|
3160
|
+
reply: (id, packet) => port.reply(id, packet),
|
|
3161
|
+
finish: () => port.finish()
|
|
3162
|
+
}, exchange, scope);
|
|
3163
|
+
const { method, scheme, authority, pathWithQuery, fields } = exchange.request;
|
|
3164
|
+
try {
|
|
3165
|
+
carrier.beginIngress(ingressPacket(dispatch), {
|
|
3166
|
+
method,
|
|
3167
|
+
...scheme === undefined ? {} : { scheme },
|
|
3168
|
+
...authority === undefined ? {} : { authority },
|
|
3169
|
+
...pathWithQuery === undefined ? {} : { pathWithQuery },
|
|
3170
|
+
fields: fields.map(mobileField)
|
|
3171
|
+
});
|
|
3172
|
+
} catch (error) {
|
|
3173
|
+
await exchanged.abandon(error);
|
|
3174
|
+
return exchanged.settled;
|
|
3175
|
+
}
|
|
3176
|
+
exchanged.begun();
|
|
3177
|
+
try {
|
|
3178
|
+
for (;; ) {
|
|
3179
|
+
const received = await carrier.receiveIngress();
|
|
3180
|
+
let event;
|
|
3181
|
+
try {
|
|
3182
|
+
event = carrierEvent(received);
|
|
3183
|
+
} catch (error) {
|
|
3184
|
+
exchanged.fail(error);
|
|
3185
|
+
continue;
|
|
3186
|
+
}
|
|
3187
|
+
exchanged.event(event);
|
|
3188
|
+
if (event.kind === "complete")
|
|
3189
|
+
break;
|
|
3190
|
+
}
|
|
3191
|
+
} catch (error) {
|
|
3192
|
+
await exchanged.abandon(error);
|
|
3193
|
+
const aborted = await Promise.allSettled([port.abort()]);
|
|
3194
|
+
if (aborted[0]?.status === "rejected")
|
|
3195
|
+
throw new AggregateError([error, aborted[0].reason], "Mobile exchange and cleanup failed");
|
|
3196
|
+
throw error;
|
|
3197
|
+
}
|
|
3198
|
+
return exchanged.settled;
|
|
3199
|
+
}
|
|
3200
|
+
async drive(packet, scope, declaration) {
|
|
3201
|
+
this.port.begin(packet, declaration);
|
|
3202
|
+
const pending = new Set;
|
|
3203
|
+
let failure;
|
|
3204
|
+
let finished = false;
|
|
3205
|
+
const signal = scope.signal;
|
|
3206
|
+
const cancel = () => this.port.cancel();
|
|
3207
|
+
const detach = () => signal?.removeEventListener("abort", cancel);
|
|
3208
|
+
try {
|
|
3209
|
+
if (signal?.aborted)
|
|
3210
|
+
cancel();
|
|
3211
|
+
else
|
|
3212
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
3213
|
+
for (;; ) {
|
|
3214
|
+
const event = JSON.parse(await this.port.receive());
|
|
3215
|
+
if (event.event === "complete") {
|
|
3216
|
+
detach();
|
|
3217
|
+
scope.cancel();
|
|
3218
|
+
await Promise.allSettled([...pending]);
|
|
3219
|
+
this.port.finish();
|
|
3220
|
+
finished = true;
|
|
3221
|
+
if (failure !== undefined)
|
|
3222
|
+
throw failure;
|
|
3223
|
+
const value = answer(JSON.stringify(event.result));
|
|
3224
|
+
if (typeof value !== "string")
|
|
3225
|
+
throw new Error("Invalid guest result packet");
|
|
3226
|
+
return value;
|
|
3227
|
+
}
|
|
3228
|
+
if (event.event !== "host")
|
|
3229
|
+
throw new Error("Unknown interpreter event");
|
|
3230
|
+
const respond = (operation) => {
|
|
3231
|
+
let response;
|
|
3232
|
+
try {
|
|
3233
|
+
response = `{"ok":${reply(operation())}}`;
|
|
3234
|
+
} catch (error) {
|
|
3235
|
+
response = refusal(error);
|
|
3236
|
+
}
|
|
3237
|
+
return this.port.reply(event.id, response);
|
|
3238
|
+
};
|
|
3239
|
+
if (!event.asynchronous)
|
|
3240
|
+
respond(() => scope.sync(decodeHostRequest(event.packet)));
|
|
3241
|
+
else if (declaration)
|
|
3242
|
+
respond(() => {
|
|
3243
|
+
throw new Error("Factories cannot perform asynchronous host operations");
|
|
3244
|
+
});
|
|
3245
|
+
else {
|
|
3246
|
+
let request;
|
|
3247
|
+
const operation = Promise.resolve().then(() => {
|
|
3248
|
+
request = decodeAsyncHostRequest(event.packet);
|
|
3249
|
+
return scope.async(request);
|
|
3250
|
+
}).then((value) => scope.deliver(request, value, (value) => respond(() => value)), (error) => void respond(() => {
|
|
3251
|
+
throw error;
|
|
3252
|
+
})).catch((error) => {
|
|
3253
|
+
failure = error;
|
|
3254
|
+
});
|
|
3255
|
+
pending.add(operation);
|
|
3256
|
+
operation.finally(() => pending.delete(operation));
|
|
3257
|
+
}
|
|
3258
|
+
}
|
|
3259
|
+
} catch (error) {
|
|
3260
|
+
if (finished)
|
|
3261
|
+
throw error;
|
|
3262
|
+
detach();
|
|
3263
|
+
scope.cancel();
|
|
3264
|
+
const results = await Promise.allSettled([this.port.abort(), ...pending]);
|
|
3265
|
+
const abort = results[0];
|
|
3266
|
+
if (abort?.status === "rejected")
|
|
3267
|
+
throw new AggregateError([error, abort.reason], "Mobile exchange and cleanup failed");
|
|
3268
|
+
throw error;
|
|
3269
|
+
} finally {
|
|
3270
|
+
detach();
|
|
3271
|
+
}
|
|
3272
|
+
}
|
|
3273
|
+
}
|
|
3274
|
+
function mobileField([name, value]) {
|
|
3275
|
+
return { name, value };
|
|
3276
|
+
}
|
|
3277
|
+
function typed(value) {
|
|
3278
|
+
if (!(value instanceof Uint8Array))
|
|
3279
|
+
throw new TypeError("the mobile ingress carrier must deliver bytes as Uint8Array");
|
|
3280
|
+
return value;
|
|
3281
|
+
}
|
|
3282
|
+
function fieldsOf(value) {
|
|
3283
|
+
if (!Array.isArray(value))
|
|
3284
|
+
throw new TypeError("mobile ingress fields must be an array");
|
|
3285
|
+
return value.map((field) => {
|
|
3286
|
+
if (typeof field?.name !== "string")
|
|
3287
|
+
throw new TypeError("mobile ingress field names are strings");
|
|
3288
|
+
return [field.name, typed(field.value)];
|
|
3289
|
+
});
|
|
3290
|
+
}
|
|
3291
|
+
function carrierEvent(event) {
|
|
3292
|
+
switch (event.kind) {
|
|
3293
|
+
case "host":
|
|
3294
|
+
case "complete":
|
|
3295
|
+
case "end":
|
|
3296
|
+
case "error":
|
|
3297
|
+
return event;
|
|
3298
|
+
case "requestPull":
|
|
3299
|
+
return { kind: "request-pull" };
|
|
3300
|
+
case "head":
|
|
3301
|
+
return { kind: "head", status: event.status, fields: fieldsOf(event.fields) };
|
|
3302
|
+
case "data":
|
|
3303
|
+
return { kind: "data", data: typed(event.bytes) };
|
|
3304
|
+
case "trailers":
|
|
3305
|
+
return { kind: "trailers", fields: fieldsOf(event.fields) };
|
|
3306
|
+
case "refused":
|
|
3307
|
+
return { kind: "refused", code: typed(event.code) };
|
|
3308
|
+
default:
|
|
3309
|
+
throw new TypeError("Unknown mobile ingress event");
|
|
3310
|
+
}
|
|
3311
|
+
}
|
|
3312
|
+
function createMobileHost2(options, backend, isolated) {
|
|
3313
|
+
return new Host2({
|
|
3314
|
+
...options,
|
|
3315
|
+
[isolate2]: async (definition) => {
|
|
3316
|
+
const artifact = backend.artifact(definition.artifact);
|
|
3317
|
+
try {
|
|
3318
|
+
const identity = JSON.parse(artifact.description());
|
|
3319
|
+
const installation = query(artifact, {
|
|
3320
|
+
kind: "install",
|
|
3321
|
+
name: identity.name,
|
|
3322
|
+
apiVersion: identity.apiVersion,
|
|
3323
|
+
requires: definition.requires ?? {},
|
|
3324
|
+
grants: definition.grants ?? {},
|
|
3325
|
+
filesystem: Object.keys(isolated.providers?.filesystem ?? {}),
|
|
3326
|
+
network: isolated.providers?.network ?? [],
|
|
3327
|
+
http: isolated.providers?.network ?? []
|
|
3328
|
+
});
|
|
3329
|
+
const bindings = JSON.stringify(installation.bindings), grants = JSON.stringify(definition.grants ?? {});
|
|
3330
|
+
const port = await backend.open(artifact, bindings, grants, cliPacket(definition.cli));
|
|
3331
|
+
const driver = new MobileDriver(port, () => artifact.free());
|
|
3332
|
+
try {
|
|
3333
|
+
return new Revision(driver, artifact, isolated.limits?.timeoutMs ?? 1e4).definition(identity, installation);
|
|
3334
|
+
} catch (error) {
|
|
3335
|
+
driver.close();
|
|
3336
|
+
throw error;
|
|
3337
|
+
}
|
|
3338
|
+
} catch (error) {
|
|
3339
|
+
artifact.free();
|
|
3340
|
+
throw error;
|
|
3341
|
+
}
|
|
3342
|
+
}
|
|
3343
|
+
});
|
|
3344
|
+
}
|
|
3345
|
+
|
|
3346
|
+
// src/host.ts
|
|
3347
|
+
class Host2 {
|
|
3348
|
+
session;
|
|
3349
|
+
constructor(options) {
|
|
3350
|
+
this.session = new Session(options);
|
|
3351
|
+
}
|
|
3352
|
+
get name() {
|
|
3353
|
+
return this.session.name;
|
|
3354
|
+
}
|
|
3355
|
+
get features() {
|
|
3356
|
+
return this.session.kernel.features;
|
|
3357
|
+
}
|
|
3358
|
+
install(definition) {
|
|
3359
|
+
return this.session.track(this.session.orbs.install(Array.isArray(definition) ? definition : [definition]));
|
|
3360
|
+
}
|
|
3361
|
+
async load(location, options) {
|
|
3362
|
+
if (!this.session.options.load)
|
|
3363
|
+
throw new Error("This host has no module loader");
|
|
3364
|
+
await this.install(await this.session.options.load(location, options));
|
|
3365
|
+
}
|
|
3366
|
+
reload(definitions, options) {
|
|
3367
|
+
return this.session.replacements.replace(definitions, options);
|
|
3368
|
+
}
|
|
3369
|
+
prepare(definitions, options) {
|
|
3370
|
+
return this.session.replacements.prepare(definitions, options);
|
|
3371
|
+
}
|
|
3372
|
+
remove(names, options) {
|
|
3373
|
+
return this.session.replacements.replace([], options, names);
|
|
3374
|
+
}
|
|
3375
|
+
hold(service, key, options) {
|
|
3376
|
+
return this.session.handles.hold(service, key, options);
|
|
3377
|
+
}
|
|
3378
|
+
get(service, key, options) {
|
|
3379
|
+
return this.session.handles.get(service, key, options);
|
|
3380
|
+
}
|
|
3381
|
+
root(operation, options = {}) {
|
|
3382
|
+
return this.session.calls.root(operation, false, undefined, options.principal);
|
|
3383
|
+
}
|
|
3384
|
+
handleHttp(orb, request, options = {}) {
|
|
3385
|
+
if (isFetchRequest(request)) {
|
|
3386
|
+
try {
|
|
3387
|
+
return this.handleHttp(orb, fromFetchRequest(request), options).then(toFetchResponse);
|
|
3388
|
+
} catch (error) {
|
|
3389
|
+
return Promise.reject(error);
|
|
3390
|
+
}
|
|
3391
|
+
}
|
|
3392
|
+
let exchange;
|
|
3393
|
+
try {
|
|
3394
|
+
exchange = new IngressExchange(checkedRequest(request));
|
|
3395
|
+
} catch (error) {
|
|
3396
|
+
return Promise.reject(error);
|
|
3397
|
+
}
|
|
3398
|
+
const session = this.session;
|
|
3399
|
+
const { signal, principal } = options;
|
|
3400
|
+
const served = session.calls.root(async (ctx) => {
|
|
3401
|
+
const cancel = () => ctx.cancel();
|
|
3402
|
+
if (signal?.aborted)
|
|
3403
|
+
cancel();
|
|
3404
|
+
else
|
|
3405
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
3406
|
+
try {
|
|
3407
|
+
const reference = await ctx.get(`${orb}::${HTTP_HANDLER}`, ["main"]);
|
|
3408
|
+
await session.calls.invokePhysical(session.handles.reference(reference), "handle", [exchange], ctx);
|
|
3409
|
+
} finally {
|
|
3410
|
+
signal?.removeEventListener("abort", cancel);
|
|
3411
|
+
}
|
|
3412
|
+
}, false, undefined, principal);
|
|
3413
|
+
session.track(served).then(() => exchange.settle(), (error) => exchange.settle(error));
|
|
3414
|
+
return exchange.head;
|
|
3415
|
+
}
|
|
3416
|
+
resource(name, options) {
|
|
3417
|
+
return this.session.scopes.resource(name, options);
|
|
3418
|
+
}
|
|
3419
|
+
diagnostics() {
|
|
3420
|
+
return this.session.lifecycle.diagnostics();
|
|
3421
|
+
}
|
|
3422
|
+
errors() {
|
|
3423
|
+
return this.session.errors.splice(0);
|
|
3424
|
+
}
|
|
3425
|
+
traces() {
|
|
3426
|
+
return this.session.telemetry?.drain() ?? [];
|
|
3427
|
+
}
|
|
3428
|
+
installedOrbs() {
|
|
3429
|
+
return this.session.kernel.command(KernelOp.Orbs).map((info) => {
|
|
3430
|
+
const definition = this.session.orbs.records.get(info.id)?.definition;
|
|
3431
|
+
const description = Object.freeze({
|
|
3432
|
+
...info,
|
|
3433
|
+
hookCapabilities: Object.fromEntries(info.hooks.map((name) => [name, definition?.hooks?.[name]?.capabilities ?? []]))
|
|
3434
|
+
});
|
|
3435
|
+
return Object.freeze({
|
|
3436
|
+
...info,
|
|
3437
|
+
describe: () => description
|
|
3438
|
+
});
|
|
3439
|
+
});
|
|
3440
|
+
}
|
|
3441
|
+
close() {
|
|
3442
|
+
return this.session.lifecycle.close();
|
|
3443
|
+
}
|
|
3444
|
+
}
|
|
3445
|
+
function createHost2(options) {
|
|
3446
|
+
return new Host2(options);
|
|
3447
|
+
}
|
|
3448
|
+
export { Gate, decodeHostRequest, decodeAsyncHostRequest, acquireReference, Scope, exportedFunctions, declaredHooks, Revision, ingressPacket, NativeIngress, createMobileHost2, Host2, createHost2 };
|