@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,1419 @@
|
|
|
1
|
+
import"./index-v6heph77.js";
|
|
2
|
+
import {
|
|
3
|
+
HTTP_HANDLER,
|
|
4
|
+
IngressExchange,
|
|
5
|
+
query
|
|
6
|
+
} from "./index-h8t0n42q.js";
|
|
7
|
+
import {
|
|
8
|
+
BrowserCapabilities,
|
|
9
|
+
checkedClocks,
|
|
10
|
+
revisionRandom,
|
|
11
|
+
browserClocks,
|
|
12
|
+
browserRandom
|
|
13
|
+
} from "./index-aaymjn7v.js";
|
|
14
|
+
import {
|
|
15
|
+
Code2,
|
|
16
|
+
Reason2,
|
|
17
|
+
TembraError2
|
|
18
|
+
} from "./index-c1w7z9hx.js";
|
|
19
|
+
import {
|
|
20
|
+
issueByteStream,
|
|
21
|
+
ComponentPort,
|
|
22
|
+
importedResource,
|
|
23
|
+
viewMethod,
|
|
24
|
+
referenceView,
|
|
25
|
+
referenceImport,
|
|
26
|
+
resourceImport,
|
|
27
|
+
converters,
|
|
28
|
+
checkPublicWasi,
|
|
29
|
+
publicWasi
|
|
30
|
+
} from "./index-smyds5ce.js";
|
|
31
|
+
import {
|
|
32
|
+
BrowserPlatformError2
|
|
33
|
+
} from "./index-n1wxzc9w.js";
|
|
34
|
+
import {
|
|
35
|
+
KernelOp
|
|
36
|
+
} from "./index-kr4x67wt.js";
|
|
37
|
+
import {
|
|
38
|
+
bindCaptured2,
|
|
39
|
+
declareFactory2,
|
|
40
|
+
validateEnvironment2,
|
|
41
|
+
signature2,
|
|
42
|
+
signatures2,
|
|
43
|
+
disposeOrb2,
|
|
44
|
+
releaseEnvironment2,
|
|
45
|
+
isolatedRevision2,
|
|
46
|
+
admitFactory2
|
|
47
|
+
} from "./index-zkqmnjj8.js";
|
|
48
|
+
import {
|
|
49
|
+
shapes,
|
|
50
|
+
lift,
|
|
51
|
+
VALUE_LIMIT,
|
|
52
|
+
Encoded,
|
|
53
|
+
encode,
|
|
54
|
+
check,
|
|
55
|
+
checkedResult,
|
|
56
|
+
Context,
|
|
57
|
+
checkSignal,
|
|
58
|
+
combinedSignal
|
|
59
|
+
} from "./index-kyt9dj0a.js";
|
|
60
|
+
import {
|
|
61
|
+
Gate,
|
|
62
|
+
acquireReference,
|
|
63
|
+
Scope,
|
|
64
|
+
declaredHooks
|
|
65
|
+
} from "./index-xrdvnv37.js";
|
|
66
|
+
import {
|
|
67
|
+
ResourceOwner,
|
|
68
|
+
resourceRoles,
|
|
69
|
+
resourceDataFunction,
|
|
70
|
+
resourceExport
|
|
71
|
+
} from "./index-hfds9mzp.js";
|
|
72
|
+
|
|
73
|
+
// src/interpreter/component/instance.ts
|
|
74
|
+
function requireJspi() {
|
|
75
|
+
const wasm = globalThis.WebAssembly;
|
|
76
|
+
if (typeof wasm?.Suspending !== "function" || typeof wasm?.promising !== "function")
|
|
77
|
+
throw new BrowserPlatformError2("Compiled Orb execution in browsers requires WebAssembly JSPI (WebAssembly.Suspending and " + "WebAssembly.promising); this engine does not provide it.");
|
|
78
|
+
}
|
|
79
|
+
var LIMITS_MODULE = "tembra:limits";
|
|
80
|
+
var compiled = new WeakMap;
|
|
81
|
+
async function compile(source) {
|
|
82
|
+
if (source instanceof WebAssembly.Module)
|
|
83
|
+
return source;
|
|
84
|
+
if (typeof Response !== "undefined" && source instanceof Response) {
|
|
85
|
+
if (!source.ok)
|
|
86
|
+
throw new Error(`Prepared core module request failed: ${source.status}`);
|
|
87
|
+
if (typeof WebAssembly.compileStreaming === "function" && source.headers.get("content-type")?.split(";")[0]?.trim() === "application/wasm")
|
|
88
|
+
return WebAssembly.compileStreaming(source);
|
|
89
|
+
return WebAssembly.compile(await source.arrayBuffer());
|
|
90
|
+
}
|
|
91
|
+
return WebAssembly.compile(source);
|
|
92
|
+
}
|
|
93
|
+
function instrumented(module) {
|
|
94
|
+
const limits = WebAssembly.Module.imports(module).filter((entry) => entry.module === LIMITS_MODULE);
|
|
95
|
+
return limits.length === 2 && limits.every((entry) => entry.kind === "global") && limits.some((entry) => entry.name === "fuel") && limits.some((entry) => entry.name === "pages");
|
|
96
|
+
}
|
|
97
|
+
function cores(record) {
|
|
98
|
+
let loading = compiled.get(record);
|
|
99
|
+
if (!loading) {
|
|
100
|
+
loading = Promise.all(record.cores.map(async (core) => {
|
|
101
|
+
const module = await compile(await core.load());
|
|
102
|
+
if (core.pages !== undefined && !instrumented(module))
|
|
103
|
+
throw new Error(`Prepared core module ${core.name} is not instrumented`);
|
|
104
|
+
return [
|
|
105
|
+
core.name,
|
|
106
|
+
core.pages === undefined ? { module } : { module, pages: BigInt(core.pages) }
|
|
107
|
+
];
|
|
108
|
+
})).then((entries) => new Map(entries));
|
|
109
|
+
compiled.set(record, loading);
|
|
110
|
+
const current = loading;
|
|
111
|
+
current.catch(() => {
|
|
112
|
+
if (compiled.get(record) === current)
|
|
113
|
+
compiled.delete(record);
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
return loading;
|
|
117
|
+
}
|
|
118
|
+
async function instantiate(record, imports, observer, limits) {
|
|
119
|
+
const modules = await cores(record);
|
|
120
|
+
const initial = new Map;
|
|
121
|
+
for (const { module, pages } of modules.values())
|
|
122
|
+
if (pages !== undefined)
|
|
123
|
+
initial.set(module, pages);
|
|
124
|
+
const getCoreModule = async (name) => {
|
|
125
|
+
const core = modules.get(name);
|
|
126
|
+
if (!core)
|
|
127
|
+
throw new Error("Unknown prepared core module");
|
|
128
|
+
return core.module;
|
|
129
|
+
};
|
|
130
|
+
const instantiateCore = async (module, coreImports) => {
|
|
131
|
+
const pages = initial.get(module);
|
|
132
|
+
if (pages === undefined)
|
|
133
|
+
throw new Error("Uninstrumented core module");
|
|
134
|
+
if (limits.pages.value < pages)
|
|
135
|
+
throw new WebAssembly.RuntimeError("memory limit exceeded");
|
|
136
|
+
limits.pages.value = limits.pages.value - pages;
|
|
137
|
+
try {
|
|
138
|
+
return await WebAssembly.instantiate(module, {
|
|
139
|
+
...coreImports,
|
|
140
|
+
[LIMITS_MODULE]: limits
|
|
141
|
+
});
|
|
142
|
+
} catch (error) {
|
|
143
|
+
limits.pages.value = limits.pages.value + pages;
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
return record.instantiate(getCoreModule, imports, instantiateCore, {
|
|
148
|
+
tembraObserver: observer
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// src/interpreter/component/kernel.ts
|
|
153
|
+
var STATE = "tembra:guest/state@1.0.0";
|
|
154
|
+
var STATE_INIT = "tembra:guest/state-init@1.0.0";
|
|
155
|
+
var RESOURCES = "tembra:guest/resources@1.0.0";
|
|
156
|
+
var RESOURCES_INIT = "tembra:guest/resources-init@1.0.0";
|
|
157
|
+
var SERVICE_RESOURCES_INIT = "tembra:guest/service-resources-init@1.0.0";
|
|
158
|
+
var CONTEXT = "tembra:guest/context@1.0.0";
|
|
159
|
+
function isKernel(contract) {
|
|
160
|
+
return contract?.startsWith("tembra:") ?? false;
|
|
161
|
+
}
|
|
162
|
+
var LEVELS = ["log", "debug", "info", "warn", "error"];
|
|
163
|
+
var isU32 = (value) => Number.isInteger(value) && value >= 0 && value <= 4294967295;
|
|
164
|
+
function json(text, what) {
|
|
165
|
+
if (typeof text !== "string")
|
|
166
|
+
throw new Error(`${what} is not JSON text`);
|
|
167
|
+
try {
|
|
168
|
+
return JSON.parse(text, (_key, value) => Object.is(value, -0) ? 0 : value);
|
|
169
|
+
} catch (error) {
|
|
170
|
+
throw new Error(`${what} is not JSON: ${error.message}`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
function opened(name, answer) {
|
|
174
|
+
const failed = (message) => new TembraError2({ code: Code2.Unavailable, reason: Reason2.Resource, message });
|
|
175
|
+
const { tag, val } = answer ?? {};
|
|
176
|
+
if (tag === "ok")
|
|
177
|
+
return val;
|
|
178
|
+
if (tag === "err")
|
|
179
|
+
throw failed(typeof val === "string" ? `the resource \`${name}\` did not open: ${val}` : `the resource \`${name}\` did not open`);
|
|
180
|
+
throw failed(`the resource \`${name}\` did not open: its opener answered no result`);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
class ComponentKernel {
|
|
184
|
+
owner;
|
|
185
|
+
orb;
|
|
186
|
+
log;
|
|
187
|
+
#scopes = new Map;
|
|
188
|
+
#hooks = new Map;
|
|
189
|
+
#runs = new Map;
|
|
190
|
+
#numbers = new Map;
|
|
191
|
+
#next = 0;
|
|
192
|
+
#exports = new Map;
|
|
193
|
+
#convert;
|
|
194
|
+
#revision;
|
|
195
|
+
#context;
|
|
196
|
+
#used;
|
|
197
|
+
constructor(owner, orb, log) {
|
|
198
|
+
this.owner = owner;
|
|
199
|
+
this.orb = orb;
|
|
200
|
+
this.log = log;
|
|
201
|
+
const graph = owner.graph;
|
|
202
|
+
this.#convert = converters(graph);
|
|
203
|
+
for (const entry of graph.exports) {
|
|
204
|
+
if (![STATE_INIT, RESOURCES_INIT, SERVICE_RESOURCES_INIT].includes(entry.contract ?? ""))
|
|
205
|
+
continue;
|
|
206
|
+
for (const [name, fn] of Object.entries(entry.functions ?? {})) {
|
|
207
|
+
const spelling = graph.javascriptNames[name];
|
|
208
|
+
if (spelling === undefined)
|
|
209
|
+
throw new Error(`Missing WIT JavaScript name for ${name}`);
|
|
210
|
+
this.#exports.set(`${entry.contract}#${name}`, {
|
|
211
|
+
binding: entry.binding,
|
|
212
|
+
spelling,
|
|
213
|
+
values: this.#convert(fn)
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
this.#context = graph.imports.some((entry) => entry.contract === CONTEXT);
|
|
218
|
+
this.#used = this.#exports.size > 0 || graph.imports.some((entry) => isKernel(entry.contract));
|
|
219
|
+
const empty = new Map;
|
|
220
|
+
this.#revision = {
|
|
221
|
+
contract: owner.contract,
|
|
222
|
+
scopes: this.#scopes,
|
|
223
|
+
views: empty,
|
|
224
|
+
imports: empty,
|
|
225
|
+
importMethods: empty,
|
|
226
|
+
importSignatures: empty,
|
|
227
|
+
hooks: this.#hooks,
|
|
228
|
+
signatures: owner.signatures,
|
|
229
|
+
execute: (command, execution, authority) => this.#execute(command, execution, authority)
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
declareHooks(hooks, signature) {
|
|
233
|
+
for (const hook of hooks) {
|
|
234
|
+
this.#hooks.set(hook.alias, hook);
|
|
235
|
+
this.owner.signatures.set(hook.slot, signature(hook));
|
|
236
|
+
const entry = this.owner.graph.imports.find((item) => item.contract === hook.name);
|
|
237
|
+
if (entry)
|
|
238
|
+
this.#runs.set(entry.binding, hook.alias);
|
|
239
|
+
}
|
|
240
|
+
if (hooks.length)
|
|
241
|
+
this.#used = true;
|
|
242
|
+
}
|
|
243
|
+
async declare(environment, declaration, service, contract) {
|
|
244
|
+
if (!this.#used)
|
|
245
|
+
return;
|
|
246
|
+
const scope = new Scope(this.#revision, declaration, service);
|
|
247
|
+
this.#scopes.set(scope.id, scope);
|
|
248
|
+
const root = service === null ? undefined : environment.parent?.kernel;
|
|
249
|
+
if (service !== null && !root)
|
|
250
|
+
throw new Error("Missing component Orb kernel table");
|
|
251
|
+
const table = { scope, resources: new Map, hooks: new Map, context: this.#context };
|
|
252
|
+
table.root = root ?? table;
|
|
253
|
+
environment.kernel = table;
|
|
254
|
+
const callback = environment.callback({ declaration });
|
|
255
|
+
const { execution } = callback.kernel;
|
|
256
|
+
try {
|
|
257
|
+
if (this.#context)
|
|
258
|
+
table.address = execution.sync({ operation: "address" });
|
|
259
|
+
if (service === null) {
|
|
260
|
+
for (const [binding, alias] of this.#runs)
|
|
261
|
+
table.hooks.set(binding, execution.sync({ operation: "hook.declare", name: alias }));
|
|
262
|
+
const list = this.#exports.get(`${RESOURCES_INIT}#declare`);
|
|
263
|
+
if (!list)
|
|
264
|
+
return;
|
|
265
|
+
const declared = await this.#call(environment, callback, list, []);
|
|
266
|
+
this.#declareResources(environment, table, execution, declared, undefined);
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (contract === undefined)
|
|
270
|
+
return;
|
|
271
|
+
const describe = this.#exports.get(`${STATE_INIT}#declare`);
|
|
272
|
+
const declared = describe ? await this.#call(environment, callback, describe, [contract]) : null;
|
|
273
|
+
if (declared !== null) {
|
|
274
|
+
if (!isU32(declared.version))
|
|
275
|
+
throw new Error("The state declaration carries no version");
|
|
276
|
+
if (typeof declared.validated !== "boolean")
|
|
277
|
+
throw new Error("The state declaration does not say whether it is validated");
|
|
278
|
+
table.state = execution.sync({
|
|
279
|
+
operation: "state.declare",
|
|
280
|
+
initial: json(declared.initial, "The initial state"),
|
|
281
|
+
version: declared.version,
|
|
282
|
+
validate: declared.validated ? this.#number({ kind: "validate", environment: environment.id, service: contract }) : null
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
const resources = this.#exports.get(`${SERVICE_RESOURCES_INIT}#declare`);
|
|
286
|
+
if (!resources)
|
|
287
|
+
return;
|
|
288
|
+
const listed = await this.#call(environment, callback, resources, [contract]);
|
|
289
|
+
this.#declareResources(environment, table, execution, listed, contract);
|
|
290
|
+
} finally {
|
|
291
|
+
callback.cancel();
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
#declareResources(environment, table, execution, declared, service) {
|
|
295
|
+
if (!Array.isArray(declared))
|
|
296
|
+
throw new Error("The resource declarations are not a list");
|
|
297
|
+
for (const resource of declared) {
|
|
298
|
+
const { name, version, dependencies: names } = resource;
|
|
299
|
+
if (typeof name !== "string")
|
|
300
|
+
throw new Error("A resource declaration carries no name");
|
|
301
|
+
if (service !== undefined && table.root !== table && table.root.resources.has(name))
|
|
302
|
+
throw new Error(`the resource \`${name}\` of each object of ${service} takes the name of the root's resource \`${name}\`: resource names are unique in the Orb`);
|
|
303
|
+
if (!isU32(version))
|
|
304
|
+
throw new Error("A resource declaration carries no version");
|
|
305
|
+
if (!Array.isArray(names))
|
|
306
|
+
throw new Error("A resource declaration carries no dependencies");
|
|
307
|
+
const dependencies = names.map((dependency) => {
|
|
308
|
+
if (typeof dependency !== "string")
|
|
309
|
+
throw new Error("A resource dependency is not a name");
|
|
310
|
+
const id = table.resources.get(dependency);
|
|
311
|
+
if (id !== undefined)
|
|
312
|
+
return { id };
|
|
313
|
+
const root = table.root.resources.get(dependency);
|
|
314
|
+
if (table.root !== table && root !== undefined)
|
|
315
|
+
return { scope: table.root.scope.id, id: root };
|
|
316
|
+
throw new Error(`the resource \`${name}\` depends on \`${dependency}\`, which the Orb does not declare before it`);
|
|
317
|
+
});
|
|
318
|
+
const numbered = { environment: environment.id, name, ...service && { service } };
|
|
319
|
+
const id = execution.sync({
|
|
320
|
+
operation: "resource.declare",
|
|
321
|
+
name,
|
|
322
|
+
version,
|
|
323
|
+
open: this.#number({ kind: "open", ...numbered }),
|
|
324
|
+
close: this.#number({ kind: "close", ...numbered }),
|
|
325
|
+
dependencies
|
|
326
|
+
});
|
|
327
|
+
if (table.resources.has(name))
|
|
328
|
+
throw new Error("A resource is declared twice");
|
|
329
|
+
table.resources.set(name, id);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
async validate(environment, value) {
|
|
333
|
+
const table = environment.kernel;
|
|
334
|
+
if (!table)
|
|
335
|
+
return;
|
|
336
|
+
for (const number of table.scope.validators) {
|
|
337
|
+
const numbered = this.#numbers.get(number);
|
|
338
|
+
if (numbered?.kind !== "validate" || numbered.environment !== environment.id)
|
|
339
|
+
throw new Error("Unknown compiled state validator");
|
|
340
|
+
const validator = this.#exports.get(`${STATE_INIT}#validate`);
|
|
341
|
+
if (!validator)
|
|
342
|
+
throw new Error("The component declares no kernel state validator");
|
|
343
|
+
const callback = environment.callback({ validation: true });
|
|
344
|
+
let verdict;
|
|
345
|
+
try {
|
|
346
|
+
verdict = await this.#call(environment, callback, validator, [
|
|
347
|
+
numbered.service,
|
|
348
|
+
encode(value).text
|
|
349
|
+
]);
|
|
350
|
+
} finally {
|
|
351
|
+
callback.cancel();
|
|
352
|
+
}
|
|
353
|
+
if (verdict.tag === "err")
|
|
354
|
+
throw new Error(typeof verdict.val === "string" ? `the state was refused: ${verdict.val}` : "the state was refused");
|
|
355
|
+
if (verdict.tag !== "ok")
|
|
356
|
+
throw new Error("the state validator answered no result");
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
release(environment) {
|
|
360
|
+
this.#scopes.delete(environment);
|
|
361
|
+
for (const [number, numbered] of this.#numbers)
|
|
362
|
+
if (numbered.environment === environment)
|
|
363
|
+
this.#numbers.delete(number);
|
|
364
|
+
}
|
|
365
|
+
imports(binding) {
|
|
366
|
+
const entry = this.owner.graph.imports.find((item) => item.binding === binding);
|
|
367
|
+
if (!entry)
|
|
368
|
+
throw new Error(`Browser component execution cannot provide import ${binding}`);
|
|
369
|
+
const functions = Object.entries(entry.functions ?? {}).map(([name, fn]) => {
|
|
370
|
+
const spelling = this.owner.graph.javascriptNames[name];
|
|
371
|
+
if (spelling === undefined)
|
|
372
|
+
throw new Error(`Missing WIT JavaScript name for ${name}`);
|
|
373
|
+
return { name, spelling, values: this.#convert(fn) };
|
|
374
|
+
});
|
|
375
|
+
const serve = (answer) => Object.fromEntries(functions.map(({ name, spelling, values }) => [
|
|
376
|
+
spelling,
|
|
377
|
+
(...args) => answer(name, values, values.hostArguments(args))
|
|
378
|
+
]));
|
|
379
|
+
switch (entry.contract) {
|
|
380
|
+
case STATE:
|
|
381
|
+
return serve((name, values, args) => values.toGuest(this.#state(name, args)));
|
|
382
|
+
case RESOURCES:
|
|
383
|
+
return serve((name, _, args) => this.#resource(name, args));
|
|
384
|
+
case CONTEXT:
|
|
385
|
+
return serve((name, values, args) => values.toGuest(this.#contextual(name, args)));
|
|
386
|
+
}
|
|
387
|
+
if (isKernel(entry.contract))
|
|
388
|
+
throw new Error(`The kernel serves no ${entry.contract}`);
|
|
389
|
+
return serve((_, values, args) => this.#run(binding, values, args));
|
|
390
|
+
}
|
|
391
|
+
#current() {
|
|
392
|
+
const callback = this.owner.port.current();
|
|
393
|
+
const access = callback.scope.kernel;
|
|
394
|
+
if (!access)
|
|
395
|
+
throw new Error("The kernel interfaces need a callback of this Orb");
|
|
396
|
+
return { callback, ...access };
|
|
397
|
+
}
|
|
398
|
+
#state(name, args) {
|
|
399
|
+
const { table, execution } = this.#current();
|
|
400
|
+
if (table.state === undefined)
|
|
401
|
+
throw new Error(table.root === table ? "contributions run in the Orb root, which owns no kernel state" : "this service object declares no kernel state");
|
|
402
|
+
let snapshot;
|
|
403
|
+
if (name === "read" && args.length === 0)
|
|
404
|
+
snapshot = execution.sync({ operation: "state.read", id: table.state });
|
|
405
|
+
else if (name === "update" && args.length === 1) {
|
|
406
|
+
const value = json(args[0], "The state value");
|
|
407
|
+
try {
|
|
408
|
+
snapshot = execution.sync({ operation: "state.update", id: table.state, value });
|
|
409
|
+
} catch (error) {
|
|
410
|
+
if (execution.sync({ operation: "signal.cancelled" }) !== true)
|
|
411
|
+
throw error;
|
|
412
|
+
snapshot = execution.sync({ operation: "state.read", id: table.state });
|
|
413
|
+
}
|
|
414
|
+
} else
|
|
415
|
+
throw new Error("unknown kernel state function");
|
|
416
|
+
return JSON.stringify(snapshot.value);
|
|
417
|
+
}
|
|
418
|
+
#resource(name, args) {
|
|
419
|
+
const { table, execution } = this.#current();
|
|
420
|
+
const [resource] = args;
|
|
421
|
+
if (name !== "read" || args.length !== 1 || typeof resource !== "string")
|
|
422
|
+
throw new Error("unknown kernel resource function");
|
|
423
|
+
const owner = [table, table.root].find((each) => each.resources.has(resource));
|
|
424
|
+
if (!owner)
|
|
425
|
+
throw new Error(`neither this object nor the Orb root declares a resource named ${resource}`);
|
|
426
|
+
const id = owner.resources.get(resource);
|
|
427
|
+
const handle = execution.sync({ operation: "resource.read", scope: owner.scope.id, id });
|
|
428
|
+
if (!isU32(handle))
|
|
429
|
+
throw new Error("resource handle is not a u32");
|
|
430
|
+
return handle;
|
|
431
|
+
}
|
|
432
|
+
#contextual(name, args) {
|
|
433
|
+
const { table, execution, principal } = this.#current();
|
|
434
|
+
switch (name) {
|
|
435
|
+
case "object":
|
|
436
|
+
if (table.address === undefined)
|
|
437
|
+
throw new Error("the address of this environment's object was not declared");
|
|
438
|
+
return table.address;
|
|
439
|
+
case "principal":
|
|
440
|
+
return principal ?? execution.sync({ operation: "context.principal" });
|
|
441
|
+
case "cancelled":
|
|
442
|
+
return execution.sync({ operation: "signal.cancelled" });
|
|
443
|
+
case "cancel":
|
|
444
|
+
try {
|
|
445
|
+
execution.sync({ operation: "context.cancel" });
|
|
446
|
+
} catch (error) {
|
|
447
|
+
if (execution.sync({ operation: "signal.cancelled" }) !== true)
|
|
448
|
+
throw error;
|
|
449
|
+
}
|
|
450
|
+
return null;
|
|
451
|
+
case "log": {
|
|
452
|
+
const [level, message] = args;
|
|
453
|
+
if (typeof level !== "string" || !LEVELS.includes(level))
|
|
454
|
+
throw new Error("Invalid console level");
|
|
455
|
+
try {
|
|
456
|
+
this.log?.({ orb: this.orb, level, message: String(message) });
|
|
457
|
+
} catch {}
|
|
458
|
+
return null;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
throw new Error("unknown kernel context function");
|
|
462
|
+
}
|
|
463
|
+
#run(binding, values, args) {
|
|
464
|
+
const { callback, table, execution } = this.#current();
|
|
465
|
+
const alias = this.#runs.get(binding);
|
|
466
|
+
const id = table.root.hooks.get(binding);
|
|
467
|
+
if (alias === undefined || id === undefined)
|
|
468
|
+
throw new Error(`the Orb root declares no hook for the import ${binding}`);
|
|
469
|
+
if (args.length !== 1)
|
|
470
|
+
throw new Error("a hook callback takes one input");
|
|
471
|
+
const shape = this.owner.signatures.get(this.#hooks.get(alias).slot);
|
|
472
|
+
const [value] = JSON.parse(encode(args, VALUE_LIMIT, shape?.params).text);
|
|
473
|
+
const run = execution.async({
|
|
474
|
+
operation: "hook.run",
|
|
475
|
+
scope: table.root.scope.id,
|
|
476
|
+
id,
|
|
477
|
+
value
|
|
478
|
+
});
|
|
479
|
+
return this.owner.port.physical(callback, run).then((result) => values.toGuest(lift(shape?.result, JSON.parse(result.text))));
|
|
480
|
+
}
|
|
481
|
+
#number(numbered) {
|
|
482
|
+
if (this.#next >= 4294967295)
|
|
483
|
+
throw new Error("callback space exhausted");
|
|
484
|
+
this.#numbers.set(++this.#next, numbered);
|
|
485
|
+
return this.#next;
|
|
486
|
+
}
|
|
487
|
+
#call(environment, callback, exported, args) {
|
|
488
|
+
const port = this.owner.port;
|
|
489
|
+
return port.run(BigInt(environment.id), callback, () => exported.values.fromGuest(() => {
|
|
490
|
+
const fn = port.exports?.[exported.binding]?.[exported.spelling];
|
|
491
|
+
if (typeof fn !== "function")
|
|
492
|
+
throw new Error(`The component does not export ${exported.binding}#${exported.spelling}`);
|
|
493
|
+
return fn(...exported.values.guestArguments(args));
|
|
494
|
+
}));
|
|
495
|
+
}
|
|
496
|
+
async#execute(command, execution, authority) {
|
|
497
|
+
const { callback: number, value } = JSON.parse(command);
|
|
498
|
+
const numbered = this.#numbers.get(number);
|
|
499
|
+
if (numbered?.kind !== "open" && numbered?.kind !== "close")
|
|
500
|
+
throw new Error("Unknown compiled resource callback");
|
|
501
|
+
const environment = this.owner.scopes.get(numbered.environment);
|
|
502
|
+
if (!environment)
|
|
503
|
+
throw new Error("The resource's Orb scope is gone");
|
|
504
|
+
const { service } = numbered;
|
|
505
|
+
const exported = this.#exports.get(`${service === undefined ? RESOURCES_INIT : SERVICE_RESOURCES_INIT}#${numbered.kind}`);
|
|
506
|
+
if (!exported)
|
|
507
|
+
throw new Error("The component declares no kernel resource callbacks");
|
|
508
|
+
const named = service === undefined ? [numbered.name] : [service, numbered.name];
|
|
509
|
+
const issued = "context" in authority ? environment.exchange(authority.context, execution) : environment.callback(authority, execution);
|
|
510
|
+
const access = issued.kernel;
|
|
511
|
+
let callback = issued;
|
|
512
|
+
if (access) {
|
|
513
|
+
const { state: _state, ...table } = access.table;
|
|
514
|
+
callback = { ...issued, kernel: { ...access, table, principal: "host" } };
|
|
515
|
+
}
|
|
516
|
+
const release = await this.owner.gate.enter(undefined, callback.signal);
|
|
517
|
+
try {
|
|
518
|
+
if (numbered.kind === "open") {
|
|
519
|
+
const answer = await this.#call(environment, callback, exported, named);
|
|
520
|
+
const handle = opened(numbered.name, answer);
|
|
521
|
+
if (!isU32(handle))
|
|
522
|
+
throw new Error("resource handle is not a u32");
|
|
523
|
+
return handle;
|
|
524
|
+
}
|
|
525
|
+
if (!isU32(value))
|
|
526
|
+
throw new Error("resource closer without a handle");
|
|
527
|
+
await this.#call(environment, callback, exported, [...named, value]);
|
|
528
|
+
return null;
|
|
529
|
+
} finally {
|
|
530
|
+
callback.cancel();
|
|
531
|
+
release();
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// src/interpreter/component/scope.ts
|
|
537
|
+
var scopeEnded = Object.freeze(new Error("Component callback scope ended"));
|
|
538
|
+
function admittedPrincipal(context) {
|
|
539
|
+
try {
|
|
540
|
+
return context.principal;
|
|
541
|
+
} catch {
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
var claims = new WeakMap;
|
|
546
|
+
|
|
547
|
+
class ComponentScope {
|
|
548
|
+
owner;
|
|
549
|
+
declaration;
|
|
550
|
+
id;
|
|
551
|
+
parent;
|
|
552
|
+
defaults = new Map;
|
|
553
|
+
kernel;
|
|
554
|
+
constructor(owner, declaration, service) {
|
|
555
|
+
this.owner = owner;
|
|
556
|
+
this.declaration = declaration;
|
|
557
|
+
this.id = declaration.environment.id;
|
|
558
|
+
const parent = service === null ? undefined : declaration.environment.orb.scope;
|
|
559
|
+
this.parent = parent ? owner.scopes.get(parent.id) : undefined;
|
|
560
|
+
if (service !== null && !this.parent)
|
|
561
|
+
throw new Error("Missing component Orb scope");
|
|
562
|
+
if (service === null) {
|
|
563
|
+
for (const [binding, name] of owner.imports)
|
|
564
|
+
if (!owner.views.has(binding))
|
|
565
|
+
this.defaults.set(binding, declaration.get(name, ["main"]));
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
exchange(context, execution) {
|
|
569
|
+
const kernel = this.access({ context }, execution);
|
|
570
|
+
const ended = new AbortController;
|
|
571
|
+
const dropped = new Set;
|
|
572
|
+
const droppedResources = new Set;
|
|
573
|
+
const release = (token) => {
|
|
574
|
+
const claim = this.claim(token, token.binding);
|
|
575
|
+
if (claim.root === context.root)
|
|
576
|
+
claim.reference.release();
|
|
577
|
+
};
|
|
578
|
+
const live = () => {
|
|
579
|
+
if (ended.signal.aborted)
|
|
580
|
+
throw scopeEnded;
|
|
581
|
+
};
|
|
582
|
+
return {
|
|
583
|
+
signal: context.signal,
|
|
584
|
+
check: () => context.check(),
|
|
585
|
+
...kernel ? { kernel } : {},
|
|
586
|
+
report: (error) => this.declaration.session.report(error),
|
|
587
|
+
cancel: () => {
|
|
588
|
+
if (!ended.signal.aborted)
|
|
589
|
+
ended.abort(scopeEnded);
|
|
590
|
+
kernel?.execution.cancel();
|
|
591
|
+
for (const token of dropped) {
|
|
592
|
+
try {
|
|
593
|
+
release(token);
|
|
594
|
+
} catch (error) {
|
|
595
|
+
this.declaration.session.report(error);
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
dropped.clear();
|
|
599
|
+
for (const owner of droppedResources) {
|
|
600
|
+
try {
|
|
601
|
+
owner.close();
|
|
602
|
+
} catch (error) {
|
|
603
|
+
this.declaration.session.report(error);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
droppedResources.clear();
|
|
607
|
+
},
|
|
608
|
+
call: async (binding, method, args, arguments_) => {
|
|
609
|
+
live();
|
|
610
|
+
const reference = (this.parent ?? this).defaults.get(binding);
|
|
611
|
+
if (!reference)
|
|
612
|
+
throw new Error("The component has no Orb dependency for this import");
|
|
613
|
+
const bound = this.owner.importMethods.get(binding)?.get(method);
|
|
614
|
+
if (!bound)
|
|
615
|
+
throw new Error("Unknown prepared import method");
|
|
616
|
+
return this.call(reference, binding, bound, args, context, ended.signal, undefined, arguments_);
|
|
617
|
+
},
|
|
618
|
+
releaseResource: (owner) => {
|
|
619
|
+
if (ended.signal.aborted)
|
|
620
|
+
owner.close();
|
|
621
|
+
else
|
|
622
|
+
droppedResources.add(owner);
|
|
623
|
+
},
|
|
624
|
+
resource: async (owner, binding, method, args, arguments_) => {
|
|
625
|
+
live();
|
|
626
|
+
const bound = this.owner.importMethods.get(binding)?.get(method);
|
|
627
|
+
if (!bound?.roles?.receiver)
|
|
628
|
+
throw new Error("Not a prepared resource method");
|
|
629
|
+
if (owner.nominal.interface !== bound.roles.receiver.interface || owner.nominal.name !== bound.roles.receiver.name)
|
|
630
|
+
throw new Error("Resource has another nominal type");
|
|
631
|
+
return this.call(owner.reference, binding, bound, args, context, ended.signal, owner, arguments_);
|
|
632
|
+
},
|
|
633
|
+
acquire: async (binding, key, abandoned) => {
|
|
634
|
+
live();
|
|
635
|
+
return this.acquire(binding, key, context, combinedSignal(ended.signal, abandoned));
|
|
636
|
+
},
|
|
637
|
+
invoke: async (token, binding, method, args) => {
|
|
638
|
+
live();
|
|
639
|
+
const claim = this.claim(token, binding);
|
|
640
|
+
if (claim.root !== context.root)
|
|
641
|
+
throw new Error("Reference belongs to another root");
|
|
642
|
+
const session = this.declaration.session;
|
|
643
|
+
if (!session.rootReferences.has(claim.root))
|
|
644
|
+
throw new Error("Reference expired with its root");
|
|
645
|
+
if (session.handles.reference(claim.reference).released)
|
|
646
|
+
throw new Error("Reference was released");
|
|
647
|
+
const bound = this.owner.views.get(binding)?.get(method);
|
|
648
|
+
if (!bound)
|
|
649
|
+
throw new Error("Unknown prepared reference method");
|
|
650
|
+
return this.call(claim.reference, binding, bound, args, context, ended.signal);
|
|
651
|
+
},
|
|
652
|
+
release: (token) => {
|
|
653
|
+
const claim = this.claim(token, token.binding);
|
|
654
|
+
if (claim.root !== context.root)
|
|
655
|
+
return;
|
|
656
|
+
if (ended.signal.aborted)
|
|
657
|
+
release(token);
|
|
658
|
+
else
|
|
659
|
+
dropped.add(token);
|
|
660
|
+
}
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
callback(authority, execution) {
|
|
664
|
+
const kernel = this.access(authority, execution);
|
|
665
|
+
if (!kernel)
|
|
666
|
+
throw new Error("This Orb uses no kernel interface");
|
|
667
|
+
const refused = () => Promise.reject(new Error("Operation requires an admitted invocation"));
|
|
668
|
+
return {
|
|
669
|
+
..."signal" in authority ? { signal: authority.signal } : {},
|
|
670
|
+
check: () => kernel.execution.check(),
|
|
671
|
+
report: (error) => this.declaration.session.report(error),
|
|
672
|
+
kernel,
|
|
673
|
+
cancel: () => kernel.execution.cancel(),
|
|
674
|
+
call: refused,
|
|
675
|
+
acquire: refused,
|
|
676
|
+
invoke: refused,
|
|
677
|
+
release: () => {},
|
|
678
|
+
releaseResource: (owner) => owner.close()
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
access(authority, execution) {
|
|
682
|
+
const table = this.kernel;
|
|
683
|
+
if (!table)
|
|
684
|
+
return;
|
|
685
|
+
return {
|
|
686
|
+
table,
|
|
687
|
+
execution: execution ?? table.scope.exchange(authority),
|
|
688
|
+
..."context" in authority && table.context ? { principal: admittedPrincipal(authority.context) } : {}
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
claim(token, binding) {
|
|
692
|
+
const claim = claims.get(token);
|
|
693
|
+
if (!claim || claim.owner !== this.owner || claim.binding !== binding)
|
|
694
|
+
throw new Error("Foreign reference handle");
|
|
695
|
+
return claim;
|
|
696
|
+
}
|
|
697
|
+
async acquire(binding, key, context, ended) {
|
|
698
|
+
if (!this.owner.views.has(binding))
|
|
699
|
+
throw new Error("The import is not a reference view");
|
|
700
|
+
const service = this.owner.imports.get(binding);
|
|
701
|
+
if (!service)
|
|
702
|
+
throw new Error("Reference is not a selected WIT Orb import");
|
|
703
|
+
return acquireReference(this.declaration, service, key, context, ended, (reference) => {
|
|
704
|
+
const token = Object.freeze({ binding });
|
|
705
|
+
claims.set(token, {
|
|
706
|
+
owner: this.owner,
|
|
707
|
+
binding,
|
|
708
|
+
reference,
|
|
709
|
+
root: context.root
|
|
710
|
+
});
|
|
711
|
+
return token;
|
|
712
|
+
});
|
|
713
|
+
}
|
|
714
|
+
async call(reference, binding, bound, args, context, ended, receiver, arguments_) {
|
|
715
|
+
checkSignal(ended);
|
|
716
|
+
context.check();
|
|
717
|
+
const shape = this.owner.signatures.get(bound.slot);
|
|
718
|
+
const input = check(this.owner.contract, bound.slot, true, encode(args, VALUE_LIMIT, shape?.params));
|
|
719
|
+
const signature = this.owner.importSignatures.get(binding);
|
|
720
|
+
const resources = Boolean(bound.roles?.owned || bound.roles?.receiver || bound.roles?.stream || bound.roles?.arguments);
|
|
721
|
+
const capture = signature ? {
|
|
722
|
+
signature,
|
|
723
|
+
input,
|
|
724
|
+
...!resources ? { dataResult: true } : {},
|
|
725
|
+
...receiver ? { receiver } : {},
|
|
726
|
+
...arguments_ ? { arguments: arguments_ } : {}
|
|
727
|
+
} : undefined;
|
|
728
|
+
if (resources && !capture)
|
|
729
|
+
throw new Error("Resource transport requires an exact prepared signature");
|
|
730
|
+
const session = this.declaration.session;
|
|
731
|
+
const record = receiver ? receiver.reference : session.handles.reference(reference);
|
|
732
|
+
if (!record.methods.has(bound.name))
|
|
733
|
+
throw new Error("Reference does not expose this method");
|
|
734
|
+
const result = await session.calls.invokePhysical(record, bound.name, lift(shape?.params, JSON.parse(input.text)), context, capture) ?? null;
|
|
735
|
+
try {
|
|
736
|
+
checkSignal(ended);
|
|
737
|
+
context.check();
|
|
738
|
+
} catch (error) {
|
|
739
|
+
for (const owner of capture?.capabilities ?? [])
|
|
740
|
+
owner.close();
|
|
741
|
+
throw error;
|
|
742
|
+
}
|
|
743
|
+
if (bound.roles?.owned || bound.roles?.stream) {
|
|
744
|
+
const capabilities = capture?.capabilities ?? [];
|
|
745
|
+
try {
|
|
746
|
+
if (!capture?.output)
|
|
747
|
+
throw new Error("Prepared provider returned no captured result");
|
|
748
|
+
const output = check(this.owner.contract, bound.slot, false, capture.output);
|
|
749
|
+
const value = lift(shape?.result, JSON.parse(output.text));
|
|
750
|
+
if (bound.roles.stream) {
|
|
751
|
+
const owner = capabilities[0];
|
|
752
|
+
if (capabilities.length !== 1 || value !== 0 || owner?.kind !== "bytes")
|
|
753
|
+
throw new Error("A byte stream result names exactly one stream attachment");
|
|
754
|
+
return owner;
|
|
755
|
+
}
|
|
756
|
+
const consumed = new Set;
|
|
757
|
+
const result = bound.roles.result(value, (nominal, index) => {
|
|
758
|
+
if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || consumed.has(index))
|
|
759
|
+
throw new Error("An owned result must redeem each attachment exactly once");
|
|
760
|
+
const owner = capabilities[index];
|
|
761
|
+
if (owner?.kind !== "resource" || owner.nominal.interface !== nominal.interface || owner.nominal.name !== nominal.name)
|
|
762
|
+
throw new Error("Resource has another nominal type");
|
|
763
|
+
consumed.add(index);
|
|
764
|
+
return owner;
|
|
765
|
+
});
|
|
766
|
+
if (consumed.size !== capabilities.length)
|
|
767
|
+
throw new Error("Unused result capability attachment");
|
|
768
|
+
for (const owner of capabilities) {
|
|
769
|
+
if (owner.kind !== "resource")
|
|
770
|
+
throw new Error("Unexpected stream attachment");
|
|
771
|
+
this.owner.importedResources?.add(owner);
|
|
772
|
+
owner.whenClosed(() => this.owner.importedResources?.delete(owner));
|
|
773
|
+
}
|
|
774
|
+
return result;
|
|
775
|
+
} catch (error) {
|
|
776
|
+
for (const owner of capabilities)
|
|
777
|
+
owner.close();
|
|
778
|
+
throw error;
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
if (capture?.capabilities?.length) {
|
|
782
|
+
for (const owner of capture.capabilities)
|
|
783
|
+
owner.close();
|
|
784
|
+
throw new Error("A data result cannot carry a capability");
|
|
785
|
+
}
|
|
786
|
+
const output = capture?.output ?? check(this.owner.contract, bound.slot, false, encode(result, VALUE_LIMIT, shape?.result));
|
|
787
|
+
return lift(shape?.result, JSON.parse(output.text));
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
// src/interpreter/component/revision.ts
|
|
792
|
+
function compiledDescription(graph, identity, roles) {
|
|
793
|
+
const services = {};
|
|
794
|
+
const hooks = {};
|
|
795
|
+
const { contributions, hooks: declared = {}, services: policies = {} } = roles;
|
|
796
|
+
const spelling = (name) => {
|
|
797
|
+
const value = graph.javascriptNames[name];
|
|
798
|
+
if (value === undefined)
|
|
799
|
+
throw new Error(`Missing WIT JavaScript name for ${name}`);
|
|
800
|
+
return value;
|
|
801
|
+
};
|
|
802
|
+
for (const entry of graph.exports) {
|
|
803
|
+
if (!entry.contract || !entry.functions || !Object.keys(entry.functions).length)
|
|
804
|
+
continue;
|
|
805
|
+
const name = entry.contract.slice(entry.contract.indexOf("/") + 1).split("@")[0];
|
|
806
|
+
if (Object.hasOwn(declared, entry.contract)) {
|
|
807
|
+
hooks[spelling(name)] = declared[entry.contract];
|
|
808
|
+
continue;
|
|
809
|
+
}
|
|
810
|
+
if (Object.hasOwn(contributions, entry.contract) || isKernel(entry.contract))
|
|
811
|
+
continue;
|
|
812
|
+
const policy = Object.hasOwn(policies, entry.contract) ? policies[entry.contract] : undefined;
|
|
813
|
+
services[spelling(name)] = {
|
|
814
|
+
methods: Object.keys(entry.functions).map(spelling),
|
|
815
|
+
...policy ? { lifetime: policy.lifetime, linger: policy.linger_ms } : {}
|
|
816
|
+
};
|
|
817
|
+
}
|
|
818
|
+
return {
|
|
819
|
+
name: identity.name,
|
|
820
|
+
apiVersion: identity.apiVersion,
|
|
821
|
+
services,
|
|
822
|
+
hooks,
|
|
823
|
+
contributes: { ...contributions }
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
function entered(context) {
|
|
827
|
+
return new Context(context.session, context.root, context.invocation, context.session.kernel.command(KernelOp.EnterExecution, {
|
|
828
|
+
call: context.invocation.id,
|
|
829
|
+
context: context.frame || undefined
|
|
830
|
+
}));
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
class ComponentRevision {
|
|
834
|
+
port;
|
|
835
|
+
contract;
|
|
836
|
+
graph;
|
|
837
|
+
timeout;
|
|
838
|
+
gate = new Gate;
|
|
839
|
+
imports = new Map;
|
|
840
|
+
importSignatures = new Map;
|
|
841
|
+
importMethods = new Map;
|
|
842
|
+
views = new Map;
|
|
843
|
+
signatures = new Map;
|
|
844
|
+
scopes = new Map;
|
|
845
|
+
importedResources = new Set;
|
|
846
|
+
#issuedResources = new Map;
|
|
847
|
+
ingressBridge;
|
|
848
|
+
kernel;
|
|
849
|
+
#closed = false;
|
|
850
|
+
constructor(port, contract, graph, timeout, log = { orb: "" }) {
|
|
851
|
+
this.port = port;
|
|
852
|
+
this.contract = contract;
|
|
853
|
+
this.graph = graph;
|
|
854
|
+
this.timeout = timeout;
|
|
855
|
+
this.kernel = new ComponentKernel(this, log.orb, log.observer);
|
|
856
|
+
port.wasi.retired.addEventListener("abort", () => {
|
|
857
|
+
for (const owner of this.importedResources)
|
|
858
|
+
owner.close();
|
|
859
|
+
for (const owners of this.#issuedResources.values())
|
|
860
|
+
for (const retire of owners)
|
|
861
|
+
retire();
|
|
862
|
+
}, { once: true });
|
|
863
|
+
}
|
|
864
|
+
async invoke(key, spelling, values, slot, shape, environment, scope, input, roles = {}, receiver, retain, arguments_) {
|
|
865
|
+
const unlock = await this.gate.enter(undefined, scope.signal);
|
|
866
|
+
let released = false;
|
|
867
|
+
const release = () => {
|
|
868
|
+
if (released)
|
|
869
|
+
return;
|
|
870
|
+
released = true;
|
|
871
|
+
unlock();
|
|
872
|
+
};
|
|
873
|
+
let continued = false;
|
|
874
|
+
const issued = [];
|
|
875
|
+
try {
|
|
876
|
+
if (!!roles.receiver !== !!receiver)
|
|
877
|
+
throw new Error("Resource receiver differs from signature");
|
|
878
|
+
const borrowed = roles.receiver && receiver?.redeem(this, environment.id, roles.receiver);
|
|
879
|
+
const checkedInput = check(this.contract, slot, true, input);
|
|
880
|
+
let args = lift(shape.params, JSON.parse(checkedInput.text));
|
|
881
|
+
const consumed = new Set;
|
|
882
|
+
const uniqueOwners = new Set;
|
|
883
|
+
const owners = arguments_?.owners ?? [];
|
|
884
|
+
const deliveries = [];
|
|
885
|
+
if (roles.arguments) {
|
|
886
|
+
if (!arguments_)
|
|
887
|
+
throw new Error("Owned arguments require a private transfer");
|
|
888
|
+
if (arguments_.accepted)
|
|
889
|
+
throw new Error("Ownership transfer was already accepted");
|
|
890
|
+
args = roles.arguments(args, (nominal, index) => {
|
|
891
|
+
if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || consumed.has(index))
|
|
892
|
+
throw new Error("An owned argument must redeem each attachment exactly once");
|
|
893
|
+
const owner = owners[index];
|
|
894
|
+
if (!owner || owner.nominal.interface !== nominal.interface || owner.nominal.name !== nominal.name)
|
|
895
|
+
throw new Error("Resource argument has another nominal type");
|
|
896
|
+
if (uniqueOwners.has(owner))
|
|
897
|
+
throw new Error("Duplicate owned argument attachment");
|
|
898
|
+
uniqueOwners.add(owner);
|
|
899
|
+
const own = owner.issuedBy(this);
|
|
900
|
+
const wrap = own ? undefined : importedResource(this.port, nominal).wrap;
|
|
901
|
+
consumed.add(index);
|
|
902
|
+
deliveries.push({ owner, nominal, ...wrap ? { wrap } : {} });
|
|
903
|
+
return deliveries.length - 1;
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
if (consumed.size !== owners.length)
|
|
907
|
+
throw new Error("Unused argument capability attachment");
|
|
908
|
+
const guestArgs = values.guestArguments(args);
|
|
909
|
+
const call = () => {
|
|
910
|
+
const exports = this.port.exports?.[key];
|
|
911
|
+
if (!exports)
|
|
912
|
+
throw new Error(`The component does not export ${key}`);
|
|
913
|
+
return resourceExport(exports, spelling, roles, borrowed || undefined, guestArgs, arguments_ ? () => {
|
|
914
|
+
arguments_.accept();
|
|
915
|
+
return roles.arguments ? roles.arguments(guestArgs, (_nominal, index) => {
|
|
916
|
+
const delivery = deliveries[index];
|
|
917
|
+
if (!delivery.wrap)
|
|
918
|
+
return delivery.owner.take(this, delivery.nominal);
|
|
919
|
+
this.importedResources.add(delivery.owner);
|
|
920
|
+
delivery.owner.whenClosed(() => this.importedResources.delete(delivery.owner));
|
|
921
|
+
return delivery.wrap(delivery.owner);
|
|
922
|
+
}) : guestArgs;
|
|
923
|
+
} : undefined);
|
|
924
|
+
};
|
|
925
|
+
if (roles.stream) {
|
|
926
|
+
const task = this.port.start(BigInt(environment.id), scope, call);
|
|
927
|
+
retain?.(task.physical);
|
|
928
|
+
const finished = task.finished.finally(() => {
|
|
929
|
+
scope.cancel();
|
|
930
|
+
release();
|
|
931
|
+
});
|
|
932
|
+
continued = true;
|
|
933
|
+
let owner;
|
|
934
|
+
try {
|
|
935
|
+
const raw = await task.result;
|
|
936
|
+
owner = issueByteStream(raw, finished, scope.signal ?? new AbortController().signal);
|
|
937
|
+
const value = check(this.contract, slot, false, encode(0));
|
|
938
|
+
task.park();
|
|
939
|
+
release();
|
|
940
|
+
return { value, capabilities: [owner], finished };
|
|
941
|
+
} catch (error) {
|
|
942
|
+
owner?.close();
|
|
943
|
+
await finished.catch(() => {
|
|
944
|
+
return;
|
|
945
|
+
});
|
|
946
|
+
throw error;
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
const result = await this.port.run(BigInt(environment.id), scope, async () => {
|
|
950
|
+
const result = await values.fromGuest(call).catch((error) => {
|
|
951
|
+
if (arguments_?.accepted)
|
|
952
|
+
this.port.poison(error);
|
|
953
|
+
throw error;
|
|
954
|
+
});
|
|
955
|
+
if (!roles.result)
|
|
956
|
+
return result;
|
|
957
|
+
return roles.result(result, (nominal, raw) => {
|
|
958
|
+
if (typeof raw !== "object" || raw === null)
|
|
959
|
+
throw new Error("Owned result is not a resource");
|
|
960
|
+
const owner = new ResourceOwner(nominal, this, environment.id, raw, () => {
|
|
961
|
+
return this.port.cleanup(async () => {
|
|
962
|
+
const unlock = await this.gate.enter();
|
|
963
|
+
try {
|
|
964
|
+
if (this.scopes.has(environment.id))
|
|
965
|
+
await this.port.destroy(() => {
|
|
966
|
+
const dispose = raw[Symbol.dispose];
|
|
967
|
+
if (typeof dispose !== "function")
|
|
968
|
+
throw new Error("Resource has no destructor");
|
|
969
|
+
dispose.call(raw);
|
|
970
|
+
});
|
|
971
|
+
} finally {
|
|
972
|
+
unlock();
|
|
973
|
+
}
|
|
974
|
+
});
|
|
975
|
+
});
|
|
976
|
+
let owners = this.#issuedResources.get(environment.id);
|
|
977
|
+
if (!owners)
|
|
978
|
+
this.#issuedResources.set(environment.id, owners = new Set);
|
|
979
|
+
const retire = owner.retirement();
|
|
980
|
+
owners.add(retire);
|
|
981
|
+
owner.whenRetired(() => owners.delete(retire));
|
|
982
|
+
issued.push(owner);
|
|
983
|
+
return issued.length - 1;
|
|
984
|
+
});
|
|
985
|
+
}, retain);
|
|
986
|
+
const value = check(this.contract, slot, false, encode(result, VALUE_LIMIT, shape.result));
|
|
987
|
+
return roles.owned ? { value, capabilities: issued } : value;
|
|
988
|
+
} catch (error) {
|
|
989
|
+
for (const owner of issued)
|
|
990
|
+
owner.close();
|
|
991
|
+
throw error;
|
|
992
|
+
} finally {
|
|
993
|
+
if (!continued) {
|
|
994
|
+
scope.cancel();
|
|
995
|
+
release();
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
ingress(contract, description, create, admit) {
|
|
1000
|
+
if (contract !== HTTP_HANDLER)
|
|
1001
|
+
throw new Error(`Unsupported incoming HTTP export ${contract}`);
|
|
1002
|
+
const service = this.graph.javascriptNames["handler"];
|
|
1003
|
+
const method = this.graph.javascriptNames["handle"];
|
|
1004
|
+
if (!service || !method)
|
|
1005
|
+
throw new Error("Missing prepared incoming HTTP handler names");
|
|
1006
|
+
const declared = description.services[service];
|
|
1007
|
+
if (!declared?.methods.includes(method))
|
|
1008
|
+
throw new Error(`The Orb exports ${HTTP_HANDLER} without a ${service}.${method} handler`);
|
|
1009
|
+
return {
|
|
1010
|
+
[declareFactory2]: create(service),
|
|
1011
|
+
lifetime: declared.lifetime,
|
|
1012
|
+
linger: declared.linger,
|
|
1013
|
+
[admitFactory2]: admit,
|
|
1014
|
+
methods: {
|
|
1015
|
+
handle: async (environment, context, value) => {
|
|
1016
|
+
const exchange = IngressExchange.claim(value);
|
|
1017
|
+
const bridge = this.ingressBridge;
|
|
1018
|
+
if (!bridge)
|
|
1019
|
+
throw new Error("This browser host has no incoming HTTP bridge");
|
|
1020
|
+
const scope = environment.exchange(entered(context));
|
|
1021
|
+
let failure = new Error("the HTTP handler callback ended");
|
|
1022
|
+
let physical;
|
|
1023
|
+
const release = await this.gate.enter(undefined, scope.signal);
|
|
1024
|
+
try {
|
|
1025
|
+
const task = this.port.start(BigInt(environment.id), scope, async () => {
|
|
1026
|
+
const handle = this.port.exports?.[HTTP_HANDLER]?.[method];
|
|
1027
|
+
if (typeof handle !== "function")
|
|
1028
|
+
throw new Error(`The component does not export ${HTTP_HANDLER}#${method}`);
|
|
1029
|
+
try {
|
|
1030
|
+
return { ok: await handle(bridge.request(exchange.own())) };
|
|
1031
|
+
} catch (error) {
|
|
1032
|
+
if (error === null || typeof error !== "object" || !Object.hasOwn(error, "payload"))
|
|
1033
|
+
throw error;
|
|
1034
|
+
return { err: error.payload };
|
|
1035
|
+
}
|
|
1036
|
+
});
|
|
1037
|
+
physical = task.physical;
|
|
1038
|
+
const { result, finished } = task;
|
|
1039
|
+
let delivery;
|
|
1040
|
+
try {
|
|
1041
|
+
const outcome = await result;
|
|
1042
|
+
if ("ok" in outcome)
|
|
1043
|
+
delivery = bridge.respond(outcome.ok, exchange);
|
|
1044
|
+
else
|
|
1045
|
+
exchange.refuse(outcome.err);
|
|
1046
|
+
} finally {
|
|
1047
|
+
await finished;
|
|
1048
|
+
}
|
|
1049
|
+
await delivery;
|
|
1050
|
+
failure = undefined;
|
|
1051
|
+
} catch (error) {
|
|
1052
|
+
failure = error;
|
|
1053
|
+
throw error;
|
|
1054
|
+
} finally {
|
|
1055
|
+
exchange.settle(failure);
|
|
1056
|
+
scope.cancel();
|
|
1057
|
+
await physical?.catch(() => {
|
|
1058
|
+
return;
|
|
1059
|
+
});
|
|
1060
|
+
release();
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
};
|
|
1065
|
+
}
|
|
1066
|
+
definition(identity, installation, description) {
|
|
1067
|
+
const checked = query(this.contract, {
|
|
1068
|
+
kind: "implementation",
|
|
1069
|
+
name: identity.name,
|
|
1070
|
+
apiVersion: identity.apiVersion,
|
|
1071
|
+
value: description,
|
|
1072
|
+
bindings: installation.bindings
|
|
1073
|
+
});
|
|
1074
|
+
const { plan } = checked;
|
|
1075
|
+
const graph = this.graph;
|
|
1076
|
+
const compile = shapes(graph);
|
|
1077
|
+
const convert = converters(graph);
|
|
1078
|
+
const names = graph.javascriptNames;
|
|
1079
|
+
const exported = (contract, method) => {
|
|
1080
|
+
const entry = graph.exports.find((item) => item.contract === contract);
|
|
1081
|
+
const found = Object.entries(entry?.functions ?? {}).find(([name]) => names[name] === method);
|
|
1082
|
+
if (!found)
|
|
1083
|
+
throw new Error(`Missing prepared signature for ${contract}#${method}`);
|
|
1084
|
+
return found[1];
|
|
1085
|
+
};
|
|
1086
|
+
this.kernel.declareHooks(checked.hooks.hooks, (hook) => compile(exported(hook.name, hook.method)));
|
|
1087
|
+
for (const [binding, service] of Object.entries(installation.importServices)) {
|
|
1088
|
+
if (checked.hooks.contributions.some((contribution) => contribution.binding === binding))
|
|
1089
|
+
continue;
|
|
1090
|
+
this.imports.set(binding, service);
|
|
1091
|
+
const provider = installation.bindings[binding];
|
|
1092
|
+
const requirement = provider?.kind === "orb" ? plan.orb.requires.find((item) => item.orb === provider.name) : undefined;
|
|
1093
|
+
const signature_ = requirement && Object.hasOwn(requirement.signatures, service) ? requirement.signatures[service] : undefined;
|
|
1094
|
+
if (signature_)
|
|
1095
|
+
this.importSignatures.set(binding, signature_);
|
|
1096
|
+
const selected = graph.imports.find((item) => item.binding === binding);
|
|
1097
|
+
if (!selected?.functions)
|
|
1098
|
+
throw new Error("Missing prepared import signatures");
|
|
1099
|
+
const view = graph.references[binding];
|
|
1100
|
+
if (view) {
|
|
1101
|
+
const methods = new Map;
|
|
1102
|
+
for (const [name, provider] of Object.entries(view.methods)) {
|
|
1103
|
+
const fn = selected.functions[name];
|
|
1104
|
+
if (!fn)
|
|
1105
|
+
throw new Error(`Missing prepared signature for ${binding}#${name}`);
|
|
1106
|
+
const slot = this.contract.bind(binding, name, false);
|
|
1107
|
+
this.signatures.set(slot, compile(viewMethod(fn)));
|
|
1108
|
+
methods.set(name, { name: provider, slot });
|
|
1109
|
+
}
|
|
1110
|
+
this.views.set(binding, methods);
|
|
1111
|
+
continue;
|
|
1112
|
+
}
|
|
1113
|
+
const methods = new Map;
|
|
1114
|
+
for (const [name, fn] of Object.entries(selected.functions)) {
|
|
1115
|
+
const spelling = names[name];
|
|
1116
|
+
if (!spelling || methods.has(spelling))
|
|
1117
|
+
throw new Error("Ambiguous prepared import method");
|
|
1118
|
+
const slot = this.contract.bind(binding, name, false);
|
|
1119
|
+
const roles = resourceRoles(graph, selected.contract ?? binding, {
|
|
1120
|
+
...fn,
|
|
1121
|
+
name
|
|
1122
|
+
});
|
|
1123
|
+
this.signatures.set(slot, compile(resourceDataFunction(fn, roles)));
|
|
1124
|
+
methods.set(spelling, { name, slot, roles });
|
|
1125
|
+
}
|
|
1126
|
+
this.importMethods.set(binding, methods);
|
|
1127
|
+
}
|
|
1128
|
+
let rootScope;
|
|
1129
|
+
const create = (service, contract) => async (declaration) => {
|
|
1130
|
+
const scope = new ComponentScope(this, declaration, service);
|
|
1131
|
+
if (service === null)
|
|
1132
|
+
rootScope = scope;
|
|
1133
|
+
this.scopes.set(scope.id, scope);
|
|
1134
|
+
await this.kernel.declare(scope, declaration, service, contract);
|
|
1135
|
+
return scope;
|
|
1136
|
+
};
|
|
1137
|
+
const admit = () => this.gate.enter(Math.max(1, Math.floor(this.timeout / 2)));
|
|
1138
|
+
const services = {};
|
|
1139
|
+
for (const service of checked.services) {
|
|
1140
|
+
const { interface: binding, alias } = service;
|
|
1141
|
+
const functions = graph.exports.find((item) => item.binding === binding)?.functions;
|
|
1142
|
+
services[service.name] = {
|
|
1143
|
+
[signature2]: service.signature,
|
|
1144
|
+
[declareFactory2]: create(alias, binding),
|
|
1145
|
+
lifetime: service.lifetime,
|
|
1146
|
+
linger: service.linger,
|
|
1147
|
+
[admitFactory2]: admit,
|
|
1148
|
+
methods: Object.fromEntries(Object.entries(service.methods).map(([method, spelling]) => {
|
|
1149
|
+
const slot = this.contract.bind(binding, method, true);
|
|
1150
|
+
const fn = functions?.[method];
|
|
1151
|
+
if (!fn)
|
|
1152
|
+
throw new Error(`Missing prepared signature for ${binding}#${method}`);
|
|
1153
|
+
const roles = resourceRoles(graph, binding, {
|
|
1154
|
+
...fn,
|
|
1155
|
+
name: method
|
|
1156
|
+
});
|
|
1157
|
+
const data = resourceDataFunction(fn, roles);
|
|
1158
|
+
const shape = compile(data);
|
|
1159
|
+
const values = convert(data);
|
|
1160
|
+
this.signatures.set(slot, shape);
|
|
1161
|
+
const invoke = (environment, context, input, receiver, retain, arguments_) => this.invoke(binding, spelling, values, slot, shape, environment, environment.exchange(entered(context)), input, roles, receiver, retain, arguments_);
|
|
1162
|
+
const invokeData = async (environment, context, args, retain) => {
|
|
1163
|
+
const input = check(this.contract, slot, true, encode(args, VALUE_LIMIT, shape.params));
|
|
1164
|
+
const output = await invoke(environment, context, input, undefined, retain);
|
|
1165
|
+
if (!(output instanceof Encoded)) {
|
|
1166
|
+
for (const capability of output.capabilities ?? [])
|
|
1167
|
+
capability.close();
|
|
1168
|
+
await output.finished;
|
|
1169
|
+
throw new Error("A data-only caller cannot receive a host capability");
|
|
1170
|
+
}
|
|
1171
|
+
return lift(shape.result, JSON.parse(output.text));
|
|
1172
|
+
};
|
|
1173
|
+
return [
|
|
1174
|
+
method,
|
|
1175
|
+
bindCaptured2((environment, context, ...args) => invokeData(environment, context, args), service.signature, invoke, invokeData)
|
|
1176
|
+
];
|
|
1177
|
+
}))
|
|
1178
|
+
};
|
|
1179
|
+
}
|
|
1180
|
+
if (plan.ingress)
|
|
1181
|
+
services[`${identity.name}::${HTTP_HANDLER}`] = this.ingress(plan.ingress, description, create, admit);
|
|
1182
|
+
const contributes = {};
|
|
1183
|
+
for (const binding of checked.hooks.contributions) {
|
|
1184
|
+
const fn = exported(binding.name, binding.method);
|
|
1185
|
+
const shape = compile(fn);
|
|
1186
|
+
const values = convert(fn);
|
|
1187
|
+
this.signatures.set(binding.slot, shape);
|
|
1188
|
+
(contributes[binding.target] ??= {})[binding.name] = {
|
|
1189
|
+
priority: binding.priority,
|
|
1190
|
+
handle: async (context, input) => {
|
|
1191
|
+
if (!rootScope || this.scopes.get(rootScope.id) !== rootScope)
|
|
1192
|
+
throw new Error("Contribution Orb scope is unavailable");
|
|
1193
|
+
const arguments_ = check(this.contract, binding.slot, true, encode([input], VALUE_LIMIT, shape.params));
|
|
1194
|
+
let physical;
|
|
1195
|
+
let result;
|
|
1196
|
+
try {
|
|
1197
|
+
result = await this.invoke(binding.name, binding.method, values, binding.slot, shape, rootScope, rootScope.exchange(entered(context)), arguments_, {}, undefined, (actual) => {
|
|
1198
|
+
physical = actual;
|
|
1199
|
+
});
|
|
1200
|
+
} finally {
|
|
1201
|
+
await physical?.catch(() => {
|
|
1202
|
+
return;
|
|
1203
|
+
});
|
|
1204
|
+
}
|
|
1205
|
+
if (!(result instanceof Encoded)) {
|
|
1206
|
+
for (const capability of result.capabilities ?? [])
|
|
1207
|
+
capability.close();
|
|
1208
|
+
throw new Error("A contribution cannot carry a host capability");
|
|
1209
|
+
}
|
|
1210
|
+
const value = lift(shape.result, JSON.parse(checkedResult(this.contract, binding.slot, result.text).text));
|
|
1211
|
+
return binding.optional && value === null ? undefined : value;
|
|
1212
|
+
}
|
|
1213
|
+
};
|
|
1214
|
+
}
|
|
1215
|
+
return {
|
|
1216
|
+
name: identity.name,
|
|
1217
|
+
apiVersion: identity.apiVersion,
|
|
1218
|
+
services,
|
|
1219
|
+
hooks: declaredHooks(checked.hooks.hooks),
|
|
1220
|
+
contributes,
|
|
1221
|
+
requires: Object.fromEntries(plan.orb.requires.map((requirement) => [
|
|
1222
|
+
requirement.orb,
|
|
1223
|
+
{ ...requirement, [signatures2]: requirement.signatures }
|
|
1224
|
+
])),
|
|
1225
|
+
[isolatedRevision2]: true,
|
|
1226
|
+
[declareFactory2]: create(null),
|
|
1227
|
+
[validateEnvironment2]: async (environment, value) => {
|
|
1228
|
+
const scope = this.scopes.get(environment.id);
|
|
1229
|
+
if (!scope)
|
|
1230
|
+
throw new Error("Validator scope is gone");
|
|
1231
|
+
const release = await this.gate.enter();
|
|
1232
|
+
try {
|
|
1233
|
+
await this.kernel.validate(scope, value);
|
|
1234
|
+
} finally {
|
|
1235
|
+
release();
|
|
1236
|
+
}
|
|
1237
|
+
},
|
|
1238
|
+
[admitFactory2]: admit,
|
|
1239
|
+
[releaseEnvironment2]: async (environment) => {
|
|
1240
|
+
if (environment === environment.orb.scope) {
|
|
1241
|
+
for (const owner of this.importedResources)
|
|
1242
|
+
owner.close();
|
|
1243
|
+
this.importedResources.clear();
|
|
1244
|
+
}
|
|
1245
|
+
const owners = this.#issuedResources.get(environment.id);
|
|
1246
|
+
for (const retire of owners ?? [])
|
|
1247
|
+
retire();
|
|
1248
|
+
await this.port.settled();
|
|
1249
|
+
this.#issuedResources.delete(environment.id);
|
|
1250
|
+
this.kernel.release(environment.id);
|
|
1251
|
+
this.scopes.delete(environment.id);
|
|
1252
|
+
},
|
|
1253
|
+
[disposeOrb2]: async () => {
|
|
1254
|
+
if (this.#closed)
|
|
1255
|
+
return;
|
|
1256
|
+
if (this.scopes.size)
|
|
1257
|
+
throw new Error("Component still owns physical scopes");
|
|
1258
|
+
await this.port.close();
|
|
1259
|
+
this.#closed = true;
|
|
1260
|
+
}
|
|
1261
|
+
};
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
// src/interpreter/component/execution.ts
|
|
1266
|
+
var PAGE = 1 << 16;
|
|
1267
|
+
function positive(name, value) {
|
|
1268
|
+
if (!Number.isSafeInteger(value) || value <= 0)
|
|
1269
|
+
throw new Error(`limits.${name} must be a positive safe integer`);
|
|
1270
|
+
return value;
|
|
1271
|
+
}
|
|
1272
|
+
function checkAdapter(record, graph, plan) {
|
|
1273
|
+
for (const entry of graph.exports)
|
|
1274
|
+
for (const name of Object.keys(entry.functions ?? {}))
|
|
1275
|
+
if (!record.promising.has(`${entry.binding}#${name}`))
|
|
1276
|
+
throw new Error(`The prepared adapter does not wrap export ${entry.binding}#${name}`);
|
|
1277
|
+
for (const name of record.imports) {
|
|
1278
|
+
if (name.startsWith("wasi:"))
|
|
1279
|
+
continue;
|
|
1280
|
+
const selected = graph.imports.find((item) => item.binding === name);
|
|
1281
|
+
if (!selected)
|
|
1282
|
+
throw new Error(`The prepared adapter names unknown import ${name}`);
|
|
1283
|
+
if (selected.type_only)
|
|
1284
|
+
continue;
|
|
1285
|
+
const kind = plan.bindings[name]?.kind;
|
|
1286
|
+
if (kind !== "kernel" && kind !== "hook" && (kind !== "orb" || !Object.hasOwn(plan.importServices, name)))
|
|
1287
|
+
throw new Error(`Browser component execution cannot provide import ${name}`);
|
|
1288
|
+
for (const fn of Object.keys(selected.functions ?? {}))
|
|
1289
|
+
if (!record.suspending.has(`${name}#${fn}`))
|
|
1290
|
+
throw new Error(`The prepared adapter does not suspend import ${name}#${fn}`);
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
async function openComponent(record, contract, installation, options, release) {
|
|
1294
|
+
requireJspi();
|
|
1295
|
+
const identity = JSON.parse(contract.description());
|
|
1296
|
+
if (identity.name !== record.orb.name || identity.apiVersion !== record.orb.apiVersion)
|
|
1297
|
+
throw new Error("The prepared adapter was generated for another Orb identity");
|
|
1298
|
+
checkPublicWasi(record.imports);
|
|
1299
|
+
const prepared = query(contract, {
|
|
1300
|
+
kind: "install",
|
|
1301
|
+
name: identity.name,
|
|
1302
|
+
apiVersion: identity.apiVersion,
|
|
1303
|
+
requires: installation.requires ?? {},
|
|
1304
|
+
grants: installation.grants ?? {},
|
|
1305
|
+
filesystem: Object.keys(options.providers?.filesystem ?? {}),
|
|
1306
|
+
network: Object.keys(options.providers?.network ?? {}),
|
|
1307
|
+
http: Object.keys(options.providers?.http ?? {})
|
|
1308
|
+
});
|
|
1309
|
+
const graph = query(contract, { kind: "describe" });
|
|
1310
|
+
checkAdapter(record, graph, prepared);
|
|
1311
|
+
const timeout = positive("timeoutMs", options.limits?.timeoutMs ?? 1e4);
|
|
1312
|
+
const memoryBytes = positive("memoryBytes", options.limits?.memoryBytes ?? 128 << 20);
|
|
1313
|
+
const fuel = BigInt(positive("fuel", options.limits?.fuel ?? 1e8));
|
|
1314
|
+
const maximumPages = Math.floor(memoryBytes / PAGE);
|
|
1315
|
+
if (maximumPages < 1 || maximumPages > record.maximumPages)
|
|
1316
|
+
throw new Error(`limits.memoryBytes must hold between 1 and ${record.maximumPages} pages of 64 KiB`);
|
|
1317
|
+
const grants = installation.grants ?? {};
|
|
1318
|
+
const system = grants.system ?? [];
|
|
1319
|
+
let capabilities;
|
|
1320
|
+
let stdio;
|
|
1321
|
+
const port = new ComponentPort(timeout, async () => {
|
|
1322
|
+
const cleanup = [Promise.resolve().then(() => capabilities?.dispose())];
|
|
1323
|
+
if (stdio)
|
|
1324
|
+
for (const provider of new Set([stdio.stdin, stdio.stdout, stdio.stderr]))
|
|
1325
|
+
cleanup.push(Promise.resolve().then(() => provider?.close?.()));
|
|
1326
|
+
const settled = await Promise.allSettled(cleanup);
|
|
1327
|
+
release();
|
|
1328
|
+
const failed = settled.filter((result) => result.status === "rejected");
|
|
1329
|
+
if (failed.length)
|
|
1330
|
+
throw new AggregateError(failed.map((result) => result.reason), "Provider cleanup failed");
|
|
1331
|
+
}, fuel);
|
|
1332
|
+
try {
|
|
1333
|
+
capabilities = await BrowserCapabilities.open(grants, options.providers ?? {});
|
|
1334
|
+
if (system.includes("cli"))
|
|
1335
|
+
stdio = options.providers?.stdio?.(identity.name, installation.cli ?? {}) ?? {};
|
|
1336
|
+
const clocks = system.includes("clocks") ? checkedClocks(options.providers?.clocks ?? browserClocks()) : undefined;
|
|
1337
|
+
const random = system.includes("random") ? revisionRandom(options.providers?.random ?? browserRandom()) : undefined;
|
|
1338
|
+
const bound = (name) => {
|
|
1339
|
+
const entry = graph.imports.find((item) => item.contract === name);
|
|
1340
|
+
const binding = entry && prepared.bindings[entry.binding];
|
|
1341
|
+
return binding?.kind === "host" ? binding.provider : undefined;
|
|
1342
|
+
};
|
|
1343
|
+
const convert = converters(graph);
|
|
1344
|
+
const revision = new ComponentRevision(port, contract, graph, timeout, {
|
|
1345
|
+
orb: identity.name,
|
|
1346
|
+
...options.onLog ? { observer: options.onLog } : {}
|
|
1347
|
+
});
|
|
1348
|
+
const network = capabilities.network;
|
|
1349
|
+
const imports = publicWasi(record.imports, {
|
|
1350
|
+
clocks,
|
|
1351
|
+
random,
|
|
1352
|
+
...stdio ? { cli: { options: installation.cli ?? {}, stdio } } : {},
|
|
1353
|
+
mounts: () => capabilities?.mounts ?? [],
|
|
1354
|
+
host: port.wasi,
|
|
1355
|
+
http: network,
|
|
1356
|
+
ingress: (bridge) => revision.ingressBridge = bridge,
|
|
1357
|
+
sockets: {
|
|
1358
|
+
types: network.sockets(bound("wasi:sockets/types@0.3.0")),
|
|
1359
|
+
lookup: network.sockets(bound("wasi:sockets/ip-name-lookup@0.3.0"))
|
|
1360
|
+
}
|
|
1361
|
+
});
|
|
1362
|
+
for (const name of record.imports) {
|
|
1363
|
+
if (Object.hasOwn(imports, name))
|
|
1364
|
+
continue;
|
|
1365
|
+
const selected = graph.imports.find((item) => item.binding === name);
|
|
1366
|
+
const resourceGraph = graph;
|
|
1367
|
+
const resourceTypes = resourceGraph.types.flatMap(({ definition }) => definition.kind === "resource" && definition.owner === (selected?.contract ?? name) && definition.name ? [{ interface: definition.owner, name: definition.name }] : []);
|
|
1368
|
+
if (selected?.type_only) {
|
|
1369
|
+
imports[name] = resourceImport(port, name, [], resourceTypes);
|
|
1370
|
+
continue;
|
|
1371
|
+
}
|
|
1372
|
+
if (!selected)
|
|
1373
|
+
throw new Error(`Browser component execution cannot provide import ${name}`);
|
|
1374
|
+
const kind = prepared.bindings[name]?.kind;
|
|
1375
|
+
if (kind === "kernel" || kind === "hook") {
|
|
1376
|
+
imports[name] = revision.kernel.imports(name);
|
|
1377
|
+
continue;
|
|
1378
|
+
}
|
|
1379
|
+
const view = graph.references[name];
|
|
1380
|
+
imports[name] = view ? referenceImport(port, name, referenceView(graph, name, view, convert)) : resourceImport(port, name, Object.entries(selected.functions ?? {}).map(([method, fn]) => {
|
|
1381
|
+
const roles = resourceRoles(graph, selected.contract ?? name, {
|
|
1382
|
+
...fn,
|
|
1383
|
+
name: method
|
|
1384
|
+
});
|
|
1385
|
+
return {
|
|
1386
|
+
name: method,
|
|
1387
|
+
spelling: graph.javascriptNames[method],
|
|
1388
|
+
roles,
|
|
1389
|
+
values: convert(resourceDataFunction(fn, roles))
|
|
1390
|
+
};
|
|
1391
|
+
}), resourceTypes);
|
|
1392
|
+
}
|
|
1393
|
+
const limits = {
|
|
1394
|
+
fuel: new WebAssembly.Global({ value: "i64", mutable: true }, fuel),
|
|
1395
|
+
pages: new WebAssembly.Global({ value: "i64", mutable: true }, BigInt(maximumPages))
|
|
1396
|
+
};
|
|
1397
|
+
port.limits = limits;
|
|
1398
|
+
const instance = await instantiate(record, imports, port.observer, limits);
|
|
1399
|
+
if (!port.attached)
|
|
1400
|
+
throw new Error("The prepared component glue is not instrumented");
|
|
1401
|
+
port.exports = instance;
|
|
1402
|
+
const description = compiledDescription(graph, identity, {
|
|
1403
|
+
contributions: JSON.parse(contract.contributions()),
|
|
1404
|
+
hooks: JSON.parse(contract.hooks()),
|
|
1405
|
+
services: JSON.parse(contract.services())
|
|
1406
|
+
});
|
|
1407
|
+
return revision.definition(identity, prepared, description);
|
|
1408
|
+
} catch (error) {
|
|
1409
|
+
try {
|
|
1410
|
+
await port.close();
|
|
1411
|
+
} catch (disposal) {
|
|
1412
|
+
throw new AggregateError([error, disposal], "Component initialization and disposal failed");
|
|
1413
|
+
}
|
|
1414
|
+
throw error;
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
export {
|
|
1418
|
+
openComponent
|
|
1419
|
+
};
|