Port Authority

Comlink, rebuilt for today's platform

Comlink made a worker feel like a local object. It was written when ports could carry far less than they can now. This page takes it apart, then puts it back together with what the platform has gained.

The result is one file with no dependencies, hawser.js (a hawser is the rope that ties a ship to a port; the name is a placeholder). Every demo below runs it between this page and real pages on other origins, and where it helps, runs Comlink 4.4.2 beside it.

How Comlink works

Comlink is about 650 lines, and the idea fits in five steps.

  1. wrap(port) returns a Proxy around an empty function. Reading a property does nothing but return another proxy that remembers the path so far.
  2. Calling it, awaiting it, assigning to it or using new posts one of six messages down the port: GET, SET, APPLY, CONSTRUCT, ENDPOINT or RELEASE, with the path and a random id.
  3. expose(object, port) listens on the other end, walks the path on the real object, does the thing, and posts the result back with the same id.
  4. Values go through structured clone. To send something by reference, such as a callback, you mark it with proxy(). Comlink then makes a new MessageChannel, exposes the value on one end, and transfers the other end in its place. Every proxied value is its own port.
  5. Extra types are handled by named transfer handlers, which is how thrown errors are flattened and rebuilt.
worker.postMessage({ id: "4f1c…", type: "APPLY", path: ["math", "add"],
  argumentList: [{ type: "RAW", value: 1 }, { type: "RAW", value: 2 }] });
// and back
port.postMessage({ id: "4f1c…", type: "RAW", value: 3 });

That design has aged well. What has changed is everything around it.

A call should fail when nobody is there to answer

Comlink keeps a map of promises waiting for replies and nothing ever empties it. If the worker crashes or the frame is closed, every call in flight waits forever. Here three things notice a departure. A page that is closing says goodbye on every link it holds. The port's new close event is used where the browser has it. And an optional heartbeat catches a side that crashed without a word. Whichever comes first, every pending call rejects with a LinkClosedError, and so does every later one. Ask the question, then remove the frame.

const api = wrap(port, { heartbeat: 1000, timeout: 30_000 });
try { await api.slow(); }
catch (error) { // LinkClosedError, or TimeoutError }
closed(api).then(() => showOffline());

Pass an AbortSignal and it arrives as one

An AbortSignal cannot be cloned, so with Comlink there is no way to cancel work you started. Here a signal in the arguments is swapped for a small token. The far side gets a real signal of its own, and when yours aborts, theirs does, with the same reason. The call also rejects on this side at once. If the caller simply disappears, every signal it sent is aborted, so work is never left running for nobody.

const controller = new AbortController();
const job = api.count(20, controller.signal);
cancelButton.onclick = () => controller.abort();

// on the other origin, nothing special
async count(to, signal) {
  for (let i = 1; i <= to; i++) { signal.throwIfAborted(); await step(i); }
}

Use an answer before it has arrived

With Comlink, each step that returns an object costs a full trip there and back, and a new port. Here a call returns something you can keep calling into straight away. Everything queued in the same tick is sent as one message, the far side runs the steps in order against the real values, and only one port is ever used. Across a worker boundary the saving is small. Across a slow hop, such as a relay or a WebRTC line, it is the difference between one wait and three.

// one message out
const title = await api.open("ideas").latest().title();

// Comlink: three round trips, three ports
const notebook = await old.open("ideas");
const note = await notebook.latest();
const title = await note.title();

Loop over something that is still happening elsewhere

An async generator on the far side can be read with for await on this side. Nothing is produced until it is asked for, so a slow reader slows the writer. Leave the loop and the generator's finally block runs over there. It also runs if the reader is garbage collected or its page goes away. For bytes, return a ReadableStream and it is moved across whole.

// there
async *ticks() {
  try { for (;;) yield await nextTick(); }
  finally { stopTicking(); }
}
// here
for await (const tick of api.ticks()) {
  if (enough(tick)) break; // stopTicking() runs on the other origin
}

Hand someone part of what you hold, and take it back

Comlink will walk any path a caller sends, including constructor, which on a function is a way to run arbitrary code in the exposing page. That is fine for your own worker and not for another origin. Here a path cannot leave the object's own surface, expose() can list the only paths allowed, and port() asks the owner to mint a new port for a third party that reaches less than you can. The guest talks to the owner directly. Abort the signal and its port dies.

expose(api, port, { only: ["counter", "search"] });

// a holder passes on less than it has
const revoke = new AbortController();
const forGuest = await port(api.counter, { only: ["read"], signal: revoke.signal });
guestWindow.postMessage("here", guestOrigin, [forGuest]);
revoke.abort(); // later

Lifetimes that end when a scope does

An object made for you on the far side is yours to end. Dispose of the proxy, with using or by hand, and its Symbol.dispose method is called over there. Forget to, and a FinalizationRegistry does it when the proxy is collected. Close the link, or lose it, and everything it was holding is disposed at once. Functions, class instances and iterators all share the one port, with a reference count kept by the side that owns them.

{
  using session = await new api.Session("ada");
  await session.who();
} // Session[Symbol.dispose]() has now run on the other origin

Then and now

Platform featureComlink 4Here
Port close eventNot used. Calls to a dead port hang.Pending and later calls reject. The event is in the HTML standard but Chromium 157 still keeps it behind the MessagePortCloseEvent flag, so a goodbye on pagehide and an optional heartbeat cover for it.
AbortSignalCannot be sent.Crosses as a working signal. Aborts when the caller goes away.
FinalizationRegistryAdded late, per port.Reference counted per object on one port. Disposal reaches the real object.
using and Symbol.disposeproxy[releaseProxy]()Every proxy is disposable. Disposing the root closes the link.
Async iterationNone.Async generators are read remotely, pull by pull, and cleaned up.
Transferable streamsNeed transfer().Things that can only be moved are moved. Buffers are copied unless you say transfer().
Errors in structured cloneRebuilt from name, message and stack as a plain Error.Sent as errors. The class, a custom name and the cause chain survive.
CallbacksEach needs proxy(), which writes a marker onto your object, and each gets a channel.Functions and class instances go by reference with no marking. Plain data is still copied.
IdentityA proxy sent back home arrives as a proxy of a proxy.It arrives as the original object. The same remote object always gives the same proxy.
Cross-originAny origin by default, any path.The origin must be named. Paths cannot reach the prototype. Allow lists, minted ports and revocation.
Round tripsOne per call.Calls made in one tick share a message, and can build on each other's results.
Assigning a propertyproxy.x = 1 sends a message you cannot await.Removed. It throws and tells you to call a method.

What is still out of reach

The whole surface

import { expose, wrap, connect, port, closed,
         share, give, transfer, offer, accept } from "/hawser.js";

expose(target, endpoint, { only, heartbeat, timeout, signal, onclose })
wrap(endpoint, { heartbeat, timeout, signal, onclose })
connect(target, endpoint)   // both directions: { remote, close, revoke, closed }
port(remote, { only, signal }) // a narrowed, revocable port to pass on
closed(remote)              // promise for why the link ended
share(object)               // send by reference
give(object)                // by reference, and theirs to dispose
transfer(buffer)            // move, do not copy
offer(window, origin)       // give a window a port, origin required
accept(origins, callback)   // take ports only from these origins

Source: hawser.js and its types, hawser.d.ts. The behaviour above is pinned down by 30 unit tests and a browser run across three origins, both in the repository. Comlink is by Surma and the Chrome Labs team, and is used here under its Apache 2.0 licence.