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
@@ -55,20 +55,24 @@ function annotateLayer (layer, matchers) {
55
55
  }
56
56
 
57
57
  /**
58
- * Resolve the route for a dispatched layer. Single-pattern layers carry a
59
- * constant route; only multi-pattern stacks need the per-request `layer.path`
60
- * match the host already computed.
58
+ * Single-pattern layers carry a constant route. Multi-pattern layers use the
59
+ * host's request-local pattern when available, or match its legacy `layer.path`.
61
60
  *
62
61
  * @param {{ captureRoute?: string, needMultiMatch: boolean,
63
62
  * matchers: Array<{ path?: string, regex?: RegExp }> }} meta
64
63
  * @param {{ path?: string }} layer
64
+ * @param {import('node:http').IncomingMessage} [req]
65
+ * @param {symbol} [matchedRoute]
65
66
  * @returns {string | undefined}
66
67
  */
67
- function resolveLayerRoute (meta, layer) {
68
+ function resolveLayerRoute (meta, layer, req, matchedRoute) {
68
69
  if (!meta.needMultiMatch) return meta.captureRoute
69
70
 
71
+ const pattern = matchedRoute && req[matchedRoute]
72
+ if (typeof pattern === 'string') return pattern
73
+
70
74
  for (const matcher of meta.matchers) {
71
- if (matcher.regex?.test(layer.path)) return matcher.path
75
+ if (matchedRoute ? matcher.regex === pattern : matcher.regex?.test(layer.path)) return matcher.path
72
76
  }
73
77
  }
74
78
 
@@ -80,11 +84,13 @@ function resolveLayerRoute (meta, layer) {
80
84
  * matchers: Array<{ path?: string, regex?: RegExp }> }} meta
81
85
  * @param {{ path?: string }} layer
82
86
  * @param {Function} next
87
+ * @param {import('node:http').IncomingMessage} req
88
+ * @param {symbol | undefined} matchedRoute
83
89
  * @returns {string | undefined | typeof ROUTE_RESOLUTION_FAILED}
84
90
  */
85
- function resolveLayerRouteOrForwardError (meta, layer, next) {
91
+ function resolveLayerRouteOrForwardError (meta, layer, next, req, matchedRoute) {
86
92
  try {
87
- return resolveLayerRoute(meta, layer)
93
+ return resolveLayerRoute(meta, layer, req, matchedRoute)
88
94
  } catch (error) {
89
95
  next(error)
90
96
  return ROUTE_RESOLUTION_FAILED
@@ -121,13 +127,14 @@ function adoptRequestNext (req, hostNext, wrappedNext) {
121
127
  * span is published only for the layer the host actually runs.
122
128
  *
123
129
  * @param {string} name Channel namespace (`apm:<name>:middleware:*`).
130
+ * @param {symbol} [matchedRoute] Native request-local route key, when provided by the host.
124
131
  * @returns {{
125
132
  * wrapLayerRequest: (originalRequest: Function) => Function,
126
133
  * wrapLayerError: (originalError: Function) => Function,
127
134
  * wrapLegacyHandle: (layer: object, original: Function, guardRepeatedNext?: boolean) => Function
128
135
  * }}
129
136
  */
130
- function createLayerDispatchWrappers (name) {
137
+ function createLayerDispatchWrappers (name, matchedRoute) {
131
138
  const enterChannel = channel(`apm:${name}:middleware:enter`)
132
139
  const exitChannel = channel(`apm:${name}:middleware:exit`)
133
140
  const finishChannel = channel(`apm:${name}:middleware:finish`)
@@ -188,7 +195,7 @@ function createLayerDispatchWrappers (name) {
188
195
 
189
196
  let route = meta.captureRoute
190
197
  if (meta.needMultiMatch) {
191
- route = resolveLayerRouteOrForwardError(meta, this, next)
198
+ route = resolveLayerRouteOrForwardError(meta, this, next, req, matchedRoute)
192
199
  if (route === ROUTE_RESOLUTION_FAILED) return
193
200
  }
194
201
 
@@ -217,7 +224,7 @@ function createLayerDispatchWrappers (name) {
217
224
 
218
225
  let route = meta.captureRoute
219
226
  if (meta.needMultiMatch) {
220
- route = resolveLayerRouteOrForwardError(meta, this, next)
227
+ route = resolveLayerRouteOrForwardError(meta, this, next, req, matchedRoute)
221
228
  if (route === ROUTE_RESOLUTION_FAILED) return
222
229
  }
223
230
 
@@ -586,6 +593,7 @@ addHook({ name: 'router', file: 'lib/layer.js', versions: ['>=1 <2'] }, Layer =>
586
593
  })
587
594
 
588
595
  const queryParserReadCh = channel('datadog:query:read:finish')
596
+ const routeCreateCh = channel('datadog:router:route:create')
589
597
 
590
598
  addHook({ name: 'router', versions: ['>=2'] }, Router => {
591
599
  const wrapRouterMethod = createWrapRouterMethod('router', getCompileToRegexp())
@@ -613,11 +621,26 @@ addHook({ name: 'router', versions: ['>=2'] }, Router => {
613
621
  })
614
622
 
615
623
  shimmer.wrap(WrappedRouter.prototype, 'use', wrapRouterMethod)
616
- shimmer.wrap(WrappedRouter.prototype, 'route', wrapRouterMethod)
624
+ shimmer.wrap(WrappedRouter.prototype, 'route', original => wrapRouterMethod(publishRouteCreate(original)))
617
625
 
618
626
  return WrappedRouter
619
627
  })
620
628
 
629
+ /**
630
+ * Publish the matching options of the Router that owns each new Route (a Router does not inherit
631
+ * the app's settings), once at registration.
632
+ * @param {(this: { caseSensitive?: boolean, strict?: boolean }, path: string) => object} original
633
+ */
634
+ function publishRouteCreate (original) {
635
+ return function (...args) {
636
+ const route = original.apply(this, args)
637
+ if (routeCreateCh.hasSubscribers) {
638
+ routeCreateCh.publish({ route, sensitive: this.caseSensitive === true, strict: this.strict === true })
639
+ }
640
+ return route
641
+ }
642
+ }
643
+
621
644
  const routerParamStartCh = channel('datadog:router:param:start')
622
645
  const visitedParams = new WeakSet()
623
646
 
@@ -644,10 +667,26 @@ function wrapHandleRequest (original) {
644
667
  }
645
668
  }
646
669
 
670
+ /** @type {Map<string | undefined, symbol>} */
671
+ const matchedRouteSymbols = new Map()
672
+
673
+ addHook({ name: 'router', file: 'lib/symbols.js', versions: ['>=2'] },
674
+ /**
675
+ * @param {{ matchedRoute: symbol }} symbols
676
+ * @param {string} version
677
+ * @param {boolean} isIitm
678
+ * @param {{ moduleBaseDir?: string }} hookMeta
679
+ */
680
+ function captureMatchedRoute (symbols, version, isIitm, { moduleBaseDir }) {
681
+ matchedRouteSymbols.set(moduleBaseDir, symbols.matchedRoute)
682
+ return symbols
683
+ })
684
+
647
685
  addHook({
648
686
  name: 'router', file: 'lib/layer.js', versions: ['>=2'],
649
- }, Layer => {
650
- const { wrapLayerRequest, wrapLayerError } = createLayerDispatchWrappers('router')
687
+ }, (Layer, version, isIitm, { moduleBaseDir }) => {
688
+ const matchedRoute = matchedRouteSymbols.get(moduleBaseDir)
689
+ const { wrapLayerRequest, wrapLayerError } = createLayerDispatchWrappers('router', matchedRoute)
651
690
 
652
691
  // `handleRequest` carries two concerns: the middleware dispatch span and the
653
692
  // param-start publish (`wrapHandleRequest`). Wrap the dispatch first so it
@@ -110,7 +110,7 @@ function noop () {}
110
110
  * @param {string} url
111
111
  */
112
112
  function removeVitestBrowserUrlMetadata (url) {
113
- const locationMatch = url.match(VITEST_BROWSER_STACK_LOCATION_RE)
113
+ const locationMatch = VITEST_BROWSER_STACK_LOCATION_RE.exec(url)
114
114
  const location = locationMatch?.[0] || ''
115
115
  const urlWithoutLocation = location ? url.slice(0, -location.length) : url
116
116
  const queryStart = urlWithoutLocation.indexOf('?')
@@ -1197,6 +1197,11 @@ function safeWorkspaceProject (ctx) {
1197
1197
  return project
1198
1198
  }
1199
1199
 
1200
+ function hasCachedSpecifications (ctx) {
1201
+ const cachedSpecs = ctx?.specifications?._cachedSpecs
1202
+ return typeof cachedSpecs?.size === 'number' && cachedSpecs.size > 0
1203
+ }
1204
+
1200
1205
  function getSortWrapper (sort, frameworkVersion) {
1201
1206
  return async function () {
1202
1207
  if (this.ctx.config.shard && this.ctx.state.pathsSet.size > 0 && arguments[0].length === 0) {
@@ -1229,13 +1234,16 @@ function getFinishWrapper (exitOrClose) {
1229
1234
 
1230
1235
  // pathsSet contains candidates before sharding, including files that never run.
1231
1236
  const hasNoTestFiles = this.state.pathsSet.size === 0
1232
- const isEmptyShard = emptyShardContexts.has(this)
1237
+ const files = this.state.getFiles()
1238
+ const tests = getTypeTasks(files)
1239
+ const isEmptyShard = emptyShardContexts.has(this) ||
1240
+ (this.config.shard && this.config.passWithNoTests && !areAllSuitesSkipped &&
1241
+ files.length === 0 && hasCachedSpecifications(this))
1233
1242
  const hasUnexpectedEmptySession = hasNoTestFiles && !isEmptyShard &&
1234
1243
  !areAllSuitesSkipped && !this.config.passWithNoTests
1235
1244
  if (!error && hasUnexpectedEmptySession) {
1236
1245
  error = new Error('No test files were found.')
1237
1246
  }
1238
- const tests = getTypeTasks(this.state.getFiles())
1239
1247
  const hasExecutedTests = tests.some(test =>
1240
1248
  test.mode !== 'skip' && test.mode !== 'todo' &&
1241
1249
  (test.result?.state === 'pass' || test.result?.state === 'fail')
@@ -0,0 +1,41 @@
1
+ 'use strict'
2
+
3
+ // Ported from datadog-lambda-js at da9fc3c0c9dca00893f70c9a1bd5ac1254af3b01.
4
+
5
+ /**
6
+ * @param {string} arn
7
+ * @param {string} [version]
8
+ */
9
+ function parseLambdaARN (arn, version) {
10
+ let [, , , region, accountId, , functionname, alias] = arn.split(':')
11
+ const tags = { region, account_id: accountId, functionname }
12
+ // If we have an alias...
13
+ if (alias === undefined) {
14
+ tags.resource = functionname
15
+ } else {
16
+ // Check if $Latest and remove $ for datadog tag convention.
17
+ if (alias.startsWith('$')) {
18
+ alias = alias.slice(1)
19
+ // Check if this is an alias and not a version.
20
+ } else if (!Number(alias)) {
21
+ tags.executedversion = version
22
+ }
23
+ tags.resource = functionname + ':' + alias
24
+ }
25
+ return tags
26
+ }
27
+
28
+ /** @param {Record<string, string | undefined>} tags */
29
+ function makeTagStringsFromObject (tags) {
30
+ return Object.entries(tags).map(([tagKey, tagValue]) => `${tagKey}:${tagValue}`)
31
+ }
32
+
33
+ /**
34
+ * @param {string} arn
35
+ * @param {string} [version]
36
+ */
37
+ function parseTagsFromARN (arn, version) {
38
+ return makeTagStringsFromObject(parseLambdaARN(arn, version))
39
+ }
40
+
41
+ module.exports = { parseLambdaARN, parseTagsFromARN }
@@ -0,0 +1,167 @@
1
+ 'use strict'
2
+
3
+ const log = require('../../../dd-trace/src/log')
4
+
5
+ /** @typedef {import('../../../dd-trace/src/opentracing/span_context')} SpanContext */
6
+ /** @typedef {import('../../../dd-trace/src/opentracing/tracer')} Tracer */
7
+
8
+ /**
9
+ * @param {Record<string, unknown>|undefined} record SNS record.
10
+ * @returns {Record<string, string>|null}
11
+ */
12
+ function getSNSHeaders (record) {
13
+ try {
14
+ const attribute = record?.Sns?.MessageAttributes?._datadog
15
+ if (!attribute?.Value) return null
16
+ const value = attribute.Type === 'String'
17
+ ? attribute.Value
18
+ : Buffer.from(attribute.Value, 'base64').toString('ascii')
19
+ return JSON.parse(value)
20
+ } catch {
21
+ return null
22
+ }
23
+ }
24
+
25
+ /**
26
+ * @param {Record<string, unknown>|undefined} record SNS-over-SQS record.
27
+ * @returns {Record<string, string>|null}
28
+ */
29
+ function getSNSSQSHeaders (record) {
30
+ if (!record) return null
31
+ try {
32
+ if (record.body) {
33
+ const body = JSON.parse(record.body)
34
+ const attribute = body?.MessageAttributes?._datadog
35
+ if (attribute?.Value) {
36
+ const value = attribute.Type === 'String'
37
+ ? attribute.Value
38
+ : Buffer.from(attribute.Value, 'base64').toString('ascii')
39
+ return JSON.parse(value)
40
+ }
41
+ }
42
+ const attribute = record.messageAttributes?._datadog
43
+ return attribute?.stringValue ? JSON.parse(attribute.stringValue) : null
44
+ } catch {
45
+ return null
46
+ }
47
+ }
48
+
49
+ /**
50
+ * @param {Record<string, unknown>|undefined} record SQS record.
51
+ * @returns {Record<string, string>|null}
52
+ */
53
+ function getSQSHeaders (record) {
54
+ try {
55
+ let headers = record?.messageAttributes?._datadog?.stringValue
56
+ if (!headers) {
57
+ const encoded = record?.messageAttributes?._datadog?.binaryValue
58
+ if (encoded) headers = Buffer.from(encoded, 'base64').toString('ascii')
59
+ }
60
+ return headers ? JSON.parse(headers) : null
61
+ } catch {
62
+ return null
63
+ }
64
+ }
65
+
66
+ /**
67
+ * @param {Record<string, unknown>|undefined} record EventBridge-over-SQS record.
68
+ * @returns {Record<string, string>|null}
69
+ */
70
+ function getEventBridgeSQSHeaders (record) {
71
+ try {
72
+ return record?.body ? JSON.parse(record.body)?.detail?._datadog ?? null : null
73
+ } catch {
74
+ return null
75
+ }
76
+ }
77
+
78
+ /**
79
+ * @param {Record<string, unknown>} event Kinesis event.
80
+ * @param {Tracer} tracer Core tracer.
81
+ * @returns {SpanContext|null}
82
+ */
83
+ function extractKinesis (event, tracer) {
84
+ const data = event?.Records?.[0]?.kinesis.data
85
+ if (data === undefined) return null
86
+ try {
87
+ if (!data) return null
88
+ const headers = JSON.parse(Buffer.from(data, 'base64').toString('ascii'))?._datadog
89
+ return headers ? tracer.extract('text_map', headers) : null
90
+ } catch (error) {
91
+ log.debug('Unable to extract trace context from Kinesis event: %s', error)
92
+ return null
93
+ }
94
+ }
95
+
96
+ /**
97
+ * @param {Record<string, unknown>} event MSK event.
98
+ * @param {Tracer} tracer Core tracer.
99
+ * @returns {SpanContext|null}
100
+ */
101
+ function extractMSK (event, tracer) {
102
+ if (!event?.records) return null
103
+ // Unlike SQS/SNS/Kinesis, MSK selects the first traced record across partitions.
104
+ for (const records of Object.values(event.records)) {
105
+ if (!Array.isArray(records)) continue
106
+ for (const record of records) {
107
+ try {
108
+ if (!Array.isArray(record?.headers)) continue
109
+ let headers = null
110
+ for (const entry of record.headers) {
111
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue
112
+ for (const [name, value] of Object.entries(entry)) {
113
+ if (Array.isArray(value)) {
114
+ headers ??= {}
115
+ headers[name.toLowerCase()] = Buffer.from(value).toString('utf8')
116
+ }
117
+ }
118
+ }
119
+ if (!headers) continue
120
+ const context = tracer.extract('text_map', headers)
121
+ if (context) return context
122
+ } catch (error) {
123
+ log.debug('Unable to extract trace context from MSK event: %s', error)
124
+ }
125
+ }
126
+ }
127
+ return null
128
+ }
129
+
130
+ /**
131
+ * @param {Record<string, unknown>} event Durable Execution event.
132
+ * @param {Tracer} tracer Core tracer.
133
+ * @returns {SpanContext|null}
134
+ */
135
+ function extractDurableExecution (event, tracer) {
136
+ if (!event?.DurableExecutionArn) return null
137
+ const operations = event.InitialExecutionState?.Operations
138
+ if (!operations || operations.length === 0) return null
139
+ let best = null
140
+ for (const op of operations) {
141
+ if (typeof op?.Name !== 'string' || !op.Name.startsWith('_datadog_')) continue
142
+ const suffix = op.Name.slice('_datadog_'.length)
143
+ const number = Number.parseInt(suffix, 10)
144
+ if (Number.isNaN(number) || String(number) !== suffix) continue
145
+ if (best === null || number > best.number) best = { number, op }
146
+ }
147
+ if (best === null) return null
148
+ const raw = best.op.Payload ?? best.op.StepDetails?.Result
149
+ if (!raw || typeof raw !== 'string') return null
150
+ let headers
151
+ try {
152
+ headers = JSON.parse(raw)
153
+ } catch (error) {
154
+ log.debug('Failed to parse trace checkpoint payload: %s', error)
155
+ }
156
+ return headers && typeof headers === 'object' ? tracer.extract('text_map', headers) : null
157
+ }
158
+
159
+ module.exports = {
160
+ getSNSHeaders,
161
+ getSNSSQSHeaders,
162
+ getSQSHeaders,
163
+ getEventBridgeSQSHeaders,
164
+ extractKinesis,
165
+ extractMSK,
166
+ extractDurableExecution,
167
+ }
@@ -0,0 +1,153 @@
1
+ 'use strict'
2
+
3
+ // Ported from datadog-lambda-js at da9fc3c0; propagation itself stays core-owned.
4
+ const log = require('../../../dd-trace/src/log')
5
+ const guards = require('../event-type-guards')
6
+ const {
7
+ getSNSHeaders,
8
+ getSNSSQSHeaders,
9
+ getSQSHeaders,
10
+ getEventBridgeSQSHeaders,
11
+ extractKinesis,
12
+ extractMSK,
13
+ extractDurableExecution,
14
+ } = require('./events')
15
+ const { extractHTTP } = require('./http')
16
+ const { fromTraceContext } = require('./span-context')
17
+ const { getStepFunctionContext, extractStepFunctionContext } = require('./step-functions')
18
+ const { extractDatadogContext, extractXrayContext, getAWSTraceHeader } = require('./xray')
19
+
20
+ /**
21
+ * @typedef {object} ExtractedContext
22
+ * @property {import('../../../dd-trace/src/opentracing/span_context')|null} spanContext
23
+ * @property {'event'|'xray'|'ddtrace'|undefined} source
24
+ */
25
+
26
+ class TraceContextExtractor {
27
+ #tracer
28
+ #config
29
+ #stepFunction
30
+
31
+ /**
32
+ * One extractor per invocation keeps source first-use Step Functions caching invocation-local.
33
+ * @param {import('../../../dd-trace/src/opentracing/tracer')} tracer Core tracer.
34
+ * @param {import('./types').ExtractorConfig} config Lambda configuration.
35
+ */
36
+ constructor (tracer, config) {
37
+ this.#tracer = tracer
38
+ this.#config = config
39
+ }
40
+
41
+ /**
42
+ * @param {Record<string, unknown>} event Lambda event.
43
+ * @param {Record<string, unknown>} context Lambda context.
44
+ * @returns {ExtractedContext|Promise<ExtractedContext>}
45
+ */
46
+ extract (event, context) {
47
+ if (this.#config.traceExtractor) return this.#extractCustom(event, context)
48
+ return this.#extractFallback(event, context)
49
+ }
50
+
51
+ /**
52
+ * Preserve the shim callback contract: pass the original event (of any shape) and AWS Lambda Context unchanged.
53
+ * Existing typed extractors return a trace context synchronously or through a Promise. It contains decimal
54
+ * traceId/parentId strings, numeric sampleMode (-1, 0, 1, 2) and source ('event', 'xray', 'ddtrace'); legacy
55
+ * traceID/parentID names remain accepted. Preparation awaits extraction before the invocation span starts.
56
+ * Failed extraction resumes the event, Step Functions, Lambda client-context and X-Ray fallback chain.
57
+ *
58
+ * @param {Record<string, unknown>} event Lambda event.
59
+ * @param {Record<string, unknown>} context Lambda context.
60
+ * @returns {Promise<ExtractedContext>}
61
+ */
62
+ async #extractCustom (event, context) {
63
+ try {
64
+ const custom = await this.#config.traceExtractor(event, context)
65
+ const spanContext = fromTraceContext(custom)
66
+ if (spanContext !== null) return { spanContext, source: custom.source }
67
+ } catch (error) {
68
+ log.error('Unable to extract trace context. Custom extractor function failed: %s', error)
69
+ }
70
+ return this.#extractFallback(event, context)
71
+ }
72
+
73
+ /**
74
+ * @param {Record<string, unknown>} event Lambda event.
75
+ * @param {Record<string, unknown>} context Lambda context.
76
+ * @returns {ExtractedContext}
77
+ */
78
+ #extractFallback (event, context) {
79
+ let spanContext = this.#extractEvent(event)
80
+ if (spanContext === null) spanContext = this.#extractStepFunction(event)
81
+ if (spanContext === null && context && typeof context === 'object') {
82
+ const custom = context.clientContext?.custom
83
+ if (custom && typeof custom === 'object') {
84
+ spanContext = this.#tracer.extract('text_map', custom._datadog === undefined ? custom : custom._datadog)
85
+ }
86
+ }
87
+ if (spanContext !== null) return { spanContext, source: 'event' }
88
+ return { spanContext: extractXrayContext(), source: 'xray' }
89
+ }
90
+
91
+ /**
92
+ * @param {Record<string, unknown>} event Lambda event.
93
+ * @returns {import('../../../dd-trace/src/opentracing/span_context')|null}
94
+ */
95
+ #extractEvent (event) {
96
+ if (!event || typeof event !== 'object') return null
97
+ if (guards.isDurableExecutionEvent(event)) return extractDurableExecution(event, this.#tracer)
98
+ const headers = event.headers ?? event.multiValueHeaders
99
+ if (headers !== null && typeof headers === 'object') {
100
+ return extractHTTP(event, this.#tracer, this.#config.decodeAuthorizerContext)
101
+ }
102
+ if (guards.isSNSEvent(event)) {
103
+ return this.#extractMessage(getSNSHeaders(event.Records[0]), getAWSTraceHeader())
104
+ }
105
+ if (guards.isSNSSQSEvent(event)) {
106
+ return this.#extractMessage(getSNSSQSHeaders(event.Records[0]), event.Records[0]?.attributes?.AWSTraceHeader)
107
+ }
108
+ if (guards.isEventBridgeSQSEvent(event)) {
109
+ return this.#extractMessage(getEventBridgeSQSHeaders(event.Records[0]))
110
+ }
111
+ if (guards.isAppSyncResolverEvent(event)) {
112
+ event.headers = event.request.headers
113
+ return extractHTTP(event, this.#tracer, false)
114
+ }
115
+ if (guards.isMSKEvent(event)) return extractMSK(event, this.#tracer)
116
+ if (guards.isSQSEvent(event)) {
117
+ return this.#extractMessage(getSQSHeaders(event.Records[0]), event.Records[0]?.attributes?.AWSTraceHeader)
118
+ }
119
+ if (guards.isKinesisStreamEvent(event)) return extractKinesis(event, this.#tracer)
120
+ if (guards.isEventBridgeEvent(event)) return this.#extractMessage(event?.detail?._datadog)
121
+ return null
122
+ }
123
+
124
+ /**
125
+ * Message carriers may contain Step Functions context instead of propagation headers.
126
+ * @param {Record<string, string>|null|undefined} headers Message carrier.
127
+ * @param {string} [awsTraceHeader] Optional Java-injected Datadog context.
128
+ * @returns {import('../../../dd-trace/src/opentracing/span_context')|null}
129
+ */
130
+ #extractMessage (headers, awsTraceHeader) {
131
+ try {
132
+ if (headers) {
133
+ const spanContext = this.#tracer.extract('text_map', headers) || this.#extractStepFunction(headers)
134
+ if (spanContext) return spanContext
135
+ }
136
+ if (awsTraceHeader !== undefined) return extractDatadogContext(awsTraceHeader)
137
+ } catch (error) {
138
+ log.debug('Unable to extract trace context from message: %s', error)
139
+ }
140
+ return null
141
+ }
142
+
143
+ /**
144
+ * @param {Record<string, unknown>} event Event or message carrier.
145
+ * @returns {import('../../../dd-trace/src/opentracing/span_context')|null}
146
+ */
147
+ #extractStepFunction (event) {
148
+ this.#stepFunction ??= { context: getStepFunctionContext(event) }
149
+ return extractStepFunctionContext(this.#stepFunction.context)
150
+ }
151
+ }
152
+
153
+ module.exports = TraceContextExtractor
@@ -0,0 +1,50 @@
1
+ 'use strict'
2
+
3
+ const log = require('../../../dd-trace/src/log')
4
+ const { isAPIGatewayEventV2, isAPIGatewayEvent } = require('../event-type-guards')
5
+
6
+ const AUTHORIZING_REQUEST_ID_HEADER = 'x-datadog-authorizing-requestid'
7
+
8
+ /**
9
+ * Decodes the authorizer's carrier only for an uncached authorization.
10
+ * @param {Record<string, unknown>} event HTTP event.
11
+ * @returns {Record<string, string>|null}
12
+ */
13
+ function getInjectedAuthorizerHeaders (event) {
14
+ const authorizer = event?.requestContext?.authorizer
15
+ if (!authorizer) return null
16
+ let raw = authorizer._datadog
17
+ // Keep REST classification ahead of HTTP API classification for overlapping shapes.
18
+ if (!isAPIGatewayEvent(event) && isAPIGatewayEventV2(event)) raw = authorizer.lambda._datadog
19
+ if (!raw) return null
20
+ const headers = JSON.parse(Buffer.from(raw, 'base64').toString())
21
+ if (authorizer.integrationLatency > 0 ||
22
+ event.requestContext.requestId === headers[AUTHORIZING_REQUEST_ID_HEADER]) return headers
23
+ return null
24
+ }
25
+
26
+ /**
27
+ * @param {Record<string, unknown>} event HTTP event.
28
+ * @param {import('../../../dd-trace/src/opentracing/tracer')} tracer Core tracer.
29
+ * @param {boolean} [decodeAuthorizerContext] Decode authorizer metadata.
30
+ * @returns {import('../../../dd-trace/src/opentracing/span_context')|null}
31
+ */
32
+ function extractHTTP (event, tracer, decodeAuthorizerContext = true) {
33
+ if (decodeAuthorizerContext) {
34
+ try {
35
+ const injected = getInjectedAuthorizerHeaders(event)
36
+ if (injected !== null) return tracer.extract('text_map', injected)
37
+ } catch (error) {
38
+ log.debug('Unable to extract trace context from authorizer event: %s', error)
39
+ }
40
+ }
41
+ const headers = event.headers ?? event.multiValueHeaders
42
+ const carrier = {}
43
+ for (const [key, value] of Object.entries(headers)) {
44
+ if (Array.isArray(value)) carrier[key.toLowerCase()] = value[0] ?? ''
45
+ else if (typeof value === 'string') carrier[key.toLowerCase()] = value
46
+ }
47
+ return tracer.extract('text_map', carrier)
48
+ }
49
+
50
+ module.exports = { extractHTTP, getInjectedAuthorizerHeaders, AUTHORIZING_REQUEST_ID_HEADER }
@@ -0,0 +1,26 @@
1
+ 'use strict'
2
+
3
+ const { AUTO_KEEP } = require('../../../../ext/priority')
4
+ const id = require('../../../dd-trace/src/id')
5
+ const SpanContext = require('../../../dd-trace/src/opentracing/span_context')
6
+
7
+ /**
8
+ * Converts the shim's custom context contract to the core tracer's context.
9
+ * Numeric sampling follows datadog-lambda-js #850 (13e2f4ca).
10
+ *
11
+ * @param {import('./types').TraceContext} context Custom extractor result.
12
+ * @returns {SpanContext|null}
13
+ */
14
+ function fromTraceContext (context) {
15
+ const traceId = context.traceId || context.traceID
16
+ const spanId = context.parentId || context.parentID
17
+ if (traceId === undefined || spanId === undefined) return null
18
+
19
+ return new SpanContext({
20
+ traceId: id(traceId, 10),
21
+ spanId: id(spanId, 10),
22
+ sampling: { priority: context.sampleMode },
23
+ })
24
+ }
25
+
26
+ module.exports = { fromTraceContext, AUTO_KEEP }