Skip to content
4 changes: 2 additions & 2 deletions src/rust/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ _Snapshot — the set drifts as crates come and go; `bazel query //src/rust/...`

| Crate | Purpose |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `jsg/` | Rust JSG bindings: `Lock`, `Rc<T>`, `Resource`, `Struct`, `Type`, `Realm`, `FeatureFlags`, module registration; V8 handle types in `jsg::v8` (`Local`, `Global`, `TracedGlobal` over marker types that mirror V8's classes, from `Value` and `Number` to the typed arrays, and `BackingStore`); JS functions from Rust closures (`v8::Function::new`); async context frames (`AsyncContextFrame`, `TracedAsyncContextFrame`); structured serialization in `jsg::Serializer`'s format (`ser`) |
| `jsg/` | Rust JSG bindings: `Lock`, `Rc<T>`, `Resource`, `Struct`, `Type`, `Realm`, `FeatureFlags`, module registration; V8 handle types in `jsg::v8` (`Local`, `Global`, `TracedGlobal` over marker types that mirror V8's classes, from `Value` and `Number` to the typed arrays, and `BackingStore`); JS functions from Rust closures (`v8::Function::new`); typed promises (`jsg::Promise<'s, T>`, counterpart of C++ `jsg::Promise<T>`, with `PromiseResolver`, `TracedPromise`, `TracedPromiseResolver` and `Lock::eval_now`; a returned promise keeps its resource alive through `ToJS::to_js_with_creator`, which containers forward); async context frames (`AsyncContextFrame`, `TracedAsyncContextFrame`); structured serialization in `jsg::Serializer`'s format (`ser`) |
| `jsg-macros/` | Proc macros: `#[jsg_struct]`, `#[jsg_method]`, `#[jsg_resource]`, `#[jsg_oneof]`, `#[jsg_static_constant]`, `#[jsg_constructor]`, `#[jsg_property]`, `#[jsg_inspect_property]`, `#[jsg_wildcard_property]` |
| `jsg-test/` | Test harness (`Harness`) for JSG Rust bindings |
| `api/` | Rust-implemented Node.js APIs; registers modules via `register_nodejs_modules()` |
Expand Down Expand Up @@ -46,7 +46,7 @@ _Snapshot — the set drifts as crates come and go; `bazel query //src/rust/...`
- **`#[jsg_resource(custom_trace)]`**: suppresses the auto-generated `Traced` impl so the user can write their own; `GarbageCollected` (`memory_name`), `jsg::Type`, `jsg::ToJS`, and `jsg::FromJS` are still generated
- **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>`). Clone a `jsg::Rc` right after moving it out of a traced field (`take`, `replace`, `pop`), since the moved one is neither strong nor traced ([#7976](https://github.com/cloudflare/workerd/issues/7976)). Don't put a `Global` in anything GC traces.
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>`). Clone a `jsg::Rc` right after moving it out of a traced field (`take`, `replace`, `pop`), since the moved one is neither strong nor traced ([#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; 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.
4. `Local<'s>` and `Lock<'s>` stay in their scope, and futures passed to async I/O are `'static`.
- **Formatting**: `rustfmt.toml` — `group_imports = "StdExternalCrate"`, `imports_granularity = "Item"` (one `use` per import)
Expand Down
92 changes: 92 additions & 0 deletions src/rust/jsg-compile-tests/ok-typed-promise.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// 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

// Methods take and return typed promises, also in containers, carry Rust values through
// reactions, chain promises, keep a promise and its resolver in fields, and report errors by
// rejecting, without `unsafe`.
use std::cell::RefCell;

use jsg::v8;
use jsg_macros::jsg_method;
use jsg_macros::jsg_resource;

pub struct Carried {
pub count: usize,
}

impl jsg::Traced for Carried {}

#[jsg_resource]
pub struct Waiter {
promise: RefCell<Option<jsg::TracedPromise<Carried>>>,
resolver: RefCell<Option<jsg::TracedPromiseResolver<Carried>>>,
}

#[jsg_resource]
impl Waiter {
#[jsg_method]
fn start(&self, lock: &mut jsg::Lock<'_>) -> Result<(), jsg::Error> {
let (promise, resolver) = jsg::Promise::<Carried>::new_with_resolver(lock)?;
*self.promise.borrow_mut() = Some(promise.into_traced(lock));
*self.resolver.borrow_mut() = Some(resolver.into_traced(lock));
Ok(())
}

#[jsg_method]
fn finish(&self, lock: &mut jsg::Lock<'_>, count: u32) -> Result<(), jsg::Error> {
if let Some(resolver) = self.resolver.borrow_mut().take() {
resolver.as_local(lock).resolve(
lock,
Carried {
count: count as usize,
},
)?;
}
Ok(())
}

#[jsg_method]
fn count<'s>(&self, lock: &mut jsg::Lock<'s>) -> Result<jsg::Promise<'s, u32>, jsg::Error> {
let promise = self.promise.borrow_mut().take();
lock.eval_now(|lock| {
let promise = promise
.ok_or_else(|| jsg::Error::new_type_error("not started"))?
.into_local(lock);
promise.then(lock, (), |_lock, (), carried| Ok(carried.count as u32))
})
}

#[jsg_method]
fn add<'s>(
&self,
lock: &mut jsg::Lock<'s>,
input: jsg::Promise<'s, u32>,
done: jsg::Promise<'s, ()>,
any: jsg::Promise<'s, v8::Value>,
) -> Result<jsg::Promise<'s, v8::Value>, jsg::Error> {
let _: jsg::Promise<'s, ()> = done.when_resolved();
let _: jsg::Promise<'s, String> = input.then_or_catch(
lock,
String::from("n"),
|_lock, prefix, n| Ok(format!("{prefix}{n}")),
|_lock, _prefix, _reason| Ok(String::new()),
)?;
any.catch(lock, (), |_lock, (), reason| Ok(reason))
}

#[jsg_method]
fn chain<'s>(
&self,
lock: &mut jsg::Lock<'s>,
input: jsg::Promise<'s, u32>,
) -> Result<Option<jsg::Promise<'s, String>>, jsg::Error> {
let chained: jsg::Promise<'s, String> = input.then_promise(lock, (), |lock, (), n| {
jsg::Promise::resolved(lock, n.to_string())
})?;
let recovered = chained.catch_promise(lock, (), |lock, (), _reason| {
jsg::Promise::resolved(lock, String::new())
})?;
Ok(Some(recovered))
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// 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 typed promise's reaction captures nothing, as an untyped one's does: its state goes in the
// reaction's data, which the garbage collector can see.
pub fn t<'s>(
lock: &mut jsg::Lock<'s>,
promise: jsg::Promise<'s, u32>,
) -> jsg::Result<jsg::Promise<'s, String>> {
let prefix = String::from("captured");
promise.then(lock, (), move |_lock, (), n| Ok(format!("{prefix}{n}")))
//~^ ERROR E0277
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// 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 typed promise is a handle in its scope; keeping one beyond it takes a `TracedPromise`.
pub fn t(
lock: &mut jsg::Lock<'_>,
kept: &mut Option<jsg::Promise<'static, u32>>,
) -> jsg::Result<()> {
*kept = Some(jsg::Promise::resolved(lock, 1)?);
//~^ ERROR lifetime may not live long enough
Ok(())
}
11 changes: 11 additions & 0 deletions src/rust/jsg-compile-tests/typed-promise-is-used-once.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// 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

// As in C++ JSG, a typed promise is used once, since only one reaction can take its value.
pub fn t<'s>(lock: &mut jsg::Lock<'s>, promise: jsg::Promise<'s, String>) -> jsg::Result<()> {
let _: jsg::Promise<'s, String> = promise.then(lock, (), |_lock, (), s| Ok(s))?;
let _: jsg::Promise<'s, String> = promise.then(lock, (), |_lock, (), s| Ok(s))?;
//~^ ERROR E0382
Ok(())
}
10 changes: 10 additions & 0 deletions src/rust/jsg-compile-tests/typed-promise-of-a-v8-marker.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// 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 V8 marker type names a kind of handle and has no value of its own to carry, so a typed promise
// of one does not exist; a promise of a JavaScript value is a `jsg::Promise<v8::Value>`.
use jsg::v8;

pub fn t(_promise: jsg::Promise<'_, v8::Uint8Array>) {}
//~^ ERROR E0277
4 changes: 4 additions & 0 deletions src/rust/jsg-cpp/ffi.c++
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,8 @@ void cpp_ref_visit(GcVisitor* visitor, const CppRef& ref) {
ref.visitForGc(*::workerd::rust::jsg::gc_visitor_from_ffi(visitor));
}

void cpp_ref_detach(const CppRef& ref) {
ref.detach();
}

} // namespace workerd::rust::jsg_cpp
10 changes: 8 additions & 2 deletions src/rust/jsg-cpp/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ pub mod bridge {
///
/// `visitor` is the visitor of a visit in progress.
pub unsafe fn cpp_ref_visit(visitor: *mut GcVisitor, cpp_ref: &CppRef);
/// Makes the reference strong again and forgets its parent, as moving a C++ `jsg::Ref`
/// does; see `jsg::GcVisitor::is_detaching`. Requires the isolate lock.
pub fn cpp_ref_detach(cpp_ref: &CppRef);
}

impl KjOwn<CppRef> {}
Expand Down Expand Up @@ -208,8 +211,11 @@ impl<T: CppResource> Clone for Ref<T> {

impl<T: CppResource> jsg::Traced for Ref<T> {
fn trace(&self, visitor: &mut v8::GcVisitor) {
// SAFETY: the visitor's pointer is valid for the duration of the visit.
unsafe { bridge::cpp_ref_visit(visitor.as_ffi(), &self.inner) };
match visitor.as_ffi() {
// SAFETY: the visitor's pointer is valid for the duration of the visit.
Some(visitor) => unsafe { bridge::cpp_ref_visit(visitor, &self.inner) },
None => bridge::cpp_ref_detach(&self.inner),
}
}
}

Expand Down
10 changes: 10 additions & 0 deletions src/rust/jsg-cpp/jsg-cpp.h
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,15 @@ class CppRef final {
visitor.visit(ref);
}

// Makes the reference strong again and forgets its parent, as moving a `jsg::Ref` out of its
// field does: for a value that its GC owner, which may have made the reference weak, no longer
// holds. A moved `jsg::Ref` keeps the parent of its old location, so it is rebuilt in place.
void detach() const {
auto fresh = ref.addRef();
kj::dtor(ref);
kj::ctor(ref, kj::mv(fresh));
}

// For clone(): only CppRef can make the badge, so no one else can pair an object with a
// reference to a different one. Public only so that kj::heap can call it.
CppRef(kj::Badge<CppRef>, void* object, ::workerd::jsg::Ref<::workerd::jsg::Object> ref)
Expand All @@ -85,6 +94,7 @@ class CppRef final {
kj::Own<CppRef> cpp_ref_clone(const CppRef& ref);
size_t cpp_ref_object(const CppRef& ref);
void cpp_ref_visit(GcVisitor* visitor, const CppRef& ref);
void cpp_ref_detach(const CppRef& ref);

// Runs `func(jsg::Lock&)` the way a JSG method callback runs C++ API code (jsg::liftKj()), and
// returns whether it completed. A `jsg::JsExceptionThrown` leaves its exception pending. A
Expand Down
3 changes: 3 additions & 0 deletions src/rust/jsg-macros/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ Generates a V8 `FunctionCallback` for a method on a `#[jsg_resource]` type.
isn't first, or has another type, is a compile error.
- Return types of `Result<T, E>` automatically throw a JavaScript exception on `Err`, and so
does an error from converting the return value with `jsg::ToJS`.
- The return value converts with `jsg::ToJS::to_js_with_creator`, with the resource's wrapper
as the creator for an instance method and `None` for a static one, as C++ JSG passes
`creator` to `wrap()`: a returned `jsg::Promise` keeps the resource alive until it settles.
- The Rust `snake_case` name is converted to `camelCase` for JavaScript; override with
`#[jsg_method(name = "jsName")]`.
- The first typed parameter may be `&mut Lock` / `&mut jsg::Lock` to receive the
Expand Down
73 changes: 51 additions & 22 deletions src/rust/jsg-macros/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,15 @@ pub fn jsg_struct(attr: TokenStream, item: TokenStream) -> TokenStream {

impl<'s> jsg::ToJS<'s> for #name {
fn to_js(self, lock: &mut jsg::Lock<'s>) -> Result<jsg::v8::Local<'s, jsg::v8::Value>, jsg::Error> {
jsg::ToJS::to_js_with_creator(self, lock, None)
}

// As C++ JSG's `JSG_STRUCT` does, passes `creator` on to the fields.
fn to_js_with_creator(
self,
lock: &mut jsg::Lock<'s>,
creator: Option<jsg::v8::Local<'s, jsg::v8::Object>>,
) -> Result<jsg::v8::Local<'s, jsg::v8::Value>, jsg::Error> {
#to_js_body
}
}
Expand Down Expand Up @@ -217,13 +226,16 @@ fn to_js_fn_body(
// A DictionaryTemplate instance has every field, so an absent optional field is undefined.
let data_properties = fields.iter().map(|(field_name, js_name, _)| {
quote! {
properties.push((#js_name, jsg::ToJS::to_js(this.#field_name, lock)?));
properties.push((
#js_name,
jsg::ToJS::to_js_with_creator(this.#field_name, lock, creator)?,
));
}
});
// Set() skips an absent optional field rather than setting it to undefined.
let field_sets = fields.iter().map(|(field_name, js_name, present)| {
let set = quote! {
let value = jsg::ToJS::to_js(value, lock)?;
let value = jsg::ToJS::to_js_with_creator(value, lock, creator)?;
obj.set(lock, #js_name, value)?;
};
if let Some(present) = present {
Expand All @@ -239,6 +251,8 @@ fn to_js_fn_body(
});
quote! {
let this = self;
// Unused by a struct without public fields.
let _ = creator;
if lock.feature_flags().get_fast_jsg_struct() {
// The fields are defined as data properties, as C++ JSG's DictionaryTemplate does, so
// no setter a script put on Object.prototype runs.
Expand Down Expand Up @@ -435,26 +449,7 @@ fn callback_with_instance(
})
.unzip();

// Check if return type is Result<T, E>
let is_result = matches!(&fn_sig.output, syn::ReturnType::Type(_, ty) if is_result_type(ty));

let conversion = if is_result {
quote! {
match result {
Ok(value) => jsg::ToJS::to_js(value, lock),
Err(err) => Err(err.into()),
}
}
} else {
quote! { jsg::ToJS::to_js(result, lock) }
};
let result_handling = quote! {
let converted: ::std::result::Result<_, jsg::Error> = #conversion;
match converted {
Ok(value) => args.set_return_value(value),
Err(err) => lock.throw_exception(&err),
}
};
let result_handling = result_handling(fn_sig, receiver);

let invocation = invocation(fn_name, receiver, receiver_check, &arg_exprs);

Expand Down Expand Up @@ -487,6 +482,40 @@ fn callback_with_instance(
.into()
}

/// The statements that convert the call's `result` and return it to JavaScript, or throw what
/// the method or the conversion failed with.
fn result_handling(fn_sig: &syn::Signature, receiver: Receiver) -> proc_macro2::TokenStream {
// Check if return type is Result<T, E>
let is_result = matches!(&fn_sig.output, syn::ReturnType::Type(_, ty) if is_result_type(ty));

// Like C++ JSG, an instance method or property passes its receiver as the `creator` of the
// value it returns, which a promise keeps alive until it settles; a static one passes none.
let creator = match receiver {
Receiver::SelfRef | Receiver::This => {
quote! { jsg::v8::Local::<jsg::v8::Object>::try_from(args.this()).ok() }
}
Receiver::None => quote! { None },
};
let conversion = if is_result {
quote! {
match result {
Ok(value) => jsg::ToJS::to_js_with_creator(value, lock, creator),
Err(err) => Err(err.into()),
}
}
} else {
quote! { jsg::ToJS::to_js_with_creator(result, lock, creator) }
};
quote! {
let creator: Option<jsg::v8::Local<'_, jsg::v8::Object>> = #creator;
let converted: ::std::result::Result<_, jsg::Error> = #conversion;
match converted {
Ok(value) => args.set_return_value(value),
Err(err) => lock.throw_exception(&err),
}
}
}

/// The statements that call `fn_name` with `arg_exprs` and bind the call's `result`: on the
/// resource of `this` for a `&self` method, with a `jsg::Rc` of it for a `this` method, and as
/// an associated function otherwise.
Expand Down
10 changes: 9 additions & 1 deletion src/rust/jsg-macros/oneof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,8 +297,16 @@ impl<'a> Union<'a> {
#(#inner_types: jsg::ToJS<#s>,)*
{
fn to_js(self, lock: &mut jsg::Lock<#s>) -> Result<jsg::v8::Local<#s, jsg::v8::Value>, jsg::Error> {
jsg::ToJS::to_js_with_creator(self, lock, None)
}

fn to_js_with_creator(
self,
lock: &mut jsg::Lock<#s>,
creator: Option<jsg::v8::Local<#s, jsg::v8::Object>>,
) -> Result<jsg::v8::Local<#s, jsg::v8::Value>, jsg::Error> {
match self {
#(Self::#variant_names(value) => jsg::ToJS::to_js(value, lock),)*
#(Self::#variant_names(value) => jsg::ToJS::to_js_with_creator(value, lock, creator),)*
}
}
}
Expand Down
Loading
Loading