Skip to content

Commit

Permalink
fix(builtin): avoid unnecessary chdir to prevent worker threads from …
Browse files Browse the repository at this point in the history
…failing
  • Loading branch information
kormide authored and alexeagle committed Feb 15, 2022
1 parent 71f4b95 commit 550673f
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 1 deletion.
10 changes: 9 additions & 1 deletion internal/node/node.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,15 @@ fi
fail("""nodejs_binary/nodejs_test only support chdir inside the current package
but %s is not a subfolder of %s""" % (ctx.attr.chdir, ctx.label.package))
chdir_script = ctx.actions.declare_file(_join(relative_dir, "__chdir.js__"))
ctx.actions.write(chdir_script, "process.chdir(__dirname)")
ctx.actions.write(chdir_script, """
/* This script is preloaded with --require, meaning it will run for the main node process
as well as each worker thread that gets spawned. Calling process.chdir() in a worker
is an error in node, so ensure it's only called once for the main process.
*/
if (process.cwd() !== __dirname) {
process.chdir(__dirname);
}
""")
runfiles.append(chdir_script)

# this join is effectively a $(rootdir) expansion
Expand Down
7 changes: 7 additions & 0 deletions internal/node/test/chdir/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,10 @@ nodejs_test(
data = ["build/app.js"],
entry_point = "test.js",
)

nodejs_test(
name = "test_multithread",
chdir = package_name(),
data = ["worker.js"],
entry_point = "multithread.js",
)
18 changes: 18 additions & 0 deletions internal/node/test/chdir/multithread.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const { Worker } = require("worker_threads")

function runWorker(message) {
return new Promise((resolve, reject) => {
const worker = new Worker("./worker.js", {workerData: {message}});
worker.on("message", resolve);
worker.on("error", reject);
worker.on("exit", code => {
if (0 !== code) {
reject(new Error(`Worker exited with code ${code}`));
}
});
})
}

(async () => {
await runWorker("foobar");
})();
4 changes: 4 additions & 0 deletions internal/node/test/chdir/worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const {parentPort, workerData} = require("worker_threads");

console.log(workerData.message);
parentPort.postMessage(true);

0 comments on commit 550673f

Please sign in to comment.