dd-trace 5.136.0 → 5.137.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 (141) hide show
  1. package/README.md +3 -0
  2. package/ci/cypress/support.js +2 -1
  3. package/ci/vitest-no-worker-init-node-setup.mjs +2 -1
  4. package/ci/vitest-no-worker-init-runner-setup.mjs +2 -1
  5. package/ci/vitest-no-worker-init-setup.mjs +729 -724
  6. package/ci/vitest-no-worker-init-v5-setup.mjs +2 -1
  7. package/package.json +33 -30
  8. package/packages/datadog-esbuild/index.js +8 -15
  9. package/packages/datadog-esbuild/src/log.js +2 -29
  10. package/packages/datadog-instrumentations/src/ai.js +6 -1
  11. package/packages/datadog-instrumentations/src/cypress-config.js +20 -9
  12. package/packages/datadog-instrumentations/src/helpers/bundler-esm-exports.js +23 -1
  13. package/packages/datadog-instrumentations/src/helpers/bundler-log.js +38 -0
  14. package/packages/datadog-instrumentations/src/helpers/bundler-transform.js +9 -6
  15. package/packages/datadog-instrumentations/src/helpers/fetch.js +51 -6
  16. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +6 -0
  17. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +8 -0
  18. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-client.js +30 -0
  19. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-server.js +23 -0
  20. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/next.js +21 -0
  21. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/postgres.js +33 -4
  22. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +30 -0
  23. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +6 -0
  24. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms/postgres.js +122 -0
  25. package/packages/datadog-instrumentations/src/microgateway-core.js +1 -2
  26. package/packages/datadog-instrumentations/src/modelcontextprotocol-client.js +21 -0
  27. package/packages/datadog-instrumentations/src/modelcontextprotocol-sdk.js +7 -1
  28. package/packages/datadog-instrumentations/src/modelcontextprotocol-server.js +41 -0
  29. package/packages/datadog-instrumentations/src/next.js +184 -20
  30. package/packages/datadog-instrumentations/src/router.js +35 -12
  31. package/packages/datadog-instrumentations/src/vitest-main.js +10 -2
  32. package/packages/datadog-plugin-aws-lambda/src/arn.js +41 -0
  33. package/packages/datadog-plugin-aws-lambda/src/event-type-guards.js +170 -0
  34. package/packages/datadog-plugin-aws-lambda/src/trigger.js +339 -0
  35. package/packages/datadog-plugin-aws-sdk/src/services/dynamodb.js +7 -0
  36. package/packages/datadog-plugin-aws-sdk/src/services/kinesis.js +32 -10
  37. package/packages/datadog-plugin-aws-sdk/src/services/lambda.js +10 -1
  38. package/packages/datadog-plugin-aws-sdk/src/services/sqs.js +4 -0
  39. package/packages/datadog-plugin-aws-sdk/src/services/stepfunctions.js +3 -0
  40. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +30 -4
  41. package/packages/datadog-plugin-cypress/src/support.mjs +1353 -0
  42. package/packages/datadog-plugin-express/src/code_origin.js +2 -2
  43. package/packages/datadog-plugin-fastify/src/code_origin.js +2 -2
  44. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +10 -0
  45. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +2 -0
  46. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +7 -0
  47. package/packages/datadog-plugin-google-cloud-pubsub/src/resource-names.js +24 -0
  48. package/packages/datadog-plugin-graphql/src/tools/transforms.js +1 -0
  49. package/packages/datadog-plugin-http/src/client.js +2 -1
  50. package/packages/datadog-plugin-http2/src/client.js +2 -1
  51. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/tracing.js +28 -2
  52. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/utils.js +1 -0
  53. package/packages/datadog-plugin-mongodb-core/src/query.js +17 -1
  54. package/packages/datadog-plugin-postgres/src/index.js +118 -41
  55. package/packages/datadog-plugin-supabase/src/supabase-auth-js-gotrueclient-getuser.js +18 -8
  56. package/packages/datadog-plugin-supabase/src/supabase-functions-js-functionsclient-invoke.js +49 -13
  57. package/packages/datadog-plugin-supabase/src/supabase-storage-js-handle-request.js +34 -9
  58. package/packages/datadog-plugin-vitest/src/index.js +3 -2
  59. package/packages/datadog-plugin-ws/src/close.js +3 -5
  60. package/packages/datadog-plugin-ws/src/producer.js +1 -4
  61. package/packages/datadog-plugin-ws/src/receiver.js +3 -5
  62. package/packages/datadog-plugin-ws/src/server.js +44 -13
  63. package/packages/datadog-vite/index.js +537 -0
  64. package/packages/datadog-vite/src/log.js +5 -0
  65. package/packages/datadog-webpack/src/log.js +2 -29
  66. package/packages/dd-trace/src/aiguard/index.js +1 -1
  67. package/packages/dd-trace/src/aiguard/integrations/index.js +6 -5
  68. package/packages/dd-trace/src/appsec/blocking/index.js +17 -1
  69. package/packages/dd-trace/src/appsec/channels.js +7 -0
  70. package/packages/dd-trace/src/appsec/downstream_requests.js +105 -0
  71. package/packages/dd-trace/src/appsec/graphql.js +10 -13
  72. package/packages/dd-trace/src/appsec/handlers/auth.js +1 -3
  73. package/packages/dd-trace/src/appsec/handlers/http-request.js +60 -65
  74. package/packages/dd-trace/src/appsec/handlers/http-response.js +61 -7
  75. package/packages/dd-trace/src/appsec/handlers/payments.js +23 -27
  76. package/packages/dd-trace/src/appsec/index.js +6 -0
  77. package/packages/dd-trace/src/appsec/lambda.js +17 -17
  78. package/packages/dd-trace/src/appsec/rasp/command_injection.js +4 -4
  79. package/packages/dd-trace/src/appsec/rasp/index.js +8 -1
  80. package/packages/dd-trace/src/appsec/rasp/lfi.js +2 -2
  81. package/packages/dd-trace/src/appsec/rasp/sql_injection.js +7 -17
  82. package/packages/dd-trace/src/appsec/rasp/ssrf.js +80 -16
  83. package/packages/dd-trace/src/appsec/rasp/utils.js +33 -3
  84. package/packages/dd-trace/src/appsec/recommended.json +70 -3
  85. package/packages/dd-trace/src/appsec/reporter.js +9 -0
  86. package/packages/dd-trace/src/appsec/sdk/set_user.js +3 -3
  87. package/packages/dd-trace/src/appsec/sdk/track_event.js +4 -4
  88. package/packages/dd-trace/src/appsec/sdk/user_blocking.js +1 -1
  89. package/packages/dd-trace/src/appsec/user_tracking.js +6 -8
  90. package/packages/dd-trace/src/appsec/waf/index.js +65 -6
  91. package/packages/dd-trace/src/appsec/waf/waf_context_wrapper.js +33 -38
  92. package/packages/dd-trace/src/appsec/waf/waf_manager.js +18 -2
  93. package/packages/dd-trace/src/config/generated-config-types.d.ts +4 -2
  94. package/packages/dd-trace/src/config/index.js +46 -26
  95. package/packages/dd-trace/src/config/parsers.js +35 -0
  96. package/packages/dd-trace/src/config/remote-config-layers.js +38 -0
  97. package/packages/dd-trace/src/config/remote_config.js +2 -1
  98. package/packages/dd-trace/src/config/supported-configurations.json +14 -6
  99. package/packages/dd-trace/src/datastreams/fnv.js +27 -0
  100. package/packages/dd-trace/src/datastreams/pathway.js +113 -28
  101. package/packages/dd-trace/src/datastreams/processor.js +5 -4
  102. package/packages/dd-trace/src/debugger/config.js +1 -1
  103. package/packages/dd-trace/src/debugger/devtools_client/request-options.js +7 -9
  104. package/packages/dd-trace/src/debugger/devtools_client/send.js +1 -1
  105. package/packages/dd-trace/src/debugger/devtools_client/state.js +3 -1
  106. package/packages/dd-trace/src/debugger/devtools_client/tags.js +1 -1
  107. package/packages/dd-trace/src/debugger/index.js +2 -2
  108. package/packages/dd-trace/src/debugger/inspect-segment.js +3 -2
  109. package/packages/dd-trace/src/debugger/pause-duration-histogram.js +4 -1
  110. package/packages/dd-trace/src/debugger/probe_sampler.js +39 -17
  111. package/packages/dd-trace/src/debugger/unsupported-runtime.js +2 -0
  112. package/packages/dd-trace/src/git_metadata.js +2 -1
  113. package/packages/dd-trace/src/index.js +6 -3
  114. package/packages/dd-trace/src/lambda/facade.js +6 -5
  115. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/index.js +54 -3
  116. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/utils.js +81 -1
  117. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +3 -0
  118. package/packages/dd-trace/src/openfeature/configuration_source.js +20 -0
  119. package/packages/dd-trace/src/plugins/ci_plugin.js +104 -9
  120. package/packages/dd-trace/src/plugins/index.js +2 -0
  121. package/packages/dd-trace/src/plugins/util/ci.js +34 -0
  122. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +9 -14
  123. package/packages/dd-trace/src/plugins/util/test.js +28 -1
  124. package/packages/dd-trace/src/plugins/util/url.js +8 -5
  125. package/packages/dd-trace/src/plugins/util/user-provided-git.js +4 -4
  126. package/packages/dd-trace/src/process-tags/index.js +1 -1
  127. package/packages/dd-trace/src/profiler.js +74 -12
  128. package/packages/dd-trace/src/profiling/profiler.js +30 -2
  129. package/packages/dd-trace/src/profiling/profilers/space.js +3 -1
  130. package/packages/dd-trace/src/profiling/profilers/wall.js +4 -4
  131. package/packages/dd-trace/src/profiling/remote-config.js +354 -0
  132. package/packages/dd-trace/src/profiling/runtime-capabilities.js +11 -0
  133. package/packages/dd-trace/src/propagation-hash/index.js +7 -0
  134. package/packages/dd-trace/src/proxy.js +13 -1
  135. package/vendor/dist/@opentelemetry/core/LICENSE +11 -0
  136. package/vendor/dist/@opentelemetry/core/index.js +1 -1
  137. package/vite.d.ts +7 -0
  138. package/vite.js +3 -0
  139. package/lambda.d.ts +0 -39
  140. package/lambda.js +0 -3
  141. package/packages/datadog-plugin-cypress/src/support.js +0 -1348
@@ -6,6 +6,18 @@ const log = require('./log')
6
6
 
7
7
  const configUpdateChannel = dc.channel('datadog:config:update')
8
8
 
9
+ // The profiler reads these settings at startup, regardless of which RC product supplies them.
10
+ const RESTART_SETTINGS = /** @type {const} */ ([
11
+ 'DD_PROFILING_CPU_ENABLED',
12
+ 'DD_PROFILING_WALLTIME_ENABLED',
13
+ 'DD_PROFILING_HEAP_ENABLED',
14
+ 'DD_PROFILING_ALLOCATION_ENABLED',
15
+ 'DD_PROFILING_UPLOAD_PERIOD',
16
+ ])
17
+
18
+ /** @type {ReturnType<typeof getRemotelyConfigurableSettings> | undefined} */
19
+ let startedSettings
20
+
9
21
  /** @type {import('./profiling/ssi-heuristics').SSIHeuristics | undefined} */
10
22
  let activeSSIHeuristics
11
23
 
@@ -20,6 +32,9 @@ let profilingModule
20
32
  */
21
33
  let deferredConfig
22
34
 
35
+ // The profiler is stopping to apply new settings, not to stay disabled.
36
+ let restartPending = false
37
+
23
38
  function getProfilingModule () {
24
39
  if (profilingModule === undefined) {
25
40
  profilingModule = require('./profiling')
@@ -38,6 +53,16 @@ function isStarted () {
38
53
  return profilingModule !== undefined && profilingModule.profiler.enabled
39
54
  }
40
55
 
56
+ /**
57
+ * Types of the running profilers (see the profiling layer's getRunningTypes()). Like isStarted(),
58
+ * this doesn't load the profiling engine just to answer.
59
+ *
60
+ * @returns {string[]}
61
+ */
62
+ function getRunningProfileTypes () {
63
+ return profilingModule?.profiler.getRunningTypes() ?? []
64
+ }
65
+
41
66
  // A stopped profiler still exports one final profile, and until that settles it reports neither
42
67
  // the state a decision would be based on nor any willingness to start again.
43
68
  function isStopping () {
@@ -62,6 +87,7 @@ function disableSSIHeuristics () {
62
87
  * @param {import('./config/config-base')} config - Tracer configuration
63
88
  */
64
89
  function start (config) {
90
+ startedSettings = getRemotelyConfigurableSettings(config)
65
91
  try {
66
92
  // Forward the full tracer config to the profiling layer.
67
93
  // Profiling code is responsible for deriving the specific options it needs.
@@ -79,6 +105,7 @@ function stop () {
79
105
  // An explicit stop is the latest desired state, so it retracts a configuration still waiting
80
106
  // for an in-flight shutdown to settle.
81
107
  deferredConfig = undefined
108
+ restartPending = false
82
109
 
83
110
  // A stop command for a profiler that has never been loaded is already satisfied.
84
111
  if (profilingModule === undefined) return
@@ -115,35 +142,70 @@ function runWithLabels (labels, fn) {
115
142
  return getProfilingModule().profiler.runWithLabels(labels, fn)
116
143
  }
117
144
 
145
+ /**
146
+ * @param {import('./config/config-base')} config - Tracer configuration
147
+ */
148
+ function getRemotelyConfigurableSettings (config) {
149
+ return RESTART_SETTINGS.map(name => config[name])
150
+ }
151
+
152
+ /**
153
+ * Settings are read at startup, so changes require a restart and may leave a profile gap.
154
+ *
155
+ * @param {import('./config/config-base')} config - Tracer configuration
156
+ */
157
+ function restartIfSettingsChanged (config) {
158
+ const settings = getRemotelyConfigurableSettings(config)
159
+ if (settings.every((value, index) => value === startedSettings?.[index])) return
160
+
161
+ log.debug('Restarting the profiler to apply changed settings')
162
+ stop()
163
+ if (isStopping()) {
164
+ // The 'stopped' event applies the config after the final export.
165
+ deferredConfig = config
166
+ restartPending = true
167
+ } else {
168
+ start(config)
169
+ }
170
+ }
171
+
118
172
  function applyDeferredConfig () {
119
173
  const config = deferredConfig
120
174
  if (config === undefined) return
121
175
  deferredConfig = undefined
122
- applyConfig(config)
176
+ const restarting = restartPending
177
+ restartPending = false
178
+ applyConfig(config, restarting)
123
179
  }
124
180
 
125
181
  /**
126
182
  * @param {import('./config/config-base')} config - Tracer configuration
183
+ * @param {boolean} [restarting] - Resume a run stopped for a settings change
127
184
  */
128
- function applyConfig (config) {
185
+ function applyConfig (config, restarting = false) {
129
186
  const enabled = config.profiling.DD_PROFILING_ENABLED
130
187
  if (enabled === 'true') {
131
188
  // A non-auto value means the SSI heuristics no longer get a say; disable them so a trigger that
132
189
  // fires after this publish can't start the profiler behind this decision's back.
133
190
  disableSSIHeuristics()
134
- // Leave an already-running profiler alone; otherwise an unrelated remote-config publish
135
- // (e.g. an unrelated sampling-rate change) would restart it on every update.
136
- if (!isStarted()) start(config)
191
+ // Unrelated config updates must not restart the profiler.
192
+ if (isStarted()) {
193
+ restartIfSettingsChanged(config)
194
+ } else {
195
+ start(config)
196
+ }
137
197
  } else if (enabled === 'false') {
138
198
  disableSSIHeuristics()
139
199
  stop()
140
200
  } else if (enabled === 'auto') {
141
- if (!isStarted() && !activeSSIHeuristics) {
142
- // 'auto' defers the start decision to SSI heuristics. A running profiler already reflects a
143
- // decision that was made (by SSI or a prior unconditional enablement), so leave it alone
144
- // rather than stopping and re-enabling it on every subsequent config publication. Also guard
145
- // against creating another active instance; each SSIHeuristics instance owns listeners and a
146
- // timer until the heuristic makes its decision or is explicitly disabled.
201
+ // A running or restarting profiler has already passed the start decision; don't
202
+ // re-run SSI heuristics on config updates.
203
+ if (isStarted()) {
204
+ restartIfSettingsChanged(config)
205
+ } else if (restarting) {
206
+ start(config)
207
+ } else if (!activeSSIHeuristics) {
208
+ // Reuse active heuristics; each instance owns listeners and a timer.
147
209
  const { SSIHeuristics } = getSSIHeuristicsModule()
148
210
  const heuristics = new SSIHeuristics(config)
149
211
  activeSSIHeuristics = heuristics
@@ -182,4 +244,4 @@ configUpdateChannel.subscribe((config) => {
182
244
 
183
245
  globalThis[Symbol.for('dd-trace')].beforeExitHandlers.add(stop)
184
246
 
185
- module.exports = { isStarted, start, stop, setCustomLabelKeys, runWithLabels }
247
+ module.exports = { isStarted, getRunningProfileTypes, start, stop, setCustomLabelKeys, runWithLabels }
@@ -1,6 +1,7 @@
1
1
  'use strict'
2
2
 
3
3
  const { EventEmitter } = require('events')
4
+ const { setImmediate: yieldToEventLoop } = require('node:timers/promises')
4
5
  const dc = require('dc-polyfill')
5
6
  const crashtracker = require('../crashtracking')
6
7
  const log = require('../log')
@@ -94,6 +95,24 @@ class Profiler extends EventEmitter {
94
95
  return this.#stopping !== undefined
95
96
  }
96
97
 
98
+ /**
99
+ * Types of the running profilers (e.g. 'wall', 'space', 'events'), plus 'cpu' when the wall
100
+ * profiler also collects CPU time and 'allocations' when the space profiler also collects
101
+ * allocations. Empty while the profiler isn't running.
102
+ *
103
+ * @returns {string[]}
104
+ */
105
+ getRunningTypes () {
106
+ if (!this.#enabled) return []
107
+ const types = []
108
+ for (const profiler of this.#profilers) {
109
+ types.push(profiler.type)
110
+ if (profiler.collectsCpuTime) types.push('cpu')
111
+ if (profiler.collectsAllocations) types.push('allocations')
112
+ }
113
+ return types
114
+ }
115
+
97
116
  /**
98
117
  * Declares the set of custom label keys that will be used with
99
118
  * {@link runWithLabels}. This is used for profile upload metadata and
@@ -424,7 +443,7 @@ class Profiler extends EventEmitter {
424
443
  const compressionFn = this.#getCompressionFn()
425
444
 
426
445
  // encode and export asynchronously
427
- await Promise.all(profiles.map(async ({ profiler, profile, info }) => {
446
+ const encodeProfile = async ({ profiler, profile, info }) => {
428
447
  try {
429
448
  const encoded = await profiler.encode(profile)
430
449
  const compressed = encoded instanceof Buffer && compressionFn !== undefined
@@ -448,7 +467,16 @@ class Profiler extends EventEmitter {
448
467
  // encode and submit the other profile types.
449
468
  log.error(error)
450
469
  }
451
- }))
470
+ }
471
+
472
+ const encodings = []
473
+ for (const profile of profiles) {
474
+ // Separate synchronous encoder prefixes without waiting for compression/export to finish.
475
+ // eslint-disable-next-line no-await-in-loop -- Encoder starts must yield, not their entire async tasks.
476
+ await yieldToEventLoop()
477
+ encodings.push(encodeProfile(profile))
478
+ }
479
+ await Promise.all(encodings)
452
480
 
453
481
  if (hasEncoded) {
454
482
  await this.#submit(encodedProfiles, infos, startDate, endDate, snapshotTags, snapshotKind)
@@ -17,6 +17,7 @@ const STACK_DEPTH = 64
17
17
  const identityRefreshChannel = channel('datadog:identity:refresh')
18
18
 
19
19
  class NativeSpaceProfiler {
20
+ collectsAllocations = false
20
21
  #config
21
22
  #exporters
22
23
  #identityRefreshListener
@@ -46,7 +47,8 @@ class NativeSpaceProfiler {
46
47
 
47
48
  this.#mapper = mapper
48
49
  this.#pprof = require('@datadog/pprof')
49
- this.#pprof.heap.start(this.#samplingInterval, STACK_DEPTH, this.#config.DD_PROFILING_ALLOCATION_ENABLED)
50
+ this.collectsAllocations = this.#config.DD_PROFILING_ALLOCATION_ENABLED
51
+ this.#pprof.heap.start(this.#samplingInterval, STACK_DEPTH, this.collectsAllocations)
50
52
 
51
53
  if (this.#config.DD_PROFILING_EXPERIMENTAL_OOM_MONITORING_ENABLED) {
52
54
  const config = this.#config
@@ -64,7 +64,7 @@ class NativeWallProfiler {
64
64
  #captureSpanData = false
65
65
  #codeHotspotsEnabled = false
66
66
  #contextCountGaugeUpdater
67
- #cpuProfilingEnabled = false
67
+ collectsCpuTime = false
68
68
  #currentContext
69
69
  #customLabelsActive = false
70
70
  #customLabelKeys
@@ -96,7 +96,7 @@ class NativeWallProfiler {
96
96
  constructor (config, { asyncContextFrameEnabled, flushInterval }) {
97
97
  this.#asyncContextFrameEnabled = asyncContextFrameEnabled
98
98
  this.#codeHotspotsEnabled = config.DD_PROFILING_CODEHOTSPOTS_ENABLED
99
- this.#cpuProfilingEnabled = config.DD_PROFILING_CPU_ENABLED
99
+ this.collectsCpuTime = config.DD_PROFILING_CPU_ENABLED
100
100
  this.#endpointCollectionEnabled = config.DD_PROFILING_ENDPOINT_COLLECTION_ENABLED
101
101
  this.#flushIntervalMillis = flushInterval
102
102
  this.#samplingIntervalMicros = SAMPLING_INTERVAL * 1000
@@ -111,7 +111,7 @@ class NativeWallProfiler {
111
111
  // capturing span data or timeline is enabled (so we need sample timestamps, and for now
112
112
  // timestamps require the sample contexts feature in the pprof wall profiler), or
113
113
  // cpu profiling is enabled.
114
- this.#withContexts = this.#captureSpanData || this.#timelineEnabled || this.#cpuProfilingEnabled
114
+ this.#withContexts = this.#captureSpanData || this.#timelineEnabled || this.collectsCpuTime
115
115
  }
116
116
 
117
117
  codeHotspotsEnabled () {
@@ -130,7 +130,7 @@ class NativeWallProfiler {
130
130
  kSampleCount = this.#pprof.time.constants.kSampleCount
131
131
 
132
132
  this.#pprof.time.start({
133
- collectCpuTime: this.#cpuProfilingEnabled,
133
+ collectCpuTime: this.collectsCpuTime,
134
134
  columnNumbers: 'emit',
135
135
  durationMillis: this.#flushIntervalMillis,
136
136
  intervalMicros: this.#samplingIntervalMicros,
@@ -0,0 +1,354 @@
1
+ 'use strict'
2
+
3
+ const { normalizeService } = require('../config/normalize-service')
4
+ const applyRemoteConfig = require('../config/remote-config-layers')
5
+ const log = require('../log')
6
+ const { allocationProfilingAvailable, cpuProfilingAvailable } = require('./runtime-capabilities')
7
+
8
+ const PRODUCT = 'APM_PROFILING'
9
+
10
+ /** @typedef {'cpuTime' | 'wallTime' | 'heapSize' | 'heapObjects' | 'allocations'} ProfileType */
11
+
12
+ // Keep every mapped profile type here; parsing is derived from this list. Profile types Node.js
13
+ // can't collect, like locks and exceptions, are ignored. So are CPU time and allocations where this
14
+ // runtime can't collect them, as the tracer configuration would turn them off again.
15
+ const PROFILE_TYPES = /** @type {ProfileType[]} */ (['wallTime', 'heapSize', 'heapObjects'])
16
+ if (cpuProfilingAvailable) PROFILE_TYPES.unshift('cpuTime')
17
+ if (allocationProfilingAvailable) PROFILE_TYPES.push('allocations')
18
+
19
+ // Profile types collected by the heap profiler.
20
+ const HEAP_PROFILE_TYPES = /** @type {ProfileType[]} */ (['heapSize', 'heapObjects', 'allocations'])
21
+
22
+ // Running profiler types (see the profiling layer's getRunningTypes()) by the profile types they serve.
23
+ const PROFILE_TYPES_BY_RUNNING_TYPE = /** @type {Record<string, ProfileType[]>} */ ({
24
+ cpu: ['cpuTime'],
25
+ wall: ['wallTime'],
26
+ space: ['heapSize', 'heapObjects'],
27
+ allocations: ['allocations'],
28
+ })
29
+
30
+ // Specificity levels of a target, from least to most specific, following the profiling Remote
31
+ // Config payload merging ADR: other tags < env < service < workload < container name < pod <
32
+ // container ID. Infrastructure levels are recognized by the tag names the Datadog agent assigns.
33
+ const LEVEL_OTHER_TAGS = 1
34
+ const LEVEL_ENV = 2
35
+ const LEVEL_SERVICE = 3
36
+ /** @type {Map<string, number>} */
37
+ const LEVEL_BY_TAG_NAME = new Map()
38
+ for (const [level, names] of /** @type {[number, string[]][]} */ ([
39
+ [4, ['kube_deployment', 'kube_replica_set', 'kube_stateful_set', 'kube_daemon_set', 'kube_job', 'kube_cronjob',
40
+ 'kube_argo_rollout', 'oshift_deployment', 'task_family']],
41
+ [5, ['kube_container_name', 'container_name', 'ecs_container_name']],
42
+ [6, ['pod_name', 'task_arn']],
43
+ [7, ['container_id']],
44
+ ])) {
45
+ for (const name of names) LEVEL_BY_TAG_NAME.set(name, level)
46
+ }
47
+ // A target's level outranks any number of conditions, which only break ties within a level.
48
+ const CONDITIONS_PER_LEVEL = 1000
49
+
50
+ /**
51
+ * @typedef {ReturnType<import('../config')>} Config
52
+ * @typedef {Partial<Record<ProfileType, boolean>>} RequestedProfilers
53
+ * @typedef {{ service?: string, env?: string, tags: string[] }} Target
54
+ * @typedef {{
55
+ * id: string,
56
+ * profilers: RequestedProfilers,
57
+ * targets: Target[],
58
+ * }} ProfilingConfig
59
+ */
60
+
61
+ /**
62
+ * Apply matching profiling configs; omitted fields use local settings.
63
+ *
64
+ * @param {import('../remote_config')} rc - RemoteConfig instance
65
+ * @param {Config} config - Tracer configuration
66
+ * @param {() => string[]} getRunningProfileTypes - Types of the running profilers
67
+ */
68
+ function enable (rc, config, getRunningProfileTypes) {
69
+ // The libdatadog fetcher used in agentless mode doesn't know APM_PROFILING yet, and would log an
70
+ // error for it.
71
+ if (config.DD_AGENTLESS_ENABLED) return
72
+
73
+ /** @type {Map<string, ProfilingConfig>} */
74
+ const configs = new Map()
75
+ // Match the initially empty profiling layer.
76
+ let lastSettings = 'null'
77
+ /**
78
+ * Profile types running under local configuration, captured before the first profiling content
79
+ * is applied. Known limitations: a profiler that SSI heuristics start later, or that APM_TRACING
80
+ * enabled earlier, is not told apart from local configuration.
81
+ *
82
+ * @type {Set<string> | undefined}
83
+ */
84
+ let localProfileTypes
85
+
86
+ rc.subscribeProducts(PRODUCT)
87
+ rc.setBatchHandler([PRODUCT], (transaction) => {
88
+ for (const item of transaction.toUnapply) {
89
+ configs.delete(item.id)
90
+ transaction.ack(item.path)
91
+ }
92
+
93
+ for (const item of [...transaction.toApply, ...transaction.toModify]) {
94
+ /** @type {string[]} */
95
+ const problems = []
96
+ const parsed = parse(item.id, item.file, problems)
97
+ if (parsed === undefined) {
98
+ configs.delete(item.id)
99
+ } else {
100
+ configs.set(item.id, parsed)
101
+ }
102
+
103
+ if (problems.length === 0) {
104
+ transaction.ack(item.path)
105
+ } else {
106
+ // Report partial failures while still applying valid fields.
107
+ const reason = problems.join('; ')
108
+ log.debug('[profiling/remote-config] Invalid profiling configuration %s: %s', item.id, reason)
109
+ transaction.error(item.path, reason)
110
+ }
111
+ }
112
+
113
+ // Skip unchanged settings to avoid redundant telemetry and config publishes.
114
+ // toSettings inserts keys in a fixed order, making JSON equality stable.
115
+ const merged = merge(configs.values(), config)
116
+ if (configs.size > 0) {
117
+ localProfileTypes ??= toProfileTypes(getRunningProfileTypes())
118
+ }
119
+ const settings = toSettings(merged, localProfileTypes ?? new Set())
120
+ const serialized = JSON.stringify(settings)
121
+ if (serialized === lastSettings) return
122
+ lastSettings = serialized
123
+
124
+ applyRemoteConfig(config, PRODUCT, settings)
125
+ })
126
+ }
127
+
128
+ /**
129
+ * @param {string} id - Remote config id
130
+ * @param {unknown} file - Remote config payload
131
+ * @param {string[]} problems - Validation errors to report
132
+ * @returns {ProfilingConfig | undefined} undefined for payloads without profiling content or with
133
+ * invalid targets
134
+ */
135
+ function parse (id, file, problems) {
136
+ if (!isObject(file)) {
137
+ problems.push('payload is not an object')
138
+ return
139
+ }
140
+
141
+ const { profilers, settings, targets } = file
142
+ if (profilers === undefined && settings === undefined) return
143
+
144
+ const parsedTargets = parseTargets(targets, problems)
145
+ if (parsedTargets === undefined) return
146
+
147
+ const parsedProfilers = parseProfilers(profilers, problems)
148
+ if (settings !== undefined && !isObject(settings)) problems.push('settings is not an object')
149
+ return { id, profilers: parsedProfilers, targets: parsedTargets }
150
+ }
151
+
152
+ /**
153
+ * @param {unknown} profilers - The payload's `profilers` section
154
+ * @param {string[]} problems - Validation errors to report
155
+ * @returns {RequestedProfilers}
156
+ */
157
+ function parseProfilers (profilers, problems) {
158
+ /** @type {RequestedProfilers} */
159
+ const parsed = {}
160
+ if (!isObject(profilers)) {
161
+ if (profilers !== undefined) problems.push('profilers is not an object')
162
+ return parsed
163
+ }
164
+ for (const type of PROFILE_TYPES) {
165
+ const value = profilers[type]
166
+ if (typeof value === 'boolean') {
167
+ parsed[type] = value
168
+ } else if (value !== undefined) {
169
+ problems.push(`profilers.${type} is not a boolean`)
170
+ }
171
+ }
172
+ return parsed
173
+ }
174
+
175
+ /**
176
+ * @param {unknown} targets - The payload's `targets` section
177
+ * @param {string[]} problems - Validation errors to report
178
+ * @returns {Target[] | undefined} undefined if the config must be dropped
179
+ */
180
+ function parseTargets (targets, problems) {
181
+ if (targets === undefined) return []
182
+ if (!Array.isArray(targets)) {
183
+ problems.push('targets is not an array')
184
+ return
185
+ }
186
+
187
+ /** @type {Target[]} */
188
+ const parsed = []
189
+ for (let index = 0; index < targets.length; index++) {
190
+ const target = targets[index]
191
+ const { service, env, tags = [] } = isObject(target) ? target : {}
192
+ if (!isObject(target) ||
193
+ (service !== undefined && typeof service !== 'string') ||
194
+ (env !== undefined && typeof env !== 'string') ||
195
+ !Array.isArray(tags) || !tags.every(tag => typeof tag === 'string')) {
196
+ problems.push(`targets[${index}] is invalid`)
197
+ continue
198
+ }
199
+ parsed.push({ service, env, tags })
200
+ }
201
+
202
+ // Reject an all-invalid target list rather than treating it as untargeted.
203
+ if (parsed.length === 0 && targets.length !== 0) {
204
+ problems.push('no valid targets')
205
+ return
206
+ }
207
+ return parsed
208
+ }
209
+
210
+ /**
211
+ * Merge the received configs field by field, with more specific targets winning. Remote Config only
212
+ * delivers configs that apply to this tracer, so every config is merged; targets only rank them.
213
+ *
214
+ * @param {Iterable<ProfilingConfig>} configs - Parsed remote configs
215
+ * @param {Config} config - Tracer configuration
216
+ */
217
+ function merge (configs, config) {
218
+ /** @type {{ specificity: number, config: ProfilingConfig }[]} */
219
+ const ranked = []
220
+ for (const profilingConfig of configs) {
221
+ ranked.push({ specificity: getSpecificity(profilingConfig.targets, config), config: profilingConfig })
222
+ }
223
+ // Merge least specific first; break ties by ID so delivery order doesn't matter.
224
+ ranked.sort((a, b) => a.specificity - b.specificity || (a.config.id < b.config.id ? -1 : 1))
225
+
226
+ /** @type {RequestedProfilers} */
227
+ const profilers = {}
228
+ for (const { config: profilingConfig } of ranked) {
229
+ Object.assign(profilers, profilingConfig.profilers)
230
+ }
231
+ return profilers
232
+ }
233
+
234
+ /**
235
+ * Specificity of the most specific target that is consistent with this tracer's service and env,
236
+ * or 0 if there is none. A config's targets can name several scopes, and the one it was delivered
237
+ * for has to be consistent with them. Tag conditions are assumed to hold: the agent has matched
238
+ * them, and the tracer doesn't know every tag it's matched by (e.g. Kubernetes tags).
239
+ *
240
+ * A target ranks by its most specific condition, and then by its number of conditions.
241
+ *
242
+ * @param {Target[]} targets - Targets of one config
243
+ * @param {Config} config - Tracer configuration
244
+ */
245
+ function getSpecificity (targets, config) {
246
+ let specificity = 0
247
+ for (const { service, env, tags } of targets) {
248
+ const hasService = service !== undefined && service !== '*'
249
+ const hasEnv = env !== undefined && env !== '*'
250
+ // The agent and the backend match normalized values, so compare normalized values too.
251
+ if ((hasService && normalizeService(service) !== normalizeService(config.service)) ||
252
+ (hasEnv && normalizeService(env) !== normalizeService(config.env))) {
253
+ continue
254
+ }
255
+
256
+ let level = 0
257
+ if (hasService) level = LEVEL_SERVICE
258
+ else if (hasEnv) level = LEVEL_ENV
259
+ for (const tag of tags) {
260
+ const separator = tag.indexOf(':')
261
+ const name = (separator === -1 ? tag : tag.slice(0, separator)).toLowerCase()
262
+ level = Math.max(level, LEVEL_BY_TAG_NAME.get(name) ?? LEVEL_OTHER_TAGS)
263
+ }
264
+ const conditions = Number(hasService) + Number(hasEnv) + tags.length
265
+ specificity = Math.max(specificity, level * CONDITIONS_PER_LEVEL + conditions)
266
+ }
267
+ return specificity
268
+ }
269
+
270
+ /**
271
+ * @param {string[]} runningTypes - Types of the running profilers
272
+ * @returns {Set<string>} The profile types they serve
273
+ */
274
+ function toProfileTypes (runningTypes) {
275
+ const profileTypes = new Set()
276
+ for (const runningType of runningTypes) {
277
+ const served = PROFILE_TYPES_BY_RUNNING_TYPE[runningType]
278
+ if (served === undefined) continue
279
+ for (const profileType of served) {
280
+ profileTypes.add(profileType)
281
+ }
282
+ }
283
+ return profileTypes
284
+ }
285
+
286
+ /**
287
+ * Map payload fields to profiling environment variables.
288
+ *
289
+ * @param {RequestedProfilers} requested - Profile types requested by the merged remote configs
290
+ * @param {Set<string>} localProfileTypes - Profile types running under local configuration
291
+ * @returns {Partial<Record<import('../config/helper').SupportedEnvKey, string>> | null} null if no fields are set
292
+ */
293
+ function toSettings (requested, localProfileTypes) {
294
+ if (PROFILE_TYPES.every(type => requested[type] === undefined)) return null
295
+
296
+ // Turning profiling on also starts every profile type that is on by default, so omitted types
297
+ // that weren't running locally are turned off; omitted types that were keep their local value.
298
+ /** @type {RequestedProfilers} */
299
+ const profilers = { ...requested }
300
+ const enablesProfiling = PROFILE_TYPES.some(type => requested[type] === true)
301
+ if (enablesProfiling) {
302
+ for (const type of PROFILE_TYPES) {
303
+ if (profilers[type] === undefined && !localProfileTypes.has(type)) profilers[type] = false
304
+ }
305
+ }
306
+ const { cpuTime, wallTime, heapSize, heapObjects, allocations } = profilers
307
+ // A profile type is on when requested, or when omitted and running locally. A type that is on
308
+ // keeps the profiler that collects it running, even if the payload turns another type of that
309
+ // profiler off.
310
+ /** @param {ProfileType} type */
311
+ const isOn = type => profilers[type] ?? localProfileTypes.has(type)
312
+
313
+ /** @type {Partial<Record<import('../config/helper').SupportedEnvKey, string>>} */
314
+ const envs = {}
315
+ // The wall profiler also samples CPU time.
316
+ if (wallTime || cpuTime) {
317
+ envs.DD_PROFILING_WALLTIME_ENABLED = 'true'
318
+ } else if (wallTime === false && !isOn('cpuTime')) {
319
+ envs.DD_PROFILING_WALLTIME_ENABLED = 'false'
320
+ }
321
+ if (cpuTime !== undefined) {
322
+ envs.DD_PROFILING_CPU_ENABLED = String(cpuTime)
323
+ }
324
+ // The heap profiler collects heap sizes, live objects and, in allocation mode, allocations.
325
+ if (heapSize || heapObjects || allocations) {
326
+ envs.DD_PROFILING_HEAP_ENABLED = 'true'
327
+ } else if ((heapSize === false || heapObjects === false) && !HEAP_PROFILE_TYPES.some(isOn)) {
328
+ envs.DD_PROFILING_HEAP_ENABLED = 'false'
329
+ }
330
+ if (allocations !== undefined) {
331
+ envs.DD_PROFILING_ALLOCATION_ENABLED = String(allocations)
332
+ }
333
+
334
+ // Any true enables profiling, and no type left on disables it; otherwise use the local setting.
335
+ if (enablesProfiling) {
336
+ envs.DD_PROFILING_ENABLED = 'true'
337
+ } else if (!PROFILE_TYPES.some(isOn)) {
338
+ envs.DD_PROFILING_ENABLED = 'false'
339
+ }
340
+
341
+ return envs
342
+ }
343
+
344
+ /**
345
+ * @param {unknown} value
346
+ * @returns {value is Record<string, unknown>}
347
+ */
348
+ function isObject (value) {
349
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
350
+ }
351
+
352
+ module.exports = {
353
+ enable,
354
+ }
@@ -0,0 +1,11 @@
1
+ 'use strict'
2
+
3
+ const { NODE_MAJOR } = require('../../../../version')
4
+
5
+ // Profiling features that depend on the runtime. The tracer configuration turns them off where
6
+ // they're unavailable, and remote configuration ignores requests for the profile types they collect.
7
+ module.exports = {
8
+ // Allocation profiling needs a sampling hook only available on Node.js 26+.
9
+ allocationProfilingAvailable: NODE_MAJOR >= 26,
10
+ cpuProfilingAvailable: process.platform !== 'win32',
11
+ }
@@ -47,6 +47,13 @@ class PropagationHashManager {
47
47
  }
48
48
  }
49
49
 
50
+ /**
51
+ * @returns {string | null} The container tags hash the agent last reported, if any
52
+ */
53
+ getContainerTagsHash () {
54
+ return this._containerTagsHash
55
+ }
56
+
50
57
  /**
51
58
  * Get the propagation hash as a BigInt
52
59
  * @returns {bigint | null} The propagation hash or null if disabled/unavailable
@@ -209,6 +209,9 @@ class Tracer extends NoopProxy {
209
209
  this.#updateDebugger(config, rc)
210
210
  })
211
211
 
212
+ // Subscribe even when profiling is off so RC can enable it.
213
+ require('./profiling/remote-config').enable(rc, config, profiler.getRunningProfileTypes)
214
+
212
215
  rc.setProductHandler('AGENT_CONFIG', (action, conf) => {
213
216
  if (!conf?.name?.startsWith('flare-log-level.')) return
214
217
 
@@ -338,6 +341,16 @@ class Tracer extends NoopProxy {
338
341
  log.error(BUNDLED_OPENSSL_WARNING)
339
342
  }
340
343
 
344
+ // Load code before the image snapshot; identity and metadata storage stay in /run.
345
+ const storeTracerMetadata = require('./tracer_metadata')
346
+ if (config.DD_TRACE_ENABLED) {
347
+ try {
348
+ require('@datadog/libdatadog-extras').maybeLoad('process-discovery')
349
+ } catch {
350
+ // Native metadata is optional; /run retains its existing availability handling.
351
+ }
352
+ }
353
+
341
354
  const ch = channel('http.server.request.start')
342
355
 
343
356
  const onHttpRequest = ({ request }) => {
@@ -347,7 +360,6 @@ class Tracer extends NoopProxy {
347
360
  reseed()
348
361
  channel('datadog:identity:update').publish(config)
349
362
  if (this._tracingInitialized) {
350
- const storeTracerMetadata = require('./tracer_metadata')
351
363
  const metadata = storeTracerMetadata(config)
352
364
  if (metadata === undefined) {
353
365
  log.warn('Could not store tracer configuration for service discovery')