Skip to content

Rust JSG: typed promises - #8153

Merged
bartlomieju merged 9 commits into
mainfrom
biwanczuk/rust-jsg-typed-promise
Nov 3, 2026
Merged

bartlomieju merged 9 commits into
mainfrom
biwanczuk/rust-jsg-typed-promise

Conversation

@bartlomieju

@bartlomieju bartlomieju commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Adds jsg::Promise<'s, T>, the counterpart of C++ JSG's
jsg::Promise<T>: a promise that carries a Rust value, which need not
have a JavaScript form. It comes with PromiseResolver<'s, T>, the
persistent TracedPromise<T> and TracedPromiseResolver<T> for
resource fields, and Lock::eval_now(), the counterpart of
Lock::evalNow().

The untyped Local<v8::Promise> stays the counterpart of JsPromise.

The promise is modeled on C++ JSG's, so that a ported API settles its
promises in the same microtasks and runs the same conversions:

  • The JavaScript promise is settled with an opaque wrapper of the Rust
    value, as by wrapOpaque(). JavaScript never sees it.
  • Returned to JavaScript (ToJS), the promise becomes that of a
    reaction that converts the value, as PromiseWrapper::wrap() does
    with thenWrap(). It is marked as handled if the typed promise was.
  • Taken from JavaScript (FromJS), a promise gets one reaction that
    converts its value, as thenUnwrap() does. A value of the wrong type
    rejects it with C++ JSG's "Incorrect type for Promise" TypeError.
    Any other value is converted at once; a thenable is followed first
    under unwrap_custom_thenables.
  • Promise<()> is jsg::Promise<void> and Promise<v8::Value> is
    jsg::Promise<jsg::Value>, carried as undefined and as the
    JavaScript value itself.
  • A typed promise is used once: then, catch and then_or_catch
    consume it, and one reaction takes the value out of its wrapper.
    Callbacks capture nothing, as those of Local<v8::Promise>::then.
    then_promise, catch_promise and then_or_catch_promise take
    callbacks that return a promise, which the returned promise follows,
    as C++ JSG's then() chains a continuation that returns one.
  • A JavaScript value that settled a typed promise in place of its own,
    which a replaced Promise.prototype.then can do when
    resolve_with_promise() resolves one promise with another, rejects
    the reaction with an internal error, where C++ JSG fails a
    KJ_ASSERT.

The U of the promise that then returns is the projection
U::Value<'a> of the callback's return type, so rustc infers it from
where the promise goes, such as a method's return type, or from an
annotation.

A returned promise keeps the object that returned it alive. C++ JSG
passes every value it converts the object whose method or property
returned it, its creator. A promise makes it the data of its
conversion reaction, so the object lives until the promise settles even
if JavaScript drops it, while something else, such as pending I/O,
keeps the promise pending.

ToJS gets to_js_with_creator(), which defaults to to_js(). The
callbacks that #[jsg_method], the property macros and
#[jsg_wildcard_property] generate pass the receiver for an instance
member and None for a static one, as C++ JSG does. Promise keeps the
creator in its reaction's data. Option, Vec, Dict, Nullable,
NullOrUndefined, Lenient, NonCoercible, #[jsg_struct] and
#[jsg_oneof] pass it on, so a promise inside them keeps it too.

A value taken from a settled promise is detached from its GC owner. A
collection while a promise is pending can leave the jsg::Rcs and
TracedGlobals its value holds weak, for the wrapper to trace. A
reaction would then get a jsg::Rc that, stored in another resource,
fails C++'s single-parent assertion at the next collection, or a
handle whose value can be collected.

A moved C++ jsg::Ref has no such problem: the move makes it strong
again, with no parent. GcVisitor gets a detaching visit that does the
same for a value its owner no longer holds, through the value's own
Traced::trace:

  • A jsg::Rc becomes strong again and forgets its parent.
  • A TracedGlobal lets go of its traced reference and makes its strong
    handle strong.
  • jsg-cpp's Ref<T> rebuilds its C++ jsg::Ref in place, since a
    moved one keeps the parent of its old location.

unwrap_opaque() detaches every value it takes. A Traced impl that
visits through GcVisitor::as_ffi() must check
GcVisitor::is_detaching().

Also:

  • Traced is removed from the zero-sized V8 marker types, such as
    v8::Number and v8::Uint8Array, which have no value to trace. A
    typed promise of a marker would otherwise carry the marker, not a
    handle, and nothing used these impls.
  • Local<v8::Promise>::has_handler(), V8's HasHandler().
  • An opaque wrapper is traced only if its value holds GC references,
    as C++ JSG's isGcVisitable<T>() decides.

V8's `Promise::HasHandler()`: whether a promise has a reaction or was
marked as handled, so that its rejection is not reported as unhandled.
C++ JSG passes every value it converts the object whose method or
property returned it, its `creator`. A promise makes it the data of its
conversion reaction, so the object lives until the promise settles.

`ToJS` gets `to_js_with_creator()`, which defaults to `to_js()`. The
callbacks that `#[jsg_method]`, the property macros and
`#[jsg_wildcard_property]` generate pass the receiver for an instance
member and `None` for a static one, as C++ JSG does. `Option`, `Vec`,
`Dict`, `Nullable`, `NullOrUndefined`, `Lenient`, `NonCoercible`,
`#[jsg_struct]` and `#[jsg_oneof]` pass it on to what they hold.
Adds `jsg::Promise<'s, T>`, the counterpart of C++ JSG's
`jsg::Promise<T>`: a promise that carries a Rust value, settled with an
opaque wrapper of it as by `wrapOpaque()`, and converted on `ToJS` and
`FromJS` as `PromiseWrapper` does. It comes with
`PromiseResolver<'s, T>`, `TracedPromise<T>`,
`TracedPromiseResolver<T>` and `Lock::eval_now()`. A returned promise
keeps its creator alive until it settles.

A value taken out of its opaque wrapper is detached from it as a moved
C++ `jsg::Ref` is: `GcVisitor` gets a detaching visit that makes a
`jsg::Rc` strong with no parent, lets a `TracedGlobal` go of its traced
reference, and rebuilds jsg-cpp's `Ref<T>` in place.

`Traced` is removed from the zero-sized V8 marker types, which have no
value to trace, and an opaque wrapper is traced only if its value holds
GC references.
@codecov-commenter

codecov-commenter commented Nov 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 6.37584% with 558 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.65%. Comparing base (29b484a) to head (978389e).

Files with missing lines Patch % Lines
src/rust/jsg/typed_promise.rs 0.00% 401 Missing ⚠️
src/rust/jsg/wrappable.rs 12.50% 56 Missing ⚠️
src/rust/jsg/v8.rs 32.30% 44 Missing ⚠️
src/rust/jsg/opaque.rs 0.00% 32 Missing ⚠️
src/rust/jsg/ffi.c++ 42.85% 11 Missing and 1 partial ⚠️
src/rust/jsg/resource.rs 0.00% 10 Missing ⚠️
src/rust/jsg/promise.rs 0.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8153      +/-   ##
==========================================
- Coverage   68.84%   68.65%   -0.19%     
==========================================
  Files         734      736       +2     
  Lines      192834   193399     +565     
  Branches    30009    30010       +1     
==========================================
+ Hits       132751   132780      +29     
- Misses      42441    42978     +537     
+ Partials    17642    17641       -1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@guybedford guybedford left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Really nice work. Following C++ JSG's wrapOpaque/thenWrap/thenUnwrap model keeps ported APIs at microtask parity, and reusing Traced::trace for detaching means every traced type handles it automatically. I checked the tests locally, and disabling the detach in unwrap_opaque does make cpp_resource_carried_by_a_typed_promise_can_be_kept abort, so it's well covered. Approving on the basis of resolving the one comment below.

AI generated under my review

Comment thread src/rust/jsg/v8.rs Resolved
A detaching visit has no C++ visitor. `as_ffi()` only debug-asserted
that, so in a release build a `Traced` impl that forgot to check
`is_detaching()` would hand C++ a null `jsg::GcVisitor*` through a safe
function. Returning an `Option` makes every caller handle that case.
@bartlomieju
bartlomieju marked this pull request as ready for review November 2, 2026 20:38
@bartlomieju
bartlomieju requested review from a team as code owners November 2, 2026 20:38

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of 5e78b8a6.

This review, of d3390198

✅ Approved — No defects found. The earlier concern about as_ffi() passing a null visitor in release builds is fixed by returning Option.

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


✅ All checks passed

🔒 Security: ✅ LGTM

What I checked:

  • Opaque unwrapping: it checks both the C++ dynamic type and the Rust TypeId, so JavaScript cannot forge a wrapper.
  • Detaching visit: as_ffi() returns None for it, which removes the null-visitor hazard.
  • Pending exceptions: attach_opaque_wrapper still checks exceptionPending().

📖 AGENTS.md: ✅ LGTM

src/rust/AGENTS.md now covers how a Traced impl should handle a detaching visit.


📋 Code Quality: ✅ LGTM

What I checked:

  • Detaching visit: the paths for Rc, TracedGlobal and CppRef match the existing strong/weak and parent bookkeeping.
  • as_ffi(): it now returns Option, and its caller handles None.
  • to_js_with_creator: every wrapping ToJS impl and macro-generated callback forwards it.
  • Typed promises: the then/catch variants pass an unconsumed wrapper through the reaction they don't run.
  • Tests: the tests that share drop counters run serially.

⚡ Performance: ✅ LGTM

The extra reaction per returned promise matches what C++ JSG's thenWrap() does.


📝 Documentation: ✅ LGTM

The README and AGENTS.md updates describe the new behaviour accurately.


Reviewed commit: d3390198

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of 249e424c.

This review, of 5e78b8a6

✅ Approved — No defects found. Since the last review, only lib.rs changed, adding module declarations and re-exports. The as_ffi() null-visitor concern is fixed by returning an Option.

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


✅ All checks passed

🔒 Security: ✅ LGTM

The lib.rs change only adds module declarations and re-exports. It opens no new attack surface.


📖 AGENTS.md: ✅ LGTM

src/rust/AGENTS.md correctly covers how a Traced impl handles a detaching visit.


📋 Code Quality: ✅ LGTM

The lib.rs changes are correct: the module declarations for opaque and typed_promise, and the re-exports of Promise, PromiseArgument, PromiseResolver, PromiseValue, TracedPromise and TracedPromiseResolver.

The code these exports rely on holds up:

  • The detaching visit gets no C++ visitor, because as_ffi() returns None.
  • unwrap_opaque checks the value's type on both the C++ and Rust sides, and detaches the value it takes.
  • Every wrapping ToJS implementation forwards to_js_with_creator.

⚡ Performance: ✅ LGTM

No performance concerns.


📝 Documentation: ✅ LGTM

The README updates describe the new behaviour accurately.


Reviewed commit: 5e78b8a6

Rust JSG method parameter and return types must implement TypeInfo.
jsg::Promise<'s, T> now describes Promise<T>, as C++ describes
jsg::Promise<T>, and the test type CreatorOf describes an unknown
value.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of 5a29e7a4.

This review, of 249e424c

✅ Approved — No defects found. The TypeInfo impl for typed promises and the creator tests are correct, and the earlier as_ffi() concern is fixed.

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


✅ All checks passed

🔒 Security: ✅ LGTM

  • Opaque unwrapping checks the Wrappable's runtime type before it downcasts, so JavaScript cannot force a bad cast.
  • A detaching visit no longer exposes a null C++ visitor, because as_ffi() returns None for it.

📖 AGENTS.md: ✅ LGTM

src/rust/AGENTS.md correctly covers how a Traced impl handles a detaching visit.


📋 Code Quality: ✅ LGTM

  • src/rust/jsg/typed_promise.rs: TypeInfo builds Type::Promise(Box::new(T::describe(cx))). So Promise<()> describes Promise<void> and Promise<v8::Value> describes Promise<any>, which matches the existing v8::Promise description and the README.
  • src/rust/jsg-test/tests/to_js_creator.rs: CreatorOf implements both ToJS and TypeInfo. The tests cover direct, fallible, optional, container, injected-this, property, wildcard and static-method callbacks.

⚡ Performance: ✅ LGTM

Each typed-promise reaction adds a constant amount of work: one extra reaction and one opaque wrap or unwrap.


📝 Documentation: ✅ LGTM

The README updates accurately describe typed promises, creators and detaching visits.


Reviewed commit: 249e424c

@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

The generated output of @cloudflare/workers-types matches the snapshot in types/generated-snapshot 🎉

# Conflicts:
#	src/rust/jsg/README.md

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Superseded by the review of 978389e1.

This review, of 5a29e7a4

✅ Approved — No defects found. The only change since the last review is a clean README merge, and the earlier as_ffi() concern stays fixed.

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


✅ All checks passed

🔒 Security: ✅ LGTM

  • unwrap_opaque checks the Wrappable's runtime type before it reads the value, and it takes the value with try_borrow_mut. JavaScript cannot force a bad cast, and taking the value a second time returns None.
  • A promise settled with a value that is not its own gets an internal error, not a panic or a mis-typed value.
  • A detaching visit no longer exposes a null C++ visitor, because as_ffi() returns None for it.

📖 AGENTS.md: ✅ LGTM

src/rust/AGENTS.md correctly describes how a Traced impl handles a detaching visit.


📋 Code Quality: ✅ LGTM

The README merge matches the code: as_ffi() returns Option, and Traced impls handle None for a detaching visit.


⚡ Performance: ✅ LGTM

Each typed-promise reaction adds a constant amount of work: one extra reaction and one opaque wrap or unwrap.


📝 Documentation: ✅ LGTM

The README updates accurately describe typed promises, creators and detaching visits.


Reviewed commit: 5a29e7a4

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Approved — No defects found. The only change since the last review is a clean README merge, and the earlier as_ffi() concern stays fixed.

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


✅ All checks passed

🔒 Security: ✅ LGTM

  • unwrap_opaque checks the Wrappable's runtime type before it reads the value, and it takes the value with try_borrow_mut. JavaScript cannot force a bad cast, and taking the value a second time returns None.
  • A promise settled with a value that is not its own gets an internal error, not a panic or a mis-typed value.
  • A detaching visit no longer exposes a null C++ visitor, because as_ffi() returns None for it.

📖 AGENTS.md: ✅ LGTM

src/rust/AGENTS.md correctly describes how a Traced impl handles a detaching visit.


📋 Code Quality: ✅ LGTM

The README merge matches the code: as_ffi() returns Option, and Traced impls handle None for a detaching visit.


⚡ Performance: ✅ LGTM

Each typed-promise reaction adds a constant amount of work: one extra reaction and one opaque wrap or unwrap.


📝 Documentation: ✅ LGTM

The README updates accurately describe typed promises, creators and detaching visits.


Reviewed commit: 978389e1 — same changes as 5a29e7a4, so this is that commit's review (no new review was run; line numbers are as of 5a29e7a4)

@bartlomieju
bartlomieju merged commit d85a6b0 into main Nov 3, 2026
36 of 39 checks passed
@bartlomieju
bartlomieju deleted the biwanczuk/rust-jsg-typed-promise branch November 3, 2026 13:36
bartlomieju added a commit that referenced this pull request Nov 4, 2026
A #[jsg_struct] field can now hold a JavaScript value, as a C++
JSG_STRUCT field of type jsg::JsRef<T> does. Such a field is a
jsg::v8::TracedGlobal<M>, which now implements Type, ToJS and FromJS
and converts as a v8::Local<'s, M> does:

- TracedGlobal<Value> takes any value, and a missing property reads as
  undefined, as with jsg::JsRef<jsg::JsValue>.
- TracedGlobal<Object> (and the other markers with a FromJS for their
  Local) takes only a value of that type, with the Local's TypeError
  ("Expected Object but got number").
- Converting to JavaScript gives back the value itself.

The macro needed no change: it already converts each field through its
own type and traces every field. So a struct with such a field holds GC
references, and a resource that keeps it traces the value, so a cycle
through it is collected.

Porting MemoryCache (#8066) needs this. Its fallback produces a
CacheValueProduceResult, whose value is a jsg::JsRef<jsg::JsValue>.
The Rust port reads that object by hand today. With this change, and
with typed promises (#8153), it can be a struct carried by a
jsg::Promise<'s, T>. That needs a 'static T, so the field is a
TracedGlobal and not a Local with the struct's lifetime.

Tests cover keeping the value's identity (with and without
fast_jsg_struct), any value and missing properties, a rejected
non-object, a struct kept past the scope it was converted in, and the
collection of a cycle through such a field. No JS-visible change;
nothing outside tests uses this yet.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants