Repository navigation
Move the REPL's environments and JavaScript API to Rust - #8914
Draft
bartlomieju wants to merge 10 commits into
Draft
bartlomieju wants to merge 10 commits into
bartlomieju wants to merge 10 commits into
Conversation
Member
|
The issue with I'm working on making kj promises safe to use and Send in #8857 it's just blocked on review |
bartlomieju
force-pushed
the
bartek/repl-rust
branch
from
November 25, 2026 23:05
e879553 to
c62426e
Compare
This was referenced Nov 25, 2026
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
force-pushed
the
bartek/repl-rust
branch
from
November 26, 2026 09:48
c62426e to
36971f4
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 replinto Rust, removing C++ and giving the host-sideIoContext API its first real user. James's REPL (#8357) ran its
environments, its
workerdglobal and its handles through C++ JSG andabstract host classes. Here an environment is a Rust
Environment(cli/repl/environment.rs) that holds one
IncomingRequestfor itslifetime and runs every input in its IoContext, and
workerd, theserver 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, thesession'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
ProcessStateandnewWorkerFactory. The commits before the port move the configservers to Rust, then add what the port needs to Rust JSG and
io-context; they are listed below.
The REPL is behind
--experimentaland 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 thisbuild 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:
IoContext::await_io_local(): awaits I/O whose future andcallback aren't
Send, such as a C++kj::Promise's or one thatholds an
Rc. It isunsafe: the caller promises the event loopstays on its OS thread, which a host that moves event loops
between threads can't.
(
ScopedChannel::evict_for_test()), ascloudflare:unsafe'sevict()does.IoOwnedLocal<T>: a value that isn'tSendheld by an IoContext,the counterpart of C++
IoOwn<T>, which a resource can hold.add_local_object(), which makes one, isunsafefor the samereason.
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.
JSG.
IoContext::IncomingRequestfor a host that holds one:delivering it, registering a pending event, running a callback in
its IoContext, and draining it.
value to an object in Rust JSG.
What is left of the REPL in C++, and how it could move to Rust:
network over the event loop, which
factory_newalso builds foreach factory. Starting the process already goes through
ProcessState; the REPL still checks autogate names itself, sincethe process ignores a name it doesn't know.
WorkerdApi, themodule registry, the isolate, script and worker. That is core
runtime and stays C++; instead of porting it,
WorkerFactorycouldbuild 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.
IoChannelFactory, and the interim conversion of aloaded 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: itsio-channelscrate 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
IoChannelFactorybuilt on them can replace the REPL's C++one.
repl_inspect(), once Rust JSG can resolve an internal module suchas
node-internal:internal_inspect.repl_new_factory(), now a thin call tonewWorkerFactory, whichgoes with item 2 or becomes
factory_newonce the REPL's factoryoptions fit
FactoryOptions.consumers are C++ and the compiler sits behind the RUST_COMPAT_DATE
autogate; it can move once that autogate is removed.