Repository navigation
Rust JSG: typed promises - #8153
Conversation
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 Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
guybedford
left a comment
There was a problem hiding this comment.
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
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.
There was a problem hiding this comment.
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()returnsNonefor it, which removes the null-visitor hazard. - Pending exceptions:
attach_opaque_wrapperstill checksexceptionPending().
📖 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,TracedGlobalandCppRefmatch the existing strong/weak and parent bookkeeping. as_ffi(): it now returnsOption, and its caller handlesNone.to_js_with_creator: every wrappingToJSimpl and macro-generated callback forwards it.- Typed promises: the
then/catchvariants 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
There was a problem hiding this comment.
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()returnsNone. unwrap_opaquechecks the value's type on both the C++ and Rust sides, and detaches the value it takes.- Every wrapping
ToJSimplementation forwardsto_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.
There was a problem hiding this comment.
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()returnsNonefor 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:TypeInfobuildsType::Promise(Box::new(T::describe(cx))). SoPromise<()>describesPromise<void>andPromise<v8::Value>describesPromise<any>, which matches the existingv8::Promisedescription and the README.src/rust/jsg-test/tests/to_js_creator.rs:CreatorOfimplements bothToJSandTypeInfo. 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
|
The generated output of |
# Conflicts: # src/rust/jsg/README.md
There was a problem hiding this comment.
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_opaquechecks the Wrappable's runtime type before it reads the value, and it takes the value withtry_borrow_mut. JavaScript cannot force a bad cast, and taking the value a second time returnsNone.- 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()returnsNonefor 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
There was a problem hiding this comment.
✅ 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_opaquechecks the Wrappable's runtime type before it reads the value, and it takes the value withtry_borrow_mut. JavaScript cannot force a bad cast, and taking the value a second time returnsNone.- 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()returnsNonefor 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)
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.
Adds
jsg::Promise<'s, T>, the counterpart of C++ JSG'sjsg::Promise<T>: a promise that carries a Rust value, which need nothave a JavaScript form. It comes with
PromiseResolver<'s, T>, thepersistent
TracedPromise<T>andTracedPromiseResolver<T>forresource fields, and
Lock::eval_now(), the counterpart ofLock::evalNow().The untyped
Local<v8::Promise>stays the counterpart ofJsPromise.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:
value, as by
wrapOpaque(). JavaScript never sees it.ToJS), the promise becomes that of areaction that converts the value, as
PromiseWrapper::wrap()doeswith
thenWrap(). It is marked as handled if the typed promise was.FromJS), a promise gets one reaction thatconverts its value, as
thenUnwrap()does. A value of the wrong typerejects 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<()>isjsg::Promise<void>andPromise<v8::Value>isjsg::Promise<jsg::Value>, carried asundefinedand as theJavaScript value itself.
then,catchandthen_or_catchconsume it, and one reaction takes the value out of its wrapper.
Callbacks capture nothing, as those of
Local<v8::Promise>::then.then_promise,catch_promiseandthen_or_catch_promisetakecallbacks that return a promise, which the returned promise follows,
as C++ JSG's
then()chains a continuation that returns one.which a replaced
Promise.prototype.thencan do whenresolve_with_promise()resolves one promise with another, rejectsthe reaction with an internal error, where C++ JSG fails a
KJ_ASSERT.The
Uof the promise thatthenreturns is the projectionU::Value<'a>of the callback's return type, so rustc infers it fromwhere 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 itsconversion 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.
ToJSgetsto_js_with_creator(), which defaults toto_js(). Thecallbacks that
#[jsg_method], the property macros and#[jsg_wildcard_property]generate pass the receiver for an instancemember and
Nonefor a static one, as C++ JSG does.Promisekeeps thecreator 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 andTracedGlobals its value holds weak, for the wrapper to trace. Areaction would then get a
jsg::Rcthat, 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::Refhas no such problem: the move makes it strongagain, with no parent.
GcVisitorgets a detaching visit that does thesame for a value its owner no longer holds, through the value's own
Traced::trace:jsg::Rcbecomes strong again and forgets its parent.TracedGloballets go of its traced reference and makes its stronghandle strong.
Ref<T>rebuilds its C++jsg::Refin place, since amoved one keeps the parent of its old location.
unwrap_opaque()detaches every value it takes. ATracedimpl thatvisits through
GcVisitor::as_ffi()must checkGcVisitor::is_detaching().Also:
Tracedis removed from the zero-sized V8 marker types, such asv8::Numberandv8::Uint8Array, which have no value to trace. Atyped promise of a marker would otherwise carry the marker, not a
handle, and nothing used these impls.
Local<v8::Promise>::has_handler(), V8'sHasHandler().as C++ JSG's
isGcVisitable<T>()decides.