GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — ffi: drain task queues after event loop callbacks · nodejs/node@53570d2

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • src
    • node_ffi.cc
  • test/ffi
    • test-ffi-callbacks.js
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎src/node_ffi.cc‎

Copy file name to clipboardExpand all lines: src/node_ffi.cc
+13Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include <cstring>
66
#include <limits>
77
#include <memory>
8+
#include <optional>
89
#include "base_object-inl.h"
910
#include "env-inl.h"
1011
#include "ffi/data.h"
@@ -13,6 +14,7 @@
1314
#include "ffi/types.h"
1415
#include "node_binding.h"
1516
#include "node_errors.h"
17+
#include "node_internals.h"
1618

1719
namespace node {
1820

@@ -772,6 +774,17 @@ void DynamicLibrary::InvokeCallback(ffi_cif* cif,
772774
callback_args[i] = ToJSArgument(isolate, cb->args[i], args[i]);
773775
}
774776

777+
// When native code invokes the callback from the event loop (for example
778+
// through a libuv handle), no callback scope is active. Open one so that
779+
// nextTick and microtasks queued by the callback are drained when it
780+
// returns, as for Node.js's own callbacks. Callbacks invoked synchronously
781+
// during a call into native code already run inside the caller's scope.
782+
Context::Scope context_scope(context);
783+
std::optional<InternalCallbackScope> callback_scope;
784+
if (env->async_callback_scope_depth() == 0) {
785+
callback_scope.emplace(env, Object::New(isolate), async_context{0, 0});
786+
}
787+
775788
TryCatch try_catch(isolate);
776789
Local<Function> callback = Local<Function>::New(isolate, cb->fn);
777790
MaybeLocal<Value> result = callback->Call(
Collapse file

‎test/ffi/test-ffi-callbacks.js‎

Copy file name to clipboardExpand all lines: test/ffi/test-ffi-callbacks.js
+60Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,3 +82,63 @@ test('ffi callback ref and unref APIs work', () => {
8282
lib.close();
8383
}
8484
});
85+
86+
test('ffi callbacks drain nextTick and microtasks only from the event loop', {
87+
skip: common.isWindows,
88+
}, async () => {
89+
const { lib, functions: symbols } = getLibrary();
90+
let ran = false;
91+
const syncCallback = lib.registerCallback(
92+
{ arguments: ['i32'], return: 'i32' },
93+
(value) => {
94+
queueMicrotask(() => { ran = true; });
95+
return value;
96+
},
97+
);
98+
99+
// The process exports libuv, so a uv timer can invoke the callback from
100+
// the event loop with no JS on the stack.
101+
const { lib: uvLib, functions: uv } = ffi.dlopen(null, {
102+
uv_handle_size: { arguments: ['i32'], return: 'u64' },
103+
uv_timer_init: { arguments: ['pointer', 'pointer'], return: 'i32' },
104+
uv_timer_start: { arguments: ['pointer', 'pointer', 'u64', 'u64'], return: 'i32' },
105+
uv_close: { arguments: ['pointer', 'pointer'], return: 'void' },
106+
});
107+
const UV_TIMER = 13;
108+
const timerSize = Number(uv.uv_handle_size(UV_TIMER)) + 64;
109+
const timers = [new Uint8Array(timerSize), new Uint8Array(timerSize)];
110+
const { promise, resolve } = Promise.withResolvers();
111+
const order = [];
112+
const timerCallbacks = [
113+
uvLib.registerCallback({ arguments: ['pointer'], return: 'void' }, () => {
114+
order.push('callback');
115+
process.nextTick(() => order.push('nextTick'));
116+
queueMicrotask(() => order.push('microtask'));
117+
}),
118+
// The second timer runs right after the first one, with no Node.js
119+
// callback in between that could drain the queues instead.
120+
uvLib.registerCallback({ arguments: ['pointer'], return: 'void' }, () => {
121+
resolve([...order]);
122+
for (const timer of timers) uv.uv_close(timer, 0n);
123+
}),
124+
];
125+
126+
try {
127+
// A callback invoked synchronously runs inside the caller's scope, so its
128+
// microtasks must not run before the native call returns.
129+
assert.strictEqual(symbols.call_int_callback(syncCallback, 1), 1);
130+
assert.strictEqual(ran, false);
131+
132+
const loop = ffi.getCurrentEventLoop();
133+
for (let i = 0; i < timers.length; i++) {
134+
assert.strictEqual(uv.uv_timer_init(loop, timers[i]), 0);
135+
assert.strictEqual(uv.uv_timer_start(timers[i], timerCallbacks[i], 0n, 0n), 0);
136+
}
137+
assert.deepStrictEqual(await promise, ['callback', 'nextTick', 'microtask']);
138+
// Let the uv_close() of the timer handles complete.
139+
await new Promise(setImmediate);
140+
} finally {
141+
lib.close();
142+
uvLib.close();
143+
}
144+
});

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.