-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathindex.js
More file actions
1376 lines (1242 loc) · 46.6 KB
/
Copy pathindex.js
File metadata and controls
1376 lines (1242 loc) · 46.6 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
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict'
const assert = require('assert')
const childProcess = require('child_process')
const { exec, execSync, fork, spawn } = childProcess
const { existsSync, readdirSync, readFileSync, unlinkSync, writeFileSync } = require('fs')
const fs = require('fs/promises')
const http = require('http')
const { builtinModules } = require('module')
const os = require('os')
const path = require('path')
const { inspect, promisify } = require('util')
const execAsync = promisify(exec)
const id = require('../../packages/dd-trace/src/id')
const { getCappedRange } = require('../../packages/dd-trace/test/plugins/versions')
const {
FLUSH_SIGNAL_KEY,
isCoverageActive,
resolveCoverageRoot,
} = require('../coverage/runtime')
const { FakeCiVisIntake } = require('../ci-visibility-intake')
const FakeAgent = require('./fake-agent')
const { BUN, withBun } = require('./bun')
const sandboxRoot = path.join(os.tmpdir(), id().toString())
const hookFile = 'dd-trace/loader-hook.mjs'
const { DEBUG } = process.env
// This is set by the setShouldKill function
let shouldKill
// Symbol constants for dynamic value matching in assertObjectContains
const ANY_STRING = Symbol('test.ANY_STRING')
const ANY_NUMBER = Symbol('test.ANY_NUMBER')
const ANY_VALUE = Symbol('test.ANY_VALUE')
const defaultStopProcTimeoutMs = 2_000
/**
* @param {string} filename
* @param {string} cwd
* @param {string|((out: Promise<string>) => void)} expectedOut
* @param {string} expectedSource
*/
async function runAndCheckOutput (filename, cwd, expectedOut, expectedSource) {
const proc = spawn(process.execPath, [filename], { cwd, stdio: 'pipe' })
assert.notStrictEqual(proc.pid, undefined, 'Process PID is not available')
const pid = proc.pid
let out = await new Promise((resolve, reject) => {
proc.once('error', reject)
const out = []
proc.stdout.on('data', data => {
out.push(data)
})
proc.stderr.pipe(process.stdout)
proc.once('exit', () => resolve(Buffer.concat(out).toString('utf8')))
if (shouldKill) {
setTimeout(() => {
if (proc.exitCode === null) proc.kill()
}, 1000) // TODO this introduces flakiness. find a better way to end the process.
}
})
if (typeof expectedOut === 'function') {
expectedOut(out)
} else {
if (process.env.DD_TRACE_DEBUG) {
// Debug adds this, which we don't care about in these tests
out = out.replace('Flushing 0 metrics via HTTP\n', '')
}
assert.match(out, new RegExp(expectedOut), `output "${out}" does not contain expected output "${expectedOut}"`)
}
if (expectedSource) {
assert.match(out, new RegExp(`instrumentation source: ${expectedSource}`),
`Expected the process to output "${expectedSource}", but logs only contain: "${out}"`)
}
return pid
}
// This is set by the useSandbox function
let sandbox
/**
* This _must_ be used with the useSandbox function
*
* @param {string} filename
* @param {string|((out: Promise<string>) => void)} expectedOut
* @param {string[]} expectedTelemetryPoints
* @param {string} expectedSource
*/
async function runAndCheckWithTelemetry (filename, expectedOut, expectedTelemetryPoints, expectedSource) {
const cwd = sandbox.folder
const cleanup = telemetryForwarder(expectedTelemetryPoints.length > 0)
const pid = await runAndCheckOutput(filename, cwd, expectedOut, expectedSource)
const msgs = await cleanup()
if (expectedTelemetryPoints.length === 0) {
// assert no telemetry sent
assert.strictEqual(msgs.length, 0, `Expected no telemetry, but got:\n${
msgs.map(msg => JSON.stringify(msg[1].points)).join('\n')
}`)
} else {
assertTelemetryPoints(pid, msgs, expectedTelemetryPoints)
}
}
/**
* @param {number} pid
* @param {[string, { metadata: Record<string, unknown>, points: { name: string, tags: string[] }[] }][]} msgs
* @param {string[]} expectedTelemetryPoints
*/
function assertTelemetryPoints (pid, msgs, expectedTelemetryPoints) {
let points = []
for (const [telemetryType, data] of msgs) {
assert.strictEqual(telemetryType, 'library_entrypoint')
assertMetadata(data.metadata, pid)
points = points.concat(data.points)
}
const expectedPoints = getPoints(...expectedTelemetryPoints)
// Sort since data can come in in any order.
assert.deepStrictEqual(points.sort(pointsSorter), expectedPoints.sort(pointsSorter))
function pointsSorter (a, b) {
a = a.name + '\t' + a.tags.join(',')
b = b.name + '\t' + b.tags.join(',')
return a === b ? 0 : a < b ? -1 : 1
}
/**
* @param {...string} args
* @returns {{ name: string, tags: string[] }[]}
*/
function getPoints (...args) {
const expectedPoints = []
for (let i = 0; i < args.length; i += 2) {
expectedPoints.push({
name: 'library_entrypoint.' + args[i],
tags: args[i + 1].split(',').filter(Boolean),
})
}
return expectedPoints
}
/**
* @param {Record<string, unknown>} actualMetadata
* @param {number} pid
*/
function assertMetadata (actualMetadata, pid) {
const expectedBasicMetadata = {
language_name: 'nodejs',
language_version: process.versions.node,
runtime_name: 'nodejs',
runtime_version: process.versions.node,
tracer_version: require('../../package.json').version,
pid,
}
// Validate basic metadata
for (const key of Object.keys(expectedBasicMetadata)) {
assert.strictEqual(actualMetadata[key], expectedBasicMetadata[key])
}
// Validate result metadata is present and has valid values
assert.strictEqual(typeof actualMetadata.result, 'string')
assert.strictEqual(typeof actualMetadata.result_class, 'string')
assert.strictEqual(typeof actualMetadata.result_reason, 'string')
assert(actualMetadata.result, 'result field should be present')
assert(actualMetadata.result_class, 'result_class field should be present')
assert(actualMetadata.result_reason, 'result_reason field should be present')
// Check that result metadata has expected values for telemetry scenarios
const validResults = ['success', 'abort', 'error', 'unknown']
const validResultClasses = ['success', 'incompatible_runtime', 'incompatible_library', 'internal_error', 'unknown']
assert(validResults.includes(actualMetadata.result), `Invalid result: ${actualMetadata.result}`)
assert(validResultClasses.includes(actualMetadata.result_class),
`Invalid result_class: ${actualMetadata.result_class}`)
}
}
/**
* @typedef {childProcess.ChildProcess & {
* url: string,
* stdout: import('node:stream').Readable,
* stderr: import('node:stream').Readable
* }} SpawnedProcess
*/
/**
* Spawns a Node.js script in a child process and returns a promise that resolves when the process is ready.
*
* This function expects the spawned process to stay alive (e.g., a server). If the process exits
* (even with code 0), the promise will reject with an error.
*
* For processes that are expected to run and exit cleanly, use `spawnProcAndExpectExit` instead.
*
* @param {string|URL} filename - The filename of the Node.js script to spawn in a child process.
* @param {childProcess.ForkOptions} [options] - The options to pass to the child process.
* @param {(data: Buffer) => void} [stdioHandler] - A function that's called with one data argument to handle the
* standard output of the child process. If not provided, the output will be logged to the console.
* @param {(data: Buffer) => void} [stderrHandler] - A function that's called with one data argument to handle the
* standard error of the child process. If not provided, the error will be logged to the console.
* @returns {Promise<SpawnedProcess>} A promise that resolves with a SpawnedProcess when the process is ready.
* The returned `SpawnedProcess` will have a `url` property that can be accessed to get the server URL.
* Note: Accessing `url` before the spawned process sends its port message will throw an error.
*/
function spawnProc (filename, options = {}, stdioHandler, stderrHandler) {
const proc = spawnProcImpl(filename, options, stdioHandler, stderrHandler)
let urlValue
Object.defineProperty(proc, 'url', {
get () {
if (urlValue === undefined) {
throw new Error('Process URL is not available yet. The spawned process has not sent a port message.')
}
return urlValue
},
set (value) {
urlValue = value
},
enumerable: true,
configurable: true,
})
return new Promise((resolve, reject) => {
proc
.on('message', (/** @type {{ port?: unknown }} */ { port }) => {
if (typeof port !== 'number' && typeof port !== 'string') {
return reject(new Error(`${filename} sent invalid port: ${port}. Expected a number or string.`))
}
proc.url = `http://localhost:${port}`
resolve(proc)
})
.once('error', reject)
.once('exit', code => {
reject(new Error(`Process exited with status code ${code}.`))
})
})
}
/**
* Spawns a Node.js script in a child process that is expected to run and exit cleanly.
*
* This function expects the process to complete and exit with code 0, in which case the promise resolves
* with `undefined`. Use this for short-lived processes like validation scripts or tests that run to completion.
*
* For long-running processes (like servers) that should not exit, use `spawnProc` instead.
*
* @param {string|URL} filename - The filename of the Node.js script to spawn in a child process.
* @param {childProcess.ForkOptions} [options] - The options to pass to the child process.
* @param {(data: Buffer) => void} [stdioHandler] - A function that's called with one data argument to handle the
* standard output of the child process. If not provided, the output will be logged to the console.
* @param {(data: Buffer) => void} [stderrHandler] - A function that's called with one data argument to handle the
* standard error of the child process. If not provided, the error will be logged to the console.
* @returns {Promise<void>} A promise that resolves when the process exits with code 0.
*/
function spawnProcAndExpectExit (filename, options = {}, stdioHandler, stderrHandler) {
const proc = spawnProcImpl(filename, options, stdioHandler, stderrHandler)
return new Promise((resolve, reject) => {
proc
.once('error', reject)
.once('exit', code => {
if (code !== 0) {
return reject(new Error(`Process exited with status code ${code}.`))
}
resolve()
})
})
}
/**
* Stop a process and wait for it to fully exit.
*
* Sends `signal` first, waits up to `timeoutMs`, and escalates to `SIGKILL` if needed.
*
* @param {childProcess.ChildProcess|undefined} proc - Process to stop.
* @param {object} [options] - Stop options.
* @param {keyof import('node:os').SignalConstants} [options.signal] - Signal to send before escalating.
* Defaults to `SIGTERM`.
* @param {number} [options.timeoutMs] - Max wait per signal in milliseconds. Defaults to the stop-proc timeout.
* @returns {Promise<void>}
*/
async function stopProc (proc, options = {}) {
if (!proc) return
if (proc.exitCode !== null || proc.signalCode !== null) return
const signal = options.signal ?? 'SIGTERM'
const timeoutMs = options.timeoutMs ?? defaultStopProcTimeoutMs
// Windows SIGTERM is forceful and skips the child's signal-flush hook, so ask the bootstrap to
// flush its V8 coverage via the IPC sentinel first and give it a chance to exit cleanly. Any
// preserved foreign-directory profiles are folded into the collector on the ensuing `exit`.
if (process.platform === 'win32' && isCoverageActive() && proc.connected) {
proc.send({ [FLUSH_SIGNAL_KEY]: true }, () => {})
if (await waitForProcExit(proc, timeoutMs)) return
}
proc.kill(signal)
const exitedAfterInitialSignal = await waitForProcExit(proc, timeoutMs)
if (exitedAfterInitialSignal) return
proc.kill('SIGKILL')
const exitedAfterSigkill = await waitForProcExit(proc, timeoutMs)
if (!exitedAfterSigkill) {
throw new Error(`Process ${proc.pid} did not exit after SIGKILL`)
}
}
/**
* Tear down a Test Optimization integration fixture between tests.
*
* Awaits each step so the next test starts from a clean slate — letting the
* previous child outlive `afterEach` leaks sockets and file descriptors that
* the next Cypress / Playwright run then races against.
*
* @param {object} env
* @param {childProcess.ChildProcess} [env.childProcess] - Test child to stop.
* @param {import('http').Server} [env.webAppServer] - Web fixture server to close.
* @param {FakeAgent} [env.receiver] - Fake agent / intake to stop.
* @returns {Promise<void>}
*/
async function stopCiVisTestEnv ({ childProcess, webAppServer, receiver }) {
await stopProc(childProcess)
if (webAppServer?.listening) {
await /** @type {Promise<void>} */ (new Promise((resolve) => webAppServer.close(() => resolve())))
}
await receiver?.stop()
}
/**
* Wait for a process to exit for up to `timeoutMs`.
*
* @param {childProcess.ChildProcess} proc - Process to wait for.
* @param {number} timeoutMs - Max time to wait in milliseconds.
* @returns {Promise<boolean>} `true` if the process exited before timeout.
*/
function waitForProcExit (proc, timeoutMs) {
if (proc.exitCode !== null || proc.signalCode !== null) {
return Promise.resolve(true)
}
return new Promise((resolve) => {
const timeout = setTimeout(() => {
proc.removeListener('exit', onExit)
resolve(false)
}, timeoutMs)
proc.once('exit', onExit)
function onExit () {
clearTimeout(timeout)
resolve(true)
}
})
}
/**
* Internal implementation for spawnProc and spawnProcAndAllowExit.
*
* @param {string|URL} filename
* @param {childProcess.ForkOptions} options
* @param {(data: Buffer) => void} [stdioHandler]
* @param {(data: Buffer) => void} [stderrHandler]
* @returns {SpawnedProcess}
*/
function spawnProcImpl (filename, options, stdioHandler, stderrHandler) {
// When stdio is 'pipe', stdout/stderr are guaranteed non-null.
const proc = /** @type {SpawnedProcess} */ (fork(filename, {
...options,
stdio: 'pipe',
}))
proc.stdout.on('data', data => {
if (stdioHandler) {
stdioHandler(data)
}
// eslint-disable-next-line no-console
if (!options.silent) console.log(data.toString())
})
proc.stderr.on('data', data => {
if (stderrHandler) {
stderrHandler(data)
}
// eslint-disable-next-line no-console
if (!options.silent) console.error(data.toString())
})
return proc
}
function log (...args) {
DEBUG === 'true' && console.log(...args) // eslint-disable-line no-console
}
function error (...args) {
DEBUG === 'true' && console.error(...args) // eslint-disable-line no-console
}
function execHelper (command, options) {
try {
log('Exec START: ', command)
execSync(command, options)
log('Exec SUCCESS: ', command)
} catch (execError) {
error('Exec ERROR: ', command, execError)
if (command.startsWith(BUN)) {
try {
log('Exec RETRY BACKOFF: 60 seconds')
execSync('sleep 60')
log('Exec RETRY START: ', command)
execSync(command, options)
log('Exec RETRY SUCCESS: ', command)
} catch (retryError) {
error('Exec RETRY ERROR', command, retryError)
throw retryError
}
} else {
throw execError
}
}
}
/**
* Async sibling of {@link execHelper}. Runs in parallel with other awaited operations and
* preserves the bun-only 60s retry semantics.
*
* @param {string} command - Command to run.
* @param {import('child_process').ExecOptions} [options] - Exec options.
* @returns {Promise<void>}
*/
async function execHelperAsync (command, options) {
try {
log('Exec START: ', command)
await execAsync(command, options)
log('Exec SUCCESS: ', command)
return
} catch (execError) {
error('Exec ERROR: ', command, execError)
if (!command.startsWith(BUN)) throw execError
}
log('Exec RETRY BACKOFF: 60 seconds')
await new Promise(resolve => setTimeout(resolve, 60_000))
try {
log('Exec RETRY START: ', command)
await execAsync(command, options)
log('Exec RETRY SUCCESS: ', command)
} catch (retryError) {
error('Exec RETRY ERROR', command, retryError)
throw retryError
}
}
/**
* @param {string} tarballPath
* @param {typeof process.env} env
* @returns {Promise<void>}
*/
async function packTarball (tarballPath, env) {
// Native V8 coverage reads execution straight from the installed (uninstrumented) sources, so
// there is no pre-instrumentation step: the tarball is always a plain pack.
await execHelperAsync(`${BUN} pm pack --ignore-scripts --quiet --gzip-level 0 --filename ${tarballPath}`, { env })
log('Tarball packed successfully:', tarballPath)
}
/**
* Copy each integration-tests path into the sandbox folder concurrently.
*
* @param {string[]} integrationTestsPaths - Source paths to copy from.
* @param {string} folder - Destination sandbox folder.
* @returns {Promise<void>}
*/
async function copyIntegrationTests (integrationTestsPaths, folder) {
await Promise.all(integrationTestsPaths.map(p => process.platform === 'win32'
? execHelperAsync(`Copy-Item -Recurse -Path "${p}" -Destination "${folder}"`, { shell: 'powershell.exe' })
: execHelperAsync(`cp -R ${p} ${folder}`)
))
}
/**
* Pack the tarball with file locking to coordinate between parallel workers.
* Only one worker will pack the tarball, others will wait for it to be ready.
*
* @param {string} tarballPath - The path where the tarball should be created
* @param {typeof process.env} env - The environment to use for the pack command
* @returns {Promise<void>}
*/
async function packTarballWithLock (tarballPath, env) {
if (existsSync(tarballPath)) {
log('Tarball already exists:', tarballPath)
return
}
const lockFile = `${tarballPath}.lock`
let lockFd
try {
// Try to acquire the lock by creating the lock file exclusively
lockFd = await fs.open(lockFile, 'wx')
log('Lock acquired, packing tarball:', tarballPath)
// Double-check if tarball was created while we were acquiring the lock
if (existsSync(tarballPath)) {
log('Tarball already exists (created while waiting for lock):', tarballPath)
return
}
// We have the lock, pack the tarball
await packTarball(tarballPath, env)
} catch (err) {
if (err.code === 'EEXIST') {
// Lock exists, another process is packing - wait for the tarball to appear
log('Lock file exists, waiting for tarball:', tarballPath)
while (!existsSync(tarballPath)) {
await new Promise(resolve => setTimeout(resolve, 100))
if (!existsSync(lockFile) && !existsSync(tarballPath)) {
// Lock holder failed without creating the tarball, retry from scratch
log('Lock released without tarball, retrying:', tarballPath)
return packTarballWithLock(tarballPath, env)
}
}
log('Tarball ready:', tarballPath)
} else {
throw err
}
} finally {
if (lockFd) {
await lockFd.close().catch(() => {})
await fs.unlink(lockFile).catch(() => {})
}
}
}
/**
* @param {string[]} dependencies
* @param {boolean} isGitRepo
* @param {string[]} integrationTestsPaths
* @param {string} [followUpCommand]
*/
async function createSandbox (
dependencies = [],
isGitRepo = false,
integrationTestsPaths = ['./integration-tests/*'],
followUpCommand
) {
const cappedDependencies = dependencies.map(dep => {
if (builtinModules.includes(dep)) return dep
const match = dep.replaceAll(/['"]/g, '').match(/^(@?[^@]+)(@(.+))?$/)
assert.notStrictEqual(match, null, `Invalid dependency format: ${dep}`)
const name = match[1]
const range = match[3] || ''
const cappedRange = getCappedRange(name, range)
return `"${name}@${cappedRange}"`
})
// We might use NODE_OPTIONS to init the tracer. We don't want this to affect this operations
const { NODE_OPTIONS, ...restOfEnv } = withBun(process.env)
const noSandbox = String(process.env.TESTING_NO_INTEGRATION_SANDBOX)
if (noSandbox === '1' || noSandbox.toLowerCase() === 'true') {
// Execute integration tests without a sandbox. This is useful when you have other components
// yarn-linked into dd-trace and want to run the integration tests against them.
// Link dd-trace to itself, then...
execHelper('yarn link')
execHelper('yarn link dd-trace')
// ... run the tests in the current directory.
return {
coverageRoot: resolveCoverageRoot({ cwd: process.cwd() }),
folder: path.join(process.cwd(), 'integration-tests'),
remove: async () => {},
}
}
const folder = path.join(sandboxRoot, id().toString())
const tarballEnv = process.env.DD_TEST_SANDBOX_TARBALL_PATH
const out = tarballEnv && tarballEnv !== '0' && tarballEnv !== 'false'
? tarballEnv
: path.join(sandboxRoot, 'dd-trace.tgz')
await fs.mkdir(folder, { recursive: true })
const addOptions = { cwd: folder, env: restOfEnv, timeout: 60_000 }
const addFlags = ['--linker=hoisted', '--trust']
// Tarball packing and integration-tests copy touch independent paths (sandbox root vs. the
// sandbox folder) and neither writes anything `bun add` will read, so run them concurrently.
await Promise.all([
packTarballWithLock(out, restOfEnv),
copyIntegrationTests(integrationTestsPaths, folder),
])
if (process.env.OFFLINE === '1' || process.env.OFFLINE === 'true') {
addFlags.push('--prefer-offline')
}
if (process.env.OMIT) {
addFlags.push(...process.env.OMIT.split(',').map(omit => `--omit=${omit}`))
}
if (DEBUG !== 'true') {
addFlags.push('--silent')
}
if (cappedDependencies.length > 0) {
// knex 1.x pulls in the @vscode/sqlite3 fork, which compiles from source when no prebuilt matches the runner
// and routinely runs past the 60s default.
execHelper(`${BUN} add ${cappedDependencies.join(' ')} ${addFlags.join(' ')}`, { ...addOptions, timeout: 300_000 })
}
execHelper(`${BUN} add file:${out} ${[...addFlags, '--ignore-scripts'].join(' ')}`, addOptions)
if (process.platform === 'win32') {
// On Windows, we can only sync entire filesystem volume caches.
execHelper(`Write-VolumeCache ${folder[0]}`, { shell: 'powershell.exe' })
} else {
execHelper(`sync ${folder}`)
}
if (followUpCommand) {
execHelper(followUpCommand, { cwd: folder, env: restOfEnv })
}
if (isGitRepo) {
execHelper('git init', { cwd: folder })
// These sandboxes are removed right after tests, so disable detached Git maintenance in them.
execHelper('git config gc.auto 0', { cwd: folder })
execHelper('git config maintenance.auto false', { cwd: folder })
await fs.writeFile(path.join(folder, '.gitignore'), 'node_modules/', { flush: true })
execHelper('git config user.email "john@doe.com"', { cwd: folder })
execHelper('git config user.name "John Doe"', { cwd: folder })
execHelper('git config commit.gpgsign false', { cwd: folder })
// Create a unique local bare repo for this test
const localRemotePath = path.join(folder, '..', `${path.basename(folder)}-remote.git`)
if (!existsSync(localRemotePath)) {
execHelper(`git init --bare ${localRemotePath}`)
// Keep the temporary bare remote from starting detached maintenance during local pushes.
execHelper(`git --git-dir=${localRemotePath} config gc.auto 0`)
execHelper(`git --git-dir=${localRemotePath} config maintenance.auto false`)
}
execHelper('git add -A', { cwd: folder })
execHelper('git commit -m "first commit" --no-verify', { cwd: folder })
execHelper(`git remote add origin ${localRemotePath}`, { cwd: folder })
execHelper('git push --set-upstream origin HEAD', { cwd: folder })
}
return {
coverageRoot: resolveCoverageRoot({ cwd: folder }),
folder,
remove: async () => {
// No coverage finalize step: every process already wrote its V8 profile to the shared
// collector dir (outside the sandbox), so deleting the sandbox folder loses nothing.
// Use `exec` below, instead of `fs.rm` to keep support for older Node.js versions, since this code is called in
// our `integration-guardrails` GitHub Actions workflow
if (process.platform === 'win32') {
return execHelper(`Remove-Item -Recurse -Path "${folder}"`, { shell: 'powershell.exe' })
} else {
return execHelper(`rm -rf ${folder}`)
}
},
}
}
/**
* @typedef {'destructure' | 'direct' | 'namespace'} NamedExportBinding
* @typedef {object} ImportVariantOptions
* @property {string} bindingName
* @property {string} packageName
* @property {boolean} defaultExport
* @property {string[]} namedExports
* @property {NamedExportBinding} [namedExportBinding]
* @typedef {Record<string, string>} ImportVariants
* @typedef {Record<string, string>} ImportVariantFiles
*/
/**
* @param {ImportVariantOptions} options
* @returns {ImportVariants}
*/
function createImportVariants (options) {
const {
bindingName,
packageName,
defaultExport,
namedExports,
namedExportBinding,
} = options
assert(defaultExport || namedExports.length, 'At least one default or named export is required')
assert(!namedExports.length || namedExportBinding, 'Named exports require a binding style')
assert(
!namedExportBinding ||
namedExportBinding === 'destructure' ||
namedExportBinding === 'direct' ||
namedExportBinding === 'namespace',
`Unknown named export binding style: ${namedExportBinding}`
)
assert(
namedExportBinding !== 'direct' || namedExports.length === 1,
'Direct named export bindings require exactly one export'
)
const variants = {}
const namespaceName = `mod${bindingName[0].toUpperCase()}${bindingName.slice(1)}`
if (defaultExport) {
variants.default = `import ${bindingName} from '${packageName}'`
variants['default-as-named'] = `import { default as ${bindingName} } from '${packageName}'`
variants['default-from-namespace'] =
`import * as ${namespaceName} from '${packageName}'; const ${bindingName} = ${namespaceName}.default`
}
if (namedExports.length) {
if (namedExportBinding === 'direct') {
const [namedExport] = namedExports
const importBinding = namedExport === bindingName ? namedExport : `${namedExport} as ${bindingName}`
variants.named = `import { ${importBinding} } from '${packageName}'`
variants['named-from-namespace'] =
`import * as ${namespaceName} from '${packageName}'; const ${bindingName} = ${namespaceName}.${namedExport}`
} else if (namedExportBinding === 'namespace') {
const exportsList = namedExports.join(', ')
variants.named = `import { ${exportsList} } from '${packageName}'; const ${bindingName} = { ${exportsList} }`
variants['named-from-namespace'] = `import * as ${bindingName} from '${packageName}'`
} else {
const exportsList = namedExports.join(', ')
variants.named = `import { ${exportsList} } from '${packageName}'`
variants['named-from-namespace'] =
`import * as ${bindingName} from '${packageName}'; const { ${exportsList} } = ${bindingName}`
}
}
return variants
}
/**
* @param {string} filename - The file that will be copied and modified for each variant.
* @param {ImportVariants} variants - Import statements keyed by variant name.
* @param {ImportVariantFiles} variantFilenames - Resulting filenames keyed by variant name.
*/
function writeSandboxVariants (filename, variants, variantFilenames) {
const origFileData = readFileSync(path.join(sandbox.folder, filename), 'utf8')
const baseVariant = variants.default ? 'default' : 'named'
for (const [variant, value] of Object.entries(variants)) {
const variantFilename = variantFilenames[variant]
let newFileData = origFileData
if (variant !== baseVariant) {
const baseValue = variants[baseVariant]
assert(baseValue, `Missing ${baseVariant} variant`)
newFileData = origFileData.replace(baseValue, `${value}`)
if (newFileData === origFileData) throw Error(`Unable to match ${baseVariant}`)
}
writeFileSync(path.join(sandbox.folder, variantFilename), newFileData)
}
}
/**
* Call after useSandbox so variant materialization runs after the sandbox setup.
*
* @param {string} filename - The file that will be copied and modified for each import variant.
* @param {ImportVariantOptions} options
* @returns {ImportVariantFiles} Resulting filenames keyed by variant name.
*/
function varySandbox (filename, options) {
const variants = createImportVariants(options)
const { name: prefix, ext: suffix } = path.parse(filename)
const variantFilenames = {}
for (const variant of Object.keys(variants)) {
variantFilenames[variant] = `${prefix}-${variant}${suffix}`
}
before(function () {
writeSandboxVariants(filename, variants, variantFilenames)
})
return variantFilenames
}
/**
* @param {boolean} shouldExpectTelemetryPoints
*/
function telemetryForwarder (shouldExpectTelemetryPoints = true) {
const forwarderOut = path.join(__dirname, 'output', `forwarder-${Date.now()}.out`)
process.env.DD_TELEMETRY_FORWARDER_PATH = path.join(__dirname, '..', 'telemetry-forwarder.sh')
process.env.FORWARDER_OUT = forwarderOut
let retries = 0
const tryAgain = async function () {
retries += 1
await new Promise(resolve => setTimeout(resolve, 100))
return cleanup()
}
const cleanup = function () {
/** @type {string[]} */
let lines
try {
lines = readFileSync(forwarderOut, 'utf8').trim().split('\n')
} catch (e) {
if (shouldExpectTelemetryPoints && e.code === 'ENOENT' && retries < 10) {
return tryAgain()
}
return []
}
/** @type {Array<[string, unknown]>} */
const msgs = []
for (const line of lines) {
const [telemetryType, data] = line.split('\t')
if (!data && retries < 10) {
return tryAgain()
}
let parsed
try {
parsed = JSON.parse(data)
} catch (e) {
if (!data && retries < 10) {
return tryAgain()
}
throw new SyntaxError(`error parsing data: ${e.message}\n${data}`, { cause: e })
}
msgs.push([telemetryType, parsed])
}
unlinkSync(forwarderOut)
delete process.env.FORWARDER_OUT
delete process.env.DD_TELEMETRY_FORWARDER_PATH
return msgs
}
return cleanup
}
/**
* @param {string | URL | Promise<string | URL | { url: string }> | { url: string }} url
* @returns {Promise<import('http').IncomingMessage & { body: string }>}
*/
async function curl (url) {
if (url !== null && typeof url === 'object') {
if ('then' in url) {
return curl(await url)
}
if ('url' in url) {
url = url.url
}
}
return new Promise((resolve, reject) => {
http.get(url, res => {
const bufs = []
res.on('data', d => bufs.push(d))
res.once('end', () => {
resolve(Object.assign(res, { body: Buffer.concat(bufs).toString('utf8') }))
})
res.once('error', reject)
}).once('error', reject)
})
}
/**
* @param {FakeAgent} agent
* @param {string | URL | Promise<string | URL | { url: string }> | { url: string }} procOrUrl
* @param {(res: { headers: Record<string, string>, payload: unknown[] }) => void} fn
* @param {number} [timeout]
* @param {number} [expectedMessageCount]
* @param {boolean} [resolveAtFirstSuccess]
*/
async function curlAndAssertMessage (agent, procOrUrl, fn, timeout, expectedMessageCount, resolveAtFirstSuccess) {
const resultPromise = agent.assertMessageReceived(fn, timeout, expectedMessageCount, resolveAtFirstSuccess)
await curl(procOrUrl)
return resultPromise
}
/**
* @param {number} port
* @returns {typeof process.env}
*/
function getCiVisAgentlessConfig (port) {
// We remove GITHUB_WORKSPACE so the repository root is not assigned to dd-trace-js
// We remove MOCHA_OPTIONS so the test runner doesn't run the tests twice
const { GITHUB_WORKSPACE, MOCHA_OPTIONS, ...rest } = process.env
return {
...rest,
DD_API_KEY: '1',
DD_CIVISIBILITY_AGENTLESS_ENABLED: '1',
DD_CIVISIBILITY_AGENTLESS_URL: `http://127.0.0.1:${port}`,
NODE_OPTIONS: '-r dd-trace/ci/init',
DD_INSTRUMENTATION_TELEMETRY_ENABLED: 'false',
}
}
/**
* @param {number} port
* @returns {typeof process.env}
*/
function getCiVisEvpProxyConfig (port) {
// We remove GITHUB_WORKSPACE so the repository root is not assigned to dd-trace-js
// We remove MOCHA_OPTIONS so the test runner doesn't run the tests twice
const { GITHUB_WORKSPACE, MOCHA_OPTIONS, ...rest } = process.env
return {
...rest,
DD_TRACE_AGENT_PORT: String(port),
NODE_OPTIONS: '-r dd-trace/ci/init',
DD_CIVISIBILITY_AGENTLESS_ENABLED: '0',
DD_INSTRUMENTATION_TELEMETRY_ENABLED: 'false',
}
}
/**
* @param {object[][]} spans
* @param {string} name
*/
function checkSpansForServiceName (spans, name) {
return spans.some((span) => span.some((nestedSpan) => nestedSpan.name === name))
}
/**
* Exercise the full `cypress run` pipeline (config loader + setupNodeEvents +
* spec resolution) once per matrix job so the first real test doesn't pay an
* electron + NYC require-hook cold-start that exceeds the per-test gather window.
* `cypress verify` only warms the binary; it leaves the run pipeline cold.
*
* The non-existent spec pattern makes cypress exit with "No specs found" *after*
* loading config and plugins — that's the side-effect we want. The non-zero exit
* code is intentionally ignored.
*
* `NODE_OPTIONS` is cleared because the workflow-level `-r ./ci/init` is relative
* to the dd-trace repo root and won't resolve from inside the sandbox. The
* coverage harness still prepends its NYC bootstrap via `patchExecOptions`, so
* the require-hook cold-start is absorbed here too.
*
* @param {string} cwd - Sandbox folder where cypress is installed.
* @returns {Promise<void>}
*/
function warmCypressBinary (cwd) {
return new Promise(resolve => {
childProcess.exec('./node_modules/.bin/cypress run --spec __ddwarmup_no_match__.cy.js', {
cwd,
timeout: 180_000,
env: { ...process.env, NODE_OPTIONS: '' },
}, () => resolve())
})
}
/**
* @typedef {Record<string, string|undefined>} AdditionalEnvArgs
*/
/**
* Prepares spawn options for plugin integration tests.
*
* @param {string} cwd
* @param {string} serverFile
* @param {string|number} agentPort
* @param {AdditionalEnvArgs} [additionalEnvArgs]
* @param {string[]} [execArgv]
* @param {(data: Buffer) => void} [stdioHandler]
* @returns {{ filename: string, options: childProcess.ForkOptions,
* stdioHandler: ((data: Buffer) => void) | undefined }}
*/
function preparePluginIntegrationTestSpawnOptions (
cwd, serverFile, agentPort, additionalEnvArgs, execArgv, stdioHandler
) {
additionalEnvArgs = { ...additionalEnvArgs }
let NODE_OPTIONS = `--loader=${hookFile}`
if (additionalEnvArgs.NODE_OPTIONS !== undefined) {
if (/--(loader|import)/.test(additionalEnvArgs.NODE_OPTIONS ?? '')) {
NODE_OPTIONS = additionalEnvArgs.NODE_OPTIONS
} else {
NODE_OPTIONS += ` ${additionalEnvArgs.NODE_OPTIONS}`
}
delete additionalEnvArgs.NODE_OPTIONS
}
const scriptPath = path.join(cwd, serverFile)
return {
filename: scriptPath,
options: {
cwd,
env: {
...process.env,
NODE_OPTIONS,
DD_TRACE_AGENT_PORT: String(agentPort),
DD_TRACE_FLUSH_INTERVAL: '0',
...additionalEnvArgs,
},
execArgv,
},
stdioHandler,