Skip to content

Commit

Permalink
module: prevent main thread exiting before esm worker ends
Browse files Browse the repository at this point in the history
PR-URL: #56183
Reviewed-By: Matteo Collina <[email protected]>
Reviewed-By: Antoine du Hamel <[email protected]>
Reviewed-By: Jacob Smith <[email protected]>
  • Loading branch information
islandryu authored and ruyadorno committed Dec 20, 2024
1 parent ad4275b commit f99075a
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/internal/modules/esm/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,6 @@ async function customizedModuleWorker(lock, syncCommPort, errorHandler) {
(port ?? syncCommPort).postMessage(wrapMessage('error', exception));
}

AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1);
AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION);
if (shouldRemoveGlobalErrorHandler) {
process.off('uncaughtException', errorHandler);
}
Expand All @@ -225,6 +223,10 @@ async function customizedModuleWorker(lock, syncCommPort, errorHandler) {
// We keep checking for new messages to not miss any.
clearImmediate(immediate);
immediate = setImmediate(checkForMessages).unref();
// To prevent the main thread from terminating before this function completes after unlocking,
// the following process is executed at the end of the function.
AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1);
AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION);
}
}

Expand Down
16 changes: 16 additions & 0 deletions test/es-module/test-esm-loader-spawn-promisified.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -285,4 +285,20 @@ describe('Loader hooks parsing modules', { concurrency: !process.env.TEST_PARALL
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
});

it('throw maximum call stack error on the loader', async () => {
const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [
'--no-warnings',
'--experimental-loader',
fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'),
'--input-type=module',
'--eval',
'await import("esmHook/maximumCallStack.mjs")',
]);

assert(stderr.includes('Maximum call stack size exceeded'));
assert.strictEqual(stdout, '');
assert.strictEqual(code, 1);
assert.strictEqual(signal, null);
});
});
7 changes: 7 additions & 0 deletions test/fixtures/es-module-loaders/hooks-custom.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -105,5 +105,12 @@ export function load(url, context, next) {
};
}

if (url.endsWith('esmHook/maximumCallStack.mjs')) {
function recurse() {
recurse();
}
recurse();
}

return next(url);
}

0 comments on commit f99075a

Please sign in to comment.