Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/rust/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ _Snapshot — the set drifts as crates come and go; `bazel query //src/rust/...`
- **Rust JSG safety rules** (full text and examples in `src/rust/jsg/README.md` §Safety rules):
1. Never call a V8 API that takes a `v8::Local<v8::Context>` while an exception or a termination is pending: V8 either clears the exception on entry, so the script runs on, or fails a debug check and in a release build runs on with it pending. Every C++ shim that passes a context to V8 first checks `exceptionPending()` (`jsg/ffi.h`) and fails with a pending error. Never throw while execution is terminating, and never discard a `jsg::Error` from an operation that can fail with a pending error (a call, `Object::get`/`set`, a coercion, `ToJS::to_js`); pass it on with `?`. Creating strings, numbers, objects, arrays, error objects and templates is fine at any time.
2. Never put traced state (`TracedGlobal`, `jsg::Rc`, or a type holding them) behind `std::rc::Rc`. To give a callback or another party access, give it a `jsg::Rc` or `jsg::Weak` to the resource that owns the state (a method gets one as `this: jsg::Rc<Self>`). Keep a `jsg::Rc` or `TracedGlobal` that is moved out of a field in a `jsg::Cell` or `jsg::RefCell`, which make it strong on the way out; a plain move out of a std cell would leave it neither strong nor traced, so std cells holding one do not compile ([#7976](https://github.com/cloudflare/workerd/issues/7976)). Don't put a `Global` in anything GC traces. A typed promise's reaction gets its value detached from the promise's wrapper, as a moved C++ `jsg::Ref` is, and so does a value leaving a `jsg::` cell; a `Traced` impl that visits through `GcVisitor::as_ffi` must handle the `None` it returns for such a visit (`GcVisitor::is_detaching()`).
3. The C++ shims call V8 directly, not C++ JSG (`JSG_TRY`, `jsg::check`, `jsg::Lock::from`, `createTunneledException`, `makeInternalError`, `jsg::Data`, ...). The one reviewed exception is `io_context_await_io_and_run()` in `src/workerd/io/io-context/ffi.c++`, which throws `jsg::JsExceptionThrown` to pass a pending exception to `IoContext::run()`; don't extend it. `//src/rust/jsg:cpp-jsg-allowlist-test` enforces this for the files in `CPP_SHIMS` in `jsg/BUILD.bazel`; add shim files outside `src/rust/jsg` there.
3. The C++ shims call V8 directly, not C++ JSG (`JSG_TRY`, `jsg::check`, `jsg::Lock::from`, `createTunneledException`, `makeInternalError`, `jsg::Data`, ...). The one reviewed exception is `throwPendingToRun()` in `src/workerd/io/io-context/ffi.c++`, which throws `jsg::JsExceptionThrown` to pass a pending exception or termination to `IoContext::run()`; only code that `run()` runs reaches it (the `io_context_await_io_and_run()` callback and a `ReentryCallback`'s function). Don't add another throw or another caller. `//src/rust/jsg:cpp-jsg-allowlist-test` enforces this for the files in `CPP_SHIMS` in `jsg/BUILD.bazel`; add shim files outside `src/rust/jsg` there.
4. `Local<'s>` and `Lock<'s>` stay in their scope, a method's `&self` lasts for the call, and futures passed to async I/O are `'static`.
5. Resource state is `Send`, which prevents data races on state that only the isolate lock guards (non-atomic counts, `Cell`s). The lock is a mutex over it: one thread at a time, but the lock passes between threads and a holder can move a value out and keep it, so the state must be `Send` (as `Mutex<T>: Sync` needs `T: Send`), not `Sync`. `Traced: Send` makes the compiler check it, so `std::rc::Rc`, `Arc<RefCell<_>>` and thread-bound KJ objects (`io_context::SpanBuilder`) can't be resource state. `jsg::Rc`, `jsg::Weak` and `jsg_cpp::Ref` are `Send` because they touch their counts only under their own isolate's lock: every operation but dropping that reaches them takes a `&Lock` and panics for another isolate's, GC and detaching visits leave another isolate's references alone (`GcVisitor::visit_rc`, `LockGuarded::get_for_visit`), and `Lock` is neither `Send` nor `Sync`. A value only the isolate lock guards that a crate outside `jsg` holds (`jsg_cpp::Ref`'s C++ `jsg::Ref`) goes in a `jsg::LockGuarded`, which lends it under its isolate's lock and drops it as a `jsg::Rc`'s parts are; `v8::WrappableRc` and the `jsg_cpp` bridge are private, since they change counts without the lock. Hand-written `Traced` impls are safe: breaking rule 2 leaks, panics or aborts, but is not UB.
- **Formatting**: `rustfmt.toml` — `group_imports = "StdExternalCrate"`, `imports_granularity = "Item"` (one `use` per import)
Expand Down
10 changes: 6 additions & 4 deletions src/rust/jsg/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,10 +253,12 @@ some other way or reaches it through another kind of cell, a std cell included,
C++ JSG will be removed, so Rust JSG must not depend on it. New code in the C++ shims in
`src/rust/jsg` calls V8 directly (`v8::TryCatch`, `v8::MaybeLocal`, `isolate->ThrowException`) and
leaves decisions to Rust. Some existing shims still use C++ JSG. Those uses are listed in the
allowlist described below, and are to be removed. The one exception is in
`src/workerd/io/io-context/ffi.c++`, where `io_context_await_io_and_run()` throws
`JsExceptionThrown` to pass an exception that Rust left pending to `IoContext::run()`, which
learns of exceptions no other way. Don't extend it.
allowlist described below, and are to be removed. The one exception is `throwPendingToRun()` in
`src/workerd/io/io-context/ffi.c++`, which throws `JsExceptionThrown` to pass an exception or a
termination that Rust left pending to `IoContext::run()`, which learns of them no other way. Only
Rust code that `run()` itself runs reaches it: the callback of `io_context_await_io_and_run()` and
the function of a `ReentryCallback`. Don't add another throw, or another caller that `run()`
doesn't run.

Don't add C++ JSG to the shims. This includes `jsg::Lock` (including `Lock::from` and
`IoContext::getCurrentLock()`),
Expand Down
7 changes: 4 additions & 3 deletions src/rust/jsg/cpp-jsg-allowlist.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ src/rust/jsg/jsg.h jsg::Lock 3
src/rust/jsg/jsg.h JsExceptionThrown 1
src/rust/jsg/jsg.h jsg::Data 1

# A reviewed exception, explained above it in that file: io_context_await_io_and_run()
# propagates the exception that a failed callback left pending to IoContext::run() as
# JsExceptionThrown, which is how run() learns of it. Don't add to it.
# A reviewed exception, explained above it in that file: throwPendingToRun() propagates the
# exception or termination that Rust left pending, for io_context_await_io_and_run() and
# ReentryCallback, to IoContext::run() as JsExceptionThrown, which is how run() learns of it.
# Don't add to it.
src/workerd/io/io-context/ffi.c++ JsExceptionThrown 1
7 changes: 6 additions & 1 deletion src/workerd/io/io-context/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,19 @@ wd_rust_crate(
testonly = True,
srcs = ["test_bridge.rs"],
crate_root = "test_bridge.rs",
cxx_bridge_deps = ["//src/rust/jsg"],
cxx_bridge_deps = [
"//src/rust/jsg",
"//src/workerd/api/channel-interop:ffi.rs@cxx",
],
cxx_bridge_hdrs = ["test-bridge.h"],
cxx_bridge_src = "test_bridge.rs",
link_deps = [":test-bridge"],
proc_macro_deps = ["//src/rust/jsg-macros"],
deps = [
":io-context",
"//src/rust/jsg",
"//src/rust/jsg-cpp",
"//src/workerd/api/channel-interop",
"@crates_vendor//futures",
],
)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// 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 output of an `await_js_local` conversion belongs to the IoContext's thread, so the
// future that holds it can't leave that thread, even when the output itself is `Send`.
use io_context::AwaitJsLocal;

fn require_send<T: Send>(_: T) {}

fn require_sync<T: Sync>(_: &T) {}

pub fn future(wait: AwaitJsLocal<u32>) {
require_send(wait); //~ ERROR E0277
}

pub fn shared(wait: &AwaitJsLocal<u32>) {
require_sync(wait); //~ ERROR E0277
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// 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 conversion of `await_js_local` is the data of a reaction, which GC can drop on any
// thread that locks the isolate, so it captures nothing that is not `Copy` and `Send`, though its
// output need not be either.
use std::cell::Cell;
use std::rc::Rc;

use io_context::IoContext;
use jsg::v8;

pub fn captures(
lock: &mut jsg::Lock<'_>,
context: &IoContext<'_>,
promise: v8::Local<'_, v8::Promise>,
) {
let name = String::from("captured");
let _ = context.await_js_local(lock, promise, move |_lock, _context, _value| {
//~^ ERROR E0277
Ok(name.len())
});
}

pub fn captures_not_send(
lock: &mut jsg::Lock<'_>,
context: &IoContext<'_>,
promise: v8::Local<'_, v8::Promise>,
counter: &'static Cell<u32>,
) {
let _ = context.await_js_local(lock, promise, move |_lock, _context, _value| {
//~^ ERROR E0277
Ok(counter.get())
});
}

pub fn output_need_not_be_send<'s>(
lock: &mut jsg::Lock<'s>,
context: &IoContext<'s>,
promise: v8::Local<'s, v8::Promise>,
) -> jsg::Result<io_context::AwaitJsLocal<Rc<u32>>> {
context.await_js_local(lock, promise, |_lock, _context, _value| Ok(Rc::new(1_u32)))
}
39 changes: 39 additions & 0 deletions src/workerd/io/io-context/compile-tests/ok-reentry-callback.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// 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 example of `IoContext::make_reentry_callback_weak()`: an API keeps a JavaScript callback that
// returns a Worker's code, for a C++ `kj::Function` to call later, as `WorkerLoader.get()` does.
// The `await_js_local` conversion builds an output that is not `Send` from the resolved
// object, in the IoContext, and its future is the function's. A Rust future can await a call too.
use std::rc::Rc;

use io_context::IoContext;
use io_context::ReentryCallback;
use jsg::FromJS;
use jsg::v8;
use jsg_macros::jsg_struct;

#[jsg_struct]
pub struct WorkerCode {
pub main_module: String,
pub compatibility_date: String,
}

pub fn keep<'s>(
lock: &mut jsg::Lock<'s>,
get_code: v8::Local<'s, v8::Function>,
) -> jsg::Result<ReentryCallback<Rc<WorkerCode>>> {
let get_code = get_code.to_global(lock);
IoContext::current(lock)?.make_reentry_callback_weak(move |lock, context| {
let code = get_code.as_local(lock).call(lock, None, &[])?;
let code = v8::Promise::resolved(lock, code)?;
context.await_js_local(lock, code, |lock, _context, value| {
Ok(Rc::new(WorkerCode::from_js(lock, value)?))
})
})
}

pub async fn fetch(callback: &ReentryCallback<Rc<WorkerCode>>) -> Option<usize> {
Some(callback.call().await.ok()?.main_module.len())
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// 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 function of a reentry callback, the future it returns and that future's output stay on the
// IoContext's thread, so none of them need be `Send`: each can hold an `Rc`, as an output can hold
// C++ objects that belong to that thread.
use std::rc::Rc;

use io_context::IoContext;
use io_context::ReentryCallback;

pub fn function(context: &IoContext<'_>, shared: Rc<u32>) -> jsg::Result<ReentryCallback<u32>> {
context.make_reentry_callback_weak(move |_lock, _context| {
let value = *shared;
Ok(async move { Ok(value) })
})
}

pub fn future(context: &IoContext<'_>) -> jsg::Result<ReentryCallback<u32>> {
context.make_reentry_callback_weak(|_lock, _context| {
let shared = Rc::new(1_u32);
Ok(async move { Ok(*shared) })
})
}

pub fn output(context: &IoContext<'_>) -> jsg::Result<ReentryCallback<Rc<u32>>> {
context.make_reentry_callback_weak(|_lock, _context| Ok(async { Ok(Rc::new(1_u32)) }))
}

pub async fn call(callback: &ReentryCallback<Rc<u32>>) -> Option<u32> {
Some(*callback.call().await.ok()?)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// 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 reentry callback is the C++ callback of `IoContext::makeReentryCallbackWeak()`, which belongs
// to its IoContext's thread: it holds the IoContext's weak reference and a pending event, whose
// counts are not atomic. So it can't leave that thread. Since `Traced` requires `Send`, it also
// can't be kept where the garbage collector, which can run on any thread that locks the isolate,
// would drop it.
use io_context::ReentryCallback;

fn require_send<T: Send>(_: T) {}

fn require_sync<T: Sync>(_: &T) {}

pub fn callback(callback: ReentryCallback<u32>) {
require_send(callback); //~ ERROR E0277
}

pub fn shared(callback: &ReentryCallback<u32>) {
require_sync(callback); //~ ERROR E0277
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// 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 function of a reentry callback runs with a new lock each time it is called, after the caller
// has returned, and the future it returns is polled with none: neither can keep a handle, of the
// caller's lock or of its own. The function is `'static`, so it can't capture a `Local` of the
// caller's lock, and its future is one type for every lock, so it can't hold a `Local` of the
// lock it is given.
use io_context::IoContext;
use jsg::v8;

pub fn captured<'s>(lock: &mut jsg::Lock<'s>, context: &IoContext<'s>) {
let object: v8::Local<'s, v8::Value> = lock.new_object().into();
let _ = context.make_reentry_callback_weak(move |_lock, _context| {
//~^ ERROR E0521
let _object = object;
Ok(async { Ok(()) })
});
}

pub fn returned(context: &IoContext<'_>) {
let _ = context.make_reentry_callback_weak(|lock, _context| {
let object: v8::Local<'_, v8::Value> = lock.new_object().into();
Ok(async move {
//~^ ERROR lifetime may not live long enough
let _object = object;
Ok(())
})
});
}
60 changes: 54 additions & 6 deletions src/workerd/io/io-context/ffi.c++
Original file line number Diff line number Diff line change
Expand Up @@ -170,10 +170,18 @@ void io_context_add_wait_until(uint64_t id, ::rust::Box<WaitUntilFuture> future)
currentWithId(id).addWaitUntil(wait_until_future_wait(kj::mv(future)));
}

namespace {

// Rust JSG's shims don't use C++ JSG (src/rust/jsg/README.md, "Safety rules", rule 3). This
// function is the reviewed exception: it throws JsExceptionThrown, which is how IoContext::run()
// learns of an exception the callback left pending in V8. That use is counted in
// src/rust/jsg/cpp-jsg-allowlist.txt, so it stays within this function.
// learns of an exception, or a termination, that Rust left pending in V8, as for C++ code it runs.
// That use is counted in src/rust/jsg/cpp-jsg-allowlist.txt, so it stays within this function.
[[noreturn]] void throwPendingToRun() {
throw jsg::JsExceptionThrown();
}

} // namespace

void io_context_await_io_and_run(
uint64_t id, ::rust::Box<IoFuture> future, ::rust::Box<IoCallback> callback) {
auto& context = currentWithId(id);
Expand All @@ -185,10 +193,9 @@ void io_context_await_io_and_run(
case IoCallbackOutcome::Succeeded:
return;
case IoCallbackOutcome::Failed:
// The exception, or termination, is pending in V8. JsExceptionThrown is how
// IoContext::run() expects to learn of it: it then logs the exception as uncaught, with its
// stack, and fails the task with it, as for C++ code it runs.
throw jsg::JsExceptionThrown();
// The exception, or termination, is pending in V8. run() then logs the exception as
// uncaught, with its stack, and fails the task with it.
throwPendingToRun();
case IoCallbackOutcome::Panicked:
// The termination takes effect only when V8 next runs JavaScript, in run()'s microtask
// checkpoint. Until then, run() would treat JsExceptionThrown as an ordinary exception and
Expand All @@ -199,6 +206,47 @@ void io_context_await_io_and_run(
});
}

ReentryCallback::ReentryCallback(IoContext& context, ::rust::Box<ReentryFn> function)
: callback(context.makeReentryCallbackWeak([function = kj::mv(function)](Worker::Lock& lock,
IoContext&,
::rust::Box<ReentryCall> call) mutable
-> kj::Promise<void> {
switch (reentry_fn_run(reinterpret_cast<uintptr_t>(lock.getIsolate()), *function, *call)) {
case ReentryOutcome::Started:
return reentry_call_wait(kj::mv(call));
case ReentryOutcome::Terminated:
// The termination is pending in V8. run() then handles it as for C++ code it runs: it
// leaves the scope of the limit enforcer, fails with the exceeded limit or the
// exception the request was aborted with, and has its microtask checkpoint cancel the
// microtasks queued meanwhile.
throwPendingToRun();
case ReentryOutcome::Panicked:
// jsg::catch_panic() threw an internal error and requested a termination, which run()'s
// microtask checkpoint delivers. run() would convert a JsExceptionThrown, running
// JavaScript first, so the call fails with a KJ exception instead.
KJ_FAIL_ASSERT("the function of IoContext::make_reentry_callback_weak() panicked");
}
KJ_UNREACHABLE;
})) {}

kj::Promise<void> ReentryCallback::call(::rust::Box<ReentryCall> call) const {
return callback(kj::mv(call));
}

kj::Own<ReentryCallback> io_context_make_reentry_callback_weak(
uint64_t id, ::rust::Box<ReentryFn> function) {
return kj::heap<ReentryCallback>(currentWithId(id), kj::mv(function));
}

kj::Own<ReentryPromise> reentry_callback_call(
const ReentryCallback& callback, ::rust::Box<ReentryCall> call) {
return kj::heap<ReentryPromise>(callback.call(kj::mv(call)));
}

kj::Promise<void> reentry_promise_wait(kj::Own<ReentryPromise> promise) {
return kj::mv(promise->promise);
}

kj::Own<IoOwnedObject> io_context_add_object(uint64_t id, ::rust::Box<IoOwnedSlot> slot) {
auto& context = currentWithId(id);
return kj::heap<IoOwnedObject>(
Expand Down
Loading
Loading