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 @@ -205,7 +205,7 @@ Be aware that workerd uses tcmalloc for memory allocation in the typical case. W
| Durable Object storage | `src/workerd/io/actor-cache.{h,c++}` + `actor-sqlite.{h,c++}` | LRU cache over RPC / SQLite-backed |
| Streams implementation | `src/workerd/api/streams/` | Has 842-line README; dual internal/standard impl |
| 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` |
| JS benchmarks | `src/workerd/api/bench-api/`, `bench-core/`, `build/wd_bench.bzl` | Rust `BenchController` and runner (`bench-api`); report building, clocks (`bench-core`); 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()`, 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 |
Expand Down
3 changes: 0 additions & 3 deletions src/workerd/api/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ filegroup(
"actor-call-retry.c++",
"actor-state.c++",
"basics.c++",
"bench.c++",
"blob.c++",
"bootstrap-utils.c++",
"cache.c++",
Expand Down Expand Up @@ -75,7 +74,6 @@ filegroup(
"actor-call-retry.h",
"actor-state.h",
"basics.h",
"bench.h",
"blob.h",
"bootstrap-utils.h",
"cache.h",
Expand Down Expand Up @@ -688,7 +686,6 @@ wd_cc_library(
"streams/pendingabort-gc-uaf-test.c++",
"actor-state-test.c++",
"alarm-retry-test.c++",
"bench-test.c++",
"basics-test.c++",
"crypto/aes-test.c++",
"crypto/impl-test.c++",
Expand Down
24 changes: 24 additions & 0 deletions src/workerd/api/bench-api/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
load("//:build/wd_rust_crate.bzl", "wd_rust_crate")

# BenchController, the first argument of a Worker's `bench()` handler, and the runner that times
# the cases it registers. C++ dispatches the bench event to it through bench_run() (ffi.rs).
wd_rust_crate(
name = "bench-api",
cxx_bridge_deps = [
"//src/rust/jsg",
"//src/workerd/util:thread-scopes",
],
cxx_bridge_hdrs = [],
cxx_bridge_src = "ffi.rs",
cxx_bridge_visibility = ["//visibility:public"],
proc_macro_deps = ["//src/rust/jsg-macros"],
test_deps = ["//src/rust/jsg-test"],
visibility = ["//visibility:public"],
deps = [
"//src/rust/jsg",
"//src/workerd/api/bench-core",
"//src/workerd/io:bench_capnp_rust",
"//src/workerd/io/io-context",
"@crates_vendor//capnp",
],
)
98 changes: 98 additions & 0 deletions src/workerd/api/bench-api/ffi.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// 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

//! The bridge through which C++ dispatches the bench event to a Worker's `bench()` handler, and
//! the C++ it calls.

#![allow(
unsafe_code,
reason = "the cxx bridge expands to unsafe FFI glue, and bench_run() takes C++'s raw isolate \
and handles"
)]

use jsg::v8;

use crate::BenchController;
use crate::runner;

#[cxx::bridge(namespace = "workerd::api")]
mod bridge {
#[namespace = "workerd::rust::jsg"]
unsafe extern "C++" {
include!("workerd/rust/jsg/ffi.h");
include!("workerd/rust/jsg/v8.rs.h");

type Isolate = jsg::v8::ffi::Isolate;
type Local = jsg::v8::ffi::Local;
type MaybeLocal = jsg::v8::ffi::MaybeLocal;
}

#[namespace = "workerd"]
unsafe extern "C++" {
include!("workerd/util/thread-scopes.h");

/// Whether the process runs `workerd bench`, the only command that dispatches the bench
/// event. Not `is_bench_mode`, which workerd-server's bridge declares: cxx names each
/// shim after the function and its namespace, so the two would collide at link time.
#[cxx_name = "isBenchMode"]
fn in_bench_mode() -> bool;
}

extern "Rust" {
/// Runs the `bench()` handler of `handler`, a Worker's exported handler object, with
/// `env` and `ctx` (undefined if it has none), then the cases it registers. `params` is
/// an encoded `BenchParams` message, in words. Returns a promise for the group: an
/// `ArrayBuffer` that holds its `BenchReport.Group`, without its name, as an encoded
/// message, which rejects if the runner itself fails. Throws if `handler` has no
/// `bench()`.
unsafe fn bench_run(
isolate: *mut Isolate,
handler: Local,
env: Local,
ctx: Local,
params: &[u64],
) -> MaybeLocal;
}
}

/// # Safety
/// C++ calls this with the isolate locked, a context entered and a `HandleScope` open, in which
/// `handler`, `env` and `ctx` are handles.
unsafe fn bench_run(
isolate: *mut bridge::Isolate,
handler: bridge::Local,
env: bridge::Local,
ctx: bridge::Local,
params: &[u64],
) -> bridge::MaybeLocal {
// SAFETY: forwarded from the caller, who also passes `handler`, `env` and `ctx` in the scope
// that the closure's lock stands for.
unsafe {
v8::run_ffi_callback(isolate, |lock| {
// The handles are in the caller's scope, which is the lock's.
let (handler, env, ctx) = (
v8::Local::<v8::Value>::from_ffi(handler),
v8::Local::<v8::Value>::from_ffi(env),
v8::Local::<v8::Value>::from_ffi(ctx),
);
// Fails closed anywhere but `workerd bench`.
if !bridge::in_bench_mode() {
return Err(jsg::Error::new_internal_error(
"the bench event is only supported by `workerd bench`",
));
}
let handler_object = v8::Local::<v8::Object>::try_from(handler).map_err(|_| {
jsg::Error::new_error("Entrypoint does not export a bench() function.")
})?;
let bench = handler_object.get(lock, "bench")?;
let bench = v8::Local::<v8::Function>::try_from(bench).map_err(|_| {
jsg::Error::new_error("Entrypoint does not export a bench() function.")
})?;
let controller = BenchController::read(params)
.map_err(|err| jsg::Error::new_internal_error(err.to_string()))?;
let controller = jsg::Rc::new(lock, controller);
runner::start(lock, &controller, bench, handler, env, ctx)
})
}
}
62 changes: 62 additions & 0 deletions src/workerd/api/bench-api/lib-test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// 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

use jsg_test::Harness;

use super::*;

fn describe(code: &str) -> Vec<u8> {
let mut description = Vec::new();
Harness::new().run_in_context(|lock, ctx| {
let value = ctx.eval_raw(lock, code).unwrap();
description = describe_exception(lock, value).unwrap();
Ok(())
});
description
}

/// A lone surrogate is kept as WTF-8, as C++ JSG's `kj::String` keeps it.
#[test]
fn strings_convert_to_wtf8() {
Harness::new().run_in_context(|lock, ctx| {
let value = ctx.eval_raw(lock, "'a\\ud800b\\u00e9'").unwrap();
let string = v8::Local::<v8::String>::try_from(value).unwrap();
assert_eq!(wtf8(lock, string), b"a\xed\xa0\x80b\xc3\xa9");
Ok(())
});
}

#[test]
fn exceptions_are_described_by_their_stack() {
let description = describe("(() => { const e = new TypeError('boom'); return e; })()");
assert!(
description.starts_with(b"TypeError: boom\n"),
"{description:?}"
);
assert_eq!(describe("({ stack: 'custom stack' })"), b"custom stack");
}

#[test]
fn exceptions_without_a_stack_are_converted_to_strings() {
assert_eq!(describe("'thrown string'"), b"thrown string");
assert_eq!(describe("42"), b"42");
assert_eq!(
describe("({ stack: 1, toString() { return 'object' } })"),
b"object"
);
}

#[test]
fn exceptions_that_cannot_be_converted_have_a_placeholder() {
let placeholder = b"(an exception that can't be converted to a string)";
assert_eq!(describe("Symbol('s')"), placeholder);
assert_eq!(
describe("({ get stack() { throw 1; } })"),
placeholder.as_slice()
);
assert_eq!(
describe("({ toString() { throw new Error('no'); } })"),
placeholder.as_slice()
);
}
Loading
Loading