supervisor.mjs raw

   1  // supervisor.mjs - the page's domain hub.
   2  //
   3  // A wasm domain runs in a Worker, and a Worker started by a Worker does not
   4  // begin to run while its creator is parked in Atomics.wait. The page is the
   5  // only realm that is never parked in wasm, so the page starts every domain and
   6  // every domain holds one MessagePort to it. This module is the logic behind
   7  // that port: ids, the tree, the message dispatch and the log queue.
   8  //
   9  // No DOM, no Worker, no page: the host passes in `start` (create a domain),
  10  // `stop` (kill one), `log`, `fault` and `exited`, so the whole protocol can be
  11  // driven from Node with fake ports. See docs/wasm-hub.md for the contract.
  12  //
  13  // The data plane does not come through here. A spawn channel is a ring the
  14  // spawning domain created; its handles ride in the boot payload, which the hub
  15  // forwards without reading.
  16  
  17  export function createHub(opts = {}) {
  18    const startDomain = opts.start;
  19    const stopDomain = opts.stop || (() => {});
  20    const logLine = opts.log || (() => {});
  21    const fault = opts.fault || (() => {});
  22    const exited = opts.exited || (() => {});
  23    const now = opts.now || (() => 0);
  24    const schedule = opts.schedule || null;
  25    // The log queue is bounded: a domain that prints without a reader (a trace
  26    // loop) must not grow the page without limit. Dropping is allowed only
  27    // because the drop is itself reported - a silent drop would make "no output"
  28    // ambiguous, which is the one thing this system may not do.
  29    const queueMax = opts.queueMax || 4096;
  30  
  31    const nodes = new Map();
  32    const roots = [];
  33    // ONE id space: a domain's id is taken from a single page-wide sequence at
  34    // spawn and never reused. The lineage is the chain of those ids (root 1,
  35    // its child 2 is "1.2", that child's child 3 is "1.2.3"), so the last
  36    // component IS the domain id - the same number the native runtime's
  37    // ch.childDomain carries.
  38    let domainSeq = 0;
  39    const stats = {
  40      spawned: 0, exited: 0, panics: 0, rebinds: 0,
  41      refusedSpawn: 0, portMismatch: 0, parentMismatch: 0, unknownKind: 0,
  42      unknownExit: 0, unknownPanic: 0, unknownHeartbeat: 0, unknownRebind: 0,
  43      unattributedLog: 0, drained: 0, dropped: 0, unattributedDropped: 0,
  44    };
  45  
  46    let queue = [];
  47    let scheduled = false;
  48    // Per-domain line assembly. Two domains print concurrently, and their writes
  49    // arrive in pieces: sharing one buffer would splice "b got" and "root got 10"
  50    // into a line neither program wrote. The hub is the only place that sees all
  51    // the ids, so it is where a line becomes whole.
  52    const partials = new Map();   // "<id>|<fd>" -> unterminated text
  53  
  54    function scheduleDrain() {
  55      if (scheduled || !schedule) return;
  56      scheduled = true;
  57      schedule(() => {
  58        scheduled = false;
  59        if (drain() > 0) scheduleDrain();
  60      });
  61    }
  62  
  63    function enqueue(entry, node) {
  64      if (queue.length >= queueMax) {
  65        stats.dropped++;
  66        if (node) node.dropped++;
  67        else stats.unattributedDropped++;
  68        return false;
  69      }
  70      queue.push(entry);
  71      scheduleDrain();
  72      return true;
  73    }
  74  
  75    // drain hands queued log lines to the page, in arrival order. Bounded so one
  76    // burst cannot hold the page's frame for longer than its batch.
  77    function drain(max = 256) {
  78      const n = Math.min(max, queue.length);
  79      for (let i = 0; i < n; i++) {
  80        logLine(queue[i]);
  81        stats.drained++;
  82      }
  83      if (n > 0) queue = queue.slice(n);
  84      return queue.length;
  85    }
  86  
  87    function emitLines(id, fd, text, node) {
  88      const key = id + '|' + fd;
  89      let buf = (partials.get(key) || '') + text;
  90      let nl;
  91      while ((nl = buf.indexOf('\n')) >= 0) {
  92        enqueue({ id, fd, text: buf.slice(0, nl + 1) }, node);
  93        buf = buf.slice(nl + 1);
  94      }
  95      if (buf.length > 0) partials.set(key, buf);
  96      else partials.delete(key);
  97    }
  98  
  99    // A domain that is done writing must not lose its last, unterminated line.
 100    function flushPartials(id, node) {
 101      for (const key of [...partials.keys()]) {
 102        const sep = key.indexOf('|');
 103        if (key.slice(0, sep) !== id) continue;
 104        const text = partials.get(key);
 105        partials.delete(key);
 106        enqueue({ id, fd: Number(key.slice(sep + 1)), text }, node);
 107      }
 108    }
 109  
 110    function nodeOf(id) {
 111      if (typeof id !== 'string') return null;
 112      return nodes.get(id) || null;
 113    }
 114  
 115    function childrenOf(id) {
 116      const out = [];
 117      for (const n of nodes.values()) if (n.parent === id) out.push(n.id);
 118      return out;
 119    }
 120  
 121    // retire removes one node. `adopt` is the clean-exit rule: its children
 122    // survive, re-parented to its parent and told so; without it the subtree is
 123    // being torn down and the children are retired separately.
 124    function retire(node, adopt) {
 125      if (!node || node.gone) return;
 126      node.gone = true;
 127      // The host decides what stopping means: a page host keeps a root's Worker
 128      // alive for callbacks and terminates every other domain.
 129      stopDomain(node.handle, node);
 130      flushPartials(node.id, node);
 131      // The drop report is the last line a domain says. It goes through the queue
 132      // when there is room and straight to the page when there is not: a summary
 133      // of lost diagnostics is the one line that may not be lost.
 134      if (node.dropped > 0) {
 135        const text = '[hub] ' + node.dropped + ' log line' + (node.dropped === 1 ? '' : 's')
 136          + ' dropped for ' + node.id + '\n';
 137        if (!enqueue({ id: node.id, fd: 2, text }, null)) logLine({ id: node.id, fd: 2, text });
 138      }
 139      if (node.root) {
 140        const at = roots.indexOf(node.id);
 141        if (at >= 0) roots.splice(at, 1);
 142      }
 143      const kids = childrenOf(node.id);
 144      const parent = nodes.get(node.parent) || null;
 145      if (parent) parent.children = parent.children.filter((c) => c !== node.id);
 146      if (adopt) {
 147        for (const cid of kids) {
 148          const c = nodes.get(cid);
 149          if (!c) continue;
 150          // A root's exit stops its tree, so the only adoption that reaches here
 151          // is an intermediate's: the children are grafted onto its parent.
 152          c.parent = node.parent;
 153          if (parent) parent.children.push(cid);
 154          stats.rebinds++;
 155          try { c.port && c.port.postMessage({ kind: 'rebind', parent: node.parent }); } catch (e) { /* the domain is gone */ }
 156        }
 157      }
 158      nodes.delete(node.id);
 159      stats.exited++;
 160      exited(node.id, node.root === true);
 161    }
 162  
 163    function stopSubtree(id) {
 164      const root = nodeOf(id);
 165      if (!root) return;
 166      const kids = childrenOf(id).slice();
 167      for (const cid of kids) stopSubtree(cid);
 168      retire(root, false);
 169    }
 170  
 171    function stopAll() {
 172      for (const id of [...roots]) stopSubtree(id);
 173      for (const id of [...nodes.keys()]) retire(nodes.get(id), false);
 174      roots.length = 0;
 175    }
 176  
 177    function attach({ id, parent, port, handle, root }) {
 178      if (typeof id !== 'string' || id.length === 0) throw new Error('supervisor.attach: id must be a non-empty string');
 179      if (nodes.has(id)) throw new Error('supervisor.attach: duplicate id ' + id);
 180      const node = {
 181        id, parent: parent || '0', port, handle: handle || null,
 182        children: [], spawned: 0, dropped: 0, lastSeen: now(), gone: false, root: root === true,
 183      };
 184      nodes.set(id, node);
 185      const p = nodes.get(node.parent);
 186      if (p) p.children.push(id);
 187      if (node.root) roots.push(id);
 188      return node;
 189    }
 190  
 191    // attachRoot gives a module's root domain the next root id. Ids are never
 192    // reused, so the counter is monotonic even after a root exits.
 193    function attachRoot({ port, handle }) {
 194      const id = String(++domainSeq);
 195      attach({ id, parent: '0', port, handle, root: true });
 196      return id;
 197    }
 198  
 199    // A refused spawn answers on the port it arrived on: that port belongs to the
 200    // sender whether or not its id is in the tree, and the sender must learn that
 201    // no domain was started for it.
 202    function refuse(port, id, reason) {
 203      stats.refusedSpawn++;
 204      const p = port || null;
 205      if (p) {
 206        try { p.postMessage({ kind: 'refused', id, reason }); } catch (e) { /* gone */ }
 207      }
 208    }
 209  
 210    function onSpawn(port, msg) {
 211      const node = nodeOf(msg.id);
 212      if (!node) { refuse(port, typeof msg.id === 'string' ? msg.id : '', 'unknown-sender'); return; }
 213      if (node.port !== port) { stats.portMismatch++; refuse(port, node.id, 'port-mismatch'); return; }
 214      if (typeof msg.parent === 'string' && msg.parent !== node.parent) stats.parentMismatch++;
 215      if (!startDomain) { refuse(port, node.id, 'no-start'); return; }
 216      const childId = node.id + '.' + (++domainSeq);
 217      const boot = {
 218        kind: 'entry',
 219        id: childId,
 220        parent: node.id,
 221        wasm: msg.wasm,
 222        fnIdx: msg.fnIdx,
 223        args: msg.args,
 224        chans: msg.chans,
 225        breaker: msg.breaker,
 226      };
 227      const started = startDomain(boot);
 228      if (!started || !started.port) throw new Error('supervisor: start() must return { handle, port }');
 229      attach({ id: childId, parent: node.id, port: started.port, handle: started.handle, root: false });
 230      stats.spawned++;
 231    }
 232  
 233    // handle is the one entry point for a message that arrived on a domain's
 234    // port. Control and logs are dispatched separately: a stale id may still
 235    // print its log line, but it may not drive the tree.
 236    function handle(port, msg) {
 237      if (!msg || typeof msg.kind !== 'string') { stats.unknownKind++; return; }
 238      switch (msg.kind) {
 239        case 'log': {
 240          const node = nodeOf(msg.id);
 241          if (!node) stats.unattributedLog++;
 242          else if (node.port !== port) stats.portMismatch++;
 243          emitLines(node ? node.id : '?', msg.fd === 2 ? 2 : 1, String(msg.text == null ? '' : msg.text), node);
 244          return;
 245        }
 246        case 'spawn': onSpawn(port, msg); return;
 247        case 'exit': {
 248          const node = nodeOf(msg.id);
 249          if (!node) { stats.unknownExit++; return; }
 250          // Every clean exit adopts. A root's exit is not a process exit on wasm:
 251          // the page keeps the root Worker for callbacks, and its children are
 252          // still live capabilities the app holds breakers for. A page teardown
 253          // (stopAll) is what ends a tree.
 254          retire(node, true);
 255          return;
 256        }
 257        case 'panic': {
 258          const node = nodeOf(msg.id);
 259          if (!node) { stats.unknownPanic++; return; }
 260          stats.panics++;
 261          // Native parity: a panic aborts the process, so the page stops every
 262          // domain on it. The tree is empty afterwards; the fault is the story.
 263          stopAll();
 264          fault({ id: node.id, text: String(msg.text == null ? '' : msg.text) });
 265          return;
 266        }
 267        case 'rebind':
 268          // Hub -> domain only. A domain asking to move itself is a bug in the
 269          // sender, not an instruction to follow.
 270          stats.unknownRebind++;
 271          return;
 272        case 'heartbeat': {
 273          const node = nodeOf(msg.id);
 274          if (!node) { stats.unknownHeartbeat++; return; }
 275          node.lastSeen = now();
 276          return;
 277        }
 278        default:
 279          stats.unknownKind++;
 280      }
 281    }
 282  
 283    function tree() {
 284      const out = {};
 285      for (const n of nodes.values()) {
 286        out[n.id] = { parent: n.parent, children: n.children.slice(), root: n.root === true };
 287      }
 288      return out;
 289    }
 290  
 291    // panic is the host's entry point for a Worker that died without posting:
 292    // the page saw its error event, not a message from the domain.
 293    function panic(id, text) {
 294      handle(null, { kind: 'panic', id, text });
 295    }
 296  
 297    return { attach, attachRoot, handle, panic, drain, tree, stopAll, stopSubtree, stats: () => stats, pending: () => queue.length };
 298  }
 299