@webpodjs/sdk 0.2.7 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +93 -15
- package/dist/agent/backend.d.ts +18 -1
- package/dist/agent/backend.js +275 -76
- package/dist/agent/backend.js.map +1 -1
- package/dist/agent/fs.d.ts +2 -2
- package/dist/agent/fs.js +3 -2
- package/dist/agent/fs.js.map +1 -1
- package/dist/agent/protocol.d.ts +40 -1
- package/dist/agent/protocol.js +39 -3
- package/dist/agent/protocol.js.map +1 -1
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/exec/client.js +21 -6
- package/dist/exec/client.js.map +1 -1
- package/dist/exec/frame.js +5 -0
- package/dist/exec/frame.js.map +1 -1
- package/dist/fs/tar.d.ts +1 -1
- package/dist/fs/tar.js +8 -2
- package/dist/fs/tar.js.map +1 -1
- package/dist/fs/workspace.js +61 -30
- package/dist/fs/workspace.js.map +1 -1
- package/dist/host/backend.d.ts +11 -0
- package/dist/host/backend.js +71 -14
- package/dist/host/backend.js.map +1 -1
- package/dist/host/channel.js +4 -1
- package/dist/host/channel.js.map +1 -1
- package/dist/host/controller.d.ts +2 -0
- package/dist/host/controller.js +11 -4
- package/dist/host/controller.js.map +1 -1
- package/dist/host/devices.d.ts +28 -2
- package/dist/host/devices.js +55 -7
- package/dist/host/devices.js.map +1 -1
- package/dist/host/pump-worker.js +12 -4
- package/dist/host/pump-worker.js.map +1 -1
- package/dist/host-exec/controller.d.ts +161 -4
- package/dist/host-exec/controller.js +1041 -70
- package/dist/host-exec/controller.js.map +1 -1
- package/dist/host-exec/protocol.d.ts +337 -4
- package/dist/host-exec/protocol.js +34 -0
- package/dist/host-exec/protocol.js.map +1 -1
- package/dist/host-exec/route.js +74 -13
- package/dist/host-exec/route.js.map +1 -1
- package/dist/host-exec/shim.d.ts +8 -2
- package/dist/host-exec/shim.js +77 -12
- package/dist/host-exec/shim.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/net/client.d.ts +5 -1
- package/dist/net/client.js +8 -4
- package/dist/net/client.js.map +1 -1
- package/dist/net/options.d.ts +14 -0
- package/dist/net/options.js +1 -1
- package/dist/net/options.js.map +1 -1
- package/dist/net/preview.d.ts +15 -1
- package/dist/net/preview.js +24 -4
- package/dist/net/preview.js.map +1 -1
- package/dist/output.d.ts +23 -0
- package/dist/output.js +161 -0
- package/dist/output.js.map +1 -0
- package/dist/pod.d.ts +21 -7
- package/dist/pod.js +165 -29
- package/dist/pod.js.map +1 -1
- package/dist/preview-relay.js +24 -7
- package/dist/preview-relay.js.map +1 -1
- package/dist/preview-serviceworker.js +71 -8
- package/dist/preview-serviceworker.js.map +1 -1
- package/dist/tools.d.ts +79 -0
- package/dist/tools.js +47 -0
- package/dist/tools.js.map +1 -0
- package/dist/types.d.ts +62 -2
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -1,22 +1,44 @@
|
|
|
1
|
+
import { STDIO_RUNNER } from "../agent/protocol.js";
|
|
1
2
|
import { WebPodError } from "../errors.js";
|
|
2
3
|
import { constrainedDevice } from "../features.js";
|
|
4
|
+
import { ProcessOutput } from "../output.js";
|
|
3
5
|
import { SIGNAL_NUMBERS } from "../types.js";
|
|
4
6
|
import { PipeWriter, createPipe } from "./pipe.js";
|
|
5
7
|
import { hostPreflight } from "./preflight.js";
|
|
6
|
-
import { PROTOCOL, SYNC_HEADER } from "./protocol.js";
|
|
8
|
+
import { HOST_ASSETS, HOST_CHUNKS, OUT_WINDOW, outCredit, outTaken, outUntaken, PROTOCOL, SYNC_HEADER } from "./protocol.js";
|
|
7
9
|
import { routeTopLevel } from "./route.js";
|
|
8
|
-
import { ShimBridge, treeRoots } from "./shim.js";
|
|
10
|
+
import { NOT_LEARNED, ShimBridge, treeRoots } from "./shim.js";
|
|
11
|
+
// A relayed port message whose end is on its way to a thread waits this long for its claim there (#relay); a thread that
|
|
12
|
+
// ended this long for its drain (#endThread).
|
|
13
|
+
const RELAY_CLAIM_MS = 5000, RELAY_DRAIN_MS = 1000;
|
|
14
|
+
// (ES2024's: not in this build's lib)
|
|
15
|
+
const waitAsync = Atomics.waitAsync;
|
|
9
16
|
const DEFAULT_EXEC_PATH = "/usr/local/bin/node";
|
|
17
|
+
/** How long the pool keeps its burst size after the last take that found no booted Worker (T291). */
|
|
18
|
+
const POOL_BURST_MS = 5000;
|
|
19
|
+
/** What an idle booted Worker counts as of memoryBudgetMB while the pool bursts (WebKit: 17-27 MB, Chromium: 10). */
|
|
20
|
+
const IDLE_WORKER_MB = 32;
|
|
21
|
+
/** How long after the first Worker's boot host-node.js's chunks are fetched ahead (once the page is idle too). */
|
|
22
|
+
const CHUNKS_AHEAD_MS = 2000;
|
|
10
23
|
const NPM = "/usr/local/lib/node_modules/npm/bin";
|
|
11
24
|
const DEFAULT_COMMANDS = { node: [], npm: [`${NPM}/npm-cli.js`], npx: [`${NPM}/npx-cli.js`] };
|
|
12
|
-
|
|
25
|
+
// PATH: the node images' (images/<name>/env), with wpm's launchers ($HOME/.webpod/bin and bin-low, T245).
|
|
26
|
+
const DEFAULT_ENV = { PATH: "/usr/local/sbin:/root/.webpod/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/.webpod/bin-low", HOME: "/root" };
|
|
13
27
|
const ENOBUFS = -105;
|
|
14
28
|
const ETIMEDOUT = -110;
|
|
15
29
|
const ENOENT = -2;
|
|
16
30
|
const EADDRINUSE = 98;
|
|
17
31
|
const ENOTSUP = 95;
|
|
32
|
+
const EPERM = 1;
|
|
33
|
+
const ESRCH = 3;
|
|
34
|
+
const EINVAL = 22;
|
|
18
35
|
const EXIT_FALLBACK = 70;
|
|
19
36
|
const BOOT_TIMEOUT_MS = 30000;
|
|
37
|
+
/** How long a killed wasm child's end waits for its Workers to stop at most, and keeps their lock then (host-exec's src/proc-lock.js). */
|
|
38
|
+
const PROC_STOP_MS = 1000;
|
|
39
|
+
const PROC_HOLD_MS = 10_000;
|
|
40
|
+
/** The most a process may declare and still start in hostExec.memoryReserveMB (T340). */
|
|
41
|
+
const SPARE_MB = 64;
|
|
20
42
|
/** HostExecStatus.reason in a tab of a pod whose workspace another tab holds (T265). */
|
|
21
43
|
const HELD_BY_ANOTHER_TAB = "another tab of this pod holds its workspace (shareTabs), whose host sessions only that tab serves";
|
|
22
44
|
const te = new TextEncoder();
|
|
@@ -29,6 +51,14 @@ const signalName = (s) => (typeof s === "string" && s in SIGNAL_NUMBERS ? s : "S
|
|
|
29
51
|
* (PID_MAX_LIMIT), and wraps around to 300. The agent's Hello names its pid_max (`pid-max=N`).
|
|
30
52
|
*/
|
|
31
53
|
const HOST_PID_BASE = 32768;
|
|
54
|
+
// The pod's CA as the agent installs it (crates/webpod-agent/src/ca.rs): its file, the profile that names the files and
|
|
55
|
+
// variables (SSL_CERT_FILE, SSL_CERT_DIR, CURL_CA_BUNDLE, ...), and the hash directory it makes of the system bundle.
|
|
56
|
+
const CA_PROFILE = "/etc/profile.d/webpod-ca.sh";
|
|
57
|
+
const POD_CA_FILE = "/etc/webpod/pod-ca.pem";
|
|
58
|
+
const CA_HASH_DIR = "/etc/webpod/certs";
|
|
59
|
+
// OpenSSL's default CA file in webpod's WASIX builds (their openssldir /etc/ssl, as Alpine's: CPython's ssl without
|
|
60
|
+
// SSL_CERT_FILE), which the agent's install leaves as the guest had it: Alpine's a link to the bundle.
|
|
61
|
+
const OPENSSL_CA_FILE = "/etc/ssl/cert.pem";
|
|
32
62
|
/** Where host pids start: HOST_PID_BASE, or above the guest's pid_max when its agent names a larger one. */
|
|
33
63
|
function hostPidBase(backend, log) {
|
|
34
64
|
const agent = backend.agent;
|
|
@@ -43,26 +73,66 @@ export class HostExecController {
|
|
|
43
73
|
#sessions;
|
|
44
74
|
#o;
|
|
45
75
|
#listeners = new Set();
|
|
46
|
-
/**
|
|
47
|
-
|
|
76
|
+
/**
|
|
77
|
+
* The pid counter host Workers share ([0]), and this controller's session ([1], a random number not 0: the owner
|
|
78
|
+
* of a host process's file lock is in another session after a reload, its pids counted again); none where there is
|
|
79
|
+
* no SharedArrayBuffer (host mode is unavailable there).
|
|
80
|
+
*/
|
|
81
|
+
#pids = typeof SharedArrayBuffer === "function" ? new SharedArrayBuffer(8) : null;
|
|
48
82
|
#table = new Map();
|
|
49
83
|
/** pids reaped or killed before their Worker was up. */
|
|
50
84
|
#gone = new Set();
|
|
85
|
+
/** The children being started (spawn received, not in the table yet): pid -> its parent's Worker. */
|
|
86
|
+
#starting = new Map();
|
|
87
|
+
/**
|
|
88
|
+
* spawnSync's host children, from the spawnSync on: pid -> the end of one another process's kill ends (its default
|
|
89
|
+
* action), the spawnSync's result as its own kill's (a timeout) is (T369); false for a guest one, whose end its port
|
|
90
|
+
* reports.
|
|
91
|
+
*/
|
|
92
|
+
#syncKills = new Map();
|
|
93
|
+
/** The first host pid (hostPidBase): any pid below is the guest's. */
|
|
94
|
+
#pidBase = HOST_PID_BASE;
|
|
51
95
|
#queue = [];
|
|
52
96
|
#warm = [];
|
|
97
|
+
/** The pooled Workers that have booted (a take of one that has not is a miss). */
|
|
98
|
+
#ready = new WeakSet();
|
|
99
|
+
/** The pool's size now: pool, or the burst's after a miss (until #burstTimer). */
|
|
100
|
+
#poolTarget = 1;
|
|
101
|
+
#burstTimer = null;
|
|
102
|
+
#lastTake = -Infinity;
|
|
103
|
+
#chunksAhead = false;
|
|
104
|
+
#chunksTimer = null;
|
|
53
105
|
#workers = new Set();
|
|
54
106
|
#max;
|
|
107
|
+
#maxThreads;
|
|
108
|
+
#memBudget;
|
|
109
|
+
/** The processes holding memory of the budget (memoryMB, a reserve granted), and the MB they hold. */
|
|
110
|
+
#memHeld = new Set();
|
|
111
|
+
#memUsed = 0;
|
|
112
|
+
/** memoryReserveMB, the small processes holding some of it, and the MB they hold. */
|
|
113
|
+
#memSpare;
|
|
114
|
+
#spareHeld = new Set();
|
|
115
|
+
#spareUsed = 0;
|
|
116
|
+
/** Reserves waiting, first come first served. */
|
|
117
|
+
#memQueue = [];
|
|
118
|
+
/** What host processes report as their CPUs (boot's cpus). */
|
|
119
|
+
#cpus;
|
|
120
|
+
/** The pod's CA files and variables as the guest has them (#loadCa), for host processes' starts; null: none yet. */
|
|
121
|
+
#ca = null;
|
|
55
122
|
#status;
|
|
56
123
|
#enabled;
|
|
57
124
|
#live = 0;
|
|
58
125
|
#threads = 0;
|
|
59
126
|
#clients = 0;
|
|
127
|
+
#memIds = 0;
|
|
60
128
|
/** The fallback tables' patterns host processes route their node children by (the image's, the learned one). */
|
|
61
129
|
#guestTable = [];
|
|
62
130
|
#listenReqs = 0;
|
|
63
131
|
/** Unix sockets of host processes (T99): listeners by key, connections by id with the two processes' Workers. */
|
|
64
132
|
#unixListeners = new Map();
|
|
65
133
|
#unixConns = new Map();
|
|
134
|
+
/** UDP between host processes (T270): the pod's host UDP ports. */
|
|
135
|
+
#udp = new UdpPorts();
|
|
66
136
|
#unixIds = 0;
|
|
67
137
|
#tree;
|
|
68
138
|
/** The guest's node shim (agents with host-exec), when host mode is on. */
|
|
@@ -71,6 +141,10 @@ export class HostExecController {
|
|
|
71
141
|
#hostOk = null;
|
|
72
142
|
/** Compiled wasm Modules the processes report (napi-wasm substitutes), handed to every Worker booted later. */
|
|
73
143
|
#wasmModules = {};
|
|
144
|
+
/** Keys the processes' WebCrypto calls imported, by their bytes and parameters (the last 32, #webcrypto). */
|
|
145
|
+
#importedKeys = new Map();
|
|
146
|
+
/** The asset files the processes asked for (HOST_ASSETS), fetched once for the page. */
|
|
147
|
+
#assets = new Map();
|
|
74
148
|
#disposed = false;
|
|
75
149
|
/** What `enabled` was set to (applied when host processes can start: this tab took the workspace over). */
|
|
76
150
|
#wanted = true;
|
|
@@ -85,8 +159,18 @@ export class HostExecController {
|
|
|
85
159
|
this.#status = status;
|
|
86
160
|
this.#enabled = status.node === "on";
|
|
87
161
|
this.#max = options.maxProcesses ?? (constrainedDevice() ? 6 : 8);
|
|
88
|
-
|
|
89
|
-
|
|
162
|
+
this.#maxThreads = options.maxThreads ?? 2 * this.#max;
|
|
163
|
+
this.#memSpare = Math.max(0, options.memoryReserveMB ?? 128);
|
|
164
|
+
this.#memBudget = options.memoryBudgetMB ?? (constrainedDevice() ? 768 : 2048);
|
|
165
|
+
this.#poolTarget = options.pool ?? 1;
|
|
166
|
+
// The device's cores, but only as many as the worker pools sized by them can start within the limits: jest-worker's
|
|
167
|
+
// cpus - 1 child processes next to jest and npm, piscina's 1.5 x cpus threads.
|
|
168
|
+
this.#cpus = Math.max(1, Math.min(globalThis.navigator?.hardwareConcurrency || 1, this.#max - 2, Math.floor(this.#maxThreads / 2)));
|
|
169
|
+
this.#pidBase = hostPidBase(backend, (level, text) => this.#log(level, text));
|
|
170
|
+
if (this.#pids) {
|
|
171
|
+
Atomics.store(new Int32Array(this.#pids), 0, this.#pidBase);
|
|
172
|
+
Atomics.store(new Int32Array(this.#pids), 1, (crypto.getRandomValues(new Uint32Array(1))[0] | 1) >> 0);
|
|
173
|
+
}
|
|
90
174
|
}
|
|
91
175
|
/** Checks what host processes need; `status.node` tells the outcome. Never throws for a missing capability. */
|
|
92
176
|
static async create(backend, options = {}) {
|
|
@@ -138,6 +222,12 @@ export class HostExecController {
|
|
|
138
222
|
if (!this.#sessions.shares?.length)
|
|
139
223
|
this.#log("info", "host-exec: the image declares no host shares (webpod-home, webpod-tmp): $HOME and /tmp are read-only to host processes");
|
|
140
224
|
await this._reloadTables();
|
|
225
|
+
// The pod's CA for host processes (T330): read now (a pod booted with it), and again once the agent installed it and
|
|
226
|
+
// once it settled (its hash directory then).
|
|
227
|
+
const ca = this.#backend;
|
|
228
|
+
void this.#loadCa();
|
|
229
|
+
for (const p of [ca.caInstalled, ca.caSettled])
|
|
230
|
+
void p?.then(() => this.#loadCa(), () => { });
|
|
141
231
|
this.#fill();
|
|
142
232
|
const hostMode = this.#backend.hostMode;
|
|
143
233
|
if (hostMode) {
|
|
@@ -156,7 +246,10 @@ export class HostExecController {
|
|
|
156
246
|
this.#hostOk = ok;
|
|
157
247
|
void this.#announce();
|
|
158
248
|
}
|
|
159
|
-
/**
|
|
249
|
+
/**
|
|
250
|
+
* HostExecInfo for the guest's node shim: node while host processes can start (and node:test's runner and watch
|
|
251
|
+
* mode, which an older host ran as plain node: the agent sends those to the guest without them), the paths they see.
|
|
252
|
+
*/
|
|
160
253
|
async #announce() {
|
|
161
254
|
const shim = this.#shim;
|
|
162
255
|
if (!shim)
|
|
@@ -164,7 +257,7 @@ export class HostExecController {
|
|
|
164
257
|
const node = this.#enabled && !this.#disposed && this.#hostOk === true;
|
|
165
258
|
const tree = node ? await this.#loadTree().catch(() => undefined) : undefined;
|
|
166
259
|
const s = this.#sessions;
|
|
167
|
-
shim.update({ runners: node && this.#enabled ? ["node"] : [], mounts: [s.workspace, ...this._sharePrefixes(), ...treeRoots(tree, this.#execPath)], excludes: (s.localPaths ?? []).map((p) => `${s.workspace}/${p}`) });
|
|
260
|
+
shim.update({ runners: node && this.#enabled ? ["node", "node --test", "node --watch", STDIO_RUNNER] : [], mounts: [s.workspace, ...this._sharePrefixes(), ...treeRoots(tree, this.#execPath)], excludes: (s.localPaths ?? []).map((p) => `${s.workspace}/${p}`) });
|
|
168
261
|
}
|
|
169
262
|
/** What routeTopLevel needs, to tell where a request runs without starting it (an execution origin's app side). */
|
|
170
263
|
get routeContext() {
|
|
@@ -224,6 +317,11 @@ export class HostExecController {
|
|
|
224
317
|
this.#shim?.close();
|
|
225
318
|
for (const q of this.#queue.splice(0))
|
|
226
319
|
q();
|
|
320
|
+
if (this.#burstTimer)
|
|
321
|
+
clearTimeout(this.#burstTimer);
|
|
322
|
+
this.#burstTimer = null;
|
|
323
|
+
if (this.#chunksTimer)
|
|
324
|
+
clearTimeout(this.#chunksTimer);
|
|
227
325
|
const warm = this.#warm.splice(0);
|
|
228
326
|
for (const e of [...this.#table.values()])
|
|
229
327
|
e.kill("SIGKILL");
|
|
@@ -242,14 +340,16 @@ export class HostExecController {
|
|
|
242
340
|
*/
|
|
243
341
|
async _reloadTables() {
|
|
244
342
|
const home = this.#o.env?.HOME ?? DEFAULT_ENV.HOME;
|
|
245
|
-
const
|
|
343
|
+
const learned = `${home}/.cache/webpod/host-exec-fallback.json`;
|
|
344
|
+
const files = ["/etc/webpod/host-exec.json", learned];
|
|
246
345
|
const all = new Set();
|
|
247
346
|
for (const f of files) {
|
|
248
347
|
try {
|
|
249
348
|
const t = JSON.parse(await this.#backend.fs.readFile(f, "utf8"));
|
|
349
|
+
// (the learned table's corepack does not count: a pod may have learned it before T371)
|
|
250
350
|
if (Array.isArray(t.guest))
|
|
251
351
|
for (const g of t.guest)
|
|
252
|
-
if (typeof g === "string")
|
|
352
|
+
if (typeof g === "string" && !(f === learned && NOT_LEARNED.has(g)))
|
|
253
353
|
all.add(g);
|
|
254
354
|
}
|
|
255
355
|
catch {
|
|
@@ -262,6 +362,87 @@ export class HostExecController {
|
|
|
262
362
|
_guestTable() {
|
|
263
363
|
return this.#guestTable;
|
|
264
364
|
}
|
|
365
|
+
/**
|
|
366
|
+
* The pod's CA files from the guest (T330, docs/design/wasix-lite.md §2.3): its file, the system bundle and the hash
|
|
367
|
+
* directory the agent's profile names, and OpenSSL's default file (/etc/ssl/cert.pem: Alpine's link to the bundle),
|
|
368
|
+
* for host processes' read-only tree at the same paths (start's rootFiles: a WASIX program's TLS, curl's, CPython's,
|
|
369
|
+
* trusts what the guest's does), on one SharedArrayBuffer. Its variables too, for host
|
|
370
|
+
* processes without them (a pod.spawn's; the shim's have the guest's). Nothing while there is no CA in the guest.
|
|
371
|
+
*/
|
|
372
|
+
async #loadCa() {
|
|
373
|
+
const fs = this.#backend.fs;
|
|
374
|
+
let profile;
|
|
375
|
+
try {
|
|
376
|
+
profile = await fs.readFile(CA_PROFILE, "utf8");
|
|
377
|
+
}
|
|
378
|
+
catch {
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
const env = {};
|
|
382
|
+
for (const line of profile.split("\n")) {
|
|
383
|
+
const m = /^export ([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line.trim());
|
|
384
|
+
if (m)
|
|
385
|
+
env[m[1]] = m[2];
|
|
386
|
+
}
|
|
387
|
+
const paths = new Set([POD_CA_FILE, ...[env.SSL_CERT_FILE, env.CURL_CA_BUNDLE].filter((p) => !!p && p.startsWith("/"))]);
|
|
388
|
+
// The same profile and the same bundle (the hash directory's fingerprint of it, ca.rs's .source) as last time: the
|
|
389
|
+
// same files (no 140 reads of the hash directory again).
|
|
390
|
+
const indexed = env.SSL_CERT_DIR === CA_HASH_DIR;
|
|
391
|
+
const source = indexed ? await fs.readFile(`${CA_HASH_DIR}/.source`, "utf8").catch(() => "") : "";
|
|
392
|
+
const key = profile + "\0" + source;
|
|
393
|
+
if (this.#ca?.key === key && source)
|
|
394
|
+
return;
|
|
395
|
+
if (indexed) {
|
|
396
|
+
for (const e of await fs.readdir(CA_HASH_DIR).catch(() => []))
|
|
397
|
+
if (e.type === "file" && !e.name.startsWith("."))
|
|
398
|
+
paths.add(`${CA_HASH_DIR}/${e.name}`);
|
|
399
|
+
}
|
|
400
|
+
// OpenSSL's default file as the guest has it: a link (and the file it leads to), or a file
|
|
401
|
+
const links = [];
|
|
402
|
+
const st = await fs.lstat(OPENSSL_CA_FILE).catch(() => null);
|
|
403
|
+
if (st?.type === "symlink") {
|
|
404
|
+
const target = await fs.readlink(OPENSSL_CA_FILE).catch(() => "");
|
|
405
|
+
if (target) {
|
|
406
|
+
links.push({ path: OPENSSL_CA_FILE, mode: 0o120777, data: new TextEncoder().encode(target) });
|
|
407
|
+
const out = [];
|
|
408
|
+
for (const c of (target.startsWith("/") ? target : `/etc/ssl/${target}`).split("/"))
|
|
409
|
+
if (c === "..")
|
|
410
|
+
out.pop();
|
|
411
|
+
else if (c && c !== ".")
|
|
412
|
+
out.push(c);
|
|
413
|
+
paths.add(`/${out.join("/")}`);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
else if (st?.type === "file")
|
|
417
|
+
paths.add(OPENSSL_CA_FILE);
|
|
418
|
+
const read = await Promise.all([...paths].map((path) => fs.readFile(path).then((data) => ({ path, mode: 0o100644, data }), () => null)));
|
|
419
|
+
const got = [...read.filter((f) => f !== null), ...links];
|
|
420
|
+
if (!got.some((f) => f.path === POD_CA_FILE))
|
|
421
|
+
return;
|
|
422
|
+
const sab = new SharedArrayBuffer(got.reduce((n, f) => n + f.data.length, 0));
|
|
423
|
+
let at = 0;
|
|
424
|
+
const files = got.map((f) => {
|
|
425
|
+
const data = new Uint8Array(sab, at, f.data.length);
|
|
426
|
+
data.set(f.data);
|
|
427
|
+
at += f.data.length;
|
|
428
|
+
return { path: f.path, mode: f.mode, data };
|
|
429
|
+
});
|
|
430
|
+
this.#ca = { files, env, key };
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* @internal What a start to `w` carries besides its process: rootFiles (the pod's CA), when there are some; the wasm
|
|
434
|
+
* Modules compiled since it booted (wasmModules), which a Worker of the pool booted ahead has not got (T365).
|
|
435
|
+
*/
|
|
436
|
+
_startFields(w) {
|
|
437
|
+
const fresh = Object.keys(this.#wasmModules).filter((k) => !w.modules?.has(k));
|
|
438
|
+
for (const k of fresh)
|
|
439
|
+
(w.modules ??= new Set()).add(k);
|
|
440
|
+
return { ...(this.#ca ? { rootFiles: this.#ca.files } : {}), ...(fresh.length ? { wasmModules: Object.fromEntries(fresh.map((k) => [k, this.#wasmModules[k]])) } : {}) };
|
|
441
|
+
}
|
|
442
|
+
/** @internal The pod's CA variables, for a host process's environment (its own win). */
|
|
443
|
+
_caEnv() {
|
|
444
|
+
return this.#ca?.env ?? {};
|
|
445
|
+
}
|
|
265
446
|
/** @internal */
|
|
266
447
|
_emit(e) {
|
|
267
448
|
this.#emit(e);
|
|
@@ -334,6 +515,12 @@ export class HostExecController {
|
|
|
334
515
|
return this.#boot(identity);
|
|
335
516
|
// A few from the pool, then a new one whose failure is the caller's: when every boot fails (the FS Worker cannot
|
|
336
517
|
// open a session), taking the next pooled one and refilling would go on for ever and freeze the page.
|
|
518
|
+
// A miss right after another take (not the first process, whose Worker may still boot with the pod) is a burst.
|
|
519
|
+
const now = Date.now();
|
|
520
|
+
const soon = now - this.#lastTake < (this.#o.poolBurstMs ?? POOL_BURST_MS);
|
|
521
|
+
this.#lastTake = now;
|
|
522
|
+
if (soon && (!this.#warm.length || !this.#ready.has(this.#warm[0])))
|
|
523
|
+
this.#burst();
|
|
337
524
|
for (let tries = 0; tries < 3 && this.#warm.length > 0; tries++) {
|
|
338
525
|
const p = this.#warm.shift();
|
|
339
526
|
this.#fill();
|
|
@@ -356,15 +543,76 @@ export class HostExecController {
|
|
|
356
543
|
_unregister(pid) {
|
|
357
544
|
this.#table.delete(pid);
|
|
358
545
|
}
|
|
359
|
-
/**
|
|
546
|
+
/**
|
|
547
|
+
* @internal Kills the processes below `pid` (its own exit or kill ends the tree, as a process group). A detached child
|
|
548
|
+
* (and what is below it) goes on, adopted as by init (ppid 1): it ends by itself, by a kill or with the pod. One that
|
|
549
|
+
* ended already (its parent had not reaped it yet) is reaped now, as init would.
|
|
550
|
+
*/
|
|
360
551
|
_killChildren(pid, signal) {
|
|
361
552
|
for (const e of [...this.#table.values()]) {
|
|
362
553
|
if (e.ppid !== pid)
|
|
363
554
|
continue;
|
|
555
|
+
if (e.detached && !e.exited) {
|
|
556
|
+
e.ppid = 1;
|
|
557
|
+
// Nobody takes its output any more (its owner's port is gone): its writes do not wait for it.
|
|
558
|
+
outUntaken(e.outCredit);
|
|
559
|
+
e.untaken?.();
|
|
560
|
+
continue;
|
|
561
|
+
}
|
|
364
562
|
this._killChildren(e.pid, signal);
|
|
365
563
|
e.kill(signal);
|
|
366
564
|
}
|
|
367
565
|
}
|
|
566
|
+
/**
|
|
567
|
+
* @internal A debugging aid (T289): asks every host Worker what its memory is (host-exec's src/mem-report.js: its JS
|
|
568
|
+
* heap where the engine tells it, its WebAssembly.Memory objects) and sums the answers. A Worker that does not answer
|
|
569
|
+
* within timeoutMs (default 1 s) is listed with its last answer, as stuck.
|
|
570
|
+
*/
|
|
571
|
+
async _memReport(options = {}) {
|
|
572
|
+
const timeoutMs = options.timeoutMs ?? 1000, id = ++this.#memIds, at = Date.now();
|
|
573
|
+
// (the page's SharedArrayBuffers for it: its spawnSync / listen answers, its 9P sessions' rings)
|
|
574
|
+
const buffers = (rec) => ({ ctl: rec.ctl.byteLength, sessions: [rec.session, ...rec.shares].reduce((n, s) => n + s.memory.byteLength, 0) });
|
|
575
|
+
const workers = await Promise.all([...this.#workers].filter((w) => !w.dead).map((rec) => new Promise((resolve) => {
|
|
576
|
+
const mem = (rec.mem ??= { last: null, waiting: new Map() });
|
|
577
|
+
const timer = setTimeout(() => {
|
|
578
|
+
mem.waiting.delete(id);
|
|
579
|
+
resolve({ ...(mem.last ? { ...mem.last.report, lastAt: mem.last.at } : { ...(rec.pid !== undefined ? { pid: rec.pid } : {}), uptimeMs: 0, heap: null, memories: [], webWorkers: 0 }), buffers: buffers(rec), stuck: true });
|
|
580
|
+
}, timeoutMs);
|
|
581
|
+
mem.waiting.set(id, (report) => {
|
|
582
|
+
clearTimeout(timer);
|
|
583
|
+
resolve({ ...report, buffers: buffers(rec) });
|
|
584
|
+
});
|
|
585
|
+
try {
|
|
586
|
+
rec.w.postMessage({ type: "mem", id });
|
|
587
|
+
}
|
|
588
|
+
catch {
|
|
589
|
+
// a Worker that cannot take it: it times out
|
|
590
|
+
}
|
|
591
|
+
})));
|
|
592
|
+
const sum = () => ({ count: 0, bytes: 0, maximum: 0 });
|
|
593
|
+
const wasm = { ...sum(), shared: sum(), byLabel: {} };
|
|
594
|
+
let heapUsed = null;
|
|
595
|
+
for (const w of workers) {
|
|
596
|
+
if (w.heap)
|
|
597
|
+
heapUsed = (heapUsed ?? 0) + w.heap.used;
|
|
598
|
+
for (const m of w.memories) {
|
|
599
|
+
if (m.origin === "import")
|
|
600
|
+
continue;
|
|
601
|
+
for (const s of [wasm, ...(m.shared ? [wasm.shared] : []), (wasm.byLabel[m.label ?? "?"] ??= sum())]) {
|
|
602
|
+
s.count++;
|
|
603
|
+
s.bytes += m.bytes;
|
|
604
|
+
s.maximum += m.maximum ?? m.bytes;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
const pm = globalThis.performance?.memory;
|
|
609
|
+
return {
|
|
610
|
+
at,
|
|
611
|
+
page: { heap: pm ? { used: pm.usedJSHeapSize, total: pm.totalJSHeapSize, limit: pm.jsHeapSizeLimit } : null },
|
|
612
|
+
workers,
|
|
613
|
+
totals: { workers: workers.length, stuck: workers.filter((w) => w.stuck).length, heapUsed, buffers: workers.reduce((n, w) => n + w.buffers.ctl + w.buffers.sessions, 0), wasm },
|
|
614
|
+
};
|
|
615
|
+
}
|
|
368
616
|
/** @internal Terminates a Worker and ends its session. */
|
|
369
617
|
_retire(w) {
|
|
370
618
|
this.#retire(w);
|
|
@@ -375,31 +623,138 @@ export class HostExecController {
|
|
|
375
623
|
w.dead = true;
|
|
376
624
|
w.abort?.();
|
|
377
625
|
this.#workers.delete(w);
|
|
626
|
+
if (w.stop) {
|
|
627
|
+
Atomics.store(w.stop, 0, 1);
|
|
628
|
+
Atomics.notify(w.stop, 0);
|
|
629
|
+
}
|
|
378
630
|
w.w.terminate();
|
|
379
631
|
w.session.close();
|
|
380
632
|
for (const s of w.shares)
|
|
381
633
|
s.close();
|
|
382
|
-
if (w.netId)
|
|
634
|
+
if (w.netId) {
|
|
635
|
+
// Its listens end now, as a process's death closes its sockets: the port is free for the next process (nodemon's
|
|
636
|
+
// restart), where the net Worker would keep them for its second's grace (closeHostSocketSoon) without the
|
|
637
|
+
// process's bye, which a killed Worker never sends. Its connections get that second for what it sent last.
|
|
638
|
+
for (const l of w.listens?.values() ?? [])
|
|
639
|
+
this.#backend.hostNet?.unlisten?.(w.netId, l.port);
|
|
383
640
|
this.#backend.hostNet?.close(w.netId);
|
|
641
|
+
}
|
|
384
642
|
for (const l of w.listens?.values() ?? [])
|
|
385
643
|
if (l.guest !== null)
|
|
386
644
|
this.#backend.hostListen?.unlisten(l.guest);
|
|
387
645
|
w.listens?.clear();
|
|
388
646
|
this.#unixGone(w);
|
|
647
|
+
this.#udp.gone(w);
|
|
389
648
|
for (const t of w.threads?.values() ?? [])
|
|
390
649
|
this.#retire(t);
|
|
391
650
|
w.threads?.clear();
|
|
651
|
+
if (w.root && w.root.tids?.get(w.tid) === w)
|
|
652
|
+
w.root.tids.delete(w.tid);
|
|
653
|
+
this.#unreserve(w);
|
|
392
654
|
w.onRetire?.();
|
|
393
655
|
}
|
|
656
|
+
// ---- memory (T258): processes that declare theirs share memoryBudgetMB ----
|
|
657
|
+
// A small one (SPARE_MB at most) that the budget has no room for starts in memoryReserveMB if that has room (T340:
|
|
658
|
+
// psql waited for good next to postgres, which holds more than a phone's budget alone).
|
|
659
|
+
#reserve(rec, asked, what) {
|
|
660
|
+
if (rec.dead)
|
|
661
|
+
return;
|
|
662
|
+
const mb = Math.max(0, Math.ceil(Number(asked) || 0));
|
|
663
|
+
this.#unreserve(rec, false);
|
|
664
|
+
const grant = (spare) => {
|
|
665
|
+
const over = !spare && this.#memUsed + mb > this.#memBudget;
|
|
666
|
+
if (over)
|
|
667
|
+
this.#log("warn", `host-exec: ${what} takes ${mb} MB, more than hostExec.memoryBudgetMB (${this.#memBudget}) leaves; nothing else holds any`);
|
|
668
|
+
rec.memoryMB = mb;
|
|
669
|
+
if (spare) {
|
|
670
|
+
this.#spareUsed += mb;
|
|
671
|
+
this.#spareHeld.add(rec);
|
|
672
|
+
}
|
|
673
|
+
else {
|
|
674
|
+
this.#memUsed += mb;
|
|
675
|
+
this.#memHeld.add(rec);
|
|
676
|
+
}
|
|
677
|
+
writeCtl(rec.ctl, over ? { granted: true, over: true } : { granted: true });
|
|
678
|
+
};
|
|
679
|
+
const fits = () => this.#memUsed + mb <= this.#memBudget || this.#memHeld.size === 0;
|
|
680
|
+
const fitsSpare = () => mb <= SPARE_MB && this.#spareUsed + mb <= this.#memSpare;
|
|
681
|
+
if (!this.#memQueue.length && fits())
|
|
682
|
+
return grant(false);
|
|
683
|
+
if (fitsSpare())
|
|
684
|
+
return grant(true);
|
|
685
|
+
const wait = this.#o.memoryWaitMs ?? 120_000;
|
|
686
|
+
const timer = setTimeout(() => {
|
|
687
|
+
const i = this.#memQueue.findIndex((q) => q.rec === rec);
|
|
688
|
+
if (i < 0)
|
|
689
|
+
return;
|
|
690
|
+
this.#memQueue.splice(i, 1);
|
|
691
|
+
const spare = mb <= SPARE_MB && this.#memSpare > 0 ? `, and the ${this.#memSpare} MB kept for small ones (hostExec.memoryReserveMB): ${this.#spareUsed} MB by ${this.#spareHeld.size}` : "";
|
|
692
|
+
writeCtl(rec.ctl, { error: `${what} needs ${mb} MB of host memory, and host processes' ${this.#memBudget} MB (hostExec.memoryBudgetMB) were taken for ${Math.round(wait / 1000)} s: ${this.#memUsed} MB by ${this.#memHeld.size} other process${this.#memHeld.size === 1 ? "" : "es"}${spare}` });
|
|
693
|
+
this.#pumpMemory();
|
|
694
|
+
}, wait);
|
|
695
|
+
this.#memQueue.push({ rec, fits, fitsSpare, grant, timer });
|
|
696
|
+
}
|
|
697
|
+
#unreserve(w, pump = true) {
|
|
698
|
+
const i = this.#memQueue.findIndex((q) => q.rec === w);
|
|
699
|
+
if (i >= 0)
|
|
700
|
+
clearTimeout(this.#memQueue.splice(i, 1)[0].timer);
|
|
701
|
+
if (this.#memHeld.delete(w))
|
|
702
|
+
this.#memUsed -= w.memoryMB ?? 0;
|
|
703
|
+
if (this.#spareHeld.delete(w))
|
|
704
|
+
this.#spareUsed -= w.memoryMB ?? 0;
|
|
705
|
+
w.memoryMB = 0;
|
|
706
|
+
if (pump)
|
|
707
|
+
this.#pumpMemory();
|
|
708
|
+
}
|
|
709
|
+
#pumpMemory() {
|
|
710
|
+
// The budget's waiting reserves first come first served, then small ones further back into memoryReserveMB.
|
|
711
|
+
while (this.#memQueue.length && this.#memQueue[0].fits()) {
|
|
712
|
+
const q = this.#memQueue.shift();
|
|
713
|
+
clearTimeout(q.timer);
|
|
714
|
+
q.grant(false);
|
|
715
|
+
}
|
|
716
|
+
for (const q of [...this.#memQueue]) {
|
|
717
|
+
if (!q.fitsSpare())
|
|
718
|
+
continue;
|
|
719
|
+
this.#memQueue.splice(this.#memQueue.indexOf(q), 1);
|
|
720
|
+
clearTimeout(q.timer);
|
|
721
|
+
q.grant(true);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
394
724
|
#fill() {
|
|
395
|
-
|
|
396
|
-
while (this.#enabled && !this.#disposed && this.#warm.length < pool) {
|
|
725
|
+
while (this.#enabled && !this.#disposed && this.#warm.length < this.#poolTarget) {
|
|
397
726
|
const p = this.#boot();
|
|
398
|
-
p.
|
|
727
|
+
p.then(() => this.#ready.add(p), () => { });
|
|
399
728
|
this.#warm.push(p);
|
|
400
729
|
}
|
|
401
730
|
}
|
|
402
|
-
|
|
731
|
+
/**
|
|
732
|
+
* A take found no booted Worker: processes start faster than one boots (npm scripts, test workers). The pool keeps
|
|
733
|
+
* poolBurst for POOL_BURST_MS after the last miss, as far as the memory budget leaves room for idle Workers.
|
|
734
|
+
*/
|
|
735
|
+
#burst() {
|
|
736
|
+
const pool = this.#o.pool ?? 1;
|
|
737
|
+
const burst = this.#o.poolBurst ?? (pool === 0 ? 0 : constrainedDevice() ? 2 : 3);
|
|
738
|
+
const room = Math.floor((this.#memBudget - this.#memUsed) / IDLE_WORKER_MB);
|
|
739
|
+
const target = Math.max(pool, Math.min(burst, room, this.#max - 1));
|
|
740
|
+
if (target <= pool || this.#disposed)
|
|
741
|
+
return;
|
|
742
|
+
this.#poolTarget = target;
|
|
743
|
+
if (this.#burstTimer)
|
|
744
|
+
clearTimeout(this.#burstTimer);
|
|
745
|
+
this.#burstTimer = setTimeout(() => {
|
|
746
|
+
this.#burstTimer = null;
|
|
747
|
+
this.#poolTarget = pool;
|
|
748
|
+
// The idle Workers past the pool end now (booting ones once booted).
|
|
749
|
+
for (const p of this.#warm.splice(pool))
|
|
750
|
+
void p.then((w) => this.#retire(w), () => { });
|
|
751
|
+
}, this.#o.poolBurstMs ?? POOL_BURST_MS);
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* A booted Worker: a host node one, else (wasi) one of host-exec's wasi-worker.js next to it, for a wasm child (T244):
|
|
755
|
+
* the same sessions and tree, no node lib, net or pool.
|
|
756
|
+
*/
|
|
757
|
+
async #boot(identity = this._identity(), thread, wasi = false, net = !wasi) {
|
|
403
758
|
const sessions = this.#sessions;
|
|
404
759
|
const client = `h${++this.#clients}`;
|
|
405
760
|
const opened = [sessions.open(client, identity), ...(sessions.shares ?? []).map((s) => s.open(client, identity))];
|
|
@@ -407,7 +762,7 @@ export class HostExecController {
|
|
|
407
762
|
let tree;
|
|
408
763
|
let sources;
|
|
409
764
|
try {
|
|
410
|
-
[all, tree, sources] = await Promise.all([Promise.all(opened), this.#loadTree(), this.#loadSources()]);
|
|
765
|
+
[all, tree, sources] = await Promise.all([Promise.all(opened), this.#loadTree(), wasi ? undefined : this.#loadSources()]);
|
|
411
766
|
}
|
|
412
767
|
catch (e) {
|
|
413
768
|
for (const p of opened)
|
|
@@ -420,9 +775,14 @@ export class HostExecController {
|
|
|
420
775
|
s.close();
|
|
421
776
|
throw new WebPodError("DISPOSED", "pod has been disposed");
|
|
422
777
|
}
|
|
423
|
-
const url = this.#o.workerUrl;
|
|
778
|
+
const url = wasi ? wasiWorkerUrl(this.#o.workerUrl) : this.#o.workerUrl;
|
|
424
779
|
const w = (this.#o.createWorker ?? ((u) => new Worker(u)))(url);
|
|
425
|
-
|
|
780
|
+
// (a wasi Worker's ctl answers a reserve only, T258: its error says why, in a few hundred bytes)
|
|
781
|
+
const rec = { w, session, shares: shareSessions, identity, ctl: newCtl(SYNC_HEADER + (wasi ? 4096 : (this.#o.syncBufferBytes ?? 16 << 20))), dead: false };
|
|
782
|
+
if (wasi)
|
|
783
|
+
rec.stop = new Int32Array(new SharedArrayBuffer(4));
|
|
784
|
+
// (the Modules its boot hands over: a start gives it the ones compiled after, _startFields)
|
|
785
|
+
rec.modules = new Set(Object.keys(this.#wasmModules));
|
|
426
786
|
// One of its 9P sessions failed in the FS Worker: the process ends (exit 70), the Worker is retired.
|
|
427
787
|
for (const s of all)
|
|
428
788
|
s.onerror = (message) => {
|
|
@@ -460,12 +820,12 @@ export class HostExecController {
|
|
|
460
820
|
const { memory, req, rep, gen, eventSeq, quiet, append } = s;
|
|
461
821
|
return { prefix, session: { memory, req, rep, ...(gen !== undefined ? { gen } : {}), ...(eventSeq !== undefined ? { eventSeq } : {}), ...(quiet !== undefined ? { quiet } : {}), ...(append ? { append } : {}) }, ...(s.events ? { events: s.events } : {}) };
|
|
462
822
|
};
|
|
463
|
-
let
|
|
464
|
-
if (this.#backend.hostNet) {
|
|
823
|
+
let netPort;
|
|
824
|
+
if (this.#backend.hostNet && net) {
|
|
465
825
|
const ch = new MessageChannel();
|
|
466
826
|
this.#backend.hostNet.open(client, ch.port1);
|
|
467
827
|
rec.netId = client;
|
|
468
|
-
|
|
828
|
+
netPort = ch.port2;
|
|
469
829
|
}
|
|
470
830
|
w.postMessage({
|
|
471
831
|
type: "boot",
|
|
@@ -474,12 +834,19 @@ export class HostExecController {
|
|
|
474
834
|
wasmModules: { ...this.#wasmModules },
|
|
475
835
|
ctl: rec.ctl,
|
|
476
836
|
pids: this.#pids,
|
|
837
|
+
cpus: this.#cpus,
|
|
838
|
+
// It answers reserve (T258).
|
|
839
|
+
memory: true,
|
|
840
|
+
...(this.#backend.hostNet?.guestInterface ? { ifaces: [this.#backend.hostNet.guestInterface()] } : {}),
|
|
477
841
|
...(tree ? { tree } : {}),
|
|
478
842
|
...(sources ? { sources } : {}),
|
|
479
|
-
...(
|
|
480
|
-
|
|
843
|
+
...(netPort ? { net: netPort } : {}),
|
|
844
|
+
// msize: what the sessions' rings take (a ring's largest message is half of it, less 4: 1 MiB rings, T354)
|
|
845
|
+
options: { ...this.#o.workerOptions, msize: Math.min(Number(this.#o.workerOptions?.msize ?? DEFAULT_MSIZE), ...[session, ...shareSessions].map((s) => ringMessageMax(s.memory, s.req))) },
|
|
481
846
|
...(thread ? { thread } : {}),
|
|
482
|
-
|
|
847
|
+
...(wasi ? {} : { wasi: true }),
|
|
848
|
+
...(rec.stop ? { stop: rec.stop.buffer } : {}),
|
|
849
|
+
}, [...(netPort ? [netPort] : []), ...all.flatMap((s) => (s.events ? [s.events] : []))]);
|
|
483
850
|
try {
|
|
484
851
|
await booted;
|
|
485
852
|
}
|
|
@@ -489,8 +856,58 @@ export class HostExecController {
|
|
|
489
856
|
}
|
|
490
857
|
if (this.#shim)
|
|
491
858
|
this.#setHostOk(true);
|
|
859
|
+
this.#fetchChunksAhead();
|
|
492
860
|
return rec;
|
|
493
861
|
}
|
|
862
|
+
/**
|
|
863
|
+
* host-node.js's chunks (HOST_CHUNKS), fetched once the first Worker has booted and the page is idle, so a process
|
|
864
|
+
* that first needs one later (offline too) has it from the page: what host-node.js carried before (T291). Not on
|
|
865
|
+
* constrained devices: there each is fetched when a process first asks for it.
|
|
866
|
+
*/
|
|
867
|
+
#fetchChunksAhead() {
|
|
868
|
+
if (this.#chunksAhead || constrainedDevice())
|
|
869
|
+
return;
|
|
870
|
+
this.#chunksAhead = true;
|
|
871
|
+
this.#chunksTimer = setTimeout(() => {
|
|
872
|
+
this.#chunksTimer = null;
|
|
873
|
+
const fetchAll = () => {
|
|
874
|
+
if (!this.#disposed)
|
|
875
|
+
for (const name of HOST_CHUNKS)
|
|
876
|
+
this.#asset(name).catch(() => { });
|
|
877
|
+
};
|
|
878
|
+
const g = globalThis;
|
|
879
|
+
if (g.requestIdleCallback)
|
|
880
|
+
g.requestIdleCallback(fetchAll, { timeout: 10_000 });
|
|
881
|
+
else
|
|
882
|
+
fetchAll();
|
|
883
|
+
}, this.#o.chunksAheadMs ?? CHUNKS_AHEAD_MS);
|
|
884
|
+
}
|
|
885
|
+
/** An asset file next to the Worker: only HOST_ASSETS' names, never a URL of the process's. */
|
|
886
|
+
#asset(name) {
|
|
887
|
+
if (!HOST_ASSETS.includes(name))
|
|
888
|
+
return Promise.reject(new Error("not an asset of host-exec's"));
|
|
889
|
+
let p = this.#assets.get(name);
|
|
890
|
+
if (!p) {
|
|
891
|
+
p = (async () => {
|
|
892
|
+
// Its URL in the error: a deployment that left the file out says which (the log's warning, the process's).
|
|
893
|
+
const url = new URL(name, new URL(this.#o.workerUrl, globalThis.location?.href)).href;
|
|
894
|
+
let res;
|
|
895
|
+
try {
|
|
896
|
+
res = await fetch(url);
|
|
897
|
+
}
|
|
898
|
+
catch (e) {
|
|
899
|
+
throw new Error(`${url}: ${e.message}`);
|
|
900
|
+
}
|
|
901
|
+
if (!res.ok)
|
|
902
|
+
throw new Error(`${url}: HTTP ${res.status}`);
|
|
903
|
+
return new Uint8Array(await res.arrayBuffer());
|
|
904
|
+
})();
|
|
905
|
+
// A failed request is tried again by the next process that asks.
|
|
906
|
+
p.catch(() => this.#assets.delete(name));
|
|
907
|
+
this.#assets.set(name, p);
|
|
908
|
+
}
|
|
909
|
+
return p;
|
|
910
|
+
}
|
|
494
911
|
#loadTree() {
|
|
495
912
|
const t = this.#o.tree;
|
|
496
913
|
if (t !== undefined && typeof t !== "string")
|
|
@@ -545,7 +962,10 @@ export class HostExecController {
|
|
|
545
962
|
#onWorker(rec, m) {
|
|
546
963
|
switch (m.type) {
|
|
547
964
|
case "spawn":
|
|
548
|
-
|
|
965
|
+
this.#starting.set(m.pid, rec);
|
|
966
|
+
return void this.#child(m, m.port, rec)
|
|
967
|
+
.catch((e) => this.#log("warn", `host-exec: spawn ${m.argv.join(" ")}: ${e.message}`))
|
|
968
|
+
.finally(() => this.#starting.delete(m.pid));
|
|
549
969
|
case "spawnSync":
|
|
550
970
|
return this.#spawnSync(m, rec);
|
|
551
971
|
case "reap":
|
|
@@ -558,9 +978,23 @@ export class HostExecController {
|
|
|
558
978
|
this.#gone.add(m.pid);
|
|
559
979
|
return;
|
|
560
980
|
}
|
|
981
|
+
case "kill-pid":
|
|
982
|
+
return void this.#killPid(m, rec).then((errno) => writeCtl(rec.ctl, { errno }));
|
|
983
|
+
case "guest-which":
|
|
984
|
+
return void this.#guestWhich(m.candidates).then((found) => writeCtl(rec.ctl, { found }));
|
|
985
|
+
case "reserve":
|
|
986
|
+
return this.#reserve(rec, m.mb, m.what ?? "a host process");
|
|
561
987
|
case "wasm-module":
|
|
562
988
|
this.#wasmModules[m.key] = m.module;
|
|
989
|
+
(rec.modules ??= new Set()).add(m.key);
|
|
990
|
+
return;
|
|
991
|
+
case "mem": {
|
|
992
|
+
const mem = (rec.mem ??= { last: null, waiting: new Map() });
|
|
993
|
+
mem.last = { at: Date.now(), report: m.report };
|
|
994
|
+
mem.waiting.get(m.id)?.(m.report);
|
|
995
|
+
mem.waiting.delete(m.id);
|
|
563
996
|
return;
|
|
997
|
+
}
|
|
564
998
|
case "trace":
|
|
565
999
|
// WEBPOD_HOST_DIAG's traces are for someone looking into a stuck process: shown as warnings.
|
|
566
1000
|
return this.#log(m.text.startsWith("diag ") ? "warn" : "debug", `host-exec [${m.pid}] ${m.text}`);
|
|
@@ -572,7 +1006,7 @@ export class HostExecController {
|
|
|
572
1006
|
case "unlisten":
|
|
573
1007
|
return this.#unlisten(rec, m.req);
|
|
574
1008
|
case "unix-listen":
|
|
575
|
-
return writeCtl(rec.ctl, this.#unixListen(rec, m.key));
|
|
1009
|
+
return void writeCtl(rec.ctl, this.#unixListen(rec, m.key));
|
|
576
1010
|
case "unix-unlisten":
|
|
577
1011
|
for (const [key, l] of this.#unixListeners)
|
|
578
1012
|
if (l.rec === rec && l.req === m.req)
|
|
@@ -583,15 +1017,52 @@ export class HostExecController {
|
|
|
583
1017
|
case "unix-close":
|
|
584
1018
|
this.#unixConns.delete(m.cid);
|
|
585
1019
|
return;
|
|
1020
|
+
case "udp-bind":
|
|
1021
|
+
return void writeCtl(rec.ctl, this.#udp.bind(rec, m));
|
|
1022
|
+
case "udp-close":
|
|
1023
|
+
return this.#udp.close(rec, m.sid);
|
|
1024
|
+
case "udp-send": {
|
|
1025
|
+
const r = this.#udp.route(rec, m);
|
|
1026
|
+
if (r && !r[0].dead)
|
|
1027
|
+
r[0].w.postMessage(r[1], [r[1].data.buffer]);
|
|
1028
|
+
return;
|
|
1029
|
+
}
|
|
586
1030
|
case "thread":
|
|
587
1031
|
return void this.#thread(rec, m).catch((e) => this.#log("warn", `host-exec: thread ${m.tid} of ${rec.pid}: ${e.message}`));
|
|
1032
|
+
case "wasix-thread":
|
|
1033
|
+
return void this.#wasixThread(rec, m).catch((e) => this.#log("warn", `host-exec: the wasm thread of ${rec.pid}: ${e.message}`));
|
|
1034
|
+
case "signals":
|
|
1035
|
+
rec.handled = new Set(m.signals);
|
|
1036
|
+
return rec.report?.(m);
|
|
588
1037
|
case "thread-end": {
|
|
589
1038
|
const t = rec.threads?.get(m.tid);
|
|
1039
|
+
// (terminate() right after new Worker(): its Worker still boots; it would start and hold a maxThreads slot)
|
|
1040
|
+
if (!t) {
|
|
1041
|
+
(rec.endedThreads ??= new Set()).add(m.tid);
|
|
1042
|
+
return;
|
|
1043
|
+
}
|
|
1044
|
+
// terminate() (or its process's end): at once, as node's; its own end: once what was sent to it is done (a WASIX
|
|
1045
|
+
// program's wasm thread at once: it relays nothing).
|
|
1046
|
+
if (!m.terminated && !t.wasix)
|
|
1047
|
+
return this.#endThread(rec, m.tid, t);
|
|
590
1048
|
rec.threads?.delete(m.tid);
|
|
591
|
-
|
|
592
|
-
this.#retire(t);
|
|
593
|
-
return;
|
|
1049
|
+
return this.#retire(t);
|
|
594
1050
|
}
|
|
1051
|
+
case "drained":
|
|
1052
|
+
return rec.ending?.();
|
|
1053
|
+
case "relay":
|
|
1054
|
+
return this.#relay(rec, m.tid, m.msg, m.transfer);
|
|
1055
|
+
case "crypto":
|
|
1056
|
+
// A result that does not fit in ctl (an AES-GCM of megabytes) is NotSupportedError: the process falls back.
|
|
1057
|
+
return void this.#webcrypto(m.calls)
|
|
1058
|
+
.catch((e) => ({ error: { name: "OperationError", message: String(e?.message ?? e) } }))
|
|
1059
|
+
.then((r) => writeCtl(rec.ctl, r) || writeCtl(rec.ctl, { error: { name: "NotSupportedError", message: "a WebCrypto result larger than hostExec.syncBufferBytes" } }));
|
|
1060
|
+
case "asset":
|
|
1061
|
+
// Without the file (a build without it, a failed request) the binding that asked falls back.
|
|
1062
|
+
return void this.#asset(m.name).then((bytes) => writeAsset(rec.ctl, { size: bytes.length }, bytes) || writeAsset(rec.ctl, { error: `${m.name} is larger than hostExec.syncBufferBytes` }), (e) => {
|
|
1063
|
+
this.#log("warn", `host-exec: ${m.name}: ${e.message}`);
|
|
1064
|
+
writeAsset(rec.ctl, { error: e.message });
|
|
1065
|
+
});
|
|
595
1066
|
default:
|
|
596
1067
|
rec.report?.(m);
|
|
597
1068
|
}
|
|
@@ -700,14 +1171,75 @@ export class HostExecController {
|
|
|
700
1171
|
if (l.guest !== null)
|
|
701
1172
|
this.#backend.hostListen?.unlisten(l.guest);
|
|
702
1173
|
}
|
|
1174
|
+
/**
|
|
1175
|
+
* A process's WebCrypto calls (host-exec's impl-crypto.js webcryptoRun, for what node does synchronously), in order
|
|
1176
|
+
* on the page's crypto.subtle while the process waits on ctl. Only SubtleCrypto's key and cipher operations; the keys
|
|
1177
|
+
* stay here. Imported keys are kept: jsonwebtoken signs with the same key every time, and importing an RSA key costs
|
|
1178
|
+
* about half as much as a signature.
|
|
1179
|
+
*/
|
|
1180
|
+
async #webcrypto(calls) {
|
|
1181
|
+
// Without WebCrypto (not a secure context) the process falls back.
|
|
1182
|
+
if (!globalThis.crypto?.subtle)
|
|
1183
|
+
return { error: { name: "NotSupportedError", message: "this page has no WebCrypto (crypto.subtle)" } };
|
|
1184
|
+
const subtle = crypto.subtle;
|
|
1185
|
+
const out = [];
|
|
1186
|
+
const arg = (a) => {
|
|
1187
|
+
if (!a || typeof a !== "object" || ArrayBuffer.isView(a) || a instanceof ArrayBuffer || Array.isArray(a) || a instanceof CryptoKey)
|
|
1188
|
+
return a;
|
|
1189
|
+
if ("ref" in a) {
|
|
1190
|
+
const { ref, part } = a;
|
|
1191
|
+
if (part !== undefined && part !== "publicKey" && part !== "privateKey")
|
|
1192
|
+
throw new TypeError(`not a key pair's half: ${part}`);
|
|
1193
|
+
return part ? out[ref][part] : out[ref];
|
|
1194
|
+
}
|
|
1195
|
+
return Object.fromEntries(Object.entries(a).map(([k, v]) => [k, arg(v)]));
|
|
1196
|
+
};
|
|
1197
|
+
const importKey = async (args) => {
|
|
1198
|
+
const [format, data, ...rest] = args;
|
|
1199
|
+
let id = `${format} ${JSON.stringify(rest)} `;
|
|
1200
|
+
if (format === "jwk")
|
|
1201
|
+
id += JSON.stringify(data);
|
|
1202
|
+
else {
|
|
1203
|
+
const u = ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data);
|
|
1204
|
+
for (let i = 0; i < u.length; i += 0x2000)
|
|
1205
|
+
id += String.fromCharCode(...u.subarray(i, i + 0x2000));
|
|
1206
|
+
}
|
|
1207
|
+
const keys = this.#importedKeys;
|
|
1208
|
+
let k = keys.get(id);
|
|
1209
|
+
if (k)
|
|
1210
|
+
keys.delete(id);
|
|
1211
|
+
else
|
|
1212
|
+
k = (await subtle.importKey(...args));
|
|
1213
|
+
keys.set(id, k);
|
|
1214
|
+
if (keys.size > 32)
|
|
1215
|
+
keys.delete(keys.keys().next().value);
|
|
1216
|
+
return k;
|
|
1217
|
+
};
|
|
1218
|
+
try {
|
|
1219
|
+
for (const c of calls) {
|
|
1220
|
+
if (!WEBCRYPTO_OPS.has(c.op))
|
|
1221
|
+
throw new TypeError(`not a WebCrypto call: ${c.op}`);
|
|
1222
|
+
const args = c.args.map(arg);
|
|
1223
|
+
out.push(await (c.op === "importKey" ? importKey(args) : subtle[c.op](...args)));
|
|
1224
|
+
}
|
|
1225
|
+
return { results: out.map((r) => (r instanceof ArrayBuffer ? { b64: base64(new Uint8Array(r)) } : typeof r === "boolean" || r?.kty ? r : null)) };
|
|
1226
|
+
}
|
|
1227
|
+
catch (e) {
|
|
1228
|
+
return { error: { name: e?.name ?? "Error", message: String(e?.message ?? e) } };
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
703
1231
|
/**
|
|
704
1232
|
* A worker_threads thread of `parent`'s process: a Worker booted as a thread, with the process's pid and its own
|
|
705
1233
|
* sessions; it ends with the process (#retire). Threads do not count against maxProcesses.
|
|
706
1234
|
*/
|
|
707
1235
|
async #thread(parent, m) {
|
|
708
|
-
// As node reports a thread that could not start: 'error' (ERR_WORKER_INIT_FAILED), then 'exit' 1.
|
|
709
|
-
|
|
710
|
-
const
|
|
1236
|
+
// As node reports a thread that could not start: 'error' (ERR_WORKER_INIT_FAILED), then 'exit' 1. Its environment
|
|
1237
|
+
// port is closed, and what its parent sent on it before the start (workerData, T246) goes now, not at a collection.
|
|
1238
|
+
const refuse = (reason) => {
|
|
1239
|
+
m.envPort.close();
|
|
1240
|
+
m.port.postMessage({ type: "exit", code: 1, error: "ERR_WORKER_INIT_FAILED", reason });
|
|
1241
|
+
};
|
|
1242
|
+
const max = this.#maxThreads;
|
|
711
1243
|
if (this.#threads >= max)
|
|
712
1244
|
return refuse(`host mode runs at most ${max} worker threads at once (hostExec.maxThreads)`);
|
|
713
1245
|
this.#threads++;
|
|
@@ -721,9 +1253,15 @@ export class HostExecController {
|
|
|
721
1253
|
throw e;
|
|
722
1254
|
}
|
|
723
1255
|
w.onRetire = () => this.#threads--;
|
|
724
|
-
|
|
1256
|
+
// (its parent gone, ending: drained, its own threads retired already; or its end came first)
|
|
1257
|
+
if (parent.dead || parent.ending || parent.endedThreads?.delete(m.tid)) {
|
|
1258
|
+
m.envPort.close();
|
|
725
1259
|
return this.#retire(w);
|
|
1260
|
+
}
|
|
726
1261
|
(parent.threads ??= new Map()).set(m.tid, w);
|
|
1262
|
+
w.tid = m.tid;
|
|
1263
|
+
w.root = parent.root ?? parent;
|
|
1264
|
+
(w.root.tids ??= new Map()).set(m.tid, w);
|
|
727
1265
|
w.pid = parent.pid;
|
|
728
1266
|
w.ppid = parent.ppid;
|
|
729
1267
|
w.report = (r) => {
|
|
@@ -734,8 +1272,114 @@ export class HostExecController {
|
|
|
734
1272
|
}
|
|
735
1273
|
};
|
|
736
1274
|
const o = this.#o;
|
|
737
|
-
const thread = { envPort: m.envPort, envBoxes: m.envBoxes, initial: m.initial ?? [], threadIds: m.threadIds, bcPrefix: m.bcPrefix, ...(m.shareEnv ? { shareEnv: m.shareEnv } : {}) };
|
|
738
|
-
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 ?? [])]);
|
|
1275
|
+
const thread = { envPort: m.envPort, envBoxes: m.envBoxes, initial: m.initial ?? [], threadIds: m.threadIds, bcPrefix: m.bcPrefix, ...(m.shareEnv ? { shareEnv: m.shareEnv } : {}), ...(m.nodeOptions !== undefined ? { nodeOptions: m.nodeOptions } : {}) };
|
|
1276
|
+
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, relay: true, ...this._startFields(w) }, [m.port, m.envPort, ...(m.initialTransfer ?? [])]);
|
|
1277
|
+
}
|
|
1278
|
+
/**
|
|
1279
|
+
* A WASIX program's wasm thread (host-exec's wasi-worker.js, T315): a wasi Worker booted with `parent`'s identity and
|
|
1280
|
+
* sessions of its own, started with the port its process sends the program on; it ends with the process (#retire) or
|
|
1281
|
+
* at its thread-end. Not a worker_threads thread: maxThreads does not count it.
|
|
1282
|
+
*/
|
|
1283
|
+
async #wasixThread(parent, m) {
|
|
1284
|
+
let w;
|
|
1285
|
+
try {
|
|
1286
|
+
w = await this.#boot(parent.identity, undefined, true);
|
|
1287
|
+
}
|
|
1288
|
+
catch (e) {
|
|
1289
|
+
m.port.postMessage({ type: "error", message: e.message });
|
|
1290
|
+
throw e;
|
|
1291
|
+
}
|
|
1292
|
+
if (parent.dead || parent.ending || parent.endedThreads?.delete(m.tid))
|
|
1293
|
+
return this.#retire(w);
|
|
1294
|
+
w.wasix = true;
|
|
1295
|
+
(parent.threads ??= new Map()).set(m.tid, w);
|
|
1296
|
+
w.pid = parent.pid;
|
|
1297
|
+
w.ppid = parent.ppid;
|
|
1298
|
+
w.report = (r) => {
|
|
1299
|
+
if (r.type === "error") {
|
|
1300
|
+
this.#log("warn", `host-exec: the wasm thread of ${parent.pid} failed: ${r.message}`);
|
|
1301
|
+
parent.threads?.delete(m.tid);
|
|
1302
|
+
this.#retire(w);
|
|
1303
|
+
}
|
|
1304
|
+
};
|
|
1305
|
+
const o = this.#o;
|
|
1306
|
+
w.w.postMessage({ type: "start", argv: [], env: {}, 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, wasixThread: true, ...this._startFields(w) }, [m.port]);
|
|
1307
|
+
}
|
|
1308
|
+
/**
|
|
1309
|
+
* A port's message to another thread of rec's process (impl-messaging.js post: Firefox delivers a SharedArrayBuffer
|
|
1310
|
+
* over a MessagePort between Workers only sometimes): to thread tid while it is there (not ending); else to the thread
|
|
1311
|
+
* the receiving end's inbox says has it now, once one has it (while the end is on its way to one, the claim there
|
|
1312
|
+
* notifies the header). Where none has it in RELAY_CLAIM_MS (or it closed, or its thread ended): back (relay-bounced,
|
|
1313
|
+
* bounced) to the thread the sending end is in, once one has it, else to rec (or the process's main thread, rec
|
|
1314
|
+
* ending), which sends it on the realm port, or on to the end where it is now, or closes its ports.
|
|
1315
|
+
*/
|
|
1316
|
+
#relay(rec, tid, msg, transfer, waited = 0, bounced = false) {
|
|
1317
|
+
const root = rec.root ?? rec;
|
|
1318
|
+
const { box, back, tag = 0, count = 0 } = msg;
|
|
1319
|
+
const at = (t) => {
|
|
1320
|
+
const w = t === 0 ? root : root.tids?.get(t);
|
|
1321
|
+
return w && !w.dead && !w.ending ? w : null;
|
|
1322
|
+
};
|
|
1323
|
+
// The thread whose a mailbox is (its header's): null for none, 0 while the end is on its way to one.
|
|
1324
|
+
const owner = (sab) => {
|
|
1325
|
+
const whose = Atomics.load(new Int32Array(sab, 0, 6), 3), t = whose - 1 - tag * count;
|
|
1326
|
+
return whose === 0 ? 0 : t >= 0 && t < count ? at(t) : null;
|
|
1327
|
+
};
|
|
1328
|
+
// Again once the end whose inbox sab is has a thread (its claim notifies the header), RELAY_CLAIM_MS at most.
|
|
1329
|
+
const later = (sab) => {
|
|
1330
|
+
const t0 = Date.now(), again = () => this.#relay(rec, -1, msg, transfer, waited + Math.max(1, Date.now() - t0), bounced);
|
|
1331
|
+
const w = waitAsync ? waitAsync(new Int32Array(sab, 0, 6), 3, 0, RELAY_CLAIM_MS - waited) : null;
|
|
1332
|
+
if (w?.async)
|
|
1333
|
+
void w.value.then(again);
|
|
1334
|
+
else if (w)
|
|
1335
|
+
again();
|
|
1336
|
+
else
|
|
1337
|
+
setTimeout(again, 5);
|
|
1338
|
+
};
|
|
1339
|
+
if (bounced) {
|
|
1340
|
+
const from = back instanceof SharedArrayBuffer ? owner(back) : null;
|
|
1341
|
+
if (from)
|
|
1342
|
+
return from.w.postMessage({ type: "relay-bounced", msg }, transfer);
|
|
1343
|
+
if (from === 0 && waited < RELAY_CLAIM_MS)
|
|
1344
|
+
return later(back);
|
|
1345
|
+
const to = rec.dead || rec.ending ? (root.dead ? null : root) : rec;
|
|
1346
|
+
return to?.w.postMessage({ type: "relay-bounced", msg }, transfer);
|
|
1347
|
+
}
|
|
1348
|
+
const to = tid >= 0 ? at(tid) : null;
|
|
1349
|
+
if (to)
|
|
1350
|
+
return to.w.postMessage({ type: "relay", msg }, transfer);
|
|
1351
|
+
if (box instanceof SharedArrayBuffer && (msg.hops ?? 0) <= 16) {
|
|
1352
|
+
const there = owner(box);
|
|
1353
|
+
if (there)
|
|
1354
|
+
return there.w.postMessage({ type: "relay", msg }, transfer);
|
|
1355
|
+
if (there === 0 && waited < RELAY_CLAIM_MS)
|
|
1356
|
+
return later(box);
|
|
1357
|
+
}
|
|
1358
|
+
this.#relay(rec, -1, msg, transfer, 0, true);
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* Thread tid of `parent`, which ended: retired once what was sent to it before is done (drain, drained), or after
|
|
1362
|
+
* RELAY_DRAIN_MS; one of parent's threads until then (retired with it). Its own threads end with it, at once.
|
|
1363
|
+
*/
|
|
1364
|
+
#endThread(parent, tid, t) {
|
|
1365
|
+
if (t.dead || t.ending)
|
|
1366
|
+
return;
|
|
1367
|
+
const retire = () => {
|
|
1368
|
+
if (parent.threads?.get(tid) === t)
|
|
1369
|
+
parent.threads.delete(tid);
|
|
1370
|
+
this.#retire(t);
|
|
1371
|
+
};
|
|
1372
|
+
t.ending = retire;
|
|
1373
|
+
for (const c of t.threads?.values() ?? [])
|
|
1374
|
+
this.#retire(c);
|
|
1375
|
+
t.threads?.clear();
|
|
1376
|
+
try {
|
|
1377
|
+
t.w.postMessage({ type: "drain" });
|
|
1378
|
+
}
|
|
1379
|
+
catch {
|
|
1380
|
+
return retire();
|
|
1381
|
+
}
|
|
1382
|
+
setTimeout(retire, RELAY_DRAIN_MS);
|
|
739
1383
|
}
|
|
740
1384
|
/** A child of a host process; `port` is its owner's end. Resolves once it is started. */
|
|
741
1385
|
async #child(spec, port, parent, force = false) {
|
|
@@ -744,7 +1388,8 @@ export class HostExecController {
|
|
|
744
1388
|
await this._acquire(force);
|
|
745
1389
|
let w;
|
|
746
1390
|
try {
|
|
747
|
-
|
|
1391
|
+
// (a wasi one's process side has the sockets of a WASIX program: T330)
|
|
1392
|
+
w = spec.runner === "wasi" ? await this.#boot(this._identity(), undefined, true, true) : await this._worker();
|
|
748
1393
|
}
|
|
749
1394
|
catch (e) {
|
|
750
1395
|
this._release();
|
|
@@ -766,17 +1411,35 @@ export class HostExecController {
|
|
|
766
1411
|
};
|
|
767
1412
|
w.pid = spec.pid;
|
|
768
1413
|
w.ppid = spec.ppid;
|
|
769
|
-
//
|
|
1414
|
+
// (its stdin its parent's, on demand: T361)
|
|
1415
|
+
if (spec.stdinDemand)
|
|
1416
|
+
w.stdinWant = parent?.stdinWant;
|
|
1417
|
+
const signal = (signum) => {
|
|
1418
|
+
if (!w.handled?.has(signum) || w.dead)
|
|
1419
|
+
return false;
|
|
1420
|
+
w.w.postMessage({ type: "signal", signal: signum });
|
|
1421
|
+
return true;
|
|
1422
|
+
};
|
|
1423
|
+
const entry = { pid: spec.pid, ppid: spec.ppid, kill: end, signal, owner: parent, ...(spec.detached ? { detached: true } : {}), ...(spec.outCredit ? { outCredit: spec.outCredit } : {}) };
|
|
1424
|
+
// A child reports on its port; what reaches the Worker itself is its end (crash or error), and a detached one's
|
|
1425
|
+
// exit, which ends it here once its parent is gone (nobody else reaps it then).
|
|
770
1426
|
w.report = (m) => {
|
|
771
1427
|
if (m.type === "error") {
|
|
772
1428
|
port.postMessage({ type: "out", fd: 2, data: te.encode(`webpod: host process failed: ${m.message}\n`) });
|
|
773
1429
|
port.postMessage({ type: "exit", code: EXIT_FALLBACK, signal: null });
|
|
774
1430
|
end();
|
|
775
1431
|
}
|
|
1432
|
+
else if (m.type === "detached-exit") {
|
|
1433
|
+
entry.exited = true;
|
|
1434
|
+
if (entry.ppid === 1)
|
|
1435
|
+
end();
|
|
1436
|
+
}
|
|
776
1437
|
};
|
|
777
|
-
this._register(
|
|
778
|
-
if (this.#gone.delete(spec.pid) || parent?.dead)
|
|
1438
|
+
this._register(entry);
|
|
1439
|
+
if (this.#gone.delete(spec.pid) || (parent?.dead && !spec.detached))
|
|
779
1440
|
return end();
|
|
1441
|
+
if (parent?.dead)
|
|
1442
|
+
entry.ppid = 1;
|
|
780
1443
|
w.w.postMessage({
|
|
781
1444
|
type: "start",
|
|
782
1445
|
argv: spec.argv,
|
|
@@ -789,8 +1452,18 @@ export class HostExecController {
|
|
|
789
1452
|
stdin: spec.stdin ?? null,
|
|
790
1453
|
port,
|
|
791
1454
|
guest: this.#guestTable,
|
|
1455
|
+
relay: true,
|
|
1456
|
+
...(spec.wasm ? { wasm: spec.wasm, ...(spec.memoryMB ? { memoryMB: spec.memoryMB, what: spec.what } : {}) } : {}),
|
|
792
1457
|
...(spec.ipc !== undefined ? { ipc: spec.ipc } : {}),
|
|
1458
|
+
...(spec.fds ? { fds: spec.fds } : {}),
|
|
1459
|
+
...(spec.detached ? { detached: true } : {}),
|
|
1460
|
+
...(spec.outCredit ? { outCredit: spec.outCredit } : {}),
|
|
1461
|
+
...(spec.signals ? { signals: spec.signals } : {}),
|
|
1462
|
+
...(spec.stdinDemand ? { stdinDemand: true } : {}),
|
|
1463
|
+
...this._startFields(w),
|
|
793
1464
|
}, [port]);
|
|
1465
|
+
if (parent?.dead)
|
|
1466
|
+
outUntaken(spec.outCredit);
|
|
794
1467
|
}
|
|
795
1468
|
/** A guest child (the agent's spawn): its stdio and exit relayed on `port`. */
|
|
796
1469
|
#guestChild(spec, port) {
|
|
@@ -808,23 +1481,59 @@ export class HostExecController {
|
|
|
808
1481
|
if (spec.stdio[0] !== "pipe")
|
|
809
1482
|
void stdin.close().catch(() => { });
|
|
810
1483
|
let stdinChain = Promise.resolve();
|
|
1484
|
+
// Its signals go to its process group (the agent's spawn makes one; agents with `kill`): what it started ends with
|
|
1485
|
+
// it too, as below a host process (a shell's children: `sh -c "cd x && node app.js"` does not exec its node).
|
|
1486
|
+
let ended = false;
|
|
1487
|
+
const signal = (sig) => {
|
|
1488
|
+
if (!ended)
|
|
1489
|
+
void this.#signalGroup(p, sig);
|
|
1490
|
+
};
|
|
1491
|
+
// Its output goes to the owner OUT_WINDOW ahead of what the owner took (out-ack, T287: a stuck owner's port took the
|
|
1492
|
+
// guest's whole output); an owner that does not say (an older host-exec) gets it as it comes.
|
|
1493
|
+
let ahead = 0, released = false;
|
|
1494
|
+
const credit = [];
|
|
1495
|
+
// Once its owner is gone (killed with it, or adopted: _killChildren), its output goes as it comes: nobody to say
|
|
1496
|
+
// it took it.
|
|
1497
|
+
const release = () => {
|
|
1498
|
+
released = true;
|
|
1499
|
+
for (const wake of credit.splice(0))
|
|
1500
|
+
wake();
|
|
1501
|
+
};
|
|
811
1502
|
port.onmessage = ({ data }) => {
|
|
812
1503
|
const x = data;
|
|
1504
|
+
// (ack: the owner's write waits until this one is the guest's, T287)
|
|
813
1505
|
if (x.type === "stdin" && x.data)
|
|
814
|
-
stdinChain = stdinChain
|
|
1506
|
+
stdinChain = stdinChain
|
|
1507
|
+
.then(() => stdin.write(x.data))
|
|
1508
|
+
.catch(() => { })
|
|
1509
|
+
.then(() => {
|
|
1510
|
+
if (x.ack && !ended)
|
|
1511
|
+
port.postMessage({ type: "stdin-ack" });
|
|
1512
|
+
});
|
|
815
1513
|
else if (x.type === "stdin-end")
|
|
816
1514
|
stdinChain = stdinChain.then(() => stdin.close()).catch(() => { });
|
|
817
1515
|
else if (x.type === "kill")
|
|
818
|
-
|
|
1516
|
+
signal(signalName(x.signal));
|
|
1517
|
+
else if (x.type === "out-ack") {
|
|
1518
|
+
ahead -= x.bytes ?? 0;
|
|
1519
|
+
for (const wake of credit.splice(0))
|
|
1520
|
+
wake();
|
|
1521
|
+
}
|
|
819
1522
|
};
|
|
820
|
-
this._register({ pid: spec.pid, ppid: spec.ppid, kill: (sig) =>
|
|
1523
|
+
this._register({ pid: spec.pid, ppid: spec.ppid, kill: (sig) => (release(), signal(sig)), untaken: release, ...(spec.detached ? { detached: true } : {}) });
|
|
1524
|
+
// An owner that acknowledges its output (outAcks) waits for its stdin writes too, once told they are acknowledged.
|
|
1525
|
+
if (spec.outAcks)
|
|
1526
|
+
port.postMessage({ type: "acks" });
|
|
821
1527
|
if (this.#gone.delete(spec.pid))
|
|
822
|
-
|
|
1528
|
+
signal("SIGKILL");
|
|
823
1529
|
const pump = async (s, fd) => {
|
|
824
1530
|
for (const reader = s.getReader();;) {
|
|
1531
|
+
while (spec.outAcks && ahead >= OUT_WINDOW && !released)
|
|
1532
|
+
await new Promise((r) => credit.push(r));
|
|
825
1533
|
const { done, value } = await reader.read();
|
|
826
1534
|
if (done)
|
|
827
1535
|
return;
|
|
1536
|
+
ahead += value.length;
|
|
828
1537
|
port.postMessage({ type: "out", fd, data: value });
|
|
829
1538
|
}
|
|
830
1539
|
};
|
|
@@ -833,17 +1542,106 @@ export class HostExecController {
|
|
|
833
1542
|
.then(async (st) => {
|
|
834
1543
|
await outs;
|
|
835
1544
|
port.postMessage({ type: "exit", code: st.code, signal: st.signal });
|
|
836
|
-
},
|
|
837
|
-
|
|
838
|
-
|
|
1545
|
+
}, (e) => {
|
|
1546
|
+
release();
|
|
1547
|
+
// The agent restarted: the session that ran it killed it.
|
|
1548
|
+
if (e instanceof WebPodError && e.code === "AGENT_RESTARTED")
|
|
1549
|
+
return void port.postMessage({ type: "exit", code: null, signal: "SIGKILL" });
|
|
1550
|
+
// It never started: its output may never end.
|
|
839
1551
|
port.postMessage({ type: "out", fd: 2, data: te.encode(`webpod: ${spec.file}: ${e.message}\n`) });
|
|
840
1552
|
port.postMessage({ type: "exit", code: 127, signal: null });
|
|
841
1553
|
})
|
|
842
1554
|
.finally(() => {
|
|
1555
|
+
ended = true;
|
|
843
1556
|
this._unregister(spec.pid);
|
|
844
1557
|
port.close();
|
|
845
1558
|
});
|
|
846
1559
|
}
|
|
1560
|
+
/**
|
|
1561
|
+
* process.kill of a pid that is not the caller's child, answered as kill(2) (0 or an errno): one of this table (a host
|
|
1562
|
+
* process, a guest child by its host pid: its group; -pid as pid), one being started (killed once it is, #gone), else
|
|
1563
|
+
* the guest's below the host pids (kill(2) there with the caller's uid: its Worker's identity, not one the Worker
|
|
1564
|
+
* could name; agents with `kill`, else 0 as before), or none (ESRCH). -1 (every process the caller may signal) would
|
|
1565
|
+
* reach the pod's agent and shims: EPERM. A signal number Linux has not (above 64) is EINVAL, as kill(2)'s.
|
|
1566
|
+
*/
|
|
1567
|
+
async #killPid(m, caller) {
|
|
1568
|
+
if (!Number.isInteger(m.signum) || m.signum < 0 || m.signum > 64)
|
|
1569
|
+
return EINVAL;
|
|
1570
|
+
if (m.pid === -1)
|
|
1571
|
+
return EPERM;
|
|
1572
|
+
const pid = Math.abs(m.pid);
|
|
1573
|
+
const e = this.#table.get(pid);
|
|
1574
|
+
// (a spawnSync's child, its Worker up or not: its parent waits in the spawnSync, which gets its end)
|
|
1575
|
+
const sync = this.#syncKills.get(pid);
|
|
1576
|
+
if (e || sync) {
|
|
1577
|
+
if (m.signal) {
|
|
1578
|
+
// (a host child with a handler for it takes it there, T347; else its default action, its end)
|
|
1579
|
+
if (e?.signal?.(m.signum))
|
|
1580
|
+
return 0;
|
|
1581
|
+
if (sync?.(m.signal) || !e)
|
|
1582
|
+
return 0;
|
|
1583
|
+
e.kill(signalName(m.signal));
|
|
1584
|
+
if (e.owner && !e.owner.dead)
|
|
1585
|
+
e.owner.w.postMessage({ type: "child-exit", pid, signal: m.signal });
|
|
1586
|
+
}
|
|
1587
|
+
return 0;
|
|
1588
|
+
}
|
|
1589
|
+
const parent = this.#starting.get(pid);
|
|
1590
|
+
if (parent) {
|
|
1591
|
+
// Killed or reaped before its Worker was up: gone, as its parent saw it end.
|
|
1592
|
+
if (this.#gone.has(pid))
|
|
1593
|
+
return ESRCH;
|
|
1594
|
+
if (m.signal) {
|
|
1595
|
+
// Ended once it is up (#gone); its parent is told now, as of a table's process.
|
|
1596
|
+
this.#gone.add(pid);
|
|
1597
|
+
if (!parent.dead)
|
|
1598
|
+
parent.w.postMessage({ type: "child-exit", pid, signal: m.signal });
|
|
1599
|
+
}
|
|
1600
|
+
return 0;
|
|
1601
|
+
}
|
|
1602
|
+
const killPid = this.#backend.killPid;
|
|
1603
|
+
if (pid >= this.#pidBase)
|
|
1604
|
+
return ESRCH;
|
|
1605
|
+
if (!killPid)
|
|
1606
|
+
return 0;
|
|
1607
|
+
return killPid(m.pid, m.signum, caller.identity?.uid ?? 0).catch(() => ESRCH);
|
|
1608
|
+
}
|
|
1609
|
+
/**
|
|
1610
|
+
* Whether the guest has a program at one of `candidates` (a file with an x bit, as execvp looks). A stat that fails
|
|
1611
|
+
* otherwise than ENOENT / ENOTDIR (EACCES, the agent) says yes: the guest's spawn tells then.
|
|
1612
|
+
*/
|
|
1613
|
+
async #guestWhich(candidates) {
|
|
1614
|
+
const found = await Promise.all(candidates.map((c) => this.#backend.fs.stat(c).then((st) => st.type === "file" && (st.mode & 0o111) !== 0, (e) => !["ENOENT", "ENOTDIR"].includes(e?.code ?? ""))));
|
|
1615
|
+
return found.includes(true);
|
|
1616
|
+
}
|
|
1617
|
+
/** `signal` to a guest process's group (kill(2) of -pid, with the agent's permission), else to the process. */
|
|
1618
|
+
async #signalGroup(p, signal) {
|
|
1619
|
+
const killPid = this.#backend.killPid;
|
|
1620
|
+
const pid = killPid ? await p.pid.catch(() => 0) : 0;
|
|
1621
|
+
if (killPid && pid > 0 && (await killPid(-pid, SIGNAL_NUMBERS[signal], 0).catch(() => -1)) === 0)
|
|
1622
|
+
return;
|
|
1623
|
+
await p.kill(signal).catch(() => { });
|
|
1624
|
+
}
|
|
1625
|
+
/**
|
|
1626
|
+
* The end of a killed wasm child, once none of its Workers runs it (T358): they run it holding its process's Web Lock
|
|
1627
|
+
* (shared), which this takes and keeps PROC_HOLD_MS (one that did not take it yet is gone by then); PROC_STOP_MS at
|
|
1628
|
+
* most (one that computes without a call: Chromium lets a Worker that does not return to its event loop run 2 s after
|
|
1629
|
+
* terminate()). host-exec's src/proc-lock.js names it so.
|
|
1630
|
+
*/
|
|
1631
|
+
#procStopped(pid) {
|
|
1632
|
+
const locks = globalThis.navigator?.locks;
|
|
1633
|
+
const session = this.#pids ? (Atomics.load(new Int32Array(this.#pids), 1) >>> 0).toString(16) : "";
|
|
1634
|
+
if (!locks || !session)
|
|
1635
|
+
return Promise.resolve();
|
|
1636
|
+
return new Promise((resolve) => {
|
|
1637
|
+
const cap = setTimeout(resolve, PROC_STOP_MS);
|
|
1638
|
+
const done = () => {
|
|
1639
|
+
clearTimeout(cap);
|
|
1640
|
+
resolve();
|
|
1641
|
+
};
|
|
1642
|
+
locks.request(`webpod-proc:${session}:${pid}`, () => (done(), new Promise((r) => setTimeout(r, PROC_HOLD_MS)))).catch(done);
|
|
1643
|
+
});
|
|
1644
|
+
}
|
|
847
1645
|
/** A blocking child: this table owns it and writes the result into the parent's control SAB. */
|
|
848
1646
|
#spawnSync(m, parent) {
|
|
849
1647
|
let ch = new MessageChannel();
|
|
@@ -859,6 +1657,7 @@ export class HostExecController {
|
|
|
859
1657
|
return;
|
|
860
1658
|
done = true;
|
|
861
1659
|
clearTimeout(timer);
|
|
1660
|
+
this.#syncKills.delete(m.pid);
|
|
862
1661
|
ch.port1.close();
|
|
863
1662
|
writeSync(parent.ctl, { pid: m.pid, status: signal ? null : code, signal, ...(error !== undefined ? { error } : {}), segs: [] }, segs);
|
|
864
1663
|
// A node child that exited goes with its Worker and its process slot: no parent reaps it as one does an async
|
|
@@ -866,16 +1665,27 @@ export class HostExecController {
|
|
|
866
1665
|
if (runner !== "guest")
|
|
867
1666
|
this.#table.get(m.pid)?.kill("SIGKILL");
|
|
868
1667
|
};
|
|
1668
|
+
let killed = false;
|
|
869
1669
|
const kill = (signal) => {
|
|
870
1670
|
if (runner === "guest")
|
|
871
1671
|
return ch.port1.postMessage({ type: "kill", signal });
|
|
1672
|
+
// (once: its end is under way, the result the first signal's)
|
|
1673
|
+
if (killed)
|
|
1674
|
+
return;
|
|
1675
|
+
killed = true;
|
|
872
1676
|
const e = this.#table.get(m.pid);
|
|
873
1677
|
if (e)
|
|
874
1678
|
e.kill(signalName(signal));
|
|
875
1679
|
else
|
|
876
1680
|
this.#gone.add(m.pid);
|
|
877
|
-
|
|
1681
|
+
// (a wasm child's end once nothing of it runs any more: #procStopped)
|
|
1682
|
+
if (runner === "wasi")
|
|
1683
|
+
void this.#procStopped(m.pid).then(() => finish(null, signal));
|
|
1684
|
+
else
|
|
1685
|
+
finish(null, signal);
|
|
878
1686
|
};
|
|
1687
|
+
// Another process's kill of it (#killPid): as this one's.
|
|
1688
|
+
this.#syncKills.set(m.pid, (signal) => runner !== "guest" && (kill(signal), true));
|
|
879
1689
|
// A host child that falls back (e4-integration.md §3.2): with nothing visible done yet it runs again in the guest
|
|
880
1690
|
// (its input written again; guestArgv: its own command line, before the route expanded it), else it ends with 70.
|
|
881
1691
|
// One killed or timed out meanwhile has its result already. One that read an inherited stdin (stdio[0] "inherit")
|
|
@@ -903,6 +1713,9 @@ export class HostExecController {
|
|
|
903
1713
|
const x = data;
|
|
904
1714
|
if (x.type === "fallback")
|
|
905
1715
|
return fellBack(x);
|
|
1716
|
+
// (the stdin it inherited, on demand: asked for there, its parent blocked meanwhile, T361)
|
|
1717
|
+
if (x.type === "stdin-want")
|
|
1718
|
+
return parent.stdinWant?.(x.bytes);
|
|
906
1719
|
if (x.type === "out") {
|
|
907
1720
|
const kind = m.stdio[x.fd];
|
|
908
1721
|
if (kind === "inherit")
|
|
@@ -926,7 +1739,8 @@ export class HostExecController {
|
|
|
926
1739
|
ch.port1.postMessage({ type: "stdin", data: m.input });
|
|
927
1740
|
ch.port1.postMessage({ type: "stdin-end" });
|
|
928
1741
|
}
|
|
929
|
-
else if (!stdin) {
|
|
1742
|
+
else if (!stdin && m.stdio[0] !== "ignore" && m.stdio[0] !== "inherit") {
|
|
1743
|
+
// No stdin for "ignore", nor for an inherited none: /dev/null's to a WASI program (T243).
|
|
930
1744
|
stdin = createPipe(pow2(Math.max(1 << 16, (m.input?.length ?? 0) + 1)));
|
|
931
1745
|
const w = new PipeWriter(stdin);
|
|
932
1746
|
void (m.input ? w.write(m.input) : Promise.resolve()).then(() => w.close(), () => w.close());
|
|
@@ -956,6 +1770,15 @@ export class HostExecController {
|
|
|
956
1770
|
}
|
|
957
1771
|
}
|
|
958
1772
|
const pow2 = (n) => 2 ** Math.ceil(Math.log2(n));
|
|
1773
|
+
/** host-exec's wasi-worker.js, next to its worker.js (workerUrl). */
|
|
1774
|
+
function wasiWorkerUrl(workerUrl) {
|
|
1775
|
+
try {
|
|
1776
|
+
return new URL("wasi-worker.js", new URL(workerUrl, globalThis.location?.href)).href;
|
|
1777
|
+
}
|
|
1778
|
+
catch {
|
|
1779
|
+
return workerUrl.replace(/[^/]*$/, "wasi-worker.js");
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
959
1782
|
const SOURCES = new Map();
|
|
960
1783
|
/**
|
|
961
1784
|
* node-lib.json in the form the Workers read without parsing it whole (each keeps only the modules it compiles, T106):
|
|
@@ -989,22 +1812,93 @@ async function fetchShared(url, what) {
|
|
|
989
1812
|
new Uint8Array(sab).set(bytes);
|
|
990
1813
|
return sab;
|
|
991
1814
|
}
|
|
992
|
-
|
|
1815
|
+
const WEBCRYPTO_OPS = new Set(["importKey", "exportKey", "generateKey", "sign", "verify", "encrypt", "decrypt", "deriveBits"]);
|
|
1816
|
+
function base64(u) {
|
|
1817
|
+
let s = "";
|
|
1818
|
+
for (let i = 0; i < u.length; i += 0x2000)
|
|
1819
|
+
s += String.fromCharCode(...u.subarray(i, i + 0x2000));
|
|
1820
|
+
return btoa(s);
|
|
1821
|
+
}
|
|
1822
|
+
/** host-exec's msize, where the rings take it. */
|
|
1823
|
+
const DEFAULT_MSIZE = 512 << 10;
|
|
1824
|
+
/** The largest message of the ring at `offset` of `memory` (abi's ring: half its capacity, less 4), by 64 bytes. */
|
|
1825
|
+
function ringMessageMax(memory, offset) {
|
|
1826
|
+
const cap = memory.byteLength >= offset + 16 ? Atomics.load(new Int32Array(memory, offset, 4), 2) >>> 0 : 0;
|
|
1827
|
+
return cap >= 256 && (cap & (cap - 1)) === 0 ? (cap / 2 - 4) & ~63 : Infinity;
|
|
1828
|
+
}
|
|
1829
|
+
/** What a Worker's ctl holds to start with (T354), after its header. */
|
|
1830
|
+
const CTL_BYTES = 1 << 20;
|
|
1831
|
+
/**
|
|
1832
|
+
* A Worker's ctl: CTL_BYTES, growable up to `max` for an answer that needs more (ctlRoom), where the browser has
|
|
1833
|
+
* growable SharedArrayBuffers; else all of `max`. JavaScriptCore lets a Worker make garbage in proportion to its heap and
|
|
1834
|
+
* the buffers it holds (a SharedArrayBuffer's whole length, touched or not: ctl was 16 MiB in every host Worker, T354);
|
|
1835
|
+
* a growable one counts as long as it is.
|
|
1836
|
+
*/
|
|
1837
|
+
function newCtl(max) {
|
|
1838
|
+
const start = SYNC_HEADER + CTL_BYTES;
|
|
1839
|
+
if (max <= start)
|
|
1840
|
+
return new SharedArrayBuffer(max);
|
|
1841
|
+
try {
|
|
1842
|
+
const sab = new SharedArrayBuffer(start, { maxByteLength: max });
|
|
1843
|
+
if (sab.growable && sab.maxByteLength === max)
|
|
1844
|
+
return sab;
|
|
1845
|
+
}
|
|
1846
|
+
catch {
|
|
1847
|
+
// (no growable SharedArrayBuffer here)
|
|
1848
|
+
}
|
|
1849
|
+
return new SharedArrayBuffer(max);
|
|
1850
|
+
}
|
|
1851
|
+
/** Whether ctl has room for an answer of `bytes` after its header: a growable ctl grows (by MiBs, to its maximum at most). */
|
|
1852
|
+
function ctlRoom(ctl, bytes) {
|
|
1853
|
+
const need = SYNC_HEADER + bytes, g = ctl;
|
|
1854
|
+
if (need <= ctl.byteLength)
|
|
1855
|
+
return true;
|
|
1856
|
+
if (!g.growable || !g.grow || need > (g.maxByteLength ?? 0))
|
|
1857
|
+
return false;
|
|
1858
|
+
try {
|
|
1859
|
+
g.grow(Math.min(g.maxByteLength, Math.ceil(need / CTL_BYTES) * CTL_BYTES));
|
|
1860
|
+
return true;
|
|
1861
|
+
}
|
|
1862
|
+
catch {
|
|
1863
|
+
return false;
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
/** A listen's, unix-listen's or crypto's answer, for the Worker blocked on ctl; false when it does not fit. */
|
|
993
1867
|
function writeCtl(ctl, res) {
|
|
994
1868
|
const json = te.encode(JSON.stringify(res));
|
|
1869
|
+
if (!ctlRoom(ctl, 4 + json.length))
|
|
1870
|
+
return false;
|
|
995
1871
|
new DataView(ctl).setUint32(SYNC_HEADER, json.length, true);
|
|
996
1872
|
new Uint8Array(ctl, SYNC_HEADER + 4).set(json);
|
|
997
1873
|
const i = new Int32Array(ctl, 0, 2);
|
|
998
1874
|
Atomics.store(i, 1, 4 + json.length);
|
|
999
1875
|
Atomics.store(i, 0, 1);
|
|
1000
1876
|
Atomics.notify(i, 0);
|
|
1877
|
+
return true;
|
|
1878
|
+
}
|
|
1879
|
+
/** An asset's answer, for the Worker blocked on ctl: false when its bytes do not fit. */
|
|
1880
|
+
function writeAsset(ctl, res, bytes) {
|
|
1881
|
+
const json = te.encode(JSON.stringify(res));
|
|
1882
|
+
const total = 4 + json.length + (bytes?.length ?? 0);
|
|
1883
|
+
if (!ctlRoom(ctl, total))
|
|
1884
|
+
return false;
|
|
1885
|
+
const u8 = new Uint8Array(ctl, SYNC_HEADER);
|
|
1886
|
+
new DataView(ctl).setUint32(SYNC_HEADER, json.length, true);
|
|
1887
|
+
u8.set(json, 4);
|
|
1888
|
+
if (bytes)
|
|
1889
|
+
u8.set(bytes, 4 + json.length);
|
|
1890
|
+
const i = new Int32Array(ctl, 0, 2);
|
|
1891
|
+
Atomics.store(i, 1, total);
|
|
1892
|
+
Atomics.store(i, 0, 1);
|
|
1893
|
+
Atomics.notify(i, 0);
|
|
1894
|
+
return true;
|
|
1001
1895
|
}
|
|
1002
1896
|
function writeSync(ctl, res, segs) {
|
|
1003
1897
|
let out = segs;
|
|
1004
1898
|
res.segs = out.map(([k, b]) => [k, b.length]);
|
|
1005
1899
|
let json = te.encode(JSON.stringify(res));
|
|
1006
1900
|
const total = 4 + json.length + out.reduce((t, [, b]) => t + b.length, 0);
|
|
1007
|
-
if (
|
|
1901
|
+
if (!ctlRoom(ctl, total)) {
|
|
1008
1902
|
res.error = ENOBUFS;
|
|
1009
1903
|
res.segs = [];
|
|
1010
1904
|
out = [];
|
|
@@ -1036,7 +1930,9 @@ class HostProcess {
|
|
|
1036
1930
|
#req;
|
|
1037
1931
|
#argv;
|
|
1038
1932
|
#pidValue;
|
|
1039
|
-
|
|
1933
|
+
/** Its stdout and stderr: a pipe's (T295), what the Worker wrote taken once it is read (its StartMessage.outCredit). */
|
|
1934
|
+
#out = [new ProcessOutput(), new ProcessOutput()];
|
|
1935
|
+
#credit = outCredit();
|
|
1040
1936
|
#pipe;
|
|
1041
1937
|
#writer;
|
|
1042
1938
|
#resolveExit;
|
|
@@ -1057,8 +1953,8 @@ class HostProcess {
|
|
|
1057
1953
|
const o = c._options();
|
|
1058
1954
|
this.#pipe = createPipe(o.stdinBytes ?? 1 << 16);
|
|
1059
1955
|
this.#writer = new PipeWriter(this.#pipe);
|
|
1060
|
-
this.stdout =
|
|
1061
|
-
this.stderr =
|
|
1956
|
+
this.stdout = this.#out[0].stream;
|
|
1957
|
+
this.stderr = this.#out[1].stream;
|
|
1062
1958
|
this.stdin = new WritableStream({
|
|
1063
1959
|
write: (chunk) => this.#writeStdin(chunk),
|
|
1064
1960
|
close: () => this.#closeStdin(),
|
|
@@ -1085,7 +1981,12 @@ class HostProcess {
|
|
|
1085
1981
|
w.report = (m) => this.#onReport(m);
|
|
1086
1982
|
this.#state = "running";
|
|
1087
1983
|
const o = c._options();
|
|
1088
|
-
|
|
1984
|
+
// (the pod's CA variables it has not got, as the guest's processes have them from the agent; its files: T330)
|
|
1985
|
+
const ca = c._caEnv(), own = { ...o.env, ...this.#req.env };
|
|
1986
|
+
for (const k of Object.keys(ca))
|
|
1987
|
+
if (!(k in own))
|
|
1988
|
+
env[k] = ca[k];
|
|
1989
|
+
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(), relay: true, outCredit: this.#credit, ...c._startFields(w) });
|
|
1089
1990
|
}
|
|
1090
1991
|
catch (e) {
|
|
1091
1992
|
// Nothing ran on the host: the guest runs it from the start.
|
|
@@ -1098,8 +1999,10 @@ class HostProcess {
|
|
|
1098
1999
|
#onReport(m) {
|
|
1099
2000
|
if (this.#state !== "running")
|
|
1100
2001
|
return;
|
|
1101
|
-
if (m.type === "out")
|
|
1102
|
-
|
|
2002
|
+
if (m.type === "out") {
|
|
2003
|
+
const n = m.data.length;
|
|
2004
|
+
this.#out[m.fd - 1]?.push(m.data, () => outTaken(this.#credit, n));
|
|
2005
|
+
}
|
|
1103
2006
|
else if (m.type === "exit")
|
|
1104
2007
|
this.#finish({ code: m.code, signal: m.signal ? signalName(m.signal) : null });
|
|
1105
2008
|
else if (m.type === "fallback") {
|
|
@@ -1122,7 +2025,7 @@ class HostProcess {
|
|
|
1122
2025
|
p = c._backend().spawn(this.#req);
|
|
1123
2026
|
}
|
|
1124
2027
|
catch (e) {
|
|
1125
|
-
this.#out[1]
|
|
2028
|
+
this.#out[1].push(te.encode(`webpod: ${e.message}\n`));
|
|
1126
2029
|
return this.#finish({ code: 127, signal: null });
|
|
1127
2030
|
}
|
|
1128
2031
|
this.#guest = p;
|
|
@@ -1138,7 +2041,7 @@ class HostProcess {
|
|
|
1138
2041
|
const { done, value } = await r.read();
|
|
1139
2042
|
if (done)
|
|
1140
2043
|
return;
|
|
1141
|
-
this.#out[i]
|
|
2044
|
+
await new Promise((took) => this.#out[i].push(value, took));
|
|
1142
2045
|
}
|
|
1143
2046
|
};
|
|
1144
2047
|
const outs = Promise.all([pump(p.stdout, 0), pump(p.stderr, 1)]).catch(() => { });
|
|
@@ -1146,7 +2049,7 @@ class HostProcess {
|
|
|
1146
2049
|
await outs;
|
|
1147
2050
|
this.#finish(st);
|
|
1148
2051
|
}, (e) => {
|
|
1149
|
-
this.#out[1]
|
|
2052
|
+
this.#out[1].push(te.encode(`webpod: ${e.message}\n`));
|
|
1150
2053
|
this.#finish({ code: 127, signal: null });
|
|
1151
2054
|
});
|
|
1152
2055
|
}
|
|
@@ -1154,7 +2057,7 @@ class HostProcess {
|
|
|
1154
2057
|
/** A runtime fallback after visible effects: cannot rerun (e4-integration.md §3.2). */
|
|
1155
2058
|
#fail(reason) {
|
|
1156
2059
|
this.#c._emit({ pid: this.#pidValue, argv: this.#argv, reason, rerun: false });
|
|
1157
|
-
this.#out[1]
|
|
2060
|
+
this.#out[1].push(te.encode(`webpod: ${reason}; this program needs regular node (WEBPOD_NODE=guest)\n`));
|
|
1158
2061
|
this.#finish({ code: EXIT_FALLBACK, signal: null });
|
|
1159
2062
|
}
|
|
1160
2063
|
#finish(status) {
|
|
@@ -1162,14 +2065,8 @@ class HostProcess {
|
|
|
1162
2065
|
return;
|
|
1163
2066
|
this.#state = "done";
|
|
1164
2067
|
this.#end();
|
|
1165
|
-
for (const
|
|
1166
|
-
|
|
1167
|
-
ctrl?.close();
|
|
1168
|
-
}
|
|
1169
|
-
catch {
|
|
1170
|
-
// already closed or errored
|
|
1171
|
-
}
|
|
1172
|
-
}
|
|
2068
|
+
for (const o of this.#out)
|
|
2069
|
+
o.end();
|
|
1173
2070
|
this.#writer.close();
|
|
1174
2071
|
this.#c._unregister(this.#pidValue);
|
|
1175
2072
|
this.#resolveExit(status);
|
|
@@ -1220,4 +2117,78 @@ class HostProcess {
|
|
|
1220
2117
|
// No tty on the host (pty requests run in the guest).
|
|
1221
2118
|
}
|
|
1222
2119
|
}
|
|
2120
|
+
/**
|
|
2121
|
+
* The pod's host UDP ports (host-exec's src/udp-socket.js udpPorts, the same rules): a socket bound to the wildcard or
|
|
2122
|
+
* the loopback of its family (else EADDRNOTAVAIL), port 0 an ephemeral one (Linux's 32768 to 60999), a port taken
|
|
2123
|
+
* EADDRINUSE unless both have SO_REUSEADDR; a datagram goes to the socket bound to its address before one bound to the
|
|
2124
|
+
* wildcard, the last bound of several, a dual-stack socket's IPv4 senders IPv4-mapped. A sid is its owner's only (another
|
|
2125
|
+
* Worker's close or send of it does nothing), and only the loopback is delivered to, whatever a Worker sends.
|
|
2126
|
+
*/
|
|
2127
|
+
class UdpPorts {
|
|
2128
|
+
#sockets = new Map();
|
|
2129
|
+
#next = 0;
|
|
2130
|
+
bind(owner, m) {
|
|
2131
|
+
const { family, address, reuse, v6only } = m;
|
|
2132
|
+
const bindable = family === 4 ? address === "0.0.0.0" || /^127\.\d+\.\d+\.\d+$/.test(address) : address === "::" || address === "::1";
|
|
2133
|
+
if (!bindable)
|
|
2134
|
+
return { error: -99 };
|
|
2135
|
+
let port = m.port;
|
|
2136
|
+
if (port === 0) {
|
|
2137
|
+
for (let i = 0; i < 1000 && (port === 0 || this.#taken(family, address, port, v6only, false)); i++)
|
|
2138
|
+
port = 32768 + Math.floor(Math.random() * 28232);
|
|
2139
|
+
if (this.#taken(family, address, port, v6only, false))
|
|
2140
|
+
return { error: -98 };
|
|
2141
|
+
}
|
|
2142
|
+
else if (this.#taken(family, address, port, v6only, reuse))
|
|
2143
|
+
return { error: -98 };
|
|
2144
|
+
const sid = ++this.#next;
|
|
2145
|
+
this.#sockets.set(sid, { sid, owner, family, address, port, reuse: !!reuse, v6only: !!v6only });
|
|
2146
|
+
return { sid, port };
|
|
2147
|
+
}
|
|
2148
|
+
close(owner, sid) {
|
|
2149
|
+
if (this.#sockets.get(sid)?.owner === owner)
|
|
2150
|
+
this.#sockets.delete(sid);
|
|
2151
|
+
}
|
|
2152
|
+
gone(owner) {
|
|
2153
|
+
for (const [sid, s] of this.#sockets)
|
|
2154
|
+
if (s.owner === owner)
|
|
2155
|
+
this.#sockets.delete(sid);
|
|
2156
|
+
}
|
|
2157
|
+
route(owner, m) {
|
|
2158
|
+
const from = this.#sockets.get(m.sid);
|
|
2159
|
+
if (from?.owner !== owner || !loopback(m.address))
|
|
2160
|
+
return null;
|
|
2161
|
+
const all = [...this.#sockets.values()].filter((s) => s.port === m.port && this.#takes(s, m.address));
|
|
2162
|
+
const to = all.filter((s) => !wildcard(s.address)).at(-1) ?? all.at(-1);
|
|
2163
|
+
if (!to)
|
|
2164
|
+
return null;
|
|
2165
|
+
let src = wildcard(from.address) ? (isV4(m.address) ? "127.0.0.1" : v4Part(m.address) ? "::ffff:127.0.0.1" : "::1") : from.address;
|
|
2166
|
+
if (to.family === 6 && isV4(src))
|
|
2167
|
+
src = `::ffff:${src}`;
|
|
2168
|
+
return [to.owner, { type: "udp-message", sid: to.sid, data: m.data, from: { address: src, family: to.family, port: from.port } }];
|
|
2169
|
+
}
|
|
2170
|
+
#taken(family, address, port, v6only, reuse) {
|
|
2171
|
+
for (const s of this.#sockets.values()) {
|
|
2172
|
+
if (s.port !== port || (reuse && s.reuse))
|
|
2173
|
+
continue;
|
|
2174
|
+
if (s.family === family ? s.address === address || wildcard(s.address) || wildcard(address) : s.family === 6 ? s.address === "::" && !s.v6only : address === "::" && !v6only)
|
|
2175
|
+
return true;
|
|
2176
|
+
}
|
|
2177
|
+
return false;
|
|
2178
|
+
}
|
|
2179
|
+
#takes(s, dest) {
|
|
2180
|
+
const d4 = v4Part(dest);
|
|
2181
|
+
if (s.family === 4)
|
|
2182
|
+
return d4 !== null && (s.address === d4 || s.address === "0.0.0.0");
|
|
2183
|
+
if (d4 !== null && isV4(dest))
|
|
2184
|
+
return s.address === "::" && !s.v6only;
|
|
2185
|
+
return s.address === dest || s.address === "::";
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
2188
|
+
const isV4 = (a) => !a.includes(":");
|
|
2189
|
+
/** The pod's loopback, where host processes' UDP goes (host-exec's udp-socket.js loopback). */
|
|
2190
|
+
const loopback = (a) => /^127\.\d+\.\d+\.\d+$/.test(a) || a === "::1" || /^::ffff:127\.\d+\.\d+\.\d+$/i.test(a);
|
|
2191
|
+
const wildcard = (a) => a === "0.0.0.0" || a === "::";
|
|
2192
|
+
/** An address's IPv4 part (127.0.0.1 of ::ffff:127.0.0.1), or null for IPv6. */
|
|
2193
|
+
const v4Part = (a) => (isV4(a) ? a : (/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(a)?.[1] ?? null));
|
|
1223
2194
|
//# sourceMappingURL=controller.js.map
|