diff --git a/src/workerd/jsg/async-context.c++ b/src/workerd/jsg/async-context.c++ index 1cec84feba3..e34cac3ce9a 100644 --- a/src/workerd/jsg/async-context.c++ +++ b/src/workerd/jsg/async-context.c++ @@ -31,6 +31,10 @@ struct AsyncResourceWrappable final: public Wrappable, } return nullptr; } + + kj::Maybe> maybeGetStrongRef() override { + return kj::addRef(*this); + } }; } // namespace @@ -62,7 +66,7 @@ AsyncResource::~AsyncResource() noexcept(false) { AsyncResource& AsyncResource::current(Lock& js) { auto& isolateBase = IsolateBase::from(js.v8Isolate); KJ_ASSERT(!isolateBase.asyncResourceStack.empty()); - return *isolateBase.asyncResourceStack.front(); + return *isolateBase.asyncResourceStack.front().resource; } kj::Own AsyncResource::create(Lock& js, kj::Maybe maybeParent) { @@ -179,7 +183,10 @@ AsyncResource::StorageScope::~StorageScope() noexcept(false) { } void IsolateBase::pushAsyncResource(AsyncResource& next) { - asyncResourceStack.push_front(&next); + asyncResourceStack.push_front(AsyncResourceEntry{ + &next, + next.maybeGetStrongRef() + }); } void IsolateBase::popAsyncResource() { diff --git a/src/workerd/jsg/async-context.h b/src/workerd/jsg/async-context.h index f25ff45e0a2..87ba1bdf07e 100644 --- a/src/workerd/jsg/async-context.h +++ b/src/workerd/jsg/async-context.h @@ -58,6 +58,8 @@ class AsyncResource { ~AsyncResource() noexcept(false); + virtual kj::Maybe> maybeGetStrongRef() { return nullptr; } + static AsyncResource& current(Lock& js); static kj::Own create(Lock& js, kj::Maybe maybeParent = nullptr); diff --git a/src/workerd/jsg/setup.c++ b/src/workerd/jsg/setup.c++ index b50fa443f6e..b34352113c1 100644 --- a/src/workerd/jsg/setup.c++ +++ b/src/workerd/jsg/setup.c++ @@ -325,7 +325,7 @@ IsolateBase::IsolateBase(const V8System& system, v8::Isolate::CreateParams&& cre ptr(newIsolate(kj::mv(createParams))), heapTracer(ptr), rootAsyncResource(*this) { - asyncResourceStack.push_front(&rootAsyncResource); + asyncResourceStack.push_front({&rootAsyncResource}); ptr->SetFatalErrorHandler(&fatalError); ptr->SetOOMErrorHandler(&oomError); diff --git a/src/workerd/jsg/setup.h b/src/workerd/jsg/setup.h index e4ff5e6ff8e..641a549e7b3 100644 --- a/src/workerd/jsg/setup.h +++ b/src/workerd/jsg/setup.h @@ -238,8 +238,13 @@ class IsolateBase { void pushAsyncResource(AsyncResource& next); void popAsyncResource(); + struct AsyncResourceEntry { + AsyncResource* resource; + kj::Maybe> maybeStrongRef; + }; + uint64_t nextAsyncResourceId = 0; - std::deque asyncResourceStack; + std::deque asyncResourceStack; kj::HashMap asyncResourcesMap; AsyncResource rootAsyncResource;