@webpodjs/sdk 0.3.0 → 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.
@@ -7,7 +7,7 @@ import { PipeWriter, createPipe } from "./pipe.js";
7
7
  import { hostPreflight } from "./preflight.js";
8
8
  import { HOST_ASSETS, HOST_CHUNKS, OUT_WINDOW, outCredit, outTaken, outUntaken, PROTOCOL, SYNC_HEADER } from "./protocol.js";
9
9
  import { routeTopLevel } from "./route.js";
10
- import { ShimBridge, treeRoots } from "./shim.js";
10
+ import { NOT_LEARNED, ShimBridge, treeRoots } from "./shim.js";
11
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
12
  // ended this long for its drain (#endThread).
13
13
  const RELAY_CLAIM_MS = 5000, RELAY_DRAIN_MS = 1000;
@@ -34,6 +34,9 @@ const ESRCH = 3;
34
34
  const EINVAL = 22;
35
35
  const EXIT_FALLBACK = 70;
36
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;
37
40
  /** The most a process may declare and still start in hostExec.memoryReserveMB (T340). */
38
41
  const SPARE_MB = 64;
39
42
  /** HostExecStatus.reason in a tab of a pod whose workspace another tab holds (T265). */
@@ -81,6 +84,12 @@ export class HostExecController {
81
84
  #gone = new Set();
82
85
  /** The children being started (spawn received, not in the table yet): pid -> its parent's Worker. */
83
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();
84
93
  /** The first host pid (hostPidBase): any pid below is the guest's. */
85
94
  #pidBase = HOST_PID_BASE;
86
95
  #queue = [];
@@ -331,14 +340,16 @@ export class HostExecController {
331
340
  */
332
341
  async _reloadTables() {
333
342
  const home = this.#o.env?.HOME ?? DEFAULT_ENV.HOME;
334
- const files = ["/etc/webpod/host-exec.json", `${home}/.cache/webpod/host-exec-fallback.json`];
343
+ const learned = `${home}/.cache/webpod/host-exec-fallback.json`;
344
+ const files = ["/etc/webpod/host-exec.json", learned];
335
345
  const all = new Set();
336
346
  for (const f of files) {
337
347
  try {
338
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)
339
350
  if (Array.isArray(t.guest))
340
351
  for (const g of t.guest)
341
- if (typeof g === "string")
352
+ if (typeof g === "string" && !(f === learned && NOT_LEARNED.has(g)))
342
353
  all.add(g);
343
354
  }
344
355
  catch {
@@ -418,9 +429,15 @@ export class HostExecController {
418
429
  });
419
430
  this.#ca = { files, env, key };
420
431
  }
421
- /** @internal A start's rootFiles (the pod's CA), when there are some. */
422
- _rootStart() {
423
- return this.#ca ? { rootFiles: this.#ca.files } : {};
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]])) } : {}) };
424
441
  }
425
442
  /** @internal The pod's CA variables, for a host process's environment (its own win). */
426
443
  _caEnv() {
@@ -606,6 +623,10 @@ export class HostExecController {
606
623
  w.dead = true;
607
624
  w.abort?.();
608
625
  this.#workers.delete(w);
626
+ if (w.stop) {
627
+ Atomics.store(w.stop, 0, 1);
628
+ Atomics.notify(w.stop, 0);
629
+ }
609
630
  w.w.terminate();
610
631
  w.session.close();
611
632
  for (const s of w.shares)
@@ -758,6 +779,10 @@ export class HostExecController {
758
779
  const w = (this.#o.createWorker ?? ((u) => new Worker(u)))(url);
759
780
  // (a wasi Worker's ctl answers a reserve only, T258: its error says why, in a few hundred bytes)
760
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));
761
786
  // One of its 9P sessions failed in the FS Worker: the process ends (exit 70), the Worker is retired.
762
787
  for (const s of all)
763
788
  s.onerror = (message) => {
@@ -820,6 +845,7 @@ export class HostExecController {
820
845
  options: { ...this.#o.workerOptions, msize: Math.min(Number(this.#o.workerOptions?.msize ?? DEFAULT_MSIZE), ...[session, ...shareSessions].map((s) => ringMessageMax(s.memory, s.req))) },
821
846
  ...(thread ? { thread } : {}),
822
847
  ...(wasi ? {} : { wasi: true }),
848
+ ...(rec.stop ? { stop: rec.stop.buffer } : {}),
823
849
  }, [...(netPort ? [netPort] : []), ...all.flatMap((s) => (s.events ? [s.events] : []))]);
824
850
  try {
825
851
  await booted;
@@ -960,6 +986,7 @@ export class HostExecController {
960
986
  return this.#reserve(rec, m.mb, m.what ?? "a host process");
961
987
  case "wasm-module":
962
988
  this.#wasmModules[m.key] = m.module;
989
+ (rec.modules ??= new Set()).add(m.key);
963
990
  return;
964
991
  case "mem": {
965
992
  const mem = (rec.mem ??= { last: null, waiting: new Map() });
@@ -1246,7 +1273,7 @@ export class HostExecController {
1246
1273
  };
1247
1274
  const o = this.#o;
1248
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 } : {}) };
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 ?? [])]);
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 ?? [])]);
1250
1277
  }
1251
1278
  /**
1252
1279
  * A WASIX program's wasm thread (host-exec's wasi-worker.js, T315): a wasi Worker booted with `parent`'s identity and
@@ -1276,7 +1303,7 @@ export class HostExecController {
1276
1303
  }
1277
1304
  };
1278
1305
  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]);
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]);
1280
1307
  }
1281
1308
  /**
1282
1309
  * A port's message to another thread of rec's process (impl-messaging.js post: Firefox delivers a SharedArrayBuffer
@@ -1433,7 +1460,7 @@ export class HostExecController {
1433
1460
  ...(spec.outCredit ? { outCredit: spec.outCredit } : {}),
1434
1461
  ...(spec.signals ? { signals: spec.signals } : {}),
1435
1462
  ...(spec.stdinDemand ? { stdinDemand: true } : {}),
1436
- ...this._rootStart(),
1463
+ ...this._startFields(w),
1437
1464
  }, [port]);
1438
1465
  if (parent?.dead)
1439
1466
  outUntaken(spec.outCredit);
@@ -1544,10 +1571,14 @@ export class HostExecController {
1544
1571
  return EPERM;
1545
1572
  const pid = Math.abs(m.pid);
1546
1573
  const e = this.#table.get(pid);
1547
- if (e) {
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) {
1548
1577
  if (m.signal) {
1549
1578
  // (a host child with a handler for it takes it there, T347; else its default action, its end)
1550
- if (e.signal?.(m.signum))
1579
+ if (e?.signal?.(m.signum))
1580
+ return 0;
1581
+ if (sync?.(m.signal) || !e)
1551
1582
  return 0;
1552
1583
  e.kill(signalName(m.signal));
1553
1584
  if (e.owner && !e.owner.dead)
@@ -1591,6 +1622,26 @@ export class HostExecController {
1591
1622
  return;
1592
1623
  await p.kill(signal).catch(() => { });
1593
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
+ }
1594
1645
  /** A blocking child: this table owns it and writes the result into the parent's control SAB. */
1595
1646
  #spawnSync(m, parent) {
1596
1647
  let ch = new MessageChannel();
@@ -1606,6 +1657,7 @@ export class HostExecController {
1606
1657
  return;
1607
1658
  done = true;
1608
1659
  clearTimeout(timer);
1660
+ this.#syncKills.delete(m.pid);
1609
1661
  ch.port1.close();
1610
1662
  writeSync(parent.ctl, { pid: m.pid, status: signal ? null : code, signal, ...(error !== undefined ? { error } : {}), segs: [] }, segs);
1611
1663
  // A node child that exited goes with its Worker and its process slot: no parent reaps it as one does an async
@@ -1613,16 +1665,27 @@ export class HostExecController {
1613
1665
  if (runner !== "guest")
1614
1666
  this.#table.get(m.pid)?.kill("SIGKILL");
1615
1667
  };
1668
+ let killed = false;
1616
1669
  const kill = (signal) => {
1617
1670
  if (runner === "guest")
1618
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;
1619
1676
  const e = this.#table.get(m.pid);
1620
1677
  if (e)
1621
1678
  e.kill(signalName(signal));
1622
1679
  else
1623
1680
  this.#gone.add(m.pid);
1624
- finish(null, signal);
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);
1625
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));
1626
1689
  // A host child that falls back (e4-integration.md §3.2): with nothing visible done yet it runs again in the guest
1627
1690
  // (its input written again; guestArgv: its own command line, before the route expanded it), else it ends with 70.
1628
1691
  // One killed or timed out meanwhile has its result already. One that read an inherited stdin (stdio[0] "inherit")
@@ -1923,7 +1986,7 @@ class HostProcess {
1923
1986
  for (const k of Object.keys(ca))
1924
1987
  if (!(k in own))
1925
1988
  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() });
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) });
1927
1990
  }
1928
1991
  catch (e) {
1929
1992
  // Nothing ran on the host: the guest runs it from the start.