relay.mjs raw

   1  // relay.mjs — the page <-> Worker DOM boundary.
   2  //
   3  // A Moxie module runs in a Worker and the document lives on the page, so the
   4  // module cannot touch the DOM directly. It asks, and waits: the request goes
   5  // over a MessagePort, the page performs the operation from dom-ops.mjs and
   6  // answers through a SharedArrayBuffer, and the Worker's Atomics.wait on the
   7  // gate is what makes the call synchronous from inside wasm. The page thread
   8  // cannot use Atomics.wait at all, which is exactly why the module is in the
   9  // Worker and the page is the server.
  10  //
  11  // Every request is answered, including the ones with no value, so DOM order is
  12  // exact: a call that returns has already happened on the page. A failed
  13  // operation does not come back as a zero the module might mistake for a real
  14  // answer - the page puts the message in the buffer and the Worker throws, so a
  15  // broken DOM call kills the domain loudly instead of corrupting it quietly.
  16  import { domOps, methodName, INT, STR, I64 } from './dom-ops.mjs';
  17  
  18  export const RELAY = 'moxie.dom.relay';
  19  
  20  // Layout of the shared buffer: four i32 words of header, then UTF-8 payload.
  21  //   i32[0] gate    0 while the page is working, 1 on success, -1 on failure
  22  //   i32[1] int     an INT answer
  23  //   i32[2] len     payload length in bytes
  24  //   i32[3] seq     the sequence number of the request being answered
  25  const HEADER = 16;
  26  const PAYLOAD = 1 << 20;
  27  const WAIT_MS = 30000;
  28  
  29  const encoder = new TextEncoder();
  30  const decoder = new TextDecoder();
  31  
  32  // makeDomProxy builds the object the module's bridge calls instead of dom.mjs
  33  // when the document is one hop away. Its methods are named after dom.mjs's
  34  // exports, so the bridge in host.mjs has one shape whether the caller is on
  35  // the page or in a Worker.
  36  export function makeDomProxy(port) {
  37    const proxy = {};
  38    const client = port ? new RelayClient(port) : null;
  39    for (const op of Object.keys(domOps)) {
  40      proxy[methodName(op)] = (...args) => {
  41        if (!client) {
  42          // Only the root domain holds the page connection. A spawned domain
  43          // reaches the DOM by asking the page directly, which needs the page to
  44          // hand it a port; until then this is loud rather than silent.
  45          throw new Error(`dom.${op}: this domain has no DOM relay (only the root domain is connected to the page)`);
  46        }
  47        if (!domOps[op].run) throw new Error(`dom.${op}: ${domOps[op].why}`);
  48        return client.call(op, args, domOps[op].kind);
  49      };
  50    }
  51    return proxy;
  52  }
  53  
  54  // RelayClient is one domain's end of the boundary. The buffer is allocated on
  55  // first use, not at import: only a domain that touches the DOM needs it, and
  56  // SharedArrayBuffer does not exist outside a cross-origin isolated page.
  57  class RelayClient {
  58    constructor(port) {
  59      this.port = port;
  60      this.seq = 0;
  61      this.sab = null;
  62      this.i32 = null;
  63      this.payload = null;
  64    }
  65  
  66    call(op, args, kind) {
  67      if (!this.sab) {
  68        this.sab = new SharedArrayBuffer(HEADER + PAYLOAD);
  69        this.i32 = new Int32Array(this.sab);
  70        this.payload = new Uint8Array(this.sab, HEADER);
  71      }
  72      const i32 = this.i32;
  73      const mine = ++this.seq;
  74      i32[1] = 0;
  75      i32[2] = 0;
  76      i32[0] = 0; // clear the gate before the request can be seen
  77      this.port.postMessage({ relay: RELAY, seq: mine, op, args, sab: this.sab });
  78      const woke = Atomics.wait(i32, 0, 0, WAIT_MS);
  79      if (woke === 'timed-out') {
  80        throw new Error(`dom.${op}: the page did not answer within ${WAIT_MS}ms`);
  81      }
  82      if (i32[3] !== mine) {
  83        throw new Error(`dom.${op}: relay answer ${i32[3]} arrived for request ${mine}`);
  84      }
  85      if (i32[0] < 0) throw new Error('dom.' + op + ': ' + this.decode(i32[2]));
  86      if (kind === INT) return i32[1];
  87      if (kind === STR) return this.decode(i32[2]);
  88      if (kind === I64) return BigInt(this.decode(i32[2]));
  89      return undefined; // VOID
  90    }
  91  
  92    decode(len) {
  93      if (len <= 0) return '';
  94      // Firefox refuses to decode a view over a SharedArrayBuffer, so copy first.
  95      const copy = new Uint8Array(len);
  96      copy.set(this.payload.subarray(0, len));
  97      return decoder.decode(copy);
  98    }
  99  }
 100  
 101  // serveRelay answers the module's DOM requests on the page. host.mjs's
 102  // startDomain installs one per root domain, so a page needs no setup of its
 103  // own to host an app.
 104  export function serveRelay(port) {
 105    // A callback the page produces later - an event, a timer, a fetch reply -
 106    // travels back over the same port and is dispatched into the module's exports
 107    // by worker-host. The ids are the module's own web/callback handles, so the
 108    // code that registered the callback is the code that runs.
 109    const cb = {
 110      void: (id) => port.postMessage({ cb: 'void', id }),
 111      str: (id, s) => port.postMessage({ cb: 'str', id, s }),
 112      bool: (id, b) => port.postMessage({ cb: 'bool', id, b }),
 113      i6: (id, a) => port.postMessage({ cb: 'i6', id, a }),
 114      ss: (id, s, t) => port.postMessage({ cb: 'ss', id, s, t }),
 115    };
 116    port.addEventListener('message', (e) => {
 117      const m = e.data;
 118      if (!m || m.relay !== RELAY) return;
 119      const gate = new Int32Array(m.sab);
 120      const out = new Uint8Array(m.sab, HEADER);
 121      const answer = (state, str) => {
 122        let b = str === undefined ? null : encoder.encode(str);
 123        if (b && b.length > PAYLOAD) {
 124          // Truncating an answer would hand the module a string the page does
 125          // not have, so replace it with a message that says so.
 126          state = -1;
 127          b = encoder.encode(`answer exceeds the ${PAYLOAD}-byte relay buffer`);
 128        }
 129        if (b) out.set(b);
 130        gate[2] = b ? b.length : 0;
 131        gate[3] = m.seq;
 132        Atomics.store(gate, 0, state);
 133        Atomics.notify(gate, 0, 1);
 134      };
 135      const op = domOps[m.op];
 136      // An unknown op means the two halves of the relay disagree about the op
 137      // set; answering with an error makes that visible instead of hanging the
 138      // Worker on a request nobody will serve.
 139      if (!op) return answer(-1, `no such operation (${m.op})`);
 140      if (!op.run) return answer(-1, op.why);
 141      try {
 142        const v = op.run(m.args, cb);
 143        if (op.kind === INT) gate[1] = v;
 144        if (op.kind === STR || op.kind === I64) return answer(1, String(v));
 145        answer(1, undefined);
 146      } catch (err) {
 147        answer(-1, String((err && err.message) || err));
 148      }
 149    });
 150    port.start();
 151  }
 152