dd-trace 5.135.0 → 5.136.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (250) hide show
  1. package/ci/init.js +2 -22
  2. package/ext/exporters.js +0 -1
  3. package/index.d.ts +105 -5
  4. package/initialize.mjs +5 -2
  5. package/lambda.d.ts +39 -0
  6. package/lambda.js +3 -0
  7. package/package.json +11 -9
  8. package/packages/datadog-esbuild/index.js +8 -55
  9. package/packages/datadog-instrumentations/src/aws-lambda.js +88 -0
  10. package/packages/datadog-instrumentations/src/cucumber.js +5 -2
  11. package/packages/datadog-instrumentations/src/elevenlabs/activity.js +114 -0
  12. package/packages/datadog-instrumentations/src/elevenlabs/audio.js +104 -0
  13. package/packages/datadog-instrumentations/src/elevenlabs/index.js +288 -0
  14. package/packages/datadog-instrumentations/src/elevenlabs/session.js +444 -0
  15. package/packages/datadog-instrumentations/src/graphql.js +20 -17
  16. package/packages/{datadog-esbuild/src/utils.js → datadog-instrumentations/src/helpers/bundler-esm-exports.js} +282 -40
  17. package/packages/datadog-instrumentations/src/helpers/bundler-transform.js +573 -0
  18. package/packages/datadog-instrumentations/src/helpers/bundler-utils.js +104 -0
  19. package/packages/datadog-instrumentations/src/helpers/hook.js +29 -1
  20. package/packages/datadog-instrumentations/src/helpers/hooks.js +3 -7
  21. package/packages/datadog-instrumentations/src/helpers/lambda-handler.js +189 -0
  22. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +2 -0
  23. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +18 -1
  24. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/async-mutex.js +41 -0
  25. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/elevenlabs.js +25 -0
  26. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql.js +0 -36
  27. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/next.js +40 -0
  28. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/openai-agents-realtime.js +23 -0
  29. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/trpc.js +148 -0
  30. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +50 -0
  31. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +17 -3
  32. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +59 -2
  33. package/packages/datadog-instrumentations/src/ioredis.js +101 -3
  34. package/packages/datadog-instrumentations/src/next.js +19 -6
  35. package/packages/datadog-instrumentations/src/openai-agents-realtime.js +149 -0
  36. package/packages/datadog-instrumentations/src/openai-realtime/audio-accumulator.js +27 -0
  37. package/packages/datadog-instrumentations/src/openai-realtime/index.js +17 -6
  38. package/packages/datadog-instrumentations/src/openai-realtime/server-playback.js +887 -0
  39. package/packages/datadog-instrumentations/src/openai-realtime/session.js +150 -25
  40. package/packages/datadog-instrumentations/src/openai-realtime/turns.js +29 -2
  41. package/packages/datadog-instrumentations/src/otel-sdk-trace.js +11 -9
  42. package/packages/datadog-instrumentations/src/webdriverio.js +12 -12
  43. package/packages/datadog-plugin-async-mutex/src/index.js +50 -0
  44. package/packages/datadog-plugin-aws-lambda/src/index.js +106 -0
  45. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +22 -11
  46. package/packages/datadog-plugin-elevenlabs/src/index.js +69 -0
  47. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +10 -7
  48. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +19 -52
  49. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +4 -2
  50. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-request-context.js +25 -4
  51. package/packages/datadog-plugin-http/src/client.js +32 -9
  52. package/packages/datadog-plugin-http2/src/client.js +38 -13
  53. package/packages/datadog-plugin-next/src/index.js +112 -14
  54. package/packages/datadog-plugin-prisma/src/datadog-tracing-helper.js +5 -3
  55. package/packages/datadog-plugin-trpc/src/index.js +15 -0
  56. package/packages/datadog-plugin-trpc/src/procedure.js +48 -0
  57. package/packages/datadog-plugin-trpc/src/request.js +81 -0
  58. package/packages/datadog-plugin-undici/src/index.js +22 -7
  59. package/packages/datadog-turbopack/index.js +4 -28
  60. package/packages/datadog-turbopack/src/loader.js +14 -452
  61. package/packages/datadog-webpack/index.js +3 -55
  62. package/packages/dd-trace/src/aiguard/evaluation.js +62 -1
  63. package/packages/dd-trace/src/aiguard/sdk.js +8 -2
  64. package/packages/dd-trace/src/aiguard/tags.js +2 -0
  65. package/packages/dd-trace/src/appsec/blocking/index.js +4 -0
  66. package/packages/dd-trace/src/appsec/graphql.js +91 -6
  67. package/packages/dd-trace/src/appsec/recommended.json +1287 -90
  68. package/packages/dd-trace/src/before-exit.js +32 -0
  69. package/packages/dd-trace/src/bootstrap.js +5 -3
  70. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +15 -2
  71. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +12 -34
  72. package/packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js +41 -13
  73. package/packages/dd-trace/src/ci-visibility/exporters/request.js +2 -3
  74. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +1 -2
  75. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +1 -1
  76. package/packages/dd-trace/src/ci-visibility/telemetry.js +6 -0
  77. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +1 -1
  78. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache-schema.js +9 -134
  79. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache.js +11 -156
  80. package/packages/dd-trace/src/config/config-types.d.ts +3 -0
  81. package/packages/dd-trace/src/config/defaults.js +5 -0
  82. package/packages/dd-trace/src/config/generated-config-types.d.ts +42 -2
  83. package/packages/dd-trace/src/config/index.js +17 -5
  84. package/packages/dd-trace/src/config/parsers.js +9 -0
  85. package/packages/dd-trace/src/config/supported-configurations.json +158 -4
  86. package/packages/dd-trace/src/constants.js +1 -0
  87. package/packages/dd-trace/src/debugger/pause-duration-histogram.js +2 -1
  88. package/packages/dd-trace/src/exporter.js +0 -11
  89. package/packages/dd-trace/src/exporters/common/request.js +81 -48
  90. package/packages/dd-trace/src/exporters/common/retry.js +12 -7
  91. package/packages/dd-trace/src/exporters/common/url.js +1 -1
  92. package/packages/dd-trace/src/id.js +1 -1
  93. package/packages/dd-trace/src/lambda/facade.js +74 -0
  94. package/packages/dd-trace/src/lambda/handler.js +3 -41
  95. package/packages/dd-trace/src/lambda/index.js +38 -15
  96. package/packages/dd-trace/src/lambda/runtime/patch.js +19 -3
  97. package/packages/dd-trace/src/lambda/wrap.js +44 -0
  98. package/packages/dd-trace/src/llmobs/constants/tags.js +2 -0
  99. package/packages/dd-trace/src/llmobs/experiments/experiment.js +10 -5
  100. package/packages/dd-trace/src/llmobs/plugins/elevenlabs.js +96 -0
  101. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +19 -6
  102. package/packages/dd-trace/src/llmobs/plugins/openai/realtime.js +38 -11
  103. package/packages/dd-trace/src/llmobs/plugins/vertexai.js +10 -2
  104. package/packages/dd-trace/src/llmobs/sdk.js +19 -0
  105. package/packages/dd-trace/src/llmobs/span_processor.js +9 -0
  106. package/packages/dd-trace/src/llmobs/tagger.js +22 -0
  107. package/packages/dd-trace/src/log/channels.js +4 -0
  108. package/packages/dd-trace/src/log/writer.js +6 -1
  109. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +4 -0
  110. package/packages/dd-trace/src/openfeature/configuration_source.js +35 -27
  111. package/packages/dd-trace/src/openfeature/flag-selection.js +152 -0
  112. package/packages/dd-trace/src/openfeature/flagging_provider.js +19 -1
  113. package/packages/dd-trace/src/openfeature/writers/base.js +1 -3
  114. package/packages/dd-trace/src/opentelemetry/logs/index.js +11 -0
  115. package/packages/dd-trace/src/opentelemetry/logs/otlp_http_log_exporter.js +1 -1
  116. package/packages/dd-trace/src/opentelemetry/metrics/index.js +7 -1
  117. package/packages/dd-trace/src/opentelemetry/metrics/otlp_http_metric_exporter.js +1 -1
  118. package/packages/dd-trace/src/opentelemetry/metrics/otlp_span_stats_exporter.js +4 -1
  119. package/packages/dd-trace/src/opentelemetry/otlp/otlp_http_exporter_base.js +19 -1
  120. package/packages/dd-trace/src/opentelemetry/span-ending-hook.js +5 -1
  121. package/packages/dd-trace/src/opentelemetry/span-helpers.js +6 -1
  122. package/packages/dd-trace/src/opentelemetry/span.js +2 -2
  123. package/packages/dd-trace/src/opentelemetry/startup-config.js +174 -0
  124. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +1 -1
  125. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +7 -1
  126. package/packages/dd-trace/src/opentracing/propagation/tracestate.js +77 -23
  127. package/packages/dd-trace/src/opentracing/tracer.js +24 -0
  128. package/packages/dd-trace/src/otel-thread-ctx.js +28 -31
  129. package/packages/dd-trace/src/plugin_manager.js +34 -7
  130. package/packages/dd-trace/src/plugins/ci_plugin.js +41 -10
  131. package/packages/dd-trace/src/plugins/index.js +6 -0
  132. package/packages/dd-trace/src/plugins/plugin.js +4 -2
  133. package/packages/dd-trace/src/plugins/tracing.js +1 -1
  134. package/packages/dd-trace/src/plugins/util/ci.js +18 -1
  135. package/packages/dd-trace/src/plugins/util/git-cache.js +4 -4
  136. package/packages/dd-trace/src/plugins/util/git.js +263 -82
  137. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +75 -46
  138. package/packages/dd-trace/src/plugins/util/inferred_proxy.js +12 -4
  139. package/packages/dd-trace/src/plugins/util/status-validator.js +23 -10
  140. package/packages/dd-trace/src/plugins/util/tags.js +6 -0
  141. package/packages/dd-trace/src/plugins/util/test.js +64 -39
  142. package/packages/dd-trace/src/plugins/util/url.js +10 -2
  143. package/packages/dd-trace/src/plugins/util/user-provided-git.js +2 -2
  144. package/packages/dd-trace/src/plugins/util/web.js +65 -10
  145. package/packages/dd-trace/src/profiling/webspan-utils.js +6 -5
  146. package/packages/dd-trace/src/proxy.js +33 -53
  147. package/packages/dd-trace/src/span_processor.js +20 -0
  148. package/packages/dd-trace/src/startup-log.js +8 -6
  149. package/packages/dd-trace/src/telemetry/metrics.js +2 -1
  150. package/packages/dd-trace/src/tracer.js +0 -2
  151. package/packages/dd-trace/src/web-tags-cache.js +8 -9
  152. package/register.js +2 -1
  153. package/vendor/dist/@apm-js-collab/code-transformer/LICENSE +489 -0
  154. package/vendor/dist/@datadog/flagging-core/LICENSE +221 -0
  155. package/vendor/dist/@datadog/flagging-core/index.js +1 -0
  156. package/vendor/dist/@datadog/openfeature-node-server/LICENSE +21 -1
  157. package/vendor/dist/@datadog/openfeature-node-server/rules-based/LICENSE +3 -1
  158. package/vendor/dist/@datadog/sketches-js/LICENSE +263 -0
  159. package/vendor/dist/@datadog/source-map/LICENSE +1 -0
  160. package/vendor/dist/@isaacs/ttlcache/LICENSE +13 -0
  161. package/vendor/dist/@opentelemetry/core/LICENSE +209 -1
  162. package/vendor/dist/crypto-randomuuid/LICENSE +3 -0
  163. package/vendor/dist/escape-string-regexp/LICENSE +13 -0
  164. package/vendor/dist/esquery/LICENSE +2 -0
  165. package/vendor/dist/https-proxy-agent/LICENSE +80 -1
  166. package/vendor/dist/istanbul-lib-coverage/LICENSE +2 -0
  167. package/vendor/dist/jest-docblock/LICENSE +16 -0
  168. package/vendor/dist/jsonpath-plus/LICENSE +13 -0
  169. package/vendor/dist/limiter/LICENSE +2 -0
  170. package/vendor/dist/lodash.sortby/LICENSE +2 -0
  171. package/vendor/dist/lru-cache/LICENSE +13 -0
  172. package/vendor/dist/meriyah/LICENSE +13 -0
  173. package/vendor/dist/module-details-from-path/LICENSE +2 -0
  174. package/vendor/dist/mutexify/promise/LICENSE +28 -0
  175. package/vendor/dist/pprof-format/LICENSE +13 -0
  176. package/vendor/dist/pprof-format/index.js +1 -1
  177. package/vendor/dist/protobufjs/LICENSE +219 -0
  178. package/vendor/dist/protobufjs/minimal/LICENSE +219 -0
  179. package/vendor/dist/proxy-from-env/LICENSE +13 -0
  180. package/vendor/dist/retry/LICENSE +2 -0
  181. package/vendor/dist/rfdc/LICENSE +2 -0
  182. package/vendor/dist/semifies/LICENSE +3 -1
  183. package/vendor/dist/shell-quote/LICENSE +3 -1
  184. package/vendor/dist/source-map/LICENSE +1 -0
  185. package/vendor/dist/source-map/lib/util/LICENSE +1 -0
  186. package/vendor/dist/tlhunter-sorted-set/LICENSE +2 -0
  187. package/vendor/dist/ttl-set/LICENSE +28 -0
  188. package/ci/diagnose.js +0 -2215
  189. package/ci/runbook.md +0 -299
  190. package/ci/test-optimization-validation/approval-artifacts.js +0 -175
  191. package/ci/test-optimization-validation/approval.js +0 -386
  192. package/ci/test-optimization-validation/artifact-id.js +0 -18
  193. package/ci/test-optimization-validation/blocker-category.js +0 -24
  194. package/ci/test-optimization-validation/bounded-json.js +0 -120
  195. package/ci/test-optimization-validation/ci-command-candidate.js +0 -77
  196. package/ci/test-optimization-validation/ci-discovery.js +0 -192
  197. package/ci/test-optimization-validation/ci-package-scripts.js +0 -169
  198. package/ci/test-optimization-validation/ci-remediation.js +0 -283
  199. package/ci/test-optimization-validation/cli.js +0 -954
  200. package/ci/test-optimization-validation/command-blocker.js +0 -377
  201. package/ci/test-optimization-validation/command-output-policy.js +0 -188
  202. package/ci/test-optimization-validation/command-runner.js +0 -649
  203. package/ci/test-optimization-validation/environment.js +0 -88
  204. package/ci/test-optimization-validation/executable-approval.js +0 -47
  205. package/ci/test-optimization-validation/executable.js +0 -244
  206. package/ci/test-optimization-validation/execution-lock.js +0 -70
  207. package/ci/test-optimization-validation/framework-adapters/cucumber-validation.json +0 -3
  208. package/ci/test-optimization-validation/framework-adapters/cucumber.js +0 -767
  209. package/ci/test-optimization-validation/framework-adapters/cypress.js +0 -99
  210. package/ci/test-optimization-validation/framework-adapters/playwright.js +0 -175
  211. package/ci/test-optimization-validation/framework-adapters/vitest.js +0 -513
  212. package/ci/test-optimization-validation/generated-file-policy.js +0 -63
  213. package/ci/test-optimization-validation/generated-files.js +0 -425
  214. package/ci/test-optimization-validation/generated-test-contract.js +0 -284
  215. package/ci/test-optimization-validation/generated-verifier.js +0 -235
  216. package/ci/test-optimization-validation/literal-environment.js +0 -56
  217. package/ci/test-optimization-validation/literal-glob.js +0 -52
  218. package/ci/test-optimization-validation/manifest-loader.js +0 -116
  219. package/ci/test-optimization-validation/manifest-scaffold.js +0 -1276
  220. package/ci/test-optimization-validation/manifest-schema.js +0 -695
  221. package/ci/test-optimization-validation/offline-fixtures.js +0 -335
  222. package/ci/test-optimization-validation/offline-output.js +0 -406
  223. package/ci/test-optimization-validation/package-check.js +0 -97
  224. package/ci/test-optimization-validation/payload-normalizer.js +0 -72
  225. package/ci/test-optimization-validation/plan-writer.js +0 -541
  226. package/ci/test-optimization-validation/preflight-runner.js +0 -186
  227. package/ci/test-optimization-validation/project-build-artifact.js +0 -31
  228. package/ci/test-optimization-validation/redaction.js +0 -319
  229. package/ci/test-optimization-validation/report-writer.js +0 -666
  230. package/ci/test-optimization-validation/result-semantics.js +0 -103
  231. package/ci/test-optimization-validation/runner-command.js +0 -264
  232. package/ci/test-optimization-validation/runner-contract.js +0 -695
  233. package/ci/test-optimization-validation/safe-files.js +0 -202
  234. package/ci/test-optimization-validation/scenarios/auto-test-retries.js +0 -171
  235. package/ci/test-optimization-validation/scenarios/basic-reporting.js +0 -407
  236. package/ci/test-optimization-validation/scenarios/ci-wiring.js +0 -666
  237. package/ci/test-optimization-validation/scenarios/early-flake-detection.js +0 -142
  238. package/ci/test-optimization-validation/scenarios/helpers.js +0 -621
  239. package/ci/test-optimization-validation/scenarios/test-management.js +0 -219
  240. package/ci/test-optimization-validation/source-text.js +0 -84
  241. package/ci/test-optimization-validation/static-diagnosis.js +0 -166
  242. package/ci/test-optimization-validation/test-output.js +0 -120
  243. package/ci/test-optimization-validation/validation-blocker.js +0 -21
  244. package/ci/validate-test-optimization.js +0 -3
  245. package/packages/datadog-esbuild/src/resolver.js +0 -284
  246. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/index.js +0 -156
  247. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/msgpack-to-json.js +0 -287
  248. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/payload-projection.js +0 -84
  249. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/sink.js +0 -368
  250. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/writer.js +0 -59
@@ -1,406 +0,0 @@
1
- 'use strict'
2
-
3
- const fs = require('node:fs')
4
- const path = require('node:path')
5
-
6
- const { parseBoundedJson } = require('./bounded-json')
7
- const { normalizeRequests } = require('./payload-normalizer')
8
-
9
- const MAX_COMPLETION_BYTES = 4096
10
- const MAX_COMPLETION_FILES = 2048
11
- const MAX_COMPLETION_TOTAL_BYTES = 2 * 1024 * 1024
12
- const MAX_DECODED_COLLECTION_ENTRIES = 100_000
13
- const MAX_OUTPUT_BYTES = 16 * 1024 * 1024
14
- const MAX_OUTPUT_FILES = 10_000
15
- const MAX_OUTPUT_MODULES = 500
16
- const MAX_OUTPUT_SUITES = 1000
17
- const MAX_OUTPUT_TESTS = 2000
18
- const MAX_OUTPUT_STRING_BYTES = 64 * 1024
19
- const MAX_SAMPLED_EVENTS_PER_PROCESS = 11
20
- const INPUT_NAMES = new Set(['known_tests', 'settings', 'skippable_tests', 'test_management'])
21
- const EVENT_TYPES = new Set(['test', 'test_module_end', 'test_session_end', 'test_suite_end'])
22
- const META_FIELDS = new Set([
23
- 'test.command',
24
- 'test.early_flake.enabled',
25
- 'test.final_status',
26
- 'test.is_new',
27
- 'test.is_retry',
28
- 'test.module',
29
- 'test.name',
30
- 'test.retry_reason',
31
- 'test.source.file',
32
- 'test.status',
33
- 'test.suite',
34
- 'test.test_management.attempt_to_fix_passed',
35
- 'test.test_management.enabled',
36
- 'test.test_management.is_attempt_to_fix',
37
- 'test.test_management.is_quarantined',
38
- 'test.test_management.is_test_disabled',
39
- ])
40
- const METRIC_FIELDS = new Set(['test.is_new', 'test.is_retry'])
41
- const ROOT_ENTRIES = new Set(['completions', 'payloads'])
42
- const PAYLOAD_KINDS = new Set(['tests'])
43
-
44
- /**
45
- * Reads bounded projected payloads and reconciles them with authoritative per-process completion records.
46
- *
47
- * @param {string} outputRoot payload output root
48
- * @returns {object} parsed output and aggregate capture metadata
49
- */
50
- function readOfflineOutput (outputRoot) {
51
- assertDirectory(outputRoot, 'output root')
52
- assertDirectoryEntries(outputRoot, ROOT_ENTRIES)
53
-
54
- const payloadsRoot = path.join(outputRoot, 'payloads')
55
- const completionsRoot = path.join(outputRoot, 'completions')
56
- const exporterInitialized = exists(payloadsRoot) || exists(completionsRoot)
57
- if (!exporterInitialized) return emptyOutput()
58
-
59
- const state = {
60
- bytes: 0n,
61
- completionBytes: 0n,
62
- decodedEntries: 0,
63
- files: 0,
64
- }
65
- const completions = readCompletions(outputRoot, completionsRoot, state)
66
- const captureMode = getCaptureMode(completions)
67
- state.eventCounts = { modules: 0, suites: 0, tests: 0, total: 0 }
68
- const artifactsByProcess = new Map()
69
- const events = []
70
-
71
- if (exists(payloadsRoot)) {
72
- assertDirectory(payloadsRoot, 'payloads directory')
73
- assertPathInside(outputRoot, payloadsRoot)
74
- assertDirectoryEntries(payloadsRoot, PAYLOAD_KINDS)
75
- readPayloadFiles(payloadsRoot, 'tests', state, (processId, value) => {
76
- assertTestPayload(value)
77
- const normalized = normalizeRequests([{ url: '/api/v2/citestcycle', payload: value }])
78
- for (const event of normalized) {
79
- assertRecognizedEventBudget(event, captureMode, completions.length, state.eventCounts)
80
- events.push(event)
81
- }
82
- const artifact = getProcessArtifacts(artifactsByProcess, processId)
83
- artifact.payloadFiles++
84
- artifact.eventsRetained += normalized.length
85
- })
86
- }
87
-
88
- if (completions.length === 0) {
89
- throw new Error('Offline Test Optimization exporter initialized but did not write completion evidence.')
90
- }
91
- reconcileCompletions(completions, artifactsByProcess)
92
-
93
- const summary = aggregateCompletions(completions)
94
- return {
95
- captureMode,
96
- completionCount: completions.length,
97
- events,
98
- initialized: true,
99
- inputs: summary.inputs,
100
- observedEventCount: summary.eventsObserved,
101
- payloadFileCount: summary.payloadFiles,
102
- retainedEventCount: summary.eventsRetained,
103
- sampled: summary.eventsObserved > summary.eventsRetained,
104
- summary,
105
- }
106
- }
107
-
108
- function readCompletions (outputRoot, directory, state) {
109
- if (!exists(directory)) return []
110
- assertDirectory(directory, 'completions directory')
111
- assertPathInside(outputRoot, directory)
112
- const filenames = fs.readdirSync(directory).sort()
113
- if (filenames.length > MAX_COMPLETION_FILES) {
114
- throw new Error(`Offline validation output exceeds ${MAX_COMPLETION_FILES} completion records.`)
115
- }
116
-
117
- const completions = []
118
- const processIds = new Set()
119
- for (const name of filenames) {
120
- const match = /^completion-([a-f0-9]{32})\.json$/.exec(name)
121
- if (!match) throw new Error('Offline validation completions directory contains an unexpected entry.')
122
- const buffer = readRegularFile(path.join(directory, name), MAX_COMPLETION_BYTES, state, true)
123
- const parsed = parseOutputJson(buffer, 'completion record', state, 1000)
124
- assertCompletion(parsed, match[1])
125
- if (processIds.has(parsed.processId)) throw new Error('Offline validation contains duplicate completion records.')
126
- processIds.add(parsed.processId)
127
- completions.push(parsed)
128
- }
129
- return completions
130
- }
131
-
132
- function readPayloadFiles (payloadsRoot, kind, state, consume) {
133
- const directory = path.join(payloadsRoot, kind)
134
- if (!exists(directory)) return
135
- assertDirectory(directory, `${kind} payload directory`)
136
- assertPathInside(payloadsRoot, directory)
137
-
138
- const pattern = new RegExp(String.raw`^${kind}-([a-f0-9]{32})-[0-9]+-[0-9]+-[0-9]+\.json$`)
139
- const filenames = fs.readdirSync(directory).sort()
140
- if (state.files + filenames.length > MAX_OUTPUT_FILES) {
141
- throw new Error(`Offline validation output exceeds ${MAX_OUTPUT_FILES} payload files.`)
142
- }
143
- for (const name of filenames) {
144
- const match = pattern.exec(name)
145
- if (!match) throw new Error(`Offline validation ${kind} payload directory contains an unexpected entry.`)
146
- state.files++
147
- const buffer = readRegularFile(path.join(directory, name), MAX_OUTPUT_BYTES, state, false)
148
- consume(match[1], parseOutputJson(buffer, `${kind} payload`, state, MAX_DECODED_COLLECTION_ENTRIES))
149
- }
150
- }
151
-
152
- function readRegularFile (filename, individualLimit, state, completion) {
153
- const stat = fs.lstatSync(filename, { bigint: true })
154
- if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink > 1) {
155
- throw new Error('Offline validation artifact must be a regular, unlinked file.')
156
- }
157
- if (stat.size > individualLimit) throw new Error(`Offline validation artifact exceeds ${individualLimit} bytes.`)
158
- const totalKey = completion ? 'completionBytes' : 'bytes'
159
- const totalLimit = completion ? MAX_COMPLETION_TOTAL_BYTES : MAX_OUTPUT_BYTES
160
- if (state[totalKey] + stat.size > totalLimit) {
161
- throw new Error(`Offline validation output exceeds ${totalLimit} aggregate bytes.`)
162
- }
163
-
164
- const file = fs.openSync(filename, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0))
165
- try {
166
- const opened = fs.fstatSync(file, { bigint: true })
167
- if (!opened.isFile() || opened.nlink > 1 || opened.dev !== stat.dev || opened.ino !== stat.ino) {
168
- throw new Error('Offline validation artifact changed while it was opened.')
169
- }
170
- const buffer = fs.readFileSync(file)
171
- const completed = fs.fstatSync(file, { bigint: true })
172
- if (completed.size !== opened.size || completed.mtimeMs !== opened.mtimeMs) {
173
- throw new Error('Offline validation artifact changed while it was read.')
174
- }
175
- state[totalKey] += BigInt(buffer.length)
176
- return buffer
177
- } finally {
178
- fs.closeSync(file)
179
- }
180
- }
181
-
182
- function parseOutputJson (buffer, label, state, perFileEntries) {
183
- if (buffer.length === 0) throw new Error(`Offline validation ${label} is empty.`)
184
- const parsed = parseBoundedJson(buffer, {
185
- label: `Offline validation ${label}`,
186
- maxCollectionEntries: perFileEntries,
187
- maxNestingDepth: 64,
188
- maxStringBytes: MAX_OUTPUT_STRING_BYTES,
189
- })
190
- state.decodedEntries += parsed.collectionEntries
191
- if (state.decodedEntries > MAX_DECODED_COLLECTION_ENTRIES) {
192
- throw new Error(
193
- `Offline validation output exceeds ${MAX_DECODED_COLLECTION_ENTRIES} aggregate decoded entries.`
194
- )
195
- }
196
- return parsed.value
197
- }
198
-
199
- function assertTestPayload (value) {
200
- if (!isObject(value) || value.version !== 1 || !Array.isArray(value.events) ||
201
- Object.keys(value).sort().join(',') !== 'events,version') {
202
- throw new Error('Offline validation test payload has an unsupported JSON shape.')
203
- }
204
- for (const event of value.events) {
205
- if (!isObject(event) || !EVENT_TYPES.has(event.type) || !isObject(event.content) ||
206
- !isObject(event.content.meta) || !isObject(event.content.metrics) ||
207
- Object.keys(event).sort().join(',') !== 'content,type' ||
208
- Object.keys(event.content).sort().join(',') !== 'meta,metrics' ||
209
- Object.keys(event.content.meta).some(name => !META_FIELDS.has(name)) ||
210
- Object.keys(event.content.metrics).some(name => !METRIC_FIELDS.has(name))) {
211
- throw new Error('Offline validation test payload contains an unsupported event shape.')
212
- }
213
- }
214
- }
215
-
216
- function assertCompletion (completion, filenameProcessId) {
217
- if (!isObject(completion) || Object.keys(completion).sort().join(',') !==
218
- 'captureMode,counts,errors,inputs,processId,version' || completion.version !== 1 ||
219
- completion.processId !== filenameProcessId || !/^[a-f0-9]{32}$/.test(completion.processId) ||
220
- !['sample', 'strict'].includes(completion.captureMode) || !isObject(completion.counts) ||
221
- !isObject(completion.inputs) || !Array.isArray(completion.errors) || completion.errors.length > 20) {
222
- throw invalidCompletionError()
223
- }
224
- const countKeys = ['eventsObserved', 'eventsRetained', 'payloadFiles']
225
- if (Object.keys(completion.counts).sort().join(',') !== countKeys.sort().join(',') ||
226
- countKeys.some(name => !isCount(completion.counts[name])) ||
227
- completion.counts.eventsRetained > completion.counts.eventsObserved ||
228
- completion.errors.some(error => typeof error !== 'string' || error.length > 100)) {
229
- throw invalidCompletionError()
230
- }
231
- assertCompletionInputs(completion.inputs)
232
- if (completion.captureMode === 'sample' && completion.counts.eventsRetained > MAX_SAMPLED_EVENTS_PER_PROCESS) {
233
- throw invalidCompletionError()
234
- }
235
- }
236
-
237
- function getCaptureMode (completions) {
238
- if (completions.length === 0) return
239
- const captureMode = completions[0].captureMode
240
- if (completions.some(completion => completion.captureMode !== captureMode)) {
241
- throw new Error('Offline Test Optimization completion records use inconsistent capture modes.')
242
- }
243
- return captureMode
244
- }
245
-
246
- function assertCompletionInputs (inputs) {
247
- for (const [name, input] of Object.entries(inputs)) {
248
- if (!INPUT_NAMES.has(name) || !isObject(input) || Object.keys(input).join(',') !== 'status' ||
249
- !['error', 'loaded'].includes(input.status)) {
250
- throw invalidCompletionError()
251
- }
252
- }
253
- }
254
-
255
- function reconcileCompletions (completions, artifactsByProcess) {
256
- const completionsByProcess = new Map(completions.map(completion => [completion.processId, completion]))
257
- for (const processId of artifactsByProcess.keys()) {
258
- if (!completionsByProcess.has(processId)) {
259
- throw new Error('Offline validation payload artifacts do not have matching completion evidence.')
260
- }
261
- }
262
- for (const completion of completions) {
263
- const artifacts = artifactsByProcess.get(completion.processId) || emptyProcessArtifacts()
264
- const counts = completion.counts
265
- if (counts.payloadFiles !== artifacts.payloadFiles || counts.eventsRetained !== artifacts.eventsRetained) {
266
- throw new Error('Offline Test Optimization completion evidence does not match retained payload artifacts.')
267
- }
268
- }
269
- }
270
-
271
- function aggregateCompletions (completions) {
272
- const aggregate = {
273
- errors: [],
274
- eventsObserved: 0,
275
- eventsRetained: 0,
276
- inputs: {},
277
- payloadFiles: 0,
278
- }
279
- for (const completion of completions) {
280
- for (const name of [
281
- 'eventsObserved',
282
- 'eventsRetained',
283
- 'payloadFiles',
284
- ]) {
285
- aggregate[name] = addCount(aggregate[name], completion.counts[name])
286
- }
287
- for (const error of completion.errors) {
288
- if (!aggregate.errors.includes(error)) aggregate.errors.push(error)
289
- }
290
- mergeInputs(aggregate.inputs, completion.inputs)
291
- }
292
- return aggregate
293
- }
294
-
295
- function getProcessArtifacts (artifacts, processId) {
296
- let value = artifacts.get(processId)
297
- if (!value) {
298
- value = emptyProcessArtifacts()
299
- artifacts.set(processId, value)
300
- }
301
- return value
302
- }
303
-
304
- function emptyProcessArtifacts () {
305
- return { eventsRetained: 0, payloadFiles: 0 }
306
- }
307
-
308
- function mergeInputs (aggregate, inputs) {
309
- for (const [name, input] of Object.entries(inputs)) {
310
- aggregate[name] = {
311
- status: aggregate[name]?.status === 'error' || input.status === 'error' ? 'error' : 'loaded',
312
- }
313
- }
314
- }
315
-
316
- function addCount (current, value) {
317
- const total = current + value
318
- if (!Number.isSafeInteger(total)) throw invalidCompletionError()
319
- return total
320
- }
321
-
322
- function isCount (value) {
323
- return Number.isSafeInteger(value) && value >= 0
324
- }
325
-
326
- function invalidCompletionError () {
327
- return new Error('Invalid offline Test Optimization exporter completion record.')
328
- }
329
-
330
- function assertDirectory (directory, label) {
331
- const stat = fs.lstatSync(directory)
332
- if (!stat.isDirectory() || stat.isSymbolicLink()) {
333
- throw new Error(`Offline validation ${label} must be a regular directory.`)
334
- }
335
- }
336
-
337
- function assertDirectoryEntries (directory, allowed) {
338
- if (fs.readdirSync(directory).some(entry => !allowed.has(entry))) {
339
- throw new Error('Offline validation payload output contains an unexpected entry.')
340
- }
341
- }
342
-
343
- function assertPathInside (parent, child) {
344
- const relative = path.relative(fs.realpathSync(parent), fs.realpathSync(child))
345
- if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
346
- throw new Error('Offline validation payload path resolves outside its output root.')
347
- }
348
- }
349
-
350
- function exists (filename) {
351
- try {
352
- fs.lstatSync(filename)
353
- return true
354
- } catch (error) {
355
- if (error.code === 'ENOENT') return false
356
- throw error
357
- }
358
- }
359
-
360
- function emptyOutput () {
361
- return {
362
- captureMode: undefined,
363
- completionCount: 0,
364
- events: [],
365
- initialized: false,
366
- inputs: {},
367
- observedEventCount: 0,
368
- payloadFileCount: 0,
369
- retainedEventCount: 0,
370
- sampled: false,
371
- summary: undefined,
372
- }
373
- }
374
-
375
- function assertRecognizedEventBudget (event, captureMode, processCount, counts) {
376
- counts.total++
377
- if (captureMode === 'sample') {
378
- if (counts.total > processCount * MAX_SAMPLED_EVENTS_PER_PROCESS) {
379
- throw new Error('Offline validation sampled output exceeds its run-wide recognized-event budget.')
380
- }
381
- return
382
- }
383
- if (event.type === 'test_module_end' && ++counts.modules > MAX_OUTPUT_MODULES) {
384
- throw new Error(`Offline validation output exceeds ${MAX_OUTPUT_MODULES} test modules.`)
385
- }
386
- if (event.type === 'test_suite_end' && ++counts.suites > MAX_OUTPUT_SUITES) {
387
- throw new Error(`Offline validation output exceeds ${MAX_OUTPUT_SUITES} test suites.`)
388
- }
389
- if (event.type === 'test' && ++counts.tests > MAX_OUTPUT_TESTS) {
390
- throw new Error(`Offline validation output exceeds ${MAX_OUTPUT_TESTS} tests.`)
391
- }
392
- }
393
-
394
- function isObject (value) {
395
- return Boolean(value && typeof value === 'object' && !Array.isArray(value))
396
- }
397
-
398
- module.exports = {
399
- MAX_COMPLETION_FILES,
400
- MAX_OUTPUT_BYTES,
401
- MAX_OUTPUT_FILES,
402
- MAX_OUTPUT_MODULES,
403
- MAX_OUTPUT_SUITES,
404
- MAX_OUTPUT_TESTS,
405
- readOfflineOutput,
406
- }
@@ -1,97 +0,0 @@
1
- 'use strict'
2
-
3
- const { spawnSync } = require('node:child_process')
4
- const path = require('node:path')
5
-
6
- const { BLOCKER_CATEGORIES } = require('./blocker-category')
7
- const { getBaseEnv } = require('./command-runner')
8
- const { sanitizeString } = require('./redaction')
9
-
10
- const DEFAULT_PACKAGE_ROOT = path.resolve(__dirname, '..', '..')
11
- const LOAD_MARKER = 'dd-trace-test-optimization-package-check-ok'
12
- const MAX_OUTPUT_BYTES = 64 * 1024
13
- const TIMEOUT_MS = 10_000
14
-
15
- // Loads the initialization entrypoint in an isolated child without initializing tracing.
16
- function checkInstalledPackage ({ packageRoot = DEFAULT_PACKAGE_ROOT } = {}) {
17
- const root = path.resolve(packageRoot)
18
- const initPath = path.join(root, 'ci', 'init.js')
19
- const script = [
20
- `require(${JSON.stringify(initPath)})`,
21
- `process.stdout.write(${JSON.stringify(LOAD_MARKER)})`,
22
- 'process.exit(0)',
23
- ].join(';')
24
- const result = spawnSync(process.execPath, ['-e', script], {
25
- cwd: root,
26
- encoding: 'utf8',
27
- env: {
28
- ...getBaseEnv('clean'),
29
- DD_CIVISIBILITY_ENABLED: 'false',
30
- DD_INSTRUMENTATION_TELEMETRY_ENABLED: 'false',
31
- DD_PROFILING_ENABLED: 'false',
32
- DD_REMOTE_CONFIGURATION_ENABLED: 'false',
33
- DD_TRACE_ENABLED: 'false',
34
- NODE_OPTIONS: '',
35
- },
36
- maxBuffer: MAX_OUTPUT_BYTES,
37
- shell: false,
38
- timeout: TIMEOUT_MS,
39
- windowsHide: true,
40
- })
41
-
42
- if (!result.error && result.status === 0 && result.stdout.includes(LOAD_MARKER)) {
43
- return {
44
- ok: true,
45
- diagnosis: 'The installed dd-trace package loaded its Test Optimization initialization entrypoint.',
46
- }
47
- }
48
-
49
- const detail = getFailureDetail(result)
50
- return {
51
- ok: false,
52
- diagnosis: 'The installed dd-trace package could not load its Test Optimization initialization entrypoint' +
53
- (detail ? `: ${detail}` : '.'),
54
- recommendation: 'Reinstall dd-trace through the project\'s normal dependency workflow, then create a fresh ' +
55
- 'validation plan. If the load check still fails, report it as an installed-package problem without running ' +
56
- 'tests.',
57
- }
58
- }
59
-
60
- function getInstalledPackageFailure (framework, packageCheck) {
61
- return {
62
- frameworkId: framework.id,
63
- scenario: 'basic-reporting',
64
- status: 'blocked',
65
- diagnosis: `${packageCheck.diagnosis} No project test was run and no library-compatibility conclusion was reached.`,
66
- evidence: {
67
- blockerCategory: BLOCKER_CATEGORIES.PROJECT_SETUP_REQUIRED,
68
- blockedByProjectSetup: true,
69
- installedPackageIncomplete: true,
70
- recommendation: packageCheck.recommendation,
71
- validationIncomplete: true,
72
- },
73
- artifacts: [],
74
- }
75
- }
76
-
77
- function getFailureDetail (result) {
78
- if (result.error?.code === 'ETIMEDOUT') return `the isolated load check exceeded ${TIMEOUT_MS} ms.`
79
- if (result.error) return `${sanitizeLine(result.error.message)}.`
80
-
81
- const output = `${result.stderr || ''}\n${result.stdout || ''}`
82
- const line = output.split(/\r?\n/).map(value => value.trim()).find(value => {
83
- return /^(?:Error:|.*(?:MODULE_NOT_FOUND|Cannot find (?:module|package)|ERR_[A-Z_]+))/.test(value)
84
- })
85
- if (line) return `${sanitizeLine(line)}.`
86
- if (result.signal) return `the isolated load check exited after signal ${sanitizeLine(result.signal)}.`
87
- return `the isolated load check exited ${result.status ?? 'without a status'}.`
88
- }
89
-
90
- function sanitizeLine (value) {
91
- const line = sanitizeString(String(value)).replaceAll(/\p{Cc}+/gu, ' ').trim().slice(0, 1000)
92
- let end = line.length
93
- while (end > 0 && line[end - 1] === '.') end--
94
- return line.slice(0, end)
95
- }
96
-
97
- module.exports = { checkInstalledPackage, getInstalledPackageFailure }
@@ -1,72 +0,0 @@
1
- 'use strict'
2
-
3
- function normalizeRequests (requests) {
4
- const events = []
5
- for (const request of requests) {
6
- if (!request.url || !request.url.endsWith('/api/v2/citestcycle')) continue
7
- const payloadEvents = request.payload && Array.isArray(request.payload.events) ? request.payload.events : []
8
- for (const event of payloadEvents) {
9
- events.push(normalizeEvent(event, request))
10
- }
11
- }
12
- return events
13
- }
14
-
15
- function normalizeEvent (event, request) {
16
- const content = event.content || {}
17
- const meta = content.meta || {}
18
- const metrics = content.metrics || {}
19
- return {
20
- type: event.type,
21
- requestUrl: request.url,
22
- name: content.name,
23
- resource: content.resource,
24
- service: content.service,
25
- error: content.error,
26
- meta,
27
- metrics,
28
- testName: meta['test.name'],
29
- testSuite: meta['test.suite'],
30
- testStatus: meta['test.status'],
31
- testSourceFile: meta['test.source.file'],
32
- retryReason: meta['test.retry_reason'],
33
- isNew: meta['test.is_new'] === 'true' || metrics['test.is_new'] === 1,
34
- isRetry: meta['test.is_retry'] === 'true' || metrics['test.is_retry'] === 1,
35
- finalStatus: meta['test.final_status'],
36
- earlyFlakeEnabled: meta['test.early_flake.enabled'] === 'true',
37
- testManagementEnabled: meta['test.test_management.enabled'] === 'true',
38
- isQuarantined: meta['test.test_management.is_quarantined'] === 'true',
39
- isDisabled: meta['test.test_management.is_test_disabled'] === 'true',
40
- isAttemptToFix: meta['test.test_management.is_attempt_to_fix'] === 'true',
41
- attemptToFixPassed: meta['test.test_management.attempt_to_fix_passed'] === 'true',
42
- }
43
- }
44
-
45
- function eventsOfType (events, type) {
46
- return events.filter(event => event.type === type)
47
- }
48
-
49
- function findTestsByIdentity (events, identities, { ignoreSuite = false } = {}) {
50
- const tests = eventsOfType(events, 'test')
51
- return tests.filter(test => identities.some(identity => matchesIdentity(test, identity, ignoreSuite)))
52
- }
53
-
54
- function matchesIdentity (test, identity, ignoreSuite) {
55
- if (identity.name && !sameOrEndsWith(test.testName, identity.name)) return false
56
- if (identity.file && !sameOrEndsWith(test.testSourceFile, identity.file)) return false
57
- if (!ignoreSuite && identity.suite && !sameOrEndsWith(test.testSuite, identity.suite)) return false
58
- return Boolean(identity.name)
59
- }
60
-
61
- function sameOrEndsWith (actual, expected) {
62
- if (!actual || !expected) return false
63
- return actual === expected ||
64
- actual.endsWith(expected) ||
65
- expected.endsWith(actual)
66
- }
67
-
68
- module.exports = {
69
- normalizeRequests,
70
- eventsOfType,
71
- findTestsByIdentity,
72
- }