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 AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ Be aware that workerd uses tcmalloc for memory allocation in the typical case. W
| Bazel build rules | `build/` | Custom `wd_*` macros; `wd_test.bzl` generates 3 test variants |
| JS benchmarks | `src/workerd/api/bench.{h,c++}`, `build/wd_bench.bzl` | `bench` handler; runner `BenchController`; report schema `io/bench.capnp`; driver `server/server/bench.rs` |
| Streams benchmarks | `src/bench/streams/` | C++ vs TS streams: the same modules under a cell per implementation; see its `AGENTS.md` |
| Clone benchmarks | `src/bench/serialization/` | `structuredClone()` of object graphs, class instances, arrays and strings |
| Clone benchmarks | `src/bench/serialization/` | `structuredClone()`, C++ vs TS (`TS_STRUCTURED_CLONE`): object graphs, arrays, strings, options, cold calls |
| TypeScript types | `types/` | Extracted from C++ RTTI + hand-written `defines/*.d.ts`; see `types/AGENTS.md` for detailed typings guidance |
| V8 patches | `patches/v8/` | See `docs/v8-updates.md` |
| Startup snapshot | `src/workerd/jsg/snapshot.{h,c++}`, `setup.{h,c++}` | Zygote bakes the top level into a V8 snapshot; `STARTUP_SNAPSHOT` autogate; see `docs/startup-snapshot.md` |
Expand Down
3 changes: 2 additions & 1 deletion docs/benchmarking.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,5 +179,6 @@ See [text-encoder-bench.js](../src/workerd/api/tests/text-encoder-bench.js).
[src/bench/streams/](../src/bench/streams/AGENTS.md) runs the same benchmarks against the C++ and
TypeScript streams implementations, to compare them.
[src/bench/serialization/](../src/bench/serialization/structured-clone.js) measures
`structuredClone()` of object graphs, class instances, arrays and strings.
`structuredClone()` of object graphs, class instances, arrays and strings, and its options,
against the C++ and TypeScript implementations, including the first calls in a new isolate.

20 changes: 18 additions & 2 deletions src/bench/serialization/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
load("//:build/wd_bench.bzl", "wd_bench")

# The structuredClone() benchmarks, against the C++ implementation and the
# TypeScript one (TS_STRUCTURED_CLONE). Enabling every autogate enables
# TS_STRUCTURED_CLONE, so the C++ config has no @all-autogates variant; the
# TypeScript config enables TS_STRUCTURED_CLONE itself.

structured_clone_srcs = [
"structured-clone.js",
"structured-clone-cold.js",
]

wd_bench(
src = "structured-clone-cpp.wd-bench",
data = structured_clone_srcs,
generate_all_autogates_variant = False,
)

wd_bench(
src = "structured-clone.wd-bench",
data = ["structured-clone.js"],
src = "structured-clone-ts.wd-bench",
data = structured_clone_srcs,
)

wd_bench(
Expand Down
24 changes: 24 additions & 0 deletions src/bench/serialization/structured-clone-cold.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0

// structuredClone() in a new isolate. The top-level calls are the first in
// their isolate, before V8 has compiled or optimized any of the code they
// run; the startup group's startup:worker case times them, in a new isolate
// for every sample, and its startup:script case times the per-isolate
// bootstrap that installs the function. The module does nothing else at top
// level, so those two cases differ between implementations by those costs
// alone.

const SMALL = { a: 1, b: 'two', c: [3] };

structuredClone(SMALL);
const buffer = new ArrayBuffer(8);
structuredClone(buffer, { transfer: [buffer] });

export default {
bench(b) {
// The same call once warm, for comparison.
b.run('small object', () => b.blackBox(structuredClone(SMALL)));
},
};
20 changes: 20 additions & 0 deletions src/bench/serialization/structured-clone-cpp.wd-bench
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using Workerd = import "/workerd/workerd.capnp";

# Runs the structuredClone() benchmarks against the C++ JSG method
# (api/global-scope.h). structured-clone-ts.wd-bench runs the same modules
# against the TypeScript one.

const unitTests :Workerd.Config = (
services = [
( name = "structured-clone",
worker = (
modules = [(name = "worker", esModule = embed "structured-clone.js")],
)
),
( name = "structured-clone-cold",
worker = (
modules = [(name = "worker", esModule = embed "structured-clone-cold.js")],
)
),
],
);
21 changes: 21 additions & 0 deletions src/bench/serialization/structured-clone-ts.wd-bench
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using Workerd = import "/workerd/workerd.capnp";

# Runs the structuredClone() benchmarks against the TypeScript implementation
# (src/per_isolate/structured-clone.ts), with byte-for-byte the same modules
# as structured-clone-cpp.wd-bench.

const unitTests :Workerd.Config = (
services = [
( name = "structured-clone",
worker = (
modules = [(name = "worker", esModule = embed "structured-clone.js")],
)
),
( name = "structured-clone-cold",
worker = (
modules = [(name = "worker", esModule = embed "structured-clone-cold.js")],
)
),
],
autogates = ["workerd-autogate-ts-structured-clone"],
);
23 changes: 22 additions & 1 deletion src/bench/serialization/structured-clone.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
// https://opensource.org/licenses/Apache-2.0

// structuredClone() of object graphs, whose every object the serializer asks its delegate about
// (jsg::Serializer::IsHostObject()), and of arrays and strings, which it does not.
// (jsg::Serializer::IsHostObject()), and of arrays and strings, which it does not; then the
// options, whose conversion is the part the C++ and TypeScript implementations do differently.

function tree(depth, width) {
if (depth === 0) return { leaf: true, n: 1 };
Expand Down Expand Up @@ -35,10 +36,30 @@ const INPUTS = {
'string 8192': 'a'.repeat(8192),
};

const SMALL = { a: 1 };
const NO_TRANSFER = {};
const EMPTY_TRANSFER = { transfer: [] };

export default {
bench(b) {
for (const [name, input] of Object.entries(INPUTS)) {
b.run(name, () => b.blackBox(structuredClone(input)));
}
b.run('small object, options without transfer', () =>
b.blackBox(structuredClone(SMALL, NO_TRANSFER))
);
b.run('small object, empty transfer', () =>
b.blackBox(structuredClone(SMALL, EMPTY_TRANSFER))
);
// A transferred buffer is detached, so each call needs new ones; the
// allocations cost the same under both implementations.
b.run('transfer 1 ArrayBuffer', () => {
const buffer = new ArrayBuffer(64);
return b.blackBox(structuredClone(buffer, { transfer: [buffer] }));
});
b.run('transfer 16 ArrayBuffers', () => {
const buffers = Array.from({ length: 16 }, () => new ArrayBuffer(64));
return b.blackBox(structuredClone(buffers, { transfer: buffers }));
});
},
};
10 changes: 0 additions & 10 deletions src/bench/serialization/structured-clone.wd-bench

This file was deleted.

5 changes: 5 additions & 0 deletions src/per_isolate/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ at context creation, before any user code. C++ entry point:
- Under the `TS_URL_PATTERN` autogate, `main.ts` installs the TypeScript
`URLPattern` (`urlpattern/`), which replaces both C++ implementations;
see `urlpattern/AGENTS.md`.
- Under the `TS_STRUCTURED_CLONE` autogate, `main.ts` installs the
TypeScript `structuredClone()` (`structured-clone.ts`, a WebIDL layer over
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`.
- 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
18 changes: 18 additions & 0 deletions src/per_isolate/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,24 @@ if (autogates['ts-url-pattern']) {
});
}

// The TypeScript structuredClone() replaces the C++ method, which
// global-scope.h then leaves out. Installed where JSG_METHOD installs it, on
// ServiceWorkerGlobalScope.prototype, with the same attributes (all three
// true).
if (autogates['ts-structured-clone']) {
const { structuredClone } = require('structured-clone');
ObjectDefineProperties(ObjectGetPrototypeOf(globalThis), {
__proto__: null,
structuredClone: {
__proto__: null,
configurable: true,
enumerable: true,
writable: true,
value: structuredClone,
},
});
}

// Internal-only: cloneable classes for testing the serialization protocol
// (serialization.ts), such as over RPC. Gated by an experimental flag that
// may never lose its experimental annotation.
Expand Down
6 changes: 6 additions & 0 deletions src/per_isolate/per_isolate-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,12 @@ declare const utils: {
value: unknown
): 'locked' | 'disturbed' | 'readable' | undefined;
encodeUtf8(str: string): Uint8Array;
// The structured clone of `value` (jsg::structuredClone), transferring the
// objects in `transfer`, a dense array the caller built. The native
// serializer's rules apply: an ArrayBuffer or a view's buffer is transferred,
// any other object throws a TypeError, and an uncloneable value a
// DataCloneError. Consumed by structured-clone.
structuredClone(value: unknown, transfer: object[] | undefined): unknown;
};

// The I/O of a bootstrap API, bound to the request that created it
Expand Down
129 changes: 129 additions & 0 deletions src/per_isolate/structured-clone.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
'use strict';

// The global structuredClone(), installed by main.ts on
// ServiceWorkerGlobalScope.prototype under the TS_STRUCTURED_CLONE autogate, in
// place of the C++ JSG method.
//
// This module is the WebIDL layer: the receiver check, the argument count, and
// the conversion of the StructuredSerializeOptions dictionary. The clone itself
// is the native serializer's, through utils.structuredClone(), so which values
// clone, which objects transfer, and the errors for either are the same as in
// C++. Where the conversion differs from C++ it follows WebIDL; the differences
// are tabled in src/tests/structured-clone/AGENTS.md.

const {
ArrayPrototypePush,
FunctionPrototypeCall,
ObjectDefineProperty,
SymbolIterator,
TypeError: TypeErrorCtor,
} = primordials;

const { structuredClone: nativeStructuredClone } = utils;

// The global proxy, which is the receiver of `globalThis.structuredClone(v)`.
const globalReceiver: unknown = globalThis;

// The C++ texts, kept where the behaviour matches.
const ILLEGAL_INVOCATION =
'Illegal invocation: function called with incorrect `this` reference. See ' +
'https://developers.cloudflare.com/workers/observability/errors/' +
'#illegal-invocation-errors for details.';
const NO_VALUE =
"Failed to execute 'structuredClone' on 'ServiceWorkerGlobalScope': " +
"parameter 1 is not of type 'Value'.";
const BAD_OPTIONS =
"Failed to execute 'structuredClone' on 'ServiceWorkerGlobalScope': " +
"parameter 2 is not of type 'StructuredCloneOptions'.";
const BAD_TRANSFER =
"Incorrect type for the 'transfer' field on 'StructuredCloneOptions': " +
"the provided value is not of type 'sequence<object>'.";
const BAD_TRANSFER_ITEM =
"Incorrect type for an element of the 'transfer' field on " +
"'StructuredCloneOptions': the provided value is not of type 'object'.";
// After V8's texts for the same failures in for...of.
const ITERATOR_NOT_OBJECT =
'Result of the Symbol.iterator method is not an object';
const RESULT_NOT_OBJECT = 'Iterator result is not an object';

function isObject(value: unknown): value is object {
return (
(typeof value === 'object' && value !== null) || typeof value === 'function'
);
}

// WebIDL's conversion to sequence<object>: any iterable, consumed through its
// own iterator (the user's, by contract), into an array of our own that the
// native side can read without running user code. Spelled out rather than
// written as for...of, which differs from WebIDL's "create a sequence from an
// iterable" in two observable ways: it reads [Symbol.iterator] a second time
// after the check, and it closes the iterator when an element is rejected.
function toObjectSequence(value: unknown): object[] {
if (!isObject(value)) {
throw new TypeErrorCtor(BAD_TRANSFER);
}
const method: unknown = (value as Record<symbol, unknown>)[SymbolIterator];
if (typeof method !== 'function') {
throw new TypeErrorCtor(BAD_TRANSFER);
}
const iterator: unknown = FunctionPrototypeCall(method, value);
if (!isObject(iterator)) {
throw new TypeErrorCtor(ITERATOR_NOT_OBJECT);
}
const next = (iterator as { next?: unknown }).next;
const list: object[] = [];
for (;;) {
const result: unknown = FunctionPrototypeCall(
next as (this: unknown) => unknown,
iterator
);
if (!isObject(result)) {
throw new TypeErrorCtor(RESULT_NOT_OBJECT);
}
if ((result as { done?: unknown }).done) {
return list;
}
const item = (result as { value?: unknown }).value;
if (!isObject(item)) {
throw new TypeErrorCtor(BAD_TRANSFER_ITEM);
}
ArrayPrototypePush(list, item);
}
}

// A method, so the function has no `prototype` and is not a constructor, like
// the JSG method it replaces.
const { structuredClone } = {
structuredClone(this: unknown, value: unknown, options?: unknown): unknown {
// WebIDL: an operation of the global takes undefined or null as the
// global itself.
if (this != null && this !== globalReceiver) {
throw new TypeErrorCtor(ILLEGAL_INVOCATION);
}
if (arguments.length === 0) {
throw new TypeErrorCtor(NO_VALUE);
}
let transfer: object[] | undefined;
if (options != null) {
if (!isObject(options)) {
throw new TypeErrorCtor(BAD_OPTIONS);
}
const list = (options as { transfer?: unknown }).transfer;
if (list !== undefined) {
transfer = toObjectSequence(list);
}
}
return nativeStructuredClone(value, transfer);
},
};

// WebIDL: the optional options argument does not count.
ObjectDefineProperty(structuredClone, 'length', {
__proto__: null,
configurable: true,
enumerable: false,
writable: false,
value: 1,
});

module.exports = { structuredClone };
Loading
Loading