hub.test.mjs raw

   1  // The hub protocol, with no browser and no Worker: fake ports in, messages
   2  // out. docs/wasm-hub.md is the contract these tests assert.
   3  import test from 'node:test';
   4  import assert from 'node:assert/strict';
   5  import { createHub } from '../../jsruntime/supervisor.mjs';
   6  
   7  function fakePort() {
   8    const sent = [];
   9    return { sent, postMessage: (m) => sent.push(m), start() {} };
  10  }
  11  
  12  function makeHub(opts = {}) {
  13    const state = { started: [], stopped: [], logs: [], faults: [], exits: [], clock: 1000 };
  14    const hub = createHub({
  15      queueMax: opts.queueMax,
  16      start: (boot) => {
  17        const port = fakePort();
  18        const handle = 'w-' + boot.id;
  19        state.started.push({ boot, port, handle });
  20        return { handle, port };
  21      },
  22      stop: (h, node) => state.stopped.push({ handle: h, root: !!(node && node.root) }),
  23      log: (e) => state.logs.push(e),
  24      fault: (f) => state.faults.push(f),
  25      exited: (id, root) => state.exits.push({ id, root }),
  26      now: () => state.clock,
  27    });
  28    return { hub, ...state };
  29  }
  30  
  31  function bootOf(state, id) {
  32    return state.started.find((s) => s.boot.id === id);
  33  }
  34  
  35  function handles(state) {
  36    return state.stopped.map((s) => s.handle);
  37  }
  38  
  39  function spawn(hub, port, id, parent = '0') {
  40    hub.handle(port, { kind: 'spawn', id, parent, wasm: '/app.wasm', fnIdx: 0, args: new Uint8Array(0), chans: [], breaker: null });
  41  }
  42  
  43  test('lineage ids and parents are assigned by the hub', () => {
  44    const { hub, started } = makeHub();
  45    const root = fakePort();
  46    assert.equal(hub.attachRoot({ port: root, handle: 'w-1' }), '1');
  47    spawn(hub, root, '1');
  48    assert.equal(started[0].boot.id, '1.2');
  49    assert.equal(started[0].boot.parent, '1');
  50    spawn(hub, started[0].port, '1.2', '1');
  51    assert.equal(started[1].boot.id, '1.2.3');
  52    assert.equal(started[1].boot.parent, '1.2');
  53    const t = hub.tree();
  54    assert.equal(t['1.2.3'].parent, '1.2');
  55    assert.deepEqual(t['1'].children, ['1.2']);
  56  });
  57  
  58  test('the boot payload crosses untouched', () => {
  59    const { hub, started } = makeHub();
  60    const root = fakePort();
  61    hub.attachRoot({ port: root, handle: 'w-1' });
  62    const args = new Uint8Array([1, 2, 3]);
  63    const chans = [{ handle: 7, sab: { fake: true } }];
  64    hub.handle(root, { kind: 'spawn', id: '1', parent: '0', wasm: '/x.wasm', fnIdx: 42, args, chans, breaker: { handle: 9 } });
  65    const b = started[0].boot;
  66    assert.equal(b.fnIdx, 42);
  67    assert.equal(b.wasm, '/x.wasm');
  68    assert.equal(b.args, args);
  69    assert.equal(b.chans, chans);
  70    assert.deepEqual(b.breaker, { handle: 9 });
  71  });
  72  
  73  test('a spawn from an unknown id is refused, not started', () => {
  74    const { hub, started } = makeHub();
  75    const ghost = fakePort();
  76    spawn(hub, ghost, '9.9', '9');
  77    assert.equal(started.length, 0);
  78    assert.equal(hub.stats().refusedSpawn, 1);
  79    assert.equal(ghost.sent[0].kind, 'refused');
  80    assert.equal(ghost.sent[0].reason, 'unknown-sender');
  81  });
  82  
  83  test('a spawn on the wrong port is refused', () => {
  84    const { hub, started } = makeHub();
  85    const root = fakePort();
  86    hub.attachRoot({ port: root, handle: 'w-1' });
  87    const other = fakePort();
  88    spawn(hub, other, '1', '0');
  89    assert.equal(started.length, 0);
  90    assert.equal(hub.stats().portMismatch, 1);
  91    assert.equal(other.sent[0].reason, 'port-mismatch');
  92  });
  93  
  94  test('logs from an unknown id are printed as ? and counted, never dropped', () => {
  95    const { hub, logs } = makeHub();
  96    hub.handle(fakePort(), { kind: 'log', id: '2.7', fd: 2, text: 'ghost line\n' });
  97    assert.equal(hub.pending(), 1);
  98    hub.drain();
  99    assert.deepEqual(logs, [{ id: '?', fd: 2, text: 'ghost line\n' }]);
 100    assert.equal(hub.stats().unattributedLog, 1);
 101  });
 102  
 103  test('the orphan invariant: A exits, B keeps logging and exits cleanly', () => {
 104    const { hub, started, stopped, logs } = makeHub();
 105    const root = fakePort();
 106    hub.attachRoot({ port: root, handle: 'w-1' });
 107    spawn(hub, root, '1');                       // A = 1.1
 108    const a = bootOf({ started }, '1.2');
 109    spawn(hub, a.port, '1.2', '1');              // B = 1.1.1
 110    const b = bootOf({ started }, '1.2.3');
 111  
 112    hub.handle(a.port, { kind: 'exit', id: '1.2' });
 113    assert.ok(handles({ stopped }).includes('w-1.2'), 'A was stopped');
 114    assert.equal(hub.tree()['1.2'], undefined);
 115    assert.equal(hub.tree()['1.2.3'].parent, '1', 'B was adopted by the root');
 116    assert.ok(b.port.sent.some((m) => m.kind === 'rebind' && m.parent === '1'), 'B was told');
 117  
 118    hub.handle(b.port, { kind: 'log', id: '1.2.3', fd: 1, text: 'b alive\n' });
 119    hub.drain();
 120    assert.deepEqual(logs.at(-1), { id: '1.2.3', fd: 1, text: 'b alive\n' });
 121  
 122    hub.handle(b.port, { kind: 'exit', id: '1.2.3' });
 123    assert.equal(hub.tree()['1.2.3'], undefined);
 124    assert.equal(hub.stats().exited, 2);
 125  });
 126  
 127  test('a parent parked in a receive does not block its child', () => {
 128    const { hub, started, logs } = makeHub();
 129    const root = fakePort();
 130    hub.attachRoot({ port: root, handle: 'w-1' });
 131    spawn(hub, root, '1');                       // A = 1.1
 132    const a = bootOf({ started }, '1.2');
 133    // A sends one spawn and then nothing else - it is parked inside the wasm
 134    // receive its child will wake. The hub must start the child and carry its
 135    // messages without A pumping anything.
 136    spawn(hub, a.port, '1.2', '1');              // B = 1.1.1
 137    const b = bootOf({ started }, '1.2.3');
 138    hub.handle(b.port, { kind: 'log', id: '1.2.3', fd: 1, text: 'b up\n' });
 139    hub.drain();
 140    assert.equal(started.length, 2);
 141    assert.deepEqual(logs.at(-1), { id: '1.2.3', fd: 1, text: 'b up\n' });
 142    assert.equal(a.port.sent.length, 0, 'nothing was required of the parked parent');
 143  });
 144  
 145  test('a panic stops every domain and reports one fault', () => {
 146    const { hub, started, stopped, faults } = makeHub();
 147    const root = fakePort();
 148    hub.attachRoot({ port: root, handle: 'w-1' });
 149    spawn(hub, root, '1');
 150    const a = bootOf({ started }, '1.2');
 151    spawn(hub, a.port, '1.2', '1');
 152    const b = bootOf({ started }, '1.2.3');
 153    hub.handle(b.port, { kind: 'panic', id: '1.2.3', text: 'boom' });
 154    assert.equal(faults.length, 1);
 155    assert.equal(faults[0].id, '1.2.3');
 156    assert.deepEqual(handles({ stopped }).sort(), ['w-1', 'w-1.2', 'w-1.2.3']);
 157    assert.deepEqual(hub.tree(), {});
 158  });
 159  
 160  test('a root exit keeps its live children; a new root never reuses an id', () => {
 161    const { hub, started, stopped } = makeHub();
 162    const one = fakePort();
 163    const two = fakePort();
 164    const oneId = hub.attachRoot({ port: one, handle: 'w-1' });
 165    const twoId = hub.attachRoot({ port: two, handle: 'w-2' });
 166    assert.deepEqual([oneId, twoId], ['1', '2']);
 167    spawn(hub, one, '1');                        // child 3 -> 1.3
 168    spawn(hub, two, '2');                        // child 4 -> 2.4
 169    hub.handle(one, { kind: 'exit', id: '1' });
 170    // The page keeps the root Worker for callbacks, so a clean root exit is not a
 171    // tree kill: its child is adopted by the hub and keeps running.
 172    assert.equal(hub.tree()['1'], undefined);
 173    assert.equal(hub.tree()['1.3'].parent, '0');
 174    assert.ok(!handles({ stopped }).includes('w-1.3'));
 175    const three = fakePort();
 176    assert.equal(hub.attachRoot({ port: three, handle: 'w-5' }), '5');
 177    hub.stopAll();
 178    // The hub ASKS for every node to stop, and tells the host whether it is a
 179    // root: a page host keeps the root's Worker alive for callbacks and stops
 180    // every other domain.
 181    assert.deepEqual(stopped.find((s) => s.handle === 'w-1'), { handle: 'w-1', root: true });
 182    assert.deepEqual(stopped.find((s) => s.handle === 'w-2'), { handle: 'w-2', root: true });
 183    assert.deepEqual(stopped.find((s) => s.handle === 'w-5'), { handle: 'w-5', root: true });
 184    assert.deepEqual(stopped.filter((s) => s.handle === 'w-1.3'), [{ handle: 'w-1.3', root: false }]);
 185    assert.deepEqual(handles({ stopped }).sort(), ['w-1', 'w-1.3', 'w-2', 'w-2.4', 'w-5']);
 186  });
 187  
 188  test('heartbeat updates lastSeen; an unknown heartbeat is counted only', () => {
 189    const { hub } = makeHub();
 190    const root = fakePort();
 191    hub.attachRoot({ port: root, handle: 'w-1' });
 192    const before = hub.tree()['1'];
 193    hub.handle(root, { kind: 'heartbeat', id: '1' });
 194    assert.deepEqual(hub.tree()['1'], before);
 195    hub.handle(root, { kind: 'heartbeat', id: '7.7' });
 196    assert.equal(hub.stats().unknownHeartbeat, 1);
 197  });
 198  
 199  test('a rebind addressed to the hub is a protocol error, not an instruction', () => {
 200    const { hub } = makeHub();
 201    const root = fakePort();
 202    hub.attachRoot({ port: root, handle: 'w-1' });
 203    hub.handle(root, { kind: 'rebind', parent: '0' });
 204    assert.equal(hub.tree()['1'].parent, '0');
 205    assert.equal(hub.stats().unknownRebind, 1);
 206  });
 207  
 208  test('lines are assembled per domain, so two domains cannot splice one another', () => {
 209    const { hub, started, logs } = makeHub();
 210    const root = fakePort();
 211    hub.attachRoot({ port: root, handle: 'w-1' });
 212    spawn(hub, root, '1');                       // child 1.1
 213    const child = started[0].port;
 214    // Interleave the two domains' pieces; each line must stay whole.
 215    hub.handle(root, { kind: 'log', id: '1', fd: 1, text: 'root got' });
 216    hub.handle(child, { kind: 'log', id: '1.2', fd: 1, text: 'b got' });
 217    assert.equal(hub.drain(), 0, 'no line is complete yet');
 218    hub.handle(root, { kind: 'log', id: '1', fd: 1, text: ' 10\n' });
 219    hub.handle(child, { kind: 'log', id: '1.2', fd: 1, text: ' 7\n' });
 220    hub.drain();
 221    assert.deepEqual(logs.slice(-2), [
 222      { id: '1', fd: 1, text: 'root got 10\n' },
 223      { id: '1.2', fd: 1, text: 'b got 7\n' },
 224    ]);
 225    // A domain that exits with an unterminated line still gets it printed.
 226    hub.handle(child, { kind: 'log', id: '1.2', fd: 1, text: 'unterminated' });
 227    hub.handle(child, { kind: 'exit', id: '1.2' });
 228    hub.drain();
 229    assert.deepEqual(logs.at(-1), { id: '1.2', fd: 1, text: 'unterminated' });
 230  });
 231  
 232  test('an overflowing queue drops with a per-domain count, reported at exit', () => {
 233    const { hub, logs } = makeHub({ queueMax: 3 });
 234    const root = fakePort();
 235    hub.attachRoot({ port: root, handle: 'w-1' });
 236    for (let i = 0; i < 5; i++) hub.handle(root, { kind: 'log', id: '1', fd: 1, text: 'line ' + i + '\n' });
 237    assert.equal(hub.pending(), 3);
 238    assert.equal(hub.stats().dropped, 2);
 239    hub.handle(root, { kind: 'exit', id: '1' });
 240    hub.drain();
 241    // The summary must survive the full queue: a lost drop report would make
 242    // "no output" ambiguous.
 243    assert.ok(logs.some((l) => l.id === '1' && l.fd === 2 && l.text.includes('2 log lines dropped for 1')),
 244      JSON.stringify(logs));
 245  });
 246  
 247  test('the log queue drains in order and in bounded batches', () => {
 248    const { hub, logs } = makeHub();
 249    const root = fakePort();
 250    hub.attachRoot({ port: root, handle: 'w-1' });
 251    for (let i = 0; i < 300; i++) hub.handle(root, { kind: 'log', id: '1', fd: 1, text: 'line ' + i + '\n' });
 252    assert.equal(hub.pending(), 300);
 253    assert.equal(hub.drain(256), 44);
 254    assert.equal(logs.length, 256);
 255    assert.equal(logs[0].text, 'line 0\n');
 256    assert.equal(logs[255].text, 'line 255\n');
 257    hub.drain();
 258    assert.equal(logs.length, 300);
 259    assert.equal(logs[299].text, 'line 299\n');
 260    assert.equal(hub.stats().drained, 300);
 261  });
 262