Skip to content

Commit

Permalink
fix(vitest): dispose vmForks listeners to avoid memory leak (#6448)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va authored Sep 3, 2024
1 parent 0499a31 commit 2673c3b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
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

0 comments on commit 2673c3b

Please sign in to comment.