Skip to content
Closed
17 changes: 14 additions & 3 deletions src/js/builtins/ProcessObjectInternals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,12 +348,13 @@ export function initializeNextTickQueue(process: typeof globalThis.process, next
var drainMicrotasks = drainMicrotasksFn;

const { validateFunction } = require("internal/validators");
const asyncHooksTick = require("internal/async_hooks_tick");

var setup;
setup = () => {
const { FixedQueue } = require("internal/fixed_queue");
queue = new FixedQueue();
tickInitHooks = require("internal/async_hooks_tick").tickInitHooks;
tickInitHooks = asyncHooksTick.tickInitHooks;

function processTicksAndRejections() {
var tock;
Expand Down Expand Up @@ -393,7 +394,8 @@ export function initializeNextTickQueue(process: typeof globalThis.process, next
}

drainMicrotasks();
} while (!queue.isEmpty());
// With both queues empty, internal/process/after_tick_drain.ts (once something loaded it) runs one callback.
} while (!queue.isEmpty() || asyncHooksTick.runAfterTickDrainCallback?.());
Comment thread
robobun marked this conversation as resolved.
Resolved
}

$putInternalField(nextTickQueue, 0, 0);
Expand All @@ -402,6 +404,16 @@ export function initializeNextTickQueue(process: typeof globalThis.process, next
setup = undefined;
};

// For internal/process/after_tick_drain.ts: makes the next drain call the tick loop, without a call of
// process.nextTick, which fake timers replace. JSNextTickQueue::drain only calls in while field 0 is set.
Comment thread
robobun marked this conversation as resolved.
Resolved
asyncHooksTick.ensureTickLoop = () => {
if (setup) {
setup();
process = globalThis.process;
}
$putInternalField(nextTickQueue, 0, 1);
};

function nextTick(cb, ...args) {
validateFunction(cb, "callback");
if (setup) {
Expand All @@ -420,7 +432,6 @@ export function initializeNextTickQueue(process: typeof globalThis.process, next
if (tickInitHooks.length !== 0) {
// node fires one TickObject init per process.nextTick() call, at
// construction time (before the callback runs).
const asyncHooksTick = require("internal/async_hooks_tick");
const asyncId = asyncHooksTick.newAsyncId();
// Snapshot: enable()/disable() from inside a hook must not affect the
// in-flight dispatch (node stages such mutations in tmp_array until
Expand Down
8 changes: 8 additions & 0 deletions src/js/internal/async_hooks_tick.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
// Currently only TickObject `init` events are delivered (enough for
// console.log/stream.write tick-coalescing tests); promise, timer and native
// resource events are still unimplemented.
//
// `ensureTickLoop` and `runAfterTickDrainCallback` connect the tick loop and
// internal/process/after_tick_drain.ts. The tick loop does not load that
// module, so a process that never uses it pays one property read for each drain.
Comment thread
robobun marked this conversation as resolved.
Resolved
const tickInitHooks: Array<(asyncId: number, type: string, triggerAsyncId: number, resource: object) => void> = [];
let nextAsyncId = 1;

Expand All @@ -17,4 +21,8 @@ export default {
newAsyncId() {
return ++nextAsyncId;
},
// Set when process.nextTick is first read, which creates the tick queue.
ensureTickLoop: undefined as (() => void) | undefined,
// Set by internal/process/after_tick_drain.ts. The tick loop calls it each time both queues are empty.
runAfterTickDrainCallback: undefined as (() => boolean) | undefined,
};
65 changes: 65 additions & 0 deletions src/js/internal/process/after_tick_drain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Node calls into JS once for each libuv event, and after each call it runs
// every process.nextTick callback and every promise job, until both queues
// are empty. So the next event of a handle (the next chunk, the EOF) never
// runs ahead of a tick or a promise job that a listener of the previous event
// queued, however long the chain of ticks and jobs is.
// https://github.com/nodejs/node/blob/v24.9.0/lib/internal/process/task_queues.js#L72-L109
//
// A module that gets several of Node's events out of one native call gives
// each of them a drain of its own with `runAfterTickDrain`. The tick loop
// (processTicksAndRejections in builtins/ProcessObjectInternals.ts) runs one
// of these callbacks each time both queues are empty, where Node's loop calls
// processPromiseRejections(). That happens inside the drain that is running,
// so no other I/O callback runs in between.
//
// Only nextTicks and promise jobs run between two callbacks. Bun reports
// unhandled rejections after the whole drain, and Node reads a pipe once for
// each turn of the event loop, so there a setImmediate() of a listener also
// runs before the next event. A setImmediate() here would wait for that too,
// but fake timers replace it, and it costs a turn of the event loop for each
// chunk.
Comment thread
robobun marked this conversation as resolved.
Resolved
const asyncHooksTick = require("internal/async_hooks_tick");

type AfterTickDrainCallback = {
callback: (arg: any) => void;
arg: unknown;
frame: import("../../node/async_hooks").Frame | undefined;
};

// A queue: entries before `head` are done. Bounded by the number of callers, which each wait for their turn.
const entries: (AfterTickDrainCallback | undefined)[] = [];
let head = 0;

function runAfterTickDrain(callback: (arg: any) => void, arg?: unknown) {
let ensureTickLoop = asyncHooksTick.ensureTickLoop;
if (ensureTickLoop === undefined) {
// The first read of process.nextTick creates the tick queue. Fake timers read it before they replace it.
void process.nextTick;
ensureTickLoop = asyncHooksTick.ensureTickLoop;
// process.nextTick was overwritten before its first read: there is no tick loop to wait for.
if (ensureTickLoop === undefined) return process.nextTick(callback, arg);
}
ensureTickLoop();
$arrayPush(entries, { callback, arg, frame: $getInternalField($asyncContext, 0) });
}

// The tick loop calls this each time both queues are empty. False: nothing waited.
function runAfterTickDrainCallback() {
if (head === entries.length) return false;
const { callback, arg, frame } = entries[head]!;
entries[head++] = undefined;
if (head === entries.length) {
entries.length = 0;
head = 0;
}
Comment thread
robobun marked this conversation as resolved.
Resolved
const restore = $getInternalField($asyncContext, 0);
$putInternalField($asyncContext, 0, frame);
// No catch and no finally, as for a tick: JSNextTickQueue::drain reports a throw inside the
// callback's async context, puts the context back, and calls the tick loop again.
Comment thread
robobun marked this conversation as resolved.
Resolved
callback(arg);
$putInternalField($asyncContext, 0, restore);
return true;
}
asyncHooksTick.runAfterTickDrainCallback = runAfterTickDrainCallback;

export default { runAfterTickDrain };
Loading
Loading