forked from vitest-dev/vitest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.ts
243 lines (211 loc) · 7.4 KB
/
pool.ts
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import { MessageChannel } from 'node:worker_threads'
import _url from 'node:url'
import { cpus } from 'node:os'
import { resolve } from 'pathe'
import type { Options as TinypoolOptions } from 'tinypool'
import { Tinypool } from 'tinypool'
import { createBirpc } from 'birpc'
import type { RawSourceMap } from 'vite-node'
import type { ResolvedConfig, WorkerContext, WorkerRPC, WorkerTestEnvironment } from '../types'
import { distDir, rootDir } from '../constants'
import { AggregateError, getEnvironmentTransformMode, groupBy } from '../utils'
import { envsOrder, groupFilesByEnv } from '../utils/test-helpers'
import type { Vitest } from './core'
export type RunWithFiles = (files: string[], invalidates?: string[]) => Promise<void>
export interface WorkerPool {
runTests: RunWithFiles
close: () => Promise<void>
}
const workerPath = _url.pathToFileURL(resolve(distDir, './worker.js')).href
const loaderPath = _url.pathToFileURL(resolve(distDir, './loader.js')).href
const suppressLoaderWarningsPath = resolve(rootDir, './suppress-warnings.cjs')
export function createPool(ctx: Vitest): WorkerPool {
const threadsCount = ctx.config.watch
? Math.max(Math.floor(cpus().length / 2), 1)
: Math.max(cpus().length - 1, 1)
const maxThreads = ctx.config.maxThreads ?? threadsCount
const minThreads = ctx.config.minThreads ?? threadsCount
const conditions = ctx.server.config.resolve.conditions?.flatMap(c => ['--conditions', c]) || []
// Instead of passing whole process.execArgv to the workers, pick allowed options.
// Some options may crash worker, e.g. --prof, --title. nodejs/node#41103
const execArgv = process.execArgv.filter(execArg =>
execArg.startsWith('--cpu-prof') || execArg.startsWith('--heap-prof'),
)
const options: TinypoolOptions = {
filename: workerPath,
// TODO: investigate further
// It seems atomics introduced V8 Fatal Error https://github.com/vitest-dev/vitest/issues/1191
useAtomics: ctx.config.useAtomics ?? false,
maxThreads,
minThreads,
execArgv: ctx.config.deps.registerNodeLoader
? [
...execArgv,
'--require',
suppressLoaderWarningsPath,
'--experimental-loader',
loaderPath,
...conditions,
]
: [
...execArgv,
...conditions,
],
}
if (ctx.config.isolate) {
options.isolateWorkers = true
options.concurrentTasksPerWorker = 1
}
if (!ctx.config.threads) {
options.concurrentTasksPerWorker = 1
options.maxThreads = 1
options.minThreads = 1
}
options.env = {
TEST: 'true',
VITEST: 'true',
NODE_ENV: ctx.config.mode || 'test',
VITEST_MODE: ctx.config.watch ? 'WATCH' : 'RUN',
...process.env,
...ctx.config.env,
}
const pool = new Tinypool(options)
const runWithFiles = (name: string): RunWithFiles => {
let id = 0
async function runFiles(config: ResolvedConfig, files: string[], environment: WorkerTestEnvironment, invalidates: string[] = []) {
ctx.state.clearFiles(files)
const { workerPort, port } = createChannel(ctx)
const workerId = ++id
const data: WorkerContext = {
port: workerPort,
config,
files,
invalidates,
environment,
workerId,
}
try {
await pool.run(data, { transferList: [workerPort], name })
}
finally {
port.close()
workerPort.close()
}
}
const Sequencer = ctx.config.sequence.sequencer
const sequencer = new Sequencer(ctx)
return async (files, invalidates) => {
const config = ctx.getSerializableConfig()
if (config.shard)
files = await sequencer.shard(files)
files = await sequencer.sort(files)
const filesByEnv = await groupFilesByEnv(files, config)
const envs = envsOrder.concat(
Object.keys(filesByEnv).filter(env => !envsOrder.includes(env)),
)
if (!ctx.config.threads) {
// always run environments isolated between each other
for (const env of envs) {
const files = filesByEnv[env]
if (!files?.length)
continue
const filesByOptions = groupBy(files, ({ environment }) => JSON.stringify(environment.options))
for (const option in filesByOptions) {
const files = filesByOptions[option]
if (files?.length) {
const filenames = files.map(f => f.file)
await runFiles(config, filenames, files[0].environment, invalidates)
}
}
}
}
else {
const promises = Object.values(filesByEnv).flat()
const results = await Promise.allSettled(promises
.map(({ file, environment }) => runFiles(config, [file], environment, invalidates)))
const errors = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected').map(r => r.reason)
if (errors.length > 0)
throw new AggregateError(errors, 'Errors occurred while running tests. For more information, see serialized error.')
}
}
}
return {
runTests: runWithFiles('run'),
close: async () => {
// node before 16.17 has a bug that causes FATAL ERROR because of the race condition
const nodeVersion = Number(process.version.match(/v(\d+)\.(\d+)/)?.[0].slice(1))
if (nodeVersion >= 16.17)
await pool.destroy()
},
}
}
function createChannel(ctx: Vitest) {
const channel = new MessageChannel()
const port = channel.port2
const workerPort = channel.port1
createBirpc<{}, WorkerRPC>(
{
async onWorkerExit(error, code) {
await ctx.logger.printError(error, false, 'Unexpected Exit')
process.exit(code || 1)
},
snapshotSaved(snapshot) {
ctx.snapshot.add(snapshot)
},
resolveSnapshotPath(testPath: string) {
return ctx.snapshot.resolvePath(testPath)
},
async getSourceMap(id, force) {
if (force) {
const mod = ctx.server.moduleGraph.getModuleById(id)
if (mod)
ctx.server.moduleGraph.invalidateModule(mod)
}
const r = await ctx.vitenode.transformRequest(id)
return r?.map as RawSourceMap | undefined
},
fetch(id, environment) {
const transformMode = getEnvironmentTransformMode(ctx.config, environment)
return ctx.vitenode.fetchModule(id, transformMode)
},
resolveId(id, importer, environment) {
const transformMode = getEnvironmentTransformMode(ctx.config, environment)
return ctx.vitenode.resolveId(id, importer, transformMode)
},
onPathsCollected(paths) {
ctx.state.collectPaths(paths)
ctx.report('onPathsCollected', paths)
},
onCollected(files) {
ctx.state.collectFiles(files)
ctx.report('onCollected', files)
},
onAfterSuiteRun(meta) {
ctx.coverageProvider?.onAfterSuiteRun(meta)
},
onTaskUpdate(packs) {
ctx.state.updateTasks(packs)
ctx.report('onTaskUpdate', packs)
},
onUserConsoleLog(log) {
ctx.state.updateUserLog(log)
ctx.report('onUserConsoleLog', log)
},
onUnhandledError(err, type) {
ctx.state.catchError(err, type)
},
onFinished(files) {
ctx.report('onFinished', files, ctx.state.getUnhandledErrors())
},
},
{
post(v) {
port.postMessage(v)
},
on(fn) {
port.on('message', fn)
},
},
)
return { workerPort, port }
}