Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
4c148a2
Add Rust interop for Fetcher and DurableObjectClass
bartlomieju Nov 18, 2026
8f27375
Let Rust call JS back later in the IoContext that created the callback
bartlomieju Nov 18, 2026
3d63348
Let Rust convert an awaited JS value into a value local to its IoContext
bartlomieju Nov 19, 2026
0623ba6
jsg-test, jsg-bench: start V8 on the main thread
bartlomieju Nov 18, 2026
5d6af15
Rust JSG: add WasmModuleObject and CompiledWasmModule
bartlomieju Nov 18, 2026
e15b97a
Narrow where a CompiledWasmModule may be dropped
bartlomieju Nov 19, 2026
1d22172
Add a Rust binding for Frankenvalue
bartlomieju Nov 18, 2026
a353c9a
Hand WorkerLoader::get()'s source to KJ in the converting microtask
bartlomieju Nov 19, 2026
aa02b6f
Merge remote-tracking branch 'origin/main' into biwanczuk/rust-worker…
bartlomieju Nov 19, 2026
bb9270d
Port the Worker Loader binding to Rust behind RUST_WORKER_LOADER
bartlomieju Nov 19, 2026
b35fa58
Merge remote-tracking branch 'origin/main' into biwanczuk/rust-worker…
bartlomieju Nov 23, 2026
07e398b
Rust JSG: add SharedArrayBuffer handles
bartlomieju Nov 23, 2026
d20c07e
Let Rust await a typed promise in its IoContext
bartlomieju Nov 23, 2026
6ab878a
Match the C++ Worker Loader where the Rust port differed
bartlomieju Nov 23, 2026
c517af0
Merge remote-tracking branch 'origin/main' into biwanczuk/rust-worker…
bartlomieju Nov 23, 2026
69b0654
Rust JSG: copy an ArrayBufferView's bytes in C++
bartlomieju Nov 24, 2026
07b2f22
Point to the Rust Worker Loader in the API directory guide
bartlomieju Nov 24, 2026
a5e599f
Await getCode()'s typed promise without a new IoContext method
bartlomieju Nov 26, 2026
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
6 changes: 4 additions & 2 deletions docs/startup-snapshot.md
Original file line number Diff line number Diff line change
Expand Up @@ -357,10 +357,12 @@ once.
| `src/workerd/api/tests/startup-snapshot-new-module-registry-test` | the same with the new module registry: re-importing modules the top level imported (also under a query or a fragment, and `import()` from inside those) and builtins, importing one it never loaded, and `import.meta`, including an `import.meta.resolve` the top level kept |
| `src/workerd/api/tests/startup-snapshot-node-test` | Node.js API objects (`AsyncLocalStorage`, a root-frame `AsyncResource`, `node:diagnostics_channel`, and the Rust resources behind `node:url` and `node:dns`) across the snapshot; an `AsyncLocalStorage` with a default value and an `AsyncResource` created inside a frame fall back |
| `src/workerd/api/tests/startup-snapshot-wrappables-test` | live objects (Headers, URL, TextEncoder, TextDecoder, crypto, navigator, performance, tracing spans started outside a request, file system handles to a `/tmp` file and to a bundle file, `node:fs`, bindings) and the identity of `crypto`, `crypto.subtle` and `navigator`, GC and a FinalizationRegistry cleanup across the snapshot; unclonable, `URLSearchParams`, a mid-stream `TextDecoder`, `performance` with a recorded entry and C++ streams left awaiting a `pull()` or `cancel()` fall back; a Worker on C++ streams otherwise transfers |
| `src/workerd/api/tests/startup-snapshot-bindings-test` | bindings captured at module scope (service stub, Durable Object namespace and ID) used at request time; an RPC method taken off a stub, `wrapped` and `cryptoKey` fall back |
| `src/workerd/api/tests/startup-snapshot-bindings-test` | bindings captured at module scope (service stub, Durable Object namespace and ID, Worker Loader) used at request time; an RPC method taken off a stub, `wrapped` and `cryptoKey` fall back |
| `src/workerd/api/tests/startup-snapshot-worker-loader-test` | the Worker Loader case of `startup-snapshot-bindings-test` with the pipeline on in every variant, so both the C++ and the Rust `WorkerLoader` cross the snapshot |
| `src/workerd/server/tests/startup-snapshot-console` | console output printed once; no zygote under an inspector; a top level that throws gets no snapshot and its startup error is reported once |

Each `wd_test` runs the pipeline in its `@all-autogates` variant and the plain Worker in the `@`
variant, and asserts the same observable behavior for both. A case Worker learns which path it
variant, and asserts the same observable behavior for both, except
`startup-snapshot-worker-loader-test`, whose config turns the pipeline on in every variant. A case Worker learns which path it
took at request time from `startedFromStartupSnapshot()` on `workerd:unsafe`; asked at module
scope, the answer would be the zygote's and be baked into the snapshot.
77 changes: 77 additions & 0 deletions src/rust/jsg-test/tests/buffer_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,83 @@ fn array_buffer_try_from_fails_for_typed_array() {
});
}

// =============================================================================
// SharedArrayBuffer
// =============================================================================

#[test]
fn shared_array_buffer_is_not_an_array_buffer() {
let harness = crate::Harness::new();
harness.run_in_context(|lock, ctx| {
let val = ctx.eval_raw(lock, "new SharedArrayBuffer(4)").unwrap();
assert!(v8::Local::<v8::ArrayBuffer>::try_from(val).is_err());
assert!(v8::Local::<v8::SharedArrayBuffer>::try_from(val).is_ok());

let val = ctx.eval_raw(lock, "new ArrayBuffer(4)").unwrap();
assert!(v8::Local::<v8::SharedArrayBuffer>::try_from(val).is_err());
Ok(())
});
}

#[test]
fn shared_array_buffer_to_vec_copies_its_bytes() {
let harness = crate::Harness::new();
harness.run_in_context(|lock, ctx| {
let val = ctx
.eval_raw(
lock,
"const sab = new SharedArrayBuffer(3, { maxByteLength: 8 }); \
new Uint8Array(sab).set([5, 6, 7]); sab.grow(4); sab",
)
.unwrap();
let buf = v8::Local::<v8::SharedArrayBuffer>::try_from(val).unwrap();
assert_eq!(buf.byte_length(), 4);
assert_eq!(buf.to_vec(), vec![5u8, 6, 7, 0]);

let val = ctx.eval_raw(lock, "new SharedArrayBuffer(0)").unwrap();
let buf = v8::Local::<v8::SharedArrayBuffer>::try_from(val).unwrap();
assert!(buf.is_empty());
assert_eq!(buf.to_vec(), Vec::<u8>::new());
Ok(())
});
}

#[test]
fn array_buffer_view_over_shared_array_buffer_to_vec_copies_its_bytes() {
let harness = crate::Harness::new();
harness.run_in_context(|lock, ctx| {
// A view at an offset, a DataView, and a length-tracking view over a growable buffer
// each copy exactly the bytes they cover.
let val = ctx
.eval_raw(
lock,
"globalThis.sab = new SharedArrayBuffer(4, { maxByteLength: 8 }); \
new Uint8Array(sab).set([1, 2, 3, 4]); new Uint8Array(sab, 1, 2)",
)
.unwrap();
let view = v8::Local::<v8::ArrayBufferView>::try_from(val).unwrap();
assert_eq!(view.to_vec(), vec![2u8, 3]);

let val = ctx.eval_raw(lock, "new DataView(sab, 2)").unwrap();
let view = v8::Local::<v8::ArrayBufferView>::try_from(val).unwrap();
assert_eq!(view.to_vec(), vec![3u8, 4]);

let val = ctx
.eval_raw(
lock,
"globalThis.tracking = new Uint8Array(sab); sab.grow(6); tracking",
)
.unwrap();
let view = v8::Local::<v8::ArrayBufferView>::try_from(val).unwrap();
assert_eq!(view.to_vec(), vec![1u8, 2, 3, 4, 0, 0]);

let val = ctx.eval_raw(lock, "new Uint8Array(sab, 6)").unwrap();
let view = v8::Local::<v8::ArrayBufferView>::try_from(val).unwrap();
assert!(view.to_vec().is_empty());
Ok(())
});
}

#[test]
fn array_buffer_into_object() {
let harness = crate::Harness::new();
Expand Down
5 changes: 5 additions & 0 deletions src/rust/jsg/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -917,6 +917,11 @@ lock, and can be handed to C++ with `into_ffi()` as a `kj::Own<v8::CompiledWasmM
which C++ makes another module object without recompiling. As in C++, RTTI describes the module
as `unknown`; a TypeScript override names it `WebAssembly.Module`.

A `Local<SharedArrayBuffer>` is not a `Local<ArrayBuffer>`, as in V8. Its `to_vec()`, like that
of a `Local<ArrayBufferView>`, whose buffer may be shared, copies the bytes in C++, so it never
borrows memory that another agent may write. The `as_slice()` of an `ArrayBufferView` or a typed
array does borrow its bytes, so it suits only a view whose buffer isn't shared.

### `Global<T>`

A persistent handle that outlives `HandleScope`s, for handles that Rust code owns outside
Expand Down
23 changes: 23 additions & 0 deletions src/rust/jsg/ffi.c++
Original file line number Diff line number Diff line change
Expand Up @@ -917,6 +917,20 @@ size_t local_array_buffer_get_backing_store(const Local& buffer) {
local_as_ref_from_ffi<v8::ArrayBuffer>(buffer)->GetBackingStore()));
}

// Local<SharedArrayBuffer>
size_t local_shared_array_buffer_byte_length(const Local& buffer) {
return local_as_ref_from_ffi<v8::SharedArrayBuffer>(buffer)->ByteLength();
}

size_t local_shared_array_buffer_copy_to(const Local& buffer, ::rust::Slice<uint8_t> out) {
auto buf = local_as_ref_from_ffi<v8::SharedArrayBuffer>(buffer);
auto size = kj::min(buf->ByteLength(), out.size());
if (size > 0) {
memcpy(out.data(), buf->Data(), size);
}
return size;
}

// Local<WasmModuleObject>
kj::Own<CompiledWasmModule> local_wasm_module_object_get_compiled_module(const Local& module) {
return kj::heap(local_as_ref_from_ffi<v8::WasmModuleObject>(module)->GetCompiledModule());
Expand Down Expand Up @@ -952,6 +966,15 @@ uintptr_t local_array_buffer_view_data(const Local& view, size_t& byte_length) {
return reinterpret_cast<uintptr_t>(bytes.begin());
}

size_t local_array_buffer_view_copy_to(const Local& view, ::rust::Slice<uint8_t> out) {
auto bytes = viewBytes(local_as_ref_from_ffi<v8::ArrayBufferView>(view));
auto size = kj::min(bytes.size(), out.size());
if (size > 0) {
memcpy(out.data(), bytes.begin(), size);
}
return size;
}

Local local_array_buffer_view_get_buffer(Isolate* isolate, const Local& view) {
return to_ffi(local_as_ref_from_ffi<v8::ArrayBufferView>(view)->Buffer());
}
Expand Down
9 changes: 9 additions & 0 deletions src/rust/jsg/ffi.h
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,12 @@ uint8_t* local_array_buffer_data(const Local& buffer);
uintptr_t local_array_buffer_contents(const Local& buffer, size_t& byteLength);
size_t local_array_buffer_get_backing_store(const Local& buffer);

// Local<SharedArrayBuffer>
size_t local_shared_array_buffer_byte_length(const Local& buffer);
// Copies the first `out.size()` bytes of the buffer, or all of them if it has fewer, into `out`,
// and returns how many it copied.
size_t local_shared_array_buffer_copy_to(const Local& buffer, ::rust::Slice<uint8_t> out);

// Local<WasmModuleObject>
kj::Own<CompiledWasmModule> local_wasm_module_object_get_compiled_module(const Local& module);

Expand All @@ -557,6 +563,9 @@ uint8_t* local_array_buffer_view_buffer_data(const Local& view);
// Returns the address of the first byte the view covers and sets `byte_length` to how many it
// covers, which is zero for a view that is detached or that does not lie within its buffer.
uintptr_t local_array_buffer_view_data(const Local& view, size_t& byte_length);
// Copies the first `out.size()` bytes the view covers, or all of them if it covers fewer, into
// `out`, and returns how many it copied.
size_t local_array_buffer_view_copy_to(const Local& view, ::rust::Slice<uint8_t> out);
Local local_array_buffer_view_get_buffer(Isolate* isolate, const Local& view);
size_t local_array_buffer_view_element_size(const Local& view);
bool local_array_buffer_view_is_integer_type(const Local& view);
Expand Down
5 changes: 5 additions & 0 deletions src/rust/jsg/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,9 @@ impl Error {
"Incorrect type for map entry '{name}': the provided value is not of type \
'{expected}'."
),
TypeErrorContext::CallbackReturn => {
format!("Callback returned incorrect type; expected '{expected}'")
}
};
Self::new_type_error(message)
}
Expand All @@ -767,6 +770,8 @@ pub enum TypeErrorContext<'a> {
ArrayElement(usize),
/// The value of a `Dict` entry, by its key.
DictField(&'a str),
/// What a JavaScript callback returned.
CallbackReturn,
}

/// A wrapper type that prevents automatic type coercion when unwrapping from JavaScript.
Expand Down
8 changes: 8 additions & 0 deletions src/rust/jsg/typed_promise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -615,6 +615,14 @@ impl<'s, T: PromiseValue> Promise<'s, T> {
T::from_raw(lock, raw).map_err(|_| self)
}

/// The JavaScript promise under this one, for code outside Rust JSG that reacts to it once
/// and takes the value from what it settles with by [`PromiseValue::from_raw`], as C++
/// `IoContext::awaitJs()` reacts to a `jsg::Promise<T>`.
#[doc(hidden)]
pub fn into_raw_promise(self) -> Local<'s, v8::Promise> {
self.handle
}

/// Makes the promise persistent, to keep it beyond the current scope.
pub fn into_traced(self, lock: &mut Lock<'s>) -> TracedPromise<T> {
TracedPromise {
Expand Down
57 changes: 54 additions & 3 deletions src/rust/jsg/v8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,12 @@ pub mod ffi {
-> usize;
pub unsafe fn local_array_buffer_get_backing_store(buffer: &Local) -> usize;

// Local<SharedArrayBuffer>
#[nothrow]
pub unsafe fn local_shared_array_buffer_byte_length(buffer: &Local) -> usize;
#[nothrow]
pub unsafe fn local_shared_array_buffer_copy_to(buffer: &Local, out: &mut [u8]) -> usize;

// Local<WasmModuleObject>
pub unsafe fn local_wasm_module_object_get_compiled_module(
module: &Local,
Expand All @@ -395,6 +401,8 @@ pub mod ffi {
pub unsafe fn local_array_buffer_view_byte_length(view: &Local) -> usize;
pub unsafe fn local_array_buffer_view_buffer_data(view: &Local) -> *mut u8;
pub unsafe fn local_array_buffer_view_data(view: &Local, byte_length: &mut usize) -> usize;
#[nothrow]
pub unsafe fn local_array_buffer_view_copy_to(view: &Local, out: &mut [u8]) -> usize;
pub unsafe fn local_array_buffer_view_get_buffer(
isolate: *mut Isolate,
view: &Local,
Expand Down Expand Up @@ -1409,7 +1417,7 @@ impl ffi::ExceptionType {
// Deliberately left unimplemented because we didn't need them yet:
// - Primitive, Numeric
// - NumberObject, BooleanObject, StringObject, SymbolObject, BigIntObject
// - Map, Set, Proxy, RegExp, External, DataView, SharedArrayBuffer, Float16Array
// - Map, Set, Proxy, RegExp, External, DataView, Float16Array
// - WasmMemoryObject
// - Context, Template, ObjectTemplate, Signature, Module, Script, Private, PrimitiveArray
//
Expand Down Expand Up @@ -1688,6 +1696,8 @@ pub struct BigInt64Array;
pub struct BigUint64Array;
pub struct Uint8ClampedArray;
pub struct ArrayBuffer;
/// Marker for `v8::SharedArrayBuffer` handles, which are not `ArrayBuffer`s.
pub struct SharedArrayBuffer;
pub struct ArrayBufferView;
/// Marker for `v8::WasmModuleObject` handles: a `WebAssembly.Module`.
pub struct WasmModuleObject;
Expand Down Expand Up @@ -2729,6 +2739,7 @@ impl_local_cast!(Function: Object, Value; is_function);
impl_local_cast!(Promise: Object, Value; is_promise);
impl_local_cast!(Array: Object, Value; is_array);
impl_local_cast!(ArrayBuffer: Object, Value; is_array_buffer);
impl_local_cast!(SharedArrayBuffer: Object, Value; is_shared_array_buffer);
impl_local_cast!(ArrayBufferView: Object, Value; is_array_buffer_view);
impl_local_cast!(WasmModuleObject: Object, Value; is_wasm_module_object);
impl_local_cast!(TypedArray: ArrayBufferView, Object, Value; is_typed_array);
Expand Down Expand Up @@ -3150,6 +3161,35 @@ impl<'s> Local<'s, ArrayBuffer> {
}
}

impl Local<'_, SharedArrayBuffer> {
/// Returns the byte length of this `SharedArrayBuffer`.
#[inline]
pub fn byte_length(&self) -> usize {
// SAFETY: handle is valid within the current HandleScope.
unsafe { ffi::local_shared_array_buffer_byte_length(self.raw()) }
}

/// Returns `true` if this `SharedArrayBuffer` has zero bytes.
#[inline]
pub fn is_empty(&self) -> bool {
self.byte_length() == 0
}

/// Copies the `SharedArrayBuffer`'s contents into a new `Vec<u8>`.
///
/// Another agent may write to shared memory at any time, so Rust never borrows it: C++
/// copies the bytes, as C++ JSG reads them.
pub fn to_vec(&self) -> Vec<u8> {
let mut bytes = vec![0; self.byte_length()];
// SAFETY: handle is valid within the current HandleScope.
let copied = unsafe { ffi::local_shared_array_buffer_copy_to(self.raw(), &mut bytes) };
// No JavaScript runs between reading the length and copying, so the buffer can't have
// grown; a growable `SharedArrayBuffer` never shrinks.
debug_assert_eq!(copied, bytes.len());
bytes
}
}

impl Local<'_, WasmModuleObject> {
/// Returns the module's compiled code, which outlives this handle.
///
Expand Down Expand Up @@ -3238,6 +3278,9 @@ impl<'s> Local<'s, ArrayBufferView> {
/// no JavaScript (which could detach, resize or write to the buffer) can run while
/// it is live.
///
/// For a view over a `SharedArrayBuffer`, another agent may write the bytes while the slice
/// is live; [`to_vec`](Self::to_vec) copies them without borrowing.
///
/// TODO(soon): When there is a safe aliasing model for Rust mutable access,
/// integrate this method with that somehow.
#[inline]
Expand Down Expand Up @@ -3275,9 +3318,17 @@ impl<'s> Local<'s, ArrayBufferView> {
}

/// Copies the view's visible byte range into a new `Vec<u8>`.
///
/// The view's buffer may be a `SharedArrayBuffer`, which another agent may write to at any
/// time, so C++ copies the bytes and Rust never borrows them.
pub fn to_vec(&self) -> Vec<u8> {
// SAFETY: the bytes are this view's, and no JavaScript runs before the copy completes.
unsafe { &*self.as_raw_slice() }.to_vec()
let mut bytes = vec![0; self.as_raw_slice().len()];
// SAFETY: handle is valid within the current HandleScope.
let copied = unsafe { ffi::local_array_buffer_view_copy_to(self.raw(), &mut bytes) };
// No JavaScript runs between reading the length and copying, so the view can't have
// shrunk.
debug_assert_eq!(copied, bytes.len());
bytes
}

/// A raw pointer to the view's visible bytes, read from V8 in one call. It is dangling, with
Expand Down
3 changes: 3 additions & 0 deletions src/workerd/api/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ crypto/ # WebCrypto + Node crypto: AES, RSA, EC, DH, HKDF, PBKDF2,
streams/ # ReadableStream/WritableStream/TransformStream (internal + standard); has README.md
node/ # Node.js compat C++ layer; register new modules in NODEJS_MODULES macro in node.h
pyodide/ # Python Workers Pyodide/Emscripten bridge (7 files)
worker-loader-api/ # Rust Worker Loader (WorkerLoader, WorkerStub), used under the RUST_WORKER_LOADER autogate
worker-loader-interop/ # C++ shims the Rust Worker Loader calls: source building, isolate loading, stub channels
tests/ # JS integration tests (238 entries); each test = .js + .wd-test pair
```

Expand All @@ -32,6 +34,7 @@ tests/ # JS integration tests (238 entries); each test = .js + .wd
| Encoding (TextEncoder/Dec) | `encoding.h`; stream variants in `streams/encoding.h` |
| Scheduled / Queue / Alarm | `scheduled.h`, `queue.h`, `actor-state.h` |
| HTMLRewriter | `html-rewriter.h` |
| Worker Loader (dynamic Workers) | `worker-loader.{h,c++}` (C++); `worker-loader-api/` + `worker-loader-interop/` (Rust, `RUST_WORKER_LOADER`) |
| R2 storage | `r2-bucket.h`, `r2-multipart.h` |
| KV / SyncKV | `kv.h`, `sync-kv.h` |
| SQL (DO) | `sql.h` |
Expand Down
20 changes: 20 additions & 0 deletions src/workerd/api/tests/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -1425,6 +1425,14 @@ wd_test(
data = ["startup-snapshot-bindings-test.js"],
)

# A Worker Loader binding across a startup snapshot in every variant: the C++ WorkerLoader in @,
# the Rust one in @all-autogates.
wd_test(
src = "startup-snapshot-worker-loader-test.wd-test",
args = ["--experimental"],
data = ["startup-snapshot-bindings-test.js"],
)

# Functions implemented in C++ across a startup snapshot. Only the @all-autogates variant runs the
# pipeline. The @all-compat-flags variant would turn new_module_registry on, under which the
# function createRequire('/worker.js') returns does not find ./lib.cjs.
Expand Down Expand Up @@ -1900,12 +1908,24 @@ wd_test(
data = ["worker-loader-rab-test.js"],
)

wd_test(
src = "worker-loader-validation-test.wd-test",
args = ["--experimental"],
data = ["worker-loader-validation-test.js"],
)

wd_test(
src = "worker-loader-gc-test.wd-test",
args = ["--experimental"],
data = ["worker-loader-gc-test.js"],
)

wd_test(
src = "worker-loader-hibernation-test.wd-test",
args = ["--experimental"],
data = ["worker-loader-hibernation-test.js"],
)

wd_test(
src = "leak-fetch-test.wd-test",
args = [
Expand Down
Loading
Loading