Repository navigation
Add Rust interop for Fetcher and DurableObjectClass - #8617
Conversation
Rust APIs can't take or return service bindings or Durable Object classes yet: `Fetcher` and `DurableObjectClass` are C++ JSG resources, and nothing exposes them to Rust. This adds per-type `jsg-cpp` shims for both, in a new `src/workerd/api/channel-interop` package. Following `src/rust/jsg/README.md` safety rule 3, the shims live with the API code rather than in Rust JSG. This is the first production use of `jsg-cpp`. Planned users: the Rust ports of the Worker Loader binding and the container binding. Also two in-progress ports that currently carry their own `Fetcher` shims: the Rust `ExecutionContext` (`ctx.mapVirtualHost`) and an internal project's cache-purge binding. Both will switch to this package once it lands. ### API Rust takes and returns these as `jsg_cpp::Ref<Fetcher>` and `jsg_cpp::Ref<DurableObjectClass>`. They work as method parameters, `#[jsg_struct]` fields, `Option`, `Nullable` and `Vec`. Unwrapping goes through the isolate's `TypeHandler`, so subclasses such as `ExtendedFetcher` are accepted, with the pointer adjusted to the base class, and anything else is rejected as C++ `jsg::Ref` parameters do. - `Fetcher::subrequest_channel()` returns its `SubrequestChannel`. - `Fetcher::from_channel()` wraps a `SubrequestChannel` in a new `Fetcher`, with the defaults `worker-loader.c++` uses. - `Fetcher::from_channel_number(channel, RequiresHostAndProtocol, InHouse)` is the constructor most bindings use: KV, R2, cache purge, `global-scope`, and the env builders. Both options are Rust enums. - `Fetcher::map_virtual_host(port)` forwards to C++ `Fetcher::mapVirtualHost`, which `ctx.mapVirtualHost` and `cloudflare:workers` also call. - `DurableObjectClass::channel()` returns its `ActorClassChannel`, as `ctx.facets.get()` needs. - `DurableObjectClass::from_channel()` wraps one in a new class, as Worker Loader's `getDurableObjectClass()` and the `ctx.exports` loopback classes need. - `require_allows_transfer()` on both channel types. The C++ channel types are exposed through aliases and held as `kj_rs::KjRc`. `KjRc` is neither `Send` nor `Sync`, so a channel can't move to another thread, into an `await_io` future, or into resource state. A compile test asserts this with `static_assertions`. Dropping a channel after its request has ended is safe, as in C++. Rust code holds an `IoContext` by id. To get from that id back to the C++ `IoContext` the shims need, a new `io-context:current-with-id` library adds `currentWithId()`, visible to `//src/workerd/api` only. Ids come from a process-unique counter, so a stale id fails a `KJ_REQUIRE` instead of matching a newer context. ### Not included yet - Creating a `Fetcher` from a `Fetcher::OutgoingFactory` (dynamic dispatch, container `getTcpPort`, facets): deferred until a port needs it. - What Worker Loader needs beyond this: a subrequest channel with no outbound connection, and `WorkerStubChannel::getEntrypoint` / `getActorClass`. - Channel tokens.
There was a problem hiding this comment.
Superseded by the review of
5500c954.
This review, of 4c148a2d
✅ Approved — No correctness, security, performance or documentation issues were found in the new Fetcher/DurableObjectClass interop shims or in the currentWithId refactor.
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
No security issues found. currentWithId rejects a stale or foreign IoContext id. Unwrapping goes through the TypeHandler, so only Fetcher / DurableObjectClass (and their subclasses) are accepted, and the transfer checks forward to the existing C++ implementations.
📖 AGENTS.md: ✅ LGTM
No AGENTS.md issues found.
📋 Code Quality: ✅ LGTM
No code quality issues found.
⚡ Performance: ✅ LGTM
No performance issues found.
📝 Documentation: ✅ LGTM
No documentation issues found.
Reviewed commit: 4c148a2d
guybedford
left a comment
There was a problem hiding this comment.
Shims look right to me and the tests pass locally. Two nits and one question on channel lifetime inline, none blocking.
C++ documents an IoChannelFactory channel as an I/O object, valid only in the IoContext it was made in, and keeps one past its request only once requireAllowsTransfer() has allowed it. Rust got a bare KjRc, which a thread-local could keep and hand to Fetcher::from_channel() in a later request. Fetcher::subrequest_channel() and DurableObjectClass::channel() now return a ScopedChannel, branded with the lock's lifetime, so it can't outlive the lock it was obtained with. Its require_allows_transfer() returns the KjRc that may be kept, and ScopedChannel::new() scopes one to the current request again. from_channel() takes a ScopedChannel. Compile tests check both sides. The options of Fetcher::from_channel_number() now cross the bridge as shared enums rather than bools: RequiresHostAndProtocol is bound to the C++ enum, and InHouse is a new enum in ffi.h. The tests also cover a Durable Object class whose transfer C++ refuses.
There was a problem hiding this comment.
Superseded by the review of
34899d7a.
This review, of 5500c954
✅ Approved — No findings. The latest commit ties channels to their request as C++ does, makes the two Fetcher options typed enums across the bridge, and tests the refusal path for class channels.
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
Only require_allows_transfer hands back a bare KjRc, and only after the C++ requireAllowsTransfer() check passes. from_channel accepts only a ScopedChannel. currentWithId rejects a stale or mismatched IoContext id with KJ_REQUIRE.
📖 AGENTS.md: ✅ LGTM
No AGENTS.md issues found.
📋 Code Quality: ✅ LGTM
The shared enums' layout matches the C++ enums. ScopedChannel is !Send/!Sync and tied to the lock's lifetime. currentWithId moved unchanged, with visibility limited to //src/workerd/api. The Bazel wiring, compile tests and C++ shims fit together, and errors go through callCpp / callCppForRef.
⚡ Performance: ✅ LGTM
Each shim call does a constant amount of work. currentWithId is one thread-local read and one id comparison.
📝 Documentation: ✅ LGTM
No documentation issues found.
Reviewed commit: 5500c954
There was a problem hiding this comment.
✅ Approved — No findings. The patches are unchanged since the last review, which found no issues, and the approver's lifetime concern is fixed in the code.
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
- Only
require_allows_transferhands back a bareKjRc, and only after the C++requireAllowsTransfer()check passes. from_channelaccepts only aScopedChannel.currentWithIdrejects a stale or mismatchedIoContextid withKJ_REQUIRE.
📖 AGENTS.md: ✅ LGTM
No AGENTS.md issues found.
📋 Code Quality: ✅ LGTM
- Enum layout: the
#[repr(i32)]shared enums match the C++ enums, which use the defaultintunderlying type. - Channel lifetime:
ScopedChannel<'s, C>is!Send/!Syncand tied to the lock's lifetime. Onlyrequire_allows_transferreturns a bareKjRc. - IoContext lookup:
currentWithIdmoved unchanged into its own library, visible only to//src/workerd/api. - Build and tests: the Bazel wiring avoids a dependency cycle. The C++ and compile tests cover acceptance, subclasses, rewrapping, the refusal paths for both channel types, GC tracing and dropping a channel after its request.
⚡ Performance: ✅ LGTM
Each shim call does a constant amount of work. currentWithId is one thread-local read and one id comparison.
📝 Documentation: ✅ LGTM
No documentation issues found.
Reviewed commit: 34899d7a
Rust APIs can't take or return service bindings or Durable Object
classes yet:
FetcherandDurableObjectClassare C++ JSG resources,and nothing exposes them to Rust. This adds per-type
jsg-cppshimsfor both, in a new
src/workerd/api/channel-interoppackage.Following
src/rust/jsg/README.mdsafety rule 3, the shims live withthe API code rather than in Rust JSG. This is the first production use
of
jsg-cpp.Planned users: the Rust ports of the Worker Loader binding and the
container binding. Also two in-progress ports that currently carry
their own
Fetchershims: the RustExecutionContext(
ctx.mapVirtualHost) and an internal project's cache-purge binding.Both will switch to this package once it lands.
API
Rust takes and returns these as
jsg_cpp::Ref<Fetcher>andjsg_cpp::Ref<DurableObjectClass>. They work as method parameters,#[jsg_struct]fields,Option,NullableandVec. Unwrappinggoes through the isolate's
TypeHandler, so subclasses such asExtendedFetcherare accepted, with the pointer adjusted to the baseclass, and anything else is rejected as C++
jsg::Refparameters do.Fetcher::subrequest_channel()returns itsSubrequestChannel.Fetcher::from_channel()wraps aSubrequestChannelin a newFetcher, with the defaultsworker-loader.c++uses.Fetcher::from_channel_number(channel, RequiresHostAndProtocol, InHouse)is the constructor most bindings use: KV, R2, cache purge,global-scope, and the env builders. Both options are Rust enums.Fetcher::map_virtual_host(port)forwards to C++Fetcher::mapVirtualHost, whichctx.mapVirtualHostandcloudflare:workersalso call.DurableObjectClass::channel()returns itsActorClassChannel, asctx.facets.get()needs.DurableObjectClass::from_channel()wraps one in a new class, asWorker Loader's
getDurableObjectClass()and thectx.exportsloopback classes need.
require_allows_transfer()on both channel types.The C++ channel types are exposed through aliases and held as
kj_rs::KjRc.KjRcis neitherSendnorSync, so a channel can'tmove to another thread, into an
await_iofuture, or into resourcestate. A compile test asserts this with
static_assertions. Droppinga channel after its request has ended is safe, as in C++.
Rust code holds an
IoContextby id. To get from that id back to theC++
IoContextthe shims need, a newio-context:current-with-idlibrary adds
currentWithId(), visible to//src/workerd/apionly.Ids come from a process-unique counter, so a stale id fails a
KJ_REQUIREinstead of matching a newer context.Not included yet
Fetcherfrom aFetcher::OutgoingFactory(dynamicdispatch, container
getTcpPort, facets): deferred until a portneeds it.
outbound connection, and
WorkerStubChannel::getEntrypoint/getActorClass.