diff --git a/src/rust/jsg/README.md b/src/rust/jsg/README.md index e3a71649d24..321efa606cd 100644 --- a/src/rust/jsg/README.md +++ b/src/rust/jsg/README.md @@ -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()`), diff --git a/src/rust/jsg/cpp-jsg-allowlist.txt b/src/rust/jsg/cpp-jsg-allowlist.txt index 65992af17b1..8b75ee6d64c 100644 --- a/src/rust/jsg/cpp-jsg-allowlist.txt +++ b/src/rust/jsg/cpp-jsg-allowlist.txt @@ -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 diff --git a/src/workerd/io/io-context.c++ b/src/workerd/io/io-context.c++ index 7465e069fe2..ca299bd5e34 100644 --- a/src/workerd/io/io-context.c++ +++ b/src/workerd/io/io-context.c++ @@ -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(0)); + return e; +} + void IoContext::abortIsolate(kj::StringPtr reason) { getIoChannelFactory().abortIsolate(reason); } diff --git a/src/workerd/io/io-context.h b/src/workerd/io/io-context.h index f96743c50b6..21d03436500 100644 --- a/src/workerd/io/io-context.h +++ b/src/workerd/io/io-context.h @@ -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(); @@ -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 tryCurrent(); @@ -1422,6 +1445,9 @@ class IoContext final: public kj::Refcounted, private kj::TaskSet::ErrorHandler // Objects pointed to by IoOwns. // 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> externalPusher; @@ -1566,8 +1592,8 @@ class IoContext final: public kj::Refcounted, private kj::TaskSet::ErrorHandler void resumeAfterIo( jsg::Lock& js, kj::Promise 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) { @@ -1583,12 +1609,6 @@ class IoContext final: public kj::Refcounted, private kj::TaskSet::ErrorHandler // Set by AwaitIoOperation. mutable kj::Maybe 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. @@ -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(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()); } } }; diff --git a/src/workerd/io/io-context/BUILD.bazel b/src/workerd/io/io-context/BUILD.bazel index 10c31cce136..51d8ed265a4 100644 --- a/src/workerd/io/io-context/BUILD.bazel +++ b/src/workerd/io/io-context/BUILD.bazel @@ -34,6 +34,7 @@ wd_cc_library( ":ffi.rs@cxx", "//src/rust/jsg:ffi", "//src/workerd/io", + "//src/workerd/jsg:inspector", ], ) @@ -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", diff --git a/src/workerd/io/io-context/ffi.c++ b/src/workerd/io/io-context/ffi.c++ index 9a0d5e856a7..4ee380165dd 100644 --- a/src/workerd/io/io-context/ffi.c++ +++ b/src/workerd/io/io-context/ffi.c++ @@ -5,8 +5,11 @@ #include "ffi.h" #include +#include #include +#include + #include #include @@ -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 io_context_isolate_weak_ref(uint64_t id) { + return kj::heap(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 isolate) { + return isolate->getLimitEnforcer().hasExcessivelyExceededHeapLimit(); + }).orDefault(false); +} + +kj::Maybe> 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 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 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 io_context_watch_abort(uint64_t id, ::rust::Box callback) { + return kj::heap(currentWithId(id), kj::mv(callback)); +} + kj::Maybe io_context_try_current_id() { return IoContext::tryGetCurrentId().map( [](IoContext::Id id) { return std::bit_cast(id); }); @@ -109,6 +173,14 @@ void io_context_write_logfwdr(uint64_t id, uint32_t channel, ::rust::Slice 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 future, ::rust::Box callback) { auto& context = currentWithId(id); @@ -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 @@ -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(kj::mv(promise)); - try { - jsg::Lock& js = context.getCurrentLock(); - // As PromiseWrapper::tryUnwrap() does for a kj::Promise argument once it has - // converted it to a jsg::Promise, which Rust's VoidPromise has done. - context.addWaitUntil(context.awaitJs(js, jsg::Promise(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(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) { diff --git a/src/workerd/io/io-context/ffi.h b/src/workerd/io/io-context/ffi.h index fbb92383cff..94a611da5f8 100644 --- a/src/workerd/io/io-context/ffi.h +++ b/src/workerd/io/io-context/ffi.h @@ -20,6 +20,82 @@ namespace workerd::io_context { // The message of the error IoContext::current() throws outside a request. ::rust::Str io_context_no_request_message(); +// IoContext::neverSettledException(). +kj::Exception io_context_never_settled_exception(); + +// IoContext::memoryLimitException(). +kj::Exception io_context_memory_limit_exception(); + +// A weak reference to the Worker::Isolate of an IoContext, from Worker::Isolate::getWeakRef(), as +// IoContext::awaitJs() takes one. It may outlive the isolate, and may be used and destroyed on +// any thread without the isolate lock: AtomicWeakRef's refcount is atomic, and a mutex guards its +// pointer to the isolate, which the isolate clears when it is destroyed. A struct of its own, +// since Rust can't name a kj::Own. +struct IsolateWeakRef { + kj::Own ref; +}; + +// A weak reference to the isolate of the IoContext that `id` identifies. +kj::Own io_context_isolate_weak_ref(uint64_t id); + +// True if the isolate still exists and IsolateLimitEnforcer::hasExcessivelyExceededHeapLimit() +// says so, which is how IoContext::AwaitJsFulfiller::rejectNeverSettled() decides. Enters no V8 +// and needs no isolate lock, so it may be called in a GC finalizer. The caller must keep the +// isolate alive meanwhile, as the IoContext that owns an await_js() wait does through its +// Worker: the strong reference this takes must not be the last one, whose release would destroy +// the isolate. +bool isolate_weak_ref_has_excessively_exceeded_heap_limit(const IsolateWeakRef& weakRef); + +// The async trace resource of a new await_js() wait in the IoContext that `id` identifies, from +// IoContext::makeAwaitJsResource(), or kj::none if it would be inert, as when the IoContext is not +// traced, so that an untraced wait allocates nothing for it. The resource may outlive the +// IoContext, and may be settled and destroyed on any thread without the isolate lock: +// AsyncResource holds an atomically refcounted AsyncTracker, whose methods drop a call made on a +// thread other than its own (see AsyncTracker). +kj::Maybe> io_context_make_await_js_resource(uint64_t id); + +// Rust type, defined in ffi.rs. +struct AbortCallback; + +// Watches the abort of an IoContext for an await_js() wait, as the onAbort() branch of the +// exclusiveJoin() in IoContext::awaitJsImpl() does: once IoContext::onAbort() rejects, in a turn +// of the IoContext's event loop, without the isolate lock and with no IoContext current, calls +// `callback` with the exception. Destroying it cancels the watch, and drops `callback`. It must be +// destroyed on the IoContext's thread, while the IoContext's abort exception is alive, which it +// reads: the await_js() sender holds it, which the IoContext owns. +class AbortWatcher final { + public: + AbortWatcher(IoContext& context, ::rust::Box callback); + ~AbortWatcher() noexcept(false); + KJ_DISALLOW_COPY_AND_MOVE(AbortWatcher); + + // The exception the IoContext was aborted with, if it was aborted after the watcher started. + // See abort_watcher_has_pending_abort(). + kj::Maybe abortedSinceStart() const; + + private: + IoContext& context; + bool abortedAtStart; + kj::Promise watch; +}; + +// Whether the watcher's IoContext was aborted after the watcher started, whether or not the watcher +// has called its callback yet. In C++, such an abort +// wins the exclusiveJoin() in IoContext::awaitJsImpl() over a JavaScript promise that settles +// later, even in the same turn: the abort's events are armed depth-first before the settling's +// are. If the IoContext was aborted before the watcher started, onAbort() returns a broken promise, +// whose event is armed breadth-first, so a promise that settles in the same turn wins instead, as +// a Rust reaction that runs before the watcher's callback does. Call it on the IoContext's thread. +bool abort_watcher_has_pending_abort(const AbortWatcher& watcher); + +// The exception the watcher's IoContext was aborted with, which abort_watcher_has_pending_abort() +// must have found. Call it on the IoContext's thread. +kj::Exception abort_watcher_pending_abort(const AbortWatcher& watcher); + +// Starts an AbortWatcher in the IoContext that `id` identifies. If the IoContext was already +// aborted, `callback` is called in a later turn, as onAbort() then returns a rejected promise. +kj::Own io_context_watch_abort(uint64_t id, ::rust::Box callback); + // IoContext::tryGetCurrentId(), as a uint64_t. kj::Maybe io_context_try_current_id(); @@ -38,6 +114,7 @@ void io_context_write_logfwdr(uint64_t id, uint32_t channel, ::rust::Slice future); // Logs `message` as an error, as KJ_LOG(ERROR) does. void io_context_log_error(::rust::Str message); +// The parts of Worker::Lock::logUncaughtException(source, exception, message) that need C++, for +// a JavaScript value and without a v8::Message. Rust reads the value's `stack` itself. + +// Whether KJ logs at INFO level (workerd --verbose), at which uncaught exceptions are logged. +bool io_context_should_log_uncaught_exceptions(); + +// KJ_LOG(INFO, "uncaught exception", source, stack), as an uncaught exception that is an object +// whose `stack` is not undefined is logged. +void io_context_log_uncaught_exception_stack(UncaughtExceptionSource source, ::rust::Str stack); + +// KJ_LOG(INFO, "uncaught exception", source, exception), as any other uncaught exception is logged. +void io_context_log_uncaught_exception_value(UncaughtExceptionSource source, ::rust::Str exception); + +// If the isolate of the current IoContext has an inspector, reports `exception` to it as thrown, +// as jsg::sendExceptionToInspector() does with no v8::Message: with a message V8 creates for the +// value, and `source` as its text. If it has one, returns false, and reports nothing, if an +// exception or a termination is pending, or if V8 fails to describe the message, leaving an +// exception pending. Takes a handle in the scope of the caller's lock. +bool io_context_send_exception_to_inspector(uint64_t id, + ::workerd::rust::jsg::Isolate* isolate, + UncaughtExceptionSource source, + ::workerd::rust::jsg::Local exception); + } // namespace workerd::io_context diff --git a/src/workerd/io/io-context/ffi.rs b/src/workerd/io/io-context/ffi.rs index dfaf2d1cf64..58a83ea23a6 100644 --- a/src/workerd/io/io-context/ffi.rs +++ b/src/workerd/io/io-context/ffi.rs @@ -7,8 +7,9 @@ #![allow( unsafe_code, reason = "the cxx bridge expands to unsafe FFI glue, io_callback_run() opens a scope C++ has \ - set up, the waitUntil call takes a V8 handle, and the trace span calls take \ - literals that C++ does not copy" + set up, the inspector call takes V8 handles, the trace span calls \ + take literals that C++ does not copy, and IsolateWeakRef and AsyncResource \ + are declared Send" )] use std::any::Any; @@ -26,23 +27,70 @@ pub mod bridge { include!("workerd/rust/jsg/ffi.h"); include!("workerd/rust/jsg/v8.rs.h"); + type Isolate = jsg::v8::ffi::Isolate; type Local = jsg::v8::ffi::Local; } + /// C++ `UncaughtExceptionSource` (`workerd/util/uncaught-exception-source.h`). + #[namespace = "workerd"] + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + #[repr(i32)] + enum UncaughtExceptionSource { + INTERNAL, + INTERNAL_ASYNC, + ASYNC_TASK, + REQUEST_HANDLER, + TRACE_HANDLER, + ALARM_HANDLER, + ON_HIBERNATE_HANDLER, + } + + /// C++ `AsyncOutcome` (`workerd/rust/async-trace/listener.h`). + #[namespace = "workerd"] + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + #[repr(u8)] + enum AsyncOutcome { + OK, + ERROR, + CANCELED, + } + #[namespace = "workerd"] unsafe extern "C++" { + include!("workerd/io/async-trace.h"); include!("workerd/io/io-context.h"); + type AsyncOutcome; + type AsyncResource; type SpanBuilder; type TraceContext; + type UncaughtExceptionSource; + + /// `AsyncResource::settle()`. Only the first settle is reported. + fn settle(self: &AsyncResource, outcome: AsyncOutcome); } unsafe extern "C++" { include!("workerd/io/io-context/ffi.h"); type IoOwnedObject; + type IsolateWeakRef; + type AbortWatcher; fn io_context_no_request_message() -> &'static str; + fn io_context_never_settled_exception() -> KjException; + fn io_context_memory_limit_exception() -> KjException; + fn io_context_isolate_weak_ref(id: u64) -> Result>; + fn isolate_weak_ref_has_excessively_exceeded_heap_limit( + isolate: &IsolateWeakRef, + ) -> Result; + fn io_context_make_await_js_resource(id: u64) -> Result>>; + fn io_context_watch_abort( + id: u64, + callback: Box, + ) -> Result>; + fn abort_watcher_has_pending_abort(watcher: &AbortWatcher) -> bool; + fn abort_watcher_pending_abort(watcher: &AbortWatcher) -> Result; fn io_context_try_current_id() -> KjMaybe; fn io_context_require_current(id: u64) -> Result<()>; fn io_context_now(id: u64) -> Result; @@ -55,9 +103,7 @@ pub mod bridge { fn io_context_add_object(id: u64, slot: Box) -> Result>; fn io_context_set_fail_open(id: u64) -> Result<()>; - // Returns false when it leaves a JavaScript exception pending. The handle belongs to the - // scope of the caller's lock. - unsafe fn io_context_add_wait_until(id: u64, promise: Local) -> Result; + fn io_context_add_wait_until(id: u64, future: Box) -> Result<()>; fn io_context_check_current(id: u64) -> Result<()>; fn io_context_abort(id: u64, reason: KjException) -> Result<()>; @@ -112,6 +158,23 @@ pub mod bridge { fn trace_context_detach_async(context: Pin<&mut TraceContext>); fn io_context_log_error(message: &str); + + fn io_context_should_log_uncaught_exceptions() -> bool; + fn io_context_log_uncaught_exception_stack(source: UncaughtExceptionSource, stack: &str); + fn io_context_log_uncaught_exception_value( + source: UncaughtExceptionSource, + exception: &str, + ); + // Returns true if the isolate has no inspector. Otherwise, returns false when an + // exception or a termination is pending, or when V8 fails to + // describe the message, leaving an exception pending. The isolate is the caller's lock's, + // and the handle belongs to its scope. + unsafe fn io_context_send_exception_to_inspector( + id: u64, + isolate: *mut Isolate, + source: UncaughtExceptionSource, + exception: Local, + ) -> Result; } /// How `io_callback_run()` ended. @@ -130,7 +193,15 @@ pub mod bridge { type IoCallback; type IoOwnedSlot; + /// What an `AbortWatcher` calls with the exception its `IoContext` was aborted with, on + /// the `IoContext`'s thread, without the isolate lock and with no `IoContext` current. + type AbortCallback; + fn aborted(self: &AbortCallback, exception: KjException); + + type WaitUntilFuture; + async fn io_future_wait(future: Box) -> Result>; + async fn wait_until_future_wait(future: Box) -> Result<()>; unsafe fn io_callback_run( isolate: usize, callback: Box, @@ -139,16 +210,70 @@ pub mod bridge { } } -/// `io_context_add_wait_until()`, failing with [`jsg::Error::pending`] if it left an exception -/// pending. -pub fn add_wait_until<'s>( - _lock: &mut jsg::Lock<'s>, +// SAFETY: an `IsolateWeakRef` holds only a `kj::Own>`, which +// may be used and released on any thread: `AtomicWeakRef` is `kj::AtomicRefcounted`, and a +// `kj::MutexGuarded` guards its pointer to the isolate, which the isolate clears when it is +// destroyed, so `tryAddStrongRef()` is safe on any thread, even once the isolate is gone. The one +// thing Rust does with it, `isolate_weak_ref_has_excessively_exceeded_heap_limit()`, takes a +// strong reference to the `kj::AtomicRefcounted` `Worker::Isolate`, and calls a `const` method of +// its `IsolateLimitEnforcer`, which needs no isolate lock (see its declaration). +unsafe impl Send for bridge::IsolateWeakRef {} + +// SAFETY: an `AsyncResource` holds only a `kj::Arc` and an id. `AsyncTracker`'s +// methods, which `settle()` and the destructor call, are `const` and may be called on any thread: +// on a thread other than the tracker's own, they do nothing but count the call +// (`AsyncTracker::onOwnerThread()`). `kj::Arc` is atomically refcounted, so the reference may be +// released on any thread. Releasing the last one there destroys only a closed tracker, whose +// sinks are gone: the IoContext holds a reference until `OwnedAsyncTracker` closes the tracker +// on its own thread. +unsafe impl Send for bridge::AsyncResource {} + +/// The exception `watcher`'s request was aborted with, if it was aborted after the watcher +/// started; see `abort_watcher_has_pending_abort()`. +pub fn pending_abort(watcher: &bridge::AbortWatcher) -> Option { + if !bridge::abort_watcher_has_pending_abort(watcher) { + return None; + } + // It was just found, so this does not fail. This runs when a sender is dropped, which must + // not panic. + bridge::abort_watcher_pending_abort(watcher).ok() +} + +/// See `bridge::AbortCallback`. The function must not panic, since the call comes from C++, and must +/// not drop the `AbortWatcher` that runs it. +pub struct AbortCallback(pub Box); + +impl AbortCallback { + fn aborted(&self, exception: cxx::KjException) { + (self.0)(exception); + } +} + +/// C++ `IoContext::neverSettledException()`, which C++ thus defines once, for itself and for Rust. +pub fn never_settled_exception() -> cxx::KjException { + bridge::io_context_never_settled_exception() +} + +/// C++ `IoContext::memoryLimitException()`, which C++ thus defines once, for itself and for Rust. +pub fn memory_limit_exception() -> cxx::KjException { + bridge::io_context_memory_limit_exception() +} + +/// `io_context_send_exception_to_inspector()`, failing with [`jsg::Error::pending`] if the +/// isolate has an inspector and an exception or a termination is pending. +pub fn send_exception_to_inspector<'s>( + lock: &jsg::Lock<'s>, id: u64, - promise: v8::Local<'s, v8::Promise>, + source: bridge::UncaughtExceptionSource, + exception: v8::Local<'s, v8::Value>, ) -> jsg::Result<()> { - // SAFETY: the handle belongs to the scope of `lock`, which is open throughout the call. - let added = unsafe { bridge::io_context_add_wait_until(id, promise.into_ffi()) }?; - pending_unless(added) + let isolate = lock.isolate().as_ffi(); + // SAFETY: `lock` keeps the isolate locked, with a context entered, and the handle belongs to + // its scope, which is open throughout the call. + let sent = unsafe { + bridge::io_context_send_exception_to_inspector(id, isolate, source, exception.into_ffi()) + }?; + pending_unless(sent) } /// Aborts the `IoContext` that `id` identifies with `reason`, as [`jsg::Lock::exception_to_kj`] @@ -180,6 +305,10 @@ fn pending_unless(succeeded: bool) -> jsg::Result<()> { /// The future that `IoContext::await_io_and_run()` waits for, with its output type erased. pub struct IoFuture(pub Pin> + Send>>); +/// The future that `io_context_add_wait_until()` waits for as a waitUntil task: an +/// [`AwaitJs`](crate::AwaitJs) whose value is discarded. +pub struct WaitUntilFuture(pub Pin> + Send>>); + /// The output of an [`IoFuture`]. pub struct IoOutput(Box); @@ -207,12 +336,12 @@ pub struct IoOwnedSlot(#[expect(dead_code, reason = "only dropped")] pub Box) -> Result, cxx::KjError> { - let mut future = CatchDropPanic(Some(*future)); + let mut future = CatchDropPanic(Some(future.0)); std::future::poll_fn(move |cx| { let Some(inner) = future.0.as_mut() else { unreachable!("dropped only with the wait") }; - match std::panic::catch_unwind(AssertUnwindSafe(|| inner.0.as_mut().poll(cx))) { + match std::panic::catch_unwind(AssertUnwindSafe(|| inner.as_mut().poll(cx))) { Ok(poll) => poll.map(|output| Ok(Box::new(IoOutput(output)))), Err(payload) => Poll::Ready(Err(cxx::KjError::new( cxx::KjExceptionType::Failed, @@ -226,11 +355,35 @@ async fn io_future_wait(future: Box) -> Result, cxx::KjE .await } -/// Holds the future of an `io_future_wait()`, which kj-rs drops through an `extern "C"` function, -/// where a panic would abort the process. -struct CatchDropPanic(Option); +/// Waits for `future` as a waitUntil task. A panic while polling it fails the task, and a panic +/// while dropping it is logged, as in `io_future_wait()`. The task fails with the future's +/// exception as it is. +async fn wait_until_future_wait(future: Box) -> Result<(), cxx::KjException> { + let mut future = CatchDropPanic(Some(future.0)); + std::future::poll_fn(move |cx| { + let Some(inner) = future.0.as_mut() else { + unreachable!("dropped only with the wait") + }; + match std::panic::catch_unwind(AssertUnwindSafe(|| inner.as_mut().poll(cx))) { + Ok(poll) => poll, + Err(payload) => Poll::Ready(Err(cxx::KjError::new( + cxx::KjExceptionType::Failed, + format!( + "the future of a waitUntil task panicked: {}", + panic_message(&*payload) + ), + ) + .into())), + } + }) + .await +} + +/// Holds the future of an `io_future_wait()` or `wait_until_future_wait()`, which kj-rs drops +/// through an `extern "C"` function, where a panic would abort the process. +struct CatchDropPanic(Option); -impl Drop for CatchDropPanic { +impl Drop for CatchDropPanic { fn drop(&mut self) { let future = self.0.take(); if let Err(payload) = std::panic::catch_unwind(AssertUnwindSafe(|| drop(future))) { diff --git a/src/workerd/io/io-context/io-context-test.c++ b/src/workerd/io/io-context/io-context-test.c++ index 6b739b1ba77..3b4b3c98476 100644 --- a/src/workerd/io/io-context/io-context-test.c++ +++ b/src/workerd/io/io-context/io-context-test.c++ @@ -9,16 +9,20 @@ #include #include #include +#include #include #include #include #include +#include + #include #include #include #include +#include namespace workerd::io_context::test { namespace { @@ -224,22 +228,26 @@ class BridgeListener final: public AsyncTraceListener { kj::Vector& events; }; -class BridgeObserver final: public IsolateObserver { +// Enables async tracing, with a `Listener` that records into `events` as the sink. +template +class TraceObserver final: public IsolateObserver { public: - explicit BridgeObserver(kj::Vector& events): events(events) {} + explicit TraceObserver(kj::Vector& events): events(events) {} kj::Maybe getAsyncTraceConfig() const override { return AsyncTraceConfig{}; } void addAsyncTraceSinks( AsyncTraceSinks& sinks, kj::StringPtr, kj::Maybe) const override { - sinks.add(kj::heap(events)); + sinks.add(kj::heap(events)); } private: kj::Vector& events; }; +using BridgeObserver = TraceObserver; + KJ_TEST("await_io_and_run() is recorded for async tracing, as awaitIo() is") { kj::Vector events; TestFixture fixture({ @@ -932,6 +940,113 @@ KJ_TEST("an add_object() value can be used in place only while its IoContext is fixture.drainAndDestroy(kj::mv(owner)); } +// A full garbage collection, in the request that `request` runs. It runs in an enterContext() of +// its own, so that no handle in the frames of the one that created the objects keeps them alive. +void collectGarbage(TestFixture& fixture, IoContext::IncomingRequest& request) { + fixture.enterContext( + request, [&](const TestFixture::Environment& env) { env.isolate->LowMemoryNotification(); }); +} + +// How the wait of the last await_js_start() ended. +kj::String jsOutcome() { + return kj::str(awaited_js_outcome()); +} + +constexpr kj::StringPtr NEVER_SETTLED_OUTCOME = + "rejected: jsg.Error: Promise will never complete."_kj; + +KJ_TEST("await_js() resolves with the converted value") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::KeepResolver); + }); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "pending"); + + fixture.enterContext(*request, + [&](const TestFixture::Environment& env) { settle_awaited_js(isolateOf(env), true); }); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "fulfilled: 42", jsOutcome()); + KJ_EXPECT(awaited_js_map_runs() == 1); + fixture.drainAndDestroy(kj::mv(request)); +} + +KJ_TEST("await_js() fails with the promise's rejection") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::KeepResolver); + }); + fixture.enterContext(*request, + [&](const TestFixture::Environment& env) { settle_awaited_js(isolateOf(env), false); }); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "rejected: jsg.TypeError: boom", jsOutcome()); + KJ_EXPECT(awaited_js_map_runs() == 0); + fixture.drainAndDestroy(kj::mv(request)); +} + +KJ_TEST("await_js() fails as never settled if tunneling the rejection throws") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::KeepResolver); + }); + // As in C++, what the `stack` getter throws rejects the reaction's promise, which drops the + // half of the wait that settles it. + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + auto reason = runScript(env, R"( + const error = new Error("boom"); + Object.defineProperty(error, "stack", { + get() { throw new TypeError("from stack getter"); }, + }); + error + )"); + reject_awaited_js(isolateOf(env), ::workerd::rust::jsg::to_ffi(kj::mv(reason))); + }); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == NEVER_SETTLED_OUTCOME, jsOutcome()); + fixture.drainAndDestroy(kj::mv(request)); +} + +KJ_TEST("await_js() fails as never settled once GC collects the unsettled promise") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::DropResolver); + }); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "pending"); + + // The reactions' data is dropped inside the collection, with the request current, so the wait + // settles there, as C++ awaitJs()'s does. + collectGarbage(fixture, *request); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == NEVER_SETTLED_OUTCOME, jsOutcome()); + KJ_EXPECT(awaited_js_map_runs() == 0); + fixture.drainAndDestroy(kj::mv(request)); +} + +KJ_TEST("a promise GC collects in another request settles the wait when its request next runs") { + TestFixture fixture; + auto owner = fixture.newIncomingRequest(); + auto other = fixture.newIncomingRequest(); + fixture.enterContext(*owner, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::DropResolver); + }); + + // The sender is queued for its own request to drop, as an IoOwn is. + collectGarbage(fixture, *other); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "pending"); + + fixture.enterContext(*owner, [&](const TestFixture::Environment&) {}); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == NEVER_SETTLED_OUTCOME, jsOutcome()); + fixture.drainAndDestroy(kj::mv(other)); + fixture.drainAndDestroy(kj::mv(owner)); +} + KJ_TEST("a span given to its IoContext ends with it, though its handle outlives it") { auto records = kj::rc(); TestFixture fixture(recordingSpans(*records)); @@ -965,6 +1080,1571 @@ KJ_TEST("a span given to its IoContext ends when its handle is dropped, once its fixture.drainAndDestroy(kj::mv(request)); } +KJ_TEST("a promise that is kept alive is not settled by GC") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::KeepResolver); + }); + collectGarbage(fixture, *request); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "pending"); + + fixture.enterContext(*request, + [&](const TestFixture::Environment& env) { settle_awaited_js(isolateOf(env), true); }); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "fulfilled: 42", jsOutcome()); + fixture.drainAndDestroy(kj::mv(request)); +} + +KJ_TEST("a cancelled await_js() does not run its conversion") { + TestFixture fixture; + auto context = fixture.newIoContext(); + auto request = fixture.newIncomingRequest(*context); + // Once the wait is cancelled, the request has nothing else to wait for, and would be aborted + // as hung. + auto pendingEvent = context->registerPendingEvent(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::Cancellable); + }); + KJ_EXPECT(cancel_awaited_js()); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "cancelled", jsOutcome()); + + fixture.enterContext(*request, + [&](const TestFixture::Environment& env) { settle_awaited_js(isolateOf(env), true); }); + fixture.pollEventLoop(); + KJ_EXPECT(awaited_js_map_runs() == 0); + pendingEvent = nullptr; + fixture.drainAndDestroy(kj::mv(request)); +} + +KJ_TEST("a cancelled await_js() whose promise GC collects drops its sender quietly") { + TestFixture fixture; + auto context = fixture.newIoContext(); + auto request = fixture.newIncomingRequest(*context); + // As above. + auto pendingEvent = context->registerPendingEvent(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::Cancellable); + }); + forget_awaited_js_resolver(); + KJ_EXPECT(cancel_awaited_js()); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "cancelled", jsOutcome()); + collectGarbage(fixture, *request); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "cancelled", jsOutcome()); + pendingEvent = nullptr; + fixture.drainAndDestroy(kj::mv(request)); +} + +KJ_TEST("destroying the IoContext drops an unsettled await_js() with its wait") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::KeepResolver); + }); + fixture.pollEventLoop(); + fixture.drainAndDestroy(kj::mv(request)); + // The future and its callback went with the IoContext's tasks. + KJ_EXPECT(jsOutcome() == "pending"); + forget_awaited_js_resolver(); +} + +constexpr kj::StringPtr MEMORY_LIMIT_OUTCOME = + "rejected: jsg.Error: Worker has exceeded memory limit."_kj; + +// The exception the wait of the last await_js_start() failed with. Call it once per wait. +kj::Exception awaitedJsError() { + return KJ_ASSERT_NONNULL( + kj::runCatchingExceptions([]() { take_awaited_js_error(); }), "the wait has not failed"); +} + +// `exception`'s details, as ": " each, separated by ", ". +kj::String describeDetails(const kj::Exception& exception) { + return kj::strArray(KJ_MAP(detail, exception.getDetails()) { + return kj::str(kj::hex(detail.id), ": ", detail.value.size()); + }, ", "); +} + +// Checks that `exception` is IoContext::memoryLimitException(), as awaitJs() fails with it. Its +// location is the one memoryLimitException() records, which C++ and Rust share; an exception that +// Rust created would have a location in Rust instead. +void expectMemoryLimitException(const kj::Exception& exception) { + auto expected = IoContext::memoryLimitException(); + KJ_EXPECT(exception.getType() == kj::Exception::Type::OVERLOADED, exception); + KJ_EXPECT(exception.getDescription() == kj::str("jsg.Error: ", IoContext::MEMORY_LIMIT_MESSAGE), + exception); + KJ_EXPECT(exception.getFile() == kj::StringPtr(expected.getFile()), exception.getFile()); + KJ_EXPECT(exception.getLine() == expected.getLine(), exception.getLine()); + // The detail, whose value is empty, marks the outcome as out of memory. + KJ_EXPECT(describeDetails(exception) == kj::str(kj::hex(MEMORY_LIMIT_DETAIL_ID), ": 0"), + describeDetails(exception)); + KJ_EXPECT(RequestObserver::outcomeFromException(exception) == EventOutcome::EXCEEDED_MEMORY); +} + +KJ_TEST("await_js() fails with the memory-limit error once GC collects the unsettled promise " + "while the isolate is past its heap limit") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::DropResolver); + }); + fixture.setHeapLimitExcessivelyExceeded(true); + collectGarbage(fixture, *request); + // As in C++, the error is chosen when the promise's reactions are collected, not when the + // wait's future is next polled. + fixture.setHeapLimitExcessivelyExceeded(false); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == MEMORY_LIMIT_OUTCOME, jsOutcome()); + expectMemoryLimitException(awaitedJsError()); + KJ_EXPECT(awaited_js_map_runs() == 0); + fixture.drainAndDestroy(kj::mv(request)); +} + +KJ_TEST("await_js() fails as never settled if the isolate is past its heap limit only while the " + "wait starts") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + fixture.setHeapLimitExcessivelyExceeded(true); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::DropResolver); + }); + fixture.setHeapLimitExcessivelyExceeded(false); + collectGarbage(fixture, *request); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == NEVER_SETTLED_OUTCOME, jsOutcome()); + auto error = awaitedJsError(); + KJ_EXPECT(error.getType() == kj::Exception::Type::FAILED, error); + KJ_EXPECT(error.getDetail(MEMORY_LIMIT_DETAIL_ID) == kj::none, describeDetails(error)); + fixture.drainAndDestroy(kj::mv(request)); +} + +// Whether the isolate is past its heap limit while destroyContextWithHeldWait() destroys the +// IoContext. +enum class HeapLimit { EXCEEDED, NOT_EXCEEDED }; + +// Starts a wait that outlives its IoContext, then destroys the IoContext, with the isolate past +// its heap limit meanwhile as `heapLimit` says, and returns how the wait ended. +kj::String destroyContextWithHeldWait(HeapLimit heapLimit) { + TestFixture fixture; + auto context = fixture.newIoContext(); + auto request = fixture.newIncomingRequest(*context); + // The request waits for nothing that the event loop runs, and would be aborted as hung, which + // would fail the wait first. + auto pendingEvent = context->registerPendingEvent(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::Held); + }); + fixture.pollEventLoop(); + KJ_EXPECT(!poll_held_awaited_js()); + fixture.setHeapLimitExcessivelyExceeded(heapLimit == HeapLimit::EXCEEDED); + fixture.drainAndDestroy(kj::mv(request)); + pendingEvent = nullptr; + context = nullptr; + fixture.setHeapLimitExcessivelyExceeded(false); + // The IoContext dropped the sender, and with it the abort watcher, which never saw an abort: the + // sender settled the wait as it was dropped. + KJ_EXPECT(poll_held_awaited_js()); + forget_awaited_js_resolver(); + return jsOutcome(); +} + +KJ_TEST("destroying the IoContext while the isolate is past its heap limit fails an unsettled " + "await_js() with the memory-limit error") { + auto outcome = destroyContextWithHeldWait(HeapLimit::EXCEEDED); + KJ_EXPECT(outcome == MEMORY_LIMIT_OUTCOME, outcome); + expectMemoryLimitException(awaitedJsError()); +} + +KJ_TEST("destroying the IoContext fails an unsettled await_js() as never settled") { + auto outcome = destroyContextWithHeldWait(HeapLimit::NOT_EXCEEDED); + KJ_EXPECT(outcome == NEVER_SETTLED_OUTCOME, outcome); +} + +KJ_TEST("past the heap limit, await_js() fails with the exception C++ awaitJs() fails with") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + kj::Maybe cppError; + kj::Maybe> cppWait; + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + // Both promises are unreachable once their resolvers are dropped, here and in Rust. + auto paf = env.js.newPromiseAndResolver(); + cppWait = env.context.awaitJs(env.js, kj::mv(paf.promise)) + .then([]() { KJ_FAIL_EXPECT("C++ awaitJs() fulfilled"); }, + [&cppError](kj::Exception&& e) { + cppError = kj::mv(e); + }).eagerlyEvaluate(nullptr); + await_js_start(isolateOf(env), AwaitJsStart::DropResolver); + }); + fixture.setHeapLimitExcessivelyExceeded(true); + collectGarbage(fixture, *request); + fixture.setHeapLimitExcessivelyExceeded(false); + fixture.pollEventLoop(); + + auto& cpp = KJ_ASSERT_NONNULL(cppError, "C++ awaitJs() has not failed"); + auto rust = awaitedJsError(); + expectMemoryLimitException(cpp); + KJ_EXPECT(rust.getType() == cpp.getType(), rust, cpp); + KJ_EXPECT(rust.getDescription() == cpp.getDescription(), rust, cpp); + KJ_EXPECT(kj::StringPtr(rust.getFile()) == kj::StringPtr(cpp.getFile()), rust, cpp); + KJ_EXPECT(rust.getLine() == cpp.getLine(), rust, cpp); + KJ_EXPECT(describeDetails(rust) == describeDetails(cpp), rust, cpp); + cppWait = kj::none; + fixture.drainAndDestroy(kj::mv(request)); +} + +// Records the init, settle and destroy events of the awaitJs resources an async tracker creates, +// labelled as in async-trace-io-test.c++: "awaitJs#1" is the first, and "request" a request, so +// that the events of different runs compare equal. +class AwaitJsTraceListener final: public AsyncTraceListener { + public: + explicit AwaitJsTraceListener(kj::Vector& events): events(events) {} + + void onInit(uint64_t, const AsyncInitEvent& e) override { + if (e.kind == AsyncKind::REQUEST) { + labels.insert(e.id, kj::str("request")); + } else if (e.kind == AsyncKind::JS_TO_KJ && e.name == "awaitJs"_kj.asArray()) { + auto label = kj::str("awaitJs#", ++awaitJsCount); + events.add( + kj::str("init ", label, " trigger=", labelOf(e.trigger), " exec=", labelOf(e.execution))); + labels.insert(e.id, kj::mv(label)); + } + } + void onSettle(uint64_t, AsyncId id, AsyncOutcome outcome, uint64_t) override { + KJ_IF_SOME(label, awaitJsLabel(id)) { + events.add(kj::str("settle ", label, " ", nameOf(outcome))); + } + } + void onDestroy(uint64_t, AsyncId id, uint64_t) override { + KJ_IF_SOME(label, awaitJsLabel(id)) { + events.add(kj::str("destroy ", label)); + } + } + + private: + kj::Vector& events; + kj::HashMap labels; + uint awaitJsCount = 0; + + kj::String labelOf(AsyncId id) { + if (id == 0) return kj::str("-"); + KJ_IF_SOME(label, labels.find(id)) { + return kj::str(label); + } + return kj::str("?", id); + } + + kj::Maybe awaitJsLabel(AsyncId id) { + KJ_IF_SOME(label, labels.find(id)) { + if (label.startsWith("awaitJs#")) return label.asPtr(); + } + return kj::none; + } + + static kj::StringPtr nameOf(AsyncOutcome outcome) { + switch (outcome) { + case AsyncOutcome::OK: + return "OK"_kj; + case AsyncOutcome::ERROR: + return "ERROR"_kj; + case AsyncOutcome::CANCELED: + return "CANCELED"_kj; + } + KJ_UNREACHABLE; + } +}; + +// Records "released" as the tracker releases the resource of an await_js() wait. A Rust wait's +// sender holds the resource and its abort watcher, and releases the resource, settled or not, as +// it is dropped, so this records when the watcher is dropped. +class AwaitJsReleaseListener final: public AsyncTraceListener { + public: + explicit AwaitJsReleaseListener(kj::Vector& events): events(events) {} + + void onInit(uint64_t, const AsyncInitEvent& e) override { + if (e.kind == AsyncKind::JS_TO_KJ && e.name == "awaitJs"_kj.asArray()) { + awaitJsIds.insert(e.id); + } + } + void onRelease(uint64_t, AsyncId id) override { + if (awaitJsIds.contains(id)) { + events.add(kj::str("released")); + } + } + + private: + kj::Vector& events; + kj::HashSet awaitJsIds; +}; + +// How the wait that traceAwaitJs() starts ends. +enum class TracedWait { + FULFILLED, + REJECTED, + // The conversion fails with its own error, a KJ exception in C++. + MAP_FAILS, + // JavaScript throws in the conversion. + MAP_THROWS, + CANCELLED_THEN_FULFILLED, + CANCELLED_THEN_REJECTED, + // GC collects the promise of a cancelled wait, which never settles. + CANCELLED_THEN_COLLECTED, + // GC collects the promise, which never settles. + NEVER_SETTLED, +}; + +kj::StringPtr nameOf(TracedWait scenario) { + switch (scenario) { + case TracedWait::FULFILLED: + return "FULFILLED"_kj; + case TracedWait::REJECTED: + return "REJECTED"_kj; + case TracedWait::MAP_FAILS: + return "MAP_FAILS"_kj; + case TracedWait::MAP_THROWS: + return "MAP_THROWS"_kj; + case TracedWait::CANCELLED_THEN_FULFILLED: + return "CANCELLED_THEN_FULFILLED"_kj; + case TracedWait::CANCELLED_THEN_REJECTED: + return "CANCELLED_THEN_REJECTED"_kj; + case TracedWait::CANCELLED_THEN_COLLECTED: + return "CANCELLED_THEN_COLLECTED"_kj; + case TracedWait::NEVER_SETTLED: + return "NEVER_SETTLED"_kj; + } + KJ_UNREACHABLE; +} + +bool isCancelled(TracedWait scenario) { + return scenario == TracedWait::CANCELLED_THEN_FULFILLED || + scenario == TracedWait::CANCELLED_THEN_REJECTED || + scenario == TracedWait::CANCELLED_THEN_COLLECTED; +} + +bool isCollected(TracedWait scenario) { + return scenario == TracedWait::NEVER_SETTLED || scenario == TracedWait::CANCELLED_THEN_COLLECTED; +} + +bool fulfills(TracedWait scenario) { + return scenario != TracedWait::REJECTED && scenario != TracedWait::CANCELLED_THEN_REJECTED; +} + +enum class Implementation { CPP, RUST }; + +// A wait of C++ IoContext::awaitJs(), the counterpart of the one await_js_start() starts through +// Rust's await_js(). Its resolver, if kept, must be taken in a request. +struct CppAwaitJs { + kj::Maybe::Resolver> resolver; + kj::Maybe> wait; + // How many times the conversion ran, as awaited_js_map_runs() counts for Rust's. + static inline uint mapRuns = 0; + + // Starts the wait, with the conversion `scenario` calls for, and keeps the resolver unless GC + // is to collect the promise. + void start(const TestFixture::Environment& env, TracedWait scenario) { + switch (scenario) { + case TracedWait::MAP_FAILS: + startWith(env, scenario, [](jsg::Lock&, double) -> double { + ++mapRuns; + JSG_FAIL_REQUIRE(RangeError, "the conversion failed"); + }); + break; + case TracedWait::MAP_THROWS: + startWith(env, scenario, [](jsg::Lock& js, double) -> double { + ++mapRuns; + js.throwException(js.rangeError("thrown by JavaScript")); + }); + break; + default: + startWith(env, scenario, [](jsg::Lock&, double value) { + ++mapRuns; + return value; + }); + break; + } + } + + // Fulfills the promise with 42, or rejects it with a TypeError, as `scenario` says, like + // settle_awaited_js(). + void settle(const TestFixture::Environment& env, TracedWait scenario) { + auto taken = KJ_ASSERT_NONNULL(kj::mv(resolver), "the resolver was not kept"); + resolver = kj::none; + if (fulfills(scenario)) { + taken.resolve(env.js, 42.0); + } else { + taken.reject(env.js, env.js.typeError("boom")); + } + } + + private: + template + void startWith(const TestFixture::Environment& env, TracedWait scenario, Func func) { + auto paf = env.js.newPromiseAndResolver(); + wait = env.context.awaitJs(env.js, kj::mv(paf.promise), kj::mv(func)) + .then([](double) {}, [](kj::Exception&&) { + }).eagerlyEvaluate(nullptr); + if (!isCollected(scenario)) resolver = kj::mv(paf.resolver); + } +}; + +// The way await_js_start() starts the Rust counterpart of `scenario`'s wait. +AwaitJsStart rustStart(TracedWait scenario) { + switch (scenario) { + case TracedWait::FULFILLED: + case TracedWait::REJECTED: + return AwaitJsStart::KeepResolver; + case TracedWait::MAP_FAILS: + return AwaitJsStart::MapFails; + case TracedWait::MAP_THROWS: + return AwaitJsStart::MapThrows; + case TracedWait::CANCELLED_THEN_FULFILLED: + case TracedWait::CANCELLED_THEN_REJECTED: + case TracedWait::CANCELLED_THEN_COLLECTED: + return AwaitJsStart::Cancellable; + case TracedWait::NEVER_SETTLED: + return AwaitJsStart::DropResolver; + } + KJ_UNREACHABLE; +} + +// Starts a wait in a traced request through C++ awaitJs() or Rust's await_js(), has it go as +// `scenario` says, and returns the events of its awaitJs resource, one per line. "settling" and +// "settled" bracket the turn in which the promise settles or GC collects it, so the events show +// that the resource is settled or destroyed in that turn, by the reaction or the collection. +kj::String traceAwaitJs(TracedWait scenario, Implementation implementation) { + kj::Vector events; + { + TestFixture fixture({ + .useRealTimers = false, + .isolateObserver = kj::atomicRefcounted>(events), + }); + auto context = fixture.newIoContext(); + auto request = fixture.newIncomingRequest(*context); + // A cancelled wait leaves the request nothing else to wait for, and it would be aborted as + // hung. + auto pendingEvent = context->registerPendingEvent(); + CppAwaitJs cpp; + CppAwaitJs::mapRuns = 0; + + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + if (implementation == Implementation::RUST) { + await_js_start(isolateOf(env), rustStart(scenario)); + // A cancellable wait keeps its resolver; this one's promise is to be collected. + if (scenario == TracedWait::CANCELLED_THEN_COLLECTED) forget_awaited_js_resolver(); + } else { + cpp.start(env, scenario); + } + }); + fixture.pollEventLoop(); + + if (isCancelled(scenario)) { + if (implementation == Implementation::RUST) { + KJ_EXPECT(cancel_awaited_js()); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "cancelled", jsOutcome()); + } else { + cpp.wait = kj::none; + fixture.pollEventLoop(); + } + } + + events.add(kj::str("settling")); + if (isCollected(scenario)) { + collectGarbage(fixture, *request); + } else { + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + if (implementation == Implementation::RUST) { + settle_awaited_js(isolateOf(env), fulfills(scenario)); + } else { + cpp.settle(env, scenario); + } + }); + } + events.add(kj::str("settled")); + fixture.pollEventLoop(); + if (isCancelled(scenario)) { + auto mapRuns = + implementation == Implementation::RUST ? awaited_js_map_runs() : CppAwaitJs::mapRuns; + KJ_EXPECT(mapRuns == 0, nameOf(scenario), mapRuns); + } + + cpp.wait = kj::none; + pendingEvent = nullptr; + fixture.drainAndDestroy(kj::mv(request)); + } + return kj::strArray(events, "\n"); +} + +// Runs `scenario` through C++ awaitJs() and Rust's await_js(), checks that their events are +// the same, and returns them. +kj::String traceAwaitJsOnBoth(TracedWait scenario) { + auto cpp = traceAwaitJs(scenario, Implementation::CPP); + auto rust = traceAwaitJs(scenario, Implementation::RUST); + KJ_EXPECT(cpp == rust, nameOf(scenario), cpp, rust); + return cpp; +} + +// The events traceAwaitJs() expects when the wait's resource is created, then `last` happens in +// the turn in which its promise settles or GC collects it. +kj::String expectedAwaitJsEvents(kj::StringPtr last) { + return kj::str("init awaitJs#1 trigger=request exec=request\nsettling\n", last, "\nsettled"); +} + +KJ_TEST("await_js() is recorded for async tracing and settled OK when fulfilled, as in C++") { + auto events = traceAwaitJsOnBoth(TracedWait::FULFILLED); + KJ_EXPECT(events == expectedAwaitJsEvents("settle awaitJs#1 OK"), events); +} + +KJ_TEST("await_js() is settled with an error for async tracing when the promise rejects or the " + "conversion fails, as in C++") { + for (auto scenario: {TracedWait::REJECTED, TracedWait::MAP_FAILS, TracedWait::MAP_THROWS}) { + auto events = traceAwaitJsOnBoth(scenario); + KJ_EXPECT(events == expectedAwaitJsEvents("settle awaitJs#1 ERROR"), nameOf(scenario), events); + } +} + +KJ_TEST("a cancelled await_js() is still settled for async tracing as its promise settles, as in " + "C++") { + auto fulfilled = traceAwaitJsOnBoth(TracedWait::CANCELLED_THEN_FULFILLED); + KJ_EXPECT(fulfilled == expectedAwaitJsEvents("settle awaitJs#1 OK"), fulfilled); + auto rejected = traceAwaitJsOnBoth(TracedWait::CANCELLED_THEN_REJECTED); + KJ_EXPECT(rejected == expectedAwaitJsEvents("settle awaitJs#1 ERROR"), rejected); +} + +KJ_TEST("an await_js() whose promise never settles is destroyed unsettled for async tracing, as " + "in C++") { + for (auto scenario: {TracedWait::NEVER_SETTLED, TracedWait::CANCELLED_THEN_COLLECTED}) { + auto events = traceAwaitJsOnBoth(scenario); + KJ_EXPECT(events == expectedAwaitJsEvents("destroy awaitJs#1"), nameOf(scenario), events); + } +} + +// Starts a wait of Rust's await_js() as `start` says in a new request of `fixture`, which must +// not be traced, fulfills its promise or has GC collect it, and returns how the wait ended. +kj::String awaitJsUntraced(TestFixture& fixture, AwaitJsStart start) { + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + KJ_EXPECT(env.context.tryGetAsyncTracker() == kj::none); + KJ_EXPECT(io_context_make_await_js_resource(idOf(env.context)) == kj::none); + await_js_start(isolateOf(env), start); + }); + if (start == AwaitJsStart::DropResolver) { + collectGarbage(fixture, *request); + } else { + fixture.enterContext(*request, + [&](const TestFixture::Environment& env) { settle_awaited_js(isolateOf(env), true); }); + } + fixture.pollEventLoop(); + fixture.drainAndDestroy(kj::mv(request)); + return jsOutcome(); +} + +KJ_TEST("in an untraced request, await_js() creates no async trace resource and still settles") { + TestFixture fixture; + auto fulfilled = awaitJsUntraced(fixture, AwaitJsStart::KeepResolver); + KJ_EXPECT(fulfilled == "fulfilled: 42", fulfilled); + auto mapFailed = awaitJsUntraced(fixture, AwaitJsStart::MapFails); + KJ_EXPECT(mapFailed == "rejected: jsg.RangeError: the conversion failed", mapFailed); + auto neverSettled = awaitJsUntraced(fixture, AwaitJsStart::DropResolver); + KJ_EXPECT(neverSettled == NEVER_SETTLED_OUTCOME, neverSettled); +} + +// Records the uncaught exceptions the worker logs, which it logs only at INFO level, while it +// exists, and passes on other messages the log level allowed before, as in request-ops-test.c++. +// Only INFO messages are recorded, so that a failed KJ_EXPECT that quotes one reaches the test. +class UncaughtExceptionLog final: public kj::ExceptionCallback { + public: + UncaughtExceptionLog(): previousLevel(currentLogLevel()) { + kj::_::Debug::setLogLevel(kj::LogSeverity::INFO); + } + ~UncaughtExceptionLog() noexcept(false) { + kj::_::Debug::setLogLevel(previousLevel); + } + + void logMessage(kj::LogSeverity severity, + const char* file, + int line, + int contextDepth, + kj::String&& text) override { + if (severity == kj::LogSeverity::INFO && text.contains("uncaught exception")) { + messages.add(kj::mv(text)); + } else if (severity >= previousLevel) { + next.logMessage(severity, file, line, contextDepth, kj::mv(text)); + } + } + + // The messages recorded since the last call, separated by " | ". + kj::String take() { + auto result = kj::strArray(messages, " | "); + messages.clear(); + return result; + } + + kj::Vector messages; + + private: + kj::LogSeverity previousLevel; + + // KJ has no getter for the log level. + static kj::LogSeverity currentLogLevel() { + for (auto severity: {kj::LogSeverity::INFO, kj::LogSeverity::WARNING, kj::LogSeverity::ERROR, + kj::LogSeverity::FATAL}) { + if (kj::_::Debug::shouldLog(severity)) return severity; + } + return kj::LogSeverity::DBG; + } +}; + +// How an await_js() rejection is logged, up to what follows "stack = " or "exception = ". +constexpr kj::StringPtr IN_PROMISE = "uncaught exception; source = Uncaught (in promise); "_kj; + +// Rejects the promise of the last await_js_start() with the value of `source`, a script. +void rejectAwaitedJs( + TestFixture& fixture, IoContext::IncomingRequest& request, kj::StringPtr source) { + fixture.enterContext(request, [&](const TestFixture::Environment& env) { + reject_awaited_js(isolateOf(env), ::workerd::rust::jsg::to_ffi(runScript(env, source))); + }); +} + +KJ_TEST("await_js() logs a rejection as an uncaught exception, once, with its stack") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::KeepResolver); + }); + UncaughtExceptionLog log; + rejectAwaitedJs(fixture, *request, R"((() => { + const error = new RangeError("boom"); + error.stack = "the stack"; + return error; + })())"); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "rejected: jsg.RangeError: boom", jsOutcome()); + auto logged = log.take(); + KJ_EXPECT(logged == kj::str(IN_PROMISE, "stack = the stack"), logged); + fixture.drainAndDestroy(kj::mv(request)); +} + +KJ_TEST("await_js() logs a rejection with a value that has no stack as the value") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::KeepResolver); + }); + UncaughtExceptionLog log; + rejectAwaitedJs(fixture, *request, R"("a string")"); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "rejected: jsg.Error: a string", jsOutcome()); + auto logged = log.take(); + KJ_EXPECT(logged == kj::str(IN_PROMISE, "exception = a string"), logged); + fixture.drainAndDestroy(kj::mv(request)); +} + +KJ_TEST("await_js() logs what JavaScript throws in its conversion, once, then tunnels it") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::MapThrows); + }); + UncaughtExceptionLog log; + fixture.enterContext(*request, + [&](const TestFixture::Environment& env) { settle_awaited_js(isolateOf(env), true); }); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "rejected: jsg.RangeError: thrown by JavaScript", jsOutcome()); + KJ_EXPECT(awaited_js_map_runs() == 1); + KJ_EXPECT(log.messages.size() == 1, kj::strArray(log.messages, " | ")); + auto logged = log.take(); + KJ_EXPECT( + logged.startsWith(kj::str(IN_PROMISE, "stack = RangeError: thrown by JavaScript")), logged); + fixture.drainAndDestroy(kj::mv(request)); +} + +KJ_TEST("await_js() converts its conversion's own error, logs it and tunnels it as one thrown") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::MapFails); + }); + UncaughtExceptionLog log; + fixture.enterContext(*request, + [&](const TestFixture::Environment& env) { settle_awaited_js(isolateOf(env), true); }); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "rejected: jsg.RangeError: the conversion failed", jsOutcome()); + // Tunneled as a JavaScript exception is, with the error serialized and its name and stack. + auto detailIds = awaited_js_detail_ids(); + auto ids = kj::arrayPtr(detailIds.data(), detailIds.size()); + KJ_EXPECT(ids.findFirst(jsg::TUNNELED_EXCEPTION_DETAIL_ID) != kj::none); + KJ_EXPECT(ids.findFirst(jsg::JS_EXCEPTION_METADATA_DETAIL_ID) != kj::none); + KJ_EXPECT(log.messages.size() == 1, kj::strArray(log.messages, " | ")); + auto logged = log.take(); + KJ_EXPECT( + logged.startsWith(kj::str(IN_PROMISE, "stack = RangeError: the conversion failed")), logged); + fixture.drainAndDestroy(kj::mv(request)); +} + +KJ_TEST("await_js() redacts and logs its conversion's internal error, then tunnels it") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::MapFailsInternally); + }); + UncaughtExceptionLog log; + { + KJ_EXPECT_LOG(ERROR, "internalMessage = the conversion failed internally"); + fixture.enterContext(*request, + [&](const TestFixture::Environment& env) { settle_awaited_js(isolateOf(env), true); }); + fixture.pollEventLoop(); + } + KJ_EXPECT( + jsOutcome().startsWith("rejected: jsg.Error: internal error; reference = "), jsOutcome()); + auto logged = log.take(); + KJ_EXPECT(logged.startsWith(kj::str(IN_PROMISE, "stack = Error: internal error; reference = ")), + logged); + fixture.drainAndDestroy(kj::mv(request)); +} + +KJ_TEST("a fulfilled await_js() logs nothing") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::KeepResolver); + }); + UncaughtExceptionLog log; + fixture.enterContext(*request, + [&](const TestFixture::Environment& env) { settle_awaited_js(isolateOf(env), true); }); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "fulfilled: 42", jsOutcome()); + auto logged = log.take(); + KJ_EXPECT(logged == "", logged); + fixture.drainAndDestroy(kj::mv(request)); +} + +KJ_TEST("await_js() logs a rejection before tunneling it, which then does not happen if logging " + "throws") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::KeepResolver); + }); + UncaughtExceptionLog log; + // Tunneling reads `overloaded` first, and logging reads `stack`. + rejectAwaitedJs(fixture, *request, R"(({ + get overloaded() { globalThis.tunneled = true; return false; }, + get stack() { throw new TypeError("from stack getter"); }, + }))"); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == NEVER_SETTLED_OUTCOME, jsOutcome()); + KJ_EXPECT(evaluate(fixture, "String(globalThis.tunneled)") == "undefined"); + auto logged = log.take(); + KJ_EXPECT(!logged.contains("Uncaught (in promise)"), logged); + fixture.drainAndDestroy(kj::mv(request)); +} + +// The notifications an inspector session sends, which InspectorChannel receives. +class InspectorNotifications { + public: + void add(kj::String notification) { + notifications.add(kj::mv(notification)); + } + + // The notifications received since the last call, separated by " | ", with the values of the + // fields that differ from one report of an exception to that of the same exception, created by + // the same source in another script, replaced with `_`. + kj::String take() { + auto result = kj::strArray(KJ_MAP(notification, notifications) { + return withoutFields( + notification, {"timestamp"_kj, "exceptionId"_kj, "objectId"_kj, "scriptId"_kj}); + }, " | "); + notifications.clear(); + return result; + } + + private: + kj::Vector notifications; + + // `json` with the value of each field named in `names` replaced with `_`. + static kj::String withoutFields(kj::StringPtr json, std::initializer_list names) { + kj::String result = kj::str(json); + for (auto name: names) { + auto key = kj::str("\"", name, "\":"); + kj::Vector out; + kj::StringPtr rest = result; + while (true) { + KJ_IF_SOME(at, rest.find(key)) { + out.addAll(rest.first(at + key.size())); + rest = rest.slice(at + key.size()); + size_t end = 0; + if (rest.startsWith("\"")) { + end = 1; + while (end < rest.size() && rest[end] != '"') { + end += rest[end] == '\\' ? 2 : 1; + } + ++end; + } else { + while (end < rest.size() && rest[end] != ',' && rest[end] != '}') ++end; + } + out.add('_'); + rest = rest.slice(kj::min(end, rest.size())); + } else { + out.addAll(rest); + break; + } + } + out.add('\0'); + result = kj::String(out.releaseAsArray()); + } + return result; + } +}; + +class InspectorChannel final: public v8_inspector::V8Inspector::Channel { + public: + explicit InspectorChannel(InspectorNotifications& notifications): notifications(notifications) {} + + void sendResponse(int, std::unique_ptr) override {} + void sendNotification(std::unique_ptr message) override { + notifications.add(kj::str(message->string())); + } + void flushProtocolNotifications() override {} + + private: + InspectorNotifications& notifications; +}; + +// The parameters of a fixture whose isolate has an inspector, without a DevTools server. +TestFixture::SetupParams inspectorParams(capnp::MallocMessageBuilder& flagsMessage) { + auto flags = flagsMessage.initRoot(); + flags.setEnableNodeJsInspectorLocalDev(true); + return {.featureFlags = flags.asReader(), .useRealTimers = false}; +} + +// Connects a session to the inspector of the isolate of `env`, and enables its Runtime domain, +// which reports exceptions. The session must be destroyed under the isolate lock. +std::unique_ptr connectInspector( + const TestFixture::Environment& env, InspectorChannel& channel) { + auto& inspector = KJ_ASSERT_NONNULL(env.context.getWorker().getIsolate().tryGetV8Inspector()); + // Context group 1 is the worker's (setupContext() in worker.c++). + auto session = inspector.connect( + 1, &channel, v8_inspector::StringView(), v8_inspector::V8Inspector::kFullyTrusted); + auto enable = R"({"id":1,"method":"Runtime.enable"})"_kj; + session->dispatchProtocolMessage( + v8_inspector::StringView(enable.asBytes().begin(), enable.size())); + return session; +} + +KJ_TEST("log_uncaught_exception() reports to the inspector and logs as C++ logUncaughtException() " + "does") { + capnp::MallocMessageBuilder flagsMessage; + TestFixture fixture(inspectorParams(flagsMessage)); + UncaughtExceptionLog log; + InspectorNotifications notifications; + InspectorChannel channel(notifications); + fixture.runInIoContext([&](const TestFixture::Environment& env) { + auto session = connectInspector(env, channel); + notifications.take(); + + struct Source { + UncaughtExceptionSource cpp; + LogSource rust; + }; + for (auto source: {Source{UncaughtExceptionSource::INTERNAL, LogSource::Internal}, + Source{UncaughtExceptionSource::INTERNAL_ASYNC, LogSource::InternalAsync}}) { + auto prefix = kj::str("uncaught exception; source = ", source.cpp, "; "); + for (auto script: + { + R"(new RangeError("boom"))"_kj, + R"((() => { const e = new Error("with\0nul"); e.stack = "before\0after"; return e; })())"_kj, + R"(new TypeError("caf\u00e9 \u{1F600}"))"_kj, + R"("a string")"_kj, + R"(({ stack: 42 }))"_kj, + R"(({}))"_kj, + R"(Symbol("symbol"))"_kj, + "undefined"_kj, + "null"_kj, + }) { + // Each implementation gets a value of its own, since reading an error's `stack` formats + // its stack trace, after which V8 no longer finds the location of the error in it. + auto cppValue = runScript(env, script); + auto rustValue = runScript(env, script); + env.context.logUncaughtException(source.cpp, jsg::JsValue(cppValue)); + auto cppReport = notifications.take(); + auto cppLog = log.take(); + + log_uncaught_exception( + isolateOf(env), source.rust, ::workerd::rust::jsg::to_ffi(kj::mv(rustValue))); + auto rustReport = notifications.take(); + auto rustLog = log.take(); + + KJ_EXPECT(cppReport.contains(R"j("method":"Runtime.exceptionThrown")j"), script, cppReport); + KJ_EXPECT(rustReport == cppReport, script, rustReport, cppReport); + KJ_EXPECT(cppLog.startsWith(prefix), script, cppLog); + KJ_EXPECT(rustLog == cppLog, script, rustLog, cppLog); + } + } + // Disconnected under the isolate lock. + session = nullptr; + }); +} + +KJ_TEST("await_js() reports a rejection to the inspector once, without logging at INFO level") { + capnp::MallocMessageBuilder flagsMessage; + TestFixture fixture(inspectorParams(flagsMessage)); + InspectorNotifications notifications; + InspectorChannel channel(notifications); + std::unique_ptr session; + auto context = fixture.newIoContext(); + auto request = fixture.newIncomingRequest(*context); + // Once the wait ends, the request has nothing else to wait for, and would be aborted as hung + // before the session is disconnected. + auto pendingEvent = context->registerPendingEvent(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + session = connectInspector(env, channel); + await_js_start(isolateOf(env), AwaitJsStart::KeepResolver); + }); + notifications.take(); + rejectAwaitedJs(fixture, *request, R"(new RangeError("boom"))"); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "rejected: jsg.RangeError: boom", jsOutcome()); + auto reports = notifications.take(); + KJ_EXPECT(reports.startsWith(R"j({"method":"Runtime.exceptionThrown")j"), reports); + KJ_EXPECT(reports.contains(R"j("text":"Uncaught RangeError: boom")j"), reports); + KJ_EXPECT(!reports.contains(" | "), reports); + fixture.enterContext(*request, [&](const TestFixture::Environment&) { session = nullptr; }); + pendingEvent = nullptr; + fixture.drainAndDestroy(kj::mv(request)); +} + +enum class LogLevel { DEFAULT, INFO }; + +// How many times the `stack` getter of a rejection runs while await_js() handles it, at `level`. +kj::String stackReads(LogLevel level) { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::KeepResolver); + }); + kj::Maybe log; + if (level == LogLevel::INFO) log.emplace(); + rejectAwaitedJs(fixture, *request, R"(({ + get stack() { + globalThis.stackReads = (globalThis.stackReads ?? 0) + 1; + return "the stack"; + }, + }))"); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome().startsWith("rejected: "), jsOutcome()); + auto reads = evaluate(fixture, "String(globalThis.stackReads)"); + fixture.drainAndDestroy(kj::mv(request)); + return reads; +} + +KJ_TEST("await_js() reads a rejection's stack to log it only when KJ logs at INFO level") { + // Tunneling reads it too. + auto quiet = stackReads(LogLevel::DEFAULT); + auto verbose = stackReads(LogLevel::INFO); + auto quietReads = KJ_ASSERT_NONNULL(quiet.tryParseAs(), quiet); + KJ_EXPECT(verbose == kj::str(quietReads + 1), quiet, verbose); +} + +constexpr kj::Exception::DetailTypeId ABORT_DETAIL_ID = 0xab07'0000'0000'0001ull; + +// The exception the tests below abort a request with. Its type is not FAILED, and it has a +// detail and a stack trace, so that a wait that fails with it is seen to fail with this very +// exception. +kj::Exception abortException() { + auto e = KJ_EXCEPTION(OVERLOADED, "jsg.Error: aborted by the test"); + e.setDetail(ABORT_DETAIL_ID, kj::heapArray({1, 2, 3})); + e.addTrace(reinterpret_cast(0xab07)); + return e; +} + +// The first address of `exception`'s stack trace, in hex, or "none". +kj::String traceOrigin(const kj::Exception& exception) { + auto trace = exception.getStackTrace(); + if (trace.size() == 0) return kj::str("none"); + return kj::str(kj::hex(reinterpret_cast(trace[0]))); +} + +// Checks that `actual` is `expected`: with its type, description, location and details, and, if +// `expected` has a stack trace, with the trace starting where it does. Each KJ promise that an +// exception passes through adds an address to its trace, and those differ between C++ and Rust. +void expectSameException(const kj::Exception& actual, const kj::Exception& expected) { + KJ_EXPECT(actual.getType() == expected.getType(), actual, expected); + KJ_EXPECT(actual.getDescription() == expected.getDescription(), actual, expected); + KJ_EXPECT(kj::StringPtr(actual.getFile()) == kj::StringPtr(expected.getFile()), actual, expected); + KJ_EXPECT(actual.getLine() == expected.getLine(), actual, expected); + KJ_EXPECT(describeDetails(actual) == describeDetails(expected), describeDetails(actual), + describeDetails(expected)); + if (expected.getStackTrace().size() > 0) { + KJ_EXPECT( + traceOrigin(actual) == traceOrigin(expected), traceOrigin(actual), traceOrigin(expected)); + } +} + +// A wait of C++ IoContext::awaitJs(), recorded as await_js_start() records Rust's. +struct RecordedCppAwaitJs { + kj::Maybe::Resolver> resolver; + kj::String outcome = kj::str("pending"); + kj::Maybe error; + // Declared after what its continuations record into, so that it is destroyed first. + kj::Maybe> wait; + // How many times the conversion ran, as awaited_js_map_runs() counts for Rust's. + static inline uint mapRuns = 0; + + // The wait, which nothing waits for until waitHeld() is called; see startHeld(). + kj::Maybe> held; + + void start(const TestFixture::Environment& env) { + startHeld(env); + waitHeld(); + } + + // Starts the wait without waiting for it, as await_js_start(Held) does. + void startHeld(const TestFixture::Environment& env) { + auto paf = env.js.newPromiseAndResolver(); + resolver = kj::mv(paf.resolver); + held = env.context.awaitJs(env.js, kj::mv(paf.promise), [](jsg::Lock&, double value) { + ++mapRuns; + return value; + }); + } + + // Waits for the wait startHeld() started, recording its outcome. + void waitHeld() { + auto promise = KJ_ASSERT_NONNULL(kj::mv(held), "no held wait"); + held = kj::none; + // The continuations record into members of this object, which owns them through `wait`. + // NOLINTBEGIN(workerd-unsafe-continuation-capture) + wait = kj::mv(promise) + .then([&outcome = outcome](double value) { + outcome = kj::str("fulfilled: ", value); + }, [&outcome = outcome, &error = error](kj::Exception&& e) { + outcome = kj::str("rejected: ", e.getDescription()); + error = kj::mv(e); + }).eagerlyEvaluate(nullptr); + // NOLINTEND(workerd-unsafe-continuation-capture) + } + + // Cancels the wait, recorded as Rust's cancelled wait is. + void cancel() { + wait = kj::none; + outcome = kj::str("cancelled"); + } + + // Fulfills the promise with 42, or rejects it with a TypeError, as settle_awaited_js() does. + void settle(jsg::Lock& js, bool fulfill) { + auto taken = KJ_ASSERT_NONNULL(kj::mv(resolver), "the resolver was not kept"); + resolver = kj::none; + if (fulfill) { + taken.resolve(js, 42.0); + } else { + taken.reject(js, js.typeError("boom")); + } + } +}; + +// Runs `settle` outside any request, then has `context`, which was aborted and no longer runs, +// run the reactions it queued with `context` current, as V8 runs them in the next microtask +// checkpoint of the isolate: here, in the one `context` runs when it logs an uncaught exception +// with the isolate lock, as it does when the isolate has an inspector. +template +void settleOnceAborted(TestFixture& fixture, IoContext& context, Func&& settle) { + fixture.enterWorkerLock([&](Worker::Lock& lock) { + JSG_WITHIN_CONTEXT_SCOPE(lock, lock.getContext(), [&](jsg::Lock& js) { settle(js); }); + }); + KJ_EXPECT_LOG(ERROR, "draining the microtask queue"); + context.logUncaughtExceptionAsync(UncaughtExceptionSource::INTERNAL, + KJ_EXCEPTION(FAILED, "draining the microtask queue"), kj::none); +} + +// When the request a wait runs in is aborted, with IoContext::abort(), relative to the wait. +enum class AbortedWait { + // While the wait is pending. Its promise never settles. + PENDING, + // While the wait is pending. Once the abort has reached the wait, its promise is fulfilled. + THEN_FULFILLED, + // As THEN_FULFILLED, but the promise is rejected. + THEN_REJECTED, + // While the wait is pending, in the turn that then fulfills its promise. + FULFILLED_IN_SAME_TURN, + // As FULFILLED_IN_SAME_TURN, but the promise is rejected. + REJECTED_IN_SAME_TURN, + // While the wait is pending, in the turn in which GC then collects its unsettled promise. + COLLECTED_IN_SAME_TURN, + // Before the wait starts, in the turn it starts in. Its promise never settles. + BEFORE_START, + // Before the wait starts, in the turn it starts in, which then fulfills its promise. + BEFORE_START_THEN_FULFILLED_IN_SAME_TURN, + // Once its promise has been fulfilled and the wait has ended. + AFTER_FULFILLED, + // Once the wait has been cancelled. Then its promise is fulfilled. + AFTER_CANCELLED, + // As THEN_FULFILLED, but nothing waits for the wait until its promise has been fulfilled. + THEN_FULFILLED_WAITED_LATE, + // As BEFORE_START, but the promise is fulfilled in a later turn, and nothing waits for the + // wait until then. + BEFORE_START_THEN_FULFILLED_WAITED_LATE, +}; + +kj::StringPtr nameOf(AbortedWait scenario) { + switch (scenario) { + case AbortedWait::PENDING: + return "PENDING"_kj; + case AbortedWait::THEN_FULFILLED: + return "THEN_FULFILLED"_kj; + case AbortedWait::THEN_REJECTED: + return "THEN_REJECTED"_kj; + case AbortedWait::FULFILLED_IN_SAME_TURN: + return "FULFILLED_IN_SAME_TURN"_kj; + case AbortedWait::REJECTED_IN_SAME_TURN: + return "REJECTED_IN_SAME_TURN"_kj; + case AbortedWait::COLLECTED_IN_SAME_TURN: + return "COLLECTED_IN_SAME_TURN"_kj; + case AbortedWait::BEFORE_START: + return "BEFORE_START"_kj; + case AbortedWait::BEFORE_START_THEN_FULFILLED_IN_SAME_TURN: + return "BEFORE_START_THEN_FULFILLED_IN_SAME_TURN"_kj; + case AbortedWait::AFTER_FULFILLED: + return "AFTER_FULFILLED"_kj; + case AbortedWait::AFTER_CANCELLED: + return "AFTER_CANCELLED"_kj; + case AbortedWait::THEN_FULFILLED_WAITED_LATE: + return "THEN_FULFILLED_WAITED_LATE"_kj; + case AbortedWait::BEFORE_START_THEN_FULFILLED_WAITED_LATE: + return "BEFORE_START_THEN_FULFILLED_WAITED_LATE"_kj; + } + KJ_UNREACHABLE; +} + +// What a wait whose request is aborted lets the test observe. +struct AbortedWaitOutcome { + // As jsOutcome() describes it, once the abort and the settling have been handled. + kj::String outcome; + kj::Maybe error; + uint mapRuns; + // The events of its awaitJs resource, as traceAwaitJs() records them. + kj::String events; + // The uncaught exceptions logged from awaiting the promise, "Uncaught (in promise)". + kj::String inPromise; + + // All but `error`, whose location differs by implementation unless it is the abort's. + kj::String toString() const { + return kj::str("outcome: ", outcome, "\nmap runs: ", mapRuns, "\nevents: ", events, + "\nuncaught (in promise): ", inPromise); + } +}; + +// Starts a wait in a traced request, whose isolate has an inspector, through C++ awaitJs() or +// Rust's await_js(), aborts the request as `scenario` says, and returns what was observed. +AbortedWaitOutcome abortWait(AbortedWait scenario, Implementation implementation) { + bool rust = implementation == Implementation::RUST; + kj::Vector events; + UncaughtExceptionLog log; + AbortedWaitOutcome result; + { + capnp::MallocMessageBuilder flagsMessage; + auto params = inspectorParams(flagsMessage); + params.isolateObserver = kj::atomicRefcounted>(events); + TestFixture fixture(kj::mv(params)); + auto context = fixture.newIoContext(); + auto request = fixture.newIncomingRequest(*context); + // Once the wait ends, the request has nothing else to wait for, and would be aborted as hung. + auto pendingEvent = context->registerPendingEvent(); + RecordedCppAwaitJs cpp; + RecordedCppAwaitJs::mapRuns = 0; + + bool late = scenario == AbortedWait::THEN_FULFILLED_WAITED_LATE || + scenario == AbortedWait::BEFORE_START_THEN_FULFILLED_WAITED_LATE; + auto start = [&](const TestFixture::Environment& env) { + if (!rust) { + if (late) { + cpp.startHeld(env); + } else { + cpp.start(env); + } + } else if (late) { + await_js_start(isolateOf(env), AwaitJsStart::Held); + } else if (scenario == AbortedWait::AFTER_CANCELLED) { + await_js_start(isolateOf(env), AwaitJsStart::Cancellable); + } else if (scenario == AbortedWait::COLLECTED_IN_SAME_TURN) { + await_js_start(isolateOf(env), AwaitJsStart::DropResolver); + } else { + await_js_start(isolateOf(env), AwaitJsStart::KeepResolver); + } + }; + auto settle = [&](jsg::Lock& js, bool fulfill) { + if (rust) { + settle_awaited_js(reinterpret_cast(js.v8Isolate), fulfill); + } else { + cpp.settle(js, fulfill); + } + }; + auto abort = [&]() { context->abort(abortException()); }; + + switch (scenario) { + case AbortedWait::PENDING: + case AbortedWait::THEN_FULFILLED: + case AbortedWait::THEN_REJECTED: + fixture.enterContext(*request, start); + fixture.pollEventLoop(); + abort(); + fixture.pollEventLoop(); + if (scenario != AbortedWait::PENDING) { + settleOnceAborted(fixture, *context, + [&](jsg::Lock& js) { settle(js, scenario == AbortedWait::THEN_FULFILLED); }); + fixture.pollEventLoop(); + } + break; + case AbortedWait::FULFILLED_IN_SAME_TURN: + case AbortedWait::REJECTED_IN_SAME_TURN: + fixture.enterContext(*request, start); + fixture.pollEventLoop(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + abort(); + settle(env.js, scenario == AbortedWait::FULFILLED_IN_SAME_TURN); + }); + fixture.pollEventLoop(); + break; + case AbortedWait::COLLECTED_IN_SAME_TURN: + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + start(env); + // Both promises are unreachable once their resolvers are dropped. + cpp.resolver = kj::none; + }); + fixture.pollEventLoop(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + abort(); + env.isolate->LowMemoryNotification(); + // GC collected the reactions, and with them the sender, which holds the watcher and + // destroys the unsettled resource as it is dropped. + if (rust) { + KJ_EXPECT(events.size() > 0 && events.back() == "destroy awaitJs#1", + kj::strArray(events, "; ")); + } + }); + fixture.pollEventLoop(); + break; + case AbortedWait::BEFORE_START: + case AbortedWait::BEFORE_START_THEN_FULFILLED_IN_SAME_TURN: + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + abort(); + start(env); + if (scenario == AbortedWait::BEFORE_START_THEN_FULFILLED_IN_SAME_TURN) { + settle(env.js, true); + } + }); + fixture.pollEventLoop(); + break; + case AbortedWait::AFTER_FULFILLED: + fixture.enterContext(*request, start); + fixture.enterContext( + *request, [&](const TestFixture::Environment& env) { settle(env.js, true); }); + fixture.pollEventLoop(); + abort(); + fixture.pollEventLoop(); + break; + case AbortedWait::AFTER_CANCELLED: + fixture.enterContext(*request, start); + fixture.pollEventLoop(); + if (rust) { + KJ_EXPECT(cancel_awaited_js()); + } else { + cpp.cancel(); + } + fixture.pollEventLoop(); + abort(); + fixture.pollEventLoop(); + settleOnceAborted(fixture, *context, [&](jsg::Lock& js) { settle(js, true); }); + fixture.pollEventLoop(); + break; + case AbortedWait::THEN_FULFILLED_WAITED_LATE: + case AbortedWait::BEFORE_START_THEN_FULFILLED_WAITED_LATE: + if (scenario == AbortedWait::THEN_FULFILLED_WAITED_LATE) { + fixture.enterContext(*request, start); + fixture.pollEventLoop(); + abort(); + } else { + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + abort(); + start(env); + }); + } + fixture.pollEventLoop(); + settleOnceAborted(fixture, *context, [&](jsg::Lock& js) { settle(js, true); }); + fixture.pollEventLoop(); + // Only now is the wait waited for. + if (rust) { + KJ_EXPECT(poll_held_awaited_js()); + } else { + cpp.waitHeld(); + fixture.pollEventLoop(); + } + break; + } + + if (rust) { + result.outcome = jsOutcome(); + result.mapRuns = awaited_js_map_runs(); + if (result.outcome.startsWith("rejected: ")) result.error = awaitedJsError(); + } else { + result.outcome = kj::str(cpp.outcome); + result.mapRuns = RecordedCppAwaitJs::mapRuns; + result.error = kj::mv(cpp.error); + } + cpp.wait = kj::none; + forget_awaited_js_resolver(); + pendingEvent = nullptr; + fixture.drainAndDestroy(kj::mv(request)); + } + result.events = kj::strArray(events, "\n"); + kj::Vector inPromise; + for (auto& message: log.messages) { + if (message.contains(IN_PROMISE)) inPromise.add(message); + } + result.inPromise = kj::str(inPromise.size()); + return result; +} + +// Runs `scenario` through C++ awaitJs() and Rust's await_js(), checks that they are observed +// alike, and returns what was observed of Rust's. +AbortedWaitOutcome abortWaitOnBoth(AbortedWait scenario) { + auto cpp = abortWait(scenario, Implementation::CPP); + auto rust = abortWait(scenario, Implementation::RUST); + KJ_EXPECT(cpp.toString() == rust.toString(), nameOf(scenario), cpp.toString(), rust.toString()); + KJ_IF_SOME(cppError, cpp.error) { + KJ_IF_SOME(rustError, rust.error) { + if (cppError.getDetail(ABORT_DETAIL_ID) != kj::none) { + expectSameException(rustError, cppError); + } + } else { + KJ_FAIL_EXPECT("only C++ failed", nameOf(scenario), cppError); + } + } + return rust; +} + +constexpr kj::StringPtr ABORTED_OUTCOME = "rejected: jsg.Error: aborted by the test"_kj; + +// The events of the awaitJs resource of a wait whose promise settles as `last` says, or that is +// destroyed unsettled with its request. +kj::String expectedAbortedWaitEvents(kj::StringPtr last) { + return kj::str("init awaitJs#1 trigger=request exec=request\n", last); +} + +KJ_TEST("await_js() fails with the exception its request is aborted with, as C++ awaitJs() does") { + auto outcome = abortWaitOnBoth(AbortedWait::PENDING); + KJ_EXPECT(outcome.outcome == ABORTED_OUTCOME, outcome.outcome); + expectSameException(KJ_ASSERT_NONNULL(outcome.error), abortException()); + KJ_EXPECT(outcome.mapRuns == 0); + // The promise never settles, so the resource is destroyed with the request. + KJ_EXPECT(outcome.events == expectedAbortedWaitEvents("destroy awaitJs#1"), outcome.events); +} + +KJ_TEST("once the abort has failed an await_js(), its promise's fulfillment runs no conversion and " + "settles the trace OK, as in C++") { + auto outcome = abortWaitOnBoth(AbortedWait::THEN_FULFILLED); + KJ_EXPECT(outcome.outcome == ABORTED_OUTCOME, outcome.outcome); + KJ_EXPECT(outcome.mapRuns == 0); + KJ_EXPECT(outcome.events == expectedAbortedWaitEvents("settle awaitJs#1 OK"), outcome.events); + KJ_EXPECT(outcome.inPromise == "0", outcome.inPromise); +} + +KJ_TEST("once the abort has failed an await_js(), its promise's rejection is still logged and " + "settles the trace ERROR, as in C++") { + auto outcome = abortWaitOnBoth(AbortedWait::THEN_REJECTED); + KJ_EXPECT(outcome.outcome == ABORTED_OUTCOME, outcome.outcome); + KJ_EXPECT(outcome.events == expectedAbortedWaitEvents("settle awaitJs#1 ERROR"), outcome.events); + KJ_EXPECT(outcome.inPromise == "1", outcome.inPromise); +} + +KJ_TEST("a promise that settles in the turn its request is aborted in loses to the abort, as in " + "C++") { + auto fulfilled = abortWaitOnBoth(AbortedWait::FULFILLED_IN_SAME_TURN); + KJ_EXPECT(fulfilled.outcome == ABORTED_OUTCOME, fulfilled.outcome); + auto rejected = abortWaitOnBoth(AbortedWait::REJECTED_IN_SAME_TURN); + KJ_EXPECT(rejected.outcome == ABORTED_OUTCOME, rejected.outcome); + KJ_EXPECT(rejected.inPromise == "1", rejected.inPromise); +} + +KJ_TEST("a promise that GC collects in the turn its request is aborted in loses to the abort, as " + "in C++") { + auto outcome = abortWaitOnBoth(AbortedWait::COLLECTED_IN_SAME_TURN); + KJ_EXPECT(outcome.outcome == ABORTED_OUTCOME, outcome.outcome); + expectSameException(KJ_ASSERT_NONNULL(outcome.error), abortException()); + KJ_EXPECT(outcome.events == expectedAbortedWaitEvents("destroy awaitJs#1"), outcome.events); +} + +KJ_TEST("await_js() in a request that was already aborted fails with the abort in a later turn, as " + "in C++") { + auto pending = abortWaitOnBoth(AbortedWait::BEFORE_START); + KJ_EXPECT(pending.outcome == ABORTED_OUTCOME, pending.outcome); + expectSameException(KJ_ASSERT_NONNULL(pending.error), abortException()); + + // A promise that settles in the same turn settles the wait first. + auto fulfilled = abortWaitOnBoth(AbortedWait::BEFORE_START_THEN_FULFILLED_IN_SAME_TURN); + KJ_EXPECT(fulfilled.outcome == "fulfilled: 42", fulfilled.outcome); + KJ_EXPECT(fulfilled.mapRuns == 1); +} + +KJ_TEST("when the abort fails an await_js() doesn't depend on when it is waited for, as in C++") { + // C++ joins the wait with onAbort() as the wait starts, and the first to fire wins, so an abort + // wins over a promise fulfilled after it even if nothing waited for the wait until then. + for (auto scenario: {AbortedWait::THEN_FULFILLED_WAITED_LATE, + AbortedWait::BEFORE_START_THEN_FULFILLED_WAITED_LATE}) { + auto outcome = abortWaitOnBoth(scenario); + KJ_EXPECT(outcome.outcome == ABORTED_OUTCOME, nameOf(scenario), outcome.outcome); + KJ_EXPECT(outcome.mapRuns == 0, nameOf(scenario)); + KJ_EXPECT(outcome.events == expectedAbortedWaitEvents("settle awaitJs#1 OK"), nameOf(scenario), + outcome.events); + expectSameException(KJ_ASSERT_NONNULL(outcome.error), abortException()); + } +} + +KJ_TEST("an abort after await_js() has ended or been cancelled changes nothing, as in C++") { + auto fulfilled = abortWaitOnBoth(AbortedWait::AFTER_FULFILLED); + KJ_EXPECT(fulfilled.outcome == "fulfilled: 42", fulfilled.outcome); + KJ_EXPECT(fulfilled.mapRuns == 1); + KJ_EXPECT(fulfilled.events == expectedAbortedWaitEvents("settle awaitJs#1 OK"), fulfilled.events); + + auto cancelled = abortWaitOnBoth(AbortedWait::AFTER_CANCELLED); + KJ_EXPECT(cancelled.outcome == "cancelled", cancelled.outcome); + KJ_EXPECT(cancelled.mapRuns == 0); + KJ_EXPECT(cancelled.events == expectedAbortedWaitEvents("settle awaitJs#1 OK"), cancelled.events); +} + +KJ_TEST("await_js() fails with the reason Rust's ctx.abort(reason) aborts with, as C++ awaitJs() " + "does") { + TestFixture fixture; + auto request = fixture.newIncomingRequest(); + RecordedCppAwaitJs cpp; + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + cpp.start(env); + await_js_start(isolateOf(env), AwaitJsStart::KeepResolver); + }); + fixture.pollEventLoop(); + kj::Maybe abortReason; + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + auto reason = runScript(env, R"(new RangeError("custom reason"))"); + abort_request(isolateOf(env), ::workerd::rust::jsg::to_ffi(kj::mv(reason))); + env.isolate->CancelTerminateExecution(); + abortReason = env.context.getAbortReason(); + }); + fixture.pollEventLoop(); + + auto& reason = KJ_ASSERT_NONNULL(abortReason, "the request was not aborted"); + KJ_EXPECT(reason.getDescription() == "jsg.RangeError: custom reason", reason); + // The reason is tunneled as a JavaScript exception is. + KJ_EXPECT(reason.getDetail(jsg::TUNNELED_EXCEPTION_DETAIL_ID) != kj::none, reason); + KJ_EXPECT(jsOutcome() == "rejected: jsg.RangeError: custom reason", jsOutcome()); + expectSameException(awaitedJsError(), reason); + expectSameException(KJ_ASSERT_NONNULL(cpp.error, "C++ awaitJs() has not failed"), reason); + KJ_EXPECT(awaited_js_map_runs() == 0); + cpp.wait = kj::none; + forget_awaited_js_resolver(); + fixture.drainAndDestroy(kj::mv(request)); +} + +KJ_TEST("a settled await_js() releases its abort watcher in the reaction, and the abort then " + "changes nothing") { + kj::Vector released; + TestFixture fixture({ + .isolateObserver = kj::atomicRefcounted>(released), + }); + auto request = fixture.newIncomingRequest(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::KeepResolver); + }); + KJ_EXPECT(released.size() == 0, kj::strArray(released, "; ")); + fixture.enterContext(*request, + [&](const TestFixture::Environment& env) { settle_awaited_js(isolateOf(env), true); }); + // The reaction ran at the end of that turn, with the request current. + KJ_EXPECT(released.size() == 1, kj::strArray(released, "; ")); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "fulfilled: 42", jsOutcome()); + + request->getContext().abort(abortException()); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "fulfilled: 42", jsOutcome()); + fixture.drainAndDestroy(kj::mv(request)); + KJ_EXPECT(released.size() == 1, kj::strArray(released, "; ")); +} + +KJ_TEST("a cancelled await_js() keeps its abort watcher until its sender is dropped, and the " + "abort then settles nothing") { + kj::Vector released; + TestFixture fixture({ + .isolateObserver = kj::atomicRefcounted>(released), + }); + auto context = fixture.newIoContext(); + auto request = fixture.newIncomingRequest(*context); + // As in "a cancelled await_js() does not run its conversion". + auto pendingEvent = context->registerPendingEvent(); + fixture.enterContext(*request, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::Cancellable); + }); + KJ_EXPECT(cancel_awaited_js()); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "cancelled", jsOutcome()); + // The request still owns the sender, which holds the watcher. + KJ_EXPECT(released.size() == 0, kj::strArray(released, "; ")); + + // The abort settles nothing, and the promise still runs no conversion. + context->abort(abortException()); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == "cancelled", jsOutcome()); + KJ_EXPECT(awaited_js_map_runs() == 0); + + // Destroying the IoContext drops the sender, and the watcher with it. + forget_awaited_js_resolver(); + fixture.drainAndDestroy(kj::mv(request)); + pendingEvent = nullptr; + context = nullptr; + KJ_EXPECT(released.size() == 1, kj::strArray(released, "; ")); +} + +KJ_TEST("an await_js() whose promise GC collects releases its abort watcher with its sender") { + kj::Vector released; + TestFixture fixture({ + .isolateObserver = kj::atomicRefcounted>(released), + }); + auto owner = fixture.newIncomingRequest(); + fixture.enterContext(*owner, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::DropResolver); + }); + KJ_EXPECT(released.size() == 0, kj::strArray(released, "; ")); + collectGarbage(fixture, *owner); + // The sender was dropped in the collection, with the request current. + KJ_EXPECT(released.size() == 1, kj::strArray(released, "; ")); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == NEVER_SETTLED_OUTCOME, jsOutcome()); + fixture.drainAndDestroy(kj::mv(owner)); +} + +KJ_TEST("an await_js() whose promise GC collects in another request releases its abort watcher " + "when its request next runs") { + kj::Vector released; + TestFixture fixture({ + .isolateObserver = kj::atomicRefcounted>(released), + }); + auto owner = fixture.newIncomingRequest(); + auto other = fixture.newIncomingRequest(); + fixture.enterContext(*owner, [&](const TestFixture::Environment& env) { + await_js_start(isolateOf(env), AwaitJsStart::DropResolver); + }); + // The sender is queued for its own request to drop, with the watcher. + collectGarbage(fixture, *other); + KJ_EXPECT(released.size() == 0, kj::strArray(released, "; ")); + KJ_EXPECT(jsOutcome() == "pending"); + fixture.enterContext(*owner, [&](const TestFixture::Environment&) {}); + KJ_EXPECT(released.size() == 1, kj::strArray(released, "; ")); + fixture.pollEventLoop(); + KJ_EXPECT(jsOutcome() == NEVER_SETTLED_OUTCOME, jsOutcome()); + fixture.drainAndDestroy(kj::mv(other)); + fixture.drainAndDestroy(kj::mv(owner)); +} + constexpr kj::StringPtr PROBE_SPECIFIER = "test:io-context-probe"_kj; KJ_TEST("the legacy registry creates a Rust module's exports outside the request resolving it") { diff --git a/src/workerd/io/io-context/lib.rs b/src/workerd/io/io-context/lib.rs index 1c8086ce14b..af019b23985 100644 --- a/src/workerd/io/io-context/lib.rs +++ b/src/workerd/io/io-context/lib.rs @@ -16,11 +16,13 @@ use std::ffi::CStr; use std::future::Future; use std::marker::PhantomData; use std::panic::AssertUnwindSafe; +use std::pin::Pin; use std::sync::Arc; use std::sync::Mutex; use std::sync::MutexGuard; use std::sync::PoisonError; use std::task::Poll; +use std::task::Waker; use std::time::Duration; use std::time::SystemTime; use std::time::UNIX_EPOCH; @@ -247,6 +249,101 @@ impl<'s> IoContext<'s> { }) } + /// Waits for `promise` as part of this request, as C++ `IoContext::awaitJs(js, promise, func)` + /// does, and returns a future for the outcome, which can be waited for without the isolate + /// lock. Dropping the future cancels the wait: `map` then does not run. + /// + /// Once `promise` is fulfilled, `map` runs with its value, in the reaction to the promise and + /// under the isolate lock, and the future resolves with what `map` returns. `map` is `Copy`, + /// so that what it captures holds no GC references, and `Send`, as the reaction's data must + /// be. What it returns holds no GC references either ([`jsg::HoldsNoGcReferences`]), since + /// nothing traces it while the future holds it. + /// + /// The future fails with a [`cxx::KjException`], so that an exception C++ created reaches C++ + /// as it is: + /// + /// - If `promise` rejects or `map` fails, with that exception, tunneled as + /// [`jsg::Lock::exception_to_kj`] does, after it is logged as an uncaught exception from + /// [`UncaughtExceptionSource::InternalAsync`]. + /// - If this `IoContext` is aborted before the wait settles, with the exception it was + /// aborted with. If it was already aborted when the wait started, the abort fails the wait + /// in a later turn, unless the promise settles first. + /// - If the wait never settles, because `promise` is garbage-collected first, this + /// `IoContext` is destroyed first, or logging or tunneling the exception throws, with an + /// `Error` whose message is `Promise will never complete.`, or, if the isolate has + /// excessively exceeded its heap limit by then, with C++ + /// `IoContext::memoryLimitException()`. + /// + /// The promise must settle in this request: a reaction that runs in another one rejects the + /// promise it returns, and settles nothing. + /// + /// If the request has async tracing, the wait is recorded as a `JS_TO_KJ` resource named + /// `awaitJs`, as C++ records it. + /// + /// # Errors + /// Fails with an internal error if this `IoContext` is no longer the current one, and with an + /// error for which [`jsg::Error::is_pending`] is true if V8 fails to register the reactions + /// or execution is terminating. + // + // TODO(someday): The join with the request's abort relies on C++ `IoContext::onAbort()`, + // through an `AbortWatcher`; a Rust IoContext will need its own abort signal. + pub fn await_js( + &self, + lock: &mut jsg::Lock<'s>, + promise: impl Into>, + map: M, + ) -> jsg::Result> + where + T: jsg::HoldsNoGcReferences + 'static, + M: Copy + + Send + + 'static + + for<'a> Fn(&mut jsg::Lock<'a>, v8::Local<'a, v8::Value>) -> jsg::Result, + { + if lock.is_execution_terminating() { + return Err(jsg::Error::pending()); + } + let shared = Arc::new(AwaitJsShared(Mutex::new(AwaitJsState::Waiting(None)))); + // Weak, so that the watcher, which the sender holds, doesn't keep the wait alive. + let weak = Arc::downgrade(&shared); + let on_abort = ffi::AbortCallback(Box::new(move |err| { + if let Some(shared) = weak.upgrade() { + shared.settle(AwaitJsState::Rejected(err)); + } + })); + let sender = self.add_object(AwaitJsSender { + shared: Arc::clone(&shared), + isolate: bridge::io_context_isolate_weak_ref(self.id)?, + async_trace: bridge::io_context_make_await_js_resource(self.id)?.into(), + abort_watcher: ThreadBoundAbortWatcher(bridge::io_context_watch_abort( + self.id, + Box::new(on_abort), + )?), + })?; + promise.into().then_or_catch( + lock, + AwaitJsReaction { sender, map }, + await_js_on_fulfilled::, + await_js_on_rejected::, + )?; + Ok(AwaitJs { shared }) + } + + /// [`await_js`](Self::await_js) for a value that converts with [`jsg::FromJS`]. + /// + /// # Errors + /// As for `await_js`. + pub fn await_js_value( + &self, + lock: &mut jsg::Lock<'s>, + promise: impl Into>, + ) -> jsg::Result> + where + T: for<'a> jsg::FromJS<'a, ResultType = T> + jsg::HoldsNoGcReferences + 'static, + { + self.await_js(lock, promise, |lock, value| T::from_js(lock, value)) + } + /// Gives this `IoContext` ownership of `value`, as C++ `IoContext::addObject()` does: it is /// dropped when the `IoContext` is destroyed, or when the returned handle is dropped, unless /// [`IoOwned::take`] has taken it. How the value is reached differs from C++; see @@ -291,8 +388,10 @@ impl<'s> IoContext<'s> { /// Has the request wait for `promise` after the response, as `ctx.waitUntil()` does through /// C++ `IoContext::awaitJs()` and `IoContext::addWaitUntil()`: the request is not done until - /// `promise` settles. If `promise` rejects, the rejection is logged as an uncaught exception, - /// as for every JavaScript promise that C++ waits for, and the response is unaffected. + /// `promise` settles. The wait is an [`await_js`](Self::await_js), whose future C++ + /// `addWaitUntil()` waits for. If `promise` rejects, the rejection is logged as an uncaught + /// exception, as for every JavaScript promise that C++ waits for, and the response is + /// unaffected. /// /// As with `awaitJs()`, `promise` must settle in this request. Its reactions run in the /// request that settles it, or, under the `handle_cross_request_promise_resolution` @@ -316,12 +415,17 @@ impl<'s> IoContext<'s> { promise: impl Into>, ) -> jsg::Result<()> { // JavaScript can't call `ctx.waitUntil()` while terminating, but Rust can call this after - // catching a termination. `awaitJs()` would then create objects, which fails a V8 debug - // check, and the request ends anyway. - if lock.is_execution_terminating() { - return Err(jsg::Error::pending()); - } - ffi::add_wait_until(lock, self.id, promise.into()) + // catching a termination. `await_js()` fails then, before creating anything, which would + // fail a V8 debug check, and the request ends anyway. + // + // As C++ `PromiseWrapper` converts the promise to a `kj::Promise`, the value is + // discarded. + let wait = self.await_js(lock, promise, |_lock, _value| Ok(()))?; + let future = ffi::WaitUntilFuture(Box::pin(wait)); + Ok(bridge::io_context_add_wait_until( + self.id, + Box::new(future), + )?) } /// Has the request fail open, as `ctx.passThroughOnException()` does through C++ @@ -374,6 +478,54 @@ impl<'s> IoContext<'s> { } } + /// Logs `exception`, a value JavaScript threw or rejected a promise with, as an uncaught + /// exception from `source`, as C++ `IoContext::logUncaughtException(source, exception)` does + /// through `Worker::Lock::logUncaughtException()`: + /// + /// - If the isolate has an inspector, reports it to the inspector as thrown, with `source`'s + /// text and a message that V8 creates for the value, so that it shows in the inspector's + /// console. + /// - If KJ logs at INFO level (`workerd --verbose`), logs `uncaught exception` with `source` + /// and the value's `stack`, if the value is an object whose `stack` is not `undefined`, or + /// else the value itself, each as [`v8::Local::::to_detail_string`] describes + /// it, up to its first NUL. + /// + /// C++ also adds an uncaught exception to the request's tail-worker trace, but not one from + /// either [`UncaughtExceptionSource`]; see there. + /// + /// # Errors + /// Fails with an internal error if this `IoContext` is no longer the current one. Fails with + /// an error for which [`jsg::Error::is_pending`] is true: + /// + /// - if an exception or a termination is already pending, and the isolate has an inspector or + /// KJ logs at INFO level; + /// - if reading `stack` runs JavaScript that throws (a getter, say), leaving that exception + /// pending, as C++ throws `JsExceptionThrown` then. The inspector has been told of + /// `exception` by then. + pub fn log_uncaught_exception( + &self, + lock: &mut jsg::Lock<'s>, + source: UncaughtExceptionSource, + exception: v8::Local<'s, v8::Value>, + ) -> jsg::Result<()> { + let source = source.into_ffi(); + ffi::send_exception_to_inspector(lock, self.id, source, exception)?; + if !bridge::io_context_should_log_uncaught_exceptions() { + return Ok(()); + } + if let Ok(object) = v8::Local::::try_from(exception) { + let stack = object.get(lock, "stack")?; + if !stack.is_undefined() { + let stack = describe_for_log(lock, stack)?; + bridge::io_context_log_uncaught_exception_stack(source, &stack); + return Ok(()); + } + } + let exception = describe_for_log(lock, exception)?; + bridge::io_context_log_uncaught_exception_value(source, &exception); + Ok(()) + } + /// Starts a span of internal tracing, as C++ `IoContext::makeTraceSpan()` does. It is a child /// of the span current in the async context frame, or of the request's span, and ends when /// the returned [`SpanBuilder`] is dropped. If the request is not traced, it records nothing. @@ -396,6 +548,45 @@ impl<'s> IoContext<'s> { } } +/// Where an uncaught exception comes from, as C++ `UncaughtExceptionSource` says. +/// +/// [`IoContext::log_uncaught_exception`] gives the inspector and the log the source's text, such +/// as `Uncaught (in promise)`. +/// +/// C++ has more sources, for the exceptions of handlers and tasks, whose uncaught exceptions it +/// also adds to the request's tail-worker trace (`addExceptionToTrace()`). It adds none from these +/// two, and `log_uncaught_exception` adds none at all, so only these two are offered. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UncaughtExceptionSource { + /// `INTERNAL`, `Uncaught`. + Internal, + /// `INTERNAL_ASYNC`, `Uncaught (in promise)`: a JavaScript promise that the runtime waits + /// for rejected, as in [`IoContext::await_js`]. + InternalAsync, +} + +impl UncaughtExceptionSource { + const fn into_ffi(self) -> bridge::UncaughtExceptionSource { + match self { + Self::Internal => bridge::UncaughtExceptionSource::INTERNAL, + Self::InternalAsync => bridge::UncaughtExceptionSource::INTERNAL_ASYNC, + } + } +} + +/// `value` as C++ JSG describes a handle in a log (`kj::str(handle)`): its detail string, up to +/// its first NUL, since C++ copies it out of V8 as a C string. +fn describe_for_log<'s>( + lock: &mut jsg::Lock<'s>, + value: v8::Local<'s, v8::Value>, +) -> jsg::Result { + let mut detail = value.to_detail_string(lock)?; + if let Some(nul) = detail.find('\0') { + detail.truncate(nul); + } + Ok(detail) +} + /// What the callback of [`IoContext::await_io`] returned, carried to the reaction that returns or /// throws it. As in C++, the promise the reaction is registered on resolves with no value, so that /// only the promise the reaction returns is resolved with the callback's value: resolving both @@ -457,6 +648,323 @@ async fn catch_poll_panic(future: F) -> Result { output } +/// What a wait of [`IoContext::await_js`] has come to, shared by its [`AwaitJs`] and its +/// [`AwaitJsSender`]. +enum AwaitJsState { + /// Not settled. Holds the waker of the last poll, if any. + Waiting(Option), + /// The promise was fulfilled with this value, converted. + Fulfilled(T), + /// The promise was rejected, converting its value failed, or the request was aborted first. + Rejected(cxx::KjException), + /// The sender was dropped without settling the wait. + NeverSettled, + /// The sender was dropped without settling the wait while the isolate had excessively + /// exceeded its heap limit. + MemoryLimitExceeded, + /// The [`AwaitJs`] was dropped before the wait settled. + Cancelled, + /// The [`AwaitJs`] returned the outcome. + Done, +} + +struct AwaitJsShared(Mutex>); + +impl AwaitJsShared { + // Nothing that holds the lock calls into V8 or panics, so it is never poisoned, and a drop + // in a GC finalizer cannot find it held by the code the finalizer interrupted. + fn lock(&self) -> MutexGuard<'_, AwaitJsState> { + self.0.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Settles the wait with `state` if it is waiting, then wakes its future. + fn settle(&self, state: AwaitJsState) { + let waker = { + let mut current = self.lock(); + let AwaitJsState::Waiting(waker) = &mut *current else { + return; + }; + let waker = waker.take(); + *current = state; + waker + }; + if let Some(waker) = waker { + waker.wake(); + } + } + + fn is_waiting(&self) -> bool { + matches!(*self.lock(), AwaitJsState::Waiting(_)) + } +} + +/// The half of a wait of [`IoContext::await_js`] that settles it, which the request owns through +/// an [`IoOwned`]. +struct AwaitJsSender { + shared: Arc>, + /// The isolate of the request the wait was started in, weakly, as C++ `awaitJsImpl()` takes + /// it, so that the wait never keeps the isolate alive. It is `Send`, as the sender must be. + isolate: KjOwn, + /// The wait's async trace resource, or `None` if the request is not traced. Settled with the + /// wait, as `AwaitJsFulfiller::settle()` does, and dropped with the sender, which reports a + /// `destroy` if it never settled. It is `Send`, as the sender must be. + /// + /// A reaction takes the sender, so a settled resource is released from the tracker, which + /// tells its sinks (`onRelease`), at the end of the reaction. C++ keeps its `AsyncResource` + /// until both reactions are dropped, and releases it then, or not at all if the tracker has + /// closed by then. Likewise, if the reaction fails before settling (logging the rejection + /// throws, or execution terminates), the sender is dropped with the reaction, which reports + /// the `destroy` then, where C++ reports it once the reactions are collected. No other event + /// differs. + async_trace: Option>, + /// The watcher of the request's abort, which settles the wait with the exception the request + /// is aborted with, as the `onAbort()` branch of C++'s `exclusiveJoin()` does. It holds the + /// wait weakly, and is dropped with the sender, on the request's thread: in the reaction that + /// settles the wait, when GC collects the reactions, or when the request is destroyed. So it + /// is not dropped when the wait is cancelled, unlike C++'s branch, but it then settles nothing. + /// It is a plain `KjOwn` rather than an [`IoOwned`]: the request may drop the sender while it + /// unlinks the sender from its owned objects, and the sender must not then reentrantly unlink + /// another owned object from that list. + abort_watcher: ThreadBoundAbortWatcher, +} + +// The sender's own fields are C++ objects and an `Arc` of the wait's state, which holds GC +// references only if `T` does, which the macro bounds out. +jsg::jsg_traced_unchecked!( AwaitJsSender); + +/// The abort watcher of an [`AwaitJsSender`]. +struct ThreadBoundAbortWatcher(KjOwn); + +#[expect( + unsafe_code, + reason = "a sender's abort watcher is touched only on its IoContext's thread; see the SAFETY \ + comment" +)] +// SAFETY: an `AbortWatcher` must be used and destroyed on its `IoContext`'s thread, while the +// `IoContext`'s abort exception is alive. Only an `AwaitJsSender` holds one, and the sender is +// `Send` only because `IoContext::add_object` requires it. `await_js()` creates the watcher on +// the `IoContext`'s thread, with it current. The sender reaches it only from a reaction that has +// taken the sender through `IoOwned::take()`, which requires the `IoContext` to be current, or +// when it is dropped: by that reaction, or by the `IoContext`, through the `SlotRef` it holds, on +// its thread and before its abort exception. The handle's own reference to the slot may be +// dropped on another thread, but if it is the last one, that `SlotRef` has emptied the slot, and +// dropping `None` touches no watcher. +unsafe impl Send for ThreadBoundAbortWatcher {} + +impl AwaitJsSender { + /// Settles the wait with `state`, then reports `outcome` for async tracing, in that order, as + /// `AwaitJsFulfiller` does. + fn settle(&self, state: AwaitJsState, outcome: bridge::AsyncOutcome) { + self.shared.settle(state); + self.settle_trace(outcome); + } + + /// Settles the wait with the exception the request was aborted with, if it was aborted after + /// the wait started, as C++'s `exclusiveJoin()` has such an abort win over whatever settles + /// the wait after it, even before the abort watcher has called back. A reaction calls this + /// before it settles the wait, and so does dropping the sender unsettled. + fn settle_with_pending_abort(&self) { + if let Some(err) = ffi::pending_abort(&self.abort_watcher.0) { + self.shared.settle(AwaitJsState::Rejected(err)); + } + } + + /// Reports `outcome` for async tracing, if the request is traced. Only the first is reported. + fn settle_trace(&self, outcome: bridge::AsyncOutcome) { + if let Some(resource) = &self.async_trace { + resource.settle(outcome); + } + } +} + +impl Drop for AwaitJsSender { + /// Settles the wait as never settling, as `~AwaitJsFulfiller()` does, unless it has settled + /// or was cancelled. As there, whether the isolate has excessively exceeded its heap limit + /// is decided now, and if it has, the wait fails with the memory-limit error instead. An + /// isolate that is gone has not. + /// + /// The reactions' data is dropped by the garbage collector once the promise is unreachable, + /// in a cppgc finalizer or the GC epilogue, so this must not enter V8, allocate on its heap, + /// or panic. It only reads the isolate's limit enforcer, which does none of these (see + /// `isolate_weak_ref_has_excessively_exceeded_heap_limit()`), sets the state and wakes the + /// future, which builds the error once it is polled. Then the async trace resource is + /// dropped, which reports to the tracker's sinks, as `~AwaitJsFulfiller()` destroys its + /// `AsyncResource` in the same finalizers. Of workerd's sinks, only the inspector's calls V8, + /// and it ignores `JS_TO_KJ` resources (`async-trace-inspector.c++`). The abort watcher is + /// dropped last, which destroys a KJ promise and drops its Rust callback, and enters no V8. + /// + /// If the request was aborted after the wait started, the wait fails with the abort instead, + /// as C++'s join has the abort win over the rejection that `~AwaitJsFulfiller()` causes. + /// Checking that only reads the exception the `IoContext` was aborted with. + fn drop(&mut self) { + if !self.shared.is_waiting() { + return; + } + self.settle_with_pending_abort(); + if !self.shared.is_waiting() { + return; + } + let exceeded = + match bridge::isolate_weak_ref_has_excessively_exceeded_heap_limit(&self.isolate) { + Ok(exceeded) => exceeded, + // The check is not expected to throw. If it does, the wait still fails, as never + // settled. Logging enters no V8. + Err(err) => { + bridge::io_context_log_error(&format!( + "checking the heap limit for an unsettled IoContext::await_js() failed: \ + {err}" + )); + false + } + }; + self.shared.settle(if exceeded { + AwaitJsState::MemoryLimitExceeded + } else { + AwaitJsState::NeverSettled + }); + } +} + +/// A future for the outcome of a JavaScript promise, from [`IoContext::await_js`]. +/// +/// It is `Send`, and is polled without the isolate lock, like the futures that +/// [`IoContext::await_io_and_run`] waits for. Dropping it before the promise settles cancels the +/// wait: the conversion then does not run. +pub struct AwaitJs { + shared: Arc>, +} + +impl Future for AwaitJs { + type Output = Result; + + fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll { + let state = { + let mut state = self.shared.lock(); + if let AwaitJsState::Waiting(waker) = &mut *state { + if waker.as_ref().is_some_and(|w| w.will_wake(cx.waker())) { + return Poll::Pending; + } + let replaced = waker.replace(cx.waker().clone()); + // Dropping a waker runs code that is not ours, so not under the lock. + drop(state); + drop(replaced); + return Poll::Pending; + } + std::mem::replace(&mut *state, AwaitJsState::Done) + }; + match state { + AwaitJsState::Waiting(_) => unreachable!("returned above"), + AwaitJsState::Fulfilled(value) => Poll::Ready(Ok(value)), + AwaitJsState::Rejected(err) => Poll::Ready(Err(err)), + AwaitJsState::NeverSettled => Poll::Ready(Err(ffi::never_settled_exception())), + AwaitJsState::MemoryLimitExceeded => Poll::Ready(Err(ffi::memory_limit_exception())), + AwaitJsState::Cancelled | AwaitJsState::Done => { + unreachable!("an AwaitJs polled after it returned its outcome") + } + } + } +} + +impl Drop for AwaitJs { + fn drop(&mut self) { + let mut state = self.shared.lock(); + if matches!(*state, AwaitJsState::Waiting(_)) { + let waiting = std::mem::replace(&mut *state, AwaitJsState::Cancelled); + // Its waker is dropped after the lock is released, as in `poll`. + drop(state); + drop(waiting); + } + } +} + +/// The data of the reactions [`IoContext::await_js`] registers. +struct AwaitJsReaction { + sender: IoOwned>, + map: M, +} + +// A `Copy` `map` holds no `jsg::Rc` or `TracedGlobal`, neither of which is `Copy`, and an `IoOwned` +// holds no JavaScript handles. Written out rather than with `jsg_traced_unchecked!`, which would +// bound `M` by `HoldsNoGcReferences`, which a closure or a function item can't implement. +impl jsg::Traced for AwaitJsReaction { + fn trace(&self, _visitor: &mut v8::GcVisitor) {} +} + +impl jsg::HoldsNoGcReferences + for AwaitJsReaction +{ +} + +/// The reaction to the fulfillment of the promise that [`IoContext::await_js`] waits for. +fn await_js_on_fulfilled<'a, T, M>( + lock: &mut jsg::Lock<'a>, + reaction: &AwaitJsReaction, + value: v8::Local<'a, v8::Value>, +) -> jsg::Result> +where + T: Send + 'static, + M: for<'b> Fn(&mut jsg::Lock<'b>, v8::Local<'b, v8::Value>) -> jsg::Result, +{ + let Some(sender) = reaction.sender.take(lock)? else { + unreachable!("only one reaction to a promise runs, once"); + }; + // As C++ does once the KJ promise is gone, `map` does not run for a wait that was cancelled or + // failed with the request's abort, and the trace still reports how the JavaScript promise + // settled. + if !sender.shared.is_waiting() { + sender.settle_trace(bridge::AsyncOutcome::OK); + return Ok(lock.undefined()); + } + // `map`'s own error is caught as the exception that throwing it throws, as C++ + // `jsg::Lock::tryCatch()` converts a KJ exception from `func`. + // An abort that the watcher has not yet delivered still wins, though `map` ran, as in C++. + match lock.try_catch(|lock| (reaction.map)(lock, value))? { + Ok(value) => { + sender.settle_with_pending_abort(); + sender.settle(AwaitJsState::Fulfilled(value), bridge::AsyncOutcome::OK); + } + Err(exception) => { + let err = reject_with_js_exception(lock, exception)?; + sender.settle_with_pending_abort(); + sender.settle(AwaitJsState::Rejected(err), bridge::AsyncOutcome::ERROR); + } + } + Ok(lock.undefined()) +} + +/// The reaction to the rejection of the promise that [`IoContext::await_js`] waits for. +fn await_js_on_rejected<'a, T, M>( + lock: &mut jsg::Lock<'a>, + reaction: &AwaitJsReaction, + reason: v8::Local<'a, v8::Value>, +) -> jsg::Result> { + let Some(sender) = reaction.sender.take(lock)? else { + unreachable!("only one reaction to a promise runs, once"); + }; + // As in C++, the rejection is logged and the trace reports it even if the wait was cancelled + // or failed with the request's abort. + let err = reject_with_js_exception(lock, reason)?; + sender.settle_with_pending_abort(); + sender.settle(AwaitJsState::Rejected(err), bridge::AsyncOutcome::ERROR); + Ok(lock.undefined()) +} + +/// The exception a wait of [`IoContext::await_js`] fails with for `exception`, which the promise +/// rejected with or `map` threw, as C++ `AwaitJsFulfiller::rejectWithJsException()` creates it: +/// logs `exception` as uncaught, then tunnels it. Fails with what JavaScript that either runs +/// throws, leaving it pending, before anything is tunneled. +fn reject_with_js_exception<'a>( + lock: &mut jsg::Lock<'a>, + exception: v8::Local<'a, v8::Value>, +) -> jsg::Result { + IoContext::current(lock)?.log_uncaught_exception( + lock, + UncaughtExceptionSource::InternalAsync, + exception, + )?; + Ok(lock.exception_to_kj(exception)?.into()) +} + /// A value an `IoContext` owns, from [`IoContext::add_object`]. /// /// Like C++ `IoOwn`, which `IoContext::addObject()` returns, it ties the value to its diff --git a/src/workerd/io/io-context/request-ops-test.c++ b/src/workerd/io/io-context/request-ops-test.c++ index 31a2d8214e5..4b0fc633c42 100644 --- a/src/workerd/io/io-context/request-ops-test.c++ +++ b/src/workerd/io/io-context/request-ops-test.c++ @@ -35,6 +35,16 @@ constexpr kj::StringPtr SCENARIOS = R"SCRIPT( addEventListener("unhandledrejection", (e) => event(`unhandled ${e.reason}`)); + // Has the request wait for `promise` through IoContext::awaitJs(), or Rust's await_js(). The + // C++ ExecutionContext has no method that only does that, so waitUntil() stands in for it. + function awaitJs(ctx, promise) { + if (globalThis.useRust) { + ctx.awaitJs(promise); + } else { + ctx.waitUntil(promise); + } + } + function abortWith(abort) { event("before"); try { @@ -81,6 +91,14 @@ constexpr kj::StringPtr SCENARIOS = R"SCRIPT( ctx.waitUntil(Promise.reject({ get stack() { throw new TypeError("from stack getter"); } })); return new Response("ok"); }, + awaitJsRejected(ctx) { + awaitJs(ctx, Promise.reject(new RangeError("rejected while awaited"))); + return new Response("ok"); + }, + awaitJsThrowingStackGetter(ctx) { + awaitJs(ctx, Promise.reject({ get stack() { throw new TypeError("from stack getter"); } })); + return new Response("ok"); + }, waitUntilNeverSettles(ctx) { ctx.waitUntil(new Promise(() => {})); return new Response("ok"); @@ -304,6 +322,25 @@ kj::String readEvents(TestFixture& fixture) { return events; } +// `events` without the " (I/O type: ...)" that C++ IoOwn appends to its error for I/O of another +// request, naming the type it holds, which a Rust IoOwned doesn't. For C++ awaitJs(), that type +// is its AwaitJsFulfiller, whose name means nothing to the Worker. +kj::String withoutIoTypes(kj::StringPtr events) { + constexpr auto IO_TYPE = " (I/O type: "_kj; + kj::Vector result; + size_t i = 0; + while (i < events.size()) { + if (events.slice(i).startsWith(IO_TYPE)) { + // The type name can contain parentheses; it ends at the end of the event. + while (i < events.size() && events[i] != ',') ++i; + continue; + } + result.add(events[i++]); + } + result.add('\0'); + return kj::String(result.releaseAsArray()); +} + // A worker running SCENARIOS, with `rustCtx` and `gate` set and `useRust` set for RUST. struct ScenarioWorker { kj::Own record = kj::refcounted(); @@ -410,14 +447,41 @@ kj::String withTunneledLocationsNormalized(kj::StringPtr text) { return kj::String(result.releaseAsArray()); } -// Runs `scenario` on both implementations, checks that they are observed alike, but for where -// JSG creates the exceptions it tunnels, and returns the outcome. +// `text` with the addresses of each logged exception's stack trace replaced by the same +// placeholder. An exception records the address of each KJ promise it passes through, and those of +// C++ and Rust differ, so only whether an exception has a trace is compared; that a Rust wait keeps +// the trace an exception had is tested in io-context-test. A trace is the rest of its line, up to +// the " | " between exceptions. +kj::String withStackTracesNormalized(kj::StringPtr text) { + constexpr auto STACK = "stack: "_kj; + constexpr auto SEPARATOR = " | "_kj; + kj::Vector result(text.size()); + size_t i = 0; + while (i < text.size()) { + if (text.slice(i).startsWith(STACK) && (i == 0 || text[i - 1] == '\n')) { + result.addAll("stack: "_kj); + i += STACK.size(); + while (i < text.size() && text[i] != '\n' && !text.slice(i).startsWith(SEPARATOR)) ++i; + } else { + result.add(text[i++]); + } + } + result.add('\0'); + return kj::String(result.releaseAsArray()); +} + +// `outcome` as it is compared between the implementations: but for where JSG creates the +// exceptions it tunnels, and for the addresses of stack traces. +kj::String comparable(const Outcome& outcome) { + return withStackTracesNormalized(withTunneledLocationsNormalized(outcome.toString())); +} + +// Runs `scenario` on both implementations, checks that they are observed alike (see +// `comparable()`), and returns the outcome. Outcome runOnBoth(kj::StringPtr scenario, Flags flags = {}) { auto cpp = run(scenario, Implementation::CPP, flags); auto rust = run(scenario, Implementation::RUST, flags); - KJ_EXPECT(withTunneledLocationsNormalized(cpp.toString()) == - withTunneledLocationsNormalized(rust.toString()), - scenario, cpp.toString(), rust.toString()); + KJ_EXPECT(comparable(cpp) == comparable(rust), scenario, cpp.toString(), rust.toString()); return cpp; } @@ -438,6 +502,8 @@ Outcome runCrossRequest(Implementation implementation, Flags flags) { Outcome runCrossRequestOnBoth(Flags flags) { auto cpp = runCrossRequest(Implementation::CPP, flags); auto rust = runCrossRequest(Implementation::RUST, flags); + cpp.events = withoutIoTypes(cpp.events); + KJ_EXPECT(!rust.events.contains(" (I/O type: "_kj), rust.events); KJ_EXPECT(cpp.toString() == rust.toString(), cpp.toString(), rust.toString()); return cpp; } @@ -487,6 +553,52 @@ KJ_TEST("what logging a waitUntil() rejection throws rejects unhandled, as in C+ outcome.uncaughtExceptions); } +// What a scenario that waits for a promise through awaitJs() lets the test observe: the events, +// and the uncaught exceptions logged from awaiting it, "Uncaught (in promise)". The C++ scenario +// also logs the failure of its waitUntil() task, which has no counterpart in Rust. +struct AwaitedOutcome { + kj::String events; + kj::String inPromise; + + kj::String toString() const { + return kj::str("events: ", events, "\nuncaught (in promise): ", inPromise); + } +}; + +AwaitedOutcome runAwaiting(kj::StringPtr scenario, Implementation implementation) { + UncaughtExceptionLog log; + ScenarioWorker worker(implementation); + KJ_EXPECT(worker.request(scenario) == 200); + worker.fixture.pollEventLoop(); + kj::Vector inPromise; + for (auto& message: log.messages) { + if (message.contains("source = Uncaught (in promise)")) inPromise.add(message); + } + return {.events = readEvents(worker.fixture), .inPromise = kj::strArray(inPromise, " | ")}; +} + +AwaitedOutcome runAwaitingOnBoth(kj::StringPtr scenario) { + auto cpp = runAwaiting(scenario, Implementation::CPP); + auto rust = runAwaiting(scenario, Implementation::RUST); + KJ_EXPECT(cpp.toString() == rust.toString(), scenario, cpp.toString(), rust.toString()); + return cpp; +} + +KJ_TEST("await_js() logs a rejection as an uncaught exception, as C++ awaitJs() does") { + auto outcome = runAwaitingOnBoth("awaitJsRejected"); + KJ_EXPECT(outcome.events == "", outcome.events); + KJ_EXPECT(outcome.inPromise.startsWith("uncaught exception; source = Uncaught (in promise); " + "stack = RangeError: rejected while awaited\n at "), + outcome.inPromise); + KJ_EXPECT(!outcome.inPromise.contains(" | "), outcome.inPromise); +} + +KJ_TEST("what logging an await_js() rejection throws rejects unhandled, as in C++") { + auto outcome = runAwaitingOnBoth("awaitJsThrowingStackGetter"); + KJ_EXPECT(outcome.events == "unhandled TypeError: from stack getter", outcome.events); + KJ_EXPECT(outcome.inPromise == "", outcome.inPromise); +} + KJ_TEST("a waitUntil() promise that can never settle fails as in C++") { auto outcome = runOnBoth("waitUntilNeverSettles"); KJ_EXPECT(outcome.statusCode == 200); @@ -494,6 +606,8 @@ KJ_TEST("a waitUntil() promise that can never settle fails as in C++") { // Once nothing else can run, the request is canceled as hung. KJ_EXPECT(outcome.uncaughtExceptions.contains("detected that your Worker's code had hung"), outcome.uncaughtExceptions); + // The abort is logged with its stack trace, which Rust keeps, as C++ does. + KJ_EXPECT(outcome.uncaughtExceptions.contains("\nstack: "), outcome.uncaughtExceptions); } KJ_TEST("a waitUntil() promise settled by another request fails without " @@ -667,9 +781,8 @@ KJ_TEST("the operations reject an IoContext id that is not the current one") { auto second = fixture.newIncomingRequest(); fixture.enterContext(*second, [&](const TestFixture::Environment& env) { - auto promise = jsg::check(v8::Promise::Resolver::New(env.js.v8Context()))->GetPromise(); - KJ_EXPECT_THROW_MESSAGE("not the one of the current request", - io_context_add_wait_until(firstId, ::workerd::rust::jsg::to_ffi(kj::mv(promise)))); + KJ_EXPECT_THROW_MESSAGE( + "not the one of the current request", io_context_check_current(firstId)); KJ_EXPECT_THROW_MESSAGE( "not the one of the current request", io_context_set_fail_open(firstId)); KJ_EXPECT_THROW_MESSAGE( @@ -679,9 +792,7 @@ KJ_TEST("the operations reject an IoContext id that is not the current one") { }); inWorkerContext(fixture, [&](jsg::Lock& js) { - auto promise = jsg::check(v8::Promise::Resolver::New(js.v8Context()))->GetPromise(); - KJ_EXPECT_THROW_MESSAGE("there is no current request", - io_context_add_wait_until(firstId, ::workerd::rust::jsg::to_ffi(kj::mv(promise)))); + KJ_EXPECT_THROW_MESSAGE("there is no current request", io_context_check_current(firstId)); KJ_EXPECT_THROW_MESSAGE("there is no current request", io_context_set_fail_open(firstId)); KJ_EXPECT_THROW_MESSAGE( "there is no current request", io_context_abort_without_reason(firstId)); diff --git a/src/workerd/io/io-context/test_bridge.rs b/src/workerd/io/io-context/test_bridge.rs index 153e0726db2..1b8360d6e16 100644 --- a/src/workerd/io/io-context/test_bridge.rs +++ b/src/workerd/io/io-context/test_bridge.rs @@ -16,13 +16,16 @@ use std::sync::Mutex; use std::sync::PoisonError; use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicU8; +use std::sync::atomic::AtomicU32; use std::sync::atomic::Ordering; use std::time::UNIX_EPOCH; use execution_context::new_gate; use execution_context::new_rust_execution_context; use execution_context::open_gate; +use futures::FutureExt; use futures::channel::oneshot; +use io_context::AwaitJs; use io_context::IoContext; use io_context::IoOwned; use io_context::IoOwnedSpan; @@ -57,6 +60,7 @@ mod ffi { type ModuleRegistry = jsg::v8::ffi::ModuleRegistry; type Isolate = jsg::v8::ffi::Isolate; type MaybeLocal = jsg::v8::ffi::MaybeLocal; + type Local = jsg::v8::ffi::Local; } /// How the last `await_released()` ends once its future has a value. @@ -109,6 +113,34 @@ mod ffi { Terminate, } + /// How `await_js_start()` starts its wait. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + enum AwaitJsStart { + /// Keeps the promise's resolver, for `settle_awaited_js()`. + KeepResolver, + /// Keeps nothing, so that the promise and its reactions are unreachable. + DropResolver, + /// Keeps the resolver, and races the wait with `cancel_awaited_js()`. + Cancellable, + /// Keeps the resolver, with a conversion that calls a function that throws a + /// `RangeError`. + MapThrows, + /// Keeps the resolver, with a conversion that returns a `RangeError`. + MapFails, + /// Keeps the resolver, with a conversion that returns an internal error. + MapFailsInternally, + /// Keeps the resolver, and holds the wait outside the request, for + /// `poll_held_awaited_js()`, so that it can outlive the `IoContext`. + Held, + } + + /// The `UncaughtExceptionSource` that `log_uncaught_exception()` logs from. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + enum LogSource { + Internal, + InternalAsync, + } + unsafe extern "C++" { include!("workerd/io/io-context/test-bridge.h"); @@ -150,6 +182,23 @@ mod ffi { fn open_gate() -> bool; unsafe fn request_ops_while_terminating(isolate: usize) -> Result<()>; + unsafe fn await_js_start(isolate: usize, start: AwaitJsStart) -> Result<()>; + unsafe fn settle_awaited_js(isolate: usize, fulfill: bool) -> Result<()>; + unsafe fn reject_awaited_js(isolate: usize, reason: Local) -> Result<()>; + unsafe fn abort_request(isolate: usize, reason: Local) -> Result<()>; + fn forget_awaited_js_resolver(); + fn cancel_awaited_js() -> bool; + fn awaited_js_outcome() -> String; + fn awaited_js_map_runs() -> u32; + fn awaited_js_detail_ids() -> Vec; + fn take_awaited_js_error() -> Result<()>; + fn poll_held_awaited_js() -> bool; + unsafe fn log_uncaught_exception( + isolate: usize, + source: LogSource, + exception: Local, + ) -> Result<()>; + unsafe fn has_current(isolate: usize) -> bool; unsafe fn now_nanos(isolate: usize) -> Result; fn now_in_current_request_nanos() -> Result; @@ -779,6 +828,282 @@ unsafe fn await_and_record_async_context(isolate: usize) -> Result<()> { .map_err(|err| to_io(&err)) } +thread_local! { + /// The resolver of the promise the last `await_js_start()` waits for, if it kept it. + static AWAITED_JS_RESOLVER: RefCell>> = + const { RefCell::new(None) }; +} + +/// How the wait of the last `await_js_start()` ended: "pending" until it does. +static AWAITED_JS_OUTCOME: Mutex = Mutex::new(String::new()); +/// How many times the conversion of the last `await_js_start()` ran. +static AWAITED_JS_MAP_RUNS: AtomicU32 = AtomicU32::new(0); +/// The exception the wait of the last `await_js_start()` failed with, if it failed. +static AWAITED_JS_ERROR: Mutex> = Mutex::new(None); +/// What cancels the wait of the last `await_js_start(Cancellable)`. +static AWAITED_JS_CANCEL: Mutex>> = Mutex::new(None); +/// The wait of the last `await_js_start(Held)`, until `poll_held_awaited_js()` finds it ended. +static AWAITED_JS_HELD: Mutex>> = Mutex::new(None); + +fn set_awaited_js_outcome(outcome: String) { + *AWAITED_JS_OUTCOME + .lock() + .unwrap_or_else(PoisonError::into_inner) = outcome; +} + +/// Records the exception the wait failed with, if it did, and returns how the wait ended. +fn record_awaited_js(result: std::result::Result) -> String { + match result { + Ok(value) => format!("fulfilled: {value}"), + Err(err) => { + let outcome = format!("rejected: {}", err.what()); + *AWAITED_JS_ERROR + .lock() + .unwrap_or_else(PoisonError::into_inner) = Some(err); + outcome + } + } +} + +/// The conversion of `await_js_start()`'s wait, which counts its runs. +fn count_and_convert<'a>( + lock: &mut jsg::Lock<'a>, + value: v8::Local<'a, v8::Value>, +) -> jsg::Result { + AWAITED_JS_MAP_RUNS.fetch_add(1, Ordering::SeqCst); + f64::from_js(lock, value) +} + +/// The conversion of `await_js_start(MapThrows)`'s wait: calls a function that throws. +fn count_and_throw<'a>( + lock: &mut jsg::Lock<'a>, + _value: v8::Local<'a, v8::Value>, +) -> jsg::Result { + AWAITED_JS_MAP_RUNS.fetch_add(1, Ordering::SeqCst); + let thrower = v8::Function::new(lock, (), |_lock, (), _args| { + Err(jsg::Error::new_range_error("thrown by JavaScript")) + })?; + thrower.call(lock, None, &[])?; + unreachable!("the function throws") +} + +/// The conversion of `await_js_start(MapFails)`'s wait. +fn count_and_fail<'a>( + _lock: &mut jsg::Lock<'a>, + _value: v8::Local<'a, v8::Value>, +) -> jsg::Result { + AWAITED_JS_MAP_RUNS.fetch_add(1, Ordering::SeqCst); + Err(jsg::Error::new_range_error("the conversion failed")) +} + +/// The conversion of `await_js_start(MapFailsInternally)`'s wait. +fn count_and_fail_internally<'a>( + _lock: &mut jsg::Lock<'a>, + _value: v8::Local<'a, v8::Value>, +) -> jsg::Result { + AWAITED_JS_MAP_RUNS.fetch_add(1, Ordering::SeqCst); + Err(jsg::Error::new_internal_error( + "the conversion failed internally", + )) +} + +/// In a request, `IoContext::await_js()`s a new promise as `start` says, and records how the +/// wait ends from the future that an `await_io_and_run()` waits for, so that it is recorded even +/// once the request is aborted, when the callback no longer runs. +unsafe fn await_js_start(isolate: usize, start: ffi::AwaitJsStart) -> Result<()> { + set_awaited_js_outcome("pending".to_owned()); + AWAITED_JS_MAP_RUNS.store(0, Ordering::SeqCst); + AWAITED_JS_ERROR + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take(); + AWAITED_JS_HELD + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take(); + AWAITED_JS_RESOLVER.with(|cell| cell.borrow_mut().take()); + let (cancel, cancelled) = oneshot::channel::<()>(); + // Without `Cancellable`, the future holds the sender, so that the wait is never cancelled. + let held_cancel = if start == ffi::AwaitJsStart::Cancellable { + *AWAITED_JS_CANCEL + .lock() + .unwrap_or_else(PoisonError::into_inner) = Some(cancel); + None + } else { + Some(cancel) + }; + + // SAFETY: see the module documentation. + jsg::callback_scope!(unsafe let lock, isolate as *mut v8::ffi::Isolate); + let context = IoContext::current(lock).map_err(|err| to_io(&err))?; + let resolver = v8::PromiseResolver::new(lock).map_err(|err| to_io(&err))?; + let promise = resolver.promise(); + let wait = match start { + ffi::AwaitJsStart::MapThrows => context.await_js(lock, promise, count_and_throw), + ffi::AwaitJsStart::MapFails => context.await_js(lock, promise, count_and_fail), + ffi::AwaitJsStart::MapFailsInternally => { + context.await_js(lock, promise, count_and_fail_internally) + } + _ => context.await_js(lock, promise, count_and_convert), + } + .map_err(|err| to_io(&err))?; + if start != ffi::AwaitJsStart::DropResolver { + let resolver = resolver.to_global(lock); + AWAITED_JS_RESOLVER.with(|cell| *cell.borrow_mut() = Some(resolver)); + } + if start == ffi::AwaitJsStart::Held { + *AWAITED_JS_HELD + .lock() + .unwrap_or_else(PoisonError::into_inner) = Some(wait); + return Ok(()); + } + let future = async move { + let _held_cancel = held_cancel; + let outcome = match futures::future::select(wait, cancelled).await { + futures::future::Either::Left((result, _)) => record_awaited_js(result), + futures::future::Either::Right(_) => "cancelled".to_owned(), + }; + set_awaited_js_outcome(outcome); + }; + context + .await_io_and_run(future, |_lock, ()| Ok(())) + .map_err(|err| to_io(&err)) +} + +/// In a request, aborts it as `ctx.abort(reason)` does, through `IoContext::abort()`, with +/// `reason`, a handle in the caller's scope, and fails unless that leaves the termination pending, +/// for C++ to cancel. +unsafe fn abort_request(isolate: usize, reason: v8::ffi::Local) -> Result<()> { + // SAFETY: see the module documentation. + jsg::callback_scope!(unsafe let lock, isolate as *mut v8::ffi::Isolate); + // SAFETY: C++ passes a handle of the scope `lock` stands for. + let reason = unsafe { v8::Local::::from_ffi(reason) }; + let context = IoContext::current(lock).map_err(|err| to_io(&err))?; + let termination = context.abort(lock, Some(reason)); + if termination.is_pending() { + Ok(()) + } else { + Err(to_io(&termination)) + } +} + +/// Fulfills the promise of the last `await_js_start()` with 42, or rejects it with a +/// `TypeError`, from the request this is called in. +unsafe fn settle_awaited_js(isolate: usize, fulfill: bool) -> Result<()> { + // SAFETY: see the module documentation. + jsg::callback_scope!(unsafe let lock, isolate as *mut v8::ffi::Isolate); + let resolver = AWAITED_JS_RESOLVER + .with(|cell| cell.borrow_mut().take()) + .ok_or_else(|| std::io::Error::other("await_js_start() kept no resolver"))? + .as_local(lock); + if fulfill { + let value = 42.0_f64.to_js(lock).map_err(|err| to_io(&err))?; + resolver.resolve(lock, value) + } else { + let reason = lock + .exception(&jsg::Error::new_type_error("boom")) + .map_err(|err| to_io(&err))?; + resolver.reject(lock, reason) + } + .map_err(|err| to_io(&err)) +} + +/// Rejects the promise of the last `await_js_start()` with `reason`, a handle in the caller's +/// scope. +unsafe fn reject_awaited_js(isolate: usize, reason: v8::ffi::Local) -> Result<()> { + // SAFETY: see the module documentation. + jsg::callback_scope!(unsafe let lock, isolate as *mut v8::ffi::Isolate); + // SAFETY: C++ passes a handle of the scope `lock` stands for. + let reason = unsafe { v8::Local::::from_ffi(reason) }; + AWAITED_JS_RESOLVER + .with(|cell| cell.borrow_mut().take()) + .ok_or_else(|| std::io::Error::other("await_js_start() kept no resolver"))? + .as_local(lock) + .reject(lock, reason) + .map_err(|err| to_io(&err)) +} + +/// Drops the resolver the last `await_js_start()` kept. +fn forget_awaited_js_resolver() { + AWAITED_JS_RESOLVER.with(|cell| cell.borrow_mut().take()); +} + +/// Cancels the wait of the last `await_js_start(Cancellable)`; false if there was none. +fn cancel_awaited_js() -> bool { + AWAITED_JS_CANCEL + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take() + .is_some_and(|cancel| cancel.send(()).is_ok()) +} + +fn awaited_js_outcome() -> String { + AWAITED_JS_OUTCOME + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() +} + +fn awaited_js_map_runs() -> u32 { + AWAITED_JS_MAP_RUNS.load(Ordering::SeqCst) +} + +fn awaited_js_detail_ids() -> Vec { + AWAITED_JS_ERROR + .lock() + .unwrap_or_else(PoisonError::into_inner) + .as_ref() + .and_then(cxx::KjException::details) + .map(|details| details.iter().map(|(id, _)| *id).collect()) + .unwrap_or_default() +} + +/// Takes the exception the wait of the last `await_js_start()` failed with and fails with it, +/// which C++ receives as that exception, or succeeds if it has not failed. +fn take_awaited_js_error() -> std::result::Result<(), cxx::KjException> { + AWAITED_JS_ERROR + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take() + .map_or(Ok(()), Err) +} + +/// Polls the wait of the last `await_js_start(Held)` once, and, if it has ended, records how, as +/// for the other waits, and returns true. +fn poll_held_awaited_js() -> bool { + let mut held = AWAITED_JS_HELD + .lock() + .unwrap_or_else(PoisonError::into_inner); + let Some(result) = held.as_mut().and_then(FutureExt::now_or_never) else { + return false; + }; + held.take(); + drop(held); + set_awaited_js_outcome(record_awaited_js(result)); + true +} + +/// In a request, `IoContext::log_uncaught_exception()`s `exception`, a handle in the caller's +/// scope, as from `source`. +unsafe fn log_uncaught_exception( + isolate: usize, + source: ffi::LogSource, + exception: v8::ffi::Local, +) -> Result<()> { + let source = if source == ffi::LogSource::Internal { + io_context::UncaughtExceptionSource::Internal + } else { + io_context::UncaughtExceptionSource::InternalAsync + }; + // SAFETY: see the module documentation. + jsg::callback_scope!(unsafe let lock, isolate as *mut v8::ffi::Isolate); + // SAFETY: C++ passes a handle of the scope `lock` stands for. + let exception = unsafe { v8::Local::::from_ffi(exception) }; + IoContext::current(lock) + .and_then(|context| context.log_uncaught_exception(lock, source, exception)) + .map_err(|err| to_io(&err)) +} + /// Resources for the JavaScript of `request-ops-test.c++`, in a module of their own because the /// resource macros expect the prelude's `Result`. mod execution_context { @@ -807,6 +1132,25 @@ mod execution_context { IoContext::current(lock)?.add_wait_until(lock, promise) } + /// Has the request wait for `promise` through `IoContext::await_js()`, ignoring how the + /// wait ends. `ctx.waitUntil()`, which waits through C++ `IoContext::awaitJs()`, is its + /// counterpart in the C++ `ExecutionContext`. + #[jsg_method] + fn await_js<'s>( + &self, + lock: &mut jsg::Lock<'s>, + promise: v8::VoidPromise<'s>, + ) -> jsg::Result<()> { + let context = IoContext::current(lock)?; + let wait = context.await_js(lock, promise, |_lock, _value| Ok(()))?; + context.await_io_and_run( + async move { + let _ = wait.await; + }, + |_lock, ()| Ok(()), + ) + } + #[jsg_method] fn pass_through_on_exception(&self, lock: &mut jsg::Lock) -> jsg::Result<()> { IoContext::current(lock)?.set_fail_open() diff --git a/src/workerd/io/limit-enforcer.h b/src/workerd/io/limit-enforcer.h index 6dc11650c09..5e353ddfa11 100644 --- a/src/workerd/io/limit-enforcer.h +++ b/src/workerd/io/limit-enforcer.h @@ -109,6 +109,8 @@ class IsolateLimitEnforcer: public kj::Refcounted { return 128 * 1024 * 1024; // 128 MB } + // IoContext::awaitJs() calls this when the promise it waits for is never settled, which can be + // in a GC finalizer or without the isolate lock, so it must neither enter V8 nor need the lock. virtual bool hasExcessivelyExceededHeapLimit() const = 0; // Returns the TrackedWasmInstanceList for this isolate. Subclasses own the list and provide diff --git a/src/workerd/jsg/inspector.c++ b/src/workerd/jsg/inspector.c++ index a434696e136..ff91c386809 100644 --- a/src/workerd/jsg/inspector.c++ +++ b/src/workerd/jsg/inspector.c++ @@ -36,6 +36,20 @@ kj::String KJ_STRINGIFY(const v8_inspector::StringView& view) { namespace workerd::jsg { +namespace { + +// `value` as kj::str(value) describes it, without a jsg::Lock. kj::none if V8 fails, leaving an +// exception pending. +kj::Maybe describe(v8::Isolate* isolate, v8::Local value) { + v8::Local detail; + if (!toDetailString(isolate, value).ToLocal(&detail)) return kj::none; + v8::String::Utf8Value utf8(isolate, detail); + if (*utf8 == nullptr) return kj::str("(couldn't stringify)"); + return kj::str(*utf8); +} + +} // namespace + StringViewWithScratch toInspectorStringView(kj::StringPtr text) { bool isAscii = simdutf::validate_ascii(text.begin(), text.size()); @@ -73,28 +87,39 @@ void sendExceptionToInspector(jsg::Lock& js, message = jsg::JsMessage::create(js, jsg::JsValue(exception)); } - // TODO(cleanup): Move the inspector stuff into a utility within jsg to better - // encapsulate KJ_ASSERT(message); - v8::Local msg = message; + if (!sendExceptionToInspector(js.v8Isolate, inspector, source, exception, message)) { + throw JsExceptionThrown(); + } +} - auto context = js.v8Context(); +bool sendExceptionToInspector(v8::Isolate* isolate, + v8_inspector::V8Inspector& inspector, + kj::StringPtr source, + v8::Local exception, + v8::Local message) { + v8::HandleScope scope(isolate); + auto context = isolate->GetCurrentContext(); - auto stackTrace = msg->GetStackTrace(); + auto stackTrace = message->GetStackTrace(); // The resource name is whatever we set in the Script ctor, e.g. "worker.js". - auto scriptResourceName = kj::str(msg->GetScriptResourceName()); - auto detailedMessage = kj::str(msg->Get()); - - auto lineNumber = msg->GetLineNumber(context).FromMaybe(0); - auto startColumn = msg->GetStartColumn(context).FromMaybe(0); - - // TODO(soon): EW-2636 Pass a real "script ID" as the last parameter instead of 0. I suspect this - // has something to do with the incorrect links in the console when it logs uncaught exceptions. - inspector.exceptionThrown(context, jsg::toInspectorStringView(source).stringView, exception, - jsg::toInspectorStringView(detailedMessage).stringView, - jsg::toInspectorStringView(scriptResourceName).stringView, lineNumber, startColumn, - inspector.createStackTrace(stackTrace), 0); + KJ_IF_SOME(scriptResourceName, describe(isolate, message->GetScriptResourceName())) { + KJ_IF_SOME(detailedMessage, describe(isolate, message->Get())) { + auto lineNumber = message->GetLineNumber(context).FromMaybe(0); + auto startColumn = message->GetStartColumn(context).FromMaybe(0); + + // TODO(soon): EW-2636 Pass a real "script ID" as the last parameter instead of 0. I suspect + // this has something to do with the incorrect links in the console when it logs uncaught + // exceptions. + inspector.exceptionThrown(context, toInspectorStringView(source).stringView, exception, + toInspectorStringView(detailedMessage).stringView, + toInspectorStringView(scriptResourceName).stringView, lineNumber, startColumn, + inspector.createStackTrace(stackTrace), 0); + return true; + } + } + return false; } } // namespace workerd::jsg diff --git a/src/workerd/jsg/inspector.h b/src/workerd/jsg/inspector.h index 9a30bb47bcd..e8780664cd4 100644 --- a/src/workerd/jsg/inspector.h +++ b/src/workerd/jsg/inspector.h @@ -49,6 +49,17 @@ void sendExceptionToInspector(jsg::Lock& js, const JsValue& exception, JsMessage message); +// Inform the inspector of an exception thrown, as the overload above does once it has a message. +// +// Runs no JavaScript, and takes no jsg::Lock, for native code that holds none, such as Rust JSG's +// shims. Requires an entered context. Returns false, and reports nothing, if V8 fails to describe +// the message, leaving an exception pending, which it does only if execution is terminating. +bool sendExceptionToInspector(v8::Isolate* isolate, + v8_inspector::V8Inspector& inspector, + kj::StringPtr source, + v8::Local exception, + v8::Local message); + } // namespace workerd::jsg namespace v8_inspector {