Skip to content

Port the Worker Loader binding to Rust behind RUST_WORKER_LOADER - #8673

Open
bartlomieju wants to merge 18 commits into
mainfrom
biwanczuk/rust-worker-loader-pr
Open

bartlomieju wants to merge 18 commits into
mainfrom
biwanczuk/rust-worker-loader-pr

Conversation

@bartlomieju

@bartlomieju bartlomieju commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Worker Loader is one of the larger binding APIs still implemented only
in C++. This change ports it, WorkerLoader and the WorkerStub it
returns, to a Rust crate in src/workerd/api/worker-loader-api, behind
a new autogate, RUST_WORKER_LOADER. With the gate on,
workerd-api.c++ creates the Rust loader for Global::WORKER_LOADER;
otherwise the unchanged C++ loader is used, and it stays the default.
TypeScript types are still generated from C++, so they don't change.
Besides moving API surface off C++, the port exercises the Rust JSG
pieces such bindings need, and adds the few that were missing: a
SharedArrayBuffer handle and IoContext::await_js_promise_local(),
which awaits a typed JS promise in the current IoContext as C++
awaitJs() does.

The port is meant to be indistinguishable from the C++ loader to a
Worker. Every check throws C++'s error type and message, word for word,
and fields are converted in the same order, so when several things are
wrong the same error wins. To that end the Rust structs carry the C++
names that errors quote, while ts_override keeps the TypeScript names.
Compatibility flags go through the same C++
compileCompatibilityFlags(), and building the Worker source, loading
the isolate and getting entrypoints and actor classes all go through
small C++ shims in src/workerd/api/worker-loader-interop. As in C++,
getCode() is held by a weak callback, so a WorkerStub doesn't keep
its request alive or block Durable Object hibernation, and module
contents live in an atomically refcounted buffer because a loaded Worker
can be reloaded from it, and dropped, on another thread.

The new tests run against both implementations: they pin the exact
errors and their order under the relevant compatibility flags, what each
kind of getCode() result converts to, hibernation with a pending
getCode(), and a loader captured in a startup snapshot. The existing
Worker Loader tests run against the Rust loader in their
@all-autogates variants. The gate switches only the binding that
workerd-api.c++ creates, so an embedder that constructs
api::WorkerLoader itself needs the same branch to use the Rust loader.

Rust APIs can't take or return service bindings or Durable Object
classes yet: `Fetcher` and `DurableObjectClass` are C++ JSG resources,
and nothing exposes them to Rust. This adds per-type `jsg-cpp` shims
for both, in a new `src/workerd/api/channel-interop` package.
Following `src/rust/jsg/README.md` safety rule 3, the shims live with
the API code rather than in Rust JSG. This is the first production use
of `jsg-cpp`.

Planned users: the Rust ports of the Worker Loader binding and the
container binding. Also two in-progress ports that currently carry
their own `Fetcher` shims: the Rust `ExecutionContext`
(`ctx.mapVirtualHost`) and an internal project's cache-purge binding.
Both will switch to this package once it lands.

### API

Rust takes and returns these as `jsg_cpp::Ref<Fetcher>` and
`jsg_cpp::Ref<DurableObjectClass>`. They work as method parameters,
`#[jsg_struct]` fields, `Option`, `Nullable` and `Vec`. Unwrapping
goes through the isolate's `TypeHandler`, so subclasses such as
`ExtendedFetcher` are accepted, with the pointer adjusted to the base
class, and anything else is rejected as C++ `jsg::Ref` parameters do.

- `Fetcher::subrequest_channel()` returns its `SubrequestChannel`.
- `Fetcher::from_channel()` wraps a `SubrequestChannel` in a new
  `Fetcher`, with the defaults `worker-loader.c++` uses.
- `Fetcher::from_channel_number(channel, RequiresHostAndProtocol,
  InHouse)` is the constructor most bindings use: KV, R2, cache purge,
  `global-scope`, and the env builders. Both options are Rust enums.
- `Fetcher::map_virtual_host(port)` forwards to C++
  `Fetcher::mapVirtualHost`, which `ctx.mapVirtualHost` and
  `cloudflare:workers` also call.
- `DurableObjectClass::channel()` returns its `ActorClassChannel`, as
  `ctx.facets.get()` needs.
- `DurableObjectClass::from_channel()` wraps one in a new class, as
  Worker Loader's `getDurableObjectClass()` and the `ctx.exports`
  loopback classes need.
- `require_allows_transfer()` on both channel types.

The C++ channel types are exposed through aliases and held as
`kj_rs::KjRc`. `KjRc` is neither `Send` nor `Sync`, so a channel can't
move to another thread, into an `await_io` future, or into resource
state. A compile test asserts this with `static_assertions`. Dropping
a channel after its request has ended is safe, as in C++.

Rust code holds an `IoContext` by id. To get from that id back to the
C++ `IoContext` the shims need, a new `io-context:current-with-id`
library adds `currentWithId()`, visible to `//src/workerd/api` only.
Ids come from a process-unique counter, so a stale id fails a
`KJ_REQUIRE` instead of matching a newer context.

### Not included yet

- Creating a `Fetcher` from a `Fetcher::OutgoingFactory` (dynamic
  dispatch, container `getTcpPort`, facets): deferred until a port
  needs it.
- What Worker Loader needs beyond this: a subrequest channel with no
  outbound connection, and `WorkerStubChannel::getEntrypoint` /
  `getActorClass`.
- Channel tokens.
IoContext::make_reentry_callback_weak() wraps
IoContext::makeReentryCallbackWeak(): the returned ReentryCallback<T>
runs a Rust function under a new lock in the creating context each time
it is called from KJ, and awaits the future the function returns. It
holds the context weakly, failing with the same errors as C++ once the
context is gone or the Durable Object is hibernating.

The callback is not Send. The function, its future and their output need
not be: C++ holds the function in the IoContext and runs and drops it on
its thread, KJ polls the future there, and the output reaches only the
call's future. So the output can hold C++ objects of that thread, as
WorkerLoader.get()'s will. 'static and the lock's lifetime keep handles
out of the function and its future.

What the function throws is caught in Rust, logged as uncaught and
tunneled, as run() does for C++ code. A termination is left pending and
propagated to IoContext::run() as JsExceptionThrown, through the one
throw the allowlist permits in ffi.c++, now shared with
io_context_await_io_and_run(), so run() handles it in its own order:
it leaves the limit enforcer's scope, fails with the exceeded limit or
the abort reason, and cancels the microtasks queued meanwhile.

TestFixture::setLimitsExceededOnLeavingJs() records an exceeded limit
only when the enforcer's enterJs() scope ends, as an enforcer that
measures CPU time over that scope does, so a test can pin that order.
IoContext::await_js_local() waits for a JavaScript promise as
await_js() does, but its conversion also gets the IoContext, and its
output need only be 'static: it can be a KjOwn<Frankenvalue>, a
KjRc<SubrequestChannel> or a C++ struct holding them, none of which is
Send. Nothing moves to another thread; the conversion, the future and
its output all stay on the IoContext's thread, hence "local". That is
what WorkerLoader.get()'s reentry callback needs to build a
DynamicWorkerSource from the WorkerCode that getCode() resolves, as C++
does with awaitJs(js, getCode(js), func).

The returned AwaitJsLocal<T> is an AwaitJs whose output is held in a
ThreadBound<T>, which claims Send so that the wait's shared state and
its sender can be reaction data. The output is created only by the
conversion, in a reaction that has taken its sender, which requires the
IoContext to be current; it is taken or dropped by the future, which is
neither Send nor Sync, or by the sender, which is always dropped on the
IoContext's thread. No reaction data or other traced state holds one,
so GC never visits or drops one. A reaction in another request fails
before the conversion runs, and the wait fails as never settled once
GC collects the reactions, as C++ awaitJs() behaves. The future can be
returned from a reentry callback's function as it is.

The make_reentry_callback_weak() example and its compile test now build
their non-Send output in the conversion.

io-context-test gains two cases: a reentry callback that takes a
Fetcher's channel through await_js_local(), which C++ receives as the
same channel, with the conversion given the creating IoContext (by
IoContext::as_ffi()); and a promise resolved from another request,
which never runs the conversion and fails the call with "Promise will
never complete." once GC collects the reactions. Compile tests pin that
the future is neither Send nor Sync and that the conversion captures
only data that is Copy and Send.
Both harnesses created their V8System lazily, on the first thread that
needed it. On Linux x86-64, V8 guards JIT memory such as the
WebAssembly code pointer table with a memory protection key, and only
the thread that creates the platform, and threads it later creates,
get access to that key. The Rust test harness runs tests on threads
spawned from the main thread, so the main thread, which disposes V8
from static destructors at exit, had no access. Once a test had
compiled WebAssembly, V8::Dispose() faulted with SEGV_PKUERR in
WasmCodePointerTable::SweepSegments.

Construct V8System at namespace scope instead, as the C++ JSG tests
and benchmarks do, so V8 starts and stops on the main thread.

(cherry picked from commit 6842191)
Rust JSG had no handle type for WebAssembly.Module. Add the
WasmModuleObject marker type, accepted as an exact-type parameter, in
unions and in Global/TracedGlobal like the other handle types, and
Local<WasmModuleObject>::compiled_module(), which returns an owned
v8::CompiledWasmModule. It exposes the module's wire bytes and can be
handed to C++ to make a module object in another isolate without
recompiling. It is Send + Sync and must be dropped before V8 is
disposed.

The Rust port of the Worker Loader binding needs this for the
WebAssembly.Module values in WorkerCode.modules.

(cherry picked from commit f5d6967)
On Linux x86-64, V8 grants access to the memory protection key that
guards its JIT memory only to the thread that starts it and the
threads that thread creates, and dropping the last reference to a
module's compiled code frees entries in the protected code pointer
table. Say so instead of claiming any thread will do, and keep the
test harness comment to the requirement it states.

(cherry picked from commit 5cc510e)
Porting Worker Loader, and other bindings that take `props` or an `env`, to
Rust needs Rust to build a Frankenvalue from a JavaScript value, as C++
Frankenvalue::fromJs does, and hand it to C++ that takes one by value. The
value may contain capabilities, such as Fetchers, DurableObjectClasses and
persistent RPC stubs, which become entries of its cap table.

The serializer does not write those capabilities: each capability type's C++
serialize() does, by downcasting the serializer's external handler to
Frankenvalue::CapTableBuilder and adding its channel to the cap table
(Fetcher::serialize in api/http.c++, and api/actor.c++). fromJs also
serializes with treatClassInstancesAsPlainObjects = false, so a class
instance throws DataCloneError. Building the value with Rust jsg::ser would
mean threading a C++ CapTableBuilder through Rust into the same C++
serialize() methods and adding that option; the C++ serializers would still
do the work, and the result is a C++ object that only C++ consumes. So Rust
calls fromJs.

The new frankenvalue crate, in src/workerd/io/frankenvalue/ beside the class,
declares workerd::Frankenvalue as an opaque cxx type that Rust holds as a
KjOwn<Frankenvalue>, since cxx can't hold an opaque C++ type by value. Rust
can build one from JavaScript or as the empty object, turn it back into
JavaScript, estimate its size, check whether it is empty, clone it, and pass
it to C++, which moves it out with kj::mv(*value). try_clone() returns a
Result because C++ clone() may throw, as a capability's clone() is virtual.
The C++ shims (ffi.h, ffi.c++) are per-type shims of the class, as Rust JSG's
safety rule 3 places them, and live in their own package because
//src/workerd/io:frankenvalue must not depend on Rust.

KjOwn<Frankenvalue> is neither Send nor Sync. The cap table holds channels of
the thread whose request made them, shared through non-atomic reference
counts that clone() and dropping change, so the value must stay on that
thread. A compile test pins this. It keeps the value out of resource state
and out of Send futures; code that needs one after a wait builds it under the
lock on the IoContext's thread.

fromJs and toJs run in jsg_cpp::call_cpp() and callCpp(), as every jsg-cpp
shim does, which take the C++ jsg::Lock the way jsg-cpp's interop tier
permits and do nothing while an exception or a termination is pending.
Whatever C++ throws stays pending in V8 as the exception C++ JSG would throw,
and Rust sees jsg::Error::pending(), so a Rust JSG method throws exactly what
a C++ method calling fromJs throws: a DataCloneError for a value that can't
be serialized or a capability that can't be transferred, and a getter's
exception unchanged.

The server crate's bridge declared workerd::Frankenvalue too, so each bridge
defined the KjOwn<Frankenvalue> drop, and a workerd binary that uses this
crate failed to link with a duplicate
cxxbridge$kjrs$own$workerd$Frankenvalue$drop. The server bridge now aliases
this crate's type, so only this crate defines the drop.

(cherry picked from commit 63a53b5)
The reentry callback returned `getCode(js).then(js, addFunctor(f))`,
which makeReentryCallbackImpl() then waited on with the one-argument
awaitJs(). `f` produces a DynamicWorkerSource, which owns KJ objects:
the globalOutbound and tail subrequest channels, the Frankenvalue env
and the module content. With `.then()`, the source reached KJ only in
a second microtask. If execution was terminated between the two, as a
limit does, the second microtask was discarded: the runtime's wait
never settled, and the source stayed in the V8 heap until GC.

The callback now returns `ioctx.awaitJs(js, getCode(js), f)`, so `f`
runs and its result is handed to the KJ promise in the same
continuation. makeReentryCallbackImpl() needs no change: a callback
returning a kj::Promise takes its plain-value branch, and run()'s
result type, kj::PromiseForResult, flattens the promise, as it already
did for the promise the jsg::Promise branch gets from awaitJs().

Other internal differences: the conversion no longer runs if the wait
was canceled before getCode() resolved, and a getCode() promise
resolved from another context now fails through awaitJs()'s IoOwn
check rather than addFunctor()'s.

Nothing JS-visible changes: error messages, the Python compat-flag
fixups, limits, and the globalOutbound/tails handling are all in
toDynamicWorkerSource(), which is untouched. A rejected getCode()
still rejects the wait with the tunneled exception. No compatibility
flag is needed.

worker-loader-source-test terminates execution between the two
microtasks and checks that the wait resolves to the source, owned by
the KJ promise. With the old shape it fails: the wait stays pending.

(cherry picked from commit 055be6b)
…-loader-pr

# Conflicts:
#	src/rust/jsg/wrappable.rs
#	src/workerd/io/io-context/io-context-test.c++
WorkerLoader and WorkerStub are Rust JSG resources in
api/worker-loader-api, with WorkerCode, Module, EntrypointOptions and a
Rust mirror of ResourceLimits as #[jsg_struct]s (dicts.rs). The checks
are plain Rust in validate.rs, with unit tests, and throw the C++
messages word for word: module kinds by name, exactly one field per
module object, Python flag fixups, the 64 MB code and 1 MB env limits,
and allowExperimental.

The structs are named as their C++ counterparts, so Rust JSG's struct
conversion errors name them as C++ JSG's do, and ts_override gives the
TypeScript names C++ generates. Each field has the type of its C++
field, so the whole struct converts in field order before any check,
with C++ JSG's errors: env and props are objects, globalOutbound is a
NullOrUndefined<Fetcher>, which, as C++ JSG converts a
kj::Maybe<jsg::Ref<Fetcher>>, blocks outbound or throws for a value
that isn't a Fetcher as dont_substitute_null_on_type_error says, and
tails and streamingTails are Vec<Fetcher>. Rust JSG has no bytes type,
so code.rs adds two for the data and wasm fields, named as C++ JSG
names kj::Array<const byte> and its union with WasmModuleObject.

api/worker-loader-interop holds the C++ shims. A SourceBuilder builds a
DynamicWorkerSource from Rust-owned buffers: Rust appends a NUL to each
string and hands the rust::String over, so nothing is copied again. Each
buffer is boxed, so the views of it stay valid as the buffers grow. They
live in an atomically refcounted SourceContent that may be destroyed on
any thread. data and wasm bytes are copied out of the V8 backing store
when the code is converted. The compatibility flags are compiled by
C++ compileCompatibilityFlags(), as the C++ loader compiles them.
load() and get() call loadIsolate(). get()'s callback is a weak
ReentryCallback, which converts the code getCode() resolves in its
IoContext through await_js_local(), as C++ get() does with
awaitJs(js, getCode(js), func). WorkerStub holds the
IoOwn<WorkerStubChannel> and returns Fetcher and DurableObjectClass
through jsg-cpp.

workerd-api.c++ creates the Rust WorkerLoader for Global::WORKER_LOADER
when the new RUST_WORKER_LOADER autogate is on, and the C++ one otherwise.
TypeScript is still generated from the C++ types, which are unchanged.

worker-loader-validation-test checks the type errors and their order
against both implementations, under each setting of
dont_substitute_null_on_type_error, and loads a Worker with byte and
WASM modules ahead of many text modules.

worker-loader-hibernation-test pins that a Durable Object holding a
WorkerStub whose code is still loading goes idle and can be evicted,
as it can't if get()'s callback holds its IoContext strongly.
startup-snapshot-bindings-test gains a Worker Loader binding captured
at the top level, which loads a Worker and rejects a future
compatibility date after the Worker starts from the snapshot.

@guybedford guybedford left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving the last commit (bb9270de8), the only one that belongs to this PR. It is gated by RUST_WORKER_LOADER, off by default, and the C++ loader is untouched.

What I checked:

  • Read the full diff against worker-loader.c++. The check order in to_source() matches toDynamicWorkerSource(), and the content ownership (SourceContent, boxed buffers, atomic refcount, IoOwn<WorkerStubChannel>) matches what C++ does.
  • Ran locally, all passing: worker-loader-validation-test (@ and @all-autogates), worker-loader-test@all-autogates, worker-loader-hibernation-test@all-autogates, startup-snapshot-bindings-test@all-autogates, and the worker-loader-api unit tests.
  • Ran over 100 edge inputs through both loaders and diffed the results: wrong-typed fields, module kinds, limits, compatibility date and flags, env and props, and the shapes getCode() can return. Property access order during conversion and every validation error are identical.

CI is red from the stack rather than this commit: jsg-test's wasm_module_object::struct_field_holds_a_module (from #8616) still expects the error text from before #8632. That was the only failure on the linux, tsan and windows jobs.

Divergences from C++ that the diffing found. None block this behind the gate, but they are worth closing before it is turned on:

  1. data and wasm given a SharedArrayBuffer: C++ accepts it (kj::Array<byte> unwraps one), bytes_of() in code.rs doesn't, so Rust throws a TypeError. This is the only accept to reject difference.
  2. getCode():
    • this is globalThis in C++ and undefined in Rust.
    • A thenable that isn't a promise is converted as the WorkerCode itself in C++. Rust adopts it through Promise::resolved().
    • For a result that isn't an object, C++ throws Callback returned incorrect type; expected 'Promise' or the Promise did not resolve to 'WorkerCode', and Rust throws Expected object but got number.
  3. get() with no arguments reports parameter 2 ('Function') where C++ reports parameter 1 ('string').

Other gaps:

  • DateValidation goes to C++ as a u8 and is static_cast to CompatibilityDateValidation behind a range check only. A static_assert on the three values, or a cxx extern enum, would pin it at compile time.
  • As the description lists, worker-loader-python-test hasn't run against the Rust loader.
  • The gate switches workerd-api.c++ only, so an embedder that creates api::WorkerLoader itself needs the same branch.

It would be good to add the cases in 1 and 2 to worker-loader-validation-test, since its expectations run against both loaders.

@bartlomieju
bartlomieju force-pushed the biwanczuk/rust-reentry-callback-stacked branch from 3d63348 to f78d0d7 Compare November 20, 2026 09:32
Base automatically changed from biwanczuk/rust-reentry-callback-stacked to main November 20, 2026 12:43
…-loader-pr

# Conflicts:
#	src/rust/jsg-test/tests/wasm_module_object.rs
#	src/rust/jsg/wrappable.rs
#	src/workerd/api/channel-interop/BUILD.bazel
#	src/workerd/api/channel-interop/channel-interop-test.c++
#	src/workerd/api/channel-interop/compile-tests/ok-channels-are-not-send.rs
#	src/workerd/api/channel-interop/ffi.c++
#	src/workerd/api/channel-interop/ffi.h
#	src/workerd/api/channel-interop/ffi.rs
#	src/workerd/api/channel-interop/lib.rs
#	src/workerd/api/channel-interop/test_bridge.rs
#	src/workerd/io/frankenvalue/ffi.h
#	src/workerd/io/io-context/compile-tests/reentry-callback-is-not-send.rs
#	src/workerd/io/io-context/io-context-test.c++
#	src/workerd/io/io-context/lib.rs
#	src/workerd/io/io-context/test-bridge.h
#	src/workerd/io/io-context/test_bridge.rs
#	src/workerd/util/autogate.h
Rust JSG could tell a SharedArrayBuffer apart from other values but
had no handle type for one, so Rust code could not read its bytes. C++
JSG takes a SharedArrayBuffer wherever it takes a kj::Array<byte>, and
the Rust Worker Loader needs to do the same for a module's data and
wasm fields.

This adds Local<SharedArrayBuffer>, which, as in V8, is not a
Local<ArrayBuffer>, with byte_length() and to_vec(). to_vec() copies
the bytes in C++, so that Rust never holds a reference to memory that
another agent may write to.
C++ IoContext::awaitJs() takes a jsg::Promise<T> and hands its
continuation the T, which the promise's own conversion made in an
earlier reaction. Rust's await_js_local() takes only an untyped
promise, so Rust code that receives a jsg::Promise<T> from a callback,
as the Rust Worker Loader does from getCode(), had to convert the value
in the awaiting reaction instead, one microtask earlier than C++.

This adds IoContext::await_js_promise_local(), which awaits a typed
jsg::Promise<'s, T> and passes its value to the map, and
Promise::into_raw_promise(), which it uses to react to the underlying
promise. It also adds TypeErrorContext::CallbackReturn for C++ JSG's
"Callback returned incorrect type" error.
Comparing the two loaders on edge-case inputs found a few places where
the Rust port behaved differently from C++. The port is still behind
the RUST_WORKER_LOADER autogate, but each difference would be visible
to a Worker once the gate is on, so this makes the port match C++:

- A SharedArrayBuffer, or a view of one, is accepted as a module's
  data or wasm bytes, as C++ JSG takes a kj::Array<const byte>.
- getCode() is called with the global object as `this`, and what it
  returns is converted as a jsg::Promise<WorkerCode>: a thenable is
  followed only under unwrap_custom_thenables, a non-promise is
  converted at once, a wrong type gives C++ JSG's "Callback returned
  incorrect type" or "did not resolve to 'WorkerCode'" error, and a
  promise's value is converted in a reaction of its own, before the
  one that builds the source.
- get() requires its name argument and accepts undefined for it, as
  C++ JSG converts a kj::Maybe<kj::String>, and names a getCode of the
  wrong type 'function', as C++ JSG names a jsg::Function.
- The compatibility-date validation mode crosses the FFI as C++'s own
  CompatibilityDateValidation, bound as a cxx extern enum, so its values
  are checked at compile time and an embedder passes the enum it passes
  to the C++ loader.

worker-loader-validation-test covers each of these against both
loaders, under both settings of unwrap_custom_thenables. The new
startup-snapshot-worker-loader-test turns the startup-snapshot
autogate on in its own config, so the C++ loader now also crosses a
snapshot, in the @ variant.
@bartlomieju
bartlomieju force-pushed the biwanczuk/rust-worker-loader-pr branch from 1922824 to c517af0 Compare November 23, 2026 22:50
@bartlomieju
bartlomieju marked this pull request as ready for review November 23, 2026 22:50
@bartlomieju
bartlomieju requested review from a team as code owners November 23, 2026 22:50

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of 07b2f220.

This review, of c517af02

💬 Approved with comments — The Rust port is off by default behind its autogate and matches the C++ loader's checks, error messages and ownership; the only finding is an optional SUGGESTION about contributor guidance.

Findings: 1 suggestion (1 is an inline comment on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📖 AGENTS.md: 💬 1 suggestion

The API directory guide could mention the new Rust Worker Loader package.

Recommendation: 💬 Optional Nits

  • [SUGGESTION] Document the new Rust Worker Loader package and its interop layer in the API directory guide. (src/workerd/api/worker-loader-api/BUILD.bazel:5)
View full review

src/workerd/api/AGENTS.md describes the API directory as C++ implementations. It could point contributors to worker-loader-api (Rust) and worker-loader-interop (C++ shims).


✅ All other checks passed

🔒 Security: ✅ LGTM

No issues found.

  • Limits. The size limits match C++: 64 MiB of code and 1 MiB of env.
  • Channel transfer. Tail and global-outbound channels must allow transfer. Only the inherited outbound skips that check, and the code explains why.
  • Rollout. The binding is off by default behind RUST_WORKER_LOADER.

📋 Code Quality: ✅ LGTM

No issues found.

  • Check order. to_source() follows the C++ order: module count, module conversion, Python and code-size checks, the experimental check, compatibility flags, env size, global outbound, tails, streaming tails, limits.
  • Errors. The error messages match C++ word for word, and validate-test.rs pins them.
  • Buffers. Module buffers are boxed and NUL-terminated, so the views stay valid while the vectors grow.
  • SharedArrayBuffer copy. The shim clamps to the destination size and handles empty buffers.

⚡ Performance: ✅ LGTM

No regressions found.

  • Byte copies. Module bytes are copied once per load, as in the C++ loader.
  • Wasm. A WebAssembly.Module shares its compiled code without a copy.
  • getCode() callback. It holds the IoContext weakly, so a WorkerStub does not keep its request alive or block Durable Object hibernation.

📝 Documentation: ✅ LGTM

No issues found.


Reviewed commit: c517af02

ArrayBufferView::to_vec() formed a &[u8] into the view's buffer and
copied from it. The buffer may be a SharedArrayBuffer, which another
agent may write to at any time, so that slice was formally a data race,
which Local<SharedArrayBuffer>::to_vec() already avoids by copying in
C++. The Rust Worker Loader takes a module's bytes from a view over a
SharedArrayBuffer through this path.

to_vec() now copies in C++ as well, so it never borrows the bytes. The
README and as_slice()'s docs say that as_slice() does borrow and so
suits only views whose buffer isn't shared. A jsg-test pins to_vec() of
a view at an offset, a DataView and a length-tracking view over a
growable SharedArrayBuffer.
src/workerd/api/AGENTS.md described the directory as C++ only. It now
lists worker-loader-api and worker-loader-interop, and its Where to
Look table names both loaders and the RUST_WORKER_LOADER autogate.

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of a5e599fc.

This review, of 07b2f220

✅ Approved — The new commits move the byte copies for SharedArrayBuffer and ArrayBufferView into C++ with size checks and tests, and fix the earlier AGENTS.md suggestion. The port stays off by default behind RUST_WORKER_LOADER, and there are no new findings.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

  • Bounds: the C++ copy shims limit each copy to kj::min(length, out.size()).
  • Data race: Rust no longer forms a slice into memory that another agent can write, which removes the formal data race on shared buffers.
  • Rollout: the port stays off by default behind RUST_WORKER_LOADER.

📖 AGENTS.md: ✅ LGTM

src/workerd/api/AGENTS.md now describes the Rust Worker Loader package and its C++ interop shims, as the earlier review suggested.


📋 Code Quality: ✅ LGTM

  • Length and copy: both to_vec() implementations read the length once, then copy at most the destination's size in C++. The debug_assert_eq! holds.
  • Empty buffers: memcpy sits behind size > 0.
  • Detached and out-of-range views: the view shim uses the same viewBytes bounds check as local_array_buffer_view_data, so it copies zero bytes for them.
  • Declarations: the signatures in ffi.h and v8.rs match the C++ definitions.

⚡ Performance: ✅ LGTM

  • Copies: each copy shim does a single memcpy.
  • Validation: it is linear in the number of modules.

📝 Documentation: ✅ LGTM

The README's new paragraph on Local<SharedArrayBuffer> matches the code: to_vec() copies in C++, and as_slice() borrows the bytes.


Reviewed commit: 07b2f220

@bartlomieju

Copy link
Copy Markdown
Collaborator Author

Plan for this PR, since it now overlaps with other work:

On WorkerStubHandle's unsafe impl Send / Sync: I checked whether
kj_rs::LoopChecked from #8857 should replace them, and I don't think
it fits here. The handle lives in a JSG resource, so it is dropped by
whatever collects the WorkerStub. That can be during another request,
and on another thread when the embedder moves event loops between
threads. LoopChecked aborts when it is dropped off its loop, so it is
meant for state that never reaches the JS heap. The handle wraps an
IoOwn, which exists for exactly this case: dropped off its thread, it
queues the deletion on its IoContext's DeleteQueue, and every use
goes through a shim that first checks that its IoContext is the current
one. What I'd rather have is a safe wrapper for this in io-context, so
a binding can keep an IoOwn-backed handle in a resource without
writing its own unsafe impl. That would be a separate change.

await_js_promise_local() had one caller, the Worker Loader, so it
isn't worth a public IoContext method. The loader now calls
await_js_local() on the typed promise's underlying promise and takes
the value that the promise's own conversion already made, through
PromiseValue::from_raw(). The conversion still runs in a reaction of
its own, before the one that builds the source, as in C++.

@clanky-the-clanker clanky-the-clanker Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Approved — The only change since the last approved review swaps a dedicated IoContext method for await_js_local() plus PromiseValue::from_raw(), and keeps the same behaviour. No new findings.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

No security issues in the changed code. The port stays off by default behind RUST_WORKER_LOADER.


📖 AGENTS.md: ✅ LGTM

src/workerd/api/AGENTS.md describes the Rust Worker Loader package and its C++ interop shims.


📋 Code Quality: ✅ LGTM

get()'s callback awaits code.into_raw_promise() with await_js_local() and unwraps the value with <WorkerCode as PromiseValue>::from_raw:

  • The conversion reaction attached by Promise::<WorkerCode>::try_from_js still runs.
  • A value that is not already a promise goes through the same path.
  • The closure captures only the Copy LoaderState.
  • The match on TypeErrorContext stays exhaustive.

⚡ Performance: ✅ LGTM

  • Validation is linear in the number of modules.
  • Each module body is copied once, the same cost as the C++ loader.
  • Wasm modules are handed over without copying their bytes.

📝 Documentation: ✅ LGTM

No documentation issues.


Reviewed commit: a5e599fc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants