Skip to content

Let Rust call JavaScript back later in its IoContext - #8672

Merged
bartlomieju merged 6 commits into
mainfrom
biwanczuk/rust-reentry-callback-stacked
Nov 20, 2026
Merged

bartlomieju merged 6 commits into
mainfrom
biwanczuk/rust-reentry-callback-stacked

Conversation

@bartlomieju

@bartlomieju bartlomieju commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

The motivation for this change is porting Worker Loader to Rust. C++
WorkerLoader::get() keeps the application's getCode() callback in a
weak reentry callback. When the runtime loads the dynamic Worker, it
calls getCode() and converts the WorkerCode it resolves into C++
objects that can't leave the IoContext's thread: channels, the
serialized env and the module content. This change adds the two
IoContext APIs that let the Rust port do the same.

IoContext::make_reentry_callback_weak() wraps C++
makeReentryCallbackWeak(). The ReentryCallback it returns runs a
Rust function in the IoContext that created it each time KJ calls it,
and the call waits for the future the function returns as part of the
request. IoContext::await_js_local() waits for a JavaScript promise as
await_js() does, but its conversion also gets the IoContext, and its
output doesn't have to be Send. It is the counterpart of C++
awaitJs(js, promise, func) when func builds KJ objects.

Both behave as their C++ counterparts do, because C++ does the work. The
callback holds the IoContext weakly, so it doesn't keep the request
alive or block a Durable Object's hibernation, and once the IoContext
is gone a call fails with the C++ errors. Each call runs inside C++
IoContext::run(), so exceptions, aborts and terminations are handled
as for C++ code. The function, its futures and the converted output
don't have to be Send, because C++ keeps them on the IoContext's
thread; the commits explain why that is sound, and debug builds assert
it for the converted output. Nothing in production calls these APIs yet,
so Workers see no change in behavior.

The tests cover calls from KJ, the weak hold of the IoContext
(including in a hibernating Durable Object), errors, terminations,
aborts and panics in the function, dropping the callback while a call is
in flight, and converting a Fetcher into a channel kept past its
request.

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.

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

Looks great, thanks. Two optional hardening suggestions inline.

Comment thread src/workerd/io/io-context/lib.rs Resolved
Comment thread src/workerd/io/io-context/lib.rs Resolved
IoContext::make_reentry_callback_weak() wraps
IoContext::makeReentryCallbackWeak(): the returned ReentryCallback<T>
runs a Rust function under a new lock in the creating context each time
it is called from KJ, and awaits the future the function returns. It
holds the context weakly, failing with the same errors as C++ once the
context is gone or the Durable Object is hibernating.

The callback is not Send. The function, its future and their output need
not be: C++ holds the function in the IoContext and runs and drops it on
its thread, KJ polls the future there, and the output reaches only the
call's future. So the output can hold C++ objects of that thread, as
WorkerLoader.get()'s will. 'static and the lock's lifetime keep handles
out of the function and its future.

What the function throws is caught in Rust, logged as uncaught and
tunneled, as run() does for C++ code. A termination is left pending and
propagated to IoContext::run() as JsExceptionThrown, through the one
throw the allowlist permits in ffi.c++, now shared with
io_context_await_io_and_run(), so run() handles it in its own order:
it leaves the limit enforcer's scope, fails with the exceeded limit or
the abort reason, and cancels the microtasks queued meanwhile.

TestFixture::setLimitsExceededOnLeavingJs() records an exceeded limit
only when the enforcer's enterJs() scope ends, as an enforcer that
measures CPU time over that scope does, so a test can pin that order.
IoContext::await_js_local() waits for a JavaScript promise as
await_js() does, but its conversion also gets the IoContext, and its
output need only be 'static: it can be a KjOwn<Frankenvalue>, a
KjRc<SubrequestChannel> or a C++ struct holding them, none of which is
Send. Nothing moves to another thread; the conversion, the future and
its output all stay on the IoContext's thread, hence "local". That is
what WorkerLoader.get()'s reentry callback needs to build a
DynamicWorkerSource from the WorkerCode that getCode() resolves, as C++
does with awaitJs(js, getCode(js), func).

The returned AwaitJsLocal<T> is an AwaitJs whose output is held in a
ThreadBound<T>, which claims Send so that the wait's shared state and
its sender can be reaction data. The output is created only by the
conversion, in a reaction that has taken its sender, which requires the
IoContext to be current; it is taken or dropped by the future, which is
neither Send nor Sync, or by the sender, which is always dropped on the
IoContext's thread. No reaction data or other traced state holds one,
so GC never visits or drops one. A reaction in another request fails
before the conversion runs, and the wait fails as never settled once
GC collects the reactions, as C++ awaitJs() behaves. The future can be
returned from a reentry callback's function as it is.

The make_reentry_callback_weak() example and its compile test now build
their non-Send output in the conversion.

io-context-test gains two cases: a reentry callback that takes a
Fetcher's channel through await_js_local(), which C++ receives as the
same channel, with the conversion given the creating IoContext (by
IoContext::as_ffi()); and a promise resolved from another request,
which never runs the conversion and fails the call with "Promise will
never complete." once GC collects the reactions. Compile tests pin that
the future is neither Send nor Sync and that the conversion captures
only data that is Copy and Send.
@bartlomieju
bartlomieju force-pushed the biwanczuk/rust-reentry-callback-stacked branch from 3d63348 to f78d0d7 Compare November 20, 2026 09:32
@bartlomieju
bartlomieju changed the base branch from biwanczuk/rust-jsg-cpp-fetcher to main November 20, 2026 09:38
@bartlomieju
bartlomieju changed the base branch from main to biwanczuk/rust-jsg-cpp-fetcher November 20, 2026 09:39
Base automatically changed from biwanczuk/rust-jsg-cpp-fetcher to main November 20, 2026 10:01
…y-callback-stacked

# Conflicts:
#	src/workerd/api/channel-interop/BUILD.bazel
#	src/workerd/api/channel-interop/channel-interop-test.c++
#	src/workerd/api/channel-interop/compile-tests/ok-channels-are-not-send.rs
#	src/workerd/api/channel-interop/ffi.c++
#	src/workerd/api/channel-interop/ffi.h
#	src/workerd/api/channel-interop/ffi.rs
#	src/workerd/api/channel-interop/lib.rs
#	src/workerd/api/channel-interop/test_bridge.rs
#	src/workerd/io/io-context/io-context-test.c++
@bartlomieju
bartlomieju marked this pull request as ready for review November 20, 2026 10:41
@bartlomieju
bartlomieju requested review from a team as code owners November 20, 2026 10:41

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

This review, of edd0ddc7

✅ Approved — No correctness, security, performance, documentation or AGENTS.md issues were found. The approver's two hardening suggestions (a thread-id debug assertion in ThreadBound, and a test that drops the callback while a call is in flight) are both 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

  • ThreadBound: The SAFETY argument for its unsafe impl Send holds. The value is created and taken only on the IoContext's thread, and AwaitJsLocal is !Send.
  • Reentry calls: Each call runs under IoContext::run(). A termination is rethrown through throwPendingToRun() rather than replaced by a JS exception, which follows the repository's rule.
  • JSG allowlist: The cpp-jsg-allowlist.txt entry matches the only C++ JSG use in ffi.c++.

📖 AGENTS.md: ✅ LGTM

The src/rust/AGENTS.md change is consistent with the repository's conventions.


📋 Code Quality: ✅ LGTM

I found no correctness, error-handling or test-coverage problems.

  • Callback signature: The ReentryCallback lambda in ffi.c++ matches what IoContext::makeReentryCallbackImpl expects.
  • Dropping the callback mid-call: This is sound because ioFunc is refcounted, and the new test pins it.
  • Error paths: Terminations, returned errors and panics in start_reentry each go down a separate path. A panic becomes a plain KJ assertion failure, so no JS exception is thrown into V8. Tests cover each path.
  • ThreadBound: The unsafe impl Send argument holds, and the debug assertion on the creating thread now guards it.
  • Test fixture: The MockLimitEnforcer::enterJs change only adds behaviour when limitsExceededOnLeavingJs is set, so existing tests are unaffected.

⚡ Performance: ✅ LGTM

No performance concerns. Nothing in production calls these APIs yet.


📝 Documentation: ✅ LGTM

The documentation updates in src/rust/jsg/README.md and src/rust/AGENTS.md match the code.


Reviewed commit: edd0ddc7

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

This review, of b8a4e235

✅ Approved — No correctness, security, performance, documentation or AGENTS.md issues were found. The approver's two hardening suggestions (a thread-id debug assertion in ThreadBound, and a test that drops the callback while a call is in flight) are both 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

  • ThreadBound: The SAFETY argument for its unsafe impl Send holds. The value is created and taken only on the IoContext's thread, and AwaitJsLocal is !Send.
  • Reentry calls: Each call runs under IoContext::run(). A termination is rethrown through throwPendingToRun() rather than replaced by a JS exception, which follows the repository's rule.
  • JSG allowlist: The cpp-jsg-allowlist.txt entry matches the only C++ JSG use in ffi.c++.

📖 AGENTS.md: ✅ LGTM

The src/rust/AGENTS.md change is consistent with the repository's conventions.


📋 Code Quality: ✅ LGTM

I found no correctness, error-handling or test-coverage problems.

  • Callback signature: The ReentryCallback lambda in ffi.c++ matches what IoContext::makeReentryCallbackImpl expects.
  • Dropping the callback mid-call: This is sound because ioFunc is refcounted, and the new test pins it.
  • Error paths: Terminations, returned errors and panics in start_reentry each go down a separate path. A panic becomes a plain KJ assertion failure, so no JS exception is thrown into V8. Tests cover each path.
  • ThreadBound: The unsafe impl Send argument holds, and the debug assertion on the creating thread now guards it.
  • Test fixture: The MockLimitEnforcer::enterJs change only adds behaviour when limitsExceededOnLeavingJs is set, so existing tests are unaffected.

⚡ Performance: ✅ LGTM

No performance concerns. Nothing in production calls these APIs yet.


📝 Documentation: ✅ LGTM

The documentation updates in src/rust/jsg/README.md and src/rust/AGENTS.md match the code.


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

The future of `ReentryCallback::call()` has two fields that aren't
`Send`, and rustc versions disagree on how many E0277 errors to report
for it: the OSS toolchain reports one per field, while the toolchain of
the internal build reports only one. The checker matches errors
exactly, so no annotation passes under both.

The test keeps checking that the callback itself is neither `Send` nor
`Sync`, which is the property it documents.

@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 — I found no correctness, security, performance, documentation or AGENTS.md issues. The one change since the last review drops the ReentryCallFuture case from a compile test, and the !Send and !Sync checks on ReentryCallback itself are still in place.

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

  • Terminations: The Terminated outcome rethrows the pending termination through throwPendingToRun() instead of replacing it with a new JS exception.
  • Panics: A panic in the Rust function fails the call with a plain KJ assertion, so no JS runs while a termination is pending.
  • ThreadBound: The SAFETY argument for its unsafe impl Send holds, and the debug assertion on the creating thread backs it up.
  • JSG allowlist: The cpp-jsg-allowlist.txt entry matches the only C++ JSG use in ffi.c++.

📖 AGENTS.md: ✅ LGTM

The src/rust/AGENTS.md change follows the repository's conventions.


📋 Code Quality: ✅ LGTM

The only change since the last review removes the ReentryCallFuture case from reentry-callback-is-not-send.rs.

  • Remaining cases: require_send(callback) and require_sync(callback) on ReentryCallback<u32> each expect a single E0277. The callback holds a KjOwn<bridge::ReentryCallback>, which is neither Send nor Sync, so that error count should be the same on any toolchain.
  • Build wiring: glob(["compile-tests/*.rs"]) in BUILD.bazel already picks up the file.
  • Header comment: The file's header comment now matches the cases that remain.
  • Earlier approver suggestions: Both are still in the code: the thread-id debug assertion in ThreadBound, and the test that drops the callback while a call is in flight.

⚡ Performance: ✅ LGTM

No performance concerns. The change since the last review is a compile test, which has no runtime cost, and nothing in production calls the new APIs yet.


📝 Documentation: ✅ LGTM

The documentation updates in src/rust/jsg/README.md and src/rust/AGENTS.md match the code.


Reviewed commit: beb2cc6e

@bartlomieju
bartlomieju merged commit 8325eed into main Nov 20, 2026
23 checks passed
@bartlomieju
bartlomieju deleted the biwanczuk/rust-reentry-callback-stacked branch November 20, 2026 12:43
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