forked from vitest-dev/vitest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit-forks.ts
More file actions
66 lines (57 loc) · 2.02 KB
/
init-forks.ts
File metadata and controls
66 lines (57 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import type { WorkerGlobalState, WorkerSetupContext } from '../../types/worker'
import type { Traces } from '../../utils/traces'
import { init } from './init'
if (!process.send) {
throw new Error('Expected worker to be run in node:child_process')
}
// Store globals in case tests overwrite them
const processExit = process.exit.bind(process)
const processSend = process.send.bind(process)
const processOn = process.on.bind(process)
const processOff = process.off.bind(process)
const processRemoveAllListeners = process.removeAllListeners.bind(process)
const isProfiling = process.execArgv.some(
execArg =>
execArg.startsWith('--prof')
|| execArg.startsWith('--cpu-prof')
|| execArg.startsWith('--heap-prof')
|| execArg.startsWith('--diagnostic-dir'),
)
// Work-around for nodejs/node#55094
if (isProfiling) {
processOn('SIGTERM', () => processExit())
}
processOn('error', onError)
export default function workerInit(options: {
runTests: (method: 'run' | 'collect', state: WorkerGlobalState, traces: Traces) => Promise<void>
setup?: (context: WorkerSetupContext) => void | Promise<() => Promise<unknown>>
}): void {
const { runTests } = options
init({
post: v => processSend(v),
on: cb => processOn('message', cb),
off: cb => processOff('message', cb),
teardown: () => {
processRemoveAllListeners('message')
processOff('error', onError)
},
runTests: (state, traces) => executeTests('run', state, traces),
collectTests: (state, traces) => executeTests('collect', state, traces),
setup: options.setup,
})
async function executeTests(method: 'run' | 'collect', state: WorkerGlobalState, traces: Traces) {
try {
await runTests(method, state, traces)
}
finally {
process.exit = processExit
}
}
}
// Prevent leaving worker in loops where it tries to send message to closed main
// thread, errors, and tries to send the error.
function onError(error: any) {
if (error?.code === 'ERR_IPC_CHANNEL_CLOSED' || error?.code === 'EPIPE') {
processExit(1)
}
}