dd-trace 5.133.0 → 5.135.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 (194) hide show
  1. package/LICENSE-3rdparty.csv +0 -1
  2. package/ci/cypress/support.js +15 -1
  3. package/ci/diagnose.js +4 -4
  4. package/ci/test-annotations.d.ts +5 -0
  5. package/ci/test-annotations.js +5 -0
  6. package/ci/test-optimization-validation/approval-artifacts.js +2 -2
  7. package/ci/test-optimization-validation/approval.js +2 -2
  8. package/ci/test-optimization-validation/artifact-id.js +2 -3
  9. package/ci/test-optimization-validation/ci-package-scripts.js +1 -1
  10. package/ci/test-optimization-validation/cli.js +1 -1
  11. package/ci/test-optimization-validation/command-runner.js +2 -3
  12. package/ci/test-optimization-validation/executable.js +1 -1
  13. package/ci/test-optimization-validation/framework-adapters/cucumber.js +1 -1
  14. package/ci/test-optimization-validation/literal-environment.js +2 -2
  15. package/ci/test-optimization-validation/manifest-scaffold.js +1 -1
  16. package/ci/test-optimization-validation/offline-fixtures.js +1 -1
  17. package/ci/test-optimization-validation/redaction.js +3 -3
  18. package/ci/test-optimization-validation/runner-contract.js +10 -10
  19. package/ci/test-optimization-validation/scenarios/ci-wiring.js +1 -1
  20. package/ci/vitest-no-worker-init-annotations.mjs +4 -0
  21. package/ci/vitest-no-worker-init-node-setup.mjs +22 -0
  22. package/ci/vitest-no-worker-init-runner-setup.mjs +7 -5
  23. package/ci/vitest-no-worker-init-setup.mjs +34 -12
  24. package/ci/vitest-no-worker-init-v5-setup.mjs +6 -0
  25. package/ext/exporters.js +1 -0
  26. package/index.d.ts +35 -5
  27. package/loader-hook.mjs +53 -0
  28. package/openfeature/exposure-hook.d.ts +66 -0
  29. package/openfeature/exposure-hook.js +5 -0
  30. package/package.json +23 -20
  31. package/packages/datadog-core/src/storage.js +1 -1
  32. package/packages/datadog-esbuild/index.js +70 -7
  33. package/packages/datadog-instrumentations/index.js +2 -1
  34. package/packages/datadog-instrumentations/src/cucumber.js +64 -21
  35. package/packages/datadog-instrumentations/src/cypress-config.js +163 -15
  36. package/packages/datadog-instrumentations/src/graphql.js +9 -3
  37. package/packages/datadog-instrumentations/src/grpc/server.js +23 -6
  38. package/packages/datadog-instrumentations/src/helpers/bundler-register.js +27 -8
  39. package/packages/datadog-instrumentations/src/helpers/fetch.js +5 -1
  40. package/packages/datadog-instrumentations/src/helpers/graphql-jit-runtime.js +30 -8
  41. package/packages/datadog-instrumentations/src/helpers/hooks.js +2 -1
  42. package/packages/datadog-instrumentations/src/helpers/register.js +9 -0
  43. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +16 -6
  44. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +10 -0
  45. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql-jit.js +3 -1
  46. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/jest.js +12 -0
  47. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/react-router.js +49 -0
  48. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/typesafe.js +23 -0
  49. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/vitest.js +8 -0
  50. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/webdriverio.js +12 -0
  51. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +8 -0
  52. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.js +19 -2
  53. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +13 -0
  54. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +1 -1
  55. package/packages/datadog-instrumentations/src/jest.js +332 -137
  56. package/packages/datadog-instrumentations/src/mariadb-bundle.js +69 -11
  57. package/packages/datadog-instrumentations/src/mariadb.js +13 -6
  58. package/packages/datadog-instrumentations/src/mocha/common.js +89 -8
  59. package/packages/datadog-instrumentations/src/mocha/main.js +11 -2
  60. package/packages/datadog-instrumentations/src/mocha/utils.js +92 -13
  61. package/packages/datadog-instrumentations/src/mocha/worker.js +1 -1
  62. package/packages/datadog-instrumentations/src/nova-sonic/session.js +25 -16
  63. package/packages/datadog-instrumentations/src/oracledb.js +33 -0
  64. package/packages/datadog-instrumentations/src/pg.js +2 -1
  65. package/packages/datadog-instrumentations/src/playwright.js +81 -26
  66. package/packages/datadog-instrumentations/src/react-router.js +106 -0
  67. package/packages/datadog-instrumentations/src/stripe.js +23 -12
  68. package/packages/datadog-instrumentations/src/typesafe.js +89 -0
  69. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +84 -47
  70. package/packages/datadog-instrumentations/src/vitest-main.js +33 -3
  71. package/packages/datadog-instrumentations/src/vitest-test-annotations.js +20 -0
  72. package/packages/datadog-instrumentations/src/vitest-util.js +5 -2
  73. package/packages/datadog-instrumentations/src/vitest-worker.js +39 -17
  74. package/packages/datadog-instrumentations/src/vitest.js +16 -6
  75. package/packages/datadog-plugin-cucumber/src/index.js +5 -0
  76. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +277 -44
  77. package/packages/datadog-plugin-cypress/src/index.js +1 -1
  78. package/packages/datadog-plugin-cypress/src/lifecycle-owner.js +20 -0
  79. package/packages/datadog-plugin-cypress/src/plugin.js +10 -0
  80. package/packages/datadog-plugin-cypress/src/retry-config-observer.js +281 -0
  81. package/packages/datadog-plugin-cypress/src/setup-handoff.js +125 -0
  82. package/packages/datadog-plugin-cypress/src/support.js +1217 -437
  83. package/packages/datadog-plugin-graphql/src/execute.js +2 -2
  84. package/packages/datadog-plugin-graphql/src/utils.js +5 -5
  85. package/packages/datadog-plugin-jest/src/index.js +25 -3
  86. package/packages/datadog-plugin-mocha/src/index.js +47 -6
  87. package/packages/datadog-plugin-oracledb/src/connection-parser.js +21 -11
  88. package/packages/datadog-plugin-playwright/src/index.js +4 -0
  89. package/packages/datadog-plugin-react-router/src/index.js +118 -0
  90. package/packages/datadog-plugin-typesafe/src/index.js +17 -0
  91. package/packages/datadog-plugin-typesafe/src/tracing.js +31 -0
  92. package/packages/datadog-plugin-vitest/src/index.js +8 -0
  93. package/packages/dd-trace/src/agent/info.js +2 -1
  94. package/packages/dd-trace/src/aiguard/evaluation.js +143 -1
  95. package/packages/dd-trace/src/aiguard/sdk.js +0 -11
  96. package/packages/dd-trace/src/appsec/iast/path-line.js +2 -1
  97. package/packages/dd-trace/src/appsec/stack_trace.js +3 -2
  98. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/worker/index.js +3 -2
  99. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +9 -16
  100. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +4 -2
  101. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +9 -16
  102. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +9 -14
  103. package/packages/dd-trace/src/ci-visibility/requests/route.js +44 -0
  104. package/packages/dd-trace/src/ci-visibility/telemetry-logs.js +5 -0
  105. package/packages/dd-trace/src/ci-visibility/test-annotations.js +72 -0
  106. package/packages/dd-trace/src/ci-visibility/test-declaration-annotations.js +170 -0
  107. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +9 -16
  108. package/packages/dd-trace/src/config/defaults.js +4 -3
  109. package/packages/dd-trace/src/config/generated-config-types.d.ts +6 -0
  110. package/packages/dd-trace/src/config/index.js +140 -39
  111. package/packages/dd-trace/src/config/parsers.js +9 -1
  112. package/packages/dd-trace/src/config/supported-configurations.json +25 -0
  113. package/packages/dd-trace/src/debugger/devtools_client/breakpoints.js +6 -5
  114. package/packages/dd-trace/src/debugger/devtools_client/condition.js +5 -5
  115. package/packages/dd-trace/src/debugger/devtools_client/snapshot/collector.js +4 -6
  116. package/packages/dd-trace/src/debugger/probe_sampler.js +6 -6
  117. package/packages/dd-trace/src/debugger/unsupported-runtime.js +16 -0
  118. package/packages/dd-trace/src/encode/0.4.js +2 -2
  119. package/packages/dd-trace/src/esm-module-load.js +58 -0
  120. package/packages/dd-trace/src/exporter.js +25 -6
  121. package/packages/dd-trace/src/exporters/agent/index.js +3 -1
  122. package/packages/dd-trace/src/exporters/agentless/index.js +3 -1
  123. package/packages/dd-trace/src/exporters/common/request.js +4 -4
  124. package/packages/dd-trace/src/exporters/llmobs/index.js +135 -0
  125. package/packages/dd-trace/src/exporters/log/index.js +4 -3
  126. package/packages/dd-trace/src/llmobs/agent-manifest.js +19 -2
  127. package/packages/dd-trace/src/llmobs/constants/tags.js +4 -0
  128. package/packages/dd-trace/src/llmobs/experiments/index.js +2 -3
  129. package/packages/dd-trace/src/llmobs/experiments/noop.js +5 -2
  130. package/packages/dd-trace/src/llmobs/index.js +13 -2
  131. package/packages/dd-trace/src/llmobs/plugins/claude-agent-sdk/index.js +1 -1
  132. package/packages/dd-trace/src/llmobs/plugins/genai/index.js +1 -1
  133. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +8 -4
  134. package/packages/dd-trace/src/llmobs/plugins/openai/constants.js +5 -0
  135. package/packages/dd-trace/src/llmobs/plugins/openai/index.js +9 -1
  136. package/packages/dd-trace/src/llmobs/plugins/typesafe/index.js +102 -0
  137. package/packages/dd-trace/src/llmobs/prompts/cache.js +3 -1
  138. package/packages/dd-trace/src/llmobs/sdk.js +17 -5
  139. package/packages/dd-trace/src/llmobs/span_processor.js +222 -12
  140. package/packages/dd-trace/src/llmobs/tagger.js +21 -8
  141. package/packages/dd-trace/src/llmobs/util.js +10 -4
  142. package/packages/dd-trace/src/llmobs/writers/util.js +3 -3
  143. package/packages/dd-trace/src/log/writer.js +7 -1
  144. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +64 -6
  145. package/packages/dd-trace/src/openfeature/configuration_source.js +18 -2
  146. package/packages/dd-trace/src/openfeature/debug-logging-hook.js +66 -3
  147. package/packages/dd-trace/src/openfeature/exposure-hook.js +185 -0
  148. package/packages/dd-trace/src/openfeature/flagging_provider.js +39 -13
  149. package/packages/dd-trace/src/openfeature/index.js +6 -0
  150. package/packages/dd-trace/src/openfeature/remote_config.js +16 -3
  151. package/packages/dd-trace/src/openfeature/writers/base.js +62 -27
  152. package/packages/dd-trace/src/openfeature/writers/exposures.js +161 -1
  153. package/packages/dd-trace/src/openfeature/writers/flag-eval-evp-hook.js +5 -0
  154. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-aggregation.js +9 -4
  155. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-payload.js +2 -0
  156. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-pii.js +2 -0
  157. package/packages/dd-trace/src/openfeature/writers/split-features.js +25 -0
  158. package/packages/dd-trace/src/openfeature/writers/util.js +4 -4
  159. package/packages/dd-trace/src/opentelemetry/metrics/periodic_metric_reader.js +2 -2
  160. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +18 -1
  161. package/packages/dd-trace/src/opentelemetry/tracer_provider.js +5 -1
  162. package/packages/dd-trace/src/opentracing/tracer.js +9 -13
  163. package/packages/dd-trace/src/otel-thread-ctx.js +47 -21
  164. package/packages/dd-trace/src/plugin_manager.js +1 -2
  165. package/packages/dd-trace/src/plugins/ci_plugin.js +4 -4
  166. package/packages/dd-trace/src/plugins/index.js +3 -0
  167. package/packages/dd-trace/src/plugins/tracing.js +1 -2
  168. package/packages/dd-trace/src/plugins/util/git.js +102 -40
  169. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +2 -4
  170. package/packages/dd-trace/src/plugins/util/stacktrace.js +2 -1
  171. package/packages/dd-trace/src/plugins/util/test.js +28 -6
  172. package/packages/dd-trace/src/plugins/util/web.js +106 -20
  173. package/packages/dd-trace/src/process-tags/index.js +1 -1
  174. package/packages/dd-trace/src/profiling/config.js +6 -3
  175. package/packages/dd-trace/src/proxy.js +15 -4
  176. package/packages/dd-trace/src/serverless.js +3 -2
  177. package/packages/dd-trace/src/span_processor.js +21 -9
  178. package/packages/dd-trace/src/span_stats.js +32 -3
  179. package/packages/dd-trace/src/startup-log.js +2 -1
  180. package/packages/dd-trace/src/tagger.js +7 -5
  181. package/packages/dd-trace/src/telemetry/dependencies.js +4 -0
  182. package/packages/dd-trace/src/telemetry/index.js +3 -0
  183. package/packages/dd-trace/src/telemetry/logs/index.js +21 -2
  184. package/packages/dd-trace/src/telemetry/logs/log-collector.js +2 -1
  185. package/packages/dd-trace/src/telemetry/telemetry.js +10 -3
  186. package/packages/dd-trace/src/util.js +9 -5
  187. package/register.js +2 -1
  188. package/vendor/dist/@apm-js-collab/code-transformer/index.js +8 -8
  189. package/vendor/dist/@datadog/openfeature-node-server/index.js +1 -1
  190. package/vendor/dist/@datadog/openfeature-node-server/rules-based/index.d.ts +78 -0
  191. package/vendor/dist/@datadog/openfeature-node-server/rules-based/index.js +1 -1
  192. package/vendor/dist/@opentelemetry/core/index.js +1 -1
  193. package/vendor/dist/@opentelemetry/resources/LICENSE +0 -201
  194. package/vendor/dist/@opentelemetry/resources/index.js +0 -1
@@ -13,6 +13,10 @@ const EvaluationTelemetryOptOutHook = require('./evaluation-telemetry-opt-out-ho
13
13
  const SpanEnrichmentHook = require('./span-enrichment-hook')
14
14
  const FlagEvalEVPHook = require('./writers/flag-eval-evp-hook')
15
15
 
16
+ const RAW_EVALUATION_DATA_WARNING = 'Feature Flags: debug logging is enabled, so feature flag logs include raw ' +
17
+ 'evaluation data (targeting keys, evaluation context attributes, flag values, and default values) that may ' +
18
+ 'contain personal or sensitive information. Unset DD_TRACE_DEBUG when you no longer need it.'
19
+
16
20
  /**
17
21
  * OpenFeature provider that integrates with Datadog's feature flagging system.
18
22
  * Extends DatadogNodeServerProvider to add tracer integration and configuration management.
@@ -30,6 +34,9 @@ class FlaggingProvider extends DatadogNodeServerProvider {
30
34
  /** @type {{ start: Function, stop: Function } | undefined} */
31
35
  #configurationSource
32
36
 
37
+ /** @type {number} */
38
+ #initializationTimeoutMs
39
+
33
40
  /**
34
41
  * @param {import('../tracer')} tracer - Datadog tracer instance
35
42
  * @param {import('../config/config-base')} config - Tracer configuration object
@@ -52,7 +59,8 @@ class FlaggingProvider extends DatadogNodeServerProvider {
52
59
  }
53
60
 
54
61
  if (config.debug && debugChannel.hasSubscribers) {
55
- this.hooks.push(new DebugLoggingHook())
62
+ this.hooks.push(new DebugLoggingHook(() => this.getConfiguration()))
63
+ log.warn(RAW_EVALUATION_DATA_WARNING)
56
64
  }
57
65
 
58
66
  if (config.featureFlags.DD_EXPERIMENTAL_FLAGGING_PROVIDER_SPAN_ENRICHMENT_ENABLED) {
@@ -64,8 +72,10 @@ class FlaggingProvider extends DatadogNodeServerProvider {
64
72
  log.info('%s span enrichment disabled', this.constructor.name)
65
73
  }
66
74
 
67
- log.debug('%s created with timeout: %dms', this.constructor.name,
68
- config.featureFlags.DD_EXPERIMENTAL_FLAGGING_PROVIDER_INITIALIZATION_TIMEOUT_MS)
75
+ this.#initializationTimeoutMs = config.featureFlags.DD_EXPERIMENTAL_FLAGGING_PROVIDER_INITIALIZATION_TIMEOUT_MS
76
+ log.debug('Feature Flags: %s created (configuration source %s, sdk env=%s, initialization timeout %dms)',
77
+ this.constructor.name, config.featureFlags.DD_FEATURE_FLAGS_CONFIGURATION_SOURCE, config.env ?? 'unset',
78
+ this.#initializationTimeoutMs)
69
79
 
70
80
  if (config.featureFlags?.DD_FLAGGING_EVALUATION_COUNTS_ENABLED !== false) {
71
81
  this.#flagEvalEVPHook = new FlagEvalEVPHook(config)
@@ -81,18 +91,16 @@ class FlaggingProvider extends DatadogNodeServerProvider {
81
91
  * @returns {Promise<void>}
82
92
  */
83
93
  initialize (context) {
84
- log.debug('Feature Flags: waiting for provider initialization...')
94
+ const hasConfiguration = this.getConfiguration() !== undefined
85
95
 
86
- this.#waitingForConfiguration = !this.getConfiguration()
96
+ this.#waitingForConfiguration = !hasConfiguration
87
97
  const promise = super.initialize(context)
88
98
 
89
- // `DatadogNodeServerProvider#initialize` starts a timer that is never unref'd, which would
90
- // otherwise keep an idle process (a short script, a serverless handler) alive for up to
91
- // `initializationTimeoutMs` while waiting for configuration to arrive.
92
- // TODO: remove once `@datadog/openfeature-node-server` unrefs this timer itself.
93
- this.initController?.timeoutId?.unref?.()
94
-
95
- if (this.getConfiguration()) this.#logInitialConfiguration()
99
+ if (hasConfiguration) {
100
+ this.#logInitialConfiguration()
101
+ } else {
102
+ log.debug('Feature Flags: waiting for provider initialization (timeout %dms)...', this.#initializationTimeoutMs)
103
+ }
96
104
 
97
105
  return promise
98
106
  }
@@ -102,9 +110,20 @@ class FlaggingProvider extends DatadogNodeServerProvider {
102
110
  */
103
111
  setConfiguration (configuration) {
104
112
  const wasWaiting = this.#waitingForConfiguration
113
+ // The upstream provider emits PROVIDER_READY for this transition without logging it.
114
+ const recovering = !wasWaiting && configuration != null && this.getConfiguration() == null &&
115
+ this.initController !== undefined && !this.initController.isInitializing()
116
+
105
117
  super.setConfiguration(configuration)
118
+ // An empty update leaves upstream initialization pending until configuration arrives or it times out.
119
+ if (configuration == null) return
106
120
  this.#waitingForConfiguration = false
107
- if (wasWaiting && configuration != null) this.#logInitialConfiguration()
121
+
122
+ if (wasWaiting) {
123
+ this.#logInitialConfiguration()
124
+ } else if (recovering) {
125
+ this.#logRecovery()
126
+ }
108
127
  }
109
128
 
110
129
  /**
@@ -131,6 +150,12 @@ class FlaggingProvider extends DatadogNodeServerProvider {
131
150
  } catch { /* logging failure must not affect initialization */ }
132
151
  }
133
152
 
153
+ #logRecovery () {
154
+ try {
155
+ log.debug('Feature Flags: configuration applied after the provider was not ready; provider is ready again')
156
+ } catch { /* logging failure must not affect applying the configuration */ }
157
+ }
158
+
134
159
  /**
135
160
  * Called when the provider is shut down.
136
161
  * Cleans up resources including channel subscriptions.
@@ -142,6 +167,7 @@ class FlaggingProvider extends DatadogNodeServerProvider {
142
167
  this.#spanEnrichmentHook = undefined
143
168
  this.#flagEvalEVPHook?.destroy()
144
169
  this.#flagEvalEVPHook = undefined
170
+ log.debug('Feature Flags: provider closed')
145
171
  }
146
172
  }
147
173
 
@@ -33,6 +33,12 @@ function _handleFlush () {
33
33
  * @param {import('../config')} config - Tracer configuration object
34
34
  */
35
35
  function enable (config) {
36
+ if (config.featureFlags?.DD_FEATURE_FLAGS_EXPOSURES_DATADOG_LOGGING_ENABLED === false) {
37
+ log.debug('Feature Flags: Datadog exposure logging disabled; set %s=true to enable',
38
+ 'DD_FEATURE_FLAGS_EXPOSURES_DATADOG_LOGGING_ENABLED')
39
+ return
40
+ }
41
+
36
42
  if (exposuresWriter) {
37
43
  log.warn('%s already enabled', exposuresWriter.constructor.name)
38
44
  return
@@ -20,18 +20,31 @@ function enable (rc, getOpenfeatureProxy, subscribe) {
20
20
  /**
21
21
  * @param {string} action
22
22
  * @param {import('@datadog/openfeature-node-server').UniversalFlagConfigurationV1} conf
23
+ * @param {string} [id] - Remote Config configuration ID
23
24
  */
24
- const updateConfiguration = (action, conf) => {
25
+ const updateConfiguration = (action, conf, id) => {
25
26
  if (action === 'apply' || action === 'modify') {
26
27
  getOpenfeatureProxy().setConfiguration(conf)
28
+ // Counting flags allocates a key array, so it stays behind the debug callback.
27
29
  // eslint-disable-next-line eslint-rules/eslint-log-printf-style
28
30
  log.debug(() => {
31
+ // The payload is not schema-validated and this runs after setConfiguration, so a throw here would
32
+ // report an already applied configuration as failed only when debug logging is on. Template literals
33
+ // throw on values such as `{ toString: null }`, so the callback returns printf arguments instead.
29
34
  const flagCount = Object.keys(conf?.flags ?? {}).length
30
- return `Feature Flags: remote_config configuration ${action} applied successfully (${flagCount} flag(s))`
35
+ return [
36
+ 'Feature Flags: remote_config configuration %s applied successfully ' +
37
+ '(%d flag(s) received; per-flag validity is checked at evaluation, ' +
38
+ 'configuration environment=%s, createdAt=%s, id=%s)',
39
+ action, flagCount, conf?.environment?.name, conf?.createdAt, id,
40
+ ]
31
41
  })
32
42
  } else if (action === 'unapply') {
33
- log.debug('Feature Flags: remote_config configuration removed')
34
43
  getOpenfeatureProxy().setConfiguration(undefined)
44
+ log.debug(
45
+ 'Feature Flags: remote_config configuration %s removed; flag evaluations will return their default values',
46
+ id
47
+ )
35
48
  }
36
49
  }
37
50
  rc.setProductHandler('FFE_FLAGS', updateConfiguration)
@@ -143,7 +143,14 @@ class BaseFFEWriter {
143
143
  continue
144
144
  }
145
145
 
146
- const eventSizeBytes = Buffer.byteLength(JSON.stringify(event))
146
+ let eventSizeBytes
147
+ try {
148
+ eventSizeBytes = Buffer.byteLength(JSON.stringify(event))
149
+ } catch {
150
+ log.warn('%s could not serialize an event, dropping event', this.constructor.name)
151
+ this._droppedEvents++
152
+ continue
153
+ }
147
154
 
148
155
  // Check individual event size limit if configured
149
156
  if (this._eventSizeLimit && eventSizeBytes > this._eventSizeLimit) {
@@ -175,7 +182,14 @@ class BaseFFEWriter {
175
182
  this._buffer = []
176
183
  this._bufferSize = 0
177
184
 
178
- const payload = this._encode(this.makePayload(events))
185
+ let payload
186
+ try {
187
+ payload = this._encode(this.makePayload(events))
188
+ } catch {
189
+ log.warn('%s could not encode %d events, dropping batch', this.constructor.name, events.length)
190
+ this._droppedEvents += events.length
191
+ return
192
+ }
179
193
 
180
194
  // Keep byte counting behind the debug callback because payloads can be several megabytes.
181
195
  // eslint-disable-next-line eslint-rules/eslint-log-printf-style
@@ -198,14 +212,19 @@ class BaseFFEWriter {
198
212
  */
199
213
  destroy () {
200
214
  if (this.#destroyer) {
201
- log.debug('Stopping %s', this.constructor.name)
215
+ log.debug('%s stopping with %d buffered events; final flush requested without awaiting delivery',
216
+ this.constructor.name, this._buffer.length)
202
217
  clearInterval(this._periodic)
203
218
  this.flush()
204
219
  globalThis[Symbol.for('dd-trace')].beforeExitHandlers.delete(this.#destroyer)
205
220
  this.#destroyer = undefined
206
221
 
207
222
  if (this._droppedEvents > 0) {
208
- log.warn('%s dropped %d events due to buffer overflow', this.constructor.name, this._droppedEvents)
223
+ log.warn(
224
+ '%s dropped %d events (buffer capacity, size limits, serialization or delivery failures)',
225
+ this.constructor.name,
226
+ this._droppedEvents
227
+ )
209
228
  }
210
229
  }
211
230
  }
@@ -313,13 +332,14 @@ class BaseFFEWriter {
313
332
  // The request helper mutates headers. Concurrent envelopes must not share them.
314
333
  const requestOptions = { ...route.requestOptions, headers: { ...route.requestOptions.headers } }
315
334
  request(payload, requestOptions, (error, response, statusCode) => {
316
- const errorMessage = error && (this.#formatError ? this.#formatError(error, statusCode) : error.message)
335
+ const errorMessage = error && (this.#formatError
336
+ ? this.#formatError(error, statusCode)
337
+ : error.message)
317
338
  if (fallbackRoute && isSafeToReplay(error, statusCode)) {
318
339
  log.debug(
319
- '%s switching from %s%s to direct intake after definitive rejection',
340
+ '%s switching from %s to direct intake after definitive rejection',
320
341
  this.constructor.name,
321
- route.url.href,
322
- route.endpoint
342
+ route.url.origin
323
343
  )
324
344
  if (this._requestOptions === route.requestOptions) {
325
345
  this.#activateRoute(fallbackRoute)
@@ -332,27 +352,25 @@ class BaseFFEWriter {
332
352
 
333
353
  if (fallbackRoute && isTransportFailure(error, statusCode)) {
334
354
  log.debug(
335
- '%s switching future batches from %s%s to direct intake after an ambiguous failure without replay',
355
+ '%s switching future batches from %s to direct intake after an ambiguous failure without replay',
336
356
  this.constructor.name,
337
- route.url.href,
338
- route.endpoint
357
+ route.url.origin
339
358
  )
340
359
  if (this._requestOptions === route.requestOptions) {
341
360
  this.#activateRoute(fallbackRoute)
342
361
  this._fallbackRoute = undefined
343
362
  route.onFallback?.()
344
363
  }
345
- log.error('Failed to send events to %s%s: %s', route.url.href, route.endpoint, errorMessage)
364
+ this.#logDropped(route, eventCount, error, errorMessage, statusCode)
346
365
  onComplete?.(false)
347
366
  return
348
367
  }
349
368
 
350
369
  if (fallbackRoute && shouldSwitchFutureRoute(statusCode)) {
351
370
  log.debug(
352
- '%s switching future batches from %s%s to direct intake after status %d without replay',
371
+ '%s switching future batches from %s to direct intake after status %d without replay',
353
372
  this.constructor.name,
354
- route.url.href,
355
- route.endpoint,
373
+ route.url.origin,
356
374
  statusCode
357
375
  )
358
376
  if (this._requestOptions === route.requestOptions) {
@@ -360,7 +378,7 @@ class BaseFFEWriter {
360
378
  this._fallbackRoute = undefined
361
379
  route.onFallback?.()
362
380
  }
363
- log.warn('Events request returned status %d', statusCode)
381
+ this.#logDropped(route, eventCount, error, errorMessage, statusCode)
364
382
  onComplete?.(false)
365
383
  return
366
384
  }
@@ -374,25 +392,42 @@ class BaseFFEWriter {
374
392
  shouldSwitchFutureRoute(statusCode))
375
393
  ) {
376
394
  route.onUnavailable()
377
- if (error) {
378
- log.error('Failed to send events to %s%s: %s', route.url.href, route.endpoint, errorMessage)
379
- } else {
380
- log.warn('Events request returned status %d', statusCode)
381
- }
395
+ this.#logDropped(route, eventCount, error, errorMessage, statusCode)
382
396
  onComplete?.(false)
383
397
  return
384
398
  }
385
399
 
386
- if (error) {
387
- log.error('Failed to send events to %s%s: %s', route.url.href, route.endpoint, errorMessage)
388
- } else if (statusCode >= 200 && statusCode < 300) {
389
- log.debug('Successfully sent %d events', eventCount)
400
+ const delivered = !error && statusCode >= 200 && statusCode < 300
401
+ if (delivered) {
402
+ log.debug('%s accepted %d events at %s (%s, status %d); downstream delivery is not observed',
403
+ this.constructor.name, eventCount, route.url.origin,
404
+ // An Agent URL path prefix precedes the EVP path, so the route type cannot be read from its start.
405
+ route.endpoint.includes('/evp_proxy/') ? 'Agent/local EVP handoff' : 'HTTP receiver', statusCode)
390
406
  } else {
391
- log.warn('Events request returned status %d', statusCode)
407
+ this.#logDropped(route, eventCount, error, errorMessage, statusCode)
392
408
  }
393
- onComplete?.(!error && statusCode >= 200 && statusCode < 300)
409
+ onComplete?.(delivered)
394
410
  })
395
411
  }
412
+
413
+ /**
414
+ * Batches are not retried after a failed final attempt, so the failure log states the loss.
415
+ *
416
+ * @param {ActiveWriterRoute} route - Route that failed
417
+ * @param {number} eventCount - Event count in the dropped batch
418
+ * @param {Error | null} error - Request error
419
+ * @param {string | null | undefined} errorMessage - Redacted request error
420
+ * @param {number | undefined} statusCode - HTTP response status
421
+ */
422
+ #logDropped (route, eventCount, error, errorMessage, statusCode) {
423
+ if (error) {
424
+ log.error('%s failed to send %d events to %s (status=%s, cause=%s); events dropped',
425
+ this.constructor.name, eventCount, route.url.origin, statusCode ?? 'none', errorMessage)
426
+ } else {
427
+ log.warn('%s events request to %s returned status %d; %d events were dropped',
428
+ this.constructor.name, route.url.origin, statusCode, eventCount)
429
+ }
430
+ }
396
431
  }
397
432
 
398
433
  module.exports = BaseFFEWriter
@@ -12,12 +12,16 @@ const {
12
12
  } = require('../../evp_proxy/constants')
13
13
  const { joinEVPProxyPath } = require('../../evp_proxy/path')
14
14
  const log = require('../../log')
15
+ const { snapshotFeatures } = require('./split-features')
15
16
  const BaseFFEWriter = require('./base')
16
17
 
17
18
  // Disabled-state cap. Drops invalidate experiment results because the provider's
18
19
  // exposure dedupe cache keeps masking dropped events after recovery. The first
19
20
  // drop emits a warning and `droppedEventCount` accumulates the cumulative loss.
20
21
  const PENDING_MAX_EVENTS = 1000
22
+ // Include the in-flight batch in both budgets. Leave headroom in the shared 64 MiB request buffer.
23
+ const DELIVERY_MAX_BYTES = 16 * 1024 * 1024
24
+ const DELIVERY_MAX_BATCHES = 1000
21
25
 
22
26
  /**
23
27
  * @typedef {object} ExposureRoute
@@ -39,6 +43,7 @@ const PENDING_MAX_EVENTS = 1000
39
43
  * @property {string} flag.key - Flag key
40
44
  * @property {object} variant - Variant information
41
45
  * @property {string} variant.key - Variant key
46
+ * @property {Record<string, string | number | boolean>} [features]
42
47
  * @property {number} [serial_id] - Serial id of the split the subject landed in
43
48
  * @property {object} subject - Subject (user/entity) information
44
49
  * @property {string} subject.id - Subject identifier
@@ -73,6 +78,19 @@ class ExposuresWriter extends BaseFFEWriter {
73
78
  #context
74
79
 
75
80
  #dropWarned = false
81
+ #deliveryWarned = false
82
+ #closed = false
83
+ #appendDepth = 0
84
+ #inFlight = false
85
+ #deliveryBytes = 0
86
+ #deliveryCount = 0
87
+ /** @type {{ payload: string, eventCount: number, bytes: number }[]} */
88
+ #deliveryQueue = []
89
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
90
+ #deliveryTimer
91
+ #shutdownDeadline = Infinity
92
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
93
+ #shutdownTimer
76
94
 
77
95
  /**
78
96
  * @param {import('../../config/config-base')} config - Tracer configuration object
@@ -91,6 +109,10 @@ class ExposuresWriter extends BaseFFEWriter {
91
109
  payloadSizeLimit: EVP_PAYLOAD_SIZE_LIMIT,
92
110
  eventSizeLimit: EVP_EVENT_SIZE_LIMIT,
93
111
  headers,
112
+ // Request errors can echo credentials in the URL or response body.
113
+ formatError: (error, statusCode) => statusCode === undefined
114
+ ? /** @type {{ code?: string }} */ (error).code ?? 'UNKNOWN'
115
+ : 'none',
94
116
  })
95
117
 
96
118
  if (route.agent || route.fallback) {
@@ -118,6 +140,14 @@ class ExposuresWriter extends BaseFFEWriter {
118
140
  * @param {ExposureRoute} [route] - Selected EVP route
119
141
  */
120
142
  setEnabled (enabled, route) {
143
+ if (this.#closed) {
144
+ // An outstanding request may discover unavailability during shutdown.
145
+ if (!enabled) {
146
+ this.#enabled = false
147
+ this.#discardDelivery()
148
+ }
149
+ return
150
+ }
121
151
  if (route) {
122
152
  this.#setRoute(route)
123
153
  }
@@ -125,10 +155,14 @@ class ExposuresWriter extends BaseFFEWriter {
125
155
  this.#enabled = enabled
126
156
 
127
157
  if (enabled && this.#pendingEvents.length > 0) {
158
+ log.debug('%s exposure delivery enabled; queueing %d pending exposure event(s)',
159
+ this.constructor.name, this.#pendingEvents.length)
128
160
  // Flush all pending events as a batch
129
161
  super.append(this.#pendingEvents)
130
162
  this.#pendingEvents = []
131
163
  }
164
+ if (enabled) this.#scheduleDelivery()
165
+ else this.#cancelDelivery()
132
166
  }
133
167
 
134
168
  /**
@@ -162,8 +196,14 @@ class ExposuresWriter extends BaseFFEWriter {
162
196
  * @param {ExposureEvent|ExposureEvent[]} events - Exposure event(s) to append
163
197
  */
164
198
  append (events) {
199
+ if (this.#closed) return
165
200
  if (this.#enabled) {
166
- super.append(events)
201
+ this.#appendDepth++
202
+ try {
203
+ super.append(events)
204
+ } finally {
205
+ this.#appendDepth--
206
+ }
167
207
  return
168
208
  }
169
209
 
@@ -194,6 +234,123 @@ class ExposuresWriter extends BaseFFEWriter {
194
234
  return
195
235
  }
196
236
  super.flush()
237
+ // Explicit, periodic and shutdown flushes may start delivery immediately.
238
+ // A byte-triggered flush during append must never initiate transport inline.
239
+ if (this.#appendDepth === 0) this.#drainDelivery()
240
+ }
241
+
242
+ destroy () {
243
+ if (this.#closed) return
244
+ this.#closed = true
245
+ this.#shutdownDeadline = Date.now() + this._timeout
246
+ this.#shutdownTimer = setTimeout(() => {
247
+ this.#shutdownTimer = undefined
248
+ this.#expireShutdown()
249
+ }, this._timeout)
250
+ this.#shutdownTimer.unref?.()
251
+ if (!this.#enabled) {
252
+ const undelivered = this.#pendingEvents.length + this._buffer.length
253
+ if (undelivered > 0) {
254
+ log.warn('%s dropped %d exposure event(s) at shutdown because exposure delivery was not enabled',
255
+ this.constructor.name, undelivered)
256
+ }
257
+ this._droppedEvents += undelivered
258
+ this.#pendingEvents = []
259
+ this._buffer = []
260
+ this._bufferSize = 0
261
+ this.#discardDelivery()
262
+ }
263
+ super.destroy()
264
+ }
265
+
266
+ /**
267
+ * Queues an encoded exposure batch, keeping accepted batches when capacity is exhausted.
268
+ * @param {string} payload - Encoded payload
269
+ * @param {number} eventCount - Number of exposures
270
+ */
271
+ _sendPayload (payload, eventCount) {
272
+ const bytes = Buffer.byteLength(payload)
273
+ if (this.#deliveryBytes + bytes > DELIVERY_MAX_BYTES || this.#deliveryCount >= DELIVERY_MAX_BATCHES) {
274
+ this._droppedEvents += eventCount
275
+ if (!this.#deliveryWarned) {
276
+ this.#deliveryWarned = true
277
+ log.warn('%s delivery queue full, dropping newest batch', this.constructor.name)
278
+ }
279
+ return
280
+ }
281
+ this.#deliveryQueue.push({ payload, eventCount, bytes })
282
+ this.#deliveryBytes += bytes
283
+ this.#deliveryCount++
284
+ this.#scheduleDelivery()
285
+ }
286
+
287
+ #scheduleDelivery () {
288
+ if (this.#deliveryQueue.length === 0) {
289
+ if (!this.#inFlight) this.#cancelShutdownTimer()
290
+ return
291
+ }
292
+ if (!this.#enabled || this.#inFlight || this.#deliveryTimer) return
293
+ // A timer yields past socket completion so Node can reach beforeExit between requests.
294
+ // Only the bounded shutdown drain should keep an otherwise idle process alive.
295
+ this.#deliveryTimer = setTimeout(() => {
296
+ this.#deliveryTimer = undefined
297
+ this.#drainDelivery()
298
+ })
299
+ if (!this.#closed) this.#deliveryTimer.unref?.()
300
+ }
301
+
302
+ #expireShutdown () {
303
+ const before = this._droppedEvents
304
+ this.#discardDelivery()
305
+ const dropped = this._droppedEvents - before
306
+ if (dropped > 0) {
307
+ log.warn('%s shutdown deadline reached, dropping %d queued events', this.constructor.name, dropped)
308
+ }
309
+ }
310
+
311
+ #cancelShutdownTimer () {
312
+ clearTimeout(this.#shutdownTimer)
313
+ this.#shutdownTimer = undefined
314
+ }
315
+
316
+ #cancelDelivery () {
317
+ if (!this.#deliveryTimer) return
318
+ clearTimeout(this.#deliveryTimer)
319
+ this.#deliveryTimer = undefined
320
+ }
321
+
322
+ #discardDelivery () {
323
+ this.#cancelDelivery()
324
+ this.#cancelShutdownTimer()
325
+ for (const batch of this.#deliveryQueue) {
326
+ this._droppedEvents += batch.eventCount
327
+ this.#deliveryBytes -= batch.bytes
328
+ this.#deliveryCount--
329
+ }
330
+ this.#deliveryQueue = []
331
+ }
332
+
333
+ #drainDelivery () {
334
+ this.#cancelDelivery()
335
+ if (Date.now() >= this.#shutdownDeadline) {
336
+ this.#expireShutdown()
337
+ return
338
+ }
339
+ if (!this.#enabled || this.#inFlight) return
340
+ const batch = this.#deliveryQueue.shift()
341
+ if (!batch) {
342
+ this.#cancelShutdownTimer()
343
+ return
344
+ }
345
+ this.#inFlight = true
346
+ super._sendPayload(batch.payload, batch.eventCount, delivered => {
347
+ this.#inFlight = false
348
+ this.#deliveryBytes -= batch.bytes
349
+ this.#deliveryCount--
350
+ if (!delivered) this._droppedEvents += batch.eventCount
351
+ // Yield even when a transport implementation invokes its callback synchronously.
352
+ this.#scheduleDelivery()
353
+ })
197
354
  }
198
355
 
199
356
  /**
@@ -222,6 +379,9 @@ class ExposuresWriter extends BaseFFEWriter {
222
379
  },
223
380
  }
224
381
 
382
+ const features = snapshotFeatures(event.features)
383
+ if (features !== undefined) formatted.features = features
384
+
225
385
  if (typeof event.serial_id === 'number') {
226
386
  formatted.serial_id = event.serial_id
227
387
  }
@@ -1,6 +1,8 @@
1
1
  'use strict'
2
2
 
3
3
  const { MAX_EVALUATION_TIMESTAMP_MS } = require('../constants/constants')
4
+ const { snapshotFeatures } = require('./split-features')
5
+
4
6
  const { snapshotEvaluationContext } = require('./flag-evaluation-context')
5
7
  const {
6
8
  recordContextTruncated, recordDropped, recordHookError, recordTargetingKeyOmitted,
@@ -82,6 +84,9 @@ class FlagEvalEVPHook {
82
84
  flagKey: hookContext.flagKey,
83
85
  variant: evaluationDetails.variant,
84
86
  allocationKey: typeof metadata?.__dd_allocation_key === 'string' ? metadata.__dd_allocation_key : undefined,
87
+ features: metadata?.__dd_has_evaluation_features === true
88
+ ? snapshotFeatures(metadata, '__dd_evaluation_feature.')
89
+ : undefined,
85
90
  runtimeDefault: evaluationDetails.variant === undefined,
86
91
  errorCode: evaluationDetails.errorCode,
87
92
  targetingKey,
@@ -7,6 +7,7 @@ const {
7
7
  FLAG_EVALUATION_GLOBAL_CAP,
8
8
  FLAG_EVALUATION_PER_FLAG_CAP,
9
9
  } = require('../constants/constants')
10
+ const { snapshotFeatures } = require('./split-features')
10
11
  const { validatedContextEntries, snapshotFromEntries } = require('./flag-evaluation-context')
11
12
  const { normalizeTargetingKey, optionalKey, protectedErrorCode } =
12
13
  require('./flag-evaluation-pii')
@@ -20,6 +21,7 @@ const MAX_DIRECT_IDENTITY_LENGTH = 16_383
20
21
  * @typedef {object} FlagEvaluationEvent
21
22
  * @property {string} flagKey
22
23
  * @property {string} [variant]
24
+ * @property {Record<string, string | number | boolean>} [features]
23
25
  * @property {string} [allocationKey]
24
26
  * @property {boolean} runtimeDefault
25
27
  * @property {unknown} [errorCode]
@@ -32,6 +34,7 @@ const MAX_DIRECT_IDENTITY_LENGTH = 16_383
32
34
  * @typedef {object} AggregationDimensions
33
35
  * @property {string} flagKey
34
36
  * @property {string} [variant]
37
+ * @property {Record<string, string | number | boolean>} [features]
35
38
  * @property {string} [allocation]
36
39
  * @property {string} [error]
37
40
  */
@@ -94,10 +97,11 @@ class FlagEvaluationAggregator {
94
97
  const error = protectedErrorCode(event.errorCode)
95
98
  const variant = optionalKey(event.variant)
96
99
  const allocation = optionalKey(event.allocationKey)
100
+ const features = snapshotFeatures(event.features)
97
101
  // Group by the raw key; the serializer independently hashes protected rows once per output bucket.
98
102
  const identity = JSON.stringify([
99
103
  flagKey, variant, allocation, event.runtimeDefault === true, error,
100
- targetingKey, contextEntries, consent,
104
+ targetingKey, contextEntries, consent, features,
101
105
  ])
102
106
  // Keep digest keys separate from short JSON identities, which always start with '['.
103
107
  const fullKey = identity.length > MAX_DIRECT_IDENTITY_LENGTH
@@ -111,11 +115,11 @@ class FlagEvaluationAggregator {
111
115
 
112
116
  const perFlag = this.#perFlag.get(flagKey) ?? 0
113
117
  if (perFlag >= FLAG_EVALUATION_PER_FLAG_CAP) {
114
- this.#addDegraded(event, { flagKey, variant, allocation, error })
118
+ this.#addDegraded(event, { flagKey, variant, allocation, error, features })
115
119
  return
116
120
  }
117
121
  if (this.#full.size >= FLAG_EVALUATION_GLOBAL_CAP) {
118
- this.#addDegraded(event, { flagKey, variant, allocation, error })
122
+ this.#addDegraded(event, { flagKey, variant, allocation, error, features })
119
123
  return
120
124
  }
121
125
 
@@ -124,6 +128,7 @@ class FlagEvaluationAggregator {
124
128
  flagKey,
125
129
  variant,
126
130
  allocation,
131
+ features,
127
132
  runtimeDefault: event.runtimeDefault === true,
128
133
  error,
129
134
  rawTargetingKey: targetingKey,
@@ -165,7 +170,7 @@ class FlagEvaluationAggregator {
165
170
  recordDegraded('cardinality_cap')
166
171
  const key = JSON.stringify([
167
172
  dimensions.flagKey, dimensions.variant, dimensions.allocation,
168
- event.runtimeDefault === true, dimensions.error,
173
+ event.runtimeDefault === true, dimensions.error, dimensions.features,
169
174
  ])
170
175
  const existing = this.#degraded.get(key)
171
176
  if (existing) {
@@ -24,6 +24,7 @@ const { recordDegraded, recordDropped, recordPayloadSplit } = require('./flag-ev
24
24
  * @property {string} [targeting_key]
25
25
  * @property {{ evaluation: ContextSnapshot }} [context]
26
26
  * @property {{ key: string }} [variant]
27
+ * @property {Record<string, string | number | boolean>} [features]
27
28
  * @property {{ key: string }} [allocation]
28
29
  * @property {{ message: string }} [error]
29
30
  */
@@ -52,6 +53,7 @@ function makeRow (entry, timestamp, degraded) {
52
53
  const allocation = normalizeTargetingKey(entry.allocation)
53
54
  if (variant) row.variant = { key: variant }
54
55
  if (allocation) row.allocation = { key: allocation }
56
+ if (entry.features !== undefined) row.features = entry.features
55
57
  const error = protectedErrorCode(entry.error)
56
58
  if (error !== undefined) row.error = { message: error }
57
59
  if (!degraded) {
@@ -1,6 +1,7 @@
1
1
  'use strict'
2
2
 
3
3
  const { hashTargetingKey: digestTargetingKey } = require('../encoding')
4
+ const { snapshotFeatures } = require('./split-features')
4
5
 
5
6
  // Keep this vocabulary explicit: an upstream enum addition needs a privacy review.
6
7
  const ERROR_CODES = new Set([
@@ -90,6 +91,7 @@ function normalizeFlagEvaluationEvent (event, targetingKey) {
90
91
  flagKey: normalizeTargetingKey(event.flagKey),
91
92
  variant: optionalKey(event.variant),
92
93
  allocationKey: optionalKey(event.allocationKey),
94
+ features: snapshotFeatures(event.features),
93
95
  runtimeDefault: event.runtimeDefault === true,
94
96
  errorCode: protectedErrorCode(event.errorCode),
95
97
  targetingKey,