dd-trace 6.22.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 (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
@@ -3,6 +3,7 @@
3
3
  const log = require('../log')
4
4
  const Sampler = require('../sampler')
5
5
  const { formatKnuthRate } = require('../util')
6
+ const { SPAN_TYPE } = require('../../../../ext/tags')
6
7
  const {
7
8
  MODEL_NAME,
8
9
  MODEL_PROVIDER,
@@ -19,6 +20,7 @@ const {
19
20
  METADATA,
20
21
  COST_TAGS,
21
22
  AGENT_MANIFEST,
23
+ AGENT_VERSION,
22
24
  METRICS,
23
25
  TOOL_DEFINITIONS,
24
26
  PARENT_ID_KEY,
@@ -28,6 +30,7 @@ const {
28
30
  NAME,
29
31
  PARENT_AGENT_NAME,
30
32
  PARENT_AGENT_SPAN_ID,
33
+ PARENT_AGENT_VERSION,
31
34
  PROPAGATED_PARENT_ID_KEY,
32
35
  PROPAGATED_PARENT_AGENT_ID_KEY,
33
36
  PROPAGATED_PARENT_AGENT_NAME_KEY,
@@ -116,6 +119,7 @@ class LLMObsTagger {
116
119
  kind,
117
120
  name,
118
121
  integration,
122
+ agentVersion,
119
123
  _decorator,
120
124
  } = {}) {
121
125
  // Do not register it in the map if it does not have an LLMObs span kind.
@@ -193,6 +197,8 @@ class LLMObsTagger {
193
197
  storage.getStore()?.agentDeclarations
194
198
  )
195
199
  if (agentDeclarations) this.#applyAgentDeclarations(span, agentDeclarations)
200
+ // The span's own version wins over the enclosing contexts.
201
+ if (agentVersion) this._setTag(span, AGENT_VERSION, agentVersion)
196
202
 
197
203
  // apply annotation context name
198
204
  const annotationContextName = annotationContext?.name
@@ -213,15 +219,16 @@ class LLMObsTagger {
213
219
 
214
220
  /**
215
221
  * Applies the agents declared by the enclosing annotation contexts, outermost first, to every span in the block.
216
- * The manifest is emitted only if the span is an agent when it finishes, since some integrations promote a span
217
- * to an agent after registration.
222
+ * Both are emitted only if the span is an agent when it finishes, since some integrations promote a span to an
223
+ * agent after registration.
218
224
  *
219
225
  * @param {import('../opentracing/span')} span
220
226
  * @param {import('./agent-manifest').AgentDeclaration[]} declarations
221
227
  */
222
228
  #applyAgentDeclarations (span, declarations) {
223
229
  for (const declaration of declarations) {
224
- this.#tagAgentManifestFields(span, declaration.manifest)
230
+ if (declaration.version) this._setTag(span, AGENT_VERSION, declaration.version)
231
+ if (declaration.manifest) this.#tagAgentManifestFields(span, declaration.manifest)
225
232
  }
226
233
  }
227
234
 
@@ -233,7 +240,9 @@ class LLMObsTagger {
233
240
  */
234
241
  tagAgent (span, agent) {
235
242
  const declaration = buildAgentDeclaration(agent)
236
- if (declaration) this.#tagAgentManifestFields(span, declaration.manifest)
243
+ if (!declaration) return
244
+ if (declaration.version) this._setTag(span, AGENT_VERSION, declaration.version)
245
+ if (declaration.manifest) this.#tagAgentManifestFields(span, declaration.manifest)
237
246
  }
238
247
 
239
248
  /**
@@ -276,8 +285,9 @@ class LLMObsTagger {
276
285
 
277
286
  /**
278
287
  * Store the nearest agent ancestor on the span so it can be surfaced as
279
- * `meta.agent_attribution` at finish. Resolved once here, at registration, so downstream
280
- * children inherit it with a single lookup rather than walking the ancestor chain.
288
+ * `meta.agent_attribution` at finish, along with that agent's version, which the agent panel reads
289
+ * off each span to attribute its spend. Resolved once here, at registration, so downstream children
290
+ * inherit it with a single lookup rather than walking the ancestor chain.
281
291
  *
282
292
  * @param {import('../opentracing/span')} span
283
293
  * @param {import('../opentracing/span')} [parent] the LLMObs parent span, if any
@@ -285,10 +295,10 @@ class LLMObsTagger {
285
295
  // TODO: spans whose kind changes after registration (e.g. claude-agent-sdk tools promoted to
286
296
  // sub-agents) will not retroactively update already-finished children's attribution. Follow up.
287
297
  #tagAgentAttribution (span, parent) {
288
- let name, spanId
298
+ let name, spanId, version
289
299
  if (registry.has(parent)) {
290
300
  // Local LLMObs parent: attribute to it if it is an agent, else inherit its resolution.
291
- ({ name, spanId } = resolveAgentAttribution(registry.get(parent), parent))
301
+ ({ name, spanId, version } = resolveAgentAttribution(registry.get(parent), parent))
292
302
  } else if (span.context()._trace.tags[PROPAGATED_PARENT_ID_KEY]) {
293
303
  // Distributed LLMObs parent: inherit the nearest agent propagated from upstream. The
294
304
  // name may be absent when the upstream hop ran an older SDK or its name was not
@@ -300,6 +310,7 @@ class LLMObsTagger {
300
310
 
301
311
  if (name != null) this._setTag(span, PARENT_AGENT_NAME, name)
302
312
  if (spanId != null) this._setTag(span, PARENT_AGENT_SPAN_ID, spanId)
313
+ if (version) this._setTag(span, PARENT_AGENT_VERSION, version)
303
314
  }
304
315
 
305
316
  // TODO: similarly for the following `tag` methods,
@@ -1011,6 +1022,8 @@ class LLMObsTagger {
1011
1022
  return
1012
1023
  }
1013
1024
 
1025
+ span.setTag(SPAN_TYPE, 'llm')
1026
+
1014
1027
  registry.set(span, {})
1015
1028
  }
1016
1029
 
@@ -8,8 +8,10 @@ const {
8
8
  SPAN_KINDS,
9
9
  SPAN_KIND,
10
10
  NAME,
11
+ AGENT_VERSION,
11
12
  PARENT_AGENT_NAME,
12
13
  PARENT_AGENT_SPAN_ID,
14
+ PARENT_AGENT_VERSION,
13
15
  } = require('./constants/tags')
14
16
 
15
17
  const DECIMAL_TRACE_ID_REGEX = /^\d+$/
@@ -325,14 +327,18 @@ function agentNameWireSafe (name) {
325
327
  *
326
328
  * @param {Record<string, unknown> | undefined} tags - Registry entry for the parent span.
327
329
  * @param {import('../opentracing/span')} [span] - The parent span itself (needed for span id / name).
328
- * @returns {{ name: string | undefined, spanId: string | undefined }}
330
+ * @returns {{ name: string | undefined, spanId: string | undefined, version: string | undefined }}
329
331
  */
330
332
  function resolveAgentAttribution (tags, span) {
331
- if (!tags) return { name: undefined, spanId: undefined }
333
+ if (!tags) return { name: undefined, spanId: undefined, version: undefined }
332
334
  if (tags[SPAN_KIND] === 'agent') {
333
- return { name: tags[NAME] || span._name, spanId: span.context().toSpanId() }
335
+ return {
336
+ name: tags[NAME] || span._name,
337
+ spanId: span.context().toSpanId(),
338
+ version: tags[AGENT_VERSION] || tags[PARENT_AGENT_VERSION],
339
+ }
334
340
  }
335
- return { name: tags[PARENT_AGENT_NAME], spanId: tags[PARENT_AGENT_SPAN_ID] }
341
+ return { name: tags[PARENT_AGENT_NAME], spanId: tags[PARENT_AGENT_SPAN_ID], version: tags[PARENT_AGENT_VERSION] }
336
342
  }
337
343
 
338
344
  function spanHasError (span) {
@@ -7,7 +7,7 @@ const { fetchAgentInfo } = require('../../agent/info')
7
7
 
8
8
  /**
9
9
  * @param {import('../../config/config-base')} config
10
- * @param {(agentless: boolean) => void} setWritersAgentlessValue
10
+ * @param {(agentless: boolean, agentAvailable?: boolean) => void} setWritersAgentlessValue
11
11
  */
12
12
  function setAgentStrategy (config, setWritersAgentlessValue) {
13
13
  const agentlessEnabled = config.llmobs.DD_LLMOBS_AGENTLESS_ENABLED
@@ -19,7 +19,7 @@ function setAgentStrategy (config, setWritersAgentlessValue) {
19
19
 
20
20
  fetchAgentInfo(config.url, (err, agentInfo) => {
21
21
  if (err) {
22
- setWritersAgentlessValue(true)
22
+ setWritersAgentlessValue(true, false)
23
23
  return
24
24
  }
25
25
 
@@ -28,7 +28,7 @@ function setAgentStrategy (config, setWritersAgentlessValue) {
28
28
  const hasEndpoint = Array.isArray(endpoints) &&
29
29
  endpoints.some(endpoint => typeof endpoint === 'string' && endpoint.startsWith(EVP_PROXY_AGENT_BASE_PATH))
30
30
  setWritersAgentlessValue(!hasEndpoint)
31
- })
31
+ }, { keepProcessAlive: true })
32
32
  }
33
33
 
34
34
  function parseResponseAndLog (err, code, eventsLength, url, eventType) {
@@ -17,7 +17,13 @@ let logger = defaultLogger
17
17
  let logChannel = new LogChannel()
18
18
 
19
19
  function withNoop (fn) {
20
- legacyStorage.run({ noop: true }, fn)
20
+ legacyStorage.run({ noop: true }, () => {
21
+ // The diagnostics channel rethrows a subscriber error as an uncaught exception, so a
22
+ // throwing configured logger would otherwise terminate the application.
23
+ try {
24
+ fn()
25
+ } catch {}
26
+ })
21
27
  }
22
28
 
23
29
  function toggleSubscription (enable, level) {
@@ -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
+ }