Skip to content

Commit 1c64bc5

Browse files
addaleaxcodebytere
authored andcommitted
worker: perform initial port.unref() before preload modules
The refcount of the internal communication port is relevant for stdio, but the `port.unref()` call effectively resets any `.ref()` calls happening during stdio operations happening before it. Therefore, do the `.unref()` call before loading preload modules, which may cause stdio operations. Fixes: #31777 PR-URL: #33455 Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Benjamin Gruenbaum <[email protected]> Reviewed-By: Juan José Arboleda <[email protected]>
1 parent 3b46e7f commit 1c64bc5

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

lib/internal/main/worker_thread.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ if (process.env.NODE_CHANNEL_FD) {
9292

9393
port.on('message', (message) => {
9494
if (message.type === LOAD_SCRIPT) {
95+
port.unref();
9596
const {
9697
argv,
9798
cwdCounter,
@@ -140,7 +141,6 @@ port.on('message', (message) => {
140141

141142
debug(`[${threadId}] starts worker script ${filename} ` +
142143
`(eval = ${eval}) at cwd = ${process.cwd()}`);
143-
port.unref();
144144
port.postMessage({ type: UP_AND_RUNNING });
145145
if (doEval) {
146146
const { evalScript } = require('internal/process/execution');
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
'use strict';
2+
const common = require('../common');
3+
const fixtures = require('../common/fixtures');
4+
const { Worker } = require('worker_threads');
5+
const assert = require('assert');
6+
7+
// Regression test for https://github.com/nodejs/node/issues/31777:
8+
// stdio operations coming from preload modules should count towards the
9+
// ref count of the internal communication port on the Worker side.
10+
11+
for (let i = 0; i < 10; i++) {
12+
const w = new Worker('console.log("B");', {
13+
execArgv: ['--require', fixtures.path('printA.js')],
14+
eval: true,
15+
stdout: true
16+
});
17+
w.on('exit', common.mustCall(() => {
18+
assert.strictEqual(w.stdout.read().toString(), 'A\nB\n');
19+
}));
20+
}

0 commit comments

Comments
 (0)