dd-trace 5.136.0 → 5.138.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 (190) 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/index.d.ts +56 -0
  8. package/initialize.mjs +5 -3
  9. package/package.json +36 -32
  10. package/packages/datadog-esbuild/index.js +8 -15
  11. package/packages/datadog-esbuild/src/log.js +2 -29
  12. package/packages/datadog-instrumentations/src/ai.js +88 -122
  13. package/packages/datadog-instrumentations/src/aws-lambda.js +9 -0
  14. package/packages/datadog-instrumentations/src/cypress-config.js +20 -9
  15. package/packages/datadog-instrumentations/src/helpers/bundler-esm-exports.js +23 -1
  16. package/packages/datadog-instrumentations/src/helpers/bundler-log.js +38 -0
  17. package/packages/datadog-instrumentations/src/helpers/bundler-transform.js +9 -6
  18. package/packages/datadog-instrumentations/src/helpers/fetch.js +51 -6
  19. package/packages/datadog-instrumentations/src/helpers/hooks.js +0 -1
  20. package/packages/datadog-instrumentations/src/helpers/instrument.js +1 -3
  21. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +6 -0
  22. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +12 -1
  23. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/ai.js +2 -0
  24. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql-jit.js +5 -3
  25. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-client.js +30 -0
  26. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-server.js +23 -0
  27. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/next.js +21 -0
  28. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/postgres.js +33 -4
  29. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +30 -0
  30. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +6 -0
  31. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms/postgres.js +122 -0
  32. package/packages/datadog-instrumentations/src/microgateway-core.js +1 -2
  33. package/packages/datadog-instrumentations/src/modelcontextprotocol-client.js +21 -0
  34. package/packages/datadog-instrumentations/src/modelcontextprotocol-sdk.js +32 -2
  35. package/packages/datadog-instrumentations/src/modelcontextprotocol-server.js +43 -0
  36. package/packages/datadog-instrumentations/src/next.js +184 -20
  37. package/packages/datadog-instrumentations/src/path-to-regexp.js +11 -11
  38. package/packages/datadog-instrumentations/src/router.js +52 -13
  39. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +1 -1
  40. package/packages/datadog-instrumentations/src/vitest-main.js +10 -2
  41. package/packages/datadog-plugin-aws-lambda/src/arn.js +41 -0
  42. package/packages/datadog-plugin-aws-lambda/src/context/events.js +167 -0
  43. package/packages/datadog-plugin-aws-lambda/src/context/extractor.js +153 -0
  44. package/packages/datadog-plugin-aws-lambda/src/context/http.js +50 -0
  45. package/packages/datadog-plugin-aws-lambda/src/context/span-context.js +26 -0
  46. package/packages/datadog-plugin-aws-lambda/src/context/step-functions.js +142 -0
  47. package/packages/datadog-plugin-aws-lambda/src/context/types.d.ts +17 -0
  48. package/packages/datadog-plugin-aws-lambda/src/context/xray.js +67 -0
  49. package/packages/datadog-plugin-aws-lambda/src/event-type-guards.js +170 -0
  50. package/packages/datadog-plugin-aws-lambda/src/index.js +52 -4
  51. package/packages/datadog-plugin-aws-lambda/src/trigger.js +339 -0
  52. package/packages/datadog-plugin-aws-sdk/src/services/dynamodb.js +7 -0
  53. package/packages/datadog-plugin-aws-sdk/src/services/kinesis.js +32 -10
  54. package/packages/datadog-plugin-aws-sdk/src/services/lambda.js +10 -1
  55. package/packages/datadog-plugin-aws-sdk/src/services/sqs.js +4 -0
  56. package/packages/datadog-plugin-aws-sdk/src/services/stepfunctions.js +3 -0
  57. package/packages/datadog-plugin-azure-functions/src/index.js +68 -12
  58. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +30 -4
  59. package/packages/datadog-plugin-cypress/src/support.mjs +1353 -0
  60. package/packages/datadog-plugin-express/src/code_origin.js +2 -2
  61. package/packages/datadog-plugin-fastify/src/code_origin.js +2 -2
  62. package/packages/datadog-plugin-fetch/src/index.js +7 -0
  63. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +10 -0
  64. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +2 -0
  65. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +7 -0
  66. package/packages/datadog-plugin-google-cloud-pubsub/src/resource-names.js +24 -0
  67. package/packages/datadog-plugin-graphql/src/tools/transforms.js +1 -0
  68. package/packages/datadog-plugin-http/src/client.js +14 -1
  69. package/packages/datadog-plugin-http/src/server.js +18 -4
  70. package/packages/datadog-plugin-http2/src/client.js +2 -1
  71. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/tracing.js +28 -2
  72. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/utils.js +1 -0
  73. package/packages/datadog-plugin-mongodb-core/src/query.js +17 -1
  74. package/packages/datadog-plugin-postgres/src/index.js +118 -41
  75. package/packages/datadog-plugin-supabase/src/supabase-auth-js-gotrueclient-getuser.js +18 -8
  76. package/packages/datadog-plugin-supabase/src/supabase-functions-js-functionsclient-invoke.js +49 -13
  77. package/packages/datadog-plugin-supabase/src/supabase-storage-js-handle-request.js +34 -9
  78. package/packages/datadog-plugin-vitest/src/index.js +3 -2
  79. package/packages/datadog-plugin-ws/src/close.js +3 -5
  80. package/packages/datadog-plugin-ws/src/producer.js +1 -4
  81. package/packages/datadog-plugin-ws/src/receiver.js +3 -5
  82. package/packages/datadog-plugin-ws/src/server.js +44 -13
  83. package/packages/datadog-vite/index.js +537 -0
  84. package/packages/datadog-vite/src/log.js +5 -0
  85. package/packages/datadog-webpack/src/log.js +2 -29
  86. package/packages/dd-trace/src/aiguard/client.js +7 -9
  87. package/packages/dd-trace/src/aiguard/evaluation.js +7 -2
  88. package/packages/dd-trace/src/aiguard/index.js +1 -1
  89. package/packages/dd-trace/src/aiguard/integrations/index.js +6 -5
  90. package/packages/dd-trace/src/aiguard/messages/utils.js +2 -2
  91. package/packages/dd-trace/src/aiguard/sdk.js +7 -2
  92. package/packages/dd-trace/src/appsec/api_security/normalized-route.js +273 -167
  93. package/packages/dd-trace/src/appsec/blocking/index.js +17 -1
  94. package/packages/dd-trace/src/appsec/channels.js +8 -0
  95. package/packages/dd-trace/src/appsec/downstream_requests.js +105 -0
  96. package/packages/dd-trace/src/appsec/graphql.js +10 -13
  97. package/packages/dd-trace/src/appsec/handlers/auth.js +1 -3
  98. package/packages/dd-trace/src/appsec/handlers/http-request.js +60 -65
  99. package/packages/dd-trace/src/appsec/handlers/http-response.js +61 -7
  100. package/packages/dd-trace/src/appsec/handlers/payments.js +23 -27
  101. package/packages/dd-trace/src/appsec/iast/taint-tracking/plugin.js +21 -14
  102. package/packages/dd-trace/src/appsec/index.js +9 -0
  103. package/packages/dd-trace/src/appsec/lambda.js +17 -17
  104. package/packages/dd-trace/src/appsec/rasp/command_injection.js +4 -4
  105. package/packages/dd-trace/src/appsec/rasp/index.js +64 -3
  106. package/packages/dd-trace/src/appsec/rasp/lfi.js +2 -2
  107. package/packages/dd-trace/src/appsec/rasp/sql_injection.js +7 -17
  108. package/packages/dd-trace/src/appsec/rasp/ssrf.js +80 -16
  109. package/packages/dd-trace/src/appsec/rasp/utils.js +47 -3
  110. package/packages/dd-trace/src/appsec/recommended.json +70 -3
  111. package/packages/dd-trace/src/appsec/reporter.js +9 -0
  112. package/packages/dd-trace/src/appsec/sdk/set_user.js +3 -3
  113. package/packages/dd-trace/src/appsec/sdk/track_event.js +4 -4
  114. package/packages/dd-trace/src/appsec/sdk/user_blocking.js +1 -1
  115. package/packages/dd-trace/src/appsec/user_tracking.js +6 -8
  116. package/packages/dd-trace/src/appsec/waf/index.js +65 -6
  117. package/packages/dd-trace/src/appsec/waf/waf_context_wrapper.js +33 -38
  118. package/packages/dd-trace/src/appsec/waf/waf_manager.js +18 -2
  119. package/packages/dd-trace/src/carrier.js +7 -1
  120. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/index.js +4 -2
  121. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/worker/index.js +31 -19
  122. package/packages/dd-trace/src/config/generated-config-types.d.ts +14 -5
  123. package/packages/dd-trace/src/config/index.js +73 -27
  124. package/packages/dd-trace/src/config/parsers.js +60 -0
  125. package/packages/dd-trace/src/config/remote-config-layers.js +38 -0
  126. package/packages/dd-trace/src/config/remote_config.js +2 -1
  127. package/packages/dd-trace/src/config/supported-configurations.json +41 -13
  128. package/packages/dd-trace/src/datastreams/fnv.js +27 -0
  129. package/packages/dd-trace/src/datastreams/http.js +57 -0
  130. package/packages/dd-trace/src/datastreams/index.js +24 -0
  131. package/packages/dd-trace/src/datastreams/pathway.js +142 -28
  132. package/packages/dd-trace/src/datastreams/processor.js +27 -7
  133. package/packages/dd-trace/src/debugger/config.js +1 -1
  134. package/packages/dd-trace/src/debugger/devtools_client/request-options.js +7 -9
  135. package/packages/dd-trace/src/debugger/devtools_client/send.js +1 -1
  136. package/packages/dd-trace/src/debugger/devtools_client/state.js +3 -1
  137. package/packages/dd-trace/src/debugger/devtools_client/tags.js +1 -1
  138. package/packages/dd-trace/src/debugger/index.js +2 -2
  139. package/packages/dd-trace/src/debugger/inspect-segment.js +3 -2
  140. package/packages/dd-trace/src/debugger/pause-duration-histogram.js +4 -1
  141. package/packages/dd-trace/src/debugger/probe_sampler.js +39 -17
  142. package/packages/dd-trace/src/debugger/unsupported-runtime.js +2 -0
  143. package/packages/dd-trace/src/git_metadata.js +2 -1
  144. package/packages/dd-trace/src/index.js +6 -3
  145. package/packages/dd-trace/src/lambda/facade.js +6 -5
  146. package/packages/dd-trace/src/lambda/handler-paths.js +1 -1
  147. package/packages/dd-trace/src/llmobs/constants/tags.js +1 -0
  148. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/index.js +86 -3
  149. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/utils.js +182 -1
  150. package/packages/dd-trace/src/llmobs/span_processor.js +3 -0
  151. package/packages/dd-trace/src/llmobs/tagger.js +9 -0
  152. package/packages/dd-trace/src/noop/span.js +0 -4
  153. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +3 -0
  154. package/packages/dd-trace/src/openfeature/configuration_source.js +20 -0
  155. package/packages/dd-trace/src/openfeature/flagging_provider.js +17 -0
  156. package/packages/dd-trace/src/opentelemetry/logs/otlp_transformer.js +2 -1
  157. package/packages/dd-trace/src/opentelemetry/metrics/otlp_transformer.js +2 -1
  158. package/packages/dd-trace/src/opentelemetry/otlp/otlp_transformer_base.js +16 -1
  159. package/packages/dd-trace/src/opentelemetry/trace/index.js +5 -4
  160. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +10 -6
  161. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +42 -26
  162. package/packages/dd-trace/src/opentracing/propagation/text_map.js +4 -4
  163. package/packages/dd-trace/src/plugin_manager.js +2 -0
  164. package/packages/dd-trace/src/plugins/ci_plugin.js +104 -9
  165. package/packages/dd-trace/src/plugins/index.js +2 -0
  166. package/packages/dd-trace/src/plugins/util/ci.js +34 -0
  167. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +9 -14
  168. package/packages/dd-trace/src/plugins/util/inferred_proxy.js +3 -5
  169. package/packages/dd-trace/src/plugins/util/test.js +28 -1
  170. package/packages/dd-trace/src/plugins/util/url.js +9 -6
  171. package/packages/dd-trace/src/plugins/util/user-provided-git.js +4 -4
  172. package/packages/dd-trace/src/process-tags/index.js +1 -1
  173. package/packages/dd-trace/src/profiler.js +74 -12
  174. package/packages/dd-trace/src/profiling/profiler.js +30 -2
  175. package/packages/dd-trace/src/profiling/profilers/space.js +3 -1
  176. package/packages/dd-trace/src/profiling/profilers/wall.js +4 -4
  177. package/packages/dd-trace/src/profiling/remote-config.js +354 -0
  178. package/packages/dd-trace/src/profiling/runtime-capabilities.js +11 -0
  179. package/packages/dd-trace/src/propagation-hash/index.js +7 -0
  180. package/packages/dd-trace/src/proxy.js +13 -1
  181. package/packages/dd-trace/src/register-loader.js +43 -0
  182. package/register.js +10 -44
  183. package/register.mjs +27 -0
  184. package/vendor/dist/@opentelemetry/core/LICENSE +11 -0
  185. package/vendor/dist/@opentelemetry/core/index.js +1 -1
  186. package/vite.d.ts +7 -0
  187. package/vite.js +3 -0
  188. package/lambda.d.ts +0 -39
  189. package/lambda.js +0 -3
  190. package/packages/datadog-plugin-cypress/src/support.js +0 -1348
@@ -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')
@@ -0,0 +1,43 @@
1
+ 'use strict'
2
+
3
+ // CommonJS and ESM preloads can both be used in the same process.
4
+ let registered = false
5
+
6
+ /**
7
+ * @param {typeof import('node:module').register | undefined} registerAsync
8
+ * @param {URL} parentURL
9
+ * @param {() => boolean | undefined} [tryRegisterSync] Returns undefined when sync hooks are unsupported.
10
+ */
11
+ function registerLoader (registerAsync, parentURL, tryRegisterSync) {
12
+ if (registered) return
13
+
14
+ let syncResult
15
+ let syncError
16
+ try {
17
+ syncResult = tryRegisterSync?.()
18
+ } catch (error) {
19
+ syncResult = false
20
+ syncError = error
21
+ }
22
+
23
+ if (syncResult) {
24
+ registered = true
25
+ return
26
+ }
27
+
28
+ if (syncResult === false) {
29
+ let message = 'dd-trace could not register synchronous loader hooks.'
30
+ if (registerAsync) message += ' Falling back to the asynchronous loader.'
31
+ if (syncError?.message) message += ` ${syncError.message}`
32
+ process.emitWarning(message)
33
+ }
34
+
35
+ // Node.js removes module.register in nodejs/node#67090.
36
+ if (registerAsync) {
37
+ const { getLoaderRegisterOptions } = require('./esm-module-load')
38
+ registerAsync('./loader-hook.mjs', parentURL, getLoaderRegisterOptions())
39
+ registered = true
40
+ }
41
+ }
42
+
43
+ module.exports = registerLoader
package/register.js CHANGED
@@ -4,48 +4,24 @@
4
4
 
5
5
  const { register } = require('node:module')
6
6
  const { pathToFileURL } = require('node:url')
7
- const { NODE_MAJOR, NODE_MINOR, NODE_PATCH } = require('./version')
8
-
9
- const parentURL = pathToFileURL(__filename)
10
- let isSyncLoaderRegistered = false
11
7
 
12
- if (shouldRegisterSyncLoaderHooks()) {
13
- let registerSyncLoaderHooks
14
- let syncRegistrationError
15
- try {
16
- ({ registerSyncLoaderHooks } = require('./loader-hook.mjs'))
17
- if (registerSyncLoaderHooks) {
18
- isSyncLoaderRegistered = registerSyncLoaderHooks()
19
- }
20
- } catch (error) {
21
- syncRegistrationError = error
22
- }
8
+ const registerLoader = require('./packages/dd-trace/src/register-loader')
9
+ const { NODE_MAJOR, NODE_MINOR, NODE_PATCH } = require('./version')
23
10
 
24
- if (!isSyncLoaderRegistered) {
25
- warnSyncLoaderFallback(syncRegistrationError)
26
- }
27
- }
11
+ registerLoader(register, pathToFileURL(__filename), tryRegisterSyncLoader)
28
12
 
29
- // `module.register` is removed in Node.js 27+ (nodejs/node#67090).
30
- if (!isSyncLoaderRegistered && register) {
31
- const { getLoaderRegisterOptions } = require('./packages/dd-trace/src/esm-module-load')
32
- register('./loader-hook.mjs', parentURL, getLoaderRegisterOptions())
33
- }
34
-
35
- function shouldRegisterSyncLoaderHooks () {
36
- if (!isSyncLoaderHookVersionSupported()) {
37
- return false
38
- }
13
+ function tryRegisterSyncLoader () {
14
+ if (!isSyncLoaderHookVersionSupported()) return
39
15
 
40
16
  try {
41
- return require('import-in-the-middle/create-hook.mjs').supportsSyncHooks()
17
+ if (!require('import-in-the-middle/create-hook.mjs').supportsSyncHooks()) return
42
18
  } catch (error) {
43
- if (error?.code !== 'ERR_REQUIRE_ESM') {
44
- warnSyncLoaderFallback(error)
45
- }
19
+ if (error?.code === 'ERR_REQUIRE_ESM') return
20
+ throw error
46
21
  }
47
22
 
48
- return false
23
+ const { registerSyncLoaderHooks } = require('./loader-hook.mjs')
24
+ return registerSyncLoaderHooks?.() ?? false
49
25
  }
50
26
 
51
27
  function isSyncLoaderHookVersionSupported () {
@@ -55,13 +31,3 @@ function isSyncLoaderHookVersionSupported () {
55
31
  if (NODE_MAJOR === 22) return NODE_MINOR > 22 || (NODE_MINOR === 22 && NODE_PATCH >= 3)
56
32
  return false
57
33
  }
58
-
59
- function warnSyncLoaderFallback (error) {
60
- let message = 'dd-trace could not register synchronous loader hooks. Falling back to the asynchronous loader.'
61
-
62
- if (error?.message) {
63
- message += ` ${error.message}`
64
- }
65
-
66
- process.emitWarning(message)
67
- }
package/register.mjs ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Registers the dd-trace loader hooks from an ES module. Unlike register.js, it loads the
3
+ * synchronous hooks through `import()`, so it does not depend on require(esm), which AWS Lambda
4
+ * disables. Without require(esm), register.js can only use the asynchronous `module.register`
5
+ * loader, which Node.js 26 deprecates.
6
+ */
7
+
8
+ /* eslint n/no-unsupported-features/node-builtins: ['error', { ignores: ['module.register'] }] */
9
+
10
+ import * as Module from 'node:module'
11
+
12
+ import { supportsSyncHooks } from 'import-in-the-middle/supports-sync-hooks.mjs'
13
+
14
+ import registerLoader from './packages/dd-trace/src/register-loader.js'
15
+
16
+ let registerSyncLoaderHooks
17
+
18
+ if (supportsSyncHooks()) {
19
+ try {
20
+ ({ registerSyncLoaderHooks } = await import('./loader-hook.mjs'))
21
+ registerSyncLoaderHooks ??= () => false
22
+ } catch (error) {
23
+ registerSyncLoaderHooks = () => { throw error }
24
+ }
25
+ }
26
+
27
+ registerLoader(Module.register, new URL(import.meta.url), registerSyncLoaderHooks)
@@ -407,3 +407,14 @@ Apache License
407
407
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
408
408
  See the License for the specific language governing permissions and
409
409
  limitations under the License.
410
+
411
+ ------------------------------------------------------------------------------
412
+
413
+ dd-trace
414
+
415
+ ## License
416
+
417
+ This work is dual-licensed under Apache 2.0 or BSD3.
418
+ You may select, at your option, one of the above-listed licenses.
419
+
420
+ `SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause`