Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/startup-snapshot.md
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ once.
| -------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| `src/workerd/jsg/snapshot-test.c++` | restore-time globals: install, removal, rejection cases; live-wrappable round trip (stateless, cloned, dropped and untransferable types), `dropUnreachableWrappables()` and `releaseSlotsWithChecks()` findings; FinalizationRegistry cleanups settled before the record, rejected after it |
| `src/rust/jsg-test/tests/startup_snapshot.rs` | Rust resources: state, shared templates, relinked references, and a type without `SnapshotTransfer` |
| `src/workerd/api/tests/startup-snapshot-globals-test` | top-level code touching `Error.stackTraceLimit`, `WebAssembly`, `Iterator`, `Temporal` (with and without the flag), a frozen `Date.prototype`, deleted restore-time globals, and the `process`/`Buffer` globals |
| `src/workerd/api/tests/startup-snapshot-globals-test` | top-level code touching `Error.stackTraceLimit`, `WebAssembly`, `Iterator`, `Temporal` (with and without the flag), a frozen `Date.prototype`, deleted restore-time globals, the `process`/`Buffer` globals, and the lazy `MessageChannel`/`MessagePort` globals, read and unread at the top level |
| `src/workerd/api/tests/startup-snapshot-listeners-test` | top-level `addEventListener()` across the snapshot: `once`, `passive`, an object listener's `handleEvent`, a replaced global `addEventListener`; `signal` fallback |
| `src/workerd/api/tests/startup-snapshot-functions-test` | a top-level `createRequire()` function across the snapshot; an `AsyncLocalStorage.bind()` function falls back |
| `src/workerd/api/tests/startup-snapshot-modules-test` | module identity across the snapshot (ESM, JSON, CJS, `node:buffer`) |
Expand Down
10 changes: 10 additions & 0 deletions src/per_isolate/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,16 @@ at context creation, before any user code. C++ entry point:
the native `utils.structuredClone()`), which replaces the C++ method; its
parity suite and divergence ledger are in `src/tests/structured-clone/`, and
its types in `types/defines/structured-clone.d.ts`.
- `main.ts` defines `MessageChannel` and `MessagePort` (`messagechannel/`)
under `expose_global_message_channel`, as lazy data properties
(`utils.defineLazyDataProperty()`): `messagechannel/messagechannel` loads
on first use, through them or through `cloudflare-internal:messagechannel`
(`requireBootstrapExport()` in `per-isolate-bootstrap.h`), which
`node:worker_threads` uses. Use the same for any other global few Workers
need. A module loaded on first use runs after user code, so its top level
must not read what user code can change, such as a constructor's
`prototype`, which `extends` reads; see `EventTargetHeritage` in
`messagechannel/messagechannel.ts`.
- EventTarget subclasses reach the (still C++) EventTarget they extend only
through `events/event-target-internals`; see `events/AGENTS.md`.
- Modules get `DOMException` from `require('dom-exception')`, which
Expand Down
67 changes: 19 additions & 48 deletions src/per_isolate/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,54 +327,25 @@ if (compatFlags['typescript_implemented_streams']) {
}
}

// The TypeScript MessageChannel and MessagePort replace the C++ ones. They are
// loaded whether or not they become globals: cloudflare-internal:messagechannel
// (used by node:worker_threads) reads them from this module's exports
// (MessageChannelModule in api/messagechannel.h).
if (autogates['ts-message-channel']) {
const {
MessageChannel,
MessagePort,
} = require('messagechannel/messagechannel');
if (compatFlags['expose_global_message_channel']) {
// Installed where JSG_NESTED_TYPE installs the C++ classes, with the same
// attributes: always on the global scope's prototype, with all three true,
// and under spec_compliant_property_attributes also as own properties of
// the global, non-enumerable per Web IDL.
ObjectDefineProperties(ObjectGetPrototypeOf(globalThis), {
MessageChannel: {
__proto__: null,
configurable: true,
enumerable: true,
writable: true,
value: MessageChannel,
},
MessagePort: {
__proto__: null,
configurable: true,
enumerable: true,
writable: true,
value: MessagePort,
},
});
if (compatFlags['spec_compliant_property_attributes']) {
ObjectDefineProperties(globalThis, {
MessageChannel: {
__proto__: null,
configurable: true,
enumerable: false,
writable: true,
value: MessageChannel,
},
MessagePort: {
__proto__: null,
configurable: true,
enumerable: false,
writable: true,
value: MessagePort,
},
});
}
// MessageChannel and MessagePort are loaded on first use, since few Workers
// use them: through the globals defined here, or through
// cloudflare-internal:messagechannel (MessageChannelModule in
// api/messagechannel.h), which node:worker_threads uses. Whichever comes first
// loads the module; the other finds it in the require() cache.
if (compatFlags['expose_global_message_channel']) {
const { defineLazyDataProperty } = utils;
const specifier = 'messagechannel/messagechannel';
// Defined as JSG_NESTED_TYPE defines a global class: always on the global
// scope's prototype, with all three attributes true, and under
// spec_compliant_property_attributes also as own properties of the global,
// non-enumerable per Web IDL. Each is a lazy data property, an ordinary data
// property once read.
const globalPrototype = ObjectGetPrototypeOf(globalThis) as object;
defineLazyDataProperty(globalPrototype, 'MessageChannel', specifier, true);
defineLazyDataProperty(globalPrototype, 'MessagePort', specifier, true);
if (compatFlags['spec_compliant_property_attributes']) {
defineLazyDataProperty(globalThis, 'MessageChannel', specifier, false);
defineLazyDataProperty(globalThis, 'MessagePort', specifier, false);
}
}

Expand Down
109 changes: 68 additions & 41 deletions src/per_isolate/messagechannel/messagechannel.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,62 @@
'use strict';

// MessageChannel and MessagePort, under the TS_MESSAGE_CHANNEL autogate. They
// replace the C++ classes in api/messagechannel.h, whose header lists where
// both depart from the HTML standard (no transfer lists, no serialization of
// ports, the extra messageerror event, a queue that follows every 'message'
// listener). This implementation keeps every one of those behaviors; only
// the differences below are its own. src/tests/events/messagechannel/
// runs one suite against both implementations, and its AGENTS.md records
// where each difference is pinned.
// MessageChannel and MessagePort, an approximation of the HTML standard's
// that departs from it as follows:
//
// DIFFERENCES FROM THE C++ IMPLEMENTATION
// - Transfer lists are not supported. postMessage() converts and reads its
// options but throws for a non-empty list, and a port cannot be
// serialized, so it cannot be sent anywhere.
// - A message that cannot be serialized makes postMessage() throw, rather
// than making the receiving port dispatch 'messageerror'. Instead, a
// throwing 'message' listener, whose exception is reported per spec,
// makes the port additionally dispatch a 'messageerror' event carrying
// the exception as its data, which the spec does not do.
// - The port message queue follows the port's 'message' listeners, as in
// Node.js. While the port has any, whether assigned to onmessage or added
// with addEventListener() (which per spec does not enable the queue),
// messages are delivered; once the last is removed, they are queued until
// another arrives or start() is called. Queued messages are held as JS
// values, with no memory accounting of their own, and do not keep their
// port from being collected.
// - close() fires 'close' on both ports, as Node.js does; the spec removed
// that event. A port whose peer is collected closes without one, when it
// next looks for the peer (posting, closing, starting, or a change in its
// 'message' listeners), at a time that depends on the collector.
// - Unlike in Node.js, an open port keeps nothing running, though closing
// ports when done with them is still best.
//
// - MessagePort's constructor inherits from EventTarget's, as WebIDL
// requires (C++ leaves its [[Prototype]] at Function.prototype), and both
// constructors' `prototype` is non-writable even without
// immutable_api_prototypes. Calling either without `new` throws the
// language's TypeError rather than JSG's.
// - A port whose peer is garbage collected is closed when it next looks for
// the peer (posting, closing, starting, or a change in its 'message'
// listeners), rather than when the peer's destructor runs. Either way the
// port closes without a 'close' event, at a time that depends on the
// collector, and no further message can reach it.
// - postMessage() always deserializes the message, even when the peer turns
// out to be gone, since the peer is looked for only after serialization,
// which runs user code that may close a port.
// - An array passed as postMessage()'s options is recognized by
// Array.isArray(), which sees through a proxy; JSG does not.
// Some webmessaging WPTs fail because of these, and many more need windows,
// workers or BroadcastChannel; src/wpt/webmessaging-test.ts records which
// run, and why the others do not pass.
//
// Otherwise the classes look as JSG's do (see the end of this file), except
// that MessagePort's constructor inherits from EventTarget's, as WebIDL
// requires, where a JSG constructor's [[Prototype]] is Function.prototype;
// both constructors' `prototype` is non-writable even without
// immutable_api_prototypes; calling either without `new` throws the
// language's TypeError rather than JSG's; and an array passed as
// postMessage()'s options is recognized by Array.isArray(), which sees
// through a proxy, where JSG's conversion does not.
//
// src/tests/events/messagechannel/ specifies the behavior, and its AGENTS.md
// indexes which test pins what.
//
// HOW IT FITS TOGETHER
//
// A port is a real EventTarget, extending the C++ one through
// events/event-target-internals. Its listener-count hook on 'message' starts
// the port when the first listener arrives and returns it to queueing when
// the last leaves, as listenerCountChanged() does in C++. Messages are cloned
// with utils.cloneMessageData() and dispatched from reactions scheduled with
// utils.queueReaction(), as C++ schedules them on js.resolvedPromise(), so a
// throw that escapes a delivery is an unhandled rejection in both. Each port
// is branded "workerd:MessagePort" so that C++ accepts it as a MessageEvent's
// source or one of its ports.
// the last leaves. Messages are cloned with utils.cloneMessageData() and
// dispatched from reactions scheduled with utils.queueReaction(), so a throw
// that escapes a delivery is an unhandled rejection. Each port is branded
// "workerd:MessagePort" so that C++ accepts it as a MessageEvent's source or
// one of its ports.
//
// The peer is held weakly, as C++ holds it, so dropping one port of a pair
// lets it be collected; the MessageChannel holds both strongly.
// The peer is held weakly, so dropping one port of a pair lets it be
// collected; the MessageChannel holds both strongly.
//
// main.ts loads this module on first use, so its top level runs after user
// code and reads nothing that code can change (see EventTargetHeritage).

import type {
EventTargetInternals,
Expand All @@ -52,8 +68,10 @@ const {
ArrayIsArray,
ArrayPrototypePush,
Error,
EventTargetPrototype,
ObjectDefineProperties,
ObjectGetOwnPropertyDescriptor,
ObjectSetPrototypeOf,
Symbol,
TypeError,
WeakRef,
Expand All @@ -75,7 +93,8 @@ const {
const { markAsRuntimeClass, setNameAndLength } =
require('runtime-class') as RuntimeClassHelpers;

// JSG's messages, so that misuse reads the same as with the C++ classes.
// JSG's messages, so that misuse reads as it does with the runtime's C++
// classes.
const kIllegalInvocation =
'Illegal invocation: function called with incorrect `this` reference. ' +
'See https://developers.cloudflare.com/workers/observability/errors/' +
Expand Down Expand Up @@ -106,9 +125,9 @@ function transferListLength(list: unknown[]): number {
return length;
}

// Converts postMessage()'s second argument, as JSG converts the C++
// method's `jsg::Optional<kj::OneOf<TransferList, PostMessageOptions>>`,
// and reports whether it names anything to transfer.
// Converts postMessage()'s second argument, an optional
// `(sequence<any> or PostMessageOptions)`, as JSG converts such a union, and
// reports whether it names anything to transfer.
function hasTransfer(options: unknown): boolean {
if (options === undefined || options === null) return false;
if (ArrayIsArray(options)) {
Expand All @@ -132,7 +151,15 @@ let entangle: (port1: MessagePort, port2: MessagePort) => void;
// port, primitives and undefined included, is an illegal invocation.
let requirePort: (receiver: unknown) => void;

class MessagePort extends EventTarget {
// This module loads on first use, when user code may already have replaced
// EventTarget.prototype, which `extends EventTarget` would read. MessagePort
// is defined over this stand-in instead, whose `prototype` is the one the
// bootstrap captured, and then inherits from EventTarget itself, which is
// what super() calls: it looks the parent constructor up when it runs.
function EventTargetHeritage(): void {}
EventTargetHeritage.prototype = EventTargetPrototype;

class MessagePort extends (EventTargetHeritage as unknown as typeof EventTarget) {
#state: PortState = 'pending';
#pending: unknown[] = [];
#peer: WeakRef<MessagePort> | undefined = undefined;
Expand Down Expand Up @@ -196,8 +223,7 @@ class MessagePort extends EventTarget {
}

// The peer, or undefined once this port is closed. A peer that has been
// collected closes this port, without a 'close' event, as the C++ peer's
// destructor does.
// collected closes this port, without a 'close' event.
#livePeer(): MessagePort | undefined {
if (this.#peer === undefined) return undefined;
const peer = WeakRefPrototypeDeref(this.#peer) as MessagePort | undefined;
Expand All @@ -215,8 +241,8 @@ class MessagePort extends EventTarget {
const peer = this.#livePeer();
if (this.#state === 'closed') return;
this.#closeQuietly();
// The peer's 'close' event fires first, as C++ closes the peer through
// its public close(); a throw from its listeners ends this close().
// The peer's 'close' event fires first; a throw from its listeners ends
// this close().
if (peer !== undefined) peer.#close();
dispatchEvent(this, createTrustedEvent('close'), 'propagate');
}
Expand Down Expand Up @@ -299,6 +325,7 @@ class MessagePort extends EventTarget {
}
}
}
ObjectSetPrototypeOf(MessagePort, EventTarget);

class MessageChannel {
constructor() {
Expand Down
10 changes: 10 additions & 0 deletions src/per_isolate/per_isolate-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,16 @@ declare const utils: {
// Promise::Then(), so scheduling runs no user code (no species lookup). A
// throw rejects the reaction's promise, reported as unhandled.
queueReaction(fn: () => void): void;
// Defines key on target as a writable, configurable data property,
// enumerable if enumerable is true, whose value is the key export of the
// bootstrap module specifier, required when the property is first read (V8's
// lazy data property). A read that throws leaves it lazy.
defineLazyDataProperty(
target: object,
key: string | symbol,
specifier: string,
enumerable: boolean
): void;
// The request-bound I/O handle (api/request-io.h), bound to the current
// request, or undefined outside of one.
createRequestIo(): RequestIo | undefined;
Expand Down
2 changes: 2 additions & 0 deletions src/per_isolate/primordials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,7 @@ const AbortSignalReasonGet = captureJsgGetter<(signal: AbortSignal) => unknown>(
);

const EventTargetCtor = globalThis.EventTarget;
const EventTargetPrototype = EventTargetCtor.prototype;
const EventTargetAddEventListener = uncurryThis(
EventTargetCtor.prototype.addEventListener
) as (target: object, type: string, listener: () => void) => void;
Expand Down Expand Up @@ -883,6 +884,7 @@ module.exports = ObjectFreeze({
JSONStringify,

// EventTarget
EventTargetPrototype,
EventTargetAddEventListener,
EventTargetRemoveEventListener,

Expand Down
Loading
Loading