Port Authority

Port patterns / Streams, zero-copy data and RPC

Send only the readable side of a stream

A stream is directional, so you can hand one origin read-only access and another write-only access. The library site gets a ReadableStream it can only listen to; the florist site gets a WritableStream it can only post into. Close the feed or error the drop box and the other origin is cut off cleanly.

When you'd use this

A host app embeds both a read-only display widget and a write-only submission widget from different vendors. Transferring a ReadableStream to the display and a WritableStream to the submitter enforces directionality at the API level — and lets you error a spammy writer without interrupting anyone else.

Code

// listen only
library.postMessage({ readable }, origin, [readable]);

// write only
const writable = new WritableStream({ start(c) { box = c; }, write: keep });
florist.postMessage({ writable }, origin, [writable]);
box.error(new Error("shut"));               // later: their next write fails

In practice

// community noticeboard embedding both read-only displays and write-only submitters
let open = true;
const readable = new ReadableStream({ start(c) { feed = c; }, cancel() { open = false; } });
const keep = (notice) => { if (open) feed.enqueue(notice); };

// display iframe: can only read
const reader = readable.getReader();
for (;;) {
  const { value, done } = await reader.read();
  if (done) break;
  show(value);
}

// submitter iframe: can only write
const writer = writable.getWriter();
try { await writer.write("Tulips half price on Friday"); }
catch { show("Submission box closed"); }

How it works

A ReadableStream can only be read, and a WritableStream can only be written. Because each is independently transferable, handing out one half gives a site read-only or write-only access.

The library gets a ReadableStream (listen only); the florist gets a WritableStream (write only, unable to see other notes in the box). The owner keeps both controllers and can close or error either side independently.

Step by step

What each press of Next does in the demo above.

  1. Give the library the listening half. Transfers a read-only ReadableStream to the library's origin while keeping the controller here.
  2. Give the florist the writing half. Transfers a write-only WritableStream to the florist's origin.
  3. Florist: drop a note. The florist writes a note into the box without being able to read what else is inside.
  4. Close the feed. Closes the ReadableStream cleanly so the library knows the feed ended.
  5. Shut the drop box. Errors the WritableStream controller.
  6. Florist: drop a note. The florist's next write rejects immediately.

What you can build with it

Built and running below.

A sealed bid box that two rivals write into

A blind submission drop-box accepting notes from multiple origins that can't read each other's entries.

Two bidders on two origins each get something to write into, and nothing to read from. Their bids land in this page. Neither can see the other's bid, or even whether the other has bid. When the owner closes the box, both writers are refused from then on. It is a sealed auction with no server.

Code

const makeSlot = (who) => new WritableStream({
  start(controller) { slots.push(controller); },
  write(bid) { bids.push({ who, bid }); },
});
const slot = makeSlot("one");
bidderOne.postMessage({ slot }, "*", [slot]);   // write only
// closing time
slots.forEach((s) => s.error(new Error("bidding has closed")));

Step by step

What each press of Next does in this demo.

  1. Give each bidder a slot. Each bidder gets a stream it can write to and cannot read.
  2. Bidder one: bid. Bidder one's bid arrives here. Bidder two is told nothing.
  3. Bidder two: bid. Bidder two bids without knowing what it is up against.
  4. Close the box. The owner shuts both slots and names the winner.
  5. Bidder one: bid. A late bid is refused.

One feed, with a writing role and a reading role

Separating read-only and write-only capabilities on the same backing resource.

A greenhouse sensor should be able to report and never read. A dashboard should be able to read and never report. This page makes one stream and gives the writing end to the sensor and the reading end to the dashboard. Nobody has to check the roles. The sensor holds an object with no way to read, and the dashboard holds one with no way to write. The stream was made in this page and still runs through it, so readings stop if this page closes.

Code

const { readable, writable } = new TransformStream();
sensor.postMessage({ feed: writable }, "*", [writable]);       // can write, cannot read
dashboard.postMessage({ feed: readable }, "*", [readable]);    // can read, cannot write

Step by step

What each press of Next does in this demo.

  1. Give out the two ends. The sensor gets the writing end and the dashboard the reading end. This page keeps neither end, but the stream still runs through it.
  2. Sensor: report a reading. A reading goes from the sensor, through the stream in this page, to the dashboard.
  3. Sensor: try to read the feed. The sensor's end has nothing to read with.
  4. Dashboard: try to write a reading. The dashboard's end has nothing to write with.

Already running elsewhere

Things to try

  • Hand out both halves, drop a note from the florist, then close the feed and shut the drop box.
  • Try dropping another note after shutting the box to watch the florist's write reject.

Gotchas

  • A write to a transferred WritableStream can resolve before the far side rejects it.
  • Erroring a stream is final; create a fresh stream to reopen.
  • A ReadableStream isn't strictly covert-channel-free: the reader controls pull timing and can pass a reason to cancel(reason) (see the timing demo).
  • Transferred streams stall silently if an intermediate forwarding context closes.

References

The web platform features this page mentions, with what each one is, its documentation on MDN and the specification that defines it.

ReadableStream
A source of data that is read a piece at a time. It can be moved to another page or worker. MDNStreams Standard
WritableStream
A destination that data is written to a piece at a time. It can be moved to another page or worker. MDNStreams Standard

For more, see Further reading: articles, talks, papers, libraries and the specifications, collected in one place.