Skip to content

Move the REPL's environments and JavaScript API to Rust - #8914

Draft
bartlomieju wants to merge 10 commits into
bartek/bootstrap-rustfrom
bartek/repl-rust
Draft

bartlomieju wants to merge 10 commits into
bartek/bootstrap-rustfrom
bartek/repl-rust

Conversation

@bartlomieju

@bartlomieju bartlomieju commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #8941 (itself on #8929): the commits from "Move the REPL's
config servers to Rust" on are this PR's.

The motivation for this change is to move the JavaScript side of
workerd repl into Rust, removing C++ and giving the host-side
IoContext API its first real user. James's REPL (#8357) ran its
environments, its workerd global and its handles through C++ JSG and
abstract host classes. Here an environment is a Rust Environment
(cli/repl/environment.rs) that holds one IncomingRequest for its
lifetime and runs every input in its IoContext, and workerd, the
server handles and the environment handles are Rust JSG resources
(cli/repl/api.rs) that hold what they stand for through
IoOwnedLocal. C++ keeps the worker an environment runs in, the
session's I/O, the rendering of results with
node-internal:internal_inspect, and the factories of loaded configs;
the process and those factories are now started the way workerd's
commands start theirs, with #8941's ProcessState and
newWorkerFactory. The commits before the port move the config
servers to Rust, then add what the port needs to Rust JSG and
io-context; they are listed below.

The REPL is behind --experimental and no Worker can reach its API,
so the Workers API surface is untouched, and the REPL's behaviour is
unchanged: inputs covering results, exceptions, awaited and unhandled
rejections, timers, loaded configs, nested environments and their
close, and evict() print the same output, byte for byte, from this
build and from the released C++ REPL. The one difference no output
shows is that promise-returning methods don't follow their promise
through the extra reaction C++ JSG adds, so they can settle a
microtask earlier. session-test.rs keeps its cases and adds one that
drops handles where C++ JSG destroys JavaScript objects, under
DISALLOW_KJ_IO_DESTRUCTORS_SCOPE, in place of the deleted C++ test;
tests/repl passes unchanged.

The Rust JSG and io-context additions, each a commit of its own and
useful beyond the REPL:

  1. IoContext::await_io_local(): awaits I/O whose future and
    callback aren't Send, such as a C++ kj::Promise's or one that
    holds an Rc. It is unsafe: the caller promises the event loop
    stays on its OS thread, which a host that moves event loops
    between threads can't.
  2. Evicting the Durable Object behind a Fetcher
    (ScopedChannel::evict_for_test()), as cloudflare:unsafe's
    evict() does.
  3. IoOwnedLocal<T>: a value that isn't Send held by an IoContext,
    the counterpart of C++ IoOwn<T>, which a resource can hold.
    add_local_object(), which makes one, is unsafe for the same
    reason.
  4. pinned-thread-io: safe wrappers of both for the workerd binary,
    whose event loops kj-rs-tokio pins to their threads. Its Bazel
    visibility is //src/workerd/server/..., so an API crate that also
    runs where loops move can't use it.
  5. Compiling and running scripts, functions and WebAssembly from Rust
    JSG.
  6. Binding IoContext::IncomingRequest for a host that holds one:
    delivering it, registering a pending event, running a callback in
    its IoContext, and draining it.
  7. Listing an object's inherited property names and converting a
    value to an object in Rust JSG.

What is left of the REPL in C++, and how it could move to Rust:

  1. The session's I/O (repl.c++): entropy, the filesystem and the
    network over the event loop, which factory_new also builds for
    each factory. Starting the process already goes through
    ProcessState; the REPL still checks autogate names itself, since
    the process ignores a name it doesn't know.
  2. The worker (repl-worker.c++): header tables, WorkerdApi, the
    module registry, the isolate, script and worker. That is core
    runtime and stays C++; instead of porting it, WorkerFactory could
    build the REPL's worker from a one-worker config, given a factory
    call that opens a host request on a worker. This removes the most
    code.
  3. The REPL's IoChannelFactory, and the interim conversion of a
    loaded server's Rust channel into a C++ one
    (repl_channel_into_kj()). Give a dynamic worker one channel table, in the server #8915 is the first step: its
    io-channels crate gives Rust one type for the runtime's channels,
    and the server's channel table can hold a C++ channel. Once the
    server hands out channels of that type the conversion goes, and a
    Rust IoChannelFactory built on them can replace the REPL's C++
    one.
  4. repl_inspect(), once Rust JSG can resolve an internal module such
    as node-internal:internal_inspect.
  5. repl_new_factory(), now a thin call to newWorkerFactory, which
    goes with item 2 or becomes factory_new once the REPL's factory
    options fit FactoryOptions.
  6. Compiling the compatibility flags, which C++ does now because its
    consumers are C++ and the compiler sits behind the RUST_COMPAT_DATE
    autogate; it can move once that autogate is removed.

@nathanwhit

nathanwhit commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

The issue with await_io_local is that it's unsound. The assumption that nothing moves between threads is only correct in workerd standalone. In production / in the internal repo (EW), the scheduler is a green threading scheduler that moves event loops to different threads between polls. So the future actually can/will move threads along with the entire event loop, and having a safe method that takes a !Send future is unsound. Likewise IoOwnedLocal is unsound for the same reason.

I'm working on making kj promises safe to use and Send in #8857 it's just blocked on review

The servers of the configs `workerd.loadConfig()` loads now live in
the CLI crate (cli/repl/server.rs), next to the config loader and
watcher they use. ReplConfigServer loads, reloads (by hand or when a
watched file changes) and closes a server. ServerRegistry holds what a
session's servers share: the loader, and the claims that refuse a
config whose Durable Object storage or UDP address another loaded
server holds. This removes repl-server.{h,c++} and the ConfigLoader
and ConfigWatch adapters in repl.c++.

C++ keeps repl_new_factory, which builds a WorkerFactory from the
encoded config, and a LoadedServer adapter that gives the JS API a
ReplServerHost over the Rust server until that API moves to Rust too.

V8 is now process-wide and never disposed. V8 can't initialize again
after it is disposed, and the Rust tests start many sessions in one
process. A later session must pass the first one's V8 flags and
autogates.

The server tests in repl-environment-test.c++ move to a Rust test of
workerd-cli (cli/repl/session-test.rs). It loads configs from temp
files with the real config compiler and fires watch changes through a
test Watch implementation.

The REPL ships only behind --experimental, so this needs no autogate.
Add IoContext::await_io_local(), the counterpart of C++ awaitIo() for
a future and output that need only be 'static, as await_js_local() is
for awaitJs(): such as the future of a C++ kj::Promise, or one that
holds an Rc. C++ awaits Rust's I/O only on the IoContext's thread, so
the type-erased IoFuture, IoOutput and IoCallback that carry the
future to awaitIoAndRun() no longer need Send either, as the
ReentryFuture of make_reentry_callback_weak() does not. await_io() and
await_io_and_run() keep their Send bounds, which their compile tests
still check, and share their implementation with await_io_local().

await_io_local() is unsafe: a host may move an event loop between OS
threads, and what the future holds, such as an Rc with clones
elsewhere, may be tied to the thread. The caller promises the event
loop stays on this thread until the future, its output and the
callback are gone. A compile test checks that it needs unsafe.

The REPL's JavaScript API, which moves to Rust, waits for its config
servers, which are Rc-based and belong to the event loop's thread.
Adapted from the unsafe modules port (#8740), without its actor calls.
Add ScopedChannel<SubrequestChannel>::evict_for_test() to
channel-interop, over C++ SubrequestChannel::evictForTest(), returning
a future to wait for with IoContext::await_io_local(), and
io_context::EvictWebSocketMode, C++
IoChannelFactory::EvictWebSocketMode, for what it does with the
object's hibernatable WebSockets.

The bridge takes io_context::EvictWebSocketMode by its alias in
io-context's ffi.h, so the enum has one Rust type.

workerd.evict() in the REPL, whose JavaScript API moves to Rust, needs
it. Taken from the unsafe modules port (#8740).
Add IoContext::add_local_object() and IoOwnedLocal<T>, the Rust
counterpart of C++ IoOwn<T> for a value that belongs to the
IoContext's thread, such as an Rc or a KjOwn of a C++ I/O object.
IoOwned<T> requires T: Send, because a resource that holds the handle
may be dropped by GC on another thread; C++ IoOwn has no such bound,
since dereferencing it asserts that its IoContext is current and
destroying it elsewhere only queues the deletion for that IoContext.

IoOwnedLocal<T> gives the same guarantees: take() and with() work only
while its IoContext is current, so on its thread, and the IoContext
drops the value there. The handle is Send and Sync, so a resource can
hold it. add_local_object() is unsafe, as await_io_local() is: the
caller promises the event loop stays on this thread while the
IoContext holds the value.

IoOwnedSpan already relied on this for one type; it is now an
IoOwnedLocal<SpanBuilder>, and its ThreadBoundSpan becomes the generic
ThreadBoundObject<T>, with the same SAFETY argument. Its spans are KJ
objects, which move with their event loop, so it takes them through a
private safe add_thread_bound_object().

The REPL's JavaScript handles, which move to Rust, hold their Rc-based
config servers this way.
IoContext::await_io_local() and add_local_object() are unsafe because
a host may move an event loop between OS threads. The workerd binary
never does: the event loops that run its IoContexts are kj-rs-tokio's
(util/setup-async-io.c++), whose tasks live on a LocalSet of the
thread that made the loop. pinned-thread-io states that once and
wraps both functions safely, as await_io() and add_object().

Its Bazel visibility is //src/workerd/server/..., so an API crate that
also runs where event loops move between threads can't depend on it.
`workerd repl`'s JavaScript handles and promises, which move to Rust,
use it.
Add v8::Script (compile and run a classic script),
v8::Function::compile() and set_name(), Value::is_async_function()
and v8::WasmModuleObject::compile(), as raw V8 shims that leave what
they throw pending. Add Isolate::is_eval_allowed(),
set_allow_eval() and is_starting_from_snapshot().

IsolateBase::setAllowEval() takes a jsg::Lock badge, which the shims
can't produce, so jsg gets free isEvalAllowed() and setAllowEval()
functions next to getCaptureThrowsAsRejections(), for the same
reason.

These are what a Rust port of UnsafeEval (workerd:unsafe-eval) and
UnsafeModule needs.

The REPL, whose evaluation moves to Rust, compiles input with them.
Taken from the unsafe modules port (#8740).
Let Rust code that opened an IoContext::IncomingRequest, and holds it
outside any IoContext, use it as C++ hosts do:

- incoming_request_delivered(), with delivered_location!() for where
  Rust delivered it, taken from #8734.
- incoming_request_run(): IoContext::run() of the request's context,
  for a Rust function that returns a future, as a ReentryCallback's
  function does. It reuses that machinery: the body of
  ReentryCallback's run() lambda becomes runReentryFn(), which both
  call, each with its own panic message.
- incoming_request_register_pending_event():
  IoContext::registerPendingEvent(), so that a context that waits for
  its host is not taken for hung.
- incoming_request_drain(): IncomingRequest::drain(), then the
  waitUntil() tasks it leaves, resolving to whether
  waitUntilStatus() is OK.

incoming_request_run() reaches throwPendingToRun() through
runReentryFn(). IoContext::run() runs it, as rule 3 of
src/rust/jsg/README.md requires, so the README and the allowlist list
it with the other two callers; the count does not change.

The REPL, whose session moves to Rust, opens one request for the
session and runs each input in it.
Add Local<Object>::property_names_with_prototypes(), the names of an
object's string-keyed properties, own and inherited, enumerable or
not, without integer indices, as v8::Object::GetPropertyNames() with
kIncludePrototypes returns them; and Local::to_object(), as
v8::Value::ToObject() converts, with a TypeError pending for null and
undefined. Both are raw V8 shims, as keys() and get() are.

The REPL's tab completion, which moves to Rust, offers the property
names of the value before the dot this way.
An environment (cli/repl/environment.rs) now holds one
IncomingRequest on its worker for its lifetime and runs every input
in that request's IoContext: it compiles an input's candidates, runs
the first that compiles, awaits the awaited ones, records `_` and
`_error`, lists property names for completion, and drains. The
environments `workerd.environment()` starts are nested in the one
that started it, which closes them when it drains; an evaluation the
close cuts short fails, as kj::Canceler made it fail in C++.

The `workerd` global and the server and environment handles
(cli/repl/api.rs) are Rust JSG resources that hold what they stand
for through IoOwnedLocal, so that collecting a handle destroys no
KJ I/O objects. This removes repl-api.{h,c++}, its registration in
the workerd API isolate, and the ReplServerHost and
ReplEnvironmentHost adapters.

repl-environment.{h,c++} becomes repl-worker.{h,c++}: C++ keeps only
the worker an environment runs in, the requests Rust opens on it,
the rendering of results with node-internal:internal_inspect, and
repl_new_factory. Choosing the compatibility flags the REPL adds
moved to Rust; compiling them stays in C++, whose consumers read the
compiled message and which honours the RUST_COMPAT_DATE autogate.

eval() on a closed environment throws, as the C++ did. Piped through
this build and the released C++ REPL, inputs covering results,
exceptions, rejections, timers, loaded configs, nested environments
and evict() print the same output. Promise-returning methods don't
follow their promise through the extra reaction C++ JSG adds, so
they can settle a microtask earlier.

repl-api-test.c++ becomes a session test that drops the handles
where C++ JSG destroys JavaScript objects.

The REPL ships only behind --experimental, so this needs no autogate.
The REPL set up the process itself: it validated and set the
autogates, started a V8 platform and V8System with the V8 flags, and
built each loaded config's WorkerFactory by hand. ProcessState and
newWorkerFactory (factory/per-process.h) now do both for workerd's
commands, for a host that starts the process once and builds many
factories, which is what the REPL is.

The first session starts the process with ProcessState::start(), and
a later one must still ask for the same autogates and V8 flags. The
REPL keeps checking the autogate names, since the process ignores a
name it doesn't know. repl_new_factory() builds each loaded config's
factory with newWorkerFactory(), which holds a reference to the
process, and takes the config by value, as that does.
@bartlomieju
bartlomieju changed the base branch from main to bartek/bootstrap-rust November 26, 2026 09:48
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