Skip to content

Commit d846d48

Browse files
clean up and add test
1 parent fc702a9 commit d846d48

File tree

6 files changed

+58
-53
lines changed

6 files changed

+58
-53
lines changed

integration-tests/vitest/vitest.spec.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2054,5 +2054,13 @@ versions.forEach((version) => {
20542054
})
20552055
})
20562056
})
2057+
2058+
it.skip('does not blow up when tinypool is used outside of a test', (done) => {
2059+
// childProcess = exec('node ./ci-visibility/run-workerpool.js', {
2060+
// cwd,
2061+
// env: getCiVisAgentlessConfig(receiver.port),
2062+
// stdio: 'pipe'
2063+
// })
2064+
})
20572065
})
20582066
})

packages/datadog-instrumentations/src/vitest.js

Lines changed: 20 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
1+
'use strict'
2+
13
const { addHook, channel } = require('./helpers/instrument')
24
const shimmer = require('../../datadog-shimmer')
35
const log = require('../../dd-trace/src/log')
6+
const {
7+
VITEST_WORKER_TRACE_PAYLOAD_CODE,
8+
VITEST_WORKER_LOGS_PAYLOAD_CODE
9+
} = require('../../dd-trace/src/plugins/util/test')
10+
411
// test hooks
512
const testStartCh = channel('ci:vitest:test:start')
613
const testFinishTimeCh = channel('ci:vitest:test:finish-time')
@@ -27,7 +34,8 @@ const isEarlyFlakeDetectionFaultyCh = channel('ci:vitest:is-early-flake-detectio
2734
const testManagementTestsCh = channel('ci:vitest:test-management-tests')
2835
const impactedTestsCh = channel('ci:vitest:modified-tests')
2936

30-
const workerReporterCh = channel('ci:vitest:worker-report:trace')
37+
const workerReportTraceCh = channel('ci:vitest:worker-report:trace')
38+
const workerReportLogsCh = channel('ci:vitest:worker-report:logs')
3139

3240
const taskToCtx = new WeakMap()
3341
const taskToStatuses = new WeakMap()
@@ -39,6 +47,7 @@ const modifiedTasks = new WeakSet()
3947
let isRetryReasonEfd = false
4048
let isRetryReasonAttemptToFix = false
4149
const switchedStatuses = new WeakSet()
50+
const workerProcesses = new WeakSet()
4251

4352
const BREAKPOINT_HIT_GRACE_PERIOD_MS = 400
4453

@@ -66,8 +75,6 @@ function getProvidedContext () {
6675
_ddModifiedTests: modifiedTests
6776
} = globalThis.__vitest_worker__.providedContext
6877

69-
// console.log('globalThis.__vitest_worker__', globalThis.__vitest_worker__)
70-
7178
return {
7279
isDiEnabled: _ddIsDiEnabled,
7380
isEarlyFlakeDetectionEnabled: _ddIsEarlyFlakeDetectionEnabled,
@@ -195,11 +202,6 @@ function getSortWrapper (sort, frameworkVersion) {
195202
let testManagementAttemptToFixRetries = 0
196203
let isDiEnabled = false
197204

198-
// console.log('this.ctx.vitest', this.ctx.vitest)
199-
// console.log('this.ctx.rpc', this.ctx.rpc)
200-
console.log('__vitest_worker__', global.__vitest_worker__)
201-
// console.log('this.ctx.getCoreWorkspaceProject()', this.ctx.getCoreWorkspaceProject())
202-
// console.log('this.ctx', this)
203205
try {
204206
const { err, libraryConfig } = await getChannelPromise(libraryConfigurationCh, frameworkVersion)
205207
if (!err) {
@@ -275,7 +277,6 @@ function getSortWrapper (sort, frameworkVersion) {
275277
log.warn('Could not send Dynamic Instrumentation configuration to workers.')
276278
}
277279
}
278-
debugger
279280

280281
if (isTestManagementTestsEnabled) {
281282
const { err, testManagementTests: receivedTestManagementTests } = await getChannelPromise(testManagementTestsCh)
@@ -369,32 +370,18 @@ function getCreateCliWrapper (vitestPackage, frameworkVersion) {
369370
return vitestPackage
370371
}
371372

372-
// UNUSED RIGHT NOW, but we can use it to bind the async resource to the test fn
373-
// getFn is what's used to get the test fn to run it with vitest:
374-
// https://github.com/vitest-dev/vitest/blob/0cbad1b0d0d56f1ec60f8496678d1435f8bb8977/packages/runner/src/run.ts#L315-L321
375-
let getFn = null
376-
377-
// run in workers only
378-
addHook({
379-
name: '@vitest/runner',
380-
versions: ['>=1.6.0'],
381-
file: 'dist/index.js'
382-
}, (suitePackage) => {
383-
getFn = suitePackage.getFn
384-
385-
return suitePackage
386-
})
387-
388-
const processToHandler = new WeakSet()
389-
390373
function threadHandler (thread) {
391-
if (processToHandler.has(thread.process)) {
374+
if (workerProcesses.has(thread.process)) {
392375
return
393376
}
394-
processToHandler.add(thread.process)
377+
workerProcesses.add(thread.process)
395378
thread.process.on('message', (message) => {
396379
if (message.__tinypool_worker_message__ && message.data) {
397-
workerReporterCh.publish(message.data)
380+
if (message.interprocessCode === VITEST_WORKER_TRACE_PAYLOAD_CODE) {
381+
workerReportTraceCh.publish(message.data)
382+
} else if (message.interprocessCode === VITEST_WORKER_LOGS_PAYLOAD_CODE) {
383+
workerReportLogsCh.publish(message.data)
384+
}
398385
}
399386
})
400387
}
@@ -405,12 +392,11 @@ addHook({
405392
file: 'dist/index.js'
406393
}, (TinyPool) => {
407394
shimmer.wrap(TinyPool.prototype, 'run', run => async function () {
408-
// we need to do this before and after because the threads list gets recycled
409-
// (the processes are re-created)
395+
// We have to do this before and after because the threads list gets recycled, that is, the processes are re-created
410396
this.threads.forEach(threadHandler)
411-
const res = await run.apply(this, arguments)
397+
const runResult = await run.apply(this, arguments)
412398
this.threads.forEach(threadHandler)
413-
return res
399+
return runResult
414400
})
415401

416402
return TinyPool
@@ -426,7 +412,6 @@ addHook({
426412
// `onBeforeRunTask` is run before any repetition or attempt is run
427413
// `onBeforeRunTask` is an async function
428414
shimmer.wrap(VitestTestRunner.prototype, 'onBeforeRunTask', onBeforeRunTask => function (task) {
429-
// console.log('on before run task', process.env)
430415
const testName = getTestName(task)
431416

432417
const {
@@ -512,7 +497,6 @@ addHook({
512497
// `onAfterRunTask` is run after all repetitions or attempts are run
513498
// `onAfterRunTask` is an async function
514499
shimmer.wrap(VitestTestRunner.prototype, 'onAfterRunTask', onAfterRunTask => function (task) {
515-
// console.log('task', task)
516500
const { isEarlyFlakeDetectionEnabled, isTestManagementTestsEnabled } = getProvidedContext()
517501

518502
if (isTestManagementTestsEnabled) {
@@ -913,8 +897,6 @@ addHook({
913897

914898
testSuiteFinishCh.publish({ status: testSuiteResult.state, onFinish, ...testSuiteCtx.currentStore })
915899

916-
// console.log('test usite finish!')
917-
// TODO: fix too frequent flushes
918900
await onFinishPromise
919901

920902
return startTestsResponse

packages/datadog-plugin-vitest/src/index.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,6 @@ class VitestPlugin extends CiPlugin {
404404
})
405405

406406
this.addSub('ci:vitest:worker-report:trace', (traces) => {
407-
// it has no test session or test module id so there are hanging
408407
const formattedTraces = JSON.parse(traces).map(trace => {
409408
return trace.map(span => ({
410409
...span,
@@ -418,6 +417,12 @@ class VitestPlugin extends CiPlugin {
418417
this.tracer._exporter.export(trace)
419418
})
420419
})
420+
421+
this.addSub('ci:vitest:worker-report:logs', (logsPayloads) => {
422+
JSON.parse(logsPayloads).forEach(({ testConfiguration, logMessage }) => {
423+
this.tracer._exporter.exportDiLogs(testConfiguration, logMessage)
424+
})
425+
})
421426
}
422427

423428
getTestProperties (testManagementTests, testSuite, testName) {

packages/dd-trace/src/ci-visibility/exporters/test-worker/index.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ const {
77
CUCUMBER_WORKER_TRACE_PAYLOAD_CODE,
88
MOCHA_WORKER_TRACE_PAYLOAD_CODE,
99
JEST_WORKER_LOGS_PAYLOAD_CODE,
10-
PLAYWRIGHT_WORKER_TRACE_PAYLOAD_CODE
10+
PLAYWRIGHT_WORKER_TRACE_PAYLOAD_CODE,
11+
VITEST_WORKER_TRACE_PAYLOAD_CODE,
12+
VITEST_WORKER_LOGS_PAYLOAD_CODE
1113
} = require('../../../plugins/util/test')
1214
const { getEnvironmentVariable } = require('../../../config-helper')
1315

@@ -24,6 +26,9 @@ function getInterprocessTraceCode () {
2426
if (getEnvironmentVariable('DD_PLAYWRIGHT_WORKER')) {
2527
return PLAYWRIGHT_WORKER_TRACE_PAYLOAD_CODE
2628
}
29+
if (getEnvironmentVariable('TINYPOOL_WORKER_ID')) {
30+
return VITEST_WORKER_TRACE_PAYLOAD_CODE
31+
}
2732
return null
2833
}
2934

@@ -39,6 +44,9 @@ function getInterprocessLogsCode () {
3944
if (getEnvironmentVariable('JEST_WORKER_ID')) {
4045
return JEST_WORKER_LOGS_PAYLOAD_CODE
4146
}
47+
if (getEnvironmentVariable('TINYPOOL_WORKER_ID')) {
48+
return VITEST_WORKER_LOGS_PAYLOAD_CODE
49+
}
4250
return null
4351
}
4452

packages/dd-trace/src/ci-visibility/exporters/test-worker/writer.js

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
const { JSONEncoder } = require('../../encode/json-encoder')
33
const { getEnvironmentVariable } = require('../../../config-helper')
44

5-
const isVitestWorker = !!getEnvironmentVariable('TINYPOOL_WORKER_ID')
6-
75
class Writer {
86
constructor (interprocessCode) {
97
this._encoder = new JSONEncoder()
@@ -37,17 +35,15 @@ class Writer {
3735
// See cucumber code:
3836
// https://github.com/cucumber/cucumber-js/blob/5ce371870b677fe3d1a14915dc535688946f734c/src/runtime/parallel/run_worker.ts#L13
3937
if (process.send) { // it only works if process.send is available
40-
if (isVitestWorker) {
41-
// in vitest we have to trick the main process into thinking these are messages from
42-
// tinypool so they are not rejected
43-
process.send({ __tinypool_worker_message__: true, data }, () => {
44-
onDone()
45-
})
46-
} else {
47-
process.send([this._interprocessCode, data], () => {
48-
onDone()
49-
})
50-
}
38+
const isVitestWorker = !!getEnvironmentVariable('TINYPOOL_WORKER_ID')
39+
40+
const payload = isVitestWorker
41+
? { __tinypool_worker_message__: true, interprocessCode: this._interprocessCode, data }
42+
: [this._interprocessCode, data]
43+
44+
process.send(payload, () => {
45+
onDone()
46+
})
5147
} else {
5248
onDone()
5349
}

packages/dd-trace/src/plugins/util/test.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,10 @@ const MOCHA_WORKER_TRACE_PAYLOAD_CODE = 80
116116
// playwright worker variables
117117
const PLAYWRIGHT_WORKER_TRACE_PAYLOAD_CODE = 90
118118

119+
// vitest worker variables
120+
const VITEST_WORKER_TRACE_PAYLOAD_CODE = 100
121+
const VITEST_WORKER_LOGS_PAYLOAD_CODE = 102
122+
119123
// Early flake detection util strings
120124
const EFD_STRING = "Retried by Datadog's Early Flake Detection"
121125
const EFD_TEST_NAME_REGEX = new RegExp(EFD_STRING + String.raw` \(#\d+\): `, 'g')
@@ -211,6 +215,8 @@ module.exports = {
211215
CUCUMBER_WORKER_TRACE_PAYLOAD_CODE,
212216
MOCHA_WORKER_TRACE_PAYLOAD_CODE,
213217
PLAYWRIGHT_WORKER_TRACE_PAYLOAD_CODE,
218+
VITEST_WORKER_TRACE_PAYLOAD_CODE,
219+
VITEST_WORKER_LOGS_PAYLOAD_CODE,
214220
TEST_SOURCE_START,
215221
TEST_SKIPPED_BY_ITR,
216222
TEST_IS_NEW,

0 commit comments

Comments
 (0)