diff --git a/docs/startup-snapshot.md b/docs/startup-snapshot.md index 307011e99cf..6dd0f7ce9ee 100644 --- a/docs/startup-snapshot.md +++ b/docs/startup-snapshot.md @@ -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. diff --git a/src/rust/jsg-test/tests/buffer_types.rs b/src/rust/jsg-test/tests/buffer_types.rs index c077d3dc10d..5af35be9c98 100644 --- a/src/rust/jsg-test/tests/buffer_types.rs +++ b/src/rust/jsg-test/tests/buffer_types.rs @@ -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::::try_from(val).is_err()); + assert!(v8::Local::::try_from(val).is_ok()); + + let val = ctx.eval_raw(lock, "new ArrayBuffer(4)").unwrap(); + assert!(v8::Local::::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::::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::::try_from(val).unwrap(); + assert!(buf.is_empty()); + assert_eq!(buf.to_vec(), Vec::::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::::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::::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::::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::::try_from(val).unwrap(); + assert!(view.to_vec().is_empty()); + Ok(()) + }); +} + #[test] fn array_buffer_into_object() { let harness = crate::Harness::new(); diff --git a/src/rust/jsg/README.md b/src/rust/jsg/README.md index 53dd10b7d2b..cb742b618bc 100644 --- a/src/rust/jsg/README.md +++ b/src/rust/jsg/README.md @@ -917,6 +917,11 @@ lock, and can be handed to C++ with `into_ffi()` as a `kj::Own` is not a `Local`, as in V8. Its `to_vec()`, like that +of a `Local`, 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` A persistent handle that outlives `HandleScope`s, for handles that Rust code owns outside diff --git a/src/rust/jsg/ffi.c++ b/src/rust/jsg/ffi.c++ index 68a5f4f3470..f0493434bc7 100644 --- a/src/rust/jsg/ffi.c++ +++ b/src/rust/jsg/ffi.c++ @@ -917,6 +917,20 @@ size_t local_array_buffer_get_backing_store(const Local& buffer) { local_as_ref_from_ffi(buffer)->GetBackingStore())); } +// Local +size_t local_shared_array_buffer_byte_length(const Local& buffer) { + return local_as_ref_from_ffi(buffer)->ByteLength(); +} + +size_t local_shared_array_buffer_copy_to(const Local& buffer, ::rust::Slice out) { + auto buf = local_as_ref_from_ffi(buffer); + auto size = kj::min(buf->ByteLength(), out.size()); + if (size > 0) { + memcpy(out.data(), buf->Data(), size); + } + return size; +} + // Local kj::Own local_wasm_module_object_get_compiled_module(const Local& module) { return kj::heap(local_as_ref_from_ffi(module)->GetCompiledModule()); @@ -952,6 +966,15 @@ uintptr_t local_array_buffer_view_data(const Local& view, size_t& byte_length) { return reinterpret_cast(bytes.begin()); } +size_t local_array_buffer_view_copy_to(const Local& view, ::rust::Slice out) { + auto bytes = viewBytes(local_as_ref_from_ffi(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(view)->Buffer()); } diff --git a/src/rust/jsg/ffi.h b/src/rust/jsg/ffi.h index ee28e130a69..af91acd7cc7 100644 --- a/src/rust/jsg/ffi.h +++ b/src/rust/jsg/ffi.h @@ -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 +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 out); + // Local kj::Own local_wasm_module_object_get_compiled_module(const Local& module); @@ -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 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); diff --git a/src/rust/jsg/lib.rs b/src/rust/jsg/lib.rs index d5ef60f2f17..19c5e670166 100644 --- a/src/rust/jsg/lib.rs +++ b/src/rust/jsg/lib.rs @@ -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) } @@ -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. diff --git a/src/rust/jsg/typed_promise.rs b/src/rust/jsg/typed_promise.rs index 15d5d88c73b..946eec74f98 100644 --- a/src/rust/jsg/typed_promise.rs +++ b/src/rust/jsg/typed_promise.rs @@ -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`. + #[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 { TracedPromise { diff --git a/src/rust/jsg/v8.rs b/src/rust/jsg/v8.rs index 8f76e2fe731..32d918035ea 100644 --- a/src/rust/jsg/v8.rs +++ b/src/rust/jsg/v8.rs @@ -378,6 +378,12 @@ pub mod ffi { -> usize; pub unsafe fn local_array_buffer_get_backing_store(buffer: &Local) -> usize; + // Local + #[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 pub unsafe fn local_wasm_module_object_get_compiled_module( module: &Local, @@ -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, @@ -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 // @@ -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; @@ -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); @@ -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`. + /// + /// 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 { + 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. /// @@ -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] @@ -3275,9 +3318,17 @@ impl<'s> Local<'s, ArrayBufferView> { } /// Copies the view's visible byte range into a new `Vec`. + /// + /// 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 { - // 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 diff --git a/src/workerd/api/AGENTS.md b/src/workerd/api/AGENTS.md index b9f1e724f0f..32932359e8c 100644 --- a/src/workerd/api/AGENTS.md +++ b/src/workerd/api/AGENTS.md @@ -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 ``` @@ -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` | diff --git a/src/workerd/api/tests/BUILD.bazel b/src/workerd/api/tests/BUILD.bazel index 3b2bdff895a..020af840461 100644 --- a/src/workerd/api/tests/BUILD.bazel +++ b/src/workerd/api/tests/BUILD.bazel @@ -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. @@ -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 = [ diff --git a/src/workerd/api/tests/startup-snapshot-bindings-test.js b/src/workerd/api/tests/startup-snapshot-bindings-test.js index 2560d951f35..bb5e0db833f 100644 --- a/src/workerd/api/tests/startup-snapshot-bindings-test.js +++ b/src/workerd/api/tests/startup-snapshot-bindings-test.js @@ -34,6 +34,9 @@ switch (MODE) { captured = { ns, id: ns.idFromName('a') }; break; } + case 'worker-loader': + captured = env.LOADER; + break; case 'rpc-property': // A method taken off a stub is a JsRpcProperty holding the stub, which has no transfer. captured = env.RPC.ping; @@ -80,6 +83,31 @@ async function checks() { captured.id.toString() === env.NS.idFromName('a').toString(), works: (await captured.ns.get(captured.id).ping()) === 'pong', }; + case 'worker-loader': { + const code = (compatibilityDate) => ({ + compatibilityDate, + mainModule: 'main.js', + modules: { + 'main.js': 'export default { echo(value) { return value; } }', + }, + }); + // workerd's loaders accept compatibility dates up to the code version only. + let futureDateRejected = false; + try { + await captured.load(code('2999-12-31')).getEntrypoint().echo(''); + } catch (e) { + futureDateRejected = /compatibility date/.test(e.message); + } + return { + sameBinding: captured === env.LOADER, + works: + (await captured + .load(code('2025-01-01')) + .getEntrypoint() + .echo('pong')) === 'pong', + futureDateRejected, + }; + } case 'rpc-property': return { works: (await captured()) === 'pong' }; case 'wrapped': @@ -107,15 +135,22 @@ async function test(ctrl, env) { // The runner went through the same pipeline as the cases: whether it was started from a // snapshot says whether the pipeline is on in this variant. const pipelineOn = unsafe.startedFromStartupSnapshot(); + // A config that turns the startup-snapshot autogate on itself requires the pipeline in every + // variant. + if (env.SNAPSHOT_REQUIRED) { + strictEqual(pipelineOn, true, 'runner: snapshotUsed'); + } // Cases whose top level the zygote can carry: started from the snapshot when the pipeline is // on. - const transferable = ['rpc', 'durable-object']; + const transferable = ['rpc', 'durable-object', 'worker-loader']; // Cases that fail the zygote, or whose bindings keep them out of the pipeline: always plain // Workers. const fallback = ['rpc-property', 'wrapped', 'crypto-key']; + // A config may bind only some of the cases. const run = async (name, expectedSnapshotUsed) => { + if (!(name in env)) return; const response = await env[name].fetch('http://case/'); const r = await response.json(); strictEqual(r.mode, name); diff --git a/src/workerd/api/tests/startup-snapshot-bindings-test.wd-test b/src/workerd/api/tests/startup-snapshot-bindings-test.wd-test index 2679d92376f..c60dd247222 100644 --- a/src/workerd/api/tests/startup-snapshot-bindings-test.wd-test +++ b/src/workerd/api/tests/startup-snapshot-bindings-test.wd-test @@ -3,7 +3,8 @@ using Workerd = import "/workerd/workerd.capnp"; # Capability bindings captured at module scope and used at request time; see # startup-snapshot-bindings-test.js. The runner's test() fetches every case service and asserts # its report. The @all-autogates variant turns the startup-snapshot autogate on, so every service -# here goes through the zygote; the @ variant runs them as plain Workers. +# here goes through the zygote, and the rust-worker-loader autogate, so the loader binding is the +# Rust WorkerLoader; the @ variant runs them as plain Workers with the C++ WorkerLoader. const compatibilityFlags :List(Text) = [ "nodejs_compat", @@ -26,6 +27,7 @@ const unitTests :Workerd.Config = ( (name = "MODE", json = "\"runner\""), (name = "rpc", service = "rpc"), (name = "durable-object", service = "durable-object"), + (name = "worker-loader", service = "worker-loader"), (name = "rpc-property", service = "rpc-property"), (name = "wrapped", service = "wrapped"), (name = "crypto-key", service = "crypto-key"), @@ -56,6 +58,16 @@ const unitTests :Workerd.Config = ( ], ) ), + ( name = "worker-loader", + worker = ( + modules = .modules, + compatibilityFlags = .compatibilityFlags, + bindings = [ + (name = "MODE", json = "\"worker-loader\""), + (name = "LOADER", workerLoader = ()), + ], + ) + ), ( name = "rpc-property", worker = ( modules = .modules, diff --git a/src/workerd/api/tests/startup-snapshot-worker-loader-test.wd-test b/src/workerd/api/tests/startup-snapshot-worker-loader-test.wd-test new file mode 100644 index 00000000000..9780e9ce7e9 --- /dev/null +++ b/src/workerd/api/tests/startup-snapshot-worker-loader-test.wd-test @@ -0,0 +1,48 @@ +using Workerd = import "/workerd/workerd.capnp"; + +# The worker-loader case of startup-snapshot-bindings-test.js, with the startup-snapshot autogate +# turned on here, so every variant starts from a snapshot: the @ variant with the C++ +# WorkerLoader, and the @all-autogates variant, which also turns the rust-worker-loader autogate +# on, with the Rust one. + +const compatibilityFlags :List(Text) = [ + "nodejs_compat", + "typescript_implemented_streams", + "experimental", + "unsafe_module", +]; + +const modules :List(Workerd.Worker.Module) = [ + (name = "worker", esModule = embed "startup-snapshot-bindings-test.js"), +]; + +const unitTests :Workerd.Config = ( + services = [ + ( name = "runner", + worker = ( + modules = .modules, + compatibilityFlags = .compatibilityFlags, + bindings = [ + (name = "MODE", json = "\"runner\""), + (name = "SNAPSHOT_REQUIRED", json = "true"), + (name = "worker-loader", service = "worker-loader"), + ], + ) + ), + ( name = "worker-loader", + worker = ( + modules = .modules, + compatibilityFlags = .compatibilityFlags, + bindings = [ + (name = "MODE", json = "\"worker-loader\""), + (name = "LOADER", workerLoader = ()), + ], + ) + ), + ], + # typescript_implemented_streams needs the per-isolate bootstrap in every variant. + autogates = [ + "workerd-autogate-per-isolate-javascript-bootstrap", + "workerd-autogate-startup-snapshot", + ], +); diff --git a/src/workerd/api/tests/worker-loader-hibernation-test.js b/src/workerd/api/tests/worker-loader-hibernation-test.js new file mode 100644 index 00000000000..7b701e78ca5 --- /dev/null +++ b/src/workerd/api/tests/worker-loader-hibernation-test.js @@ -0,0 +1,49 @@ +// 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 + +// A Durable Object that holds a WorkerStub from LOADER.get() can still go idle and be evicted: +// the stub's getCode callback holds the actor's IoContext weakly, so it does not keep the +// actor's request open. +import assert from 'node:assert'; +import unsafe from 'workerd:unsafe'; +import { DurableObject } from 'cloudflare:workers'; + +export class LoaderHolder extends DurableObject { + constructor(ctx, env) { + super(ctx, env); + this.worker = null; + } + + // Keeps the stub in a field. workerd fetches a dynamic worker's code once, at load, and drops + // the getCode callback when the worker has started, so getCode() here never resolves: that + // keeps the callback alive for as long as the stub. + hold() { + this.worker = this.env.LOADER.get('child', () => new Promise(() => {})); + } + + holdsWorker() { + return this.worker !== null; + } +} + +export const evictWhileHoldingWorkerStub = { + async test(ctrl, env) { + const stub = env.HOLDER.getByName('holder'); + await stub.hold(); + assert.strictEqual(await stub.holdsWorker(), true); + + // evict() waits for the actor to become idle. Its own deadline outlasts the test's, so a + // shorter one turns an actor that never goes idle into a failure here. + const deadline = new Promise((resolve, reject) => { + setTimeout( + () => reject(new Error('the Durable Object never became idle')), + 5000 + ); + }); + await Promise.race([unsafe.evict(stub), deadline]); + + // The next call reaches a new instance, which holds no stub. + assert.strictEqual(await stub.holdsWorker(), false); + }, +}; diff --git a/src/workerd/api/tests/worker-loader-hibernation-test.wd-test b/src/workerd/api/tests/worker-loader-hibernation-test.wd-test new file mode 100644 index 00000000000..9226933602a --- /dev/null +++ b/src/workerd/api/tests/worker-loader-hibernation-test.wd-test @@ -0,0 +1,23 @@ +using Workerd = import "/workerd/workerd.capnp"; + +const unitTests :Workerd.Config = ( + services = [ + ( name = "TEST_TMPDIR", disk = (writable = true) ), + ( name = "worker-loader-hibernation-test", + worker = ( + modules = [ + ( name = "worker", esModule = embed "worker-loader-hibernation-test.js" ), + ], + compatibilityFlags = ["nodejs_compat", "experimental", "unsafe_module"], + durableObjectNamespaces = [ + ( className = "LoaderHolder", uniqueKey = "loader-holder" ), + ], + durableObjectStorage = ( localDisk = "TEST_TMPDIR" ), + bindings = [ + ( name = "LOADER", workerLoader = () ), + ( name = "HOLDER", durableObjectNamespace = "LoaderHolder" ), + ], + ) + ), + ], +); diff --git a/src/workerd/api/tests/worker-loader-validation-test.js b/src/workerd/api/tests/worker-loader-validation-test.js new file mode 100644 index 00000000000..5266a0df239 --- /dev/null +++ b/src/workerd/api/tests/worker-loader-validation-test.js @@ -0,0 +1,321 @@ +// 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 errors Worker Loader throws for code of the wrong type, the order it checks the code in, +// and a Worker whose modules C++ keeps in buffers that grow while they are added. + +import assert from 'node:assert'; + +// Minimal valid WASM module that exports an add(i32, i32) -> i32 function. +const WASM_ADD_BYTES = new Uint8Array([ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x07, 0x01, 0x60, 0x02, + 0x7f, 0x7f, 0x01, 0x7f, 0x03, 0x02, 0x01, 0x00, 0x07, 0x07, 0x01, 0x03, 0x61, + 0x64, 0x64, 0x00, 0x00, 0x0a, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, + 0x6a, 0x0b, +]); + +const MAIN = 'export default { fetch() { return new Response("ok"); } }'; + +function code(overrides) { + return { + compatibilityDate: '2025-01-01', + mainModule: 'main.js', + modules: { 'main.js': MAIN }, + ...overrides, + }; +} + +function field(name, struct, type) { + return ( + `Incorrect type for the '${name}' field on '${struct}': ` + + `the provided value is not of type '${type}'.` + ); +} + +const DATA = field('data', 'Module', 'Array'); +const WASM = field('wasm', 'Module', 'Array or WasmModuleObject'); +const ELEMENT_0 = + "Incorrect type for array element 0: the provided value is not of type 'Fetcher'."; + +function rejects(env, overrides, message) { + assert.throws(() => env.loader.load(code(overrides)), { + name: 'TypeError', + message, + }); +} + +// Each field whose conversion can fail, given a value of the wrong type, throws what C++ JSG throws +// for that field of the C++ struct. +export let wrongTypes = { + test(ctrl, env) { + rejects(env, { modules: { 'main.js': MAIN, 'a.bin': { data: 5 } } }, DATA); + rejects(env, { modules: { 'main.js': MAIN, 'a.wasm': { wasm: 5 } } }, WASM); + rejects(env, { env: 5 }, field('env', 'WorkerCode', 'Object')); + rejects(env, { env: null }, field('env', 'WorkerCode', 'Object')); + rejects(env, { tails: [5] }, ELEMENT_0); + rejects(env, { tails: 5 }, field('tails', 'WorkerCode', 'Array')); + rejects(env, { allowExperimental: true, streamingTails: [5] }, ELEMENT_0); + rejects( + env, + { allowExperimental: true, streamingTails: 5 }, + field('streamingTails', 'WorkerCode', 'Array') + ); + const worker = env.loader.load(code({})); + const props = field('props', 'EntrypointOptions', 'Object'); + assert.throws(() => worker.getEntrypoint(undefined, { props: 5 }), { + name: 'TypeError', + message: props, + }); + assert.throws(() => worker.getDurableObjectClass(undefined, { props: 5 }), { + name: 'TypeError', + message: props, + }); + }, +}; + +// A `globalOutbound` that isn't a `Fetcher` converts, as C++ JSG converts a +// `kj::Maybe>`: under `dont_substitute_null_on_type_error` it is a `TypeError`, +// and otherwise it is none, which blocks the global outbound, as `null` does. +export let globalOutboundOfWrongType = { + async test(ctrl, env) { + const fetcher = code({ + globalOutbound: 5, + modules: { + 'main.js': `export default { + async fetch() { + try { + await fetch("http://example.com/"); + return new Response("fetched"); + } catch (e) { + return new Response(e.message); + } + } + }`, + }, + }); + if (env.noSubstituteNull) { + assert.throws(() => env.loader.load(fetcher), { + name: 'TypeError', + message: field('globalOutbound', 'WorkerCode', 'Fetcher'), + }); + return; + } + const worker = env.loader.load(fetcher); + const response = await worker.getEntrypoint().fetch('http://x/'); + assert.strictEqual( + await response.text(), + 'This worker is not permitted to access the internet via global functions like fetch(). ' + + "It must use capabilities (such as bindings in 'env') to talk to the outside world." + ); + }, +}; + +// Fields of the wrong type are found before any module is checked, as C++ JSG converts the whole +// struct first. +export let typeErrorsComeFirst = { + test(ctrl, env) { + // Not the error for a TypeScript module name. + rejects( + env, + { modules: { 'x.ts': 'export {}', 'main.js': { data: 5 } } }, + DATA + ); + // Not the error for a module object with two properties. + rejects(env, { modules: { 'main.js': { js: MAIN, data: 5 } } }, DATA); + // Not the error for `env`, which follows `modules` in the struct. + rejects(env, { modules: { 'main.js': { data: 5 } }, env: 5 }, DATA); + // Not the error for a Python module in a JavaScript Worker. + rejects( + env, + { modules: { 'main.js': MAIN, 'x.py': '', 'w.wasm': { wasm: 5 } } }, + WASM + ); + }, +}; + +// A byte module and a WASM module, each before many text modules, so that the buffers C++ keeps +// the modules' names and bodies in grow while modules are added. +export let manyModules = { + async test(ctrl, env) { + const modules = {}; + modules['a.bin'] = { data: new TextEncoder().encode('bytes') }; + for (let i = 0; i < 20; i++) modules[`t${i}.js`] = `export default ${i};`; + modules['w.wasm'] = { wasm: WASM_ADD_BYTES }; + for (let i = 20; i < 40; i++) modules[`t${i}.js`] = `export default ${i};`; + let imports = ''; + let sum = ''; + for (let i = 0; i < 40; i++) { + imports += `import t${i} from "t${i}.js";\n`; + sum += `+ t${i}`; + } + modules['main.js'] = ` + ${imports} + import bytes from "a.bin"; + import wasm from "w.wasm"; + export default { + fetch() { + const add = new WebAssembly.Instance(wasm).exports.add; + const text = new TextDecoder().decode(bytes); + return new Response(text + " " + add(0 ${sum}, 1)); + } + }`; + const worker = env.loader.load(code({ modules })); + const response = await worker.getEntrypoint().fetch('http://x/'); + assert.strictEqual(await response.text(), 'bytes 781'); + }, +}; + +function respond(text) { + return code({ + modules: { + 'main.js': `export default { fetch() { return new Response(${JSON.stringify(text)}); } }`, + }, + }); +} + +async function fetchText(worker) { + const response = await worker.getEntrypoint().fetch('http://x/'); + return response.text(); +} + +// A `SharedArrayBuffer`, or a view of one, is bytes for a `data` or `wasm` module, as C++ JSG +// takes a `kj::Array`. +export let sharedArrayBuffers = { + async test(ctrl, env) { + const shared = (bytes) => { + const buffer = new SharedArrayBuffer(bytes.byteLength); + new Uint8Array(buffer).set(bytes); + return buffer; + }; + const text = new TextEncoder().encode('shared'); + const worker = env.loader.load( + code({ + modules: { + 'main.js': ` + import bytes from "a.bin"; + import view from "b.bin"; + import wasm from "w.wasm"; + export default { + fetch() { + const add = new WebAssembly.Instance(wasm).exports.add; + const decode = (b) => new TextDecoder().decode(b); + return new Response(decode(bytes) + " " + decode(view) + " " + add(2, 3)); + } + }`, + 'a.bin': { data: shared(text) }, + 'b.bin': { data: new Uint8Array(shared(text), 1, 4) }, + 'w.wasm': { wasm: shared(WASM_ADD_BYTES) }, + }, + }) + ); + assert.strictEqual(await fetchText(worker), 'shared hare 5'); + }, +}; + +// `get()` takes a name, which may be `null` or `undefined` but not missing, as C++ JSG converts a +// `kj::Maybe` parameter. +export let getArguments = { + async test(ctrl, env) { + assert.throws(() => env.loader.get(), { + name: 'TypeError', + message: + "Failed to execute 'get' on 'WorkerLoader': parameter 1 is not of type 'string'.", + }); + assert.throws(() => env.loader.get(null), { + name: 'TypeError', + message: + "Failed to execute 'get' on 'WorkerLoader': parameter 2 is not of type 'function'.", + }); + const worker = env.loader.get(undefined, () => respond('unnamed')); + assert.strictEqual(await fetchText(worker), 'unnamed'); + }, +}; + +// `getCode()` is called with the global object as `this`, as C++ JSG calls a `jsg::Function`. +export let getCodeThis = { + async test(ctrl, env) { + let thisIsGlobal; + const worker = env.loader.get('get-code-this', function () { + thisIsGlobal = this === globalThis; + return respond('called'); + }); + assert.strictEqual(await fetchText(worker), 'called'); + assert.strictEqual(thisIsGlobal, true); + }, +}; + +// What `getCode()` returns converts as C++ JSG converts a callback's `jsg::Promise`: +// a promise to what it resolves to, a thenable to what it resolves to only under +// `unwrap_custom_thenables`, and anything else to `WorkerCode` itself. +export let getCodeResults = { + async test(ctrl, env) { + assert.strictEqual( + await fetchText(env.loader.get('plain', () => respond('plain'))), + 'plain' + ); + assert.strictEqual( + await fetchText( + env.loader.get('promise', async () => respond('promise')) + ), + 'promise' + ); + + const thenable = { + ...respond('the thenable itself'), + then(resolve) { + resolve(respond('what it resolves to')); + }, + }; + assert.strictEqual( + await fetchText(env.loader.get('thenable', () => thenable)), + env.unwrapThenables ? 'what it resolves to' : 'the thenable itself' + ); + + await assert.rejects(fetchText(env.loader.get('number', () => 5)), { + name: 'TypeError', + message: "Callback returned incorrect type; expected 'Promise'", + }); + await assert.rejects( + fetchText(env.loader.get('async-number', async () => 5)), + { + name: 'TypeError', + message: + "Incorrect type for Promise: the Promise did not resolve to 'WorkerCode'.", + } + ); + }, +}; + +// A promise from `getCode()` is converted to `WorkerCode` in a reaction of its own, and the +// Worker's source, which serializes `env`, is made in the next one, as C++ JSG converts the +// promise before `IoContext::awaitJs()` reacts to it. +export let getCodeConversionOrder = { + async test(ctrl, env) { + const log = []; + const worker = env.loader.get('conversion-order', () => { + queueMicrotask(() => log.push('queued by getCode')); + return Promise.resolve({ + ...respond('ordered'), + get compatibilityDate() { + log.push('convert'); + queueMicrotask(() => log.push('queued by conversion')); + return '2025-01-01'; + }, + env: { + get value() { + log.push('serialize env'); + return 1; + }, + }, + }); + }); + assert.strictEqual(await fetchText(worker), 'ordered'); + assert.deepStrictEqual(log, [ + 'queued by getCode', + 'convert', + 'queued by conversion', + 'serialize env', + ]); + }, +}; diff --git a/src/workerd/api/tests/worker-loader-validation-test.wd-test b/src/workerd/api/tests/worker-loader-validation-test.wd-test new file mode 100644 index 00000000000..5dbf1757da7 --- /dev/null +++ b/src/workerd/api/tests/worker-loader-validation-test.wd-test @@ -0,0 +1,45 @@ +using Workerd = import "/workerd/workerd.capnp"; + +# The same tests under each setting of `dont_substitute_null_on_type_error`, which changes how a +# `globalOutbound` of the wrong type converts, and of `unwrap_custom_thenables`, which changes how +# a thenable that `getCode()` returns converts. +const unitTests :Workerd.Config = ( + services = [ + ( name = "worker-loader-validation-test", + worker = ( + modules = [ + (name = "worker", esModule = embed "worker-loader-validation-test.js") + ], + compatibilityFlags = [ + "nodejs_compat", + "experimental", + "dont_substitute_null_on_type_error", + "unwrap_custom_thenables", + ], + bindings = [ + (name = "loader", workerLoader = ()), + (name = "noSubstituteNull", json = "true"), + (name = "unwrapThenables", json = "true"), + ], + ) + ), + ( name = "worker-loader-validation-substitute-null-test", + worker = ( + modules = [ + (name = "worker", esModule = embed "worker-loader-validation-test.js") + ], + compatibilityFlags = [ + "nodejs_compat", + "experimental", + "substitute_null_on_type_error", + "no_unwrap_custom_thenables", + ], + bindings = [ + (name = "loader", workerLoader = ()), + (name = "noSubstituteNull", json = "false"), + (name = "unwrapThenables", json = "false"), + ], + ) + ), + ], +); diff --git a/src/workerd/api/worker-loader-api/BUILD.bazel b/src/workerd/api/worker-loader-api/BUILD.bazel new file mode 100644 index 00000000000..fc767397de0 --- /dev/null +++ b/src/workerd/api/worker-loader-api/BUILD.bazel @@ -0,0 +1,25 @@ +load("//:build/wd_rust_crate.bzl", "wd_rust_crate") + +# WorkerLoader and WorkerStub, the JavaScript API of a Worker Loader binding, in Rust. C++ creates +# it for a Worker Loader binding when the RUST_WORKER_LOADER autogate is on; worker-loader.c++ +# otherwise. +wd_rust_crate( + name = "worker-loader-api", + cxx_bridge_deps = [ + "//src/rust/jsg", + "//src/workerd/io:compatibility-date", + ], + cxx_bridge_hdrs = [], + cxx_bridge_src = "ffi.rs", + cxx_bridge_visibility = ["//visibility:public"], + proc_macro_deps = ["//src/rust/jsg-macros"], + visibility = ["//visibility:public"], + deps = [ + "//src/rust/jsg", + "//src/rust/jsg-cpp", + "//src/workerd/api/channel-interop", + "//src/workerd/api/worker-loader-interop", + "//src/workerd/io/frankenvalue", + "//src/workerd/io/io-context", + ], +) diff --git a/src/workerd/api/worker-loader-api/code.rs b/src/workerd/api/worker-loader-api/code.rs new file mode 100644 index 00000000000..67c7041e2ba --- /dev/null +++ b/src/workerd/api/worker-loader-api/code.rs @@ -0,0 +1,132 @@ +// 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 types of a module object's `data` and `wasm` fields, which C++ declares as +//! `kj::Array` and `kj::OneOf, jsg::V8Ref>`. +//! Rust JSG has no type that takes an `ArrayBuffer` or an `ArrayBufferView` as bytes, so these +//! convert as C++ JSG converts those types, with the names C++ JSG gives them in its errors. + +use jsg::FromJS; +use jsg::ToJS; +use jsg::v8; + +/// The bytes of an `ArrayBufferView`, an `ArrayBuffer` or a `SharedArrayBuffer`, as C++ JSG +/// takes a `kj::Array`, copied out of the V8 backing store, which a resizable or +/// transferable buffer can lose before the Worker is compiled. +fn bytes_of(value: v8::Local<'_, v8::Value>) -> Option> { + if let Ok(view) = v8::Local::::try_from(value) { + return Some(view.to_vec()); + } + if let Ok(buffer) = v8::Local::::try_from(value) { + return Some(buffer.to_vec()); + } + if let Ok(buffer) = v8::Local::::try_from(value) { + return Some(buffer.to_vec()); + } + None +} + +/// A `data` module's body: the bytes of an `ArrayBuffer` or an `ArrayBufferView`, which it +/// imports as an `ArrayBuffer`. +pub struct Bytes(pub Vec); + +jsg::jsg_traced_unchecked!(Bytes); + +impl jsg::TypeInfo for Bytes { + fn describe(cx: &mut jsg::rtti::Context) -> jsg::rtti::Type { + ::describe(cx) + } +} + +impl<'s> FromJS<'s> for Bytes { + type ResultType = Self; + + // Reading a buffer's bytes runs no script. + const OBJECT_CONVERSION_MAY_RUN_SCRIPT: bool = false; + + // As C++ JSG names `kj::Array`. + fn type_name() -> String { + "Array".to_owned() + } + + fn from_js(lock: &mut jsg::Lock<'s>, value: v8::Local<'s, v8::Value>) -> jsg::Result { + Self::try_from_js(lock, value)?.ok_or_else(|| { + jsg::Error::new_type_error(format!("Expected Array but got {}", value.type_of(lock))) + }) + } + + fn try_from_js( + _lock: &mut jsg::Lock<'s>, + value: v8::Local<'s, v8::Value>, + ) -> jsg::Result> { + Ok(bytes_of(value).map(Self)) + } +} + +impl<'s> ToJS<'s> for Bytes { + fn to_js(self, lock: &mut jsg::Lock<'s>) -> jsg::Result> { + Ok(v8::ArrayBuffer::new(lock, &self.0).into()) + } +} + +/// A `wasm` module's body: bytes to compile, or a `WebAssembly.Module` whose compiled code the +/// Worker shares. +pub enum Wasm { + Bytes(Vec), + Module(v8::TracedGlobal), +} + +impl jsg::Traced for Wasm { + fn trace(&self, visitor: &mut v8::GcVisitor) { + if let Self::Module(module) = self { + module.trace(visitor); + } + } +} + +impl jsg::TypeInfo for Wasm { + fn describe(cx: &mut jsg::rtti::Context) -> jsg::rtti::Type { + ::describe(cx) + } +} + +impl<'s> FromJS<'s> for Wasm { + type ResultType = Self; + + // Reading a buffer's bytes or checking for a module object runs no script. + const OBJECT_CONVERSION_MAY_RUN_SCRIPT: bool = false; + + // As C++ JSG names `kj::OneOf, jsg::V8Ref>`. + fn type_name() -> String { + "Array or WasmModuleObject".to_owned() + } + + fn from_js(lock: &mut jsg::Lock<'s>, value: v8::Local<'s, v8::Value>) -> jsg::Result { + Self::try_from_js(lock, value)?.ok_or_else(|| { + jsg::Error::new_type_error(format!( + "Expected Array or WasmModuleObject but got {}", + value.type_of(lock) + )) + }) + } + + fn try_from_js( + lock: &mut jsg::Lock<'s>, + value: v8::Local<'s, v8::Value>, + ) -> jsg::Result> { + if let Ok(module) = v8::Local::::try_from(value) { + return Ok(Some(Self::Module(module.to_traced_global(lock)))); + } + Ok(bytes_of(value).map(Self::Bytes)) + } +} + +impl<'s> ToJS<'s> for Wasm { + fn to_js(self, lock: &mut jsg::Lock<'s>) -> jsg::Result> { + match self { + Self::Bytes(bytes) => Ok(v8::ArrayBuffer::new(lock, &bytes).into()), + Self::Module(module) => Ok(module.as_local(lock).into()), + } + } +} diff --git a/src/workerd/api/worker-loader-api/dicts.rs b/src/workerd/api/worker-loader-api/dicts.rs new file mode 100644 index 00000000000..643e82e6bd6 --- /dev/null +++ b/src/workerd/api/worker-loader-api/dicts.rs @@ -0,0 +1,90 @@ +// 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 JavaScript dictionaries of Worker Loader. + +// `#[jsg_struct]` binds each field to a local of the same name in the code it generates. +#![allow( + non_snake_case, + reason = "a `#[jsg_struct]` field is named as its JavaScript property is" +)] + +use channel_interop::Fetcher; +use jsg::v8; +use jsg_macros::jsg_oneof; +use jsg_macros::jsg_struct; + +use crate::code::Bytes; +use crate::code::Wasm; + +// Each struct is named as its C++ counterpart, which C++ JSG's conversion errors name, and the +// TypeScript name C++ generates is given by `ts_override`. + +/// Limits on a stage of a Worker's resources, as C++ `workerd::ResourceLimits`. +#[jsg_struct] +pub struct ResourceLimits { + pub cpuMs: Option, + pub subRequests: Option, +} + +/// The options of `WorkerStub.getEntrypoint()` and `getDurableObjectClass()`. +#[jsg_struct(ts_override = "WorkerStubEntrypointOptions")] +pub struct EntrypointOptions { + pub props: Option>, + pub limits: Option, +} + +/// A module given as an object, whose one field says what kind of module it is. +#[jsg_struct( + ts_override = "WorkerLoaderModule { data?: ArrayBuffer; json?: any; wasm?: ArrayBuffer | \ + ArrayBufferView | WebAssembly.Module; }" +)] +pub struct Module { + /// An ES module. + pub js: Option, + /// A `CommonJS` module. + pub cjs: Option, + /// A text blob, which imports as a string. + pub text: Option, + /// A byte blob, which imports as an `ArrayBuffer`. + pub data: Option, + /// Any JavaScript value, serialized to JSON and parsed again when imported. + pub json: Option>, + /// A Python module. + pub py: Option, + /// A WASM module, as bytes to compile or an already-compiled `WebAssembly.Module`. + pub wasm: Option, +} + +/// What a module name maps to: a `WebAssembly.Module`, whose compiled code the Worker shares, a +/// module object, or a string whose kind the name gives. +#[jsg_oneof] +pub enum ModuleContent { + Wasm(v8::TracedGlobal), + Module(Module), + Text(String), +} + +/// A dynamic Worker's code. +#[jsg_struct( + ts_override = "WorkerLoaderWorkerCode { modules: Record; env?: any; globalOutbound?: Fetcher | null; tails?: \ + Fetcher[]; streamingTails?: Fetcher[]; }" +)] +pub struct WorkerCode { + pub compatibilityDate: String, + pub compatibilityFlags: Option>, + pub allowExperimental: Option, + pub limits: Option, + pub mainModule: String, + pub modules: jsg::Dict, + /// Any RPC-serializable object. + pub env: Option>, + /// The loaded Worker's global outbound: inherited from the caller if undefined, blocked if + /// `null`, or, as C++ JSG converts a `kj::Maybe>`, if it isn't a `Fetcher` + /// and the `dont_substitute_null_on_type_error` compatibility flag is off. + pub globalOutbound: jsg::NullOrUndefined>, + pub tails: Option>>, + pub streamingTails: Option>>, +} diff --git a/src/workerd/api/worker-loader-api/ffi.rs b/src/workerd/api/worker-loader-api/ffi.rs new file mode 100644 index 00000000000..180b11c61de --- /dev/null +++ b/src/workerd/api/worker-loader-api/ffi.rs @@ -0,0 +1,58 @@ +// 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++ creates a [`WorkerLoader`](crate::WorkerLoader). + +#![allow( + unsafe_code, + reason = "the cxx bridge expands to unsafe FFI glue, and worker_loader_new() takes C++'s raw \ + isolate" +)] + +use jsg::ToJS; +use jsg::v8; + +#[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 MaybeLocal = jsg::v8::ffi::MaybeLocal; + } + + #[namespace = "workerd"] + unsafe extern "C++" { + include!("workerd/io/compatibility-date.h"); + + type CompatibilityDateValidation = worker_loader_interop::CompatibilityDateValidation; + } + + extern "Rust" { + /// A new `WorkerLoader` on the loader channel `channel`. + unsafe fn worker_loader_new( + isolate: *mut Isolate, + channel: u32, + date_validation: CompatibilityDateValidation, + ) -> MaybeLocal; + } +} + +/// # Safety +/// C++ calls this with the isolate locked, a context entered and a `HandleScope` open. +unsafe fn worker_loader_new( + isolate: *mut bridge::Isolate, + channel: u32, + date_validation: bridge::CompatibilityDateValidation, +) -> bridge::MaybeLocal { + // SAFETY: forwarded from the caller. + unsafe { + v8::run_ffi_callback(isolate, |lock| { + let loader = jsg::Rc::new(lock, crate::WorkerLoader::new(channel, date_validation)); + loader.to_js(lock) + }) + } +} diff --git a/src/workerd/api/worker-loader-api/lib.rs b/src/workerd/api/worker-loader-api/lib.rs new file mode 100644 index 00000000000..56f78b207ca --- /dev/null +++ b/src/workerd/api/worker-loader-api/lib.rs @@ -0,0 +1,500 @@ +// 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 Worker Loader binding in Rust: `WorkerLoader`, which loads dynamic Workers, and +//! `WorkerStub`, a loaded Worker's entrypoints. It does what `api/worker-loader.c++` does, and +//! C++ creates it for a Worker Loader binding when the `RUST_WORKER_LOADER` autogate is on. +//! +//! The checks are plain Rust in [`validate`]; `api/worker-loader-interop` builds the C++ +//! `DynamicWorkerSource`, compiles its compatibility flags and calls +//! `IoChannelFactory::loadIsolate()`. + +mod code; +mod dicts; +mod ffi; +pub mod validate; + +use channel_interop::DurableObjectClass; +use channel_interop::Fetcher; +pub use dicts::EntrypointOptions; +pub use dicts::Module; +pub use dicts::ModuleContent; +pub use dicts::ResourceLimits; +pub use dicts::WorkerCode; +use frankenvalue::Frankenvalue; +use io_context::IoContext; +use jsg::FromJS; +use jsg::PromiseValue; +use jsg::v8; +use jsg_macros::jsg_method; +use jsg_macros::jsg_resource; +use kj_rs::KjOwn; +use worker_loader_interop::CompatibilityDateValidation; +use worker_loader_interop::Limits; +use worker_loader_interop::SourceBuilder; +use worker_loader_interop::WorkerStubHandle; + +use crate::code::Bytes; +use crate::code::Wasm; +use crate::validate::ErrorKind; +use crate::validate::ModuleKind; +use crate::validate::ValidationError; + +fn limits_to_ffi(limits: Option<&ResourceLimits>) -> Limits { + Limits { + present: limits.is_some(), + has_cpu_ms: limits.is_some_and(|l| l.cpuMs.is_some()), + cpu_ms: limits.and_then(|l| l.cpuMs).unwrap_or_default(), + has_sub_requests: limits.is_some_and(|l| l.subRequests.is_some()), + sub_requests: limits.and_then(|l| l.subRequests).unwrap_or_default(), + } +} + +/// What a `WorkerLoader` is: its loader channel and the compatibility dates it accepts. It is +/// also what a startup snapshot keeps of it. +#[derive(Clone, Copy, Debug)] +pub struct LoaderState { + channel: u32, + date_validation: CompatibilityDateValidation, +} + +// Plain data. +jsg::jsg_traced_unchecked!(LoaderState); + +/// `env.LOADER`: loads dynamic Workers on a loader channel. +#[jsg_resource(name = "WorkerLoader", ts_root)] +pub struct WorkerLoader { + state: LoaderState, +} + +impl WorkerLoader { + #[must_use] + pub fn new(channel: u32, date_validation: CompatibilityDateValidation) -> Self { + Self { + state: LoaderState { + channel, + date_validation, + }, + } + } +} + +#[jsg_resource] +impl WorkerLoader { + /// `get(name, getCode)`: the Worker named `name`, loaded with the code `getCode()` returns + /// or resolves to when it needs loading, which may be more than once. An unnamed Worker is + /// never shared. + #[jsg_method] + pub fn get<'s>( + &self, + lock: &mut jsg::Lock<'s>, + name: jsg::Nullable, + get_code: CodeFunction<'s>, + ) -> jsg::Result> { + let io_context = IoContext::current(lock)?; + let name = match name { + jsg::Nullable::Some(name) => Some(name), + jsg::Nullable::Null => None, + }; + let callback = code_callback(lock, &io_context, self.state, get_code.0)?; + let handle = worker_loader_interop::get( + lock, + &io_context, + self.state.channel, + name.as_deref(), + callback, + )?; + Ok(jsg::Rc::new(lock, WorkerStub::new(handle))) + } + + /// `load(code)`: a new Worker of `code`, as `get(null, () => code)`. + #[jsg_method] + pub fn load<'s>( + &self, + lock: &mut jsg::Lock<'s>, + code: WorkerCode, + ) -> jsg::Result> { + let io_context = IoContext::current(lock)?; + let source = to_source(lock, &io_context, self.state, code)?; + let handle = worker_loader_interop::load(lock, &io_context, self.state.channel, source)?; + Ok(jsg::Rc::new(lock, WorkerStub::new(handle))) + } +} + +impl jsg::SnapshotTransfer for WorkerLoader { + type Snapshot = LoaderState; + + fn snapshot(&self) -> LoaderState { + self.state + } + + fn restore(state: &LoaderState) -> Self { + Self { state: *state } + } +} + +/// The `WorkerStubChannel` a `WorkerStub` holds. +struct StubChannel(KjOwn); + +// It holds a C++ channel, which refers to nothing in the V8 heap. +jsg::jsg_traced_unchecked!(StubChannel); + +/// A loaded Worker: not one entrypoint but the whole Worker, whose entrypoints the caller picks, +/// with any props. +#[jsg_resource( + name = "WorkerStub", + ts_override = "{ getEntrypoint(name?: \ + string, options?: WorkerStubEntrypointOptions): Fetcher; \ + getDurableObjectClass(name?: \ + string, options?: WorkerStubEntrypointOptions): DurableObjectClass; }" +)] +pub struct WorkerStub { + channel: StubChannel, +} + +impl WorkerStub { + fn new(handle: KjOwn) -> Self { + Self { + channel: StubChannel(handle), + } + } +} + +#[jsg_resource] +impl WorkerStub { + /// `getEntrypoint(name?, options?)`: a `Fetcher` for the entrypoint `name`, the default one + /// if it is absent, `null` or `"default"`. + #[jsg_method] + pub fn get_entrypoint<'s>( + &self, + lock: &mut jsg::Lock<'s>, + name: Option>, + options: Option, + ) -> jsg::Result> { + let (props, limits) = entrypoint_options(lock, options)?; + let name = validate::entrypoint_name(nullable_name(name)); + let io_context = IoContext::current(lock)?; + self.channel + .0 + .entrypoint(lock, &io_context, name.as_deref(), props, &limits) + } + + /// `getDurableObjectClass(name?, options?)`: a `DurableObjectClass` for the class `name`, as + /// for `getEntrypoint()`. + #[jsg_method] + pub fn get_durable_object_class<'s>( + &self, + lock: &mut jsg::Lock<'s>, + name: Option>, + options: Option, + ) -> jsg::Result> { + let (props, limits) = entrypoint_options(lock, options)?; + let name = validate::entrypoint_name(nullable_name(name)); + let io_context = IoContext::current(lock)?; + self.channel + .0 + .actor_class(lock, &io_context, name.as_deref(), props, &limits) + } +} + +fn nullable_name(name: Option>) -> Option { + match name { + Some(jsg::Nullable::Some(name)) => Some(name), + _ => None, + } +} + +/// The props, as a `Frankenvalue`, and the limits of entrypoint options. +fn entrypoint_options( + lock: &mut jsg::Lock<'_>, + options: Option, +) -> jsg::Result<(KjOwn, Limits)> { + let Some(options) = options else { + return Ok((Frankenvalue::empty(), limits_to_ffi(None))); + }; + let props = match &options.props { + Some(props) => { + let props = props.as_local(lock); + Frankenvalue::from_js(lock, props.into())? + } + None => Frankenvalue::empty(), + }; + Ok((props, limits_to_ffi(options.limits.as_ref()))) +} + +/// `get()`'s `getCode`: a function, which C++ declares as a `jsg::Function`, under the name C++ +/// JSG gives that type in its errors. +pub struct CodeFunction<'s>(v8::Local<'s, v8::Function>); + +impl jsg::TypeInfo for CodeFunction<'_> { + fn describe(cx: &mut jsg::rtti::Context) -> jsg::rtti::Type { + ::describe(cx) + } +} + +impl<'s> FromJS<'s> for CodeFunction<'s> { + type ResultType = Self; + + // Checking for a function runs no script. + const OBJECT_CONVERSION_MAY_RUN_SCRIPT: bool = false; + + fn type_name() -> String { + "function".to_owned() + } + + fn from_js(lock: &mut jsg::Lock<'s>, value: v8::Local<'s, v8::Value>) -> jsg::Result { + Self::try_from_js(lock, value)?.ok_or_else(|| { + jsg::Error::new_type_error(format!("Expected function but got {}", value.type_of(lock))) + }) + } + + fn try_from_js( + _lock: &mut jsg::Lock<'s>, + value: v8::Local<'s, v8::Value>, + ) -> jsg::Result> { + Ok(v8::Local::::try_from(value).ok().map(Self)) + } +} + +/// The callback that `get()` hands to C++, which calls `get_code` in `io_context` each time the +/// Worker needs loading, and makes the Worker's source in the same `IoContext`. +/// +/// `get_code` is called and what it returns converted as C++ JSG calls a +/// `jsg::Function()>`: with the global object as `this`, and with the +/// result converted to a `jsg::Promise`, so a promise's value is converted in a +/// reaction of its own, before the one that makes the source, and anything else at once. +/// +/// The callback holds the `IoContext` weakly, as C++ does: the `WorkerStub` and the stubs it +/// vends hold it until they are collected, and a strong one would keep the request open, which +/// blocks Durable Object hibernation. +fn code_callback<'s>( + lock: &mut jsg::Lock<'s>, + io_context: &IoContext<'s>, + state: LoaderState, + get_code: v8::Local<'s, v8::Function>, +) -> jsg::Result { + let get_code = get_code.to_global(lock); + let callback = io_context.make_reentry_callback_weak(move |lock, context| { + let this = lock.global_object().into(); + let code = get_code.as_local(lock).call(lock, Some(this), &[])?; + let Some(code) = jsg::Promise::::try_from_js(lock, code)? else { + return Err(jsg::Error::new_incorrect_type( + jsg::TypeErrorContext::CallbackReturn, + &jsg::Promise::::type_name(), + )); + }; + // `getCode()` may resolve its promise from another request: the source is made only in + // this `IoContext`, as C++ `awaitJs(js, promise, func)` ensures. The typed promise has + // already converted its value to `WorkerCode` in a reaction of its own, as in C++, so + // this reaction only takes it. + context.await_js_local(lock, code.into_raw_promise(), move |lock, context, raw| { + let code = ::from_raw(lock, raw)?; + to_source(lock, context, state, code) + }) + })?; + Ok(worker_loader_interop::CodeCallback(callback)) +} + +fn js_error(err: ValidationError) -> jsg::Error { + match err.kind { + ErrorKind::Error => jsg::Error::new_error(err.message), + ErrorKind::TypeError => jsg::Error::new_type_error(err.message), + } +} + +/// The source of the Worker that `code` describes, checked as C++ `toDynamicWorkerSource()` +/// checks it, in the same order. +fn to_source<'s>( + lock: &mut jsg::Lock<'s>, + io_context: &IoContext<'s>, + state: LoaderState, + code: WorkerCode, +) -> jsg::Result> { + let WorkerCode { + compatibilityDate: compat_date, + compatibilityFlags: compat_flags, + allowExperimental: allow_experimental, + limits, + mainModule: main_module, + modules, + env, + globalOutbound: global_outbound, + tails, + streamingTails: streaming_tails, + } = code; + let mut builder = SourceBuilder::new(&main_module); + + validate::require_modules(modules.len()).map_err(js_error)?; + let mut kinds: Vec<(String, ModuleKind, usize)> = Vec::with_capacity(modules.len()); + for (name, content) in modules { + let (kind, size) = add_module(lock, builder.pin_mut(), &name, &main_module, content)?; + kinds.push((name, kind, size)); + } + validate::check_modules( + &main_module, + kinds + .iter() + .map(|(name, kind, size)| (name.as_str(), *kind, *size)), + ) + .map_err(js_error)?; + + let flags = validate::python_flags(&main_module, compat_flags); + let allow_experimental = allow_experimental.unwrap_or(false); + let caller_experimental = lock.feature_flags().get_workerd_experimental(); + validate::check_allow_experimental(allow_experimental, caller_experimental) + .map_err(js_error)?; + builder.pin_mut().compile_compat_flags( + lock, + &compat_date, + flags.as_deref().unwrap_or_default(), + allow_experimental, + state.date_validation, + )?; + + if let Some(env) = env { + let env = env.as_local(lock); + let env = Frankenvalue::from_js(lock, env.into())?; + validate::check_env_size(env.estimate_size()).map_err(js_error)?; + builder.pin_mut().set_env(env); + } + + match global_outbound { + jsg::NullOrUndefined::Undefined => builder + .pin_mut() + .inherit_global_outbound(lock, io_context)?, + jsg::NullOrUndefined::Null => {} + jsg::NullOrUndefined::Some(fetcher) => { + let channel = fetcher + .get(lock) + .subrequest_channel(lock, io_context)? + .require_allows_transfer(lock)?; + builder.pin_mut().set_global_outbound(channel); + } + } + + for tail in tails.unwrap_or_default() { + let channel = tail + .get(lock) + .subrequest_channel(lock, io_context)? + .require_allows_transfer(lock)?; + builder.pin_mut().add_tail(channel); + } + + if let Some(streaming_tails) = streaming_tails { + validate::check_streaming_tails(allow_experimental).map_err(js_error)?; + for tail in streaming_tails { + let channel = tail + .get(lock) + .subrequest_channel(lock, io_context)? + .require_allows_transfer(lock)?; + builder.pin_mut().add_streaming_tail(channel); + } + } + + builder + .pin_mut() + .set_limits(&limits_to_ffi(limits.as_ref())); + Ok(builder) +} + +/// Adds the module `name` to `builder`, and returns its kind and the size of its body. +fn add_module( + lock: &mut jsg::Lock<'_>, + builder: std::pin::Pin<&mut SourceBuilder>, + name: &str, + main_module: &str, + content: ModuleContent, +) -> jsg::Result<(ModuleKind, usize)> { + match content { + ModuleContent::Text(text) => { + let kind = validate::classify_string_module(name, main_module).map_err(js_error)?; + let size = text.len(); + builder.add_text(to_ffi_kind(kind), name, text)?; + Ok((kind, size)) + } + ModuleContent::Wasm(module) => add_wasm(lock, builder, name, Wasm::Module(module)), + ModuleContent::Module(module) => { + let count = [ + module.js.is_some(), + module.cjs.is_some(), + module.text.is_some(), + module.data.is_some(), + module.json.is_some(), + module.py.is_some(), + module.wasm.is_some(), + ] + .into_iter() + .filter(|&set| set) + .count(); + validate::require_exactly_one_field(name, count).map_err(js_error)?; + let Module { + js, + cjs, + text, + data, + json, + py, + wasm, + } = module; + let (kind, body) = if let Some(js) = js { + (ModuleKind::Es, js) + } else if let Some(cjs) = cjs { + (ModuleKind::CommonJs, cjs) + } else if let Some(text) = text { + (ModuleKind::Text, text) + } else if let Some(py) = py { + (ModuleKind::Python, py) + } else if let Some(json) = json { + let json = json.as_local(lock); + (ModuleKind::Json, jsg::json::stringify(lock, json)?) + } else if let Some(Bytes(bytes)) = data { + let size = bytes.len(); + builder.add_bytes(to_ffi_kind(ModuleKind::Data), name, bytes)?; + return Ok((ModuleKind::Data, size)); + } else if let Some(wasm) = wasm { + return add_wasm(lock, builder, name, wasm); + } else { + unreachable!("exactly one field is set") + }; + let size = body.len(); + builder.add_text(to_ffi_kind(kind), name, body)?; + Ok((kind, size)) + } + } +} + +fn add_wasm( + lock: &mut jsg::Lock<'_>, + builder: std::pin::Pin<&mut SourceBuilder>, + name: &str, + wasm: Wasm, +) -> jsg::Result<(ModuleKind, usize)> { + match wasm { + Wasm::Bytes(bytes) => { + let size = bytes.len(); + builder.add_bytes(to_ffi_kind(ModuleKind::Wasm), name, bytes)?; + Ok((ModuleKind::Wasm, size)) + } + // No copy: the wire bytes are owned by the compiled module, not the V8 heap. + Wasm::Module(module) => { + let module = module.as_local(lock).compiled_module(); + let size = module.wire_bytes().len(); + builder.add_compiled_wasm(lock, name, module)?; + Ok((ModuleKind::Wasm, size)) + } + } +} + +fn to_ffi_kind(kind: ModuleKind) -> worker_loader_interop::ModuleKind { + use worker_loader_interop::ModuleKind as Ffi; + match kind { + ModuleKind::Es => Ffi::Es, + ModuleKind::CommonJs => Ffi::CommonJs, + ModuleKind::Text => Ffi::Text, + ModuleKind::Data => Ffi::Data, + ModuleKind::Json => Ffi::Json, + ModuleKind::Python => Ffi::Python, + ModuleKind::Wasm => Ffi::Wasm, + } +} diff --git a/src/workerd/api/worker-loader-api/validate-test.rs b/src/workerd/api/worker-loader-api/validate-test.rs new file mode 100644 index 00000000000..714d3d7fc70 --- /dev/null +++ b/src/workerd/api/worker-loader-api/validate-test.rs @@ -0,0 +1,186 @@ +// 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 super::*; + +#[expect( + clippy::unnecessary_wraps, + reason = "`python_flags` takes and returns an `Option`" +)] +fn flags(names: &[&str]) -> Option> { + Some(names.iter().map(|&n| n.to_owned()).collect()) +} + +#[test] +fn string_modules_classify_by_name() { + assert_eq!(classify_string_module("a.js", "a.js"), Ok(ModuleKind::Es)); + assert_eq!( + classify_string_module("a.py", "a.js"), + Ok(ModuleKind::Python) + ); + assert_eq!( + classify_string_module("python_modules/pkg/METADATA", "main.py"), + Ok(ModuleKind::Text) + ); +} + +#[test] +fn python_modules_dir_is_text_only_for_python_workers() { + let err = classify_string_module("python_modules/METADATA", "main.js").unwrap_err(); + assert_eq!(err.kind, ErrorKind::TypeError); + assert_eq!( + err.message, + "Module name must end with '.js' or '.py' (or the content must be an object indicating \ + the type explicitly). Got: python_modules/METADATA" + ); +} + +#[test] +fn typescript_names_suggest_bundling() { + for name in ["a.ts", "a.tsx", "a.jsx"] { + let err = classify_string_module(name, "main.js").unwrap_err(); + assert_eq!( + err.message, + format!( + "Module name must end with '.js' or '.py' (or the content must be an object \ + indicating the type explicitly). Got: {name}. If you're trying to load \ + TypeScript, bundle it first with '@cloudflare/worker-bundler' and pass the \ + generated JavaScript modules." + ) + ); + } +} + +#[test] +fn no_modules_is_a_type_error() { + let err = require_modules(0).unwrap_err(); + assert_eq!(err.kind, ErrorKind::TypeError); + assert_eq!( + err.message, + "Dynamic Worker code must contain at least one module." + ); + assert!(require_modules(1).is_ok()); +} + +#[test] +fn module_objects_need_exactly_one_field() { + assert!(require_exactly_one_field("m", 1).is_ok()); + for count in [0, 2] { + let err = require_exactly_one_field("m", count).unwrap_err(); + assert_eq!(err.kind, ErrorKind::TypeError); + assert_eq!( + err.message, + format!( + "Each module must contain exactly one of 'js', 'cjs', 'text', 'data', 'json', \ + 'py', or 'wasm'. Module 'm' contained {count} properties." + ) + ); + } +} + +#[test] +fn javascript_workers_hold_no_python() { + let err = check_modules( + "main.js", + [ + ("main.js", ModuleKind::Es, 1), + ("x.py", ModuleKind::Python, 1), + ], + ) + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::TypeError); + assert_eq!( + err.message, + "Module \"x.py\" is a Python module, but the main module isn't a Python module." + ); + assert!(check_modules("main.py", [("x.py", ModuleKind::Python, 1)]).is_ok()); +} + +#[test] +fn code_size_limit() { + assert!(check_modules("a.js", [("a.js", ModuleKind::Es, MAX_CODE_SIZE)]).is_ok()); + let err = check_modules( + "a.js", + [ + ("a.js", ModuleKind::Es, MAX_CODE_SIZE), + ("b.wasm", ModuleKind::Wasm, 1), + ], + ) + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::Error); + assert_eq!( + err.message, + "Dynamic Worker code size (67108865 bytes) exceeds the maximum allowed size of 67108864 \ + bytes." + ); +} + +#[test] +fn env_size_limit() { + assert!(check_env_size(MAX_ENV_SIZE).is_ok()); + let err = check_env_size(MAX_ENV_SIZE + 1).unwrap_err(); + assert_eq!( + err.message, + "Dynamic Worker env size (1048577 bytes) exceeds the maximum allowed size of 1048576 \ + bytes." + ); +} + +#[test] +fn python_flags_are_added() { + assert_eq!(python_flags("a.js", None), None); + assert_eq!(python_flags("a.js", flags(&["x"])), flags(&["x"])); + assert_eq!( + python_flags("a.py", None), + flags(&["python_workers", "disable_python_external_sdk"]) + ); + assert_eq!( + python_flags("a.py", flags(&["x", "python_workers"])), + flags(&["x", "python_workers", "disable_python_external_sdk"]) + ); + assert_eq!( + python_flags("a.py", flags(&["enable_python_external_sdk"])), + flags(&["enable_python_external_sdk", "python_workers"]) + ); + assert_eq!( + python_flags( + "a.py", + flags(&["python_workers", "disable_python_external_sdk"]) + ), + flags(&["python_workers", "disable_python_external_sdk"]) + ); +} + +#[test] +fn allow_experimental_needs_experimental_caller() { + assert!(check_allow_experimental(false, false).is_ok()); + assert!(check_allow_experimental(true, true).is_ok()); + let err = check_allow_experimental(true, false).unwrap_err(); + assert_eq!(err.kind, ErrorKind::Error); + assert_eq!( + err.message, + "'allowExperimental' is only allowed when the calling worker has the 'experimental' \ + compat flag set." + ); +} + +#[test] +fn streaming_tails_need_allow_experimental() { + assert!(check_streaming_tails(true).is_ok()); + assert_eq!( + check_streaming_tails(false).unwrap_err().message, + "Streaming tail workers are experimental. You must pass the option 'allowExperimental: \ + true' to the worker loader to use them" + ); +} + +#[test] +fn default_entrypoint_names() { + assert_eq!(entrypoint_name(None), None); + assert_eq!(entrypoint_name(Some("default".to_owned())), None); + assert_eq!( + entrypoint_name(Some("Foo".to_owned())), + Some("Foo".to_owned()) + ); +} diff --git a/src/workerd/api/worker-loader-api/validate.rs b/src/workerd/api/worker-loader-api/validate.rs new file mode 100644 index 00000000000..562629a1c71 --- /dev/null +++ b/src/workerd/api/worker-loader-api/validate.rs @@ -0,0 +1,246 @@ +// 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 checks Worker Loader applies to a dynamic Worker's code, in plain Rust. +//! +//! They are which kind of module a name stands for, the limits on code and `env` size, and the +//! flags that Python Workers need. C++ `compileCompatibilityFlags()` compiles the flags. Each +//! error's message is word for word the one `api/worker-loader.c++` throws. + +#![expect( + clippy::case_sensitive_file_extension_comparisons, + reason = "module names are matched case-sensitively, as `api/worker-loader.c++` matches them" +)] + +/// The largest total size, in bytes, of a dynamic Worker's module bodies: the documented paid +/// Worker uncompressed size limit. +pub const MAX_CODE_SIZE: usize = 64 * 1024 * 1024; + +/// The largest estimated size, in bytes, of a dynamic Worker's serialized `env`: roughly the +/// paid Worker analog of 128 environment variables at 5 KB each. +pub const MAX_ENV_SIZE: usize = 1024 * 1024; + +/// The kind of a module, as C++ `Worker::Script::ModuleContent` distinguishes them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ModuleKind { + Es, + CommonJs, + Text, + Data, + Json, + Python, + Wasm, +} + +/// What JavaScript sees a failed check as. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ErrorKind { + Error, + TypeError, +} + +/// A failed check. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ValidationError { + pub kind: ErrorKind, + pub message: String, +} + +impl ValidationError { + fn error(message: String) -> Self { + Self { + kind: ErrorKind::Error, + message, + } + } + + fn type_error(message: String) -> Self { + Self { + kind: ErrorKind::TypeError, + message, + } + } +} + +pub type Result = std::result::Result; + +/// Whether `main_module` names a Python module, which makes the Worker a Python Worker. +#[must_use] +pub fn is_python_main(main_module: &str) -> bool { + main_module.ends_with(".py") +} + +/// Fails unless the Worker has at least one module. +/// +/// # Errors +/// A `TypeError` for no modules. +pub fn require_modules(count: usize) -> Result<()> { + if count == 0 { + return Err(ValidationError::type_error( + "Dynamic Worker code must contain at least one module.".to_owned(), + )); + } + Ok(()) +} + +/// The kind of a module given as a bare string, by its name: `.py` is Python, `.js` an ES module, +/// and, in a Python Worker, anything under `python_modules/` text. +/// +/// # Errors +/// A `TypeError` for any other name, which suggests bundling for TypeScript and JSX names. +pub fn classify_string_module(name: &str, main_module: &str) -> Result { + if name.ends_with(".py") { + return Ok(ModuleKind::Python); + } + if name.ends_with(".js") { + return Ok(ModuleKind::Es); + } + // Python packages bundled in Workers can have non-code files (METADATA, RECORD, etc), so file + // extensions aren't limited for Python Workers. + if is_python_main(main_module) && name.starts_with("python_modules/") { + return Ok(ModuleKind::Text); + } + let mut message = format!( + "Module name must end with '.js' or '.py' (or the content must be an object indicating \ + the type explicitly). Got: {name}" + ); + if name.ends_with(".ts") || name.ends_with(".tsx") || name.ends_with(".jsx") { + message.push_str( + ". If you're trying to load TypeScript, bundle it first with \ + '@cloudflare/worker-bundler' and pass the generated JavaScript modules.", + ); + } + Err(ValidationError::type_error(message)) +} + +/// Fails unless a module object set exactly one of its fields; `count` is how many it set. +/// +/// # Errors +/// A `TypeError` naming the module and the count. +pub fn require_exactly_one_field(name: &str, count: usize) -> Result<()> { + if count != 1 { + return Err(ValidationError::type_error(format!( + "Each module must contain exactly one of 'js', 'cjs', 'text', 'data', 'json', 'py', \ + or 'wasm'. Module '{name}' contained {count} properties." + ))); + } + Ok(()) +} + +/// Checks the modules once each has its kind and size. +/// +/// A JavaScript Worker may hold no Python module, and the bodies may total at most +/// [`MAX_CODE_SIZE`] bytes. Python Workers may hold any module, since Python packages can contain +/// arbitrary `.js` files. +/// +/// # Errors +/// A `TypeError` for the first Python module of a JavaScript Worker, otherwise an `Error` if the +/// code is too large. +pub fn check_modules<'a>( + main_module: &str, + modules: impl IntoIterator, +) -> Result<()> { + let is_python = is_python_main(main_module); + let mut total: usize = 0; + for (name, kind, size) in modules { + if !is_python && kind == ModuleKind::Python { + return Err(ValidationError::type_error(format!( + "Module \"{name}\" is a Python module, but the main module isn't a Python module." + ))); + } + total = total.saturating_add(size); + } + if total > MAX_CODE_SIZE { + return Err(ValidationError::error(format!( + "Dynamic Worker code size ({total} bytes) exceeds the maximum allowed size of \ + {MAX_CODE_SIZE} bytes." + ))); + } + Ok(()) +} + +/// The compatibility flags of a Worker, with those a Python Worker needs. +/// +/// A Python Worker needs `python_workers` and, unless the caller says otherwise, +/// `disable_python_external_sdk`, since dynamic Workers can't include the SDK yet. Any other +/// Worker's flags are returned as they are. +#[must_use] +pub fn python_flags(main_module: &str, flags: Option>) -> Option> { + if !is_python_main(main_module) { + return flags; + } + let given = flags.as_deref().unwrap_or_default(); + let has = |flag: &str| given.iter().any(|f| f == flag); + let has_python_workers = has("python_workers"); + // TODO: The external SDK is disabled because dynamic Workers have no way to include it. + // Once RM-28738 is implemented this may go away. + let add_sdk_disable = !has("enable_python_external_sdk") && !has("disable_python_external_sdk"); + if has_python_workers && !add_sdk_disable { + return flags; + } + let mut flags = flags.unwrap_or_default(); + if !has_python_workers { + flags.push("python_workers".to_owned()); + } + if add_sdk_disable { + flags.push("disable_python_external_sdk".to_owned()); + } + Some(flags) +} + +/// Fails if the code asks for experimental features but the calling Worker doesn't have the +/// `experimental` compatibility flag. +/// +/// # Errors +/// An `Error`. +pub fn check_allow_experimental(allow_experimental: bool, caller_experimental: bool) -> Result<()> { + if allow_experimental && !caller_experimental { + return Err(ValidationError::error( + "'allowExperimental' is only allowed when the calling worker has the 'experimental' \ + compat flag set." + .to_owned(), + )); + } + Ok(()) +} + +/// Fails if the code names streaming tail Workers without allowing experimental features. +/// +/// # Errors +/// An `Error`. +pub fn check_streaming_tails(allow_experimental: bool) -> Result<()> { + if !allow_experimental { + return Err(ValidationError::error( + "Streaming tail workers are experimental. You must pass the option \ + 'allowExperimental: true' to the worker loader to use them" + .to_owned(), + )); + } + Ok(()) +} + +/// Fails if the estimated size of the serialized `env` is over [`MAX_ENV_SIZE`]. +/// +/// # Errors +/// An `Error`. +pub fn check_env_size(estimate: usize) -> Result<()> { + if estimate > MAX_ENV_SIZE { + return Err(ValidationError::error(format!( + "Dynamic Worker env size ({estimate} bytes) exceeds the maximum allowed size of \ + {MAX_ENV_SIZE} bytes." + ))); + } + Ok(()) +} + +/// The entrypoint a name asks for: `None`, for the default one, if it is absent, `null` or +/// `"default"`. +#[must_use] +pub fn entrypoint_name(name: Option) -> Option { + name.filter(|name| name != "default") +} + +#[cfg(test)] +#[path = "validate-test.rs"] +mod tests; diff --git a/src/workerd/api/worker-loader-interop/BUILD.bazel b/src/workerd/api/worker-loader-interop/BUILD.bazel new file mode 100644 index 00000000000..2a9a220b585 --- /dev/null +++ b/src/workerd/api/worker-loader-interop/BUILD.bazel @@ -0,0 +1,43 @@ +load("//:build/wd_cc_library.bzl", "wd_cc_library") +load("//:build/wd_rust_crate.bzl", "wd_rust_crate") + +# What the Rust Worker Loader (api/worker-loader-api) needs of C++: building a +# DynamicWorkerSource, IoChannelFactory::loadIsolate(), and the WorkerStubChannel it returns. +# ffi.h and ffi.c++ are the shims, C++ API code that lives with the API. +wd_rust_crate( + name = "worker-loader-interop", + srcs = [ + "ffi.rs", + "lib.rs", + ], + cxx_bridge_deps = [ + "//src/rust/jsg", + "//src/rust/jsg-cpp:ffi", + "//src/workerd/api/channel-interop:ffi.rs@cxx", + "//src/workerd/io", + "//src/workerd/io/frankenvalue:ffi.rs@cxx", + ], + cxx_bridge_hdrs = ["ffi.h"], + cxx_bridge_src = "ffi.rs", + link_deps = [":ffi"], + visibility = ["//visibility:public"], + deps = [ + "//src/rust/jsg", + "//src/rust/jsg-cpp", + "//src/workerd/api/channel-interop", + "//src/workerd/io/frankenvalue", + "//src/workerd/io/io-context", + ], +) + +wd_cc_library( + name = "ffi", + srcs = ["ffi.c++"], + hdrs = ["ffi.h"], + deps = [ + ":ffi.rs@cxx", + "//src/rust/jsg-cpp:ffi", + "//src/workerd/io", + "//src/workerd/io/io-context:current-with-id", + ], +) diff --git a/src/workerd/api/worker-loader-interop/ffi.c++ b/src/workerd/api/worker-loader-interop/ffi.c++ new file mode 100644 index 00000000000..320a5e764b0 --- /dev/null +++ b/src/workerd/api/worker-loader-interop/ffi.c++ @@ -0,0 +1,315 @@ +// 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 + +#include "ffi.h" + +#include +#include +#include +#include +#include + +#include + +namespace workerd::api::worker_loader_interop { + +namespace { + +// A view of text that Rust appended a NUL to. +kj::StringPtr textOf(const ::rust::String& text) { + KJ_ASSERT(text.size() > 0 && text.data()[text.size() - 1] == '\0'); + return kj::StringPtr(text.data(), text.size() - 1); +} + +kj::ArrayPtr bytesOf(const ::rust::Vec& bytes) { + return kj::ArrayPtr(bytes.data(), bytes.size()); +} + +kj::Maybe nameOf(bool hasName, ::rust::Str name) { + if (!hasName) return kj::none; + return kj::str(kj::ArrayPtr(name.data(), name.size())); +} + +kj::Maybe limitsOf(const Limits& limits) { + if (!limits.present) return kj::none; + ResourceLimits result; + if (limits.has_cpu_ms) result.cpuMs = limits.cpu_ms; + if (limits.has_sub_requests) result.subRequests = limits.sub_requests; + return kj::mv(result); +} + +} // namespace + +SourceBuilder::SourceBuilder(::rust::String mainModule) + : content(kj::atomicRefcounted()) { + content->mainModule = kj::mv(mainModule); +} + +kj::StringPtr SourceBuilder::keepText(::rust::String text) { + // Each buffer is boxed, so the views stay valid as the vector grows. + return textOf(*content->texts.add(kj::heap(kj::mv(text)))); +} + +kj::ArrayPtr SourceBuilder::keepBytes(::rust::Vec bytes) { + return bytesOf(*content->bytes.add(kj::heap(kj::mv(bytes)))); +} + +void SourceBuilder::addText(uint8_t kind, ::rust::String name, ::rust::String body) { + auto moduleName = keepText(kj::mv(name)); + auto text = keepText(kj::mv(body)); + WorkerSource::ModuleContent moduleContent = [&]() -> WorkerSource::ModuleContent { + switch (static_cast(kind)) { + case ModuleKind::Es: + return WorkerSource::EsModule{.body = text.asArray()}; + case ModuleKind::CommonJs: + return WorkerSource::CommonJsModule{.body = text}; + case ModuleKind::Text: + return WorkerSource::TextModule{.body = text}; + case ModuleKind::Json: + return WorkerSource::JsonModule{.body = text}; + case ModuleKind::Python: + return WorkerSource::PythonModule{.body = text}; + case ModuleKind::Data: + case ModuleKind::Wasm: + break; + } + KJ_FAIL_ASSERT("not a text module kind", kind); + }(); + modules.add(WorkerSource::Module{.name = moduleName, .content = kj::mv(moduleContent)}); +} + +void SourceBuilder::addBytes(uint8_t kind, ::rust::String name, ::rust::Vec body) { + auto moduleName = keepText(kj::mv(name)); + auto bytes = keepBytes(kj::mv(body)); + WorkerSource::ModuleContent moduleContent = [&]() -> WorkerSource::ModuleContent { + switch (static_cast(kind)) { + case ModuleKind::Data: + return WorkerSource::DataModule{.body = bytes}; + case ModuleKind::Wasm: + return WorkerSource::WasmModule{.body = bytes}; + default: + break; + } + KJ_FAIL_ASSERT("not a byte module kind", kind); + }(); + modules.add(WorkerSource::Module{.name = moduleName, .content = kj::mv(moduleContent)}); +} + +void SourceBuilder::addCompiledWasm( + ::rust::String name, kj::Own module, bool esmBuiltins, bool sourceUrl) { + auto moduleName = keepText(kj::mv(name)); + // The wire bytes are owned by the compiled module, which the module content keeps. + auto wireBytes = module->GetWireBytesRef(); + modules.add(WorkerSource::Module{.name = moduleName, + .content = WorkerSource::WasmModule{ + .body = kj::arrayPtr(wireBytes.data(), wireBytes.size()), + .compiledModule = *module, + .compiledWithEsmIntegrationBuiltins = esmBuiltins, + .compiledWithWasmSourceUrlSupport = sourceUrl, + }}); +} + +void SourceBuilder::compileCompatFlags(jsg::Lock& js, + kj::StringPtr compatDate, + kj::ArrayPtr flags, + bool allowExperimental, + CompatibilityDateValidation dateValidation) { + capnp::word scratch[capnp::sizeInWords() + 4]{}; + capnp::MallocMessageBuilder message(scratch); + auto builder = message.getRoot(); + SimpleWorkerErrorReporter errorReporter; + // allowedExperimentalFlags is null on purpose, as in worker-loader.c++: a Worker Loader trusted + // with specific experimental flags doesn't pass that trust on to its dynamic Workers. + compileCompatibilityFlags( + compatDate, flags, builder, errorReporter, allowExperimental, dateValidation, nullptr); + if (!errorReporter.errors.empty()) { + JSG_FAIL_REQUIRE(Error, errorReporter.errors.front()); + } + content->compatFlags = capnp::clone(builder.asReader()); +} + +void SourceBuilder::setLimits(const Limits& limits) { + this->limits = limitsOf(limits); +} + +void SourceBuilder::setEnv(kj::Own env) { + this->env = kj::mv(*env); +} + +void SourceBuilder::setGlobalOutbound(kj::Rc channel) { + globalOutbound = kj::mv(channel); +} + +void SourceBuilder::addTail(kj::Rc channel) { + tails.add(kj::mv(channel)); +} + +void SourceBuilder::addStreamingTail(kj::Rc channel) { + streamingTails.add(kj::mv(channel)); +} + +DynamicWorkerSource SourceBuilder::build() { + KJ_ASSERT(content->compatFlags.get() != nullptr, "compat flags must be set"); + auto mainModule = textOf(content->mainModule); + CompatibilityFlags::Reader compatFlags = *content->compatFlags; + return { + .source = WorkerSource(WorkerSource::ModulesSource{ + .mainModule = mainModule, + .modules = modules.releaseAsArray(), + .isPython = mainModule.endsWith(".py"_kj), + }), + .compatibilityFlags = compatFlags, + .limits = kj::mv(limits), + .env = kj::mv(env), + .globalOutbound = kj::mv(globalOutbound), + .tails = tails.releaseAsArray(), + .streamingTails = streamingTails.releaseAsArray(), + .ownContent = addRefContent(), + .ownContentIsRpcResponse = false, + }; +} + +kj::Own source_builder_new(::rust::String mainModule) { + return kj::heap(kj::mv(mainModule)); +} + +void source_builder_add_text( + SourceBuilder& builder, uint8_t kind, ::rust::String name, ::rust::String body) { + builder.addText(kind, kj::mv(name), kj::mv(body)); +} + +void source_builder_add_bytes( + SourceBuilder& builder, uint8_t kind, ::rust::String name, ::rust::Vec body) { + builder.addBytes(kind, kj::mv(name), kj::mv(body)); +} + +bool source_builder_compile_compat_flags(v8::Isolate* isolate, + SourceBuilder& builder, + ::rust::Str compatDate, + ::rust::Slice flags, + bool allowExperimental, + CompatibilityDateValidation dateValidation) { + return jsg_cpp::callCpp(isolate, [&](jsg::Lock& js) { + auto date = kj::str(kj::ArrayPtr(compatDate.data(), compatDate.size())); + auto ownFlags = KJ_MAP(flag, flags) { + return kj::str(kj::ArrayPtr(flag.data(), flag.size())); + }; + builder.compileCompatFlags(js, date, ownFlags, allowExperimental, dateValidation); + }); +} + +void source_builder_set_limits(SourceBuilder& builder, const Limits& limits) { + builder.setLimits(limits); +} + +void source_builder_set_env(SourceBuilder& builder, kj::Own env) { + builder.setEnv(kj::mv(env)); +} + +void source_builder_set_global_outbound(SourceBuilder& builder, kj::Rc channel) { + builder.setGlobalOutbound(kj::mv(channel)); +} + +void source_builder_add_tail(SourceBuilder& builder, kj::Rc channel) { + builder.addTail(kj::mv(channel)); +} + +void source_builder_add_streaming_tail(SourceBuilder& builder, kj::Rc channel) { + builder.addStreamingTail(kj::mv(channel)); +} + +bool source_builder_add_compiled_wasm(v8::Isolate* isolate, + SourceBuilder& builder, + ::rust::String name, + kj::Own module) { + return jsg_cpp::callCpp(isolate, [&](jsg::Lock& js) { + builder.addCompiledWasm(kj::mv(name), kj::mv(module), js.isWasmEsmIntegrationBuiltinsEnabled(), + js.isWasmSourceUrlSupportEnabled()); + }); +} + +bool source_builder_inherit_global_outbound( + v8::Isolate* isolate, SourceBuilder& builder, uint64_t ioContextId) { + return jsg_cpp::callCpp(isolate, [&](jsg::Lock&) { + auto& ioctx = io_context::currentWithId(ioContextId); + // Transferability needn't be checked: what may be the parent's global outbound may be the + // child's. + builder.setGlobalOutbound( + ioctx.getIoChannelFactory().getSubrequestChannel(IoContext::NULL_CLIENT_CHANNEL)); + }); +} + +bool worker_loader_load(v8::Isolate* isolate, + uint64_t ioContextId, + uint32_t channel, + kj::Own builder, + kj::Maybe>& result) { + return jsg_cpp::callCpp(isolate, [&](jsg::Lock&) { + auto& ioctx = io_context::currentWithId(ioContextId); + auto content = builder->addRefContent(); + auto source = builder->build(); + // The callback may be called any number of times, even without an ID: the runtime can evict + // the isolate while a stub exists and no request is active on it, then recreate it on the + // next request. It may destroy the content on another thread, which SourceContent allows. + auto isolateChannel = ioctx.getIoChannelFactory().loadIsolate( + channel, kj::none, [source = kj::mv(source), content = kj::mv(content)]() mutable { + return source.clone(kj::atomicAddRef(*content)); + }); + result = kj::heap(ioctx.addObject(kj::mv(isolateChannel))); + }); +} + +bool worker_loader_get(v8::Isolate* isolate, + uint64_t ioContextId, + uint32_t channel, + bool hasName, + ::rust::Str name, + ::rust::Box callback, + kj::Maybe>& result) { + return jsg_cpp::callCpp(isolate, [&](jsg::Lock&) { + auto& ioctx = io_context::currentWithId(ioContextId); + auto isolateChannel = ioctx.getIoChannelFactory().loadIsolate(channel, nameOf(hasName, name), + [callback = kj::mv(callback)]() mutable -> kj::Promise { + return code_callback_call(*callback).then( + [](kj::Own builder) { return builder->build(); }); + }); + result = kj::heap(ioctx.addObject(kj::mv(isolateChannel))); + }); +} + +bool worker_stub_get_entrypoint(v8::Isolate* isolate, + const WorkerStubHandle& stub, + uint64_t ioContextId, + bool hasName, + ::rust::Str name, + kj::Own props, + const Limits& limits, + kj::Maybe>& result) { + return jsg_cpp::callCppForRef(isolate, result, [&](jsg::Lock& js) -> jsg::Ref { + auto& ioctx = io_context::currentWithId(ioContextId); + auto& channel = *const_cast(stub).channel; + auto subreqChannel = + channel.getEntrypoint(nameOf(hasName, name), kj::mv(*props), limitsOf(limits)); + return js.alloc(ioctx.addObject(kj::mv(subreqChannel))); + }); +} + +bool worker_stub_get_actor_class(v8::Isolate* isolate, + const WorkerStubHandle& stub, + uint64_t ioContextId, + bool hasName, + ::rust::Str name, + kj::Own props, + const Limits& limits, + kj::Maybe>& result) { + return jsg_cpp::callCppForRef( + isolate, result, [&](jsg::Lock& js) -> jsg::Ref { + auto& ioctx = io_context::currentWithId(ioContextId); + auto& channel = *const_cast(stub).channel; + return js.alloc(ioctx.addObject( + channel.getActorClass(nameOf(hasName, name), kj::mv(*props), limitsOf(limits)))); + }); +} + +} // namespace workerd::api::worker_loader_interop diff --git a/src/workerd/api/worker-loader-interop/ffi.h b/src/workerd/api/worker-loader-interop/ffi.h new file mode 100644 index 00000000000..fb0b23b81e5 --- /dev/null +++ b/src/workerd/api/worker-loader-interop/ffi.h @@ -0,0 +1,181 @@ +// 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 + +#pragma once + +// The shims through which the Rust Worker Loader (api/worker-loader-api) builds a +// `DynamicWorkerSource`, loads it with `IoChannelFactory::loadIsolate()`, and gets entrypoints +// from the `WorkerStubChannel` it returns (ffi.rs). They are C++ API code, which uses C++ JSG as +// api/worker-loader.c++ does; see src/rust/jsg/README.md, "Safety rules", rule 3. +// +// Every function that takes an isolate takes the isolate of the caller's lock, locked by this +// thread with a context entered and a HandleScope open. It runs its C++ in jsg_cpp::callCpp() and +// returns false, with an exception pending, if it threw. A shim that takes an `ioContextId` finds +// the IoContext with io_context::currentWithId(), so it fails unless that IoContext is current. + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +namespace workerd::api::worker_loader_interop { + +namespace jsg_cpp = ::workerd::rust::jsg_cpp; + +using SubrequestChannel = IoChannelFactory::SubrequestChannel; +using CompiledWasmModule = v8::CompiledWasmModule; + +// Defined by the bridge (ffi.rs). +struct CodeCallback; +struct Limits; + +// What a source's pointers point into: buffers that Rust made and C++ now owns, each a boxed +// `::rust::String` or `::rust::Vec`, so that neither the buffer nor the object holding it moves +// as the vectors grow. Text ends in a NUL that Rust appended, which is not part of the text, so +// that it can be viewed as a `kj::StringPtr`. +// +// A loaded Worker may be evicted and reloaded from the same source any number of times, and the +// content may be destroyed on another thread, so its refcount is atomic. Destroying a +// `::rust::String` or `::rust::Vec` frees Rust memory, which any thread may do. +struct SourceContent final: public kj::AtomicRefcounted { + ::rust::String mainModule; + kj::Vector> texts; + kj::Vector>> bytes; + kj::Own compatFlags; +}; + +// A `DynamicWorkerSource` under construction, built from what Rust gives it. +class SourceBuilder { + public: + SourceBuilder(::rust::String mainModule); + + // `kind` is a `ModuleKind` of the bridge: a module whose body is text. + void addText(uint8_t kind, ::rust::String name, ::rust::String body); + // `kind` is `ModuleKind::Data` or `ModuleKind::Wasm`: a module whose body is bytes. + void addBytes(uint8_t kind, ::rust::String name, ::rust::Vec body); + // A WASM module that shares already-compiled code. `esmBuiltins` and `sourceUrl` are the + // isolate's settings it was compiled with. + void addCompiledWasm( + ::rust::String name, kj::Own module, bool esmBuiltins, bool sourceUrl); + + // Compiles the code's compatibility date and flags with compileCompatibilityFlags(), as + // worker-loader.c++ does, so both loaders get the same compiler. Throws the first error, as + // worker-loader.c++ does. + void compileCompatFlags(jsg::Lock& js, + kj::StringPtr compatDate, + kj::ArrayPtr flags, + bool allowExperimental, + CompatibilityDateValidation dateValidation); + void setLimits(const Limits& limits); + void setEnv(kj::Own env); + void setGlobalOutbound(kj::Rc channel); + void addTail(kj::Rc channel); + void addStreamingTail(kj::Rc channel); + + // Builds the source. `ownContent` holds a reference to the content. + DynamicWorkerSource build(); + + // A new reference to the content, for each clone of the source that `build()` returns. + kj::Own addRefContent() { + return kj::atomicAddRef(*content); + } + + private: + // Moves `text` (`bytes`) into the content, and returns a view of it. + kj::StringPtr keepText(::rust::String text); + kj::ArrayPtr keepBytes(::rust::Vec bytes); + + kj::Own content; + kj::Vector modules; + kj::Maybe limits; + Frankenvalue env; + kj::Maybe> globalOutbound; + kj::Vector> tails; + kj::Vector> streamingTails; +}; + +// A `WorkerStub`'s channel, owned by the IoContext that loaded it, as C++ `WorkerStub` holds it. +// The `IoOwn` may be destroyed on any thread: if it is not the IoContext's, the deletion is queued +// for the IoContext. It is dereferenced only by the shims below, which check that its IoContext is +// current. +struct WorkerStubHandle { + IoOwn channel; +}; + +kj::Own source_builder_new(::rust::String mainModule); +void source_builder_add_text( + SourceBuilder& builder, uint8_t kind, ::rust::String name, ::rust::String body); +void source_builder_add_bytes( + SourceBuilder& builder, uint8_t kind, ::rust::String name, ::rust::Vec body); +void source_builder_set_limits(SourceBuilder& builder, const Limits& limits); +void source_builder_set_env(SourceBuilder& builder, kj::Own env); +void source_builder_set_global_outbound(SourceBuilder& builder, kj::Rc channel); +void source_builder_add_tail(SourceBuilder& builder, kj::Rc channel); +void source_builder_add_streaming_tail(SourceBuilder& builder, kj::Rc channel); + +// builder.addCompiledWasm(), with the settings of the caller's isolate. +bool source_builder_add_compiled_wasm(v8::Isolate* isolate, + SourceBuilder& builder, + ::rust::String name, + kj::Own module); + +// builder.compileCompatFlags(). +bool source_builder_compile_compat_flags(v8::Isolate* isolate, + SourceBuilder& builder, + ::rust::Str compatDate, + ::rust::Slice flags, + bool allowExperimental, + CompatibilityDateValidation dateValidation); + +// Has the loaded Worker inherit the calling Worker's global outbound: +// getSubrequestChannel(IoContext::NULL_CLIENT_CHANNEL). +bool source_builder_inherit_global_outbound( + v8::Isolate* isolate, SourceBuilder& builder, uint64_t ioContextId); + +// WorkerLoader.load(): loadIsolate(channel, kj::none, ...) with a callback that clones the source. +bool worker_loader_load(v8::Isolate* isolate, + uint64_t ioContextId, + uint32_t channel, + kj::Own builder, + kj::Maybe>& result); + +// WorkerLoader.get(): loadIsolate(channel, name, ...) with a callback that calls `callback` for +// each source. +bool worker_loader_get(v8::Isolate* isolate, + uint64_t ioContextId, + uint32_t channel, + bool hasName, + ::rust::Str name, + ::rust::Box callback, + kj::Maybe>& result); + +// js.alloc(ioctx.addObject(stub.channel->getEntrypoint(name, props, limits))). +bool worker_stub_get_entrypoint(v8::Isolate* isolate, + const WorkerStubHandle& stub, + uint64_t ioContextId, + bool hasName, + ::rust::Str name, + kj::Own props, + const Limits& limits, + kj::Maybe>& result); + +// The same with getActorClass(), for a DurableObjectClass. +bool worker_stub_get_actor_class(v8::Isolate* isolate, + const WorkerStubHandle& stub, + uint64_t ioContextId, + bool hasName, + ::rust::Str name, + kj::Own props, + const Limits& limits, + kj::Maybe>& result); + +} // namespace workerd::api::worker_loader_interop diff --git a/src/workerd/api/worker-loader-interop/ffi.rs b/src/workerd/api/worker-loader-interop/ffi.rs new file mode 100644 index 00000000000..01585513388 --- /dev/null +++ b/src/workerd/api/worker-loader-interop/ffi.rs @@ -0,0 +1,486 @@ +// 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 + +#![allow( + unsafe_code, + reason = "the cxx bridge expands to unsafe FFI glue, the shims take C++'s raw isolate, and the \ + stub handle is sent between threads; see the SAFETY comments" +)] + +//! The bridge to `ffi.h`, and the Rust API over it. + +use std::future::Future; + +use channel_interop::DurableObjectClass; +use channel_interop::Fetcher; +use channel_interop::SubrequestChannel; +use frankenvalue::Frankenvalue; +use io_context::IoContext; +use io_context::ReentryCallback; +use jsg::v8; +use kj_rs::KjMaybe; +use kj_rs::KjOwn; +use kj_rs::KjRc; + +// Every function that takes an isolate takes the isolate of the caller's lock, locked by this +// thread with a context entered and a `HandleScope` open. +#[cxx::bridge(namespace = "workerd::api::worker_loader_interop")] +pub mod bridge { + /// The kind of a module, as C++ `WorkerSource::ModuleContent` distinguishes them. + #[repr(u8)] + enum ModuleKind { + Es, + CommonJs, + Text, + Data, + Json, + Python, + Wasm, + } + + /// C++ `CompatibilityDateValidation` (`workerd/io/compatibility-date.h`): the compatibility + /// dates a Worker Loader accepts. + #[namespace = "workerd"] + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + #[repr(i32)] + enum CompatibilityDateValidation { + CODE_VERSION, + CURRENT_DATE_FOR_CLOUDFLARE, + FUTURE_FOR_TEST, + } + + #[namespace = "workerd"] + unsafe extern "C++" { + include!("workerd/io/compatibility-date.h"); + type CompatibilityDateValidation; + } + + /// C++ `kj::Maybe`: `present` says whether there are limits at all. + struct Limits { + present: bool, + has_cpu_ms: bool, + cpu_ms: u32, + has_sub_requests: bool, + sub_requests: u32, + } + + #[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 CompiledWasmModule = jsg::v8::ffi::CompiledWasmModule; + } + + #[namespace = "workerd::rust::jsg_cpp"] + unsafe extern "C++" { + include!("workerd/rust/jsg-cpp/jsg-cpp.h"); + type CppRef = jsg_cpp::CppRef; + } + + #[namespace = "workerd"] + unsafe extern "C++" { + include!("workerd/io/frankenvalue/ffi.h"); + type Frankenvalue = frankenvalue::Frankenvalue; + } + + #[namespace = "workerd::api::channel_interop"] + unsafe extern "C++" { + include!("workerd/api/channel-interop/ffi.h"); + type SubrequestChannel = channel_interop::SubrequestChannel; + } + + unsafe extern "C++" { + include!("workerd/api/worker-loader-interop/ffi.h"); + + /// A C++ `DynamicWorkerSource` under construction. + type SourceBuilder; + + /// A `WorkerStub`'s C++ `IoOwn`. + type WorkerStubHandle; + + fn source_builder_new(main_module: String) -> KjOwn; + fn source_builder_add_text( + builder: Pin<&mut SourceBuilder>, + kind: u8, + name: String, + body: String, + ) -> Result<()>; + fn source_builder_add_bytes( + builder: Pin<&mut SourceBuilder>, + kind: u8, + name: String, + body: Vec, + ) -> Result<()>; + fn source_builder_set_limits(builder: Pin<&mut SourceBuilder>, limits: &Limits); + fn source_builder_set_env(builder: Pin<&mut SourceBuilder>, env: KjOwn); + fn source_builder_set_global_outbound( + builder: Pin<&mut SourceBuilder>, + channel: KjRc, + ); + fn source_builder_add_tail( + builder: Pin<&mut SourceBuilder>, + channel: KjRc, + ); + fn source_builder_add_streaming_tail( + builder: Pin<&mut SourceBuilder>, + channel: KjRc, + ); + + // Per-method shims. Each returns false with an exception pending if the C++ threw. + unsafe fn source_builder_add_compiled_wasm( + isolate: *mut Isolate, + builder: Pin<&mut SourceBuilder>, + name: String, + module: KjOwn, + ) -> bool; + unsafe fn source_builder_compile_compat_flags( + isolate: *mut Isolate, + builder: Pin<&mut SourceBuilder>, + compat_date: &str, + flags: &[String], + allow_experimental: bool, + date_validation: CompatibilityDateValidation, + ) -> bool; + unsafe fn source_builder_inherit_global_outbound( + isolate: *mut Isolate, + builder: Pin<&mut SourceBuilder>, + io_context_id: u64, + ) -> bool; + unsafe fn worker_loader_load( + isolate: *mut Isolate, + io_context_id: u64, + channel: u32, + builder: KjOwn, + result: &mut KjMaybe>, + ) -> bool; + unsafe fn worker_loader_get( + isolate: *mut Isolate, + io_context_id: u64, + channel: u32, + has_name: bool, + name: &str, + callback: Box, + result: &mut KjMaybe>, + ) -> bool; + #[expect( + clippy::too_many_arguments, + reason = "an out-parameter shim, as C++ declares it" + )] + unsafe fn worker_stub_get_entrypoint( + isolate: *mut Isolate, + stub: &WorkerStubHandle, + io_context_id: u64, + has_name: bool, + name: &str, + props: KjOwn, + limits: &Limits, + result: &mut KjMaybe>, + ) -> bool; + #[expect( + clippy::too_many_arguments, + reason = "an out-parameter shim, as C++ declares it" + )] + unsafe fn worker_stub_get_actor_class( + isolate: *mut Isolate, + stub: &WorkerStubHandle, + io_context_id: u64, + has_name: bool, + name: &str, + props: KjOwn, + limits: &Limits, + result: &mut KjMaybe>, + ) -> bool; + } + + extern "Rust" { + /// The callback of `WorkerLoader.get()`, which C++ calls, and drops, on the thread of the + /// IoContext that made it. + type CodeCallback; + + /// Calls `callback`: a promise for the source of the Worker it gets the code of. + async fn code_callback_call(callback: &CodeCallback) -> Result>; + } + + impl KjOwn {} + impl KjOwn {} +} + +pub use bridge::CompatibilityDateValidation; +pub use bridge::Limits; +pub use bridge::ModuleKind; +pub use bridge::SourceBuilder; +pub use bridge::WorkerStubHandle; + +// SAFETY: the handle holds a C++ `IoOwn`, which may be destroyed on any thread: off its +// IoContext's thread, it only queues the deletion for the IoContext (`DeleteQueue` in +// io-own.c++). It is dereferenced only by the shims, which run under the isolate lock and check +// that its IoContext is the current one, so on that IoContext's thread. +unsafe impl Send for WorkerStubHandle {} +// SAFETY: as for `Send`: `&WorkerStubHandle` reaches the channel only through the shims. +unsafe impl Sync for WorkerStubHandle {} + +/// The callback of `WorkerLoader.get()`. +pub struct CodeCallback(pub ReentryCallback>); + +fn code_callback_call( + callback: &CodeCallback, +) -> impl Future, cxx::KjException>> + use<> { + callback.0.call() +} + +impl SourceBuilder { + /// A new builder for a Worker whose main module is `main_module`. + #[must_use] + pub fn new(main_module: &str) -> KjOwn { + bridge::source_builder_new(nul_terminated(main_module)) + } + + /// Adds a module whose body is text, as `kind`, which is not `Data` or `Wasm`. The builder + /// takes `body`. + /// + /// # Errors + /// Fails with an internal error for a kind whose body is bytes. + pub fn add_text( + self: std::pin::Pin<&mut Self>, + kind: ModuleKind, + name: &str, + mut body: String, + ) -> jsg::Result<()> { + // The body moves to C++ with a NUL appended, rather than being copied. + body.push('\0'); + Ok(bridge::source_builder_add_text( + self, + kind.repr, + nul_terminated(name), + body, + )?) + } + + /// Adds a `Data` or `Wasm` module of `body`, which the builder takes. + /// + /// # Errors + /// Fails with an internal error for a kind whose body is text. + pub fn add_bytes( + self: std::pin::Pin<&mut Self>, + kind: ModuleKind, + name: &str, + body: Vec, + ) -> jsg::Result<()> { + Ok(bridge::source_builder_add_bytes( + self, + kind.repr, + nul_terminated(name), + body, + )?) + } + + /// Adds a WASM module that shares the compiled code of `module`. + /// + /// # Errors + /// A pending error if the C++ threw. + pub fn add_compiled_wasm( + self: std::pin::Pin<&mut Self>, + lock: &mut jsg::Lock<'_>, + name: &str, + module: v8::CompiledWasmModule, + ) -> jsg::Result<()> { + let name = nul_terminated(name); + let module = module.into_ffi(); + jsg_cpp::call_cpp(lock, |isolate| { + // SAFETY: `call_cpp` calls the shim with the lock's isolate. + unsafe { bridge::source_builder_add_compiled_wasm(isolate, self, name, module) } + }) + } + + /// Compiles the code's compatibility date and flags with C++ `compileCompatibilityFlags()`, + /// as the C++ Worker Loader does. + /// + /// # Errors + /// A pending error with the compiler's first error, as C++ Worker Loader throws it. + pub fn compile_compat_flags( + self: std::pin::Pin<&mut Self>, + lock: &mut jsg::Lock<'_>, + compat_date: &str, + flags: &[String], + allow_experimental: bool, + date_validation: CompatibilityDateValidation, + ) -> jsg::Result<()> { + jsg_cpp::call_cpp(lock, |isolate| { + // SAFETY: `call_cpp` calls the shim with the lock's isolate. + unsafe { + bridge::source_builder_compile_compat_flags( + isolate, + self, + compat_date, + flags, + allow_experimental, + date_validation, + ) + } + }) + } + + pub fn set_limits(self: std::pin::Pin<&mut Self>, limits: &Limits) { + bridge::source_builder_set_limits(self, limits); + } + + pub fn set_env(self: std::pin::Pin<&mut Self>, env: KjOwn) { + bridge::source_builder_set_env(self, env); + } + + pub fn set_global_outbound(self: std::pin::Pin<&mut Self>, channel: KjRc) { + bridge::source_builder_set_global_outbound(self, channel); + } + + /// Has the Worker inherit the global outbound of the calling Worker. + /// + /// # Errors + /// A pending error if the C++ threw, as unless `io_context` is current. + pub fn inherit_global_outbound<'s>( + self: std::pin::Pin<&mut Self>, + lock: &mut jsg::Lock<'s>, + io_context: &IoContext<'s>, + ) -> jsg::Result<()> { + let id = io_context.as_ffi(); + jsg_cpp::call_cpp(lock, |isolate| { + // SAFETY: `call_cpp` calls the shim with the lock's isolate. + unsafe { bridge::source_builder_inherit_global_outbound(isolate, self, id) } + }) + } + + pub fn add_tail(self: std::pin::Pin<&mut Self>, channel: KjRc) { + bridge::source_builder_add_tail(self, channel); + } + + pub fn add_streaming_tail(self: std::pin::Pin<&mut Self>, channel: KjRc) { + bridge::source_builder_add_streaming_tail(self, channel); + } +} + +/// Loads the Worker that `builder` describes on the loader channel `channel`, as `load()` does. +/// +/// # Errors +/// A pending error if the C++ threw. +pub fn load<'s>( + lock: &mut jsg::Lock<'s>, + io_context: &IoContext<'s>, + channel: u32, + builder: KjOwn, +) -> jsg::Result> { + let id = io_context.as_ffi(); + let mut slot = KjMaybe::None; + jsg_cpp::call_cpp(lock, |isolate| { + // SAFETY: `call_cpp` calls the shim with the lock's isolate. + unsafe { bridge::worker_loader_load(isolate, id, channel, builder, &mut slot) } + })?; + Ok(Option::from(slot).unwrap_or_else(|| unreachable!("a shim that completed sets its result"))) +} + +/// Loads, or finds, the Worker named `name` on the loader channel `channel`, whose source +/// `callback` gets, as `get()` does. +/// +/// # Errors +/// A pending error if the C++ threw. +pub fn get<'s>( + lock: &mut jsg::Lock<'s>, + io_context: &IoContext<'s>, + channel: u32, + name: Option<&str>, + callback: CodeCallback, +) -> jsg::Result> { + let id = io_context.as_ffi(); + let mut slot = KjMaybe::None; + let callback = Box::new(callback); + jsg_cpp::call_cpp(lock, |isolate| { + // SAFETY: `call_cpp` calls the shim with the lock's isolate. + unsafe { + bridge::worker_loader_get( + isolate, + id, + channel, + name.is_some(), + name.unwrap_or_default(), + callback, + &mut slot, + ) + } + })?; + Ok(Option::from(slot).unwrap_or_else(|| unreachable!("a shim that completed sets its result"))) +} + +impl WorkerStubHandle { + /// A `Fetcher` for the entrypoint `name` (`None` for the default one) of the stub's Worker. + /// + /// # Errors + /// A pending error if the C++ threw, as unless `io_context` is the stub's. + pub fn entrypoint<'s>( + &self, + lock: &mut jsg::Lock<'s>, + io_context: &IoContext<'s>, + name: Option<&str>, + props: KjOwn, + limits: &Limits, + ) -> jsg::Result> { + let id = io_context.as_ffi(); + // SAFETY: the shim instantiates callCppForRef with api::Fetcher, and `call_cpp_for_ref` + // calls it with the lock's isolate. + let fetcher = unsafe { + jsg_cpp::call_cpp_for_ref(lock, |isolate, result| { + bridge::worker_stub_get_entrypoint( + isolate, + self, + id, + name.is_some(), + name.unwrap_or_default(), + props, + limits, + result, + ) + }) + }?; + Ok(fetcher.unwrap_or_else(|| unreachable!("a shim that completed sets its result"))) + } + + /// A `DurableObjectClass` for the class `name` (`None` for the default one) of the stub's + /// Worker. + /// + /// # Errors + /// As for [`entrypoint`](Self::entrypoint). + pub fn actor_class<'s>( + &self, + lock: &mut jsg::Lock<'s>, + io_context: &IoContext<'s>, + name: Option<&str>, + props: KjOwn, + limits: &Limits, + ) -> jsg::Result> { + let id = io_context.as_ffi(); + // SAFETY: the shim instantiates callCppForRef with api::DurableObjectClass, and + // `call_cpp_for_ref` calls it with the lock's isolate. + let class = unsafe { + jsg_cpp::call_cpp_for_ref(lock, |isolate, result| { + bridge::worker_stub_get_actor_class( + isolate, + self, + id, + name.is_some(), + name.unwrap_or_default(), + props, + limits, + result, + ) + }) + }?; + Ok(class.unwrap_or_else(|| unreachable!("a shim that completed sets its result"))) + } +} + +/// `text` followed by a NUL, so that C++ can view it as a `kj::StringPtr` without copying it. +fn nul_terminated(text: &str) -> String { + let mut owned = String::with_capacity(text.len() + 1); + owned.push_str(text); + owned.push('\0'); + owned +} diff --git a/src/workerd/api/worker-loader-interop/lib.rs b/src/workerd/api/worker-loader-interop/lib.rs new file mode 100644 index 00000000000..026b8e18379 --- /dev/null +++ b/src/workerd/api/worker-loader-interop/lib.rs @@ -0,0 +1,23 @@ +// 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 + +//! Interop with C++ `IoChannelFactory::loadIsolate()` for the Rust Worker Loader +//! (`api/worker-loader-api`): a [`SourceBuilder`] builds a C++ `DynamicWorkerSource` from +//! buffers that Rust made and hands over without copying, [`load`] and [`get`] load it, and a +//! [`WorkerStubHandle`] holds the `WorkerStubChannel` they return, from which it gets entrypoints +//! as `Fetcher`s and Durable Object classes as `DurableObjectClass`es. +//! +//! The C++ side, `ffi.h` and `ffi.c++`, is C++ API code, which lives here with the API rather +//! than in Rust JSG. + +mod ffi; + +pub use ffi::CodeCallback; +pub use ffi::CompatibilityDateValidation; +pub use ffi::Limits; +pub use ffi::ModuleKind; +pub use ffi::SourceBuilder; +pub use ffi::WorkerStubHandle; +pub use ffi::get; +pub use ffi::load; diff --git a/src/workerd/server/BUILD.bazel b/src/workerd/server/BUILD.bazel index ed63205ebbd..0fff8e0d0bd 100644 --- a/src/workerd/server/BUILD.bazel +++ b/src/workerd/server/BUILD.bazel @@ -229,6 +229,8 @@ wd_cc_library( "//src/workerd/api/bench-api:ffi.rs@cxx", "//src/workerd/api/memory-cache-api", "//src/workerd/api/memory-cache-api:ffi.rs@cxx", + "//src/workerd/api/worker-loader-api", + "//src/workerd/api/worker-loader-api:ffi.rs@cxx", "//src/workerd/io:promise-wrapper", ], local_defines = select({ diff --git a/src/workerd/server/workerd-api.c++ b/src/workerd/server/workerd-api.c++ index 9d011d74912..ffdbcaaae47 100644 --- a/src/workerd/server/workerd-api.c++ +++ b/src/workerd/server/workerd-api.c++ @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -761,6 +762,11 @@ static v8::Local createBindingValue(JsgWorkerdIsolate::Lock& lock, context, lock.alloc(global.getLoopbackActorClass())); case Global::WORKER_LOADER: + if (util::Autogate::isEnabled(util::AutogateKey::RUST_WORKER_LOADER)) { + return jsg::check(::workerd::rust::jsg::maybe_local_from_ffi( + api::worker_loader_new(lock.v8Isolate, global.getWorkerLoader(), + CompatibilityDateValidation::CODE_VERSION))); + } return lock.wrap(context, lock.alloc( global.getWorkerLoader(), CompatibilityDateValidation::CODE_VERSION)); diff --git a/src/workerd/util/autogate.h b/src/workerd/util/autogate.h index c9eb93179fa..7ec02e0bcf8 100644 --- a/src/workerd/util/autogate.h +++ b/src/workerd/util/autogate.h @@ -141,7 +141,10 @@ namespace workerd::util { V(IO_CHANNELS_FROM_RUNNING_REQUEST) \ /* WorkerInterface::fromException() makes the Rust worker in src/rust/worker/failure.rs \ instead of the C++ ErrorWorkerInterface in io/worker-interface.c++. */ \ - V(RUST_FAILURE_WORKER_INTERFACE) + V(RUST_FAILURE_WORKER_INTERFACE) \ + /* When enabled, Worker Loader bindings are the Rust WorkerLoader \ + (src/workerd/api/worker-loader-api) instead of the C++ one (api/worker-loader.c++). */ \ + V(RUST_WORKER_LOADER) // clang-format on // --------------------------------------------------------------------------------------