@webpodjs/sdk 0.2.7 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +93 -15
  2. package/dist/agent/backend.d.ts +18 -1
  3. package/dist/agent/backend.js +275 -76
  4. package/dist/agent/backend.js.map +1 -1
  5. package/dist/agent/fs.d.ts +2 -2
  6. package/dist/agent/fs.js +3 -2
  7. package/dist/agent/fs.js.map +1 -1
  8. package/dist/agent/protocol.d.ts +40 -1
  9. package/dist/agent/protocol.js +39 -3
  10. package/dist/agent/protocol.js.map +1 -1
  11. package/dist/errors.d.ts +1 -1
  12. package/dist/errors.js.map +1 -1
  13. package/dist/exec/client.js +21 -6
  14. package/dist/exec/client.js.map +1 -1
  15. package/dist/exec/frame.js +5 -0
  16. package/dist/exec/frame.js.map +1 -1
  17. package/dist/fs/tar.d.ts +1 -1
  18. package/dist/fs/tar.js +8 -2
  19. package/dist/fs/tar.js.map +1 -1
  20. package/dist/fs/workspace.js +61 -30
  21. package/dist/fs/workspace.js.map +1 -1
  22. package/dist/host/backend.d.ts +11 -0
  23. package/dist/host/backend.js +68 -12
  24. package/dist/host/backend.js.map +1 -1
  25. package/dist/host/controller.d.ts +2 -0
  26. package/dist/host/controller.js +11 -4
  27. package/dist/host/controller.js.map +1 -1
  28. package/dist/host/devices.d.ts +19 -2
  29. package/dist/host/devices.js +37 -3
  30. package/dist/host/devices.js.map +1 -1
  31. package/dist/host-exec/controller.d.ts +153 -4
  32. package/dist/host-exec/controller.js +974 -66
  33. package/dist/host-exec/controller.js.map +1 -1
  34. package/dist/host-exec/protocol.d.ts +330 -4
  35. package/dist/host-exec/protocol.js +34 -0
  36. package/dist/host-exec/protocol.js.map +1 -1
  37. package/dist/host-exec/route.js +74 -13
  38. package/dist/host-exec/route.js.map +1 -1
  39. package/dist/host-exec/shim.d.ts +2 -2
  40. package/dist/host-exec/shim.js +69 -12
  41. package/dist/host-exec/shim.js.map +1 -1
  42. package/dist/index.d.ts +3 -1
  43. package/dist/index.js +1 -0
  44. package/dist/index.js.map +1 -1
  45. package/dist/net/client.d.ts +5 -1
  46. package/dist/net/client.js +8 -4
  47. package/dist/net/client.js.map +1 -1
  48. package/dist/net/options.d.ts +14 -0
  49. package/dist/net/options.js +1 -1
  50. package/dist/net/options.js.map +1 -1
  51. package/dist/net/preview.d.ts +15 -1
  52. package/dist/net/preview.js +24 -4
  53. package/dist/net/preview.js.map +1 -1
  54. package/dist/output.d.ts +23 -0
  55. package/dist/output.js +161 -0
  56. package/dist/output.js.map +1 -0
  57. package/dist/pod.d.ts +21 -7
  58. package/dist/pod.js +165 -29
  59. package/dist/pod.js.map +1 -1
  60. package/dist/preview-relay.js +24 -7
  61. package/dist/preview-relay.js.map +1 -1
  62. package/dist/preview-serviceworker.js +71 -8
  63. package/dist/preview-serviceworker.js.map +1 -1
  64. package/dist/tools.d.ts +77 -0
  65. package/dist/tools.js +47 -0
  66. package/dist/tools.js.map +1 -0
  67. package/dist/types.d.ts +62 -2
  68. package/dist/version.d.ts +1 -1
  69. package/dist/version.js +1 -1
  70. package/package.json +1 -1
@@ -1,22 +1,41 @@
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
10
  import { 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
- const DEFAULT_ENV = { PATH: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", HOME: "/root" };
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
+ /** The most a process may declare and still start in hostExec.memoryReserveMB (T340). */
38
+ const SPARE_MB = 64;
20
39
  /** HostExecStatus.reason in a tab of a pod whose workspace another tab holds (T265). */
21
40
  const HELD_BY_ANOTHER_TAB = "another tab of this pod holds its workspace (shareTabs), whose host sessions only that tab serves";
22
41
  const te = new TextEncoder();
@@ -29,6 +48,14 @@ const signalName = (s) => (typeof s === "string" && s in SIGNAL_NUMBERS ? s : "S
29
48
  * (PID_MAX_LIMIT), and wraps around to 300. The agent's Hello names its pid_max (`pid-max=N`).
30
49
  */
31
50
  const HOST_PID_BASE = 32768;
51
+ // The pod's CA as the agent installs it (crates/webpod-agent/src/ca.rs): its file, the profile that names the files and
52
+ // variables (SSL_CERT_FILE, SSL_CERT_DIR, CURL_CA_BUNDLE, ...), and the hash directory it makes of the system bundle.
53
+ const CA_PROFILE = "/etc/profile.d/webpod-ca.sh";
54
+ const POD_CA_FILE = "/etc/webpod/pod-ca.pem";
55
+ const CA_HASH_DIR = "/etc/webpod/certs";
56
+ // OpenSSL's default CA file in webpod's WASIX builds (their openssldir /etc/ssl, as Alpine's: CPython's ssl without
57
+ // SSL_CERT_FILE), which the agent's install leaves as the guest had it: Alpine's a link to the bundle.
58
+ const OPENSSL_CA_FILE = "/etc/ssl/cert.pem";
32
59
  /** Where host pids start: HOST_PID_BASE, or above the guest's pid_max when its agent names a larger one. */
33
60
  function hostPidBase(backend, log) {
34
61
  const agent = backend.agent;
@@ -43,26 +70,60 @@ export class HostExecController {
43
70
  #sessions;
44
71
  #o;
45
72
  #listeners = new Set();
46
- /** The pid counter host Workers share; none where there is no SharedArrayBuffer (host mode is unavailable there). */
47
- #pids = typeof SharedArrayBuffer === "function" ? new SharedArrayBuffer(4) : null;
73
+ /**
74
+ * The pid counter host Workers share ([0]), and this controller's session ([1], a random number not 0: the owner
75
+ * of a host process's file lock is in another session after a reload, its pids counted again); none where there is
76
+ * no SharedArrayBuffer (host mode is unavailable there).
77
+ */
78
+ #pids = typeof SharedArrayBuffer === "function" ? new SharedArrayBuffer(8) : null;
48
79
  #table = new Map();
49
80
  /** pids reaped or killed before their Worker was up. */
50
81
  #gone = new Set();
82
+ /** The children being started (spawn received, not in the table yet): pid -> its parent's Worker. */
83
+ #starting = new Map();
84
+ /** The first host pid (hostPidBase): any pid below is the guest's. */
85
+ #pidBase = HOST_PID_BASE;
51
86
  #queue = [];
52
87
  #warm = [];
88
+ /** The pooled Workers that have booted (a take of one that has not is a miss). */
89
+ #ready = new WeakSet();
90
+ /** The pool's size now: pool, or the burst's after a miss (until #burstTimer). */
91
+ #poolTarget = 1;
92
+ #burstTimer = null;
93
+ #lastTake = -Infinity;
94
+ #chunksAhead = false;
95
+ #chunksTimer = null;
53
96
  #workers = new Set();
54
97
  #max;
98
+ #maxThreads;
99
+ #memBudget;
100
+ /** The processes holding memory of the budget (memoryMB, a reserve granted), and the MB they hold. */
101
+ #memHeld = new Set();
102
+ #memUsed = 0;
103
+ /** memoryReserveMB, the small processes holding some of it, and the MB they hold. */
104
+ #memSpare;
105
+ #spareHeld = new Set();
106
+ #spareUsed = 0;
107
+ /** Reserves waiting, first come first served. */
108
+ #memQueue = [];
109
+ /** What host processes report as their CPUs (boot's cpus). */
110
+ #cpus;
111
+ /** The pod's CA files and variables as the guest has them (#loadCa), for host processes' starts; null: none yet. */
112
+ #ca = null;
55
113
  #status;
56
114
  #enabled;
57
115
  #live = 0;
58
116
  #threads = 0;
59
117
  #clients = 0;
118
+ #memIds = 0;
60
119
  /** The fallback tables' patterns host processes route their node children by (the image's, the learned one). */
61
120
  #guestTable = [];
62
121
  #listenReqs = 0;
63
122
  /** Unix sockets of host processes (T99): listeners by key, connections by id with the two processes' Workers. */
64
123
  #unixListeners = new Map();
65
124
  #unixConns = new Map();
125
+ /** UDP between host processes (T270): the pod's host UDP ports. */
126
+ #udp = new UdpPorts();
66
127
  #unixIds = 0;
67
128
  #tree;
68
129
  /** The guest's node shim (agents with host-exec), when host mode is on. */
@@ -71,6 +132,10 @@ export class HostExecController {
71
132
  #hostOk = null;
72
133
  /** Compiled wasm Modules the processes report (napi-wasm substitutes), handed to every Worker booted later. */
73
134
  #wasmModules = {};
135
+ /** Keys the processes' WebCrypto calls imported, by their bytes and parameters (the last 32, #webcrypto). */
136
+ #importedKeys = new Map();
137
+ /** The asset files the processes asked for (HOST_ASSETS), fetched once for the page. */
138
+ #assets = new Map();
74
139
  #disposed = false;
75
140
  /** What `enabled` was set to (applied when host processes can start: this tab took the workspace over). */
76
141
  #wanted = true;
@@ -85,8 +150,18 @@ export class HostExecController {
85
150
  this.#status = status;
86
151
  this.#enabled = status.node === "on";
87
152
  this.#max = options.maxProcesses ?? (constrainedDevice() ? 6 : 8);
88
- if (this.#pids)
89
- Atomics.store(new Int32Array(this.#pids), 0, hostPidBase(backend, (level, text) => this.#log(level, text)));
153
+ this.#maxThreads = options.maxThreads ?? 2 * this.#max;
154
+ this.#memSpare = Math.max(0, options.memoryReserveMB ?? 128);
155
+ this.#memBudget = options.memoryBudgetMB ?? (constrainedDevice() ? 768 : 2048);
156
+ this.#poolTarget = options.pool ?? 1;
157
+ // The device's cores, but only as many as the worker pools sized by them can start within the limits: jest-worker's
158
+ // cpus - 1 child processes next to jest and npm, piscina's 1.5 x cpus threads.
159
+ this.#cpus = Math.max(1, Math.min(globalThis.navigator?.hardwareConcurrency || 1, this.#max - 2, Math.floor(this.#maxThreads / 2)));
160
+ this.#pidBase = hostPidBase(backend, (level, text) => this.#log(level, text));
161
+ if (this.#pids) {
162
+ Atomics.store(new Int32Array(this.#pids), 0, this.#pidBase);
163
+ Atomics.store(new Int32Array(this.#pids), 1, (crypto.getRandomValues(new Uint32Array(1))[0] | 1) >> 0);
164
+ }
90
165
  }
91
166
  /** Checks what host processes need; `status.node` tells the outcome. Never throws for a missing capability. */
92
167
  static async create(backend, options = {}) {
@@ -138,6 +213,12 @@ export class HostExecController {
138
213
  if (!this.#sessions.shares?.length)
139
214
  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
215
  await this._reloadTables();
216
+ // The pod's CA for host processes (T330): read now (a pod booted with it), and again once the agent installed it and
217
+ // once it settled (its hash directory then).
218
+ const ca = this.#backend;
219
+ void this.#loadCa();
220
+ for (const p of [ca.caInstalled, ca.caSettled])
221
+ void p?.then(() => this.#loadCa(), () => { });
141
222
  this.#fill();
142
223
  const hostMode = this.#backend.hostMode;
143
224
  if (hostMode) {
@@ -156,7 +237,10 @@ export class HostExecController {
156
237
  this.#hostOk = ok;
157
238
  void this.#announce();
158
239
  }
159
- /** HostExecInfo for the guest's node shim: node while host processes can start, the paths they see. */
240
+ /**
241
+ * HostExecInfo for the guest's node shim: node while host processes can start (and node:test's runner and watch
242
+ * mode, which an older host ran as plain node: the agent sends those to the guest without them), the paths they see.
243
+ */
160
244
  async #announce() {
161
245
  const shim = this.#shim;
162
246
  if (!shim)
@@ -164,7 +248,7 @@ export class HostExecController {
164
248
  const node = this.#enabled && !this.#disposed && this.#hostOk === true;
165
249
  const tree = node ? await this.#loadTree().catch(() => undefined) : undefined;
166
250
  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}`) });
251
+ 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
252
  }
169
253
  /** What routeTopLevel needs, to tell where a request runs without starting it (an execution origin's app side). */
170
254
  get routeContext() {
@@ -224,6 +308,11 @@ export class HostExecController {
224
308
  this.#shim?.close();
225
309
  for (const q of this.#queue.splice(0))
226
310
  q();
311
+ if (this.#burstTimer)
312
+ clearTimeout(this.#burstTimer);
313
+ this.#burstTimer = null;
314
+ if (this.#chunksTimer)
315
+ clearTimeout(this.#chunksTimer);
227
316
  const warm = this.#warm.splice(0);
228
317
  for (const e of [...this.#table.values()])
229
318
  e.kill("SIGKILL");
@@ -262,6 +351,81 @@ export class HostExecController {
262
351
  _guestTable() {
263
352
  return this.#guestTable;
264
353
  }
354
+ /**
355
+ * The pod's CA files from the guest (T330, docs/design/wasix-lite.md §2.3): its file, the system bundle and the hash
356
+ * directory the agent's profile names, and OpenSSL's default file (/etc/ssl/cert.pem: Alpine's link to the bundle),
357
+ * for host processes' read-only tree at the same paths (start's rootFiles: a WASIX program's TLS, curl's, CPython's,
358
+ * trusts what the guest's does), on one SharedArrayBuffer. Its variables too, for host
359
+ * processes without them (a pod.spawn's; the shim's have the guest's). Nothing while there is no CA in the guest.
360
+ */
361
+ async #loadCa() {
362
+ const fs = this.#backend.fs;
363
+ let profile;
364
+ try {
365
+ profile = await fs.readFile(CA_PROFILE, "utf8");
366
+ }
367
+ catch {
368
+ return;
369
+ }
370
+ const env = {};
371
+ for (const line of profile.split("\n")) {
372
+ const m = /^export ([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line.trim());
373
+ if (m)
374
+ env[m[1]] = m[2];
375
+ }
376
+ const paths = new Set([POD_CA_FILE, ...[env.SSL_CERT_FILE, env.CURL_CA_BUNDLE].filter((p) => !!p && p.startsWith("/"))]);
377
+ // The same profile and the same bundle (the hash directory's fingerprint of it, ca.rs's .source) as last time: the
378
+ // same files (no 140 reads of the hash directory again).
379
+ const indexed = env.SSL_CERT_DIR === CA_HASH_DIR;
380
+ const source = indexed ? await fs.readFile(`${CA_HASH_DIR}/.source`, "utf8").catch(() => "") : "";
381
+ const key = profile + "\0" + source;
382
+ if (this.#ca?.key === key && source)
383
+ return;
384
+ if (indexed) {
385
+ for (const e of await fs.readdir(CA_HASH_DIR).catch(() => []))
386
+ if (e.type === "file" && !e.name.startsWith("."))
387
+ paths.add(`${CA_HASH_DIR}/${e.name}`);
388
+ }
389
+ // OpenSSL's default file as the guest has it: a link (and the file it leads to), or a file
390
+ const links = [];
391
+ const st = await fs.lstat(OPENSSL_CA_FILE).catch(() => null);
392
+ if (st?.type === "symlink") {
393
+ const target = await fs.readlink(OPENSSL_CA_FILE).catch(() => "");
394
+ if (target) {
395
+ links.push({ path: OPENSSL_CA_FILE, mode: 0o120777, data: new TextEncoder().encode(target) });
396
+ const out = [];
397
+ for (const c of (target.startsWith("/") ? target : `/etc/ssl/${target}`).split("/"))
398
+ if (c === "..")
399
+ out.pop();
400
+ else if (c && c !== ".")
401
+ out.push(c);
402
+ paths.add(`/${out.join("/")}`);
403
+ }
404
+ }
405
+ else if (st?.type === "file")
406
+ paths.add(OPENSSL_CA_FILE);
407
+ const read = await Promise.all([...paths].map((path) => fs.readFile(path).then((data) => ({ path, mode: 0o100644, data }), () => null)));
408
+ const got = [...read.filter((f) => f !== null), ...links];
409
+ if (!got.some((f) => f.path === POD_CA_FILE))
410
+ return;
411
+ const sab = new SharedArrayBuffer(got.reduce((n, f) => n + f.data.length, 0));
412
+ let at = 0;
413
+ const files = got.map((f) => {
414
+ const data = new Uint8Array(sab, at, f.data.length);
415
+ data.set(f.data);
416
+ at += f.data.length;
417
+ return { path: f.path, mode: f.mode, data };
418
+ });
419
+ this.#ca = { files, env, key };
420
+ }
421
+ /** @internal A start's rootFiles (the pod's CA), when there are some. */
422
+ _rootStart() {
423
+ return this.#ca ? { rootFiles: this.#ca.files } : {};
424
+ }
425
+ /** @internal The pod's CA variables, for a host process's environment (its own win). */
426
+ _caEnv() {
427
+ return this.#ca?.env ?? {};
428
+ }
265
429
  /** @internal */
266
430
  _emit(e) {
267
431
  this.#emit(e);
@@ -334,6 +498,12 @@ export class HostExecController {
334
498
  return this.#boot(identity);
335
499
  // A few from the pool, then a new one whose failure is the caller's: when every boot fails (the FS Worker cannot
336
500
  // open a session), taking the next pooled one and refilling would go on for ever and freeze the page.
501
+ // A miss right after another take (not the first process, whose Worker may still boot with the pod) is a burst.
502
+ const now = Date.now();
503
+ const soon = now - this.#lastTake < (this.#o.poolBurstMs ?? POOL_BURST_MS);
504
+ this.#lastTake = now;
505
+ if (soon && (!this.#warm.length || !this.#ready.has(this.#warm[0])))
506
+ this.#burst();
337
507
  for (let tries = 0; tries < 3 && this.#warm.length > 0; tries++) {
338
508
  const p = this.#warm.shift();
339
509
  this.#fill();
@@ -356,15 +526,76 @@ export class HostExecController {
356
526
  _unregister(pid) {
357
527
  this.#table.delete(pid);
358
528
  }
359
- /** @internal Kills the processes below `pid` (its own exit or kill ends the tree, as a process group). */
529
+ /**
530
+ * @internal Kills the processes below `pid` (its own exit or kill ends the tree, as a process group). A detached child
531
+ * (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
532
+ * ended already (its parent had not reaped it yet) is reaped now, as init would.
533
+ */
360
534
  _killChildren(pid, signal) {
361
535
  for (const e of [...this.#table.values()]) {
362
536
  if (e.ppid !== pid)
363
537
  continue;
538
+ if (e.detached && !e.exited) {
539
+ e.ppid = 1;
540
+ // Nobody takes its output any more (its owner's port is gone): its writes do not wait for it.
541
+ outUntaken(e.outCredit);
542
+ e.untaken?.();
543
+ continue;
544
+ }
364
545
  this._killChildren(e.pid, signal);
365
546
  e.kill(signal);
366
547
  }
367
548
  }
549
+ /**
550
+ * @internal A debugging aid (T289): asks every host Worker what its memory is (host-exec's src/mem-report.js: its JS
551
+ * heap where the engine tells it, its WebAssembly.Memory objects) and sums the answers. A Worker that does not answer
552
+ * within timeoutMs (default 1 s) is listed with its last answer, as stuck.
553
+ */
554
+ async _memReport(options = {}) {
555
+ const timeoutMs = options.timeoutMs ?? 1000, id = ++this.#memIds, at = Date.now();
556
+ // (the page's SharedArrayBuffers for it: its spawnSync / listen answers, its 9P sessions' rings)
557
+ const buffers = (rec) => ({ ctl: rec.ctl.byteLength, sessions: [rec.session, ...rec.shares].reduce((n, s) => n + s.memory.byteLength, 0) });
558
+ const workers = await Promise.all([...this.#workers].filter((w) => !w.dead).map((rec) => new Promise((resolve) => {
559
+ const mem = (rec.mem ??= { last: null, waiting: new Map() });
560
+ const timer = setTimeout(() => {
561
+ mem.waiting.delete(id);
562
+ 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 });
563
+ }, timeoutMs);
564
+ mem.waiting.set(id, (report) => {
565
+ clearTimeout(timer);
566
+ resolve({ ...report, buffers: buffers(rec) });
567
+ });
568
+ try {
569
+ rec.w.postMessage({ type: "mem", id });
570
+ }
571
+ catch {
572
+ // a Worker that cannot take it: it times out
573
+ }
574
+ })));
575
+ const sum = () => ({ count: 0, bytes: 0, maximum: 0 });
576
+ const wasm = { ...sum(), shared: sum(), byLabel: {} };
577
+ let heapUsed = null;
578
+ for (const w of workers) {
579
+ if (w.heap)
580
+ heapUsed = (heapUsed ?? 0) + w.heap.used;
581
+ for (const m of w.memories) {
582
+ if (m.origin === "import")
583
+ continue;
584
+ for (const s of [wasm, ...(m.shared ? [wasm.shared] : []), (wasm.byLabel[m.label ?? "?"] ??= sum())]) {
585
+ s.count++;
586
+ s.bytes += m.bytes;
587
+ s.maximum += m.maximum ?? m.bytes;
588
+ }
589
+ }
590
+ }
591
+ const pm = globalThis.performance?.memory;
592
+ return {
593
+ at,
594
+ page: { heap: pm ? { used: pm.usedJSHeapSize, total: pm.totalJSHeapSize, limit: pm.jsHeapSizeLimit } : null },
595
+ workers,
596
+ 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 },
597
+ };
598
+ }
368
599
  /** @internal Terminates a Worker and ends its session. */
369
600
  _retire(w) {
370
601
  this.#retire(w);
@@ -379,27 +610,130 @@ export class HostExecController {
379
610
  w.session.close();
380
611
  for (const s of w.shares)
381
612
  s.close();
382
- if (w.netId)
613
+ if (w.netId) {
614
+ // Its listens end now, as a process's death closes its sockets: the port is free for the next process (nodemon's
615
+ // restart), where the net Worker would keep them for its second's grace (closeHostSocketSoon) without the
616
+ // process's bye, which a killed Worker never sends. Its connections get that second for what it sent last.
617
+ for (const l of w.listens?.values() ?? [])
618
+ this.#backend.hostNet?.unlisten?.(w.netId, l.port);
383
619
  this.#backend.hostNet?.close(w.netId);
620
+ }
384
621
  for (const l of w.listens?.values() ?? [])
385
622
  if (l.guest !== null)
386
623
  this.#backend.hostListen?.unlisten(l.guest);
387
624
  w.listens?.clear();
388
625
  this.#unixGone(w);
626
+ this.#udp.gone(w);
389
627
  for (const t of w.threads?.values() ?? [])
390
628
  this.#retire(t);
391
629
  w.threads?.clear();
630
+ if (w.root && w.root.tids?.get(w.tid) === w)
631
+ w.root.tids.delete(w.tid);
632
+ this.#unreserve(w);
392
633
  w.onRetire?.();
393
634
  }
635
+ // ---- memory (T258): processes that declare theirs share memoryBudgetMB ----
636
+ // A small one (SPARE_MB at most) that the budget has no room for starts in memoryReserveMB if that has room (T340:
637
+ // psql waited for good next to postgres, which holds more than a phone's budget alone).
638
+ #reserve(rec, asked, what) {
639
+ if (rec.dead)
640
+ return;
641
+ const mb = Math.max(0, Math.ceil(Number(asked) || 0));
642
+ this.#unreserve(rec, false);
643
+ const grant = (spare) => {
644
+ const over = !spare && this.#memUsed + mb > this.#memBudget;
645
+ if (over)
646
+ this.#log("warn", `host-exec: ${what} takes ${mb} MB, more than hostExec.memoryBudgetMB (${this.#memBudget}) leaves; nothing else holds any`);
647
+ rec.memoryMB = mb;
648
+ if (spare) {
649
+ this.#spareUsed += mb;
650
+ this.#spareHeld.add(rec);
651
+ }
652
+ else {
653
+ this.#memUsed += mb;
654
+ this.#memHeld.add(rec);
655
+ }
656
+ writeCtl(rec.ctl, over ? { granted: true, over: true } : { granted: true });
657
+ };
658
+ const fits = () => this.#memUsed + mb <= this.#memBudget || this.#memHeld.size === 0;
659
+ const fitsSpare = () => mb <= SPARE_MB && this.#spareUsed + mb <= this.#memSpare;
660
+ if (!this.#memQueue.length && fits())
661
+ return grant(false);
662
+ if (fitsSpare())
663
+ return grant(true);
664
+ const wait = this.#o.memoryWaitMs ?? 120_000;
665
+ const timer = setTimeout(() => {
666
+ const i = this.#memQueue.findIndex((q) => q.rec === rec);
667
+ if (i < 0)
668
+ return;
669
+ this.#memQueue.splice(i, 1);
670
+ 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}` : "";
671
+ 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}` });
672
+ this.#pumpMemory();
673
+ }, wait);
674
+ this.#memQueue.push({ rec, fits, fitsSpare, grant, timer });
675
+ }
676
+ #unreserve(w, pump = true) {
677
+ const i = this.#memQueue.findIndex((q) => q.rec === w);
678
+ if (i >= 0)
679
+ clearTimeout(this.#memQueue.splice(i, 1)[0].timer);
680
+ if (this.#memHeld.delete(w))
681
+ this.#memUsed -= w.memoryMB ?? 0;
682
+ if (this.#spareHeld.delete(w))
683
+ this.#spareUsed -= w.memoryMB ?? 0;
684
+ w.memoryMB = 0;
685
+ if (pump)
686
+ this.#pumpMemory();
687
+ }
688
+ #pumpMemory() {
689
+ // The budget's waiting reserves first come first served, then small ones further back into memoryReserveMB.
690
+ while (this.#memQueue.length && this.#memQueue[0].fits()) {
691
+ const q = this.#memQueue.shift();
692
+ clearTimeout(q.timer);
693
+ q.grant(false);
694
+ }
695
+ for (const q of [...this.#memQueue]) {
696
+ if (!q.fitsSpare())
697
+ continue;
698
+ this.#memQueue.splice(this.#memQueue.indexOf(q), 1);
699
+ clearTimeout(q.timer);
700
+ q.grant(true);
701
+ }
702
+ }
394
703
  #fill() {
395
- const pool = this.#o.pool ?? 1;
396
- while (this.#enabled && !this.#disposed && this.#warm.length < pool) {
704
+ while (this.#enabled && !this.#disposed && this.#warm.length < this.#poolTarget) {
397
705
  const p = this.#boot();
398
- p.catch(() => { });
706
+ p.then(() => this.#ready.add(p), () => { });
399
707
  this.#warm.push(p);
400
708
  }
401
709
  }
402
- async #boot(identity = this._identity(), thread) {
710
+ /**
711
+ * A take found no booted Worker: processes start faster than one boots (npm scripts, test workers). The pool keeps
712
+ * poolBurst for POOL_BURST_MS after the last miss, as far as the memory budget leaves room for idle Workers.
713
+ */
714
+ #burst() {
715
+ const pool = this.#o.pool ?? 1;
716
+ const burst = this.#o.poolBurst ?? (pool === 0 ? 0 : constrainedDevice() ? 2 : 3);
717
+ const room = Math.floor((this.#memBudget - this.#memUsed) / IDLE_WORKER_MB);
718
+ const target = Math.max(pool, Math.min(burst, room, this.#max - 1));
719
+ if (target <= pool || this.#disposed)
720
+ return;
721
+ this.#poolTarget = target;
722
+ if (this.#burstTimer)
723
+ clearTimeout(this.#burstTimer);
724
+ this.#burstTimer = setTimeout(() => {
725
+ this.#burstTimer = null;
726
+ this.#poolTarget = pool;
727
+ // The idle Workers past the pool end now (booting ones once booted).
728
+ for (const p of this.#warm.splice(pool))
729
+ void p.then((w) => this.#retire(w), () => { });
730
+ }, this.#o.poolBurstMs ?? POOL_BURST_MS);
731
+ }
732
+ /**
733
+ * 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):
734
+ * the same sessions and tree, no node lib, net or pool.
735
+ */
736
+ async #boot(identity = this._identity(), thread, wasi = false, net = !wasi) {
403
737
  const sessions = this.#sessions;
404
738
  const client = `h${++this.#clients}`;
405
739
  const opened = [sessions.open(client, identity), ...(sessions.shares ?? []).map((s) => s.open(client, identity))];
@@ -407,7 +741,7 @@ export class HostExecController {
407
741
  let tree;
408
742
  let sources;
409
743
  try {
410
- [all, tree, sources] = await Promise.all([Promise.all(opened), this.#loadTree(), this.#loadSources()]);
744
+ [all, tree, sources] = await Promise.all([Promise.all(opened), this.#loadTree(), wasi ? undefined : this.#loadSources()]);
411
745
  }
412
746
  catch (e) {
413
747
  for (const p of opened)
@@ -420,9 +754,10 @@ export class HostExecController {
420
754
  s.close();
421
755
  throw new WebPodError("DISPOSED", "pod has been disposed");
422
756
  }
423
- const url = this.#o.workerUrl;
757
+ const url = wasi ? wasiWorkerUrl(this.#o.workerUrl) : this.#o.workerUrl;
424
758
  const w = (this.#o.createWorker ?? ((u) => new Worker(u)))(url);
425
- const rec = { w, session, shares: shareSessions, identity, ctl: new SharedArrayBuffer(SYNC_HEADER + (this.#o.syncBufferBytes ?? 16 << 20)), dead: false };
759
+ // (a wasi Worker's ctl answers a reserve only, T258: its error says why, in a few hundred bytes)
760
+ const rec = { w, session, shares: shareSessions, identity, ctl: newCtl(SYNC_HEADER + (wasi ? 4096 : (this.#o.syncBufferBytes ?? 16 << 20))), dead: false };
426
761
  // One of its 9P sessions failed in the FS Worker: the process ends (exit 70), the Worker is retired.
427
762
  for (const s of all)
428
763
  s.onerror = (message) => {
@@ -460,12 +795,12 @@ export class HostExecController {
460
795
  const { memory, req, rep, gen, eventSeq, quiet, append } = s;
461
796
  return { prefix, session: { memory, req, rep, ...(gen !== undefined ? { gen } : {}), ...(eventSeq !== undefined ? { eventSeq } : {}), ...(quiet !== undefined ? { quiet } : {}), ...(append ? { append } : {}) }, ...(s.events ? { events: s.events } : {}) };
462
797
  };
463
- let net;
464
- if (this.#backend.hostNet) {
798
+ let netPort;
799
+ if (this.#backend.hostNet && net) {
465
800
  const ch = new MessageChannel();
466
801
  this.#backend.hostNet.open(client, ch.port1);
467
802
  rec.netId = client;
468
- net = ch.port2;
803
+ netPort = ch.port2;
469
804
  }
470
805
  w.postMessage({
471
806
  type: "boot",
@@ -474,12 +809,18 @@ export class HostExecController {
474
809
  wasmModules: { ...this.#wasmModules },
475
810
  ctl: rec.ctl,
476
811
  pids: this.#pids,
812
+ cpus: this.#cpus,
813
+ // It answers reserve (T258).
814
+ memory: true,
815
+ ...(this.#backend.hostNet?.guestInterface ? { ifaces: [this.#backend.hostNet.guestInterface()] } : {}),
477
816
  ...(tree ? { tree } : {}),
478
817
  ...(sources ? { sources } : {}),
479
- ...(net ? { net } : {}),
480
- ...(this.#o.workerOptions ? { options: this.#o.workerOptions } : {}),
818
+ ...(netPort ? { net: netPort } : {}),
819
+ // msize: what the sessions' rings take (a ring's largest message is half of it, less 4: 1 MiB rings, T354)
820
+ options: { ...this.#o.workerOptions, msize: Math.min(Number(this.#o.workerOptions?.msize ?? DEFAULT_MSIZE), ...[session, ...shareSessions].map((s) => ringMessageMax(s.memory, s.req))) },
481
821
  ...(thread ? { thread } : {}),
482
- }, [...(net ? [net] : []), ...all.flatMap((s) => (s.events ? [s.events] : []))]);
822
+ ...(wasi ? {} : { wasi: true }),
823
+ }, [...(netPort ? [netPort] : []), ...all.flatMap((s) => (s.events ? [s.events] : []))]);
483
824
  try {
484
825
  await booted;
485
826
  }
@@ -489,8 +830,58 @@ export class HostExecController {
489
830
  }
490
831
  if (this.#shim)
491
832
  this.#setHostOk(true);
833
+ this.#fetchChunksAhead();
492
834
  return rec;
493
835
  }
836
+ /**
837
+ * host-node.js's chunks (HOST_CHUNKS), fetched once the first Worker has booted and the page is idle, so a process
838
+ * that first needs one later (offline too) has it from the page: what host-node.js carried before (T291). Not on
839
+ * constrained devices: there each is fetched when a process first asks for it.
840
+ */
841
+ #fetchChunksAhead() {
842
+ if (this.#chunksAhead || constrainedDevice())
843
+ return;
844
+ this.#chunksAhead = true;
845
+ this.#chunksTimer = setTimeout(() => {
846
+ this.#chunksTimer = null;
847
+ const fetchAll = () => {
848
+ if (!this.#disposed)
849
+ for (const name of HOST_CHUNKS)
850
+ this.#asset(name).catch(() => { });
851
+ };
852
+ const g = globalThis;
853
+ if (g.requestIdleCallback)
854
+ g.requestIdleCallback(fetchAll, { timeout: 10_000 });
855
+ else
856
+ fetchAll();
857
+ }, this.#o.chunksAheadMs ?? CHUNKS_AHEAD_MS);
858
+ }
859
+ /** An asset file next to the Worker: only HOST_ASSETS' names, never a URL of the process's. */
860
+ #asset(name) {
861
+ if (!HOST_ASSETS.includes(name))
862
+ return Promise.reject(new Error("not an asset of host-exec's"));
863
+ let p = this.#assets.get(name);
864
+ if (!p) {
865
+ p = (async () => {
866
+ // Its URL in the error: a deployment that left the file out says which (the log's warning, the process's).
867
+ const url = new URL(name, new URL(this.#o.workerUrl, globalThis.location?.href)).href;
868
+ let res;
869
+ try {
870
+ res = await fetch(url);
871
+ }
872
+ catch (e) {
873
+ throw new Error(`${url}: ${e.message}`);
874
+ }
875
+ if (!res.ok)
876
+ throw new Error(`${url}: HTTP ${res.status}`);
877
+ return new Uint8Array(await res.arrayBuffer());
878
+ })();
879
+ // A failed request is tried again by the next process that asks.
880
+ p.catch(() => this.#assets.delete(name));
881
+ this.#assets.set(name, p);
882
+ }
883
+ return p;
884
+ }
494
885
  #loadTree() {
495
886
  const t = this.#o.tree;
496
887
  if (t !== undefined && typeof t !== "string")
@@ -545,7 +936,10 @@ export class HostExecController {
545
936
  #onWorker(rec, m) {
546
937
  switch (m.type) {
547
938
  case "spawn":
548
- return void this.#child(m, m.port, rec).catch((e) => this.#log("warn", `host-exec: spawn ${m.argv.join(" ")}: ${e.message}`));
939
+ this.#starting.set(m.pid, rec);
940
+ return void this.#child(m, m.port, rec)
941
+ .catch((e) => this.#log("warn", `host-exec: spawn ${m.argv.join(" ")}: ${e.message}`))
942
+ .finally(() => this.#starting.delete(m.pid));
549
943
  case "spawnSync":
550
944
  return this.#spawnSync(m, rec);
551
945
  case "reap":
@@ -558,9 +952,22 @@ export class HostExecController {
558
952
  this.#gone.add(m.pid);
559
953
  return;
560
954
  }
955
+ case "kill-pid":
956
+ return void this.#killPid(m, rec).then((errno) => writeCtl(rec.ctl, { errno }));
957
+ case "guest-which":
958
+ return void this.#guestWhich(m.candidates).then((found) => writeCtl(rec.ctl, { found }));
959
+ case "reserve":
960
+ return this.#reserve(rec, m.mb, m.what ?? "a host process");
561
961
  case "wasm-module":
562
962
  this.#wasmModules[m.key] = m.module;
563
963
  return;
964
+ case "mem": {
965
+ const mem = (rec.mem ??= { last: null, waiting: new Map() });
966
+ mem.last = { at: Date.now(), report: m.report };
967
+ mem.waiting.get(m.id)?.(m.report);
968
+ mem.waiting.delete(m.id);
969
+ return;
970
+ }
564
971
  case "trace":
565
972
  // WEBPOD_HOST_DIAG's traces are for someone looking into a stuck process: shown as warnings.
566
973
  return this.#log(m.text.startsWith("diag ") ? "warn" : "debug", `host-exec [${m.pid}] ${m.text}`);
@@ -572,7 +979,7 @@ export class HostExecController {
572
979
  case "unlisten":
573
980
  return this.#unlisten(rec, m.req);
574
981
  case "unix-listen":
575
- return writeCtl(rec.ctl, this.#unixListen(rec, m.key));
982
+ return void writeCtl(rec.ctl, this.#unixListen(rec, m.key));
576
983
  case "unix-unlisten":
577
984
  for (const [key, l] of this.#unixListeners)
578
985
  if (l.rec === rec && l.req === m.req)
@@ -583,15 +990,52 @@ export class HostExecController {
583
990
  case "unix-close":
584
991
  this.#unixConns.delete(m.cid);
585
992
  return;
993
+ case "udp-bind":
994
+ return void writeCtl(rec.ctl, this.#udp.bind(rec, m));
995
+ case "udp-close":
996
+ return this.#udp.close(rec, m.sid);
997
+ case "udp-send": {
998
+ const r = this.#udp.route(rec, m);
999
+ if (r && !r[0].dead)
1000
+ r[0].w.postMessage(r[1], [r[1].data.buffer]);
1001
+ return;
1002
+ }
586
1003
  case "thread":
587
1004
  return void this.#thread(rec, m).catch((e) => this.#log("warn", `host-exec: thread ${m.tid} of ${rec.pid}: ${e.message}`));
1005
+ case "wasix-thread":
1006
+ return void this.#wasixThread(rec, m).catch((e) => this.#log("warn", `host-exec: the wasm thread of ${rec.pid}: ${e.message}`));
1007
+ case "signals":
1008
+ rec.handled = new Set(m.signals);
1009
+ return rec.report?.(m);
588
1010
  case "thread-end": {
589
1011
  const t = rec.threads?.get(m.tid);
1012
+ // (terminate() right after new Worker(): its Worker still boots; it would start and hold a maxThreads slot)
1013
+ if (!t) {
1014
+ (rec.endedThreads ??= new Set()).add(m.tid);
1015
+ return;
1016
+ }
1017
+ // terminate() (or its process's end): at once, as node's; its own end: once what was sent to it is done (a WASIX
1018
+ // program's wasm thread at once: it relays nothing).
1019
+ if (!m.terminated && !t.wasix)
1020
+ return this.#endThread(rec, m.tid, t);
590
1021
  rec.threads?.delete(m.tid);
591
- if (t)
592
- this.#retire(t);
593
- return;
1022
+ return this.#retire(t);
594
1023
  }
1024
+ case "drained":
1025
+ return rec.ending?.();
1026
+ case "relay":
1027
+ return this.#relay(rec, m.tid, m.msg, m.transfer);
1028
+ case "crypto":
1029
+ // A result that does not fit in ctl (an AES-GCM of megabytes) is NotSupportedError: the process falls back.
1030
+ return void this.#webcrypto(m.calls)
1031
+ .catch((e) => ({ error: { name: "OperationError", message: String(e?.message ?? e) } }))
1032
+ .then((r) => writeCtl(rec.ctl, r) || writeCtl(rec.ctl, { error: { name: "NotSupportedError", message: "a WebCrypto result larger than hostExec.syncBufferBytes" } }));
1033
+ case "asset":
1034
+ // Without the file (a build without it, a failed request) the binding that asked falls back.
1035
+ 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) => {
1036
+ this.#log("warn", `host-exec: ${m.name}: ${e.message}`);
1037
+ writeAsset(rec.ctl, { error: e.message });
1038
+ });
595
1039
  default:
596
1040
  rec.report?.(m);
597
1041
  }
@@ -700,14 +1144,75 @@ export class HostExecController {
700
1144
  if (l.guest !== null)
701
1145
  this.#backend.hostListen?.unlisten(l.guest);
702
1146
  }
1147
+ /**
1148
+ * A process's WebCrypto calls (host-exec's impl-crypto.js webcryptoRun, for what node does synchronously), in order
1149
+ * on the page's crypto.subtle while the process waits on ctl. Only SubtleCrypto's key and cipher operations; the keys
1150
+ * stay here. Imported keys are kept: jsonwebtoken signs with the same key every time, and importing an RSA key costs
1151
+ * about half as much as a signature.
1152
+ */
1153
+ async #webcrypto(calls) {
1154
+ // Without WebCrypto (not a secure context) the process falls back.
1155
+ if (!globalThis.crypto?.subtle)
1156
+ return { error: { name: "NotSupportedError", message: "this page has no WebCrypto (crypto.subtle)" } };
1157
+ const subtle = crypto.subtle;
1158
+ const out = [];
1159
+ const arg = (a) => {
1160
+ if (!a || typeof a !== "object" || ArrayBuffer.isView(a) || a instanceof ArrayBuffer || Array.isArray(a) || a instanceof CryptoKey)
1161
+ return a;
1162
+ if ("ref" in a) {
1163
+ const { ref, part } = a;
1164
+ if (part !== undefined && part !== "publicKey" && part !== "privateKey")
1165
+ throw new TypeError(`not a key pair's half: ${part}`);
1166
+ return part ? out[ref][part] : out[ref];
1167
+ }
1168
+ return Object.fromEntries(Object.entries(a).map(([k, v]) => [k, arg(v)]));
1169
+ };
1170
+ const importKey = async (args) => {
1171
+ const [format, data, ...rest] = args;
1172
+ let id = `${format} ${JSON.stringify(rest)} `;
1173
+ if (format === "jwk")
1174
+ id += JSON.stringify(data);
1175
+ else {
1176
+ const u = ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data);
1177
+ for (let i = 0; i < u.length; i += 0x2000)
1178
+ id += String.fromCharCode(...u.subarray(i, i + 0x2000));
1179
+ }
1180
+ const keys = this.#importedKeys;
1181
+ let k = keys.get(id);
1182
+ if (k)
1183
+ keys.delete(id);
1184
+ else
1185
+ k = (await subtle.importKey(...args));
1186
+ keys.set(id, k);
1187
+ if (keys.size > 32)
1188
+ keys.delete(keys.keys().next().value);
1189
+ return k;
1190
+ };
1191
+ try {
1192
+ for (const c of calls) {
1193
+ if (!WEBCRYPTO_OPS.has(c.op))
1194
+ throw new TypeError(`not a WebCrypto call: ${c.op}`);
1195
+ const args = c.args.map(arg);
1196
+ out.push(await (c.op === "importKey" ? importKey(args) : subtle[c.op](...args)));
1197
+ }
1198
+ return { results: out.map((r) => (r instanceof ArrayBuffer ? { b64: base64(new Uint8Array(r)) } : typeof r === "boolean" || r?.kty ? r : null)) };
1199
+ }
1200
+ catch (e) {
1201
+ return { error: { name: e?.name ?? "Error", message: String(e?.message ?? e) } };
1202
+ }
1203
+ }
703
1204
  /**
704
1205
  * A worker_threads thread of `parent`'s process: a Worker booted as a thread, with the process's pid and its own
705
1206
  * sessions; it ends with the process (#retire). Threads do not count against maxProcesses.
706
1207
  */
707
1208
  async #thread(parent, m) {
708
- // As node reports a thread that could not start: 'error' (ERR_WORKER_INIT_FAILED), then 'exit' 1.
709
- const refuse = (reason) => m.port.postMessage({ type: "exit", code: 1, error: "ERR_WORKER_INIT_FAILED", reason });
710
- const max = this.#o.maxThreads ?? 2 * this.#max;
1209
+ // As node reports a thread that could not start: 'error' (ERR_WORKER_INIT_FAILED), then 'exit' 1. Its environment
1210
+ // port is closed, and what its parent sent on it before the start (workerData, T246) goes now, not at a collection.
1211
+ const refuse = (reason) => {
1212
+ m.envPort.close();
1213
+ m.port.postMessage({ type: "exit", code: 1, error: "ERR_WORKER_INIT_FAILED", reason });
1214
+ };
1215
+ const max = this.#maxThreads;
711
1216
  if (this.#threads >= max)
712
1217
  return refuse(`host mode runs at most ${max} worker threads at once (hostExec.maxThreads)`);
713
1218
  this.#threads++;
@@ -721,9 +1226,15 @@ export class HostExecController {
721
1226
  throw e;
722
1227
  }
723
1228
  w.onRetire = () => this.#threads--;
724
- if (parent.dead)
1229
+ // (its parent gone, ending: drained, its own threads retired already; or its end came first)
1230
+ if (parent.dead || parent.ending || parent.endedThreads?.delete(m.tid)) {
1231
+ m.envPort.close();
725
1232
  return this.#retire(w);
1233
+ }
726
1234
  (parent.threads ??= new Map()).set(m.tid, w);
1235
+ w.tid = m.tid;
1236
+ w.root = parent.root ?? parent;
1237
+ (w.root.tids ??= new Map()).set(m.tid, w);
727
1238
  w.pid = parent.pid;
728
1239
  w.ppid = parent.ppid;
729
1240
  w.report = (r) => {
@@ -734,8 +1245,114 @@ export class HostExecController {
734
1245
  }
735
1246
  };
736
1247
  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 ?? [])]);
1248
+ 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 } : {}) };
1249
+ 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._rootStart() }, [m.port, m.envPort, ...(m.initialTransfer ?? [])]);
1250
+ }
1251
+ /**
1252
+ * A WASIX program's wasm thread (host-exec's wasi-worker.js, T315): a wasi Worker booted with `parent`'s identity and
1253
+ * sessions of its own, started with the port its process sends the program on; it ends with the process (#retire) or
1254
+ * at its thread-end. Not a worker_threads thread: maxThreads does not count it.
1255
+ */
1256
+ async #wasixThread(parent, m) {
1257
+ let w;
1258
+ try {
1259
+ w = await this.#boot(parent.identity, undefined, true);
1260
+ }
1261
+ catch (e) {
1262
+ m.port.postMessage({ type: "error", message: e.message });
1263
+ throw e;
1264
+ }
1265
+ if (parent.dead || parent.ending || parent.endedThreads?.delete(m.tid))
1266
+ return this.#retire(w);
1267
+ w.wasix = true;
1268
+ (parent.threads ??= new Map()).set(m.tid, w);
1269
+ w.pid = parent.pid;
1270
+ w.ppid = parent.ppid;
1271
+ w.report = (r) => {
1272
+ if (r.type === "error") {
1273
+ this.#log("warn", `host-exec: the wasm thread of ${parent.pid} failed: ${r.message}`);
1274
+ parent.threads?.delete(m.tid);
1275
+ this.#retire(w);
1276
+ }
1277
+ };
1278
+ const o = this.#o;
1279
+ 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._rootStart() }, [m.port]);
1280
+ }
1281
+ /**
1282
+ * A port's message to another thread of rec's process (impl-messaging.js post: Firefox delivers a SharedArrayBuffer
1283
+ * over a MessagePort between Workers only sometimes): to thread tid while it is there (not ending); else to the thread
1284
+ * 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
1285
+ * notifies the header). Where none has it in RELAY_CLAIM_MS (or it closed, or its thread ended): back (relay-bounced,
1286
+ * bounced) to the thread the sending end is in, once one has it, else to rec (or the process's main thread, rec
1287
+ * ending), which sends it on the realm port, or on to the end where it is now, or closes its ports.
1288
+ */
1289
+ #relay(rec, tid, msg, transfer, waited = 0, bounced = false) {
1290
+ const root = rec.root ?? rec;
1291
+ const { box, back, tag = 0, count = 0 } = msg;
1292
+ const at = (t) => {
1293
+ const w = t === 0 ? root : root.tids?.get(t);
1294
+ return w && !w.dead && !w.ending ? w : null;
1295
+ };
1296
+ // The thread whose a mailbox is (its header's): null for none, 0 while the end is on its way to one.
1297
+ const owner = (sab) => {
1298
+ const whose = Atomics.load(new Int32Array(sab, 0, 6), 3), t = whose - 1 - tag * count;
1299
+ return whose === 0 ? 0 : t >= 0 && t < count ? at(t) : null;
1300
+ };
1301
+ // Again once the end whose inbox sab is has a thread (its claim notifies the header), RELAY_CLAIM_MS at most.
1302
+ const later = (sab) => {
1303
+ const t0 = Date.now(), again = () => this.#relay(rec, -1, msg, transfer, waited + Math.max(1, Date.now() - t0), bounced);
1304
+ const w = waitAsync ? waitAsync(new Int32Array(sab, 0, 6), 3, 0, RELAY_CLAIM_MS - waited) : null;
1305
+ if (w?.async)
1306
+ void w.value.then(again);
1307
+ else if (w)
1308
+ again();
1309
+ else
1310
+ setTimeout(again, 5);
1311
+ };
1312
+ if (bounced) {
1313
+ const from = back instanceof SharedArrayBuffer ? owner(back) : null;
1314
+ if (from)
1315
+ return from.w.postMessage({ type: "relay-bounced", msg }, transfer);
1316
+ if (from === 0 && waited < RELAY_CLAIM_MS)
1317
+ return later(back);
1318
+ const to = rec.dead || rec.ending ? (root.dead ? null : root) : rec;
1319
+ return to?.w.postMessage({ type: "relay-bounced", msg }, transfer);
1320
+ }
1321
+ const to = tid >= 0 ? at(tid) : null;
1322
+ if (to)
1323
+ return to.w.postMessage({ type: "relay", msg }, transfer);
1324
+ if (box instanceof SharedArrayBuffer && (msg.hops ?? 0) <= 16) {
1325
+ const there = owner(box);
1326
+ if (there)
1327
+ return there.w.postMessage({ type: "relay", msg }, transfer);
1328
+ if (there === 0 && waited < RELAY_CLAIM_MS)
1329
+ return later(box);
1330
+ }
1331
+ this.#relay(rec, -1, msg, transfer, 0, true);
1332
+ }
1333
+ /**
1334
+ * Thread tid of `parent`, which ended: retired once what was sent to it before is done (drain, drained), or after
1335
+ * RELAY_DRAIN_MS; one of parent's threads until then (retired with it). Its own threads end with it, at once.
1336
+ */
1337
+ #endThread(parent, tid, t) {
1338
+ if (t.dead || t.ending)
1339
+ return;
1340
+ const retire = () => {
1341
+ if (parent.threads?.get(tid) === t)
1342
+ parent.threads.delete(tid);
1343
+ this.#retire(t);
1344
+ };
1345
+ t.ending = retire;
1346
+ for (const c of t.threads?.values() ?? [])
1347
+ this.#retire(c);
1348
+ t.threads?.clear();
1349
+ try {
1350
+ t.w.postMessage({ type: "drain" });
1351
+ }
1352
+ catch {
1353
+ return retire();
1354
+ }
1355
+ setTimeout(retire, RELAY_DRAIN_MS);
739
1356
  }
740
1357
  /** A child of a host process; `port` is its owner's end. Resolves once it is started. */
741
1358
  async #child(spec, port, parent, force = false) {
@@ -744,7 +1361,8 @@ export class HostExecController {
744
1361
  await this._acquire(force);
745
1362
  let w;
746
1363
  try {
747
- w = await this._worker();
1364
+ // (a wasi one's process side has the sockets of a WASIX program: T330)
1365
+ w = spec.runner === "wasi" ? await this.#boot(this._identity(), undefined, true, true) : await this._worker();
748
1366
  }
749
1367
  catch (e) {
750
1368
  this._release();
@@ -766,17 +1384,35 @@ export class HostExecController {
766
1384
  };
767
1385
  w.pid = spec.pid;
768
1386
  w.ppid = spec.ppid;
769
- // A child reports on its port; what reaches the Worker itself is its end (crash or error).
1387
+ // (its stdin its parent's, on demand: T361)
1388
+ if (spec.stdinDemand)
1389
+ w.stdinWant = parent?.stdinWant;
1390
+ const signal = (signum) => {
1391
+ if (!w.handled?.has(signum) || w.dead)
1392
+ return false;
1393
+ w.w.postMessage({ type: "signal", signal: signum });
1394
+ return true;
1395
+ };
1396
+ const entry = { pid: spec.pid, ppid: spec.ppid, kill: end, signal, owner: parent, ...(spec.detached ? { detached: true } : {}), ...(spec.outCredit ? { outCredit: spec.outCredit } : {}) };
1397
+ // A child reports on its port; what reaches the Worker itself is its end (crash or error), and a detached one's
1398
+ // exit, which ends it here once its parent is gone (nobody else reaps it then).
770
1399
  w.report = (m) => {
771
1400
  if (m.type === "error") {
772
1401
  port.postMessage({ type: "out", fd: 2, data: te.encode(`webpod: host process failed: ${m.message}\n`) });
773
1402
  port.postMessage({ type: "exit", code: EXIT_FALLBACK, signal: null });
774
1403
  end();
775
1404
  }
1405
+ else if (m.type === "detached-exit") {
1406
+ entry.exited = true;
1407
+ if (entry.ppid === 1)
1408
+ end();
1409
+ }
776
1410
  };
777
- this._register({ pid: spec.pid, ppid: spec.ppid, kill: end });
778
- if (this.#gone.delete(spec.pid) || parent?.dead)
1411
+ this._register(entry);
1412
+ if (this.#gone.delete(spec.pid) || (parent?.dead && !spec.detached))
779
1413
  return end();
1414
+ if (parent?.dead)
1415
+ entry.ppid = 1;
780
1416
  w.w.postMessage({
781
1417
  type: "start",
782
1418
  argv: spec.argv,
@@ -789,8 +1425,18 @@ export class HostExecController {
789
1425
  stdin: spec.stdin ?? null,
790
1426
  port,
791
1427
  guest: this.#guestTable,
1428
+ relay: true,
1429
+ ...(spec.wasm ? { wasm: spec.wasm, ...(spec.memoryMB ? { memoryMB: spec.memoryMB, what: spec.what } : {}) } : {}),
792
1430
  ...(spec.ipc !== undefined ? { ipc: spec.ipc } : {}),
1431
+ ...(spec.fds ? { fds: spec.fds } : {}),
1432
+ ...(spec.detached ? { detached: true } : {}),
1433
+ ...(spec.outCredit ? { outCredit: spec.outCredit } : {}),
1434
+ ...(spec.signals ? { signals: spec.signals } : {}),
1435
+ ...(spec.stdinDemand ? { stdinDemand: true } : {}),
1436
+ ...this._rootStart(),
793
1437
  }, [port]);
1438
+ if (parent?.dead)
1439
+ outUntaken(spec.outCredit);
794
1440
  }
795
1441
  /** A guest child (the agent's spawn): its stdio and exit relayed on `port`. */
796
1442
  #guestChild(spec, port) {
@@ -808,23 +1454,59 @@ export class HostExecController {
808
1454
  if (spec.stdio[0] !== "pipe")
809
1455
  void stdin.close().catch(() => { });
810
1456
  let stdinChain = Promise.resolve();
1457
+ // Its signals go to its process group (the agent's spawn makes one; agents with `kill`): what it started ends with
1458
+ // it too, as below a host process (a shell's children: `sh -c "cd x && node app.js"` does not exec its node).
1459
+ let ended = false;
1460
+ const signal = (sig) => {
1461
+ if (!ended)
1462
+ void this.#signalGroup(p, sig);
1463
+ };
1464
+ // Its output goes to the owner OUT_WINDOW ahead of what the owner took (out-ack, T287: a stuck owner's port took the
1465
+ // guest's whole output); an owner that does not say (an older host-exec) gets it as it comes.
1466
+ let ahead = 0, released = false;
1467
+ const credit = [];
1468
+ // Once its owner is gone (killed with it, or adopted: _killChildren), its output goes as it comes: nobody to say
1469
+ // it took it.
1470
+ const release = () => {
1471
+ released = true;
1472
+ for (const wake of credit.splice(0))
1473
+ wake();
1474
+ };
811
1475
  port.onmessage = ({ data }) => {
812
1476
  const x = data;
1477
+ // (ack: the owner's write waits until this one is the guest's, T287)
813
1478
  if (x.type === "stdin" && x.data)
814
- stdinChain = stdinChain.then(() => stdin.write(x.data)).catch(() => { });
1479
+ stdinChain = stdinChain
1480
+ .then(() => stdin.write(x.data))
1481
+ .catch(() => { })
1482
+ .then(() => {
1483
+ if (x.ack && !ended)
1484
+ port.postMessage({ type: "stdin-ack" });
1485
+ });
815
1486
  else if (x.type === "stdin-end")
816
1487
  stdinChain = stdinChain.then(() => stdin.close()).catch(() => { });
817
1488
  else if (x.type === "kill")
818
- void p.kill(signalName(x.signal)).catch(() => { });
1489
+ signal(signalName(x.signal));
1490
+ else if (x.type === "out-ack") {
1491
+ ahead -= x.bytes ?? 0;
1492
+ for (const wake of credit.splice(0))
1493
+ wake();
1494
+ }
819
1495
  };
820
- this._register({ pid: spec.pid, ppid: spec.ppid, kill: (sig) => void p.kill(sig).catch(() => { }) });
1496
+ this._register({ pid: spec.pid, ppid: spec.ppid, kill: (sig) => (release(), signal(sig)), untaken: release, ...(spec.detached ? { detached: true } : {}) });
1497
+ // An owner that acknowledges its output (outAcks) waits for its stdin writes too, once told they are acknowledged.
1498
+ if (spec.outAcks)
1499
+ port.postMessage({ type: "acks" });
821
1500
  if (this.#gone.delete(spec.pid))
822
- void p.kill("SIGKILL").catch(() => { });
1501
+ signal("SIGKILL");
823
1502
  const pump = async (s, fd) => {
824
1503
  for (const reader = s.getReader();;) {
1504
+ while (spec.outAcks && ahead >= OUT_WINDOW && !released)
1505
+ await new Promise((r) => credit.push(r));
825
1506
  const { done, value } = await reader.read();
826
1507
  if (done)
827
1508
  return;
1509
+ ahead += value.length;
828
1510
  port.postMessage({ type: "out", fd, data: value });
829
1511
  }
830
1512
  };
@@ -833,17 +1515,82 @@ export class HostExecController {
833
1515
  .then(async (st) => {
834
1516
  await outs;
835
1517
  port.postMessage({ type: "exit", code: st.code, signal: st.signal });
836
- },
837
- // It never started: its output may never end.
838
- (e) => {
1518
+ }, (e) => {
1519
+ release();
1520
+ // The agent restarted: the session that ran it killed it.
1521
+ if (e instanceof WebPodError && e.code === "AGENT_RESTARTED")
1522
+ return void port.postMessage({ type: "exit", code: null, signal: "SIGKILL" });
1523
+ // It never started: its output may never end.
839
1524
  port.postMessage({ type: "out", fd: 2, data: te.encode(`webpod: ${spec.file}: ${e.message}\n`) });
840
1525
  port.postMessage({ type: "exit", code: 127, signal: null });
841
1526
  })
842
1527
  .finally(() => {
1528
+ ended = true;
843
1529
  this._unregister(spec.pid);
844
1530
  port.close();
845
1531
  });
846
1532
  }
1533
+ /**
1534
+ * 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
1535
+ * process, a guest child by its host pid: its group; -pid as pid), one being started (killed once it is, #gone), else
1536
+ * the guest's below the host pids (kill(2) there with the caller's uid: its Worker's identity, not one the Worker
1537
+ * could name; agents with `kill`, else 0 as before), or none (ESRCH). -1 (every process the caller may signal) would
1538
+ * reach the pod's agent and shims: EPERM. A signal number Linux has not (above 64) is EINVAL, as kill(2)'s.
1539
+ */
1540
+ async #killPid(m, caller) {
1541
+ if (!Number.isInteger(m.signum) || m.signum < 0 || m.signum > 64)
1542
+ return EINVAL;
1543
+ if (m.pid === -1)
1544
+ return EPERM;
1545
+ const pid = Math.abs(m.pid);
1546
+ const e = this.#table.get(pid);
1547
+ if (e) {
1548
+ if (m.signal) {
1549
+ // (a host child with a handler for it takes it there, T347; else its default action, its end)
1550
+ if (e.signal?.(m.signum))
1551
+ return 0;
1552
+ e.kill(signalName(m.signal));
1553
+ if (e.owner && !e.owner.dead)
1554
+ e.owner.w.postMessage({ type: "child-exit", pid, signal: m.signal });
1555
+ }
1556
+ return 0;
1557
+ }
1558
+ const parent = this.#starting.get(pid);
1559
+ if (parent) {
1560
+ // Killed or reaped before its Worker was up: gone, as its parent saw it end.
1561
+ if (this.#gone.has(pid))
1562
+ return ESRCH;
1563
+ if (m.signal) {
1564
+ // Ended once it is up (#gone); its parent is told now, as of a table's process.
1565
+ this.#gone.add(pid);
1566
+ if (!parent.dead)
1567
+ parent.w.postMessage({ type: "child-exit", pid, signal: m.signal });
1568
+ }
1569
+ return 0;
1570
+ }
1571
+ const killPid = this.#backend.killPid;
1572
+ if (pid >= this.#pidBase)
1573
+ return ESRCH;
1574
+ if (!killPid)
1575
+ return 0;
1576
+ return killPid(m.pid, m.signum, caller.identity?.uid ?? 0).catch(() => ESRCH);
1577
+ }
1578
+ /**
1579
+ * Whether the guest has a program at one of `candidates` (a file with an x bit, as execvp looks). A stat that fails
1580
+ * otherwise than ENOENT / ENOTDIR (EACCES, the agent) says yes: the guest's spawn tells then.
1581
+ */
1582
+ async #guestWhich(candidates) {
1583
+ 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 ?? ""))));
1584
+ return found.includes(true);
1585
+ }
1586
+ /** `signal` to a guest process's group (kill(2) of -pid, with the agent's permission), else to the process. */
1587
+ async #signalGroup(p, signal) {
1588
+ const killPid = this.#backend.killPid;
1589
+ const pid = killPid ? await p.pid.catch(() => 0) : 0;
1590
+ if (killPid && pid > 0 && (await killPid(-pid, SIGNAL_NUMBERS[signal], 0).catch(() => -1)) === 0)
1591
+ return;
1592
+ await p.kill(signal).catch(() => { });
1593
+ }
847
1594
  /** A blocking child: this table owns it and writes the result into the parent's control SAB. */
848
1595
  #spawnSync(m, parent) {
849
1596
  let ch = new MessageChannel();
@@ -903,6 +1650,9 @@ export class HostExecController {
903
1650
  const x = data;
904
1651
  if (x.type === "fallback")
905
1652
  return fellBack(x);
1653
+ // (the stdin it inherited, on demand: asked for there, its parent blocked meanwhile, T361)
1654
+ if (x.type === "stdin-want")
1655
+ return parent.stdinWant?.(x.bytes);
906
1656
  if (x.type === "out") {
907
1657
  const kind = m.stdio[x.fd];
908
1658
  if (kind === "inherit")
@@ -926,7 +1676,8 @@ export class HostExecController {
926
1676
  ch.port1.postMessage({ type: "stdin", data: m.input });
927
1677
  ch.port1.postMessage({ type: "stdin-end" });
928
1678
  }
929
- else if (!stdin) {
1679
+ else if (!stdin && m.stdio[0] !== "ignore" && m.stdio[0] !== "inherit") {
1680
+ // No stdin for "ignore", nor for an inherited none: /dev/null's to a WASI program (T243).
930
1681
  stdin = createPipe(pow2(Math.max(1 << 16, (m.input?.length ?? 0) + 1)));
931
1682
  const w = new PipeWriter(stdin);
932
1683
  void (m.input ? w.write(m.input) : Promise.resolve()).then(() => w.close(), () => w.close());
@@ -956,6 +1707,15 @@ export class HostExecController {
956
1707
  }
957
1708
  }
958
1709
  const pow2 = (n) => 2 ** Math.ceil(Math.log2(n));
1710
+ /** host-exec's wasi-worker.js, next to its worker.js (workerUrl). */
1711
+ function wasiWorkerUrl(workerUrl) {
1712
+ try {
1713
+ return new URL("wasi-worker.js", new URL(workerUrl, globalThis.location?.href)).href;
1714
+ }
1715
+ catch {
1716
+ return workerUrl.replace(/[^/]*$/, "wasi-worker.js");
1717
+ }
1718
+ }
959
1719
  const SOURCES = new Map();
960
1720
  /**
961
1721
  * node-lib.json in the form the Workers read without parsing it whole (each keeps only the modules it compiles, T106):
@@ -989,22 +1749,93 @@ async function fetchShared(url, what) {
989
1749
  new Uint8Array(sab).set(bytes);
990
1750
  return sab;
991
1751
  }
992
- /** A listen's (or unix-listen's) answer, for the Worker blocked on ctl. */
1752
+ const WEBCRYPTO_OPS = new Set(["importKey", "exportKey", "generateKey", "sign", "verify", "encrypt", "decrypt", "deriveBits"]);
1753
+ function base64(u) {
1754
+ let s = "";
1755
+ for (let i = 0; i < u.length; i += 0x2000)
1756
+ s += String.fromCharCode(...u.subarray(i, i + 0x2000));
1757
+ return btoa(s);
1758
+ }
1759
+ /** host-exec's msize, where the rings take it. */
1760
+ const DEFAULT_MSIZE = 512 << 10;
1761
+ /** The largest message of the ring at `offset` of `memory` (abi's ring: half its capacity, less 4), by 64 bytes. */
1762
+ function ringMessageMax(memory, offset) {
1763
+ const cap = memory.byteLength >= offset + 16 ? Atomics.load(new Int32Array(memory, offset, 4), 2) >>> 0 : 0;
1764
+ return cap >= 256 && (cap & (cap - 1)) === 0 ? (cap / 2 - 4) & ~63 : Infinity;
1765
+ }
1766
+ /** What a Worker's ctl holds to start with (T354), after its header. */
1767
+ const CTL_BYTES = 1 << 20;
1768
+ /**
1769
+ * A Worker's ctl: CTL_BYTES, growable up to `max` for an answer that needs more (ctlRoom), where the browser has
1770
+ * growable SharedArrayBuffers; else all of `max`. JavaScriptCore lets a Worker make garbage in proportion to its heap and
1771
+ * the buffers it holds (a SharedArrayBuffer's whole length, touched or not: ctl was 16 MiB in every host Worker, T354);
1772
+ * a growable one counts as long as it is.
1773
+ */
1774
+ function newCtl(max) {
1775
+ const start = SYNC_HEADER + CTL_BYTES;
1776
+ if (max <= start)
1777
+ return new SharedArrayBuffer(max);
1778
+ try {
1779
+ const sab = new SharedArrayBuffer(start, { maxByteLength: max });
1780
+ if (sab.growable && sab.maxByteLength === max)
1781
+ return sab;
1782
+ }
1783
+ catch {
1784
+ // (no growable SharedArrayBuffer here)
1785
+ }
1786
+ return new SharedArrayBuffer(max);
1787
+ }
1788
+ /** Whether ctl has room for an answer of `bytes` after its header: a growable ctl grows (by MiBs, to its maximum at most). */
1789
+ function ctlRoom(ctl, bytes) {
1790
+ const need = SYNC_HEADER + bytes, g = ctl;
1791
+ if (need <= ctl.byteLength)
1792
+ return true;
1793
+ if (!g.growable || !g.grow || need > (g.maxByteLength ?? 0))
1794
+ return false;
1795
+ try {
1796
+ g.grow(Math.min(g.maxByteLength, Math.ceil(need / CTL_BYTES) * CTL_BYTES));
1797
+ return true;
1798
+ }
1799
+ catch {
1800
+ return false;
1801
+ }
1802
+ }
1803
+ /** A listen's, unix-listen's or crypto's answer, for the Worker blocked on ctl; false when it does not fit. */
993
1804
  function writeCtl(ctl, res) {
994
1805
  const json = te.encode(JSON.stringify(res));
1806
+ if (!ctlRoom(ctl, 4 + json.length))
1807
+ return false;
995
1808
  new DataView(ctl).setUint32(SYNC_HEADER, json.length, true);
996
1809
  new Uint8Array(ctl, SYNC_HEADER + 4).set(json);
997
1810
  const i = new Int32Array(ctl, 0, 2);
998
1811
  Atomics.store(i, 1, 4 + json.length);
999
1812
  Atomics.store(i, 0, 1);
1000
1813
  Atomics.notify(i, 0);
1814
+ return true;
1815
+ }
1816
+ /** An asset's answer, for the Worker blocked on ctl: false when its bytes do not fit. */
1817
+ function writeAsset(ctl, res, bytes) {
1818
+ const json = te.encode(JSON.stringify(res));
1819
+ const total = 4 + json.length + (bytes?.length ?? 0);
1820
+ if (!ctlRoom(ctl, total))
1821
+ return false;
1822
+ const u8 = new Uint8Array(ctl, SYNC_HEADER);
1823
+ new DataView(ctl).setUint32(SYNC_HEADER, json.length, true);
1824
+ u8.set(json, 4);
1825
+ if (bytes)
1826
+ u8.set(bytes, 4 + json.length);
1827
+ const i = new Int32Array(ctl, 0, 2);
1828
+ Atomics.store(i, 1, total);
1829
+ Atomics.store(i, 0, 1);
1830
+ Atomics.notify(i, 0);
1831
+ return true;
1001
1832
  }
1002
1833
  function writeSync(ctl, res, segs) {
1003
1834
  let out = segs;
1004
1835
  res.segs = out.map(([k, b]) => [k, b.length]);
1005
1836
  let json = te.encode(JSON.stringify(res));
1006
1837
  const total = 4 + json.length + out.reduce((t, [, b]) => t + b.length, 0);
1007
- if (total > ctl.byteLength - SYNC_HEADER) {
1838
+ if (!ctlRoom(ctl, total)) {
1008
1839
  res.error = ENOBUFS;
1009
1840
  res.segs = [];
1010
1841
  out = [];
@@ -1036,7 +1867,9 @@ class HostProcess {
1036
1867
  #req;
1037
1868
  #argv;
1038
1869
  #pidValue;
1039
- #out = [null, null];
1870
+ /** Its stdout and stderr: a pipe's (T295), what the Worker wrote taken once it is read (its StartMessage.outCredit). */
1871
+ #out = [new ProcessOutput(), new ProcessOutput()];
1872
+ #credit = outCredit();
1040
1873
  #pipe;
1041
1874
  #writer;
1042
1875
  #resolveExit;
@@ -1057,8 +1890,8 @@ class HostProcess {
1057
1890
  const o = c._options();
1058
1891
  this.#pipe = createPipe(o.stdinBytes ?? 1 << 16);
1059
1892
  this.#writer = new PipeWriter(this.#pipe);
1060
- this.stdout = new ReadableStream({ start: (ctrl) => void (this.#out[0] = ctrl) });
1061
- this.stderr = new ReadableStream({ start: (ctrl) => void (this.#out[1] = ctrl) });
1893
+ this.stdout = this.#out[0].stream;
1894
+ this.stderr = this.#out[1].stream;
1062
1895
  this.stdin = new WritableStream({
1063
1896
  write: (chunk) => this.#writeStdin(chunk),
1064
1897
  close: () => this.#closeStdin(),
@@ -1085,7 +1918,12 @@ class HostProcess {
1085
1918
  w.report = (m) => this.#onReport(m);
1086
1919
  this.#state = "running";
1087
1920
  const o = c._options();
1088
- 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() });
1921
+ // (the pod's CA variables it has not got, as the guest's processes have them from the agent; its files: T330)
1922
+ const ca = c._caEnv(), own = { ...o.env, ...this.#req.env };
1923
+ for (const k of Object.keys(ca))
1924
+ if (!(k in own))
1925
+ env[k] = ca[k];
1926
+ 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._rootStart() });
1089
1927
  }
1090
1928
  catch (e) {
1091
1929
  // Nothing ran on the host: the guest runs it from the start.
@@ -1098,8 +1936,10 @@ class HostProcess {
1098
1936
  #onReport(m) {
1099
1937
  if (this.#state !== "running")
1100
1938
  return;
1101
- if (m.type === "out")
1102
- this.#out[m.fd - 1]?.enqueue(m.data);
1939
+ if (m.type === "out") {
1940
+ const n = m.data.length;
1941
+ this.#out[m.fd - 1]?.push(m.data, () => outTaken(this.#credit, n));
1942
+ }
1103
1943
  else if (m.type === "exit")
1104
1944
  this.#finish({ code: m.code, signal: m.signal ? signalName(m.signal) : null });
1105
1945
  else if (m.type === "fallback") {
@@ -1122,7 +1962,7 @@ class HostProcess {
1122
1962
  p = c._backend().spawn(this.#req);
1123
1963
  }
1124
1964
  catch (e) {
1125
- this.#out[1]?.enqueue(te.encode(`webpod: ${e.message}\n`));
1965
+ this.#out[1].push(te.encode(`webpod: ${e.message}\n`));
1126
1966
  return this.#finish({ code: 127, signal: null });
1127
1967
  }
1128
1968
  this.#guest = p;
@@ -1138,7 +1978,7 @@ class HostProcess {
1138
1978
  const { done, value } = await r.read();
1139
1979
  if (done)
1140
1980
  return;
1141
- this.#out[i]?.enqueue(value);
1981
+ await new Promise((took) => this.#out[i].push(value, took));
1142
1982
  }
1143
1983
  };
1144
1984
  const outs = Promise.all([pump(p.stdout, 0), pump(p.stderr, 1)]).catch(() => { });
@@ -1146,7 +1986,7 @@ class HostProcess {
1146
1986
  await outs;
1147
1987
  this.#finish(st);
1148
1988
  }, (e) => {
1149
- this.#out[1]?.enqueue(te.encode(`webpod: ${e.message}\n`));
1989
+ this.#out[1].push(te.encode(`webpod: ${e.message}\n`));
1150
1990
  this.#finish({ code: 127, signal: null });
1151
1991
  });
1152
1992
  }
@@ -1154,7 +1994,7 @@ class HostProcess {
1154
1994
  /** A runtime fallback after visible effects: cannot rerun (e4-integration.md §3.2). */
1155
1995
  #fail(reason) {
1156
1996
  this.#c._emit({ pid: this.#pidValue, argv: this.#argv, reason, rerun: false });
1157
- this.#out[1]?.enqueue(te.encode(`webpod: ${reason}; this program needs regular node (WEBPOD_NODE=guest)\n`));
1997
+ this.#out[1].push(te.encode(`webpod: ${reason}; this program needs regular node (WEBPOD_NODE=guest)\n`));
1158
1998
  this.#finish({ code: EXIT_FALLBACK, signal: null });
1159
1999
  }
1160
2000
  #finish(status) {
@@ -1162,14 +2002,8 @@ class HostProcess {
1162
2002
  return;
1163
2003
  this.#state = "done";
1164
2004
  this.#end();
1165
- for (const ctrl of this.#out) {
1166
- try {
1167
- ctrl?.close();
1168
- }
1169
- catch {
1170
- // already closed or errored
1171
- }
1172
- }
2005
+ for (const o of this.#out)
2006
+ o.end();
1173
2007
  this.#writer.close();
1174
2008
  this.#c._unregister(this.#pidValue);
1175
2009
  this.#resolveExit(status);
@@ -1220,4 +2054,78 @@ class HostProcess {
1220
2054
  // No tty on the host (pty requests run in the guest).
1221
2055
  }
1222
2056
  }
2057
+ /**
2058
+ * The pod's host UDP ports (host-exec's src/udp-socket.js udpPorts, the same rules): a socket bound to the wildcard or
2059
+ * the loopback of its family (else EADDRNOTAVAIL), port 0 an ephemeral one (Linux's 32768 to 60999), a port taken
2060
+ * EADDRINUSE unless both have SO_REUSEADDR; a datagram goes to the socket bound to its address before one bound to the
2061
+ * wildcard, the last bound of several, a dual-stack socket's IPv4 senders IPv4-mapped. A sid is its owner's only (another
2062
+ * Worker's close or send of it does nothing), and only the loopback is delivered to, whatever a Worker sends.
2063
+ */
2064
+ class UdpPorts {
2065
+ #sockets = new Map();
2066
+ #next = 0;
2067
+ bind(owner, m) {
2068
+ const { family, address, reuse, v6only } = m;
2069
+ const bindable = family === 4 ? address === "0.0.0.0" || /^127\.\d+\.\d+\.\d+$/.test(address) : address === "::" || address === "::1";
2070
+ if (!bindable)
2071
+ return { error: -99 };
2072
+ let port = m.port;
2073
+ if (port === 0) {
2074
+ for (let i = 0; i < 1000 && (port === 0 || this.#taken(family, address, port, v6only, false)); i++)
2075
+ port = 32768 + Math.floor(Math.random() * 28232);
2076
+ if (this.#taken(family, address, port, v6only, false))
2077
+ return { error: -98 };
2078
+ }
2079
+ else if (this.#taken(family, address, port, v6only, reuse))
2080
+ return { error: -98 };
2081
+ const sid = ++this.#next;
2082
+ this.#sockets.set(sid, { sid, owner, family, address, port, reuse: !!reuse, v6only: !!v6only });
2083
+ return { sid, port };
2084
+ }
2085
+ close(owner, sid) {
2086
+ if (this.#sockets.get(sid)?.owner === owner)
2087
+ this.#sockets.delete(sid);
2088
+ }
2089
+ gone(owner) {
2090
+ for (const [sid, s] of this.#sockets)
2091
+ if (s.owner === owner)
2092
+ this.#sockets.delete(sid);
2093
+ }
2094
+ route(owner, m) {
2095
+ const from = this.#sockets.get(m.sid);
2096
+ if (from?.owner !== owner || !loopback(m.address))
2097
+ return null;
2098
+ const all = [...this.#sockets.values()].filter((s) => s.port === m.port && this.#takes(s, m.address));
2099
+ const to = all.filter((s) => !wildcard(s.address)).at(-1) ?? all.at(-1);
2100
+ if (!to)
2101
+ return null;
2102
+ let src = wildcard(from.address) ? (isV4(m.address) ? "127.0.0.1" : v4Part(m.address) ? "::ffff:127.0.0.1" : "::1") : from.address;
2103
+ if (to.family === 6 && isV4(src))
2104
+ src = `::ffff:${src}`;
2105
+ return [to.owner, { type: "udp-message", sid: to.sid, data: m.data, from: { address: src, family: to.family, port: from.port } }];
2106
+ }
2107
+ #taken(family, address, port, v6only, reuse) {
2108
+ for (const s of this.#sockets.values()) {
2109
+ if (s.port !== port || (reuse && s.reuse))
2110
+ continue;
2111
+ if (s.family === family ? s.address === address || wildcard(s.address) || wildcard(address) : s.family === 6 ? s.address === "::" && !s.v6only : address === "::" && !v6only)
2112
+ return true;
2113
+ }
2114
+ return false;
2115
+ }
2116
+ #takes(s, dest) {
2117
+ const d4 = v4Part(dest);
2118
+ if (s.family === 4)
2119
+ return d4 !== null && (s.address === d4 || s.address === "0.0.0.0");
2120
+ if (d4 !== null && isV4(dest))
2121
+ return s.address === "::" && !s.v6only;
2122
+ return s.address === dest || s.address === "::";
2123
+ }
2124
+ }
2125
+ const isV4 = (a) => !a.includes(":");
2126
+ /** The pod's loopback, where host processes' UDP goes (host-exec's udp-socket.js loopback). */
2127
+ const loopback = (a) => /^127\.\d+\.\d+\.\d+$/.test(a) || a === "::1" || /^::ffff:127\.\d+\.\d+\.\d+$/i.test(a);
2128
+ const wildcard = (a) => a === "0.0.0.0" || a === "::";
2129
+ /** An address's IPv4 part (127.0.0.1 of ::ffff:127.0.0.1), or null for IPv6. */
2130
+ const v4Part = (a) => (isV4(a) ? a : (/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(a)?.[1] ?? null));
1223
2131
  //# sourceMappingURL=controller.js.map