Skip to content

Commit 4d8ae36

Browse files
adrian-niculescuedusperoni
authored andcommitted
fix(worker): fire a worker_threads once listener at most once under a reentrant emit
An earlier listener that emitted the same event again let the nested emit fire and remove a later once listener, and the outer emit then called it a second time from its snapshot. A once registration now records that it fired, as Node's once wrapper does.
1 parent 0c55f95 commit 4d8ae36

2 files changed

Lines changed: 25 additions & 1 deletion

File tree

‎test-app/app/src/main/assets/app/tests/testMessaging.js‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,23 @@ describe("Messaging runtime edges", function () {
398398
});
399399
});
400400

401+
it("calls a node:worker_threads once listener once when an earlier listener emits again", function () {
402+
var wt = require("node:worker_threads");
403+
var worker = new wt.Worker("~/tests/eventLoopEchoWorker.js");
404+
var calls = 0;
405+
var nested = false;
406+
worker.on("probe", function () {
407+
if (!nested) {
408+
nested = true;
409+
worker.emit("probe");
410+
}
411+
});
412+
worker.once("probe", function () { calls++; });
413+
worker.emit("probe");
414+
worker.terminate();
415+
expect(calls).toBe(1);
416+
});
417+
401418
it("routes a throw from a parentPort listener to the parent's 'error' listeners", function (done) {
402419
var wt = require("node:worker_threads");
403420
var worker = new wt.Worker("~/tests/messaging/parentPortThrowingWorker.js");

‎test-app/runtime/src/main/cpp/js/node-worker-threads.js‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ class WorkerEmitter {
101101
}
102102
const key = `${type}`;
103103
const list = this.#listeners[key] || (this.#listeners[key] = []);
104-
ArrayPrototypePush(list, { listener, once: true });
104+
ArrayPrototypePush(list, { listener, once: true, fired: false });
105105
return this;
106106
}
107107

@@ -134,6 +134,13 @@ class WorkerEmitter {
134134
for (let i = 0; i < snapshot.length; i++) {
135135
const entry = snapshot[i];
136136
if (entry.once) {
137+
// Node's once wrapper: a registration fires at most once, even when
138+
// an earlier listener emits the same event again and the nested emit
139+
// fires it first.
140+
if (entry.fired) {
141+
continue;
142+
}
143+
entry.fired = true;
137144
const index = ArrayPrototypeIndexOf(list, entry);
138145
if (index !== -1) {
139146
ArrayPrototypeSplice(list, index, 1);

0 commit comments

Comments
 (0)