Repository navigation
Generate Typescript types for Rust JSG Bindings - #8077
Conversation
|
This pull request's reviews are posted as pull request reviews: see the review of |
|
Since last review: 2 resolved, 0 still open, 0 new. Not re-run: kj-style (no author changes in their files since the last review) Reviewed commit: b8b3d091 · github run |
b8b3d09 to
3b8788e
Compare
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #8077 +/- ##
==========================================
- Coverage 68.46% 68.45% -0.01%
==========================================
Files 731 732 +1
Lines 191130 191548 +418
Branches 29842 29871 +29
==========================================
+ Hits 130854 131124 +270
- Misses 42785 42916 +131
- Partials 17491 17508 +17 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
3b8788e to
a884f68
Compare
7d39443 to
6123299
Compare
guybedford
left a comment
There was a problem hiding this comment.
LGTM, this is a great start in the right direction to iterate on. Running the same members() registration for both template creation and RTTI is a nice way to keep the types in line with what each resource registers under a given set of flags.
da05ca2 to
7e5be9c
Compare
There was a problem hiding this comment.
Superseded by the review of
17a18708.
This review, of 7e5be9c5
💬 Approved with comments — Nothing changed since the last review is unsafe to merge. One INFO note: a v8::Local<v8::BigInt> parameter is declared more permissively than the runtime accepts, and nothing uses it as a parameter yet.
Findings: 1 info (1 is an inline comment on the diff)
Not opened by the correctness review: 4 changed files it was meant to read
src/rust/jsg-cpp/ffi.rssrc/rust/jsg/lib.rssrc/workerd/io/io-context/BUILD.bazeltypes/src/generator/type.ts
The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.
📋 Code Quality: 💬 1 info
One INFO note on how v8::BigInt is described as a parameter; everything else is consistent.
Recommendation: 💬 Optional Nits
- [INFO] A
v8::Local<v8::BigInt>parameter is declarednumber | bigint, but conversion accepts only a BigInt. (src/rust/jsg/rtti.rs:554)
View full review
CppResource::fully_qualified_name: every implementor implements it. TheTypeInfo for Ref<T>impl refers to the C++ class's description by that name.Resource::members(registry, flags),add_builtinandaddBuiltinModule: every caller and override uses the new forms.rtti.c++: the Rust RTTI context is encoded once and appended.setWithCaveatscopies the data, so the reader's lifetime is safe.- Macros: the offsets for
thisand the lock are correct. Duplicate parameter names are a compile error. Only public struct fields are described, which matches whatto_jsandfrom_jsconvert. - One note:
v8::Local<v8::BigInt>is described asjsg::JsBigInt(number | bigint), which is wider than what conversion accepts when it is a parameter.
✅ All other checks passed
🔒 Security: ✅ LGTM
The change describes types for the RTTI export and changes how module exports are registered. No untrusted input reaches new code, and it does not touch authentication or authorization.
📖 AGENTS.md: ✅ LGTM
No new issues. One note from earlier reviews is still open.
⚡ Performance: ✅ LGTM
The runtime cost does not change. Only the RTTI exporter builds type descriptions.
📝 Documentation: ✅ LGTM
The README updates match the members(registry, flags) API, the module callback shape, ts_root and the TypeInfo mappings.
Reviewed commit: 7e5be9c5
7e5be9c to
17a1870
Compare
There was a problem hiding this comment.
Superseded by the review of
dcc716be.
This review, of 17a18708
💬 Approved with comments — The changes to src/rust/jsg/rtti.rs since the last review introduce no new problems. One INFO note remains: a v8::Local<v8::BigInt> parameter is declared more permissively than the runtime accepts, but nothing takes one as a parameter yet.
Findings: 1 info
Not opened by the correctness review: 3 changed files it was meant to read
src/rust/jsg-cpp/ffi.rssrc/rust/jsg/lib.rssrc/workerd/io/io-context/BUILD.bazel
The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.
📋 Code Quality: 💬 1 info
One INFO note remains open. The changes to rtti.rs introduce no new problems.
Recommendation: 💬 Optional Nits
- [INFO] A
v8::Local<v8::BigInt>parameter is declarednumber | bigint, but conversion accepts only a BigInt. (src/rust/jsg/rtti.rs:555)
View full review
src/rust/jsg/rtti.rs:555(primitive!(v8::BigInt, Type::BigInt)) is encoded asjsg::JsBigInt(line 297), and the generator declares that type asnumber | bigint. When the type is a parameter, conversion accepts only a real BigInt, so the declaration is wider than what the runtime accepts. @edmundhung [approver] raised the same point. Nothing takes this type as a parameter yet, so it does not block the change.
The other changes in this revision look correct and match the coverage in rtti-test.rs and rust.spec.ts: the i64/u64 handling, the interning in Context::structure, the registry-based member description and the guard against nested-type cycles in write_structure.
✅ All other checks passed
🔒 Security: ✅ LGTM
The change describes types for the RTTI export and changes how module exports are registered. No untrusted input reaches the new code.
📖 AGENTS.md: ✅ LGTM
The updates to src/rust/AGENTS.md and types/AGENTS.md match the change.
⚡ Performance: ✅ LGTM
The new code runs only in the RTTI export, not at request time. A guard stops nested structures from cycling, and the interning lookups take constant time.
📝 Documentation: ✅ LGTM
The README updates match the members(registry, flags) API, the module callback shape, ts_root and the TypeInfo mappings.
Reviewed commit: 17a18708
17a1870 to
dcc716b
Compare
There was a problem hiding this comment.
Superseded by the review of
ca6dceb1.
This review, of dcc716be
✅ Approved — Nothing changed since the last review has a problem. The only open item is an earlier informational note about how a BigInt parameter is declared, and nothing uses that type as a parameter yet.
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 changed code builds type descriptions for the RTTI export. No untrusted input reaches it.
📖 AGENTS.md: ✅ LGTM
The updates to src/rust/AGENTS.md and types/AGENTS.md match the change.
📋 Code Quality: ✅ LGTM
Checked and correct:
- Module registration: the trampoline converts the module's exports with
callback(lock).and_then(|e| e.to_js(lock)). Errors from the callback and from the conversion are both still thrown to the importer. - C++ registry:
RustModuleRegistryusesif constexprto choose between describing a module and adding it to a runtime registry. Runtime registries ignore the describe pointer. - RTTI export merge: the Rust groups and modules are appended to the export, and both counts include them. The message is checked to be a whole number of Cap'n Proto words before it is copied into a word-aligned array.
- Structure interning:
Context::structureadds a type before it visits the type's members, so resources that refer to each other are handled.write_structurestops when a nested type refers back to itself. - Build wiring: the
proc_macro_depsadded insrc/workerd/io/io-context/BUILD.bazeland thefully_qualified_namerequirement insrc/rust/jsg-cpp/ffi.rsmatch how the code uses them.
One earlier note is still open: a v8::Local<v8::BigInt> parameter is declared wider than the runtime accepts (src/rust/jsg/rtti.rs:557).
⚡ Performance: ✅ LGTM
The new code runs only in the RTTI export, at build time, not when a request is handled. Interning uses hash map lookups, and the cycle guard means describing nested structures always finishes.
📝 Documentation: ✅ LGTM
The READMEs match the code: the members(registry, flags) API, the module callback shape, ts_root and the TypeInfo mappings.
Reviewed commit: dcc716be
Resource::members adds each member to a registry, members(registry, flags), instead of returning a Vec<Member>, like the Registry parameter of C++ registerMembers. Generated member factories return `impl jsg::MemberDefinition`, which template creation builds into a Member; a hand-built Member is also a MemberDefinition. This prepares for RTTI: an RTTI registry can run the same registration code and collect type descriptions instead of callbacks, so TypeScript declarations follow the members a resource registers under a given set of compatibility flags.
dcc716b to
ca6dceb
Compare
There was a problem hiding this comment.
Superseded by the review of
4dab5f49.
This review, of ca6dceb1
✅ Approved — Nothing changed since the last review has a problem. The only open item is an earlier informational note about how a BigInt parameter is declared, and nothing uses that type as a parameter yet.
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 changed code builds type descriptions for the RTTI export. No untrusted input reaches it.
📖 AGENTS.md: ✅ LGTM
The updates to src/rust/AGENTS.md and types/AGENTS.md match the change.
📋 Code Quality: ✅ LGTM
Checked and correct:
- Module registration: the trampoline converts the module's exports with
callback(lock).and_then(|e| e.to_js(lock)). Errors from the callback and from the conversion are both still thrown to the importer. - C++ registry:
RustModuleRegistryusesif constexprto choose between describing a module and adding it to a runtime registry. Runtime registries ignore the describe pointer. - RTTI export merge: the Rust groups and modules are appended to the export, and both counts include them. The message is checked to be a whole number of Cap'n Proto words before it is copied into a word-aligned array.
- Structure interning:
Context::structureadds a type before it visits the type's members, so resources that refer to each other are handled.write_structurestops when a nested type refers back to itself. - Build wiring: the
proc_macro_depsadded insrc/workerd/io/io-context/BUILD.bazeland thefully_qualified_namerequirement insrc/rust/jsg-cpp/ffi.rsmatch how the code uses them.
One earlier note is still open: a v8::Local<v8::BigInt> parameter is declared wider than the runtime accepts (src/rust/jsg/rtti.rs:557).
⚡ Performance: ✅ LGTM
The new code runs only in the RTTI export, at build time, not when a request is handled. Interning uses hash map lookups, and the cycle guard means describing nested structures always finishes.
📝 Documentation: ✅ LGTM
The READMEs match the code: the members(registry, flags) API, the module callback shape, ts_root and the TypeInfo mappings.
Reviewed commit: ca6dceb1 — same changes as dcc716be, so this is that commit's review (no new review was run; line numbers are as of dcc716be)
Add jsg::TypeInfo, which describes a binding type's JavaScript representation in the shared rtti.capnp schema without an isolate. #[jsg_resource], #[jsg_struct] and #[jsg_oneof] generate it; built-in conversion types implement it by hand, as custom conversion types must. A resource is described with the members it registers. Member factories return a definition that can both build the member and describe it, and RTTI runs Resource::members with its own registry under the compatibility flags of the jsg::rtti::Context, as C++ runs registerMembers with the RTTI builder's flags. Template creation never runs the descriptions, and RTTI never builds callbacks. As in C++, a nested type is described with its whole structure, through which the generator reaches it, and inspect properties, wildcard properties and other hand-built members have no description. The Context interns named types by TypeId before describing their members, so shared and recursive types are emitted once. Their type names identify them to the generator, so two types with one type name are rejected. Declaration names follow `name = "..."` separately, and ts_root marks a root of the ambient declarations, like JSG_TS_ROOT. Parameter names are camelCased, lose unused-parameter underscores and escape TypeScript reserved words; parameters whose names collide are rejected. Cover the mappings with an end-to-end test that runs a Rust fixture's RTTI through the types/ generator and type-checks the result. The fixture runs as test data in the target configuration, to avoid building V8 again as an exec-configuration tool. Teach the formatter to cover Rust sources under types/.
The RTTI export could not describe Rust builtin modules: they register an opaque callback, and its EncoderModuleRegistryImpl overload for module callbacks does nothing. Have module callbacks return their exports resource, jsg::Result<Rc<T>>, which registration converts, so the exports type is known statically. Registration passes the C++ registry a second function pointer next to the callback, which describes T in a jsg::rtti::Context. The RustModuleRegistry adapter hands it to registries that define addRustBuiltinModule, which only the workerd:rtti encoder does, and runtime registries ignore it. The encoder thus collects every module's types in one Context, under the export's compatibility flags, without running module code, and merges the encoded groups and modules with the C++ ones. Callbacks still capture nothing, and an error one returns is still thrown to the importer. api-rtti-test checks that the export discovers node-internal:dns, its exports type and the structs that type returns.
ca6dceb to
4dab5f4
Compare
There was a problem hiding this comment.
💬 Approved with comments — Nothing changed since the last review has a problem. The only open item is an earlier INFO about how a BigInt parameter is declared, which is deferred to a follow-up and affects no existing API.
Findings: 1 info (1 is an inline comment on the diff)
The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.
📋 Code Quality: 💬 1 info
No new problems. One earlier INFO about BigInt parameter typing is still open and deferred to a follow-up.
Recommendation: 💬 Optional Nits
- [INFO] A
v8::Local<v8::BigInt>parameter is declarednumber | bigint, but conversion accepts only a BigInt. Deferred by @nathanwhit [author] to a follow-up as an existing generator bug that also affects C++; nothing takes this type as a parameter yet. (src/rust/jsg/rtti.rs:554)
View full review
Checked at this commit and correct:
- Module trampoline: errors from the callback and from the
to_jsconversion are both thrown to the importer. Runtime registries ignore the describe pointer, and theif constexprbranch picks the exporter correctly. - RTTI export merge:
registerModulesruns before groups are counted, so the Rust groups and modules are included in both counts. The size check comes before the word-aligned copy. - Macro expansion:
jsg_structdescribes the same public fields it projects to JS.describe_argsskipsthisand the lock in the same way the callbacks do, and colliding parameter names are rejected at compile time, which a compile test covers. Propertyreadonlyandprototypesettings match the generated member factory. - Cycle handling: a structure is interned before its members are visited, and
write_structurestops when a type nests itself. - Generator test: the assertions in
types/test/generator/rust.spec.tsmatch the fixture intypes/rtti-fixture/main.rs.
Still open: a v8::Local<v8::BigInt> parameter is declared wider than the runtime accepts. @nathanwhit [author] says this is an existing generator bug that also affects C++ bindings and will be fixed in a follow-up.
✅ All other checks passed
🔒 Security: ✅ LGTM
The changed code builds type descriptions for the RTTI export at build time, and no untrusted input reaches it. The byte copy in src/workerd/api/rtti.c++ is guarded by a check that the message is a whole number of Cap'n Proto words.
📖 AGENTS.md: ✅ LGTM
The updates to src/rust/AGENTS.md and types/AGENTS.md match the change.
⚡ Performance: ✅ LGTM
The new code runs only during the RTTI export at build time, never while a request is handled.
📝 Documentation: ✅ LGTM
The updated src/rust/jsg-macros/README.md matches the macro behaviour at this commit.
Reviewed commit: 4dab5f49
The C++ Hyperdrive stays registered with the isolate, so the RTTI export describes it while the RUST_HYPERDRIVE autogate makes bindings of the Rust one. The parity test pins what runs, but not what only the types say, such as argument and return types. rtti-test.c++ compares the C++ jsg::rtti::Builder's Structure for api::Hyperdrive with the one the Rust Hyperdrive describes through jsg::TypeInfo (#8077), which a testonly bridge crate, rtti-test-bridge, encodes. Both are compared as the TypeScript generator reads them: without the fully qualified name and tsName, the C++ jsg::Lock argument, the C++ type names of strings and numbers, fastApiCompatible and argNames, and with members in name order, since the Rust macro registers methods before properties. Neither order is observable in JS, and the generated types take Hyperdrive's member order from types/defines/hyperdrive.d.ts. The hyperdrive crate now lists its sources, so that it does not compile the bridge.
Motivation
@cloudflare/workers-typesis generated from the RTTI export (workerd:rtti), which only knows about C++ bindings. Rust modules register a callback the exporter can't inspect, and its overload for them is aTODOthat does nothing. As more APIs are written in Rust, they need to show up in the generated types like C++ ones do.Design
1. Members are added to a registry
To describe a resource, the RTTI export needs the list of members that the resource's JavaScript class actually gets.
Resource::membersnowadds each member to a registry instead of returning a list, like the
Registryparameter of C++registerMembers:Template creation and the RTTI export run the same
members, each with its own registry. Template creation keeps thecallbacks and never builds a type description; RTTI keeps the type descriptions and never builds a callback. So the
TypeScript declarations match what each resource registers under the export's compatibility flags, including choices like
those above.
2.
TypeInfodescribes Rust typesjsg::TypeInfodescribes how a Rust type looks in JavaScript, using the existingrtti.capnpschema and without an isolate.#[jsg_resource],#[jsg_struct]and#[jsg_oneof]generate the implementation; built-in and custom conversion types implement it by hand. Thetypes/generator is unchanged.Here are the type translations:
Option<T>T | undefined(optional)jsg::Nullable<T>T | null(input also readsundefinedasnull; the parameter is required)jsg::NullOrUndefined<T>,jsg::Lenient<T>T | null | undefined(optional)Vec<T>,&[T]T[](numbers included)jsg::Dict<V>Record<string, V>v8::Local<v8::Uint8Array>and other typed arraysUint8Array, etc.Result<T, E>TSystemTimeDate(arguments also acceptnumber)v8::Local<v8::Date>Datei64,u64,v8::Local<BigInt>number | bigint(as C++ describesint64_t)v8::Local<Promise>Promise<any>(arguments also accept plain values, as in C++)3. Module types are included in the export
To describe a module, the exporter needs its exports type without running the module. So module callbacks now return the exports resource, and registration converts it to JS:
Callbacks still capture nothing, and an error a callback returns is still thrown to the importer.
Registration passes the C++ registry a second function pointer next to the callback, which describes the exports type.
RustModuleRegistryuses anif constexprto check whether the wrapped registry hasaddRustBuiltinModule; only the exporter does.Commits
MemberRegistry. Runtime only; contains the API change.TypeInfo.Not in this PR
JSG_TS_OVERRIDE/JSG_TS_DEFINEequivalents: a follow-up PR.