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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion REPLAY_BACKEND_REV
Original file line number Diff line number Diff line change
@@ -1 +1 @@
8f4031d9945c50a8f41ea8279347f86e6afbb8eb
f6e6c8c29dd50b1d60a064aeba476b4ba1c5ca1c
8 changes: 8 additions & 0 deletions lib/async_hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ const {
emitDestroy,
initHooksExist,
destroyHooksExist,
dependencyGraphInit,
dependencyGraphInitMicrotask,
microtaskResourceOptions,
} = internal_async_hooks;

// Get symbols
Expand Down Expand Up @@ -200,6 +203,11 @@ class AsyncResource {
this[async_id_symbol] = asyncId;
this[trigger_async_id_symbol] = triggerAsyncId;

if (opts === microtaskResourceOptions)
dependencyGraphInitMicrotask(asyncId);
else
dependencyGraphInit(asyncId, type);

if (initHooksExist()) {
if (type.length === 0) {
throw new ERR_ASYNC_TYPE(type);
Expand Down
50 changes: 48 additions & 2 deletions lib/internal/async_hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -533,8 +533,11 @@ function emitAfterScript(asyncId) {


function emitDestroyScript(asyncId) {
// Return early if there are no destroy callbacks, or invalid asyncId.
if (!hasHooks(kDestroy) || !(asyncId > 0))
// Return early if the asyncId is invalid, or there are no destroy callbacks.
if (!(asyncId > 0))
return;
dependencyGraphDestroy(asyncId);
if (!hasHooks(kDestroy))
return;
async_wrap.queueDestroyAsyncId(asyncId);
}
Expand All @@ -556,6 +559,8 @@ function pushAsyncContext(asyncId, triggerAsyncId, resource) {
async_hook_fields[kStackLength]++;
async_id_fields[kExecutionAsyncId] = asyncId;
async_id_fields[kTriggerAsyncId] = triggerAsyncId;
if (dependencyGraph)
async_wrap.dependencyGraphPush(asyncId, offset);
}


Expand All @@ -574,10 +579,46 @@ function popAsyncContext(asyncId) {
async_id_fields[kTriggerAsyncId] = async_wrap.async_ids_stack[2 * offset + 1];
execution_async_resources.pop();
async_hook_fields[kStackLength] = offset;
if (dependencyGraph)
async_wrap.dependencyGraphPop(offset);
return offset > 0;
}


// The Replay dependency graph (src/node_dependency_graph.h): whether this
// thread reports async ops to it. Set at pre-execution, so that the snapshot
// doesn't hold it. The value is recorded, so JS takes the same paths when
// recording and replaying.
let dependencyGraph = false;

function setupDependencyGraph() {
dependencyGraph = async_wrap.dependencyGraphInstrumented();
}

function dependencyGraphInstrumented() {
return dependencyGraph;
}

function dependencyGraphInit(asyncId, type) {
if (dependencyGraph)
async_wrap.dependencyGraphInit(asyncId, type);
}

function dependencyGraphInitMicrotask(asyncId) {
if (dependencyGraph)
async_wrap.dependencyGraphInitMicrotask(asyncId);
}

function dependencyGraphDestroy(asyncId) {
if (dependencyGraph)
async_wrap.dependencyGraphDestroy(asyncId);
}

// The options queueMicrotask() creates its AsyncResource with. The dependency
// graph reports a resource created with them as a microtask.
const microtaskResourceOptions = { requireManualDestroy: true };


function executionAsyncId() {
return async_id_fields[kExecutionAsyncId];
}
Expand Down Expand Up @@ -626,6 +667,11 @@ module.exports = {
popAsyncContext,
registerDestroyHook,
useDomainTrampoline,
setupDependencyGraph,
dependencyGraphInstrumented,
dependencyGraphInit,
dependencyGraphInitMicrotask,
microtaskResourceOptions,
nativeHooks: {
init: emitInitNative,
before: emitBeforeNative,
Expand Down
2 changes: 2 additions & 0 deletions lib/internal/process/pre_execution.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const {
},
runDeserializeCallbacks,
} = require('internal/v8/startup_snapshot');
const { setupDependencyGraph } = require('internal/async_hooks');

function prepareMainThreadExecution(expandArgv1 = false, initializeModules = true) {
return prepareExecution({
Expand Down Expand Up @@ -108,6 +109,7 @@ function prepareExecution(options) {
const { expandArgv1, initializeModules, isMainThread, shouldSpawnLoaderHookWorker, shouldPreloadModules } = options;

refreshRuntimeOptions();
setupDependencyGraph();

// Patch the process object and get the resolved main entry point.
const mainEntry = patchProcessObject(expandArgv1);
Expand Down
13 changes: 8 additions & 5 deletions lib/internal/process/task_queues.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ const {
emitBefore,
emitAfter,
emitDestroy,
dependencyGraphInit,
dependencyGraphInstrumented,
microtaskResourceOptions,
symbols: { async_id_symbol, trigger_async_id_symbol },
} = require('internal/async_hooks');
const FixedQueue = require('internal/fixed_queue');
Expand Down Expand Up @@ -148,6 +151,7 @@ function nextTick(callback) {
const tickObject = new TickObject(callback, args, asyncId, triggerAsyncId);
if (initHooksExist())
emitInit(asyncId, 'TickObject', triggerAsyncId, tickObject);
dependencyGraphInit(asyncId, 'TickObject');
queue.push(tickObject);
}

Expand All @@ -162,21 +166,20 @@ function runMicrotask() {
});
}

const defaultMicrotaskResourceOpts = { requireManualDestroy: true };

function queueMicrotask(callback) {
validateFunction(callback, 'callback');

const contextFrame = AsyncContextFrame.current();
if (contextFrame || enabledHooksExist()) {
// The dependency graph reports the microtask through its AsyncResource.
if (contextFrame || enabledHooksExist() || dependencyGraphInstrumented()) {
const asyncResource = new AsyncResource(
'Microtask',
defaultMicrotaskResourceOpts,
microtaskResourceOptions,
);
asyncResource.callback = callback;
enqueueMicrotask(FunctionPrototypeBind(runMicrotask, asyncResource));
} else {
// Fast path: no AsyncLocalStorage in use
// Fast path: no AsyncLocalStorage, async hooks or dependency graph in use
enqueueMicrotask(callback);
}
}
Expand Down
16 changes: 14 additions & 2 deletions lib/internal/timers.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ const {
} = primordials;

const binding = internalBinding('timers');
const { dependencyGraphInitTimer } = internalBinding('async_wrap');
const {
immediateInfo,
timeoutInfo,
Expand All @@ -95,6 +96,8 @@ const {
getDefaultTriggerAsyncId,
newAsyncId,
initHooksExist,
dependencyGraphInit,
dependencyGraphInstrumented,
// The needed emit*() functions.
emitInit,
emitBefore,
Expand Down Expand Up @@ -209,6 +212,14 @@ function initAsyncResource(resource, type) {
emitInit(asyncId, type, triggerAsyncId, resource);
}

// Timeouts are timers in the dependency graph. Legacy enrolled objects have no
// _repeat and fire once. Their fields are only read while instrumented.
function initTimeoutAsyncResource(timer) {
initAsyncResource(timer, 'Timeout');
if (dependencyGraphInstrumented())
dependencyGraphInitTimer(timer[async_id_symbol], timer._idleTimeout, !timer._repeat);
}

let warnedNegativeNumber = false;
let warnedNotNumber = false;

Expand Down Expand Up @@ -256,7 +267,7 @@ class Timeout {
this[kRefed] = isRefed;
this[kHasPrimitive] = false;

initAsyncResource(this, 'Timeout');
initTimeoutAsyncResource(this);
}

// Make sure the linked list only shows the minimal necessary information.
Expand Down Expand Up @@ -407,7 +418,7 @@ function insertGuarded(item, refed) {
const isDestroyed = item._destroyed;
if (isDestroyed || !item[async_id_symbol]) {
item._destroyed = false;
initAsyncResource(item, 'Timeout');
initTimeoutAsyncResource(item);
}

if (isDestroyed) {
Expand Down Expand Up @@ -753,6 +764,7 @@ class Immediate {
this[kRefed] = false;

initAsyncResource(this, 'Immediate');
dependencyGraphInit(this[async_id_symbol], 'Immediate');

this.ref();
immediateInfo[kCount]++;
Expand Down
2 changes: 2 additions & 0 deletions node.gyp
Original file line number Diff line number Diff line change
Expand Up @@ -859,8 +859,10 @@
'sources': [
'<@(node_sources)',
'src/node_deferred_finalization.cc',
'src/node_dependency_graph.cc',
'src/node_recordreplay.cc',
'src/node_deferred_finalization.h',
'src/node_dependency_graph.h',
# Dependency headers
'deps/v8/include/v8.h',
'deps/postject/postject-api.h',
Expand Down
5 changes: 5 additions & 0 deletions src/async_wrap.cc
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,7 @@ void AsyncWrap::CreatePerIsolateProperties(IsolateData* isolate_data,
SetMethod(isolate, target, "setPromiseHooks", SetPromiseHooks);
SetMethod(isolate, target, "getPromiseHooks", GetPromiseHooks);
SetMethod(isolate, target, "registerDestroyHook", RegisterDestroyHook);
AsyncDependencyGraph::CreatePerIsolateProperties(isolate_data, target);
AsyncWrap::GetConstructorTemplate(isolate_data);
}

Expand Down Expand Up @@ -511,6 +512,7 @@ void AsyncWrap::RegisterExternalReferences(
registry->Register(SetPromiseHooks);
registry->Register(GetPromiseHooks);
registry->Register(RegisterDestroyHook);
AsyncDependencyGraph::RegisterExternalReferences(registry);
registry->Register(AsyncWrap::GetAsyncId);
registry->Register(AsyncWrap::AsyncReset);
registry->Register(AsyncWrap::GetAsyncContextFrame);
Expand Down Expand Up @@ -581,6 +583,8 @@ void AsyncWrap::EmitTraceEventDestroy() {
}

void AsyncWrap::EmitDestroy(Environment* env, double async_id) {
env->async_hooks()->dependency_graph().OnDestroy(async_id);

if (env->async_hooks()->fields()[AsyncHooks::kDestroy] == 0 ||
!env->can_call_into_js()) {
return;
Expand Down Expand Up @@ -668,6 +672,7 @@ void AsyncWrap::EmitAsyncInit(Environment* env,
CHECK(!object.IsEmpty());
CHECK(!type.IsEmpty());
AsyncHooks* async_hooks = env->async_hooks();
async_hooks->dependency_graph().OnInit(env->isolate(), async_id, type);

// Nothing to execute, so can continue normally.
if (async_hooks->fields()[AsyncHooks::kInit] == 0) {
Expand Down
3 changes: 3 additions & 0 deletions src/env.cc
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ void AsyncHooks::push_async_context(
fields_[kStackLength] += 1;
async_id_fields_[kExecutionAsyncId] = async_id;
async_id_fields_[kTriggerAsyncId] = trigger_async_id;
dependency_graph_.OnPush(async_id, offset);

#ifdef DEBUG
for (uint32_t i = offset; i < native_execution_async_resources_.size(); i++)
Expand Down Expand Up @@ -185,6 +186,7 @@ bool AsyncHooks::pop_async_context(double async_id) {
async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset];
async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1];
fields_[kStackLength] = offset;
dependency_graph_.OnPop(offset);

if (offset < native_execution_async_resources_.size() &&
std::visit([](auto* ptr) { return ptr != nullptr; },
Expand Down Expand Up @@ -227,6 +229,7 @@ void AsyncHooks::clear_async_id_stack() {
async_id_fields_[kExecutionAsyncId] = 0;
async_id_fields_[kTriggerAsyncId] = 0;
fields_[kStackLength] = 0;
dependency_graph_.OnPop(0);
}

void AsyncHooks::InstallPromiseHooks(Local<Context> ctx) {
Expand Down
6 changes: 6 additions & 0 deletions src/env.h
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
#include "node.h"
#include "node_binding.h"
#include "node_builtins.h"
#include "node_dependency_graph.h"
#include "node_exit_code.h"
#include "node_main_instance.h"
#include "node_options.h"
Expand Down Expand Up @@ -441,6 +442,9 @@ class AsyncHooks : public MemoryRetainer {
bool pop_async_context(double async_id);
void clear_async_id_stack(); // Used in fatal exceptions.

// The async ops in the Replay dependency graph, mirroring this stack.
AsyncDependencyGraph& dependency_graph() { return dependency_graph_; }

AsyncHooks(const AsyncHooks&) = delete;
AsyncHooks& operator=(const AsyncHooks&) = delete;
AsyncHooks(AsyncHooks&&) = delete;
Expand Down Expand Up @@ -512,6 +516,8 @@ class AsyncHooks : public MemoryRetainer {
const SerializeInfo* info_ = nullptr;

std::array<v8::Global<v8::Function>, 4> js_promise_hooks_;

AsyncDependencyGraph dependency_graph_;
};

class ImmediateInfo : public MemoryRetainer {
Expand Down
2 changes: 2 additions & 0 deletions src/node.cc
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,8 @@ MaybeLocal<Value> StartExecution(Environment* env,
if (v8::IsMainThread()) {
v8::recordreplay::NewCheckpoint();
}
// The root of the dependency graph: the main script runs in its window.
env->async_hooks()->dependency_graph().OnInitScript(1);
InternalCallbackScope callback_scope(
env,
Object::New(env->isolate()),
Expand Down
Loading