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
@@ -1,9 +1,8 @@
1
1
  'use strict'
2
2
 
3
- // encoding used here is sha256
4
- // other languages use FNV1
5
- // this inconsistency is ok because hashes do not need to be consistent across services
6
- const crypto = require('crypto')
3
+ // Pathway hashes must equal dd-trace-java's for the same checkpoint, so a pathway that crosses
4
+ // tracers resolves to one set of nodes. The rules below mirror dd-trace-java's BaseHash and
5
+ // DataStreamsTags (node hash) and DefaultPathwayContext#generatePathwayHash (pathway hash).
7
6
  const { LRUCache } = require('../../../../vendor/dist/lru-cache')
8
7
  const {
9
8
  hasDsmBase64,
@@ -15,8 +14,39 @@ const {
15
14
  } = require('../carrier')
16
15
  const log = require('../log')
17
16
  const { encodeVarintInto, decodeVarint } = require('./encoding')
17
+ const { writeFnv64LE } = require('./fnv')
18
18
 
19
19
  const cache = new LRUCache({ max: 500 })
20
+ const seeds = new LRUCache({ max: 100 })
21
+ let nextSeedId = 0
22
+ /** @type {{ id: number, state: Buffer } | undefined} */
23
+ let lastSeed
24
+ /** @type {unknown[]} */
25
+ let lastSeedInputs = []
26
+
27
+ // dd-trace-java hashes these tag keys in this order, not alphabetically. Keys it does not know are
28
+ // hashed after them, alphabetically.
29
+ const HASHED_TAG_RANK = new Map([
30
+ ['bus', 0],
31
+ ['direction', 1],
32
+ ['exchange', 2],
33
+ ['topic', 3],
34
+ ['type', 4],
35
+ ['subscription', 5],
36
+ ['kafka_cluster_id', 6],
37
+ ])
38
+ const UNKNOWN_TAG_RANK = HASHED_TAG_RANK.size
39
+
40
+ // dd-trace-java reports these tags but keeps them out of the pathway hash.
41
+ const UNHASHED_TAG_KEYS = new Set([
42
+ 'ds.name',
43
+ 'ds.namespace',
44
+ 'manual_checkpoint',
45
+ 'group',
46
+ 'consumer_group',
47
+ 'partition',
48
+ 'has_routing_key',
49
+ ])
20
50
 
21
51
  const PATHWAY_CONTEXT_BYTES = 20
22
52
 
@@ -24,43 +54,98 @@ const PATHWAY_CONTEXT_BYTES = 20
24
54
  // `Buffer.from(...)` copy-out so callers never observe mutation between checkpoints.
25
55
  const pathwayScratch = Buffer.allocUnsafe(PATHWAY_CONTEXT_BYTES)
26
56
 
27
- function shaHash (checkpointString) {
28
- // Copy out of the 32-byte digest so the LRU cache doesn't retain it.
29
- return Buffer.from(crypto.createHash('sha256').update(checkpointString).digest().subarray(0, 8))
57
+ /**
58
+ * @param {string} tag
59
+ */
60
+ function tagKey (tag) {
61
+ const colon = tag.indexOf(':')
62
+ return colon === -1 ? tag : tag.slice(0, colon)
63
+ }
64
+
65
+ /**
66
+ * @param {string} tag
67
+ */
68
+ function tagRank (tag) {
69
+ return HASHED_TAG_RANK.get(tagKey(tag)) ?? UNKNOWN_TAG_RANK
70
+ }
71
+
72
+ /**
73
+ * @param {string[]} sortedEdgeTags
74
+ */
75
+ function hashedEdgeTags (sortedEdgeTags) {
76
+ return sortedEdgeTags
77
+ .filter(tag => !UNHASHED_TAG_KEYS.has(tagKey(tag)))
78
+ .sort((a, b) => tagRank(a) - tagRank(b))
79
+ .join('')
80
+ }
81
+
82
+ /**
83
+ * Like dd-trace-java's BaseHash, the FNV state over service, env, process tags and container tags
84
+ * hash is computed once per distinct value and continued for every checkpoint. `id` stands in for
85
+ * that value in the checkpoint cache key; ids are never reused, so an evicted seed cannot alias another.
86
+ *
87
+ * @param {string} service
88
+ * @param {string | undefined} env
89
+ * @param {string | undefined} processTags
90
+ * @param {string | null | undefined} containerTagsHash
91
+ * @returns {{ id: number, state: Buffer }}
92
+ */
93
+ function nodeHashSeed (service, env, processTags, containerTagsHash) {
94
+ if (
95
+ lastSeed !== undefined &&
96
+ lastSeedInputs[0] === service &&
97
+ lastSeedInputs[1] === env &&
98
+ lastSeedInputs[2] === processTags &&
99
+ lastSeedInputs[3] === containerTagsHash
100
+ ) {
101
+ return lastSeed
102
+ }
103
+ // dd-trace-java folds the container tags hash only when it folds process tags.
104
+ const prefix = processTags
105
+ ? `${service}${env ?? ''}${processTags}${containerTagsHash || ''}`
106
+ : `${service}${env ?? ''}`
107
+ let seed = seeds.get(prefix)
108
+ if (seed === undefined) {
109
+ const state = Buffer.alloc(8)
110
+ writeFnv64LE(Buffer.from(prefix, 'utf8'), state, 0)
111
+ seed = { id: nextSeedId++, state }
112
+ seeds.set(prefix, seed)
113
+ }
114
+ lastSeedInputs = [service, env, processTags, containerTagsHash]
115
+ lastSeed = seed
116
+ return seed
30
117
  }
31
118
 
32
119
  /**
120
+ * Sorts `edgeTags` in place.
121
+ *
122
+ * Returns one Buffer instance per distinct set of arguments while it stays cached: StatsBucket keys
123
+ * stats points by that instance, which keeps tags left out of the hash, such as `group`, in separate
124
+ * stats points.
125
+ *
33
126
  * @param {string} service
34
- * @param {string} env
127
+ * @param {string | undefined} env
35
128
  * @param {string[]} edgeTags
36
- * @param {Buffer} parentHash
37
- * @param {bigint | null} propagationHashBigInt - Optional propagation hash for process/container tags
129
+ * @param {Buffer} parentHash Parent pathway hash as uint64 little-endian.
130
+ * @param {string} [processTags] Serialized process tags; omitted when process tags are off.
131
+ * @param {string | null} [containerTagsHash] Container tags hash from the agent.
132
+ * @returns {Buffer} Pathway hash as uint64 little-endian.
38
133
  */
39
- function computeHash (service, env, edgeTags, parentHash, propagationHashBigInt = null) {
134
+ function computeHash (service, env, edgeTags, parentHash, processTags, containerTagsHash) {
40
135
  edgeTags.sort()
41
- const hashableEdgeTags = edgeTags.includes('manual_checkpoint:true')
42
- ? edgeTags.filter(item => item !== 'manual_checkpoint:true')
43
- : edgeTags
44
-
45
- // The cache key includes parentHash so a fan-in node with different parents
46
- // gets distinct cache entries; the hash input below excludes parentHash and
47
- // gets combined with it via a second sha pass to produce the final hash.
48
- const joinedEdgeTags = hashableEdgeTags.join('')
49
- const propagationHex = propagationHashBigInt ? propagationHashBigInt.toString(16) : ''
50
- const propagationPart = propagationHex ? `:${propagationHex}` : ''
51
- const key = `${service}${env}${joinedEdgeTags}${parentHash}${propagationPart}`
136
+ const seed = nodeHashSeed(service, env, processTags, containerTagsHash)
137
+ const key = `${seed.id}\0${edgeTags.join('\0')}\0${parentHash.toString('hex')}`
52
138
 
53
139
  let value = cache.get(key)
54
140
  if (value) {
55
141
  return value
56
142
  }
57
143
 
58
- const baseString = `${service}${env}${joinedEdgeTags}`
59
- const hashInput = propagationHex ? `${baseString}:${propagationHex}` : baseString
60
-
61
- const currentHash = shaHash(hashInput)
62
- const buf = Buffer.concat([currentHash, parentHash], 16)
63
- value = shaHash(buf.toString())
144
+ const pathwayInput = Buffer.alloc(16)
145
+ writeFnv64LE(Buffer.from(hashedEdgeTags(edgeTags), 'utf8'), pathwayInput, 0, seed.state)
146
+ parentHash.copy(pathwayInput, 8)
147
+ value = Buffer.allocUnsafe(8)
148
+ writeFnv64LE(pathwayInput, value, 0)
64
149
  cache.set(key, value)
65
150
  return value
66
151
  }
@@ -332,10 +332,11 @@ class DataStreamsProcessor {
332
332
  )
333
333
  }
334
334
 
335
- // Get propagation hash if enabled
336
- const propagationHashValue = propagationHash.isEnabled() ? propagationHash.getHash() : null
337
-
338
- const hash = computePathwayHash(this.service, this.env, edgeTags, parentHash, propagationHashValue)
335
+ const hash = propagationHash.isEnabled()
336
+ ? computePathwayHash(
337
+ this.service, this.env, edgeTags, parentHash, processTags.serialized, propagationHash.getContainerTagsHash()
338
+ )
339
+ : computePathwayHash(this.service, this.env, edgeTags, parentHash)
339
340
  const edgeLatencyNs = nowNs - edgeStartNs
340
341
  const pathwayLatencyNs = nowNs - pathwayStartNs
341
342
  const dataStreamsContext = {
@@ -27,7 +27,7 @@ module.exports = function getDebuggerConfig (config, inputPath) {
27
27
  repositoryUrl,
28
28
  runtimeId: config.tags['runtime-id'],
29
29
  service: config.service,
30
- url: agentless ? agentlessUrl.origin : config.url.toString(),
30
+ url: agentlessUrl === undefined ? config.url.toString() : agentlessUrl.origin,
31
31
  version: config.version,
32
32
  inputPath,
33
33
  }
@@ -1,7 +1,7 @@
1
1
  'use strict'
2
2
 
3
3
  /**
4
- * @param {ReturnType<import('../config')>} config - Debugger configuration
4
+ * @param {NonNullable<ReturnType<import('../config')>>} config - Debugger configuration
5
5
  * @param {string} path - Request path
6
6
  * @param {Record<string, string>} headers - Payload headers
7
7
  * @returns {{
@@ -12,17 +12,15 @@
12
12
  * }}
13
13
  */
14
14
  module.exports = function getRequestOptions (config, path, headers) {
15
- const options = {
16
- method: 'POST',
17
- url: config.url,
18
- path,
19
- headers,
20
- }
21
-
22
15
  if (config.agentless) {
23
16
  if (config.apiKey !== undefined) headers['DD-API-KEY'] = config.apiKey
24
17
  headers['DD-EVP-ORIGIN'] = 'agent-debugger'
25
18
  }
26
19
 
27
- return options
20
+ return {
21
+ method: 'POST',
22
+ url: config.url,
23
+ path,
24
+ headers,
25
+ }
28
26
  }
@@ -131,7 +131,7 @@ function onFlush (payload, done) {
131
131
  }
132
132
 
133
133
  /**
134
- * @param {number} statusCode - The status code of the response
134
+ * @param {number | undefined} statusCode - The status code of the response, if one was received
135
135
  * @param {string} payload - The payload to send
136
136
  * @param {() => void} done - Releases the payload from the upload queue
137
137
  */
@@ -1,7 +1,9 @@
1
1
  'use strict'
2
2
 
3
3
  const { join, dirname } = require('path')
4
- const { normalize } = require('../../../../../vendor/dist/source-map/lib/util')
4
+ const { normalize } = /** @type {{ normalize: (path: string) => string }} */ (
5
+ require('../../../../../vendor/dist/source-map/lib/util')
6
+ )
5
7
  const { loadSourceMapSync, getOriginalPosition } = require('./source-maps')
6
8
  const session = require('./session')
7
9
  const log = require('./log')
@@ -3,7 +3,7 @@
3
3
  const { GIT_COMMIT_SHA, GIT_REPOSITORY_URL } = require('../../plugins/util/tags')
4
4
 
5
5
  /**
6
- * @param {ReturnType<import('../config')>} config - Debugger configuration
6
+ * @param {NonNullable<ReturnType<import('../config')>>} config - Debugger configuration
7
7
  * @param {string} hostname - Host name
8
8
  * @param {string} debuggerVersion - Debugger version
9
9
  * @param {typeof import('./log')} log - Debugger logger
@@ -231,7 +231,7 @@ function logWorkerError (error, reason = error.reason) {
231
231
  * Sends the new configuration to the worker thread via the config channel.
232
232
  * Does nothing if the worker is not started.
233
233
  *
234
- * @param {import('../config/config-base')} config - The updated tracer configuration object
234
+ * @param {Config} config - The updated tracer configuration object
235
235
  */
236
236
  function configure (config) {
237
237
  if (configChannel === null) return
@@ -339,7 +339,7 @@ function detectDebuggerEndpoint (config, cb) {
339
339
 
340
340
  log.debug('[debugger] Detecting available debugger endpoints...')
341
341
 
342
- fetchAgentInfo(config.url, (err, agentInfo) => {
342
+ fetchAgentInfo(/** @type {URL} */ (config.url), (err, agentInfo) => {
343
343
  if (err) {
344
344
  log.warn('[debugger] Failed to query agent %s endpoint, falling back to %s',
345
345
  DEBUGGER_INPUT_V2,
@@ -8,13 +8,14 @@ const { REDACTED_PLACEHOLDER } = require('./redaction')
8
8
  /** @typedef {NonNullable<ReturnType<typeof globalThis.Object.getOwnPropertyDescriptor>>} PropertyDescriptor */
9
9
  /** @typedef {Map<unknown, unknown> | Set<unknown>} Collection */
10
10
  /** @typedef {(name: string) => boolean} IsRedactedIdentifier */
11
+ /** @typedef {{ get: (this: Collection) => number }} SizeDescriptor */
11
12
 
12
13
  const mapEntries = Map.prototype.entries
13
14
  const mapKeys = Map.prototype.keys
14
15
  const mapSet = Map.prototype.set
15
- const mapSizeGetter = Object.getOwnPropertyDescriptor(Map.prototype, 'size').get
16
+ const mapSizeGetter = /** @type {SizeDescriptor} */ (Object.getOwnPropertyDescriptor(Map.prototype, 'size')).get
16
17
  const setAdd = Set.prototype.add
17
- const setSizeGetter = Object.getOwnPropertyDescriptor(Set.prototype, 'size').get
18
+ const setSizeGetter = /** @type {SizeDescriptor} */ (Object.getOwnPropertyDescriptor(Set.prototype, 'size')).get
18
19
  const setValues = Set.prototype.values
19
20
  const mapIteratorNext = Object.getPrototypeOf(mapEntries.call(new Map())).next
20
21
  const setIteratorNext = Object.getPrototypeOf(setValues.call(new Set())).next
@@ -1,6 +1,9 @@
1
1
  'use strict'
2
2
 
3
- const { LogCollapsingLowestDenseDDSketch } = require('../../../../vendor/dist/@datadog/sketches-js')
3
+ /** @typedef {typeof import('../../../../vendor/node_modules/@datadog/sketches-js')} Sketches */
4
+ const { LogCollapsingLowestDenseDDSketch } = /** @type {Sketches} */ (
5
+ require('../../../../vendor/dist/@datadog/sketches-js')
6
+ )
4
7
  const { TELEMETRY_DISTRIBUTION_RELATIVE_ACCURACY } = require('../constants')
5
8
 
6
9
  /**
@@ -103,9 +103,14 @@ function installProbeSampler (guardrailMetrics, config) {
103
103
  Atomics.store(sampledProbeIndexes, SAMPLED_PROBE_COUNT_INDEX, 0)
104
104
  Atomics.store(sampledProbeIndexes, SAMPLED_PROBE_OVERFLOW_INDEX, 0)
105
105
 
106
- const oneSecondNs = 1_000_000_000n
106
+ const ONE_SECOND_NS = 1_000_000_000n
107
107
  let globalSnapshotSamplingRateWindowStart = 0n
108
- let snapshotsSampledWithinTheLastSecond = 0
108
+ /**
109
+ * The snapshots counted toward the global snapshot rate limit in the current window. Later probes in a sampled trace
110
+ * aren't limited by it, so this can exceed the limit. The excess is carried over into the following windows, which
111
+ * keeps the overall volume within the limit on average.
112
+ */
113
+ let snapshotsCountedInWindow = 0
109
114
 
110
115
  ddTraceGlobal[Symbol.for(PROBE_SAMPLER_SYMBOL)] = {
111
116
  /**
@@ -274,8 +279,9 @@ function installProbeSampler (guardrailMetrics, config) {
274
279
  * Sample a snapshot-producing probe hit using the sampling decision of its trace. The first such probe hit in the
275
280
  * trace makes the decision for all of them, subject to its per-probe rate limit and the global snapshot rate limit.
276
281
  * If the trace is sampled, each probe then emits once in it without being subject to the rate limits, so the trace
277
- * emits a complete set of snapshots. Those snapshots still count toward the rate limits, which keeps the overall
278
- * volume close to the limits by making later traces less likely to be sampled.
282
+ * emits a complete set of snapshots. Those snapshots still count toward the rate limits. Any that exceed the global
283
+ * snapshot rate limit are carried over into its following windows, so later traces are less likely to be sampled
284
+ * until the excess is made up.
279
285
  *
280
286
  * @param {LocalTrace} trace - The trace the probe was hit in.
281
287
  * @param {number} probeIndex - The worker-side probe sampling index.
@@ -325,14 +331,33 @@ function installProbeSampler (guardrailMetrics, config) {
325
331
  return true
326
332
  }
327
333
 
328
- if (isSnapshotProducingProbe &&
329
- now - globalSnapshotSamplingRateWindowStart <= oneSecondNs &&
330
- snapshotsSampledWithinTheLastSecond >= MAX_SNAPSHOTS_PER_SECOND_GLOBALLY) {
331
- guardrailMetrics.eventSkipped(SKIPPED_REASON.RATE_LIMIT_GLOBAL, EVENT_TYPE.SNAPSHOT)
332
- return true
333
- }
334
+ return isSnapshotProducingProbe && isGloballyRateLimited(now)
335
+ }
334
336
 
335
- return false
337
+ /**
338
+ * Check the global snapshot rate limit, recording the skip if it is reached.
339
+ *
340
+ * @param {bigint} now - The current time.
341
+ */
342
+ function isGloballyRateLimited (now) {
343
+ advanceGlobalSnapshotWindow(now)
344
+ if (snapshotsCountedInWindow < MAX_SNAPSHOTS_PER_SECOND_GLOBALLY) return false
345
+ guardrailMetrics.eventSkipped(SKIPPED_REASON.RATE_LIMIT_GLOBAL, EVENT_TYPE.SNAPSHOT)
346
+ return true
347
+ }
348
+
349
+ /**
350
+ * Start a new window of the global snapshot rate limit if the current one has passed. Snapshots counted in excess of
351
+ * the limit are carried over, reduced by the limit for each window that has passed since.
352
+ *
353
+ * @param {bigint} now - The current time.
354
+ */
355
+ function advanceGlobalSnapshotWindow (now) {
356
+ const elapsedNs = now - globalSnapshotSamplingRateWindowStart
357
+ if (elapsedNs <= ONE_SECOND_NS) return
358
+ const allowance = Number(elapsedNs / ONE_SECOND_NS) * MAX_SNAPSHOTS_PER_SECOND_GLOBALLY
359
+ snapshotsCountedInWindow = Math.max(snapshotsCountedInWindow - allowance, 0)
360
+ globalSnapshotSamplingRateWindowStart = now
336
361
  }
337
362
 
338
363
  /**
@@ -347,12 +372,8 @@ function installProbeSampler (guardrailMetrics, config) {
347
372
  if (!storeSampledProbeIndex(probeIndex)) return false
348
373
 
349
374
  if (isSnapshotProducingProbe) {
350
- if (now - globalSnapshotSamplingRateWindowStart > oneSecondNs) {
351
- snapshotsSampledWithinTheLastSecond = 1
352
- globalSnapshotSamplingRateWindowStart = now
353
- } else {
354
- snapshotsSampledWithinTheLastSecond++
355
- }
375
+ advanceGlobalSnapshotWindow(now)
376
+ snapshotsCountedInWindow++
356
377
  }
357
378
 
358
379
  lastCaptureNsByProbeId.set(probeId, now)
@@ -441,6 +462,7 @@ function truncateErrorDescription (description) {
441
462
  *
442
463
  * @param {object} error - The thrown object to inspect.
443
464
  * @param {'name' | 'message'} property - The property to find.
465
+ * @returns {string | void}
444
466
  */
445
467
  function getErrorStringProperty (error, property) {
446
468
  while (error !== null) {
@@ -7,6 +7,8 @@
7
7
  * few of its methods, never returns their results, and never emits its events. Deno doesn't let worker threads
8
8
  * connect to the main thread inspector. Deno reports a Node.js `process.version`, so both runtimes are detected by
9
9
  * their own `process.versions` entry instead.
10
+ *
11
+ * @returns {'Bun' | 'Deno' | void}
10
12
  */
11
13
  function getUnsupportedRuntime () {
12
14
  if (process.versions.bun !== undefined) return 'Bun'
@@ -19,7 +19,8 @@ const {
19
19
  const cache = {}
20
20
 
21
21
  /**
22
- * @param {import('./config/config-types').ConfigProperties} config
22
+ * @param {Pick<import('./config/config-types').ConfigProperties, 'DD_GIT_COMMIT_SHA' | 'DD_GIT_FOLDER_PATH' |
23
+ * 'DD_GIT_PROPERTIES_FILE' | 'DD_GIT_REPOSITORY_URL' | 'DD_TRACE_GIT_METADATA_ENABLED' | 'tags'>} config
23
24
  */
24
25
  function getGitMetadata (config) {
25
26
  if (!config.DD_TRACE_GIT_METADATA_ENABLED) {
@@ -6,13 +6,16 @@ const { isTrue } = require('./util')
6
6
  // Global `jest` is only present in Jest workers.
7
7
  const inJestWorker = typeof jest !== 'undefined'
8
8
 
9
- // skipDefault: distinguish an unset DD_TRACE_ENABLED (fall back to the OTel signal) from an
10
- // explicit value; the registered default would otherwise mask the OTEL_TRACES_EXPORTER check.
9
+ // skipDefault: distinguish an unset DD_TRACE_ENABLED (fall back to the OTel settings) from an
10
+ // explicit value; the registered default would otherwise mask the OTel checks.
11
11
  const ddTraceEnabled = getValueFromEnvSources('DD_TRACE_ENABLED', true)
12
12
  const agentlessTracingEnabled = getValueFromEnvSources('DD_AGENTLESS_ENABLED') ||
13
13
  isTrue(getEnvironmentVariable('_DD_APM_TRACING_AGENTLESS_ENABLED'))
14
+ // OTEL_SDK_DISABLED turns the whole SDK off, while OTEL_TRACES_EXPORTER only selects a trace
15
+ // transport, which agentless mode replaces.
14
16
  const ddTraceDisabled = ddTraceEnabled === undefined
15
- ? !agentlessTracingEnabled && getValueFromEnvSources('OTEL_TRACES_EXPORTER') === 'none'
17
+ ? getValueFromEnvSources('OTEL_SDK_DISABLED') ||
18
+ (!agentlessTracingEnabled && getValueFromEnvSources('OTEL_TRACES_EXPORTER') === 'none')
16
19
  : ddTraceEnabled === false
17
20
 
18
21
  module.exports = ddTraceDisabled || inJestWorker
@@ -1,5 +1,7 @@
1
1
  'use strict'
2
2
 
3
+ // Internal bridge for datadog-lambda-js. Applications should use that package's wrapper API.
4
+
3
5
  const tracer = require('../../../..')
4
6
  const { AUTO_KEEP } = require('../../../../ext/priority')
5
7
  const { writeDatadogTraceId, writeDatadogParentId, writeDatadogSamplingPriority } = require('../carrier')
@@ -52,17 +54,16 @@ function reportInitFailure (failure) {
52
54
  /**
53
55
  * Builds the message for a facade entry point whose implementation has not landed yet.
54
56
  *
55
- * The five-function surface is a cross-major contract, so the names are reserved from the first
56
- * release of the facade. Throwing keeps the gap loud: a silent no-op here would drop customer
57
- * metrics with no error anywhere, which is the failure mode this migration exists to avoid.
57
+ * The shim requires the same internal contract on each supported tracer line. Throwing keeps the gap loud:
58
+ * a silent no-op here would drop customer metrics with no error anywhere.
58
59
  * The shim's integration lands only after these are implemented, so the throw never ships to a
59
60
  * shim user.
60
61
  *
61
62
  * @param {string} name Facade entry point.
62
63
  */
63
64
  function notImplemented (name) {
64
- return `dd-trace/lambda ${name}() is not implemented yet: Lambda metrics land with the metrics ` +
65
- 'pipeline (migration PR 12). Keep using datadog-lambda-js for custom metrics until then.'
65
+ return `Internal Lambda ${name}() is not implemented yet. ` +
66
+ 'Keep using datadog-lambda-js for custom metrics until the metrics pipeline is ported.'
66
67
  }
67
68
 
68
69
  module.exports = {
@@ -1,7 +1,7 @@
1
1
  'use strict'
2
2
 
3
3
  const LLMObsPlugin = require('../base')
4
- const { formatInput, formatOutput } = require('./utils')
4
+ const { formatInput, formatOutput, formatServerInput, getClientInfoTags, safeStringify } = require('./utils')
5
5
 
6
6
  class McpToolCallLLMObsPlugin extends LLMObsPlugin {
7
7
  static id = 'llmobs_mcp_tool_call'
@@ -61,8 +61,59 @@ class McpListToolsLLMObsPlugin extends LLMObsPlugin {
61
61
  const span = ctx.currentStore?.span
62
62
  if (!span || ctx.error) return
63
63
 
64
- this._tagger.tagTextIO(span, null, JSON.stringify(ctx.result))
64
+ this._tagger.tagTextIO(span, null, safeStringify(ctx.result))
65
65
  }
66
66
  }
67
67
 
68
- module.exports = [McpToolCallLLMObsPlugin, McpListToolsLLMObsPlugin]
68
+ class McpServerRequestLLMObsPlugin extends LLMObsPlugin {
69
+ static id = 'llmobs_mcp_server_request'
70
+ static integration = 'modelcontextprotocol-sdk'
71
+ static prefix = 'tracing:apm:mcp:server:request'
72
+
73
+ getLLMObsSpanRegisterOptions (ctx) {
74
+ const { request } = ctx
75
+ if (request?.method === 'tools/call') {
76
+ return { kind: 'tool', name: request.params?.name || 'unknown_tool' }
77
+ }
78
+ return { kind: 'task', name: `mcp.${request?.method ?? 'unknown'}` }
79
+ }
80
+
81
+ setLLMObsTags (ctx) {
82
+ const span = ctx.currentStore?.span
83
+ if (!span) return
84
+
85
+ const { request, extra, server } = ctx
86
+ const spanTags = {
87
+ mcp_method: request?.method,
88
+ ...getClientInfoTags(extra?.mcpReq?.envelope, server),
89
+ }
90
+ const sessionId = extra?.sessionId ?? server?.transport?.sessionId
91
+ if (sessionId) spanTags.mcp_session_id = String(sessionId)
92
+ if (request?.method === 'tools/call') {
93
+ spanTags.mcp_tool = request.params?.name || 'unknown_tool'
94
+ spanTags.mcp_tool_kind = 'server'
95
+ }
96
+ this._tagger.tagSpanTags(span, spanTags)
97
+
98
+ const output = ctx.error ? undefined : safeStringify(ctx.result)
99
+ this._tagger.tagTextIO(span, formatServerInput(request, extra?.mcpReq), output)
100
+ }
101
+ }
102
+
103
+ class McpToolCallV2LLMObsPlugin extends McpToolCallLLMObsPlugin {
104
+ static id = 'llmobs_mcp_tool_call_v2'
105
+ static prefix = 'tracing:orchestrion:@modelcontextprotocol/client:Client_callTool'
106
+ }
107
+
108
+ class McpListToolsV2LLMObsPlugin extends McpListToolsLLMObsPlugin {
109
+ static id = 'llmobs_mcp_list_tools_v2'
110
+ static prefix = 'tracing:orchestrion:@modelcontextprotocol/client:Client_listTools'
111
+ }
112
+
113
+ module.exports = [
114
+ McpToolCallLLMObsPlugin,
115
+ McpListToolsLLMObsPlugin,
116
+ McpToolCallV2LLMObsPlugin,
117
+ McpListToolsV2LLMObsPlugin,
118
+ McpServerRequestLLMObsPlugin,
119
+ ]
@@ -52,4 +52,84 @@ function formatOutput (result) {
52
52
  }
53
53
  }
54
54
 
55
- module.exports = { formatInput, formatOutput }
55
+ const DISTRIBUTED_TRACE_META_KEY = '_dd_trace_context'
56
+ const CLIENT_INFO_META_KEY = 'io.modelcontextprotocol/clientInfo'
57
+ const MAX_CLIENT_INFO_TAG_LENGTH = 256
58
+
59
+ /**
60
+ * @param {unknown} value
61
+ */
62
+ function safeStringify (value) {
63
+ if (value === undefined) return
64
+ try {
65
+ return JSON.stringify(value)
66
+ } catch {}
67
+ }
68
+
69
+ /**
70
+ * Copies `_meta` keys except the trace context.
71
+ * @param {Record<string, unknown>} target
72
+ * @param {Record<string, unknown>} [source]
73
+ */
74
+ function copyMetaKeys (target, source) {
75
+ if (!source) return false
76
+
77
+ let copied = false
78
+ for (const key of Object.keys(source)) {
79
+ if (key === DISTRIBUTED_TRACE_META_KEY) continue
80
+ target[key] = source[key]
81
+ copied = true
82
+ }
83
+ return copied
84
+ }
85
+
86
+ /**
87
+ * Formats a server request as JSON-RPC without the trace context. Before a handler runs, SDK 2.x moves the reserved
88
+ * `io.modelcontextprotocol/*` `_meta` keys into `mcpReq.envelope` and drops the JSON-RPC id. Both are put back, so the
89
+ * input matches the request that the client sent.
90
+ * @param {{ method?: string, id?: string|number, params?: { _meta?: Record<string, unknown> } }} [request]
91
+ * @param {{ id?: string|number, envelope?: Record<string, unknown> }} [mcpReq]
92
+ */
93
+ function formatServerInput (request, mcpReq) {
94
+ let params = request?.params
95
+ const meta = {}
96
+ const hasEnvelopeKeys = copyMetaKeys(meta, mcpReq?.envelope)
97
+ const hasRequestKeys = copyMetaKeys(meta, params?._meta)
98
+
99
+ const rest = {}
100
+ let hasRest = false
101
+ if (params) {
102
+ for (const [key, value] of Object.entries(params)) {
103
+ if (key === '_meta') continue
104
+ rest[key] = value
105
+ hasRest = true
106
+ }
107
+ }
108
+ if (hasEnvelopeKeys || hasRequestKeys) {
109
+ params = { ...rest, _meta: meta }
110
+ } else if (params?._meta !== undefined) {
111
+ // `_meta` held only the trace context that the client tracer added, so drop `params` if nothing else is left.
112
+ params = hasRest ? rest : undefined
113
+ }
114
+
115
+ return safeStringify({ method: request?.method, params, jsonrpc: '2.0', id: request?.id ?? mcpReq?.id })
116
+ }
117
+
118
+ /**
119
+ * Client identity comes from the request envelope on stateless requests and from the handshake otherwise.
120
+ * @param {Record<string, unknown>} [envelope]
121
+ * @param {{ getClientVersion?: () => unknown }} [server]
122
+ */
123
+ function getClientInfoTags (envelope, server) {
124
+ const clientInfo = envelope?.[CLIENT_INFO_META_KEY] ?? server?.getClientVersion?.()
125
+ const tags = {}
126
+ if (!clientInfo || typeof clientInfo !== 'object') return tags
127
+
128
+ for (const field of ['name', 'title', 'version']) {
129
+ const value = clientInfo[field]
130
+ if (value) tags[`mcp_client_${field}`] = String(value).slice(0, MAX_CLIENT_INFO_TAG_LENGTH)
131
+ }
132
+ return tags
133
+ }
134
+
135
+ module.exports = { formatInput, formatOutput, formatServerInput, getClientInfoTags, safeStringify }
@@ -26,6 +26,7 @@ const POLL_FAILED_WITHOUT_CONFIGURATION = 'Feature Flags: agentless configuratio
26
26
  * @property {number} requestTimeoutMs
27
27
  * @property {string | undefined} apiKey
28
28
  * @property {string | undefined} env
29
+ * @property {string | undefined} service
29
30
  */
30
31
 
31
32
  /**
@@ -163,6 +164,8 @@ class AgentlessConfigurationSource {
163
164
  const headers = getClientLibraryHeaders()
164
165
  headers['Accept-Encoding'] = 'gzip'
165
166
  if (this.#config.apiKey) headers['DD-API-KEY'] = this.#config.apiKey
167
+ // The CDN uses this header to attribute the usage of this request to the service.
168
+ if (this.#config.service) headers['DD-Service'] = this.#config.service
166
169
  if (this.#etag) headers['If-None-Match'] = this.#etag
167
170
 
168
171
  /**