Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions src/rust/jsg/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,9 +253,7 @@ leaves decisions to Rust. Some existing shims still use C++ JSG. Those uses are
allowlist described below, and are to be removed. The one exception is in
`src/workerd/io/io-context/ffi.c++`, where `io_context_await_io_and_run()` throws
`JsExceptionThrown` to pass an exception that Rust left pending to `IoContext::run()`, which
learns of exceptions no other way, and `io_context_add_wait_until()` calls the C++ function that
`ctx.waitUntil()` calls, so that a Rust implementation matches C++ exactly; its "C++ JSG" section
explains why that is sound. Don't extend it.
learns of exceptions no other way. Don't extend it.

Don't add C++ JSG to the shims. This includes `jsg::Lock` (including `Lock::from` and
`IoContext::getCurrentLock()`),
Expand Down
10 changes: 3 additions & 7 deletions src/rust/jsg/cpp-jsg-allowlist.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,7 @@ src/rust/jsg/jsg.h jsg::Lock 3
src/rust/jsg/jsg.h JsExceptionThrown 1
src/rust/jsg/jsg.h jsg::Data 1

# A reviewed exception, explained under "C++ JSG" in that file: io_context_await_io_and_run()
# A reviewed exception, explained above it in that file: io_context_await_io_and_run()
# propagates the exception that a failed callback left pending to IoContext::run() as
# JsExceptionThrown, which is how run() learns of it, and io_context_add_wait_until() reuses
# what ctx.waitUntil() calls. Don't add to it.
src/workerd/io/io-context/ffi.c++ jsg::Lock 1
src/workerd/io/io-context/ffi.c++ getCurrentLock 1
src/workerd/io/io-context/ffi.c++ JsExceptionThrown 2
src/workerd/io/io-context/ffi.c++ jsg::Promise 1
# JsExceptionThrown, which is how run() learns of it. Don't add to it.
src/workerd/io/io-context/ffi.c++ JsExceptionThrown 1
10 changes: 10 additions & 0 deletions src/workerd/io/io-context.c++
Original file line number Diff line number Diff line change
Expand Up @@ -777,6 +777,16 @@ kj::Exception IoContext::abortWithoutReasonException() {
FAILED, Error, "Worker execution was aborted due to call to ctx.abort().");
}

kj::Exception IoContext::neverSettledException() {
return JSG_KJ_EXCEPTION(FAILED, Error, "Promise will never complete.");
}

kj::Exception IoContext::memoryLimitException() {
auto e = JSG_KJ_EXCEPTION(OVERLOADED, Error, MEMORY_LIMIT_MESSAGE);
e.setDetail(MEMORY_LIMIT_DETAIL_ID, kj::heapArray<kj::byte>(0));
return e;
}

void IoContext::abortIsolate(kj::StringPtr reason) {
getIoChannelFactory().abortIsolate(reason);
}
Expand Down
42 changes: 30 additions & 12 deletions src/workerd/io/io-context.h
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,16 @@ class IoContext final: public kj::Refcounted, private kj::TaskSet::ErrorHandler
return asyncTracker.get();
}

// The async trace resource of an awaitJs() wait, which the wait settles when the JavaScript
// promise settles. Inert if the context is not traced. The Rust io-context crate's await_js()
// creates its resource with this too.
AsyncResource makeAwaitJsResource() const {
KJ_IF_SOME(tracker, tryGetAsyncTracker()) {
return tracker.create(AsyncKind::JS_TO_KJ, "awaitJs"_kj);
}
return {};
}

// Gets the actor, throwing if there isn't one.
Worker::Actor& getActorOrThrow();

Expand Down Expand Up @@ -602,6 +612,19 @@ class IoContext final: public kj::Refcounted, private kj::TaskSet::ErrorHandler
"operation within a handler. "
"https://developers.cloudflare.com/workers/runtime-apis/handlers/"_kj;

// The exception with which awaitJs() fails if JavaScript never settles the promise: a FAILED
// Error whose message is "Promise will never complete.".
static kj::Exception neverSettledException();

// The message of memoryLimitException().
static constexpr kj::StringPtr MEMORY_LIMIT_MESSAGE = "Worker has exceeded memory limit."_kj;

// The exception with which awaitJs() fails, rather than with neverSettledException(), if
// JavaScript never settles the promise while the isolate has excessively exceeded its heap
// limit: an OVERLOADED Error with MEMORY_LIMIT_MESSAGE, carrying MEMORY_LIMIT_DETAIL_ID, which
// marks it as an out-of-memory outcome.
static kj::Exception memoryLimitException();

// Like current(), but returns kj::none if there is no current context.
static kj::Maybe<IoContext&> tryCurrent();

Expand Down Expand Up @@ -1422,6 +1445,9 @@ class IoContext final: public kj::Refcounted, private kj::TaskSet::ErrorHandler
// Objects pointed to by IoOwn<T>s.
// NOTE: This must live below `deleteQueue`, as some of these OwnedObjects may own attachctx()'ed
// objects which reference `deleteQueue` in their destructors.
// NOTE: This must also live below `abortException` and `abortFlag`: the half of a Rust
// await_js() wait that settles it reads `abortException` when it is destroyed, and destroys a
// branch of `abortFlag`.
OwnedObjectList ownedObjects;

kj::Maybe<kj::Rc<ExternalPusherImpl>> externalPusher;
Expand Down Expand Up @@ -1566,8 +1592,8 @@ class IoContext final: public kj::Refcounted, private kj::TaskSet::ErrorHandler
void resumeAfterIo(
jsg::Lock& js, kj::Promise<T> promise, InputLockOrMaybeCriticalSection ilOrCs, Func&& func);

// Async trace resources for the awaitIo() and awaitJs() bridges. Inert if the context is not
// traced.
// The async trace resource for the awaitIo() bridge. Inert if the context is not traced.
// awaitJs()'s is makeAwaitJsResource().
AsyncResource makeAwaitIoResource() const {
KJ_IF_SOME(tracker, tryGetAsyncTracker()) {
KJ_IF_SOME(name, awaitIoOperationName) {
Expand All @@ -1583,12 +1609,6 @@ class IoContext final: public kj::Refcounted, private kj::TaskSet::ErrorHandler

// Set by AwaitIoOperation.
mutable kj::Maybe<kj::StringPtr> awaitIoOperationName;
AsyncResource makeAwaitJsResource() const {
KJ_IF_SOME(tracker, tryGetAsyncTracker()) {
return tracker.create(AsyncKind::JS_TO_KJ, "awaitJs"_kj);
}
return {};
}

// The IncomingRequest that is currently considered "current". This is always the
// latest-starting request that hasn't yet completed.
Expand Down Expand Up @@ -2113,13 +2133,11 @@ class IoContext::AwaitJsFulfiller final: public kj::Refcounted {
return isolate->getLimitEnforcer().hasExcessivelyExceededHeapLimit();
}).orDefault(false);
if (hasExcessivelyExceededHeapLimit) {
auto e = JSG_KJ_EXCEPTION(OVERLOADED, Error, "Worker has exceeded memory limit.");
e.setDetail(MEMORY_LIMIT_DETAIL_ID, kj::heapArray<kj::byte>(0));
fulfiller->reject(kj::mv(e));
fulfiller->reject(memoryLimitException());
} else {
// The JavaScript resolver was garbage collected, i.e. JavaScript will never resolve
// this promise.
fulfiller->reject(JSG_KJ_EXCEPTION(FAILED, Error, "Promise will never complete."));
fulfiller->reject(neverSettledException());
}
}
};
Expand Down
6 changes: 5 additions & 1 deletion src/workerd/io/io-context/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ wd_cc_library(
":ffi.rs@cxx",
"//src/rust/jsg:ffi",
"//src/workerd/io",
"//src/workerd/jsg:inspector",
],
)

Expand Down Expand Up @@ -87,8 +88,11 @@ wd_cc_library(
)

# io-context inside a request of a real worker and in a Durable Object, and the IoContext that
# Rust builtin modules see when a request resolves them.
# Rust builtin modules see when a request resolves them. Large: most of its cases start a worker
# of their own, which with every autogate on adds up to more than the moderate timeout in a debug
# build.
kj_test(
size = "large",
src = "io-context-test.c++",
deps = [
":ffi",
Expand Down
131 changes: 102 additions & 29 deletions src/workerd/io/io-context/ffi.c++
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
#include "ffi.h"

#include <workerd/io/io-context/ffi.rs.h>
#include <workerd/jsg/inspector.h>
#include <workerd/rust/jsg/ffi-inl.h>

#include <v8-inspector.h>

#include <capnp/message.h>
#include <capnp/serialize.h>

Expand Down Expand Up @@ -59,6 +62,67 @@ void setTag(Span& span, Literal key, Value value) {
return IoContext::NO_REQUEST_MESSAGE.cStr();
}

kj::Exception io_context_never_settled_exception() {
return IoContext::neverSettledException();
}

kj::Exception io_context_memory_limit_exception() {
return IoContext::memoryLimitException();
}

kj::Own<IsolateWeakRef> io_context_isolate_weak_ref(uint64_t id) {
return kj::heap<IsolateWeakRef>(currentWithId(id).getWorker().getIsolate().getWeakRef());
}

bool isolate_weak_ref_has_excessively_exceeded_heap_limit(const IsolateWeakRef& weakRef) {
// Rust calls this when it drops the half of an await_js() wait that settles it: in a cppgc
// finalizer or the GC epilogue, or without the isolate lock, where ~AwaitJsFulfiller() runs
// rejectNeverSettled(). It enters no V8: tryAddStrongRef() takes the weak reference's mutex and
// an atomic reference, and hasExcessivelyExceededHeapLimit() must not (see its declaration).
return weakRef.ref->tryAddStrongRef()
.map([](kj::Own<const Worker::Isolate> isolate) {
return isolate->getLimitEnforcer().hasExcessivelyExceededHeapLimit();
}).orDefault(false);
}

kj::Maybe<kj::Own<AsyncResource>> io_context_make_await_js_resource(uint64_t id) {
auto resource = currentWithId(id).makeAwaitJsResource();
// An inert resource, whose id is 0, reports nothing.
if (resource.getId() == 0) return kj::none;
return kj::heap(kj::mv(resource));
}

AbortWatcher::AbortWatcher(IoContext& context, ::rust::Box<AbortCallback> callback)
: context(context),
abortedAtStart(context.getAbortReason() != kj::none),
// onAbort() never resolves: the IoContext only rejects its abort flag. The callback only
// settles Rust's state and wakes its future, so it runs no JavaScript and needs no lock.
watch(context.onAbort()
.catch_([callback = kj::mv(callback)](
kj::Exception&& e) { callback->aborted(kj::mv(e)); })
.eagerlyEvaluate(nullptr)) {}

AbortWatcher::~AbortWatcher() noexcept(false) {}

kj::Maybe<kj::Exception> AbortWatcher::abortedSinceStart() const {
if (abortedAtStart) {
return kj::none;
}
return context.getAbortReason();
}

bool abort_watcher_has_pending_abort(const AbortWatcher& watcher) {
return watcher.abortedSinceStart() != kj::none;
}

kj::Exception abort_watcher_pending_abort(const AbortWatcher& watcher) {
return KJ_REQUIRE_NONNULL(watcher.abortedSinceStart(), "the IoContext was not aborted since");
}

kj::Own<AbortWatcher> io_context_watch_abort(uint64_t id, ::rust::Box<AbortCallback> callback) {
return kj::heap<AbortWatcher>(currentWithId(id), kj::mv(callback));
}

kj::Maybe<uint64_t> io_context_try_current_id() {
return IoContext::tryGetCurrentId().map(
[](IoContext::Id id) { return std::bit_cast<uint64_t>(id); });
Expand Down Expand Up @@ -109,6 +173,14 @@ void io_context_write_logfwdr(uint64_t id, uint32_t channel, ::rust::Slice<const
}
}

void io_context_add_wait_until(uint64_t id, ::rust::Box<WaitUntilFuture> future) {
currentWithId(id).addWaitUntil(wait_until_future_wait(kj::mv(future)));
}

// Rust JSG's shims don't use C++ JSG (src/rust/jsg/README.md, "Safety rules", rule 3). This
// function is the reviewed exception: it throws JsExceptionThrown, which is how IoContext::run()
// learns of an exception the callback left pending in V8. That use is counted in
// src/rust/jsg/cpp-jsg-allowlist.txt, so it stays within this function.
void io_context_await_io_and_run(
uint64_t id, ::rust::Box<IoFuture> future, ::rust::Box<IoCallback> callback) {
auto& context = currentWithId(id);
Expand All @@ -122,7 +194,7 @@ void io_context_await_io_and_run(
case IoCallbackOutcome::Failed:
// The exception, or termination, is pending in V8. JsExceptionThrown is how
// IoContext::run() expects to learn of it: it then logs the exception as uncaught, with its
// stack, and fails the task with it, as for C++ code it runs. See "C++ JSG" below.
// stack, and fails the task with it, as for C++ code it runs.
throw jsg::JsExceptionThrown();
case IoCallbackOutcome::Panicked:
// The termination takes effect only when V8 next runs JavaScript, in run()'s microtask
Expand Down Expand Up @@ -212,36 +284,37 @@ void io_context_abort_without_reason(uint64_t id) {
currentWithId(id).abort(IoContext::abortWithoutReasonException());
}

// C++ JSG
//
// Rust JSG's shims don't use C++ JSG (src/rust/jsg/README.md, "Safety rules", rule 3). This file
// has reviewed exceptions. io_context_await_io_and_run(), above, throws JsExceptionThrown, which
// is how IoContext::run() learns of an exception. The function below calls IoContext::awaitJs(),
// which ctx.waitUntil() calls, so that a Rust implementation matches C++ exactly rather than
// reimplementing it over V8. Each use of C++ JSG, including getCurrentLock(), is counted in
// src/rust/jsg/cpp-jsg-allowlist.txt, so it stays within these two functions.
//
// They rely on this invariant: once currentWithId() has passed, the IoContext is current, which
// it is only inside IoContext::run() or a call from the JavaScript it runs, under the
// Worker::Lock that getCurrentLock() returns. That is the isolate lock the caller's Rust
// jsg::Lock stands for, so C++ JSG may use it, and the handles Rust passes belong to the
// caller's open HandleScope, in the IoContext's context.
//
// When C++ JSG throws JsExceptionThrown, the JavaScript exception, or termination, is pending in
// V8, where C++ JSG left it; the function returns false, and Rust passes the exception on.

bool io_context_add_wait_until(uint64_t id, ::workerd::rust::jsg::Local promise) {
bool io_context_should_log_uncaught_exceptions() {
return kj::_::Debug::shouldLog(kj::LogSeverity::INFO);
}

void io_context_log_uncaught_exception_stack(UncaughtExceptionSource source, ::rust::Str text) {
// Named as in Worker::Lock::logUncaughtException(), since KJ_LOG writes the names.
auto stack = kj::str(kj::arrayPtr(text.data(), text.size()));
KJ_LOG(INFO, "uncaught exception", source, stack);
}

void io_context_log_uncaught_exception_value(UncaughtExceptionSource source, ::rust::Str text) {
auto exception = kj::str(kj::arrayPtr(text.data(), text.size()));
KJ_LOG(INFO, "uncaught exception", source, exception);
}

bool io_context_send_exception_to_inspector(uint64_t id,
::workerd::rust::jsg::Isolate* isolate,
UncaughtExceptionSource source,
::workerd::rust::jsg::Local exception) {
auto& context = currentWithId(id);
auto handle = ::workerd::rust::jsg::local_from_ffi<v8::Promise>(kj::mv(promise));
try {
jsg::Lock& js = context.getCurrentLock();
// As PromiseWrapper::tryUnwrap() does for a kj::Promise<void> argument once it has
// converted it to a jsg::Promise<void>, which Rust's VoidPromise has done.
context.addWaitUntil(context.awaitJs(js, jsg::Promise<void>(js.v8Isolate, handle)));
return true;
} catch (jsg::JsExceptionThrown&) {
return false;
KJ_IF_SOME(inspector, context.getWorker().getIsolate().tryGetV8Inspector()) {
// The calls below take the context.
if (::workerd::rust::jsg::exceptionPending(isolate)) return false;
auto value = ::workerd::rust::jsg::local_from_ffi<v8::Value>(kj::mv(exception));
// As jsg::sendExceptionToInspector() does for an exception without a v8::Message, such as one
// a promise rejected with. V8 creates a message from the current stack trace, or the one the
// error captured.
auto message = v8::Exception::CreateMessage(isolate, value);
return jsg::sendExceptionToInspector(isolate, inspector, kj::str(source), value, message);
}
return true;
}

void io_context_log_error(::rust::Str message) {
Expand Down
Loading
Loading