diff --git a/code/components/citizen-scripting-node/include/NodeScriptRuntime.h b/code/components/citizen-scripting-node/include/NodeScriptRuntime.h index a2e322cb2d..5f1418d426 100644 --- a/code/components/citizen-scripting-node/include/NodeScriptRuntime.h +++ b/code/components/citizen-scripting-node/include/NodeScriptRuntime.h @@ -74,6 +74,9 @@ class NodeScriptRuntime : public OMClass m_stringValues[50]; int m_curStringValue; + // set after an event or ref call, TickFast then runs the promise continuations they queued + mutable std::atomic m_hasPendingCallbacks = false; + // routines and callbacks TTickRoutine m_tickRoutine; TEventRoutine m_eventRoutine; diff --git a/code/components/citizen-scripting-node/src/NodeScriptRuntime.cpp b/code/components/citizen-scripting-node/src/NodeScriptRuntime.cpp index b51445319d..eee7cdf0b7 100644 --- a/code/components/citizen-scripting-node/src/NodeScriptRuntime.cpp +++ b/code/components/citizen-scripting-node/src/NodeScriptRuntime.cpp @@ -552,10 +552,43 @@ result_t NodeScriptRuntime::Destroy() void NodeScriptRuntime::TickFast() const { - SharedPushEnvironmentNoContext _(m_isolate); - // SharedPushEnvironment pushed(this); - uv_run(m_uvLoop, UV_RUN_NOWAIT); - g_nodeEnv.GetPlatform()->DrainTasks(m_isolate); + { + SharedPushEnvironmentNoContext _(m_isolate); + // SharedPushEnvironment pushed(this); + uv_run(m_uvLoop, UV_RUN_NOWAIT); + g_nodeEnv.GetPlatform()->DrainTasks(m_isolate); + } + + // events and ref calls from other resources don't come through our uv loop, so the promise + // continuations they queue (e.g. `await` on a callback from another resource) would otherwise + // wait for our next tick. Run them here, outside of any JS, like node does after its own callbacks. + if (m_hasPendingCallbacks.exchange(false) && m_nodeEnvironment) + { + // this is outside the resource tick, so give it its own profiler scope + fwRefContainer profiler; + + if (m_parentObject) + { + profiler = m_parentObject->GetManager()->GetComponent(); + } + + const bool profiling = profiler.GetRef() && profiler->IsRecording(); + + if (profiling) + { + profiler->EnterResource(m_resourceName, "callbacks"); + } + + { + SharedPushEnvironment pushed(this); + node::CallbackScope scope(m_nodeEnvironment, GetContext()->Global(), node::async_context{ 0, 0 }); + } + + if (profiling) + { + profiler->ExitResource(); + } + } } result_t NodeScriptRuntime::Tick() @@ -582,6 +615,7 @@ result_t NodeScriptRuntime::TriggerEvent(char* eventName, char* eventPayload, ui { SharedPushEnvironment pushed(this); m_eventRoutine(eventName, eventPayload, payloadSize, eventSource); + m_hasPendingCallbacks = true; } return FX_S_OK; } @@ -747,6 +781,7 @@ result_t NodeScriptRuntime::CallRef(int32_t refIdx, char* argsSerialized, uint32 SharedPushEnvironment pushed(this); auto rv = m_callRefRoutine(refIdx, argsSerialized, argsLength); + m_hasPendingCallbacks = true; return rv.CopyTo(retval); } return FX_S_OK;