@webpodjs/sdk 0.1.3 → 0.2.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 +12 -0
- package/dist/agent/backend.d.ts +13 -0
- package/dist/agent/backend.js +63 -0
- package/dist/agent/backend.js.map +1 -1
- package/dist/agent/protocol.d.ts +104 -1
- package/dist/agent/protocol.js +90 -0
- package/dist/agent/protocol.js.map +1 -1
- package/dist/exec/client.d.ts +41 -0
- package/dist/exec/client.js +401 -0
- package/dist/exec/client.js.map +1 -0
- package/dist/exec/frame.d.ts +1 -0
- package/dist/exec/frame.js +236 -0
- package/dist/exec/frame.js.map +1 -0
- package/dist/exec/options.d.ts +39 -0
- package/dist/exec/options.js +113 -0
- package/dist/exec/options.js.map +1 -0
- package/dist/exec/protocol.d.ts +2 -0
- package/dist/exec/protocol.js +3 -0
- package/dist/exec/protocol.js.map +1 -0
- package/dist/exec/wire.d.ts +49 -0
- package/dist/exec/wire.js +333 -0
- package/dist/exec/wire.js.map +1 -0
- package/dist/exec-frame.html +10 -0
- package/dist/fs/workspace.js +32 -7
- package/dist/fs/workspace.js.map +1 -1
- package/dist/host/backend.d.ts +14 -2
- package/dist/host/backend.js +69 -15
- package/dist/host/backend.js.map +1 -1
- package/dist/host/controller.d.ts +9 -0
- package/dist/host/controller.js +13 -3
- package/dist/host/controller.js.map +1 -1
- package/dist/host/devices.d.ts +29 -0
- package/dist/host/devices.js +102 -4
- package/dist/host/devices.js.map +1 -1
- package/dist/host-exec/controller.d.ts +255 -0
- package/dist/host-exec/controller.js +1176 -0
- package/dist/host-exec/controller.js.map +1 -0
- package/dist/host-exec/pipe.d.ts +21 -0
- package/dist/host-exec/pipe.js +83 -0
- package/dist/host-exec/pipe.js.map +1 -0
- package/dist/host-exec/preflight.d.ts +6 -0
- package/dist/host-exec/preflight.js +15 -0
- package/dist/host-exec/preflight.js.map +1 -0
- package/dist/host-exec/protocol.d.ts +340 -0
- package/dist/host-exec/protocol.js +16 -0
- package/dist/host-exec/protocol.js.map +1 -0
- package/dist/host-exec/route.d.ts +22 -0
- package/dist/host-exec/route.js +37 -0
- package/dist/host-exec/route.js.map +1 -0
- package/dist/host-exec/shim.d.ts +28 -0
- package/dist/host-exec/shim.js +456 -0
- package/dist/host-exec/shim.js.map +1 -0
- package/dist/index.d.ts +7 -2
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/net/preview.d.ts +10 -2
- package/dist/net/preview.js +8 -0
- package/dist/net/preview.js.map +1 -1
- package/dist/pod.d.ts +22 -0
- package/dist/pod.js +129 -11
- package/dist/pod.js.map +1 -1
- package/dist/types.d.ts +35 -2
- package/dist/version.d.ts +1 -0
- package/dist/version.js +4 -0
- package/dist/version.js.map +1 -0
- package/package.json +6 -4
|
@@ -0,0 +1,1176 @@
|
|
|
1
|
+
import { WebPodError } from "../errors.js";
|
|
2
|
+
import { constrainedDevice } from "../features.js";
|
|
3
|
+
import { SIGNAL_NUMBERS } from "../types.js";
|
|
4
|
+
import { PipeWriter, createPipe } from "./pipe.js";
|
|
5
|
+
import { hostPreflight } from "./preflight.js";
|
|
6
|
+
import { PROTOCOL, SYNC_HEADER } from "./protocol.js";
|
|
7
|
+
import { routeTopLevel } from "./route.js";
|
|
8
|
+
import { ShimBridge, treeRoots } from "./shim.js";
|
|
9
|
+
const DEFAULT_EXEC_PATH = "/usr/local/bin/node";
|
|
10
|
+
const NPM = "/usr/local/lib/node_modules/npm/bin";
|
|
11
|
+
const DEFAULT_COMMANDS = { node: [], npm: [`${NPM}/npm-cli.js`], npx: [`${NPM}/npx-cli.js`] };
|
|
12
|
+
const DEFAULT_ENV = { PATH: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", HOME: "/root" };
|
|
13
|
+
const ENOBUFS = -105;
|
|
14
|
+
const ETIMEDOUT = -110;
|
|
15
|
+
const ENOENT = -2;
|
|
16
|
+
const EADDRINUSE = 98;
|
|
17
|
+
const ENOTSUP = 95;
|
|
18
|
+
const EXIT_FALLBACK = 70;
|
|
19
|
+
const BOOT_TIMEOUT_MS = 30000;
|
|
20
|
+
const te = new TextEncoder();
|
|
21
|
+
const signalName = (s) => (typeof s === "string" && s in SIGNAL_NUMBERS ? s : "SIGTERM");
|
|
22
|
+
/**
|
|
23
|
+
* The first pid of the processes the guest's kernel does not number (host children, pod.spawn's host processes; a
|
|
24
|
+
* top-level one of the node shim has the shim's): above every pid the guest can hand out, so that one never names
|
|
25
|
+
* the other (nodemon's `kill -USR2 <pid>` runs in the guest; the table here holds both). The guest's kernel
|
|
26
|
+
* (engines/qemu-wasm/guest, CONFIG_BASE_SMALL) has a pid_max of 4096 that sysctl can raise to 32768 at most
|
|
27
|
+
* (PID_MAX_LIMIT), and wraps around to 300. The agent's Hello names its pid_max (`pid-max=N`).
|
|
28
|
+
*/
|
|
29
|
+
const HOST_PID_BASE = 32768;
|
|
30
|
+
/** Where host pids start: HOST_PID_BASE, or above the guest's pid_max when its agent names a larger one. */
|
|
31
|
+
function hostPidBase(backend, log) {
|
|
32
|
+
const agent = backend.agent;
|
|
33
|
+
const max = Number(/(?:^|\s)pid-max=(\d+)(?:\s|$)/.exec(typeof agent === "string" ? agent : "")?.[1] ?? 0);
|
|
34
|
+
if (max <= HOST_PID_BASE)
|
|
35
|
+
return HOST_PID_BASE;
|
|
36
|
+
log("warn", `host-exec: the guest's pid_max is ${max}, above ${HOST_PID_BASE}: host pids start at ${max}`);
|
|
37
|
+
return max;
|
|
38
|
+
}
|
|
39
|
+
export class HostExecController {
|
|
40
|
+
#backend;
|
|
41
|
+
#sessions;
|
|
42
|
+
#o;
|
|
43
|
+
#listeners = new Set();
|
|
44
|
+
/** The pid counter host Workers share; none where there is no SharedArrayBuffer (host mode is unavailable there). */
|
|
45
|
+
#pids = typeof SharedArrayBuffer === "function" ? new SharedArrayBuffer(4) : null;
|
|
46
|
+
#table = new Map();
|
|
47
|
+
/** pids reaped or killed before their Worker was up. */
|
|
48
|
+
#gone = new Set();
|
|
49
|
+
#queue = [];
|
|
50
|
+
#warm = [];
|
|
51
|
+
#workers = new Set();
|
|
52
|
+
#max;
|
|
53
|
+
#status;
|
|
54
|
+
#enabled;
|
|
55
|
+
#live = 0;
|
|
56
|
+
#threads = 0;
|
|
57
|
+
#clients = 0;
|
|
58
|
+
/** The fallback tables' patterns host processes route their node children by (the image's, the learned one). */
|
|
59
|
+
#guestTable = [];
|
|
60
|
+
#listenReqs = 0;
|
|
61
|
+
/** Unix sockets of host processes (T99): listeners by key, connections by id with the two processes' Workers. */
|
|
62
|
+
#unixListeners = new Map();
|
|
63
|
+
#unixConns = new Map();
|
|
64
|
+
#unixIds = 0;
|
|
65
|
+
#tree;
|
|
66
|
+
/** The guest's node shim (agents with host-exec), when host mode is on. */
|
|
67
|
+
#shim = null;
|
|
68
|
+
/** Whether host processes can start (a Worker booted with its session): null until known. */
|
|
69
|
+
#hostOk = null;
|
|
70
|
+
/** Compiled wasm Modules the processes report (napi-wasm substitutes), handed to every Worker booted later. */
|
|
71
|
+
#wasmModules = {};
|
|
72
|
+
#disposed = false;
|
|
73
|
+
constructor(backend, options, status) {
|
|
74
|
+
this.#backend = backend;
|
|
75
|
+
this.#sessions = backend.hostSessions ?? null;
|
|
76
|
+
this.#o = options;
|
|
77
|
+
this.#status = status;
|
|
78
|
+
this.#enabled = status.node === "on";
|
|
79
|
+
this.#max = options.maxProcesses ?? (constrainedDevice() ? 6 : 8);
|
|
80
|
+
if (this.#pids)
|
|
81
|
+
Atomics.store(new Int32Array(this.#pids), 0, hostPidBase(backend, (level, text) => this.#log(level, text)));
|
|
82
|
+
}
|
|
83
|
+
/** Checks what host processes need; `status.node` tells the outcome. Never throws for a missing capability. */
|
|
84
|
+
static async create(backend, options = {}) {
|
|
85
|
+
const off = (node, reason) => new HostExecController(backend, options, { node, ...(reason ? { reason } : {}), runners: [] });
|
|
86
|
+
if (options.node !== true)
|
|
87
|
+
return off("off");
|
|
88
|
+
if (!options.workerUrl)
|
|
89
|
+
throw new WebPodError("EINVAL", "hostExec.node needs hostExec.workerUrl (@webpodjs/host-exec's dist/worker.js)");
|
|
90
|
+
if (!backend.hostSessions)
|
|
91
|
+
return off("unavailable", "no shared workspace (needs an engine with an FS Worker and a workspace)");
|
|
92
|
+
const local = backend.hostSessions.localPaths ?? [];
|
|
93
|
+
if (local.length > 0)
|
|
94
|
+
return off("unavailable", `the workspace keeps ${local.join(", ")} on the guest's data disk (fsWorker workspace.localPaths: [] for hostExec)`);
|
|
95
|
+
const reason = await (options.preflight ?? hostPreflight)();
|
|
96
|
+
if (reason)
|
|
97
|
+
return off("unavailable", reason);
|
|
98
|
+
const c = new HostExecController(backend, options, { node: "on", runners: ["node"] });
|
|
99
|
+
if (!backend.hostSessions.shares?.length)
|
|
100
|
+
c.#log("info", "host-exec: the image declares no host shares (webpod-home, webpod-tmp): $HOME and /tmp are read-only to host processes");
|
|
101
|
+
await c._reloadTables();
|
|
102
|
+
c.#fill();
|
|
103
|
+
if (backend.hostMode) {
|
|
104
|
+
c.#shim = new ShimBridge(c, backend.hostMode);
|
|
105
|
+
// Until a Worker has booted with its session (the workspace may be another tab's), the shim runs guest node.
|
|
106
|
+
const first = c.#warm[0] ?? c.#sessions.open("probe", c._identity()).then((s) => s.close());
|
|
107
|
+
void Promise.resolve(first).then(() => c.#setHostOk(true), (e) => {
|
|
108
|
+
c.#log("warn", `host-exec: the guest's node shim runs regular node: ${e.message}`);
|
|
109
|
+
c.#setHostOk(false);
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
return c;
|
|
113
|
+
}
|
|
114
|
+
#setHostOk(ok) {
|
|
115
|
+
if (this.#hostOk === ok)
|
|
116
|
+
return;
|
|
117
|
+
this.#hostOk = ok;
|
|
118
|
+
void this.#announce();
|
|
119
|
+
}
|
|
120
|
+
/** HostExecInfo for the guest's node shim: node while host processes can start, the paths they see. */
|
|
121
|
+
async #announce() {
|
|
122
|
+
const shim = this.#shim;
|
|
123
|
+
if (!shim)
|
|
124
|
+
return;
|
|
125
|
+
const node = this.#enabled && !this.#disposed && this.#hostOk === true;
|
|
126
|
+
const tree = node ? await this.#loadTree().catch(() => undefined) : undefined;
|
|
127
|
+
const s = this.#sessions;
|
|
128
|
+
shim.update({ runners: node && this.#enabled ? ["node"] : [], mounts: [s.workspace, ...this._sharePrefixes(), ...treeRoots(tree, this.#execPath)], excludes: (s.localPaths ?? []).map((p) => `${s.workspace}/${p}`) });
|
|
129
|
+
}
|
|
130
|
+
/** What routeTopLevel needs, to tell where a request runs without starting it (an execution origin's app side). */
|
|
131
|
+
get routeContext() {
|
|
132
|
+
return this.#sessions ? { execPath: this.#execPath, commands: this.#o.commands ?? DEFAULT_COMMANDS, workspace: this.#sessions.workspace, shares: this._sharePrefixes() } : null;
|
|
133
|
+
}
|
|
134
|
+
get status() {
|
|
135
|
+
return { ...this.#status, runners: [...this.#status.runners] };
|
|
136
|
+
}
|
|
137
|
+
get enabled() {
|
|
138
|
+
return this.#enabled;
|
|
139
|
+
}
|
|
140
|
+
set enabled(on) {
|
|
141
|
+
on = on === true && this.#status.node === "on";
|
|
142
|
+
if (on === this.#enabled)
|
|
143
|
+
return;
|
|
144
|
+
this.#enabled = on;
|
|
145
|
+
void this.#announce();
|
|
146
|
+
if (on)
|
|
147
|
+
this.#fill();
|
|
148
|
+
else
|
|
149
|
+
for (const p of this.#warm.splice(0))
|
|
150
|
+
void p.then((w) => this.#retire(w), () => { });
|
|
151
|
+
}
|
|
152
|
+
on(event, listener) {
|
|
153
|
+
if (event !== "fallback")
|
|
154
|
+
throw new WebPodError("EINVAL", `unknown hostExec event: ${String(event)}`);
|
|
155
|
+
this.#listeners.add(listener);
|
|
156
|
+
return () => this.#listeners.delete(listener);
|
|
157
|
+
}
|
|
158
|
+
/** Starts `req` as a host process, or returns null: it runs in the guest. */
|
|
159
|
+
spawn(req) {
|
|
160
|
+
if (!this.#enabled || this.#disposed || !this.#sessions)
|
|
161
|
+
return null;
|
|
162
|
+
const route = routeTopLevel(req, { execPath: this.#execPath, commands: this.#o.commands ?? DEFAULT_COMMANDS, workspace: this.#sessions.workspace, shares: this._sharePrefixes() });
|
|
163
|
+
if (!route)
|
|
164
|
+
return null;
|
|
165
|
+
if (route.runner === "guest") {
|
|
166
|
+
this.#emit({ pid: null, argv: [req.command, ...req.args], reason: route.reason, rerun: false });
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
return new HostProcess(this, req, route.argv, route.cwd);
|
|
170
|
+
}
|
|
171
|
+
async dispose() {
|
|
172
|
+
if (this.#disposed)
|
|
173
|
+
return;
|
|
174
|
+
this.#disposed = true;
|
|
175
|
+
this.#enabled = false;
|
|
176
|
+
await this.#announce();
|
|
177
|
+
this.#shim?.close();
|
|
178
|
+
for (const q of this.#queue.splice(0))
|
|
179
|
+
q();
|
|
180
|
+
const warm = this.#warm.splice(0);
|
|
181
|
+
for (const e of [...this.#table.values()])
|
|
182
|
+
e.kill("SIGKILL");
|
|
183
|
+
for (const w of [...this.#workers])
|
|
184
|
+
this.#retire(w);
|
|
185
|
+
await Promise.allSettled(warm.map((p) => p.then((w) => this.#retire(w))));
|
|
186
|
+
}
|
|
187
|
+
get #execPath() {
|
|
188
|
+
return this.#o.execPath ?? DEFAULT_EXEC_PATH;
|
|
189
|
+
}
|
|
190
|
+
// --- internals shared with HostProcess ---
|
|
191
|
+
/**
|
|
192
|
+
* @internal Reads the fallback tables of the guest ({ "guest": [pattern] }: the image's /etc/webpod/host-exec.json and
|
|
193
|
+
* the learned $HOME/.cache/webpod/host-exec-fallback.json), which host processes apply to the node processes they
|
|
194
|
+
* start, as the shim does to the guest's (the project's table, in the workspace, they read themselves).
|
|
195
|
+
*/
|
|
196
|
+
async _reloadTables() {
|
|
197
|
+
const home = this.#o.env?.HOME ?? DEFAULT_ENV.HOME;
|
|
198
|
+
const files = ["/etc/webpod/host-exec.json", `${home}/.cache/webpod/host-exec-fallback.json`];
|
|
199
|
+
const all = new Set();
|
|
200
|
+
for (const f of files) {
|
|
201
|
+
try {
|
|
202
|
+
const t = JSON.parse(await this.#backend.fs.readFile(f, "utf8"));
|
|
203
|
+
if (Array.isArray(t.guest))
|
|
204
|
+
for (const g of t.guest)
|
|
205
|
+
if (typeof g === "string")
|
|
206
|
+
all.add(g);
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
// no table there
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
this.#guestTable = [...all];
|
|
213
|
+
}
|
|
214
|
+
/** @internal */
|
|
215
|
+
_guestTable() {
|
|
216
|
+
return this.#guestTable;
|
|
217
|
+
}
|
|
218
|
+
/** @internal */
|
|
219
|
+
_emit(e) {
|
|
220
|
+
this.#emit(e);
|
|
221
|
+
}
|
|
222
|
+
/** @internal */
|
|
223
|
+
_backend() {
|
|
224
|
+
return this.#backend;
|
|
225
|
+
}
|
|
226
|
+
/** @internal */
|
|
227
|
+
_options() {
|
|
228
|
+
return this.#o;
|
|
229
|
+
}
|
|
230
|
+
/** @internal The next pid (the Workers take theirs from the same counter). */
|
|
231
|
+
_pid() {
|
|
232
|
+
return Atomics.add(new Int32Array(this.#pids), 0, 1);
|
|
233
|
+
}
|
|
234
|
+
/** @internal Waits for a process slot (`maxProcesses`); `force` takes one anyway (spawnSync: the parent is blocked). */
|
|
235
|
+
_acquire(force = false) {
|
|
236
|
+
if (this.#disposed)
|
|
237
|
+
return Promise.reject(new WebPodError("DISPOSED", "pod has been disposed"));
|
|
238
|
+
if (force || this.#live < this.#max) {
|
|
239
|
+
this.#live++;
|
|
240
|
+
return Promise.resolve();
|
|
241
|
+
}
|
|
242
|
+
return new Promise((resolve, reject) => this.#queue.push(() => {
|
|
243
|
+
if (this.#disposed)
|
|
244
|
+
return reject(new WebPodError("DISPOSED", "pod has been disposed"));
|
|
245
|
+
this.#live++;
|
|
246
|
+
resolve();
|
|
247
|
+
}));
|
|
248
|
+
}
|
|
249
|
+
/** @internal */
|
|
250
|
+
_release() {
|
|
251
|
+
this.#live--;
|
|
252
|
+
if (this.#live < this.#max)
|
|
253
|
+
this.#queue.shift()?.();
|
|
254
|
+
}
|
|
255
|
+
/** @internal The identity of pooled Workers' sessions. */
|
|
256
|
+
_identity() {
|
|
257
|
+
return { uid: this.#o.uid ?? 0, gid: this.#o.gid ?? 0 };
|
|
258
|
+
}
|
|
259
|
+
/** @internal Whether processes start on the host now (enabled, not disposed). */
|
|
260
|
+
_on() {
|
|
261
|
+
return this.#enabled && !this.#disposed;
|
|
262
|
+
}
|
|
263
|
+
/** @internal Where the other shares are mounted in host processes (and in the guest). */
|
|
264
|
+
_sharePrefixes() {
|
|
265
|
+
return (this.#sessions?.shares ?? []).map((s) => s.prefix);
|
|
266
|
+
}
|
|
267
|
+
/** @internal */
|
|
268
|
+
_execPath() {
|
|
269
|
+
return this.#execPath;
|
|
270
|
+
}
|
|
271
|
+
/** @internal The read-only tree, if any. */
|
|
272
|
+
_tree() {
|
|
273
|
+
return this.#loadTree();
|
|
274
|
+
}
|
|
275
|
+
/** @internal */
|
|
276
|
+
_log(level, text) {
|
|
277
|
+
this.#log(level, text);
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* @internal A booted Worker: from the pool, else a new one; one of its own for another identity than the pool's
|
|
281
|
+
* (supplementary groups count, except for root, whom the FS Worker does not check).
|
|
282
|
+
*/
|
|
283
|
+
async _worker(identity) {
|
|
284
|
+
const own = this._identity();
|
|
285
|
+
const same = (i) => i.uid === own.uid && i.gid === own.gid && (i.uid === 0 || (i.groups ?? []).every((g) => g === i.gid));
|
|
286
|
+
if (identity && !same(identity))
|
|
287
|
+
return this.#boot(identity);
|
|
288
|
+
// A few from the pool, then a new one whose failure is the caller's: when every boot fails (the FS Worker cannot
|
|
289
|
+
// open a session), taking the next pooled one and refilling would go on for ever and freeze the page.
|
|
290
|
+
for (let tries = 0; tries < 3 && this.#warm.length > 0; tries++) {
|
|
291
|
+
const p = this.#warm.shift();
|
|
292
|
+
this.#fill();
|
|
293
|
+
try {
|
|
294
|
+
const w = await p;
|
|
295
|
+
if (!w.dead)
|
|
296
|
+
return w; // its session failed while it waited
|
|
297
|
+
}
|
|
298
|
+
catch (e) {
|
|
299
|
+
this.#log("warn", `host-exec: pooled Worker failed: ${e.message}`);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return this.#boot();
|
|
303
|
+
}
|
|
304
|
+
/** @internal */
|
|
305
|
+
_register(e) {
|
|
306
|
+
this.#table.set(e.pid, e);
|
|
307
|
+
}
|
|
308
|
+
/** @internal */
|
|
309
|
+
_unregister(pid) {
|
|
310
|
+
this.#table.delete(pid);
|
|
311
|
+
}
|
|
312
|
+
/** @internal Kills the processes below `pid` (its own exit or kill ends the tree, as a process group). */
|
|
313
|
+
_killChildren(pid, signal) {
|
|
314
|
+
for (const e of [...this.#table.values()]) {
|
|
315
|
+
if (e.ppid !== pid)
|
|
316
|
+
continue;
|
|
317
|
+
this._killChildren(e.pid, signal);
|
|
318
|
+
e.kill(signal);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
/** @internal Terminates a Worker and ends its session. */
|
|
322
|
+
_retire(w) {
|
|
323
|
+
this.#retire(w);
|
|
324
|
+
}
|
|
325
|
+
#retire(w) {
|
|
326
|
+
if (w.dead)
|
|
327
|
+
return;
|
|
328
|
+
w.dead = true;
|
|
329
|
+
w.abort?.();
|
|
330
|
+
this.#workers.delete(w);
|
|
331
|
+
w.w.terminate();
|
|
332
|
+
w.session.close();
|
|
333
|
+
for (const s of w.shares)
|
|
334
|
+
s.close();
|
|
335
|
+
if (w.netId)
|
|
336
|
+
this.#backend.hostNet?.close(w.netId);
|
|
337
|
+
for (const l of w.listens?.values() ?? [])
|
|
338
|
+
if (l.guest !== null)
|
|
339
|
+
this.#backend.hostListen?.unlisten(l.guest);
|
|
340
|
+
w.listens?.clear();
|
|
341
|
+
this.#unixGone(w);
|
|
342
|
+
for (const t of w.threads?.values() ?? [])
|
|
343
|
+
this.#retire(t);
|
|
344
|
+
w.threads?.clear();
|
|
345
|
+
w.onRetire?.();
|
|
346
|
+
}
|
|
347
|
+
#fill() {
|
|
348
|
+
const pool = this.#o.pool ?? 1;
|
|
349
|
+
while (this.#enabled && !this.#disposed && this.#warm.length < pool) {
|
|
350
|
+
const p = this.#boot();
|
|
351
|
+
p.catch(() => { });
|
|
352
|
+
this.#warm.push(p);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
async #boot(identity = this._identity(), thread) {
|
|
356
|
+
const sessions = this.#sessions;
|
|
357
|
+
const client = `h${++this.#clients}`;
|
|
358
|
+
const opened = [sessions.open(client, identity), ...(sessions.shares ?? []).map((s) => s.open(client, identity))];
|
|
359
|
+
let all;
|
|
360
|
+
let tree;
|
|
361
|
+
let sources;
|
|
362
|
+
try {
|
|
363
|
+
[all, tree, sources] = await Promise.all([Promise.all(opened), this.#loadTree(), this.#loadSources()]);
|
|
364
|
+
}
|
|
365
|
+
catch (e) {
|
|
366
|
+
for (const p of opened)
|
|
367
|
+
void p.then((s) => s.close(), () => { });
|
|
368
|
+
throw e;
|
|
369
|
+
}
|
|
370
|
+
const [session, ...shareSessions] = all;
|
|
371
|
+
if (this.#disposed) {
|
|
372
|
+
for (const s of all)
|
|
373
|
+
s.close();
|
|
374
|
+
throw new WebPodError("DISPOSED", "pod has been disposed");
|
|
375
|
+
}
|
|
376
|
+
const url = this.#o.workerUrl;
|
|
377
|
+
const w = (this.#o.createWorker ?? ((u) => new Worker(u)))(url);
|
|
378
|
+
const rec = { w, session, shares: shareSessions, identity, ctl: new SharedArrayBuffer(SYNC_HEADER + (this.#o.syncBufferBytes ?? 16 << 20)), dead: false };
|
|
379
|
+
// One of its 9P sessions failed in the FS Worker: the process ends (exit 70), the Worker is retired.
|
|
380
|
+
for (const s of all)
|
|
381
|
+
s.onerror = (message) => {
|
|
382
|
+
this.#log("warn", `host-exec: session ${s.client} failed: ${message}`);
|
|
383
|
+
if (rec.report)
|
|
384
|
+
rec.report({ type: "error", message: `its file system session failed: ${message}` });
|
|
385
|
+
else
|
|
386
|
+
this.#retire(rec);
|
|
387
|
+
};
|
|
388
|
+
this.#workers.add(rec);
|
|
389
|
+
const booted = new Promise((resolve, reject) => {
|
|
390
|
+
const timer = setTimeout(() => reject(new Error("no reply to boot")), BOOT_TIMEOUT_MS);
|
|
391
|
+
const settle = () => {
|
|
392
|
+
clearTimeout(timer);
|
|
393
|
+
rec.report = rec.abort = undefined;
|
|
394
|
+
};
|
|
395
|
+
rec.abort = () => {
|
|
396
|
+
settle();
|
|
397
|
+
reject(new Error("terminated while booting"));
|
|
398
|
+
};
|
|
399
|
+
rec.report = (m) => {
|
|
400
|
+
if (m.type === "booted") {
|
|
401
|
+
settle();
|
|
402
|
+
resolve();
|
|
403
|
+
}
|
|
404
|
+
else if (m.type === "error") {
|
|
405
|
+
settle();
|
|
406
|
+
reject(new Error(m.message));
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
});
|
|
410
|
+
w.onmessage = ({ data }) => this.#onWorker(rec, data);
|
|
411
|
+
w.onerror = (e) => rec.report?.({ type: "error", message: e.message ?? "worker error" });
|
|
412
|
+
const mount = (prefix, s) => {
|
|
413
|
+
const { memory, req, rep, gen, eventSeq, quiet, append } = s;
|
|
414
|
+
return { prefix, session: { memory, req, rep, ...(gen !== undefined ? { gen } : {}), ...(eventSeq !== undefined ? { eventSeq } : {}), ...(quiet !== undefined ? { quiet } : {}), ...(append ? { append } : {}) }, ...(s.events ? { events: s.events } : {}) };
|
|
415
|
+
};
|
|
416
|
+
let net;
|
|
417
|
+
if (this.#backend.hostNet) {
|
|
418
|
+
const ch = new MessageChannel();
|
|
419
|
+
this.#backend.hostNet.open(client, ch.port1);
|
|
420
|
+
rec.netId = client;
|
|
421
|
+
net = ch.port2;
|
|
422
|
+
}
|
|
423
|
+
w.postMessage({
|
|
424
|
+
type: "boot",
|
|
425
|
+
protocol: PROTOCOL,
|
|
426
|
+
mounts: [mount(sessions.workspace, session), ...shareSessions.map((s, i) => mount(sessions.shares[i].prefix, s))],
|
|
427
|
+
wasmModules: { ...this.#wasmModules },
|
|
428
|
+
ctl: rec.ctl,
|
|
429
|
+
pids: this.#pids,
|
|
430
|
+
...(tree ? { tree } : {}),
|
|
431
|
+
...(sources ? { sources } : {}),
|
|
432
|
+
...(net ? { net } : {}),
|
|
433
|
+
...(this.#o.workerOptions ? { options: this.#o.workerOptions } : {}),
|
|
434
|
+
...(thread ? { thread } : {}),
|
|
435
|
+
}, [...(net ? [net] : []), ...all.flatMap((s) => (s.events ? [s.events] : []))]);
|
|
436
|
+
try {
|
|
437
|
+
await booted;
|
|
438
|
+
}
|
|
439
|
+
catch (e) {
|
|
440
|
+
this.#retire(rec);
|
|
441
|
+
throw new WebPodError("ENGINE_UNAVAILABLE", `host-exec Worker ${url}: ${e.message}`);
|
|
442
|
+
}
|
|
443
|
+
if (this.#shim)
|
|
444
|
+
this.#setHostOk(true);
|
|
445
|
+
return rec;
|
|
446
|
+
}
|
|
447
|
+
#loadTree() {
|
|
448
|
+
const t = this.#o.tree;
|
|
449
|
+
if (t !== undefined && typeof t !== "string")
|
|
450
|
+
return Promise.resolve(t);
|
|
451
|
+
if (t === undefined) {
|
|
452
|
+
// The default: tree.bin next to the Worker, if there is one.
|
|
453
|
+
let url;
|
|
454
|
+
try {
|
|
455
|
+
url = new URL("tree.bin", new URL(this.#o.workerUrl, globalThis.location?.href)).href;
|
|
456
|
+
}
|
|
457
|
+
catch {
|
|
458
|
+
return Promise.resolve(undefined);
|
|
459
|
+
}
|
|
460
|
+
this.#tree ??= fetchShared(url, "tree").catch((e) => {
|
|
461
|
+
this.#log("warn", `host-exec: no npm tree (${e.message}): npm and npx need one on the host (hostExec.tree)`);
|
|
462
|
+
return undefined;
|
|
463
|
+
});
|
|
464
|
+
return this.#tree;
|
|
465
|
+
}
|
|
466
|
+
this.#tree ??= fetchShared(t, "tree");
|
|
467
|
+
return this.#tree;
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* node-lib.json once for every Worker of the page (indexed: indexSources); when the default one fails, each Worker
|
|
471
|
+
* fetches its own.
|
|
472
|
+
*/
|
|
473
|
+
#loadSources() {
|
|
474
|
+
const s = this.#o.sources;
|
|
475
|
+
if (s === false)
|
|
476
|
+
return Promise.resolve(undefined);
|
|
477
|
+
let url;
|
|
478
|
+
try {
|
|
479
|
+
url = s ?? new URL("node-lib.json", new URL(this.#o.workerUrl, globalThis.location?.href)).href;
|
|
480
|
+
}
|
|
481
|
+
catch {
|
|
482
|
+
return Promise.resolve(undefined);
|
|
483
|
+
}
|
|
484
|
+
// Every pod of the page shares one copy.
|
|
485
|
+
let p = SOURCES.get(url);
|
|
486
|
+
if (!p) {
|
|
487
|
+
p = fetchShared(url, "sources").then(indexSources);
|
|
488
|
+
SOURCES.set(url, p);
|
|
489
|
+
p.catch(() => SOURCES.delete(url));
|
|
490
|
+
}
|
|
491
|
+
if (s !== undefined)
|
|
492
|
+
return p;
|
|
493
|
+
return p.catch((e) => {
|
|
494
|
+
this.#log("warn", `host-exec: ${e.message}; each Worker loads its own`);
|
|
495
|
+
return undefined;
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
#onWorker(rec, m) {
|
|
499
|
+
switch (m.type) {
|
|
500
|
+
case "spawn":
|
|
501
|
+
return void this.#child(m, m.port, rec).catch((e) => this.#log("warn", `host-exec: spawn ${m.argv.join(" ")}: ${e.message}`));
|
|
502
|
+
case "spawnSync":
|
|
503
|
+
return this.#spawnSync(m, rec);
|
|
504
|
+
case "reap":
|
|
505
|
+
case "kill": {
|
|
506
|
+
const e = this.#table.get(m.pid);
|
|
507
|
+
if (e)
|
|
508
|
+
e.kill(signalName(m.type === "kill" ? m.signal : "SIGKILL"));
|
|
509
|
+
// A kill can overtake the child's start; a reap comes after its exit.
|
|
510
|
+
else if (m.type === "kill")
|
|
511
|
+
this.#gone.add(m.pid);
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
case "wasm-module":
|
|
515
|
+
this.#wasmModules[m.key] = m.module;
|
|
516
|
+
return;
|
|
517
|
+
case "trace":
|
|
518
|
+
// WEBPOD_HOST_DIAG's traces are for someone looking into a stuck process: shown as warnings.
|
|
519
|
+
return this.#log(m.text.startsWith("diag ") ? "warn" : "debug", `host-exec [${m.pid}] ${m.text}`);
|
|
520
|
+
case "listen":
|
|
521
|
+
return void this.#listen(rec, m).then((r) => writeCtl(rec.ctl, r), (e) => {
|
|
522
|
+
this.#log("warn", `host-exec: listen ${m.address}:${m.port}: ${e.message}`);
|
|
523
|
+
writeCtl(rec.ctl, { error: -ENOTSUP });
|
|
524
|
+
});
|
|
525
|
+
case "unlisten":
|
|
526
|
+
return this.#unlisten(rec, m.req);
|
|
527
|
+
case "unix-listen":
|
|
528
|
+
return writeCtl(rec.ctl, this.#unixListen(rec, m.key));
|
|
529
|
+
case "unix-unlisten":
|
|
530
|
+
for (const [key, l] of this.#unixListeners)
|
|
531
|
+
if (l.rec === rec && l.req === m.req)
|
|
532
|
+
this.#unixListeners.delete(key);
|
|
533
|
+
return;
|
|
534
|
+
case "unix-connect":
|
|
535
|
+
return this.#unixConnect(rec, m.id, m.key);
|
|
536
|
+
case "unix-close":
|
|
537
|
+
this.#unixConns.delete(m.cid);
|
|
538
|
+
return;
|
|
539
|
+
case "thread":
|
|
540
|
+
return void this.#thread(rec, m).catch((e) => this.#log("warn", `host-exec: thread ${m.tid} of ${rec.pid}: ${e.message}`));
|
|
541
|
+
case "thread-end": {
|
|
542
|
+
const t = rec.threads?.get(m.tid);
|
|
543
|
+
rec.threads?.delete(m.tid);
|
|
544
|
+
if (t)
|
|
545
|
+
this.#retire(t);
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
default:
|
|
549
|
+
rec.report?.(m);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* A process listens: the net Worker takes the page's connections to the port, the agent holds it in the guest
|
|
554
|
+
* (and forwards the guest's). A fixed port is registered on the net Worker first, so the guest's first
|
|
555
|
+
* connection is not reset; port 0 needs the guest's pick first.
|
|
556
|
+
*/
|
|
557
|
+
async #listen(rec, m) {
|
|
558
|
+
const net = this.#backend.hostNet;
|
|
559
|
+
if (!net?.listen || !net.unlisten || !rec.netId)
|
|
560
|
+
return { error: -ENOTSUP };
|
|
561
|
+
const id = rec.netId;
|
|
562
|
+
const guest = this.#backend.hostListen ?? null;
|
|
563
|
+
const onNet = async (port) => {
|
|
564
|
+
try {
|
|
565
|
+
return await net.listen(id, port);
|
|
566
|
+
}
|
|
567
|
+
catch {
|
|
568
|
+
return null;
|
|
569
|
+
}
|
|
570
|
+
};
|
|
571
|
+
let port;
|
|
572
|
+
let held = null;
|
|
573
|
+
if (m.port === 0 && guest) {
|
|
574
|
+
const g = await guest.listen(m.address, 0, m.uid);
|
|
575
|
+
if ("errno" in g)
|
|
576
|
+
return { error: -g.errno };
|
|
577
|
+
held = g.req;
|
|
578
|
+
port = await onNet(g.port);
|
|
579
|
+
if (port === null) {
|
|
580
|
+
guest.unlisten(g.req);
|
|
581
|
+
return { error: -EADDRINUSE };
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
else {
|
|
585
|
+
port = await onNet(m.port);
|
|
586
|
+
if (port === null)
|
|
587
|
+
return { error: -EADDRINUSE };
|
|
588
|
+
if (guest) {
|
|
589
|
+
const g = await guest.listen(m.address, port, m.uid).catch((e) => {
|
|
590
|
+
net.unlisten(id, port);
|
|
591
|
+
throw e;
|
|
592
|
+
});
|
|
593
|
+
if ("errno" in g) {
|
|
594
|
+
net.unlisten(id, port);
|
|
595
|
+
return { error: -g.errno };
|
|
596
|
+
}
|
|
597
|
+
held = g.req;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
if (rec.dead) {
|
|
601
|
+
if (held !== null)
|
|
602
|
+
guest?.unlisten(held);
|
|
603
|
+
return { error: -ENOTSUP };
|
|
604
|
+
}
|
|
605
|
+
const req = ++this.#listenReqs;
|
|
606
|
+
(rec.listens ??= new Map()).set(req, { port, guest: held });
|
|
607
|
+
return { port, req };
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* A process listens on a unix socket: connections to key go to it from now on (as a socket file bound again after
|
|
611
|
+
* the last one's was removed, the newest listener has the path).
|
|
612
|
+
*/
|
|
613
|
+
#unixListen(rec, key) {
|
|
614
|
+
if (rec.dead)
|
|
615
|
+
return { error: -ENOTSUP };
|
|
616
|
+
const req = ++this.#unixIds;
|
|
617
|
+
this.#unixListeners.set(key, { rec, req });
|
|
618
|
+
return { req };
|
|
619
|
+
}
|
|
620
|
+
/** A connection between two host processes: a MessageChannel, one end to each of their Workers. */
|
|
621
|
+
#unixConnect(rec, id, key) {
|
|
622
|
+
const l = this.#unixListeners.get(key);
|
|
623
|
+
const post = (to, m) => to.w.postMessage(m, "port" in m ? [m.port] : []);
|
|
624
|
+
if (!l || l.rec.dead)
|
|
625
|
+
return post(rec, { type: "unix-connected", id, error: "ECONNREFUSED" });
|
|
626
|
+
const cid = ++this.#unixIds;
|
|
627
|
+
const { port1, port2 } = new MessageChannel();
|
|
628
|
+
this.#unixConns.set(cid, [rec, l.rec]);
|
|
629
|
+
post(l.rec, { type: "unix-accept", req: l.req, cid, port: port1 });
|
|
630
|
+
post(rec, { type: "unix-connected", id, cid, port: port2 });
|
|
631
|
+
}
|
|
632
|
+
/** A process's Worker is gone: its listeners with it, the other ends of its connections are told. */
|
|
633
|
+
#unixGone(w) {
|
|
634
|
+
for (const [key, l] of this.#unixListeners)
|
|
635
|
+
if (l.rec === w)
|
|
636
|
+
this.#unixListeners.delete(key);
|
|
637
|
+
for (const [cid, ends] of this.#unixConns) {
|
|
638
|
+
if (!ends.includes(w))
|
|
639
|
+
continue;
|
|
640
|
+
this.#unixConns.delete(cid);
|
|
641
|
+
const other = ends[0] === w ? ends[1] : ends[0];
|
|
642
|
+
if (!other.dead)
|
|
643
|
+
other.w.postMessage({ type: "unix-gone", cid });
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
#unlisten(rec, req) {
|
|
647
|
+
const l = rec.listens?.get(req);
|
|
648
|
+
if (!l)
|
|
649
|
+
return;
|
|
650
|
+
rec.listens.delete(req);
|
|
651
|
+
if (rec.netId)
|
|
652
|
+
this.#backend.hostNet?.unlisten?.(rec.netId, l.port);
|
|
653
|
+
if (l.guest !== null)
|
|
654
|
+
this.#backend.hostListen?.unlisten(l.guest);
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* A worker_threads thread of `parent`'s process: a Worker booted as a thread, with the process's pid and its own
|
|
658
|
+
* sessions; it ends with the process (#retire). Threads do not count against maxProcesses.
|
|
659
|
+
*/
|
|
660
|
+
async #thread(parent, m) {
|
|
661
|
+
// As node reports a thread that could not start: 'error' (ERR_WORKER_INIT_FAILED), then 'exit' 1.
|
|
662
|
+
const refuse = (reason) => m.port.postMessage({ type: "exit", code: 1, error: "ERR_WORKER_INIT_FAILED", reason });
|
|
663
|
+
const max = this.#o.maxThreads ?? 2 * this.#max;
|
|
664
|
+
if (this.#threads >= max)
|
|
665
|
+
return refuse(`host mode runs at most ${max} worker threads at once (hostExec.maxThreads)`);
|
|
666
|
+
this.#threads++;
|
|
667
|
+
let w;
|
|
668
|
+
try {
|
|
669
|
+
w = await this.#boot(parent.identity, { tid: m.tid, name: m.name });
|
|
670
|
+
}
|
|
671
|
+
catch (e) {
|
|
672
|
+
this.#threads--;
|
|
673
|
+
refuse(`the thread's Worker did not start: ${e.message}`);
|
|
674
|
+
throw e;
|
|
675
|
+
}
|
|
676
|
+
w.onRetire = () => this.#threads--;
|
|
677
|
+
if (parent.dead)
|
|
678
|
+
return this.#retire(w);
|
|
679
|
+
(parent.threads ??= new Map()).set(m.tid, w);
|
|
680
|
+
w.pid = parent.pid;
|
|
681
|
+
w.ppid = parent.ppid;
|
|
682
|
+
w.report = (r) => {
|
|
683
|
+
if (r.type === "error") {
|
|
684
|
+
this.#log("warn", `host-exec: thread ${m.tid} of ${parent.pid} failed: ${r.message}`);
|
|
685
|
+
parent.threads?.delete(m.tid);
|
|
686
|
+
this.#retire(w);
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
const o = this.#o;
|
|
690
|
+
const thread = { envPort: m.envPort, envBoxes: m.envBoxes, initial: m.initial ?? [], threadIds: m.threadIds, bcPrefix: m.bcPrefix, ...(m.shareEnv ? { shareEnv: m.shareEnv } : {}) };
|
|
691
|
+
w.w.postMessage({ type: "start", argv: [this.#execPath, ...m.execArgv], env: m.env ?? {}, cwd: m.cwd, pid: parent.pid ?? 0, ppid: parent.ppid ?? 1, uid: parent.identity?.uid ?? o.uid ?? 0, gid: parent.identity?.gid ?? o.gid ?? 0, stdin: null, port: m.port, thread }, [m.port, m.envPort, ...(m.initialTransfer ?? [])]);
|
|
692
|
+
}
|
|
693
|
+
/** A child of a host process; `port` is its owner's end. Resolves once it is started. */
|
|
694
|
+
async #child(spec, port, parent, force = false) {
|
|
695
|
+
if (spec.runner === "guest")
|
|
696
|
+
return this.#guestChild(spec, port);
|
|
697
|
+
await this._acquire(force);
|
|
698
|
+
let w;
|
|
699
|
+
try {
|
|
700
|
+
w = await this._worker();
|
|
701
|
+
}
|
|
702
|
+
catch (e) {
|
|
703
|
+
this._release();
|
|
704
|
+
port.postMessage({ type: "out", fd: 2, data: te.encode(`webpod: cannot start ${spec.argv[0]}: ${e.message}\n`) });
|
|
705
|
+
port.postMessage({ type: "exit", code: 127, signal: null });
|
|
706
|
+
throw e;
|
|
707
|
+
}
|
|
708
|
+
let done = false;
|
|
709
|
+
const end = () => {
|
|
710
|
+
if (done)
|
|
711
|
+
return;
|
|
712
|
+
done = true;
|
|
713
|
+
// Its children end with it: an orphan has nobody to reap it or take its output (its owner was this Worker), and
|
|
714
|
+
// one waiting for its stdin (esbuild's service) would hold its slot for good (e4-integration.md §3.3).
|
|
715
|
+
this._killChildren(spec.pid, "SIGKILL");
|
|
716
|
+
this._unregister(spec.pid);
|
|
717
|
+
this.#retire(w);
|
|
718
|
+
this._release();
|
|
719
|
+
};
|
|
720
|
+
w.pid = spec.pid;
|
|
721
|
+
w.ppid = spec.ppid;
|
|
722
|
+
// A child reports on its port; what reaches the Worker itself is its end (crash or error).
|
|
723
|
+
w.report = (m) => {
|
|
724
|
+
if (m.type === "error") {
|
|
725
|
+
port.postMessage({ type: "out", fd: 2, data: te.encode(`webpod: host process failed: ${m.message}\n`) });
|
|
726
|
+
port.postMessage({ type: "exit", code: EXIT_FALLBACK, signal: null });
|
|
727
|
+
end();
|
|
728
|
+
}
|
|
729
|
+
};
|
|
730
|
+
this._register({ pid: spec.pid, ppid: spec.ppid, kill: end });
|
|
731
|
+
if (this.#gone.delete(spec.pid) || parent?.dead)
|
|
732
|
+
return end();
|
|
733
|
+
w.w.postMessage({
|
|
734
|
+
type: "start",
|
|
735
|
+
argv: spec.argv,
|
|
736
|
+
env: spec.env,
|
|
737
|
+
cwd: spec.cwd,
|
|
738
|
+
pid: spec.pid,
|
|
739
|
+
ppid: spec.ppid,
|
|
740
|
+
uid: this.#o.uid ?? 0,
|
|
741
|
+
gid: this.#o.gid ?? 0,
|
|
742
|
+
stdin: spec.stdin ?? null,
|
|
743
|
+
port,
|
|
744
|
+
guest: this.#guestTable,
|
|
745
|
+
...(spec.ipc !== undefined ? { ipc: spec.ipc } : {}),
|
|
746
|
+
}, [port]);
|
|
747
|
+
}
|
|
748
|
+
/** A guest child (the agent's spawn): its stdio and exit relayed on `port`. */
|
|
749
|
+
#guestChild(spec, port) {
|
|
750
|
+
let p;
|
|
751
|
+
try {
|
|
752
|
+
p = this.#backend.spawn({ command: spec.file, args: spec.argv.slice(1), cwd: spec.cwd, env: spec.env });
|
|
753
|
+
}
|
|
754
|
+
catch (e) {
|
|
755
|
+
port.postMessage({ type: "out", fd: 2, data: te.encode(`webpod: ${spec.file}: ${e.message}\n`) });
|
|
756
|
+
port.postMessage({ type: "exit", code: 127, signal: null });
|
|
757
|
+
port.close();
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
const stdin = p.stdin.getWriter();
|
|
761
|
+
if (spec.stdio[0] !== "pipe")
|
|
762
|
+
void stdin.close().catch(() => { });
|
|
763
|
+
let stdinChain = Promise.resolve();
|
|
764
|
+
port.onmessage = ({ data }) => {
|
|
765
|
+
const x = data;
|
|
766
|
+
if (x.type === "stdin" && x.data)
|
|
767
|
+
stdinChain = stdinChain.then(() => stdin.write(x.data)).catch(() => { });
|
|
768
|
+
else if (x.type === "stdin-end")
|
|
769
|
+
stdinChain = stdinChain.then(() => stdin.close()).catch(() => { });
|
|
770
|
+
else if (x.type === "kill")
|
|
771
|
+
void p.kill(signalName(x.signal)).catch(() => { });
|
|
772
|
+
};
|
|
773
|
+
this._register({ pid: spec.pid, ppid: spec.ppid, kill: (sig) => void p.kill(sig).catch(() => { }) });
|
|
774
|
+
if (this.#gone.delete(spec.pid))
|
|
775
|
+
void p.kill("SIGKILL").catch(() => { });
|
|
776
|
+
const pump = async (s, fd) => {
|
|
777
|
+
for (const reader = s.getReader();;) {
|
|
778
|
+
const { done, value } = await reader.read();
|
|
779
|
+
if (done)
|
|
780
|
+
return;
|
|
781
|
+
port.postMessage({ type: "out", fd, data: value });
|
|
782
|
+
}
|
|
783
|
+
};
|
|
784
|
+
const outs = Promise.all([pump(p.stdout, 1), pump(p.stderr, 2)]).catch(() => { });
|
|
785
|
+
void p.exit
|
|
786
|
+
.then(async (st) => {
|
|
787
|
+
await outs;
|
|
788
|
+
port.postMessage({ type: "exit", code: st.code, signal: st.signal });
|
|
789
|
+
},
|
|
790
|
+
// It never started: its output may never end.
|
|
791
|
+
(e) => {
|
|
792
|
+
port.postMessage({ type: "out", fd: 2, data: te.encode(`webpod: ${spec.file}: ${e.message}\n`) });
|
|
793
|
+
port.postMessage({ type: "exit", code: 127, signal: null });
|
|
794
|
+
})
|
|
795
|
+
.finally(() => {
|
|
796
|
+
this._unregister(spec.pid);
|
|
797
|
+
port.close();
|
|
798
|
+
});
|
|
799
|
+
}
|
|
800
|
+
/** A blocking child: this table owns it and writes the result into the parent's control SAB. */
|
|
801
|
+
#spawnSync(m, parent) {
|
|
802
|
+
let ch = new MessageChannel();
|
|
803
|
+
let runner = m.runner;
|
|
804
|
+
const max = m.maxBuffer ?? 1024 * 1024;
|
|
805
|
+
const segs = [];
|
|
806
|
+
const size = [0, 0, 0];
|
|
807
|
+
let error;
|
|
808
|
+
let done = false;
|
|
809
|
+
let timer;
|
|
810
|
+
const finish = (code, signal) => {
|
|
811
|
+
if (done)
|
|
812
|
+
return;
|
|
813
|
+
done = true;
|
|
814
|
+
clearTimeout(timer);
|
|
815
|
+
ch.port1.close();
|
|
816
|
+
writeSync(parent.ctl, { pid: m.pid, status: signal ? null : code, signal, ...(error !== undefined ? { error } : {}), segs: [] }, segs);
|
|
817
|
+
// A node child that exited goes with its Worker and its process slot: no parent reaps it as one does an async
|
|
818
|
+
// child (T106: esbuild's install script's execFileSync, the wasm substitutes' fetch, left their Workers).
|
|
819
|
+
if (runner !== "guest")
|
|
820
|
+
this.#table.get(m.pid)?.kill("SIGKILL");
|
|
821
|
+
};
|
|
822
|
+
const kill = (signal) => {
|
|
823
|
+
if (runner === "guest")
|
|
824
|
+
return ch.port1.postMessage({ type: "kill", signal });
|
|
825
|
+
const e = this.#table.get(m.pid);
|
|
826
|
+
if (e)
|
|
827
|
+
e.kill(signalName(signal));
|
|
828
|
+
else
|
|
829
|
+
this.#gone.add(m.pid);
|
|
830
|
+
finish(null, signal);
|
|
831
|
+
};
|
|
832
|
+
// A host child that falls back (e4-integration.md §3.2): with nothing visible done yet it runs again in the guest
|
|
833
|
+
// (its input written again; guestArgv: its own command line, before the route expanded it), else it ends with 70.
|
|
834
|
+
// One killed or timed out meanwhile has its result already. One that read an inherited stdin (stdio[0] "inherit")
|
|
835
|
+
// before it fell back is not told apart: its rerun does not get what it read.
|
|
836
|
+
const fellBack = (x) => {
|
|
837
|
+
if (done)
|
|
838
|
+
return;
|
|
839
|
+
this.#table.get(m.pid)?.kill("SIGKILL");
|
|
840
|
+
if (!x.rerun) {
|
|
841
|
+
const kind = m.stdio[2] === "pipe" ? 2 : m.stdio[2] === "inherit" ? -2 : 0;
|
|
842
|
+
if (kind)
|
|
843
|
+
segs.push([kind, te.encode(`webpod: ${x.reason}; this program needs regular node (WEBPOD_NODE=guest)\n`)]);
|
|
844
|
+
return finish(EXIT_FALLBACK, null);
|
|
845
|
+
}
|
|
846
|
+
runner = "guest";
|
|
847
|
+
ch.port1.close();
|
|
848
|
+
ch = new MessageChannel();
|
|
849
|
+
ch.port1.onmessage = onReport;
|
|
850
|
+
if (m.input)
|
|
851
|
+
ch.port1.postMessage({ type: "stdin", data: m.input });
|
|
852
|
+
ch.port1.postMessage({ type: "stdin-end" });
|
|
853
|
+
this.#guestChild({ ...m, runner: "guest", argv: m.guestArgv ?? m.argv, reason: x.reason }, ch.port2);
|
|
854
|
+
};
|
|
855
|
+
const onReport = ({ data }) => {
|
|
856
|
+
const x = data;
|
|
857
|
+
if (x.type === "fallback")
|
|
858
|
+
return fellBack(x);
|
|
859
|
+
if (x.type === "out") {
|
|
860
|
+
const kind = m.stdio[x.fd];
|
|
861
|
+
if (kind === "inherit")
|
|
862
|
+
segs.push([-x.fd, x.data]);
|
|
863
|
+
else if (kind === "pipe") {
|
|
864
|
+
segs.push([x.fd, x.data]);
|
|
865
|
+
size[x.fd] += x.data.length;
|
|
866
|
+
if (size[x.fd] > max && error === undefined) {
|
|
867
|
+
error = ENOBUFS;
|
|
868
|
+
kill(m.killSignal ?? "SIGTERM");
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
else if (x.type === "exit")
|
|
873
|
+
finish(x.code ?? null, x.signal ?? null);
|
|
874
|
+
};
|
|
875
|
+
ch.port1.onmessage = onReport;
|
|
876
|
+
let stdin = m.stdin ?? null;
|
|
877
|
+
if (m.runner === "guest") {
|
|
878
|
+
if (m.input)
|
|
879
|
+
ch.port1.postMessage({ type: "stdin", data: m.input });
|
|
880
|
+
ch.port1.postMessage({ type: "stdin-end" });
|
|
881
|
+
}
|
|
882
|
+
else if (!stdin) {
|
|
883
|
+
stdin = createPipe(pow2(Math.max(1 << 16, (m.input?.length ?? 0) + 1)));
|
|
884
|
+
const w = new PipeWriter(stdin);
|
|
885
|
+
void (m.input ? w.write(m.input) : Promise.resolve()).then(() => w.close(), () => w.close());
|
|
886
|
+
}
|
|
887
|
+
if (m.timeout && m.timeout > 0)
|
|
888
|
+
timer = setTimeout(() => {
|
|
889
|
+
error = ETIMEDOUT;
|
|
890
|
+
kill(m.killSignal ?? "SIGTERM");
|
|
891
|
+
}, m.timeout);
|
|
892
|
+
this.#child({ ...m, stdin }, ch.port2, parent, true).catch(() => {
|
|
893
|
+
error ??= ENOENT;
|
|
894
|
+
finish(null, null);
|
|
895
|
+
});
|
|
896
|
+
}
|
|
897
|
+
#emit(e) {
|
|
898
|
+
for (const l of this.#listeners) {
|
|
899
|
+
try {
|
|
900
|
+
l(e);
|
|
901
|
+
}
|
|
902
|
+
catch (err) {
|
|
903
|
+
this.#log("warn", `hostExec fallback listener: ${err.message}`);
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
#log(level, text) {
|
|
908
|
+
this.#o.onLog?.(level, text);
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
const pow2 = (n) => 2 ** Math.ceil(Math.log2(n));
|
|
912
|
+
const SOURCES = new Map();
|
|
913
|
+
/**
|
|
914
|
+
* node-lib.json in the form the Workers read without parsing it whole (each keeps only the modules it compiles, T106):
|
|
915
|
+
* "WPNL", a u32 count, a u32 offset and length for each module's id and then its source (UTF-8), then the bytes.
|
|
916
|
+
*/
|
|
917
|
+
export function indexSources(json) {
|
|
918
|
+
const lib = JSON.parse(new TextDecoder().decode(new Uint8Array(json).slice()));
|
|
919
|
+
const parts = Object.entries(lib).flatMap(([id, src]) => [te.encode(id), te.encode(src)]);
|
|
920
|
+
const head = 8 + parts.length * 8;
|
|
921
|
+
const sab = new SharedArrayBuffer(head + parts.reduce((t, p) => t + p.length, 0));
|
|
922
|
+
const u8 = new Uint8Array(sab);
|
|
923
|
+
const dv = new DataView(sab);
|
|
924
|
+
u8.set(te.encode("WPNL"));
|
|
925
|
+
dv.setUint32(4, parts.length / 2, true);
|
|
926
|
+
let at = head;
|
|
927
|
+
parts.forEach((p, i) => {
|
|
928
|
+
dv.setUint32(8 + i * 8, at, true);
|
|
929
|
+
dv.setUint32(12 + i * 8, p.length, true);
|
|
930
|
+
u8.set(p, at);
|
|
931
|
+
at += p.length;
|
|
932
|
+
});
|
|
933
|
+
return sab;
|
|
934
|
+
}
|
|
935
|
+
/** One copy of a resource that every process reads. */
|
|
936
|
+
async function fetchShared(url, what) {
|
|
937
|
+
const r = await fetch(url);
|
|
938
|
+
if (!r.ok)
|
|
939
|
+
throw new WebPodError("ENGINE_UNAVAILABLE", `host-exec ${what} ${url}: HTTP ${r.status}`);
|
|
940
|
+
const bytes = new Uint8Array(await r.arrayBuffer());
|
|
941
|
+
const sab = new SharedArrayBuffer(bytes.length);
|
|
942
|
+
new Uint8Array(sab).set(bytes);
|
|
943
|
+
return sab;
|
|
944
|
+
}
|
|
945
|
+
/** A listen's (or unix-listen's) answer, for the Worker blocked on ctl. */
|
|
946
|
+
function writeCtl(ctl, res) {
|
|
947
|
+
const json = te.encode(JSON.stringify(res));
|
|
948
|
+
new DataView(ctl).setUint32(SYNC_HEADER, json.length, true);
|
|
949
|
+
new Uint8Array(ctl, SYNC_HEADER + 4).set(json);
|
|
950
|
+
const i = new Int32Array(ctl, 0, 2);
|
|
951
|
+
Atomics.store(i, 1, 4 + json.length);
|
|
952
|
+
Atomics.store(i, 0, 1);
|
|
953
|
+
Atomics.notify(i, 0);
|
|
954
|
+
}
|
|
955
|
+
function writeSync(ctl, res, segs) {
|
|
956
|
+
let out = segs;
|
|
957
|
+
res.segs = out.map(([k, b]) => [k, b.length]);
|
|
958
|
+
let json = te.encode(JSON.stringify(res));
|
|
959
|
+
const total = 4 + json.length + out.reduce((t, [, b]) => t + b.length, 0);
|
|
960
|
+
if (total > ctl.byteLength - SYNC_HEADER) {
|
|
961
|
+
res.error = ENOBUFS;
|
|
962
|
+
res.segs = [];
|
|
963
|
+
out = [];
|
|
964
|
+
json = te.encode(JSON.stringify(res));
|
|
965
|
+
}
|
|
966
|
+
const dv = new DataView(ctl);
|
|
967
|
+
const u8 = new Uint8Array(ctl, SYNC_HEADER);
|
|
968
|
+
dv.setUint32(SYNC_HEADER, json.length, true);
|
|
969
|
+
u8.set(json, 4);
|
|
970
|
+
let o = 4 + json.length;
|
|
971
|
+
for (const [, b] of out) {
|
|
972
|
+
u8.set(b, o);
|
|
973
|
+
o += b.length;
|
|
974
|
+
}
|
|
975
|
+
const i = new Int32Array(ctl, 0, 2);
|
|
976
|
+
Atomics.store(i, 1, o);
|
|
977
|
+
Atomics.store(i, 0, 1);
|
|
978
|
+
Atomics.notify(i, 0);
|
|
979
|
+
}
|
|
980
|
+
/** A top-level host process (`pod.spawn`), with the PodProcess surface of a guest one. */
|
|
981
|
+
class HostProcess {
|
|
982
|
+
runner = "host";
|
|
983
|
+
pid;
|
|
984
|
+
stdin;
|
|
985
|
+
stdout;
|
|
986
|
+
stderr;
|
|
987
|
+
exit;
|
|
988
|
+
#c;
|
|
989
|
+
#req;
|
|
990
|
+
#argv;
|
|
991
|
+
#pidValue;
|
|
992
|
+
#out = [null, null];
|
|
993
|
+
#pipe;
|
|
994
|
+
#writer;
|
|
995
|
+
#resolveExit;
|
|
996
|
+
#worker = null;
|
|
997
|
+
#state = "starting";
|
|
998
|
+
/** stdin written while on the host, for a rerun in the guest; null once over replayBytes. */
|
|
999
|
+
#replay = [];
|
|
1000
|
+
#replayed = 0;
|
|
1001
|
+
#guestStdin = null;
|
|
1002
|
+
#stdinClosed = false;
|
|
1003
|
+
#slot = false;
|
|
1004
|
+
constructor(c, req, argv, cwd) {
|
|
1005
|
+
this.#c = c;
|
|
1006
|
+
this.#req = req;
|
|
1007
|
+
this.#argv = argv;
|
|
1008
|
+
this.#pidValue = c._pid();
|
|
1009
|
+
this.pid = Promise.resolve(this.#pidValue);
|
|
1010
|
+
const o = c._options();
|
|
1011
|
+
this.#pipe = createPipe(o.stdinBytes ?? 1 << 16);
|
|
1012
|
+
this.#writer = new PipeWriter(this.#pipe);
|
|
1013
|
+
this.stdout = new ReadableStream({ start: (ctrl) => void (this.#out[0] = ctrl) });
|
|
1014
|
+
this.stderr = new ReadableStream({ start: (ctrl) => void (this.#out[1] = ctrl) });
|
|
1015
|
+
this.stdin = new WritableStream({
|
|
1016
|
+
write: (chunk) => this.#writeStdin(chunk),
|
|
1017
|
+
close: () => this.#closeStdin(),
|
|
1018
|
+
abort: () => this.#closeStdin(),
|
|
1019
|
+
});
|
|
1020
|
+
this.exit = new Promise((r) => (this.#resolveExit = r));
|
|
1021
|
+
c._register({ pid: this.#pidValue, ppid: 0, kill: (sig) => void this.kill(sig) });
|
|
1022
|
+
void this.#start({ ...DEFAULT_ENV, ...o.env, ...req.env }, cwd);
|
|
1023
|
+
}
|
|
1024
|
+
async #start(env, cwd) {
|
|
1025
|
+
const c = this.#c;
|
|
1026
|
+
try {
|
|
1027
|
+
await c._acquire();
|
|
1028
|
+
this.#slot = true;
|
|
1029
|
+
if (this.#state !== "starting")
|
|
1030
|
+
return this.#end();
|
|
1031
|
+
const w = await c._worker();
|
|
1032
|
+
if (this.#state !== "starting") {
|
|
1033
|
+
c._retire(w);
|
|
1034
|
+
return this.#end();
|
|
1035
|
+
}
|
|
1036
|
+
this.#worker = w;
|
|
1037
|
+
w.pid = this.#pidValue;
|
|
1038
|
+
w.report = (m) => this.#onReport(m);
|
|
1039
|
+
this.#state = "running";
|
|
1040
|
+
const o = c._options();
|
|
1041
|
+
w.w.postMessage({ type: "start", argv: this.#argv, env, cwd, pid: this.#pidValue, ppid: 1, uid: o.uid ?? 0, gid: o.gid ?? 0, stdin: this.#pipe, guest: c._guestTable() });
|
|
1042
|
+
}
|
|
1043
|
+
catch (e) {
|
|
1044
|
+
// Nothing ran on the host: the guest runs it from the start.
|
|
1045
|
+
if (this.#state === "starting")
|
|
1046
|
+
this.#toGuest(`host start failed: ${e.message}`);
|
|
1047
|
+
else
|
|
1048
|
+
this.#end();
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
#onReport(m) {
|
|
1052
|
+
if (this.#state !== "running")
|
|
1053
|
+
return;
|
|
1054
|
+
if (m.type === "out")
|
|
1055
|
+
this.#out[m.fd - 1]?.enqueue(m.data);
|
|
1056
|
+
else if (m.type === "exit")
|
|
1057
|
+
this.#finish({ code: m.code, signal: m.signal ? signalName(m.signal) : null });
|
|
1058
|
+
else if (m.type === "fallback") {
|
|
1059
|
+
if (m.rerun && this.#replay)
|
|
1060
|
+
this.#toGuest(m.reason);
|
|
1061
|
+
else
|
|
1062
|
+
this.#fail(m.reason);
|
|
1063
|
+
}
|
|
1064
|
+
else if (m.type === "error")
|
|
1065
|
+
this.#fail(`host process failed: ${m.message}`);
|
|
1066
|
+
}
|
|
1067
|
+
/** Runs the request in the guest from the start (stdin written so far replayed). */
|
|
1068
|
+
#toGuest(reason) {
|
|
1069
|
+
const c = this.#c;
|
|
1070
|
+
c._emit({ pid: this.#pidValue, argv: this.#argv, reason, rerun: true });
|
|
1071
|
+
this.#end();
|
|
1072
|
+
this.#state = "guest";
|
|
1073
|
+
let p;
|
|
1074
|
+
try {
|
|
1075
|
+
p = c._backend().spawn(this.#req);
|
|
1076
|
+
}
|
|
1077
|
+
catch (e) {
|
|
1078
|
+
this.#out[1]?.enqueue(te.encode(`webpod: ${e.message}\n`));
|
|
1079
|
+
return this.#finish({ code: 127, signal: null });
|
|
1080
|
+
}
|
|
1081
|
+
this.#guest = p;
|
|
1082
|
+
const w = p.stdin.getWriter();
|
|
1083
|
+
for (const b of this.#replay ?? [])
|
|
1084
|
+
void w.write(b).catch(() => { });
|
|
1085
|
+
this.#replay = null;
|
|
1086
|
+
this.#guestStdin = w;
|
|
1087
|
+
if (this.#stdinClosed)
|
|
1088
|
+
void w.close().catch(() => { });
|
|
1089
|
+
const pump = async (s, i) => {
|
|
1090
|
+
for (const r = s.getReader();;) {
|
|
1091
|
+
const { done, value } = await r.read();
|
|
1092
|
+
if (done)
|
|
1093
|
+
return;
|
|
1094
|
+
this.#out[i]?.enqueue(value);
|
|
1095
|
+
}
|
|
1096
|
+
};
|
|
1097
|
+
const outs = Promise.all([pump(p.stdout, 0), pump(p.stderr, 1)]).catch(() => { });
|
|
1098
|
+
void p.exit.then(async (st) => {
|
|
1099
|
+
await outs;
|
|
1100
|
+
this.#finish(st);
|
|
1101
|
+
}, (e) => {
|
|
1102
|
+
this.#out[1]?.enqueue(te.encode(`webpod: ${e.message}\n`));
|
|
1103
|
+
this.#finish({ code: 127, signal: null });
|
|
1104
|
+
});
|
|
1105
|
+
}
|
|
1106
|
+
#guest = null;
|
|
1107
|
+
/** A runtime fallback after visible effects: cannot rerun (e4-integration.md §3.2). */
|
|
1108
|
+
#fail(reason) {
|
|
1109
|
+
this.#c._emit({ pid: this.#pidValue, argv: this.#argv, reason, rerun: false });
|
|
1110
|
+
this.#out[1]?.enqueue(te.encode(`webpod: ${reason}; this program needs regular node (WEBPOD_NODE=guest)\n`));
|
|
1111
|
+
this.#finish({ code: EXIT_FALLBACK, signal: null });
|
|
1112
|
+
}
|
|
1113
|
+
#finish(status) {
|
|
1114
|
+
if (this.#state === "done")
|
|
1115
|
+
return;
|
|
1116
|
+
this.#state = "done";
|
|
1117
|
+
this.#end();
|
|
1118
|
+
for (const ctrl of this.#out) {
|
|
1119
|
+
try {
|
|
1120
|
+
ctrl?.close();
|
|
1121
|
+
}
|
|
1122
|
+
catch {
|
|
1123
|
+
// already closed or errored
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
this.#writer.close();
|
|
1127
|
+
this.#c._unregister(this.#pidValue);
|
|
1128
|
+
this.#resolveExit(status);
|
|
1129
|
+
}
|
|
1130
|
+
/** The host side of the process is over: its Worker, session, slot and children. */
|
|
1131
|
+
#end() {
|
|
1132
|
+
const c = this.#c;
|
|
1133
|
+
c._killChildren(this.#pidValue, "SIGKILL");
|
|
1134
|
+
if (this.#worker) {
|
|
1135
|
+
c._retire(this.#worker);
|
|
1136
|
+
this.#worker = null;
|
|
1137
|
+
}
|
|
1138
|
+
if (this.#slot) {
|
|
1139
|
+
this.#slot = false;
|
|
1140
|
+
c._release();
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
async #writeStdin(chunk) {
|
|
1144
|
+
if (this.#guestStdin)
|
|
1145
|
+
return this.#guestStdin.write(chunk);
|
|
1146
|
+
if (this.#state === "done")
|
|
1147
|
+
return;
|
|
1148
|
+
if (this.#replay) {
|
|
1149
|
+
this.#replayed += chunk.length;
|
|
1150
|
+
if (this.#replayed > (this.#c._options().replayBytes ?? 1 << 20))
|
|
1151
|
+
this.#replay = null;
|
|
1152
|
+
else
|
|
1153
|
+
this.#replay.push(chunk.slice());
|
|
1154
|
+
}
|
|
1155
|
+
// A process that exited leaves the rest unread, like a closed pipe.
|
|
1156
|
+
await this.#writer.write(chunk).catch(() => { });
|
|
1157
|
+
}
|
|
1158
|
+
async #closeStdin() {
|
|
1159
|
+
this.#stdinClosed = true;
|
|
1160
|
+
if (this.#guestStdin)
|
|
1161
|
+
return this.#guestStdin.close();
|
|
1162
|
+
this.#writer.close();
|
|
1163
|
+
}
|
|
1164
|
+
async kill(signal = "SIGTERM") {
|
|
1165
|
+
if (this.#state === "done")
|
|
1166
|
+
return;
|
|
1167
|
+
if (this.#state === "guest" && this.#guest)
|
|
1168
|
+
return this.#guest.kill(signal);
|
|
1169
|
+
// Worker processes take the default action of every signal (e4-integration.md §3.3).
|
|
1170
|
+
this.#finish({ code: null, signal });
|
|
1171
|
+
}
|
|
1172
|
+
async resize() {
|
|
1173
|
+
// No tty on the host (pty requests run in the guest).
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
//# sourceMappingURL=controller.js.map
|