Skip to content

Commit 4a1947e

Browse files
authored
Ensure workers are cleaned up always (#71564)
This ensures we properly clean up workers even if an error is thrown before our normal `.end()` call is done. This can be verified currently by building `pnpm next test/e2e/app-dir/dynamic-io` which should encounter an error and fail but the workers were previously being kept and using lots of CPU, now they are properly cleaned up.
1 parent e406def commit 4a1947e

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

packages/next/src/lib/verifyAndLint.ts

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,14 @@ export async function verifyAndLint(
1515
enableWorkerThreads: boolean | undefined,
1616
telemetry: Telemetry
1717
): Promise<void> {
18+
let lintWorkers:
19+
| (Worker & {
20+
runLintCheck: typeof import('./eslint/runLintCheck').runLintCheck
21+
})
22+
| undefined
23+
1824
try {
19-
const lintWorkers = new Worker(require.resolve('./eslint/runLintCheck'), {
25+
lintWorkers = new Worker(require.resolve('./eslint/runLintCheck'), {
2026
numWorkers: 1,
2127
enableWorkerThreads,
2228
maxRetries: 0,
@@ -37,7 +43,7 @@ export async function verifyAndLint(
3743
[]
3844
)
3945

40-
const lintResults = await lintWorkers.runLintCheck(dir, lintDirs, {
46+
const lintResults = await lintWorkers?.runLintCheck(dir, lintDirs, {
4147
lintDuringBuild: true,
4248
eslintOptions: {
4349
cacheLocation,
@@ -63,8 +69,6 @@ export async function verifyAndLint(
6369
if (lintOutput) {
6470
console.log(lintOutput)
6571
}
66-
67-
lintWorkers.end()
6872
} catch (err) {
6973
if (isError(err)) {
7074
if (err.type === 'CompileError' || err instanceof CompileError) {
@@ -77,5 +81,9 @@ export async function verifyAndLint(
7781
}
7882
}
7983
throw err
84+
} finally {
85+
try {
86+
lintWorkers?.end()
87+
} catch {}
8088
}
8189
}

packages/next/src/lib/worker.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,11 @@ export class Worker {
3838

3939
this._worker = undefined
4040

41+
// ensure we end workers if they weren't before exit
42+
process.on('exit', () => {
43+
this.close()
44+
})
45+
4146
const createWorker = () => {
4247
// Get the node options without inspect and also remove the
4348
// --max-old-space-size flag as it can cause memory issues.

0 commit comments

Comments
 (0)