dd-trace 6.23.0 → 6.24.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 (168) 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 -32
  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 +19 -0
  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 +11 -9
  31. package/packages/datadog-core/src/storage.js +1 -1
  32. package/packages/datadog-esbuild/index.js +70 -7
  33. package/packages/datadog-instrumentations/src/cucumber.js +53 -19
  34. package/packages/datadog-instrumentations/src/cypress-config.js +163 -15
  35. package/packages/datadog-instrumentations/src/graphql.js +9 -3
  36. package/packages/datadog-instrumentations/src/grpc/server.js +23 -6
  37. package/packages/datadog-instrumentations/src/helpers/fetch.js +5 -1
  38. package/packages/datadog-instrumentations/src/helpers/graphql-jit-runtime.js +30 -8
  39. package/packages/datadog-instrumentations/src/helpers/hooks.js +1 -1
  40. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +16 -6
  41. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +8 -0
  42. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql-jit.js +3 -1
  43. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/react-router.js +49 -0
  44. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/typesafe.js +23 -0
  45. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/webdriverio.js +12 -0
  46. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +8 -0
  47. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.js +19 -2
  48. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +8 -0
  49. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +1 -1
  50. package/packages/datadog-instrumentations/src/jest.js +265 -82
  51. package/packages/datadog-instrumentations/src/mariadb-bundle.js +69 -11
  52. package/packages/datadog-instrumentations/src/mariadb.js +13 -6
  53. package/packages/datadog-instrumentations/src/mocha/common.js +89 -8
  54. package/packages/datadog-instrumentations/src/mocha/main.js +11 -2
  55. package/packages/datadog-instrumentations/src/mocha/utils.js +58 -12
  56. package/packages/datadog-instrumentations/src/mocha/worker.js +1 -1
  57. package/packages/datadog-instrumentations/src/oracledb.js +33 -0
  58. package/packages/datadog-instrumentations/src/pg.js +2 -1
  59. package/packages/datadog-instrumentations/src/playwright.js +81 -28
  60. package/packages/datadog-instrumentations/src/react-router.js +106 -0
  61. package/packages/datadog-instrumentations/src/typesafe.js +89 -0
  62. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +84 -48
  63. package/packages/datadog-instrumentations/src/vitest-main.js +26 -0
  64. package/packages/datadog-instrumentations/src/vitest-test-annotations.js +20 -0
  65. package/packages/datadog-instrumentations/src/vitest-worker.js +39 -17
  66. package/packages/datadog-instrumentations/src/vitest.js +10 -8
  67. package/packages/datadog-plugin-cucumber/src/index.js +5 -0
  68. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +274 -44
  69. package/packages/datadog-plugin-cypress/src/index.js +1 -1
  70. package/packages/datadog-plugin-cypress/src/lifecycle-owner.js +20 -0
  71. package/packages/datadog-plugin-cypress/src/plugin.js +10 -0
  72. package/packages/datadog-plugin-cypress/src/retry-config-observer.js +281 -0
  73. package/packages/datadog-plugin-cypress/src/setup-handoff.js +125 -0
  74. package/packages/datadog-plugin-cypress/src/support.js +1217 -439
  75. package/packages/datadog-plugin-graphql/src/execute.js +2 -2
  76. package/packages/datadog-plugin-graphql/src/utils.js +5 -5
  77. package/packages/datadog-plugin-jest/src/index.js +25 -3
  78. package/packages/datadog-plugin-mocha/src/index.js +47 -6
  79. package/packages/datadog-plugin-oracledb/src/connection-parser.js +21 -11
  80. package/packages/datadog-plugin-playwright/src/index.js +4 -0
  81. package/packages/datadog-plugin-react-router/src/index.js +118 -0
  82. package/packages/datadog-plugin-typesafe/src/index.js +17 -0
  83. package/packages/datadog-plugin-typesafe/src/tracing.js +31 -0
  84. package/packages/datadog-plugin-vitest/src/index.js +8 -0
  85. package/packages/dd-trace/src/agent/info.js +2 -1
  86. package/packages/dd-trace/src/aiguard/sdk.js +0 -11
  87. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +9 -16
  88. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +4 -2
  89. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +9 -16
  90. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +9 -14
  91. package/packages/dd-trace/src/ci-visibility/requests/route.js +44 -0
  92. package/packages/dd-trace/src/ci-visibility/telemetry-logs.js +5 -0
  93. package/packages/dd-trace/src/ci-visibility/test-annotations.js +72 -0
  94. package/packages/dd-trace/src/ci-visibility/test-declaration-annotations.js +170 -0
  95. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +9 -16
  96. package/packages/dd-trace/src/config/defaults.js +4 -3
  97. package/packages/dd-trace/src/config/generated-config-types.d.ts +4 -0
  98. package/packages/dd-trace/src/config/index.js +95 -39
  99. package/packages/dd-trace/src/config/parsers.js +9 -1
  100. package/packages/dd-trace/src/config/supported-configurations.json +16 -0
  101. package/packages/dd-trace/src/debugger/probe_sampler.js +6 -6
  102. package/packages/dd-trace/src/encode/0.4.js +2 -2
  103. package/packages/dd-trace/src/esm-module-load.js +58 -0
  104. package/packages/dd-trace/src/exporter.js +25 -6
  105. package/packages/dd-trace/src/exporters/agent/index.js +3 -1
  106. package/packages/dd-trace/src/exporters/agentless/index.js +3 -1
  107. package/packages/dd-trace/src/exporters/common/request.js +4 -4
  108. package/packages/dd-trace/src/exporters/llmobs/index.js +135 -0
  109. package/packages/dd-trace/src/exporters/log/index.js +4 -3
  110. package/packages/dd-trace/src/llmobs/constants/tags.js +1 -0
  111. package/packages/dd-trace/src/llmobs/experiments/index.js +2 -3
  112. package/packages/dd-trace/src/llmobs/experiments/noop.js +5 -2
  113. package/packages/dd-trace/src/llmobs/index.js +13 -2
  114. package/packages/dd-trace/src/llmobs/plugins/claude-agent-sdk/index.js +1 -1
  115. package/packages/dd-trace/src/llmobs/plugins/genai/index.js +1 -1
  116. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +8 -4
  117. package/packages/dd-trace/src/llmobs/plugins/typesafe/index.js +102 -0
  118. package/packages/dd-trace/src/llmobs/prompts/cache.js +3 -1
  119. package/packages/dd-trace/src/llmobs/sdk.js +2 -1
  120. package/packages/dd-trace/src/llmobs/span_processor.js +210 -12
  121. package/packages/dd-trace/src/llmobs/tagger.js +3 -0
  122. package/packages/dd-trace/src/llmobs/writers/util.js +3 -3
  123. package/packages/dd-trace/src/log/writer.js +7 -1
  124. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +64 -6
  125. package/packages/dd-trace/src/openfeature/configuration_source.js +18 -2
  126. package/packages/dd-trace/src/openfeature/debug-logging-hook.js +66 -3
  127. package/packages/dd-trace/src/openfeature/exposure-hook.js +185 -0
  128. package/packages/dd-trace/src/openfeature/flagging_provider.js +39 -13
  129. package/packages/dd-trace/src/openfeature/remote_config.js +16 -3
  130. package/packages/dd-trace/src/openfeature/writers/base.js +62 -27
  131. package/packages/dd-trace/src/openfeature/writers/exposures.js +161 -1
  132. package/packages/dd-trace/src/openfeature/writers/flag-eval-evp-hook.js +5 -0
  133. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-aggregation.js +9 -4
  134. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-payload.js +2 -0
  135. package/packages/dd-trace/src/openfeature/writers/flag-evaluation-pii.js +2 -0
  136. package/packages/dd-trace/src/openfeature/writers/split-features.js +25 -0
  137. package/packages/dd-trace/src/opentelemetry/metrics/periodic_metric_reader.js +2 -2
  138. package/packages/dd-trace/src/opentelemetry/tracer_provider.js +5 -1
  139. package/packages/dd-trace/src/opentracing/tracer.js +9 -13
  140. package/packages/dd-trace/src/otel-thread-ctx.js +47 -21
  141. package/packages/dd-trace/src/plugins/ci_plugin.js +4 -4
  142. package/packages/dd-trace/src/plugins/index.js +3 -0
  143. package/packages/dd-trace/src/plugins/tracing.js +1 -1
  144. package/packages/dd-trace/src/plugins/util/git.js +11 -5
  145. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +2 -4
  146. package/packages/dd-trace/src/plugins/util/test.js +26 -6
  147. package/packages/dd-trace/src/plugins/util/web.js +16 -0
  148. package/packages/dd-trace/src/process-tags/index.js +1 -1
  149. package/packages/dd-trace/src/profiling/config.js +6 -3
  150. package/packages/dd-trace/src/proxy.js +15 -4
  151. package/packages/dd-trace/src/serverless.js +3 -2
  152. package/packages/dd-trace/src/span_processor.js +21 -9
  153. package/packages/dd-trace/src/span_stats.js +28 -2
  154. package/packages/dd-trace/src/startup-log.js +2 -1
  155. package/packages/dd-trace/src/tagger.js +7 -5
  156. package/packages/dd-trace/src/telemetry/dependencies.js +4 -0
  157. package/packages/dd-trace/src/telemetry/index.js +3 -0
  158. package/packages/dd-trace/src/telemetry/logs/index.js +21 -2
  159. package/packages/dd-trace/src/telemetry/logs/log-collector.js +1 -0
  160. package/packages/dd-trace/src/telemetry/telemetry.js +10 -3
  161. package/packages/dd-trace/src/util.js +1 -1
  162. package/register.js +2 -1
  163. package/vendor/dist/@datadog/openfeature-node-server/index.js +1 -1
  164. package/vendor/dist/@datadog/openfeature-node-server/rules-based/index.d.ts +78 -0
  165. package/vendor/dist/@datadog/openfeature-node-server/rules-based/index.js +1 -1
  166. package/vendor/dist/@opentelemetry/core/index.js +1 -1
  167. package/vendor/dist/@opentelemetry/resources/LICENSE +0 -201
  168. package/vendor/dist/@opentelemetry/resources/index.js +0 -1
@@ -14,6 +14,8 @@ const FIRST_RETRY_MAX_MS = 10_000
14
14
  const SECOND_RETRY_MIN_MS = 5000
15
15
  const SECOND_RETRY_MAX_MS = 30_000
16
16
  const RETRY_JITTER = 0.2
17
+ const POLL_FAILED_WITHOUT_CONFIGURATION = 'Feature Flags: agentless configuration poll failed (%s); ' +
18
+ 'no configuration has been applied yet, so flag evaluations return their default values'
17
19
 
18
20
  /**
19
21
  * @typedef {object} AgentlessSourceConfig
@@ -45,12 +47,17 @@ class AgentlessConfigurationSource {
45
47
 
46
48
  #applicationFailureLogged = false
47
49
 
50
+ /** @type {string | undefined} */
51
+ #appliedCreatedAt
52
+
48
53
  /** @type {AgentlessSourceConfig} */
49
54
  #config
50
55
 
51
56
  /** @type {string | undefined} */
52
57
  #etag
53
58
 
59
+ #failedPolls = 0
60
+
54
61
  /** @type {Set<string>} */
55
62
  #failureWarnings = new Set()
56
63
 
@@ -74,8 +81,11 @@ class AgentlessConfigurationSource {
74
81
  }
75
82
 
76
83
  stop () {
77
- this.#abortController?.abort()
84
+ if (!this.#abortController) return
85
+
86
+ this.#abortController.abort()
78
87
  this.#abortController = undefined
88
+ log.debug('Feature Flags: agentless configuration polling stopped')
79
89
  }
80
90
 
81
91
  /**
@@ -132,10 +142,13 @@ class AgentlessConfigurationSource {
132
142
 
133
143
  if (attempt === MAX_ATTEMPTS) {
134
144
  this.#warnFailure(response.statusCode, response.error, attempt)
145
+ this.#logPollFailure('retries exhausted')
135
146
  return
136
147
  }
137
148
 
138
149
  const delay = retryDelay(this.#config.pollIntervalMs, attempt, Math.random())
150
+ log.debug('Feature Flags: agentless configuration poll attempt %d/%d is retryable; retrying in %dms',
151
+ attempt, MAX_ATTEMPTS, delay)
139
152
  if (!await wait(delay, abortController.signal)) return
140
153
  }
141
154
  }
@@ -187,23 +200,40 @@ class AgentlessConfigurationSource {
187
200
  */
188
201
  #apply (response) {
189
202
  const statusCode = response.statusCode
190
- if (statusCode === 304) return
203
+ if (statusCode === 304) {
204
+ // A custom endpoint can answer 304 without having been sent an ETag, so it confirms nothing
205
+ // until a configuration has been applied.
206
+ if (this.#appliedCreatedAt === undefined) {
207
+ this.#logPollFailure('HTTP 304 received before any configuration was applied')
208
+ } else {
209
+ this.#logPollRecovery()
210
+ }
211
+ return
212
+ }
191
213
 
192
214
  if (statusCode === 401 || statusCode === 403) {
193
215
  this.#warnFailure(statusCode, undefined, 1)
216
+ this.#logPollFailure('authentication failed, not retried')
194
217
  return
195
218
  }
196
219
 
197
- if (statusCode !== 200) return
220
+ if (statusCode !== 200) {
221
+ this.#logPollFailure('HTTP status is not retryable')
222
+ return
223
+ }
198
224
 
199
225
  let configuration
200
226
  try {
201
227
  configuration = parseConfiguration(response.body)
202
- } catch {
228
+ } catch (error) {
203
229
  if (!this.#malformedPayloadLogged) {
204
230
  this.#malformedPayloadLogged = true
205
231
  log.error('Feature Flagging agentless endpoint returned malformed UFC payload')
206
232
  }
233
+ // JSON.parse messages quote the payload, so only report our own validation reasons.
234
+ log.debug('Feature Flags: agentless configuration payload rejected: %s',
235
+ error instanceof SyntaxError ? 'response body is not valid JSON' : error.message)
236
+ this.#logPollFailure('malformed UFC payload')
207
237
  return
208
238
  }
209
239
 
@@ -214,19 +244,47 @@ class AgentlessConfigurationSource {
214
244
  this.#applicationFailureLogged = true
215
245
  log.warn('Feature Flagging agentless UFC payload could not be applied: %s', errorMessage(error))
216
246
  }
247
+ this.#logPollFailure('configuration could not be applied')
217
248
  return
218
249
  }
219
250
 
220
251
  const etag = response.headers?.etag
221
252
  const value = Array.isArray(etag) ? etag[0] : etag
222
253
  this.#etag = value?.trim() || undefined
254
+ this.#appliedCreatedAt = configuration.createdAt
223
255
 
224
256
  // eslint-disable-next-line eslint-rules/eslint-log-printf-style
225
257
  log.debug(() => {
226
- const flagCount = Object.keys(configuration.flags ?? {}).length
258
+ const flagCount = Object.keys(configuration.flags).length
259
+ // A custom endpoint is requested as configured, so DD_ENV is only sent when the URL carries dd_env.
260
+ const requestedEnv = this.#config.endpoint.searchParams.get('dd_env')
227
261
  return 'Feature Flags: agentless configuration applied successfully ' +
228
- `(${flagCount} flag(s), env=${this.#config.env ?? 'unset'})`
262
+ `(${flagCount} flag(s) received; per-flag validity is checked at evaluation, ` +
263
+ `configuration environment=${configuration.environment.name}, ` +
264
+ `createdAt=${configuration.createdAt}, etag=${this.#etag ?? 'none'}, ` +
265
+ `sdk env=${this.#config.env ?? 'unset'}, requested dd_env=${requestedEnv ?? 'not sent'})`
229
266
  })
267
+ this.#logPollRecovery()
268
+ }
269
+
270
+ /**
271
+ * @param {string} reason
272
+ */
273
+ #logPollFailure (reason) {
274
+ this.#failedPolls++
275
+ if (this.#appliedCreatedAt === undefined) {
276
+ log.debug(POLL_FAILED_WITHOUT_CONFIGURATION, reason)
277
+ } else {
278
+ log.debug('Feature Flags: agentless configuration poll failed (%s); keeping the configuration created at %s',
279
+ reason, this.#appliedCreatedAt)
280
+ }
281
+ }
282
+
283
+ #logPollRecovery () {
284
+ if (this.#failedPolls === 0) return
285
+
286
+ log.debug('Feature Flags: agentless configuration poll succeeded after %d failed poll(s)', this.#failedPolls)
287
+ this.#failedPolls = 0
230
288
  }
231
289
 
232
290
  /**
@@ -5,6 +5,11 @@ const log = require('../log')
5
5
 
6
6
  const DEFAULT_AGENTLESS_PATH = '/api/v2/feature-flagging/config/rules-based/server'
7
7
  const MAX_POLL_INTERVAL_SECONDS = 60 * 60
8
+ const AGENTLESS_START_MESSAGE = 'Feature Flags: starting agentless configuration source at %s ' +
9
+ '(%s endpoint, poll interval %ds, request timeout %ds, DD-API-KEY header %s)'
10
+ const REMOTE_CONFIG_DISABLED_WARNING = 'Feature Flags: configuration source is remote_config but Remote ' +
11
+ 'Configuration is disabled; flag evaluations will return their default values. Set ' +
12
+ 'DD_REMOTE_CONFIGURATION_ENABLED=true or DD_FEATURE_FLAGS_CONFIGURATION_SOURCE=agentless'
8
13
 
9
14
  /**
10
15
  * @typedef {import('@datadog/openfeature-node-server').UniversalFlagConfigurationV1} UniversalFlagConfiguration
@@ -27,6 +32,9 @@ function create (config, applyConfiguration) {
27
32
 
28
33
  if (source !== 'agentless') {
29
34
  log.debug('Feature Flags: configuration source is %s, not agentless; skipping agentless setup', source)
35
+ if (source === 'remote_config' && !config.remoteConfig?.DD_REMOTE_CONFIGURATION_ENABLED) {
36
+ log.warn(REMOTE_CONFIG_DISABLED_WARNING)
37
+ }
30
38
  return
31
39
  }
32
40
 
@@ -39,10 +47,18 @@ function create (config, applyConfiguration) {
39
47
 
40
48
  const AgentlessConfigurationSource = require('./agentless_configuration_source')
41
49
  const resolvedEndpoint = endpoint(config, baseUrl)
42
- log.debug('Feature Flags: starting agentless configuration source at %s', redactedUrl(resolvedEndpoint))
50
+ const effectivePollIntervalSeconds = Math.min(pollIntervalSeconds, MAX_POLL_INTERVAL_SECONDS)
51
+ log.debug(
52
+ AGENTLESS_START_MESSAGE,
53
+ redactedUrl(resolvedEndpoint),
54
+ hasCustomEndpoint ? 'custom' : 'default',
55
+ effectivePollIntervalSeconds,
56
+ requestTimeoutSeconds,
57
+ hasCustomEndpoint ? 'not sent' : 'sent'
58
+ )
43
59
  return new AgentlessConfigurationSource({
44
60
  endpoint: resolvedEndpoint,
45
- pollIntervalMs: Math.min(pollIntervalSeconds, MAX_POLL_INTERVAL_SECONDS) * 1000,
61
+ pollIntervalMs: effectivePollIntervalSeconds * 1000,
46
62
  requestTimeoutMs: requestTimeoutSeconds * 1000,
47
63
  apiKey: hasCustomEndpoint ? undefined : config.DD_API_KEY,
48
64
  env: config.env,
@@ -1,18 +1,81 @@
1
1
  'use strict'
2
2
 
3
+ const { inspect } = require('node:util')
4
+
3
5
  const log = require('../log')
6
+ const { debugChannel } = require('../log/channels')
7
+
8
+ // Debug output must show raw values and contexts in full rather than inspect's default depth and length limits.
9
+ const INSPECT_OPTIONS = {
10
+ breakLength: Infinity,
11
+ compact: true,
12
+ customInspect: false,
13
+ depth: Infinity,
14
+ maxArrayLength: Infinity,
15
+ maxStringLength: Infinity,
16
+ }
17
+
18
+ const PROVIDER_RESOLUTION = 'datadog.debugLogging.providerResolution'
19
+
20
+ /**
21
+ * @typedef {import('@datadog/openfeature-node-server').UniversalFlagConfigurationV1} UniversalFlagConfiguration
22
+ */
4
23
 
5
24
  /**
6
25
  * Logs full evaluation details under DD_TRACE_DEBUG, matching EvalMetricsHook's use of `finally`.
7
26
  */
8
27
  class DebugLoggingHook {
28
+ #getConfiguration
29
+
30
+ /**
31
+ * @param {() => UniversalFlagConfiguration | undefined} [getConfiguration] - Current configuration
32
+ */
33
+ constructor (getConfiguration) {
34
+ this.#getConfiguration = getConfiguration
35
+ }
36
+
37
+ /**
38
+ * Keeps the provider resolution so `finally` can tell it apart from a result replaced by a failing later hook.
39
+ *
40
+ * @param {{ hookData?: { set: (key: string, value: unknown) => void } }} hookContext - Hook context
41
+ * @param {object} evaluationDetails - Provider resolution details
42
+ */
43
+ after (hookContext, evaluationDetails) {
44
+ if (!debugChannel.hasSubscribers) return
45
+ // A formatted snapshot preserves primitive fields and nested values before application hooks can mutate them.
46
+ hookContext?.hookData?.set(PROVIDER_RESOLUTION, inspect(evaluationDetails, INSPECT_OPTIONS))
47
+ }
48
+
9
49
  /**
10
- * @param {{ flagKey: string }} hookContext - Hook context containing the flag key
11
- * @param {object} evaluationDetails - Full evaluation details
50
+ * @param {{
51
+ * flagKey: string,
52
+ * flagValueType?: string,
53
+ * defaultValue?: unknown,
54
+ * context?: object,
55
+ * hookData?: { get: (key: string) => unknown }
56
+ * }} hookContext - Hook context containing the flag key and evaluation inputs
57
+ * @param {object} evaluationDetails - Evaluation details observed by this hook
12
58
  */
13
59
  finally (hookContext, evaluationDetails) {
14
60
  try {
15
- log.debug('Feature Flags: evaluated %s: %o', hookContext?.flagKey, evaluationDetails)
61
+ // eslint-disable-next-line eslint-rules/eslint-log-printf-style
62
+ log.debug(() => {
63
+ const configuration = this.#getConfiguration?.()
64
+ const configurationIdentity = configuration
65
+ ? `configuration observed at logging time: createdAt=${configuration.createdAt}, ` +
66
+ `configuration environment=${configuration.environment?.name}`
67
+ : 'no configuration observed at logging time'
68
+ const details = inspect(evaluationDetails, INSPECT_OPTIONS)
69
+ let message = `Feature Flags: evaluated ${hookContext?.flagKey} (type=${hookContext?.flagValueType}, ` +
70
+ `default=${inspect(hookContext?.defaultValue, INSPECT_OPTIONS)}, ` +
71
+ `context=${inspect(hookContext?.context, INSPECT_OPTIONS)}, ${configurationIdentity}): ` +
72
+ `finally hook saw ${details}`
73
+ const resolution = hookContext?.hookData?.get(PROVIDER_RESOLUTION)
74
+ if (resolution !== undefined && resolution !== details) {
75
+ message += `; earlier resolution seen by provider hook: ${resolution}`
76
+ }
77
+ return message
78
+ })
16
79
  } catch (error) {
17
80
  try {
18
81
  // Defense in depth; the OpenFeature SDK already guards finally hooks.
@@ -0,0 +1,185 @@
1
+ 'use strict'
2
+
3
+ const log = require('../log')
4
+
5
+ const METADATA_FEATURE_PREFIX = '__dd_feature.'
6
+ const METADATA_ALLOCATION_KEY = '__dd_allocation_key'
7
+ const METADATA_DO_LOG = '__dd_do_log'
8
+ const METADATA_EXPOSURE_CACHE_HIT = '__dd_exposure_cache_hit'
9
+
10
+ /**
11
+ * An OpenFeature hook that hands each completed flag evaluation to a callback,
12
+ * with the Datadog exposure decision, so an application can record exposures in
13
+ * its own data store.
14
+ *
15
+ * This hook is optional. The provider puts the same data in the flag metadata,
16
+ * so any OpenFeature hook can read it. This class reads it for you.
17
+ *
18
+ * Register it with `OpenFeature.addHooks(new ExposureHook(callback))` or on a
19
+ * client. The callback runs for every evaluation, including errors and repeats.
20
+ * Use `shouldSend()` to keep the new or changed exposures.
21
+ *
22
+ * When the provider's own hooks run and `DD_FEATURE_FLAGS_EXPOSURES_DATADOG_LOGGING_ENABLED`
23
+ * is on, these are exactly the exposures that Datadog sends. With that setting
24
+ * off, Datadog receives no exposures, and `shouldSend()` gives the same results.
25
+ *
26
+ * The callback runs on the evaluation thread: hand the data to a background
27
+ * queue instead of doing I/O in the callback. An exception from the callback
28
+ * does not affect the evaluation. The first one is logged at warn level, later
29
+ * ones at debug level.
30
+ */
31
+ class ExposureHook {
32
+ #callback
33
+ #warned = false
34
+
35
+ /**
36
+ * @param {(evaluation: ExposureEvaluation) => void} callback
37
+ */
38
+ constructor (callback) {
39
+ if (typeof callback !== 'function') {
40
+ throw new TypeError('ExposureHook requires a callback function')
41
+ }
42
+ this.#callback = callback
43
+ }
44
+
45
+ /**
46
+ * Runs in the final hook stage, so a later hook's error is seen.
47
+ *
48
+ * @param {import('@openfeature/core').HookContext} hookContext
49
+ * @param {import('@openfeature/core').EvaluationDetails<import('@openfeature/core').FlagValue>} evaluationDetails
50
+ */
51
+ finally (hookContext, evaluationDetails) {
52
+ if (evaluationDetails == null) return
53
+ try {
54
+ const result = /** @type {unknown} */ (this.#callback(new ExposureEvaluation(hookContext, evaluationDetails)))
55
+ // An async callback reports its failure through the returned promise, which the catch below never sees.
56
+ if (isThenable(result)) result.then(undefined, error => this.#logFailure(error))
57
+ } catch (error) {
58
+ this.#logFailure(error)
59
+ }
60
+ }
61
+
62
+ /** @param {unknown} error */
63
+ #logFailure (error) {
64
+ try {
65
+ if (this.#warned) {
66
+ log.debug('Exposure callback failed', error)
67
+ } else {
68
+ this.#warned = true
69
+ log.warn('Exposure callback failed; later failures are logged at debug level', error)
70
+ }
71
+ } catch {
72
+ // Formatting a value the callback threw can itself throw; the evaluation must still succeed.
73
+ }
74
+ }
75
+ }
76
+
77
+ /**
78
+ * @param {unknown} value
79
+ * @returns {value is PromiseLike<unknown>}
80
+ */
81
+ function isThenable (value) {
82
+ return typeof (/** @type {{ then?: unknown } | null | undefined} */ (value))?.then === 'function'
83
+ }
84
+
85
+ /** A completed evaluation and its Datadog exposure decision. */
86
+ class ExposureEvaluation {
87
+ /** @type {import('@openfeature/core').EvaluationDetails<import('@openfeature/core').FlagValue>} */
88
+ #details
89
+
90
+ /** @type {import('@openfeature/core').EvaluationContext | undefined} */
91
+ #context
92
+
93
+ /**
94
+ * @param {import('@openfeature/core').HookContext} hookContext
95
+ * @param {import('@openfeature/core').EvaluationDetails<import('@openfeature/core').FlagValue>} details
96
+ */
97
+ constructor (hookContext, details) {
98
+ this.flagKey = hookContext?.flagKey ?? details.flagKey
99
+ this.#details = details
100
+ // A wrapper may expose an unreadable context; the exposure decision below never reads it.
101
+ try {
102
+ this.#context = hookContext?.context
103
+ } catch {
104
+ this.#context = undefined
105
+ }
106
+ }
107
+
108
+ /** The flag key, variant, value, error and flag metadata of the evaluation. */
109
+ get details () {
110
+ return this.#details
111
+ }
112
+
113
+ /** The selected variant key, or undefined when the default value was returned. */
114
+ get variant () {
115
+ return this.#details.variant
116
+ }
117
+
118
+ /** The key of the selected allocation, or undefined when none was selected. */
119
+ get allocation () {
120
+ const allocationKey = this.#details.flagMetadata?.[METADATA_ALLOCATION_KEY]
121
+ return typeof allocationKey === 'string' ? allocationKey : undefined
122
+ }
123
+
124
+ /** The evaluation context, including the targeting key. */
125
+ get context () {
126
+ return this.#context
127
+ }
128
+
129
+ /** The targeting key of the evaluation context, if readable. */
130
+ get targetingKey () {
131
+ const targetingKey = this.#context?.targetingKey
132
+ return typeof targetingKey === 'string' ? targetingKey : undefined
133
+ }
134
+
135
+ /**
136
+ * True when the evaluation succeeded and selected an allocation that logs
137
+ * exposures, whether or not this subject was already exposed.
138
+ */
139
+ isExposure () {
140
+ return this.#details.errorCode === undefined &&
141
+ this.#details.variant != null &&
142
+ typeof this.allocation === 'string' &&
143
+ this.#details.flagMetadata?.[METADATA_DO_LOG] === true
144
+ }
145
+
146
+ /**
147
+ * True when this exposure repeats one already recorded for this subject:
148
+ * same allocation, variant and serial id. False for a new or changed
149
+ * exposure, and for an evaluation that is not an exposure.
150
+ */
151
+ isCacheHit () {
152
+ return this.isExposure() && this.#details.flagMetadata?.[METADATA_EXPOSURE_CACHE_HIT] === true
153
+ }
154
+
155
+ /**
156
+ * True for a new or changed exposure: the decision the provider uses for
157
+ * Datadog.
158
+ */
159
+ shouldSend () {
160
+ return this.isExposure() && this.#details.flagMetadata?.[METADATA_EXPOSURE_CACHE_HIT] === false
161
+ }
162
+
163
+ /**
164
+ * The HOOK features of the selected split, such as `holdout.key` and
165
+ * `holdout.assignment_group`. Values are a string, number or boolean.
166
+ * Read-only; empty when the split has none.
167
+ */
168
+ getFeatures () {
169
+ const metadata = this.#details.flagMetadata
170
+ const features = Object.create(null)
171
+ if (metadata != null) {
172
+ for (const [key, value] of Object.entries(metadata)) {
173
+ if (!key.startsWith(METADATA_FEATURE_PREFIX)) continue
174
+ if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') continue
175
+ features[key.slice(METADATA_FEATURE_PREFIX.length)] = value
176
+ }
177
+ }
178
+ return Object.freeze(features)
179
+ }
180
+ }
181
+
182
+ module.exports = {
183
+ ExposureEvaluation,
184
+ ExposureHook,
185
+ }
@@ -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
 
@@ -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)