Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(vitest): dispose vmForks listeners to avoid memory leak #6448

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/vitest/src/runtime/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@ import type { ContextRPC, WorkerGlobalState } from '../types/worker'
import { setupInspect } from './inspector'
import { createRuntimeRpc, rpcDone } from './rpc'
import type { VitestWorker } from './workers/types'
import { disposeInternalListeners } from './workers/utils'

if (isChildProcess()) {
setProcessTitle(`vitest ${poolId}`)
}

// this is what every pool executes when running tests
async function execute(mehtod: 'run' | 'collect', ctx: ContextRPC) {
disposeInternalListeners()

const prepareStart = performance.now()

const inspectorCleanup = setupInspect(ctx)
Expand Down
18 changes: 16 additions & 2 deletions packages/vitest/src/runtime/workers/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const REGEXP_WRAP_PREFIX = '$$vitest:'
// Store global APIs in case process is overwritten by tests
const processSend = process.send?.bind(process)
const processOn = process.on?.bind(process)
const processOff = process.off?.bind(process)
const dispose: (() => void)[] = []

export function createThreadsRpcOptions({
port,
Expand All @@ -23,6 +25,16 @@ export function createThreadsRpcOptions({
}
}

export function disposeInternalListeners() {
for (const fn of dispose) {
try {
fn()
}
catch {}
}
dispose.length = 0
}

export function createForksRpcOptions(
nodeV8: typeof import('v8'),
): WorkerRpcOptions {
Expand All @@ -33,14 +45,16 @@ export function createForksRpcOptions(
processSend!(v)
},
on(fn) {
processOn('message', (message: any, ...extras: any) => {
const handler = (message: any, ...extras: any) => {
// Do not react on Tinypool's internal messaging
if ((message as TinypoolWorkerMessage)?.__tinypool_worker_message__) {
return
}

return fn(message, ...extras)
})
}
processOn('message', handler)
dispose.push(() => processOff('message', handler))
},
}
}
Expand Down
Loading