Skip to content

Add Rust interop for Fetcher and DurableObjectClass - #8617

Merged
bartlomieju merged 4 commits into
mainfrom
biwanczuk/rust-jsg-cpp-fetcher
Nov 20, 2026
Merged

bartlomieju merged 4 commits into
mainfrom
biwanczuk/rust-jsg-cpp-fetcher

Conversation

@bartlomieju

Copy link
Copy Markdown
Collaborator

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.

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.

@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 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 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.

Shims look right to me and the tests pass locally. Two nits and one question on channel lifetime inline, none blocking.

Comment thread src/workerd/api/channel-interop/ffi.rs Resolved
Comment thread src/workerd/api/channel-interop/ffi.rs Resolved
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.
@bartlomieju
bartlomieju marked this pull request as ready for review November 19, 2026 13:12

@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 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

@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 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_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

  • Enum layout: the #[repr(i32)] shared enums match the C++ enums, which use the default int underlying type.
  • Channel lifetime: ScopedChannel<'s, C> is !Send/!Sync and tied to the lock's lifetime. Only require_allows_transfer returns a bare KjRc.
  • IoContext lookup: currentWithId moved 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

@bartlomieju
bartlomieju merged commit b5f552c into main Nov 20, 2026
23 checks passed
@bartlomieju
bartlomieju deleted the biwanczuk/rust-jsg-cpp-fetcher branch November 20, 2026 10:01
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.

2 participants