dd-trace 5.135.0 → 5.136.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 (250) hide show
  1. package/ci/init.js +2 -22
  2. package/ext/exporters.js +0 -1
  3. package/index.d.ts +105 -5
  4. package/initialize.mjs +5 -2
  5. package/lambda.d.ts +39 -0
  6. package/lambda.js +3 -0
  7. package/package.json +11 -9
  8. package/packages/datadog-esbuild/index.js +8 -55
  9. package/packages/datadog-instrumentations/src/aws-lambda.js +88 -0
  10. package/packages/datadog-instrumentations/src/cucumber.js +5 -2
  11. package/packages/datadog-instrumentations/src/elevenlabs/activity.js +114 -0
  12. package/packages/datadog-instrumentations/src/elevenlabs/audio.js +104 -0
  13. package/packages/datadog-instrumentations/src/elevenlabs/index.js +288 -0
  14. package/packages/datadog-instrumentations/src/elevenlabs/session.js +444 -0
  15. package/packages/datadog-instrumentations/src/graphql.js +20 -17
  16. package/packages/{datadog-esbuild/src/utils.js → datadog-instrumentations/src/helpers/bundler-esm-exports.js} +282 -40
  17. package/packages/datadog-instrumentations/src/helpers/bundler-transform.js +573 -0
  18. package/packages/datadog-instrumentations/src/helpers/bundler-utils.js +104 -0
  19. package/packages/datadog-instrumentations/src/helpers/hook.js +29 -1
  20. package/packages/datadog-instrumentations/src/helpers/hooks.js +3 -7
  21. package/packages/datadog-instrumentations/src/helpers/lambda-handler.js +189 -0
  22. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +2 -0
  23. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +18 -1
  24. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/async-mutex.js +41 -0
  25. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/elevenlabs.js +25 -0
  26. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql.js +0 -36
  27. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/next.js +40 -0
  28. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/openai-agents-realtime.js +23 -0
  29. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/trpc.js +148 -0
  30. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +50 -0
  31. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +17 -3
  32. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +59 -2
  33. package/packages/datadog-instrumentations/src/ioredis.js +101 -3
  34. package/packages/datadog-instrumentations/src/next.js +19 -6
  35. package/packages/datadog-instrumentations/src/openai-agents-realtime.js +149 -0
  36. package/packages/datadog-instrumentations/src/openai-realtime/audio-accumulator.js +27 -0
  37. package/packages/datadog-instrumentations/src/openai-realtime/index.js +17 -6
  38. package/packages/datadog-instrumentations/src/openai-realtime/server-playback.js +887 -0
  39. package/packages/datadog-instrumentations/src/openai-realtime/session.js +150 -25
  40. package/packages/datadog-instrumentations/src/openai-realtime/turns.js +29 -2
  41. package/packages/datadog-instrumentations/src/otel-sdk-trace.js +11 -9
  42. package/packages/datadog-instrumentations/src/webdriverio.js +12 -12
  43. package/packages/datadog-plugin-async-mutex/src/index.js +50 -0
  44. package/packages/datadog-plugin-aws-lambda/src/index.js +106 -0
  45. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +22 -11
  46. package/packages/datadog-plugin-elevenlabs/src/index.js +69 -0
  47. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +10 -7
  48. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +19 -52
  49. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +4 -2
  50. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-request-context.js +25 -4
  51. package/packages/datadog-plugin-http/src/client.js +32 -9
  52. package/packages/datadog-plugin-http2/src/client.js +38 -13
  53. package/packages/datadog-plugin-next/src/index.js +112 -14
  54. package/packages/datadog-plugin-prisma/src/datadog-tracing-helper.js +5 -3
  55. package/packages/datadog-plugin-trpc/src/index.js +15 -0
  56. package/packages/datadog-plugin-trpc/src/procedure.js +48 -0
  57. package/packages/datadog-plugin-trpc/src/request.js +81 -0
  58. package/packages/datadog-plugin-undici/src/index.js +22 -7
  59. package/packages/datadog-turbopack/index.js +4 -28
  60. package/packages/datadog-turbopack/src/loader.js +14 -452
  61. package/packages/datadog-webpack/index.js +3 -55
  62. package/packages/dd-trace/src/aiguard/evaluation.js +62 -1
  63. package/packages/dd-trace/src/aiguard/sdk.js +8 -2
  64. package/packages/dd-trace/src/aiguard/tags.js +2 -0
  65. package/packages/dd-trace/src/appsec/blocking/index.js +4 -0
  66. package/packages/dd-trace/src/appsec/graphql.js +91 -6
  67. package/packages/dd-trace/src/appsec/recommended.json +1287 -90
  68. package/packages/dd-trace/src/before-exit.js +32 -0
  69. package/packages/dd-trace/src/bootstrap.js +5 -3
  70. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +15 -2
  71. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +12 -34
  72. package/packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js +41 -13
  73. package/packages/dd-trace/src/ci-visibility/exporters/request.js +2 -3
  74. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +1 -2
  75. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +1 -1
  76. package/packages/dd-trace/src/ci-visibility/telemetry.js +6 -0
  77. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +1 -1
  78. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache-schema.js +9 -134
  79. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache.js +11 -156
  80. package/packages/dd-trace/src/config/config-types.d.ts +3 -0
  81. package/packages/dd-trace/src/config/defaults.js +5 -0
  82. package/packages/dd-trace/src/config/generated-config-types.d.ts +42 -2
  83. package/packages/dd-trace/src/config/index.js +17 -5
  84. package/packages/dd-trace/src/config/parsers.js +9 -0
  85. package/packages/dd-trace/src/config/supported-configurations.json +158 -4
  86. package/packages/dd-trace/src/constants.js +1 -0
  87. package/packages/dd-trace/src/debugger/pause-duration-histogram.js +2 -1
  88. package/packages/dd-trace/src/exporter.js +0 -11
  89. package/packages/dd-trace/src/exporters/common/request.js +81 -48
  90. package/packages/dd-trace/src/exporters/common/retry.js +12 -7
  91. package/packages/dd-trace/src/exporters/common/url.js +1 -1
  92. package/packages/dd-trace/src/id.js +1 -1
  93. package/packages/dd-trace/src/lambda/facade.js +74 -0
  94. package/packages/dd-trace/src/lambda/handler.js +3 -41
  95. package/packages/dd-trace/src/lambda/index.js +38 -15
  96. package/packages/dd-trace/src/lambda/runtime/patch.js +19 -3
  97. package/packages/dd-trace/src/lambda/wrap.js +44 -0
  98. package/packages/dd-trace/src/llmobs/constants/tags.js +2 -0
  99. package/packages/dd-trace/src/llmobs/experiments/experiment.js +10 -5
  100. package/packages/dd-trace/src/llmobs/plugins/elevenlabs.js +96 -0
  101. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +19 -6
  102. package/packages/dd-trace/src/llmobs/plugins/openai/realtime.js +38 -11
  103. package/packages/dd-trace/src/llmobs/plugins/vertexai.js +10 -2
  104. package/packages/dd-trace/src/llmobs/sdk.js +19 -0
  105. package/packages/dd-trace/src/llmobs/span_processor.js +9 -0
  106. package/packages/dd-trace/src/llmobs/tagger.js +22 -0
  107. package/packages/dd-trace/src/log/channels.js +4 -0
  108. package/packages/dd-trace/src/log/writer.js +6 -1
  109. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +4 -0
  110. package/packages/dd-trace/src/openfeature/configuration_source.js +35 -27
  111. package/packages/dd-trace/src/openfeature/flag-selection.js +152 -0
  112. package/packages/dd-trace/src/openfeature/flagging_provider.js +19 -1
  113. package/packages/dd-trace/src/openfeature/writers/base.js +1 -3
  114. package/packages/dd-trace/src/opentelemetry/logs/index.js +11 -0
  115. package/packages/dd-trace/src/opentelemetry/logs/otlp_http_log_exporter.js +1 -1
  116. package/packages/dd-trace/src/opentelemetry/metrics/index.js +7 -1
  117. package/packages/dd-trace/src/opentelemetry/metrics/otlp_http_metric_exporter.js +1 -1
  118. package/packages/dd-trace/src/opentelemetry/metrics/otlp_span_stats_exporter.js +4 -1
  119. package/packages/dd-trace/src/opentelemetry/otlp/otlp_http_exporter_base.js +19 -1
  120. package/packages/dd-trace/src/opentelemetry/span-ending-hook.js +5 -1
  121. package/packages/dd-trace/src/opentelemetry/span-helpers.js +6 -1
  122. package/packages/dd-trace/src/opentelemetry/span.js +2 -2
  123. package/packages/dd-trace/src/opentelemetry/startup-config.js +174 -0
  124. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +1 -1
  125. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +7 -1
  126. package/packages/dd-trace/src/opentracing/propagation/tracestate.js +77 -23
  127. package/packages/dd-trace/src/opentracing/tracer.js +24 -0
  128. package/packages/dd-trace/src/otel-thread-ctx.js +28 -31
  129. package/packages/dd-trace/src/plugin_manager.js +34 -7
  130. package/packages/dd-trace/src/plugins/ci_plugin.js +41 -10
  131. package/packages/dd-trace/src/plugins/index.js +6 -0
  132. package/packages/dd-trace/src/plugins/plugin.js +4 -2
  133. package/packages/dd-trace/src/plugins/tracing.js +1 -1
  134. package/packages/dd-trace/src/plugins/util/ci.js +18 -1
  135. package/packages/dd-trace/src/plugins/util/git-cache.js +4 -4
  136. package/packages/dd-trace/src/plugins/util/git.js +263 -82
  137. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +75 -46
  138. package/packages/dd-trace/src/plugins/util/inferred_proxy.js +12 -4
  139. package/packages/dd-trace/src/plugins/util/status-validator.js +23 -10
  140. package/packages/dd-trace/src/plugins/util/tags.js +6 -0
  141. package/packages/dd-trace/src/plugins/util/test.js +64 -39
  142. package/packages/dd-trace/src/plugins/util/url.js +10 -2
  143. package/packages/dd-trace/src/plugins/util/user-provided-git.js +2 -2
  144. package/packages/dd-trace/src/plugins/util/web.js +65 -10
  145. package/packages/dd-trace/src/profiling/webspan-utils.js +6 -5
  146. package/packages/dd-trace/src/proxy.js +33 -53
  147. package/packages/dd-trace/src/span_processor.js +20 -0
  148. package/packages/dd-trace/src/startup-log.js +8 -6
  149. package/packages/dd-trace/src/telemetry/metrics.js +2 -1
  150. package/packages/dd-trace/src/tracer.js +0 -2
  151. package/packages/dd-trace/src/web-tags-cache.js +8 -9
  152. package/register.js +2 -1
  153. package/vendor/dist/@apm-js-collab/code-transformer/LICENSE +489 -0
  154. package/vendor/dist/@datadog/flagging-core/LICENSE +221 -0
  155. package/vendor/dist/@datadog/flagging-core/index.js +1 -0
  156. package/vendor/dist/@datadog/openfeature-node-server/LICENSE +21 -1
  157. package/vendor/dist/@datadog/openfeature-node-server/rules-based/LICENSE +3 -1
  158. package/vendor/dist/@datadog/sketches-js/LICENSE +263 -0
  159. package/vendor/dist/@datadog/source-map/LICENSE +1 -0
  160. package/vendor/dist/@isaacs/ttlcache/LICENSE +13 -0
  161. package/vendor/dist/@opentelemetry/core/LICENSE +209 -1
  162. package/vendor/dist/crypto-randomuuid/LICENSE +3 -0
  163. package/vendor/dist/escape-string-regexp/LICENSE +13 -0
  164. package/vendor/dist/esquery/LICENSE +2 -0
  165. package/vendor/dist/https-proxy-agent/LICENSE +80 -1
  166. package/vendor/dist/istanbul-lib-coverage/LICENSE +2 -0
  167. package/vendor/dist/jest-docblock/LICENSE +16 -0
  168. package/vendor/dist/jsonpath-plus/LICENSE +13 -0
  169. package/vendor/dist/limiter/LICENSE +2 -0
  170. package/vendor/dist/lodash.sortby/LICENSE +2 -0
  171. package/vendor/dist/lru-cache/LICENSE +13 -0
  172. package/vendor/dist/meriyah/LICENSE +13 -0
  173. package/vendor/dist/module-details-from-path/LICENSE +2 -0
  174. package/vendor/dist/mutexify/promise/LICENSE +28 -0
  175. package/vendor/dist/pprof-format/LICENSE +13 -0
  176. package/vendor/dist/pprof-format/index.js +1 -1
  177. package/vendor/dist/protobufjs/LICENSE +219 -0
  178. package/vendor/dist/protobufjs/minimal/LICENSE +219 -0
  179. package/vendor/dist/proxy-from-env/LICENSE +13 -0
  180. package/vendor/dist/retry/LICENSE +2 -0
  181. package/vendor/dist/rfdc/LICENSE +2 -0
  182. package/vendor/dist/semifies/LICENSE +3 -1
  183. package/vendor/dist/shell-quote/LICENSE +3 -1
  184. package/vendor/dist/source-map/LICENSE +1 -0
  185. package/vendor/dist/source-map/lib/util/LICENSE +1 -0
  186. package/vendor/dist/tlhunter-sorted-set/LICENSE +2 -0
  187. package/vendor/dist/ttl-set/LICENSE +28 -0
  188. package/ci/diagnose.js +0 -2215
  189. package/ci/runbook.md +0 -299
  190. package/ci/test-optimization-validation/approval-artifacts.js +0 -175
  191. package/ci/test-optimization-validation/approval.js +0 -386
  192. package/ci/test-optimization-validation/artifact-id.js +0 -18
  193. package/ci/test-optimization-validation/blocker-category.js +0 -24
  194. package/ci/test-optimization-validation/bounded-json.js +0 -120
  195. package/ci/test-optimization-validation/ci-command-candidate.js +0 -77
  196. package/ci/test-optimization-validation/ci-discovery.js +0 -192
  197. package/ci/test-optimization-validation/ci-package-scripts.js +0 -169
  198. package/ci/test-optimization-validation/ci-remediation.js +0 -283
  199. package/ci/test-optimization-validation/cli.js +0 -954
  200. package/ci/test-optimization-validation/command-blocker.js +0 -377
  201. package/ci/test-optimization-validation/command-output-policy.js +0 -188
  202. package/ci/test-optimization-validation/command-runner.js +0 -649
  203. package/ci/test-optimization-validation/environment.js +0 -88
  204. package/ci/test-optimization-validation/executable-approval.js +0 -47
  205. package/ci/test-optimization-validation/executable.js +0 -244
  206. package/ci/test-optimization-validation/execution-lock.js +0 -70
  207. package/ci/test-optimization-validation/framework-adapters/cucumber-validation.json +0 -3
  208. package/ci/test-optimization-validation/framework-adapters/cucumber.js +0 -767
  209. package/ci/test-optimization-validation/framework-adapters/cypress.js +0 -99
  210. package/ci/test-optimization-validation/framework-adapters/playwright.js +0 -175
  211. package/ci/test-optimization-validation/framework-adapters/vitest.js +0 -513
  212. package/ci/test-optimization-validation/generated-file-policy.js +0 -63
  213. package/ci/test-optimization-validation/generated-files.js +0 -425
  214. package/ci/test-optimization-validation/generated-test-contract.js +0 -284
  215. package/ci/test-optimization-validation/generated-verifier.js +0 -235
  216. package/ci/test-optimization-validation/literal-environment.js +0 -56
  217. package/ci/test-optimization-validation/literal-glob.js +0 -52
  218. package/ci/test-optimization-validation/manifest-loader.js +0 -116
  219. package/ci/test-optimization-validation/manifest-scaffold.js +0 -1276
  220. package/ci/test-optimization-validation/manifest-schema.js +0 -695
  221. package/ci/test-optimization-validation/offline-fixtures.js +0 -335
  222. package/ci/test-optimization-validation/offline-output.js +0 -406
  223. package/ci/test-optimization-validation/package-check.js +0 -97
  224. package/ci/test-optimization-validation/payload-normalizer.js +0 -72
  225. package/ci/test-optimization-validation/plan-writer.js +0 -541
  226. package/ci/test-optimization-validation/preflight-runner.js +0 -186
  227. package/ci/test-optimization-validation/project-build-artifact.js +0 -31
  228. package/ci/test-optimization-validation/redaction.js +0 -319
  229. package/ci/test-optimization-validation/report-writer.js +0 -666
  230. package/ci/test-optimization-validation/result-semantics.js +0 -103
  231. package/ci/test-optimization-validation/runner-command.js +0 -264
  232. package/ci/test-optimization-validation/runner-contract.js +0 -695
  233. package/ci/test-optimization-validation/safe-files.js +0 -202
  234. package/ci/test-optimization-validation/scenarios/auto-test-retries.js +0 -171
  235. package/ci/test-optimization-validation/scenarios/basic-reporting.js +0 -407
  236. package/ci/test-optimization-validation/scenarios/ci-wiring.js +0 -666
  237. package/ci/test-optimization-validation/scenarios/early-flake-detection.js +0 -142
  238. package/ci/test-optimization-validation/scenarios/helpers.js +0 -621
  239. package/ci/test-optimization-validation/scenarios/test-management.js +0 -219
  240. package/ci/test-optimization-validation/source-text.js +0 -84
  241. package/ci/test-optimization-validation/static-diagnosis.js +0 -166
  242. package/ci/test-optimization-validation/test-output.js +0 -120
  243. package/ci/test-optimization-validation/validation-blocker.js +0 -21
  244. package/ci/validate-test-optimization.js +0 -3
  245. package/packages/datadog-esbuild/src/resolver.js +0 -284
  246. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/index.js +0 -156
  247. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/msgpack-to-json.js +0 -287
  248. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/payload-projection.js +0 -84
  249. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/sink.js +0 -368
  250. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/writer.js +0 -59
@@ -0,0 +1,96 @@
1
+ 'use strict'
2
+
3
+ const { pcm16ToWav } = require('../audio-codec')
4
+ const { fitsInlineAudioBudget, formatAudioPartWithGuard } = require('../audio-utils')
5
+ const { AUDIO_FALLBACK, LLMOBS_AUDIO_INLINE_MAX_BYTES } = require('../constants/audio')
6
+ const { SESSION_ID } = require('../constants/tags')
7
+ const { storage } = require('../storage')
8
+ const LLMObsPlugin = require('./base')
9
+
10
+ /** @typedef {import('../../../../datadog-instrumentations/src/elevenlabs/session').Scope} Scope */
11
+ /** @typedef {import('../../../../datadog-core/src/storage').Store<unknown>} Store */
12
+
13
+ class ElevenLabsLLMObsPlugin extends LLMObsPlugin {
14
+ static id = 'elevenlabs_llmobs'
15
+ static integration = 'elevenlabs'
16
+ static prefix = 'tracing:apm:elevenlabs:span'
17
+ static emitsGenAiApmTags = false
18
+
19
+ constructor (...args) {
20
+ super(...args)
21
+ this.addSub('dd-trace:elevenlabs:audio', () => {})
22
+ this.addSub('dd-trace:elevenlabs:capture-context', message => {
23
+ const scope = /** @type {Scope} */ (message)
24
+ // An absent store intentionally restores an explicit root context.
25
+ const store = /** @type {Store} */ (storage.getStore())
26
+ const previous = scope.runInContext ?? (fn => fn())
27
+ scope.runInContext = fn => previous(() => storage.run(store, fn))
28
+ })
29
+ this.addSub('apm:elevenlabs:annotate', ctx => this.setLLMObsTags(ctx))
30
+ }
31
+
32
+ /** @param {object} ctx */
33
+ getLLMObsSpanRegisterOptions (ctx) {
34
+ const options = {
35
+ kind: ctx.kind,
36
+ name: ctx.name,
37
+ sessionId: ctx.session.sessionId,
38
+ }
39
+ if (ctx.kind === 'llm') {
40
+ options.modelName = ctx.turn.model
41
+ options.modelProvider = 'elevenlabs'
42
+ }
43
+ return options
44
+ }
45
+
46
+ // Annotation is owned by the APM pre-finish signal; the base asyncEnd would tag after serialization.
47
+ asyncEnd () {}
48
+
49
+ /** @param {object} ctx */
50
+ setLLMObsTags (ctx) {
51
+ const span = ctx.currentStore?.span
52
+ if (!span) return
53
+ this._tagger._setTag(span, SESSION_ID, ctx.session.sessionId)
54
+ const { turn } = ctx
55
+ const metadata = { ...turn.metadata }
56
+ if (ctx.activity !== undefined) metadata.user_speech_activity = ctx.activity
57
+ this._tagger.tagMetadata(span, metadata)
58
+ if (ctx.kind === 'tool') {
59
+ this._tagger.tagTextIO(span, JSON.stringify(ctx.parameters), ctx.output)
60
+ return
61
+ }
62
+ if (ctx.kind !== 'llm') {
63
+ if (ctx.name === 'elevenlabs audio turn') this._tagger.tagTextIO(span, turn.userText, turn.text)
64
+ else this._tagger.tagTextIO(span, undefined, ctx.transcript)
65
+ return
66
+ }
67
+ if (turn.model) this._tagger.tagModelName(span, turn.model)
68
+ const input = { role: 'user', content: turn.userText || '' }
69
+ const output = { role: 'assistant', content: turn.text || '' }
70
+ if (turn.calls.size) output.toolCalls = [...turn.calls.values()]
71
+ if (turn.results.size) input.toolResults = [...turn.results.values()]
72
+ // Leave room for the serialized UTF-8 text, tools, metadata, and audio-part wrappers before
73
+ // spending one event budget across both complete WAVs.
74
+ let budget = Math.max(0, LLMOBS_AUDIO_INLINE_MAX_BYTES -
75
+ Buffer.byteLength(JSON.stringify([[input], [output], metadata])) - 256)
76
+ for (const [message, audio, rate] of [
77
+ [input, turn.input, turn.inputRate], [output, turn.output, turn.outputRate],
78
+ ]) {
79
+ if (rate && audio.size && !audio.overflow && fitsInlineAudioBudget(audio.size + 44, budget)) {
80
+ const part = formatAudioPartWithGuard(pcm16ToWav(audio.bytes(), rate), 'audio/wav', budget)
81
+ if (part) {
82
+ message.audioParts = [part]
83
+ budget -= part.content.length
84
+ }
85
+ }
86
+ if (audio.present && !message.audioParts) {
87
+ metadata.audio_omitted = true
88
+ message.content ||= AUDIO_FALLBACK
89
+ }
90
+ }
91
+ this._tagger.tagMetadata(span, metadata)
92
+ this._tagger.tagLLMIO(span, [input], [output])
93
+ }
94
+ }
95
+
96
+ module.exports = ElevenLabsLLMObsPlugin
@@ -101,20 +101,33 @@ function extractMetrics (response) {
101
101
 
102
102
  if (!tokenUsage) return metrics
103
103
 
104
- if (tokenUsage.promptTokenCount) {
105
- metrics.inputTokens = tokenUsage.promptTokenCount
104
+ // Gemini reports thinking tokens (`thoughtsTokenCount`) and tool-use prompt tokens
105
+ // (`toolUsePromptTokenCount`) outside of `candidatesTokenCount` / `promptTokenCount`.
106
+ const { thoughtsTokenCount, toolUsePromptTokenCount, cachedContentTokenCount } = tokenUsage
107
+ const inputTokens = (tokenUsage.promptTokenCount || 0) + (toolUsePromptTokenCount || 0)
108
+ const outputTokens = (tokenUsage.candidatesTokenCount || 0) + (thoughtsTokenCount || 0)
109
+
110
+ if (inputTokens) {
111
+ metrics.inputTokens = inputTokens
106
112
  }
107
113
 
108
- if (tokenUsage.candidatesTokenCount) {
109
- metrics.outputTokens = tokenUsage.candidatesTokenCount
114
+ if (outputTokens) {
115
+ metrics.outputTokens = outputTokens
110
116
  }
111
117
 
112
- const totalTokens = tokenUsage.totalTokenCount ||
113
- (tokenUsage.promptTokenCount || 0) + (tokenUsage.candidatesTokenCount || 0)
118
+ const totalTokens = tokenUsage.totalTokenCount || inputTokens + outputTokens
114
119
  if (totalTokens) {
115
120
  metrics.totalTokens = totalTokens
116
121
  }
117
122
 
123
+ if (cachedContentTokenCount) {
124
+ metrics.cacheReadTokens = cachedContentTokenCount
125
+ }
126
+
127
+ if (thoughtsTokenCount) {
128
+ metrics.reasoningOutputTokens = thoughtsTokenCount
129
+ }
130
+
118
131
  return metrics
119
132
  }
120
133
 
@@ -120,26 +120,53 @@ function buildMessage (role, side, maxAudioBytes) {
120
120
  }
121
121
 
122
122
  /**
123
- * @param {{ input_tokens?: number, output_tokens?: number, total_tokens?: number } | undefined} usage
123
+ * @param {{
124
+ * input_tokens?: number, output_tokens?: number, total_tokens?: number,
125
+ * input_token_details?: {
126
+ * audio_tokens?: number, text_tokens?: number, image_tokens?: number, cached_tokens?: number,
127
+ * cached_tokens_details?: { audio_tokens?: number, text_tokens?: number, image_tokens?: number }
128
+ * },
129
+ * output_token_details?: { audio_tokens?: number, text_tokens?: number }
130
+ * } | undefined} usage
124
131
  * @returns {Record<string, number> | undefined}
125
132
  */
126
133
  function usageMetrics (usage) {
127
134
  if (!usage) return
128
135
 
129
- const { input_tokens: inputTokens, output_tokens: outputTokens } = usage
130
- let { total_tokens: totalTokens } = usage
131
-
136
+ // Named modality and cache counts are subsets of the inclusive totals.
137
+ // Missing details stay absent; never infer text or a cache intersection.
138
+ const inputDetails = usage.input_token_details
139
+ const counts = {
140
+ input_tokens: usage.input_tokens,
141
+ output_tokens: usage.output_tokens,
142
+ total_tokens: usage.total_tokens,
143
+ cache_read_input_tokens: inputDetails?.cached_tokens,
144
+ input_audio_tokens: inputDetails?.audio_tokens,
145
+ input_text_tokens: inputDetails?.text_tokens,
146
+ input_image_tokens: inputDetails?.image_tokens,
147
+ output_audio_tokens: usage.output_token_details?.audio_tokens,
148
+ output_text_tokens: usage.output_token_details?.text_tokens,
149
+ cache_audio_read_tokens: inputDetails?.cached_tokens_details?.audio_tokens,
150
+ cache_text_read_tokens: inputDetails?.cached_tokens_details?.text_tokens,
151
+ cache_image_read_tokens: inputDetails?.cached_tokens_details?.image_tokens,
152
+ }
132
153
  /** @type {Record<string, number>} */
133
154
  const metrics = {}
134
- if (inputTokens != null) metrics.input_tokens = inputTokens
135
- if (outputTokens != null) metrics.output_tokens = outputTokens
136
- // Mirror the chat and responses fallback.
137
- if (totalTokens == null && inputTokens != null && outputTokens != null) {
138
- totalTokens = inputTokens + outputTokens
155
+ let hasMetrics = false
156
+ for (const [key, value] of Object.entries(counts)) {
157
+ if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) {
158
+ metrics[key] = value
159
+ hasMetrics = true
160
+ }
139
161
  }
140
- if (totalTokens != null) metrics.total_tokens = totalTokens
141
162
 
142
- return metrics.total_tokens === undefined && metrics.input_tokens === undefined ? undefined : metrics
163
+ // Preserve the existing total fallback only when no total was supplied. Both
164
+ // components and their sum must be valid; an invalid reported total stays absent.
165
+ if (usage.total_tokens == null && metrics.input_tokens !== undefined && metrics.output_tokens !== undefined) {
166
+ const total = metrics.input_tokens + metrics.output_tokens
167
+ if (Number.isSafeInteger(total)) metrics.total_tokens = total
168
+ }
169
+ return hasMetrics ? metrics : undefined
143
170
  }
144
171
 
145
172
  /**
@@ -187,9 +187,17 @@ function extractMetrics (result) {
187
187
  const tokenCounts = response.usageMetadata
188
188
  const metrics = {}
189
189
  if (tokenCounts) {
190
- metrics.inputTokens = tokenCounts.promptTokenCount
191
- metrics.outputTokens = tokenCounts.candidatesTokenCount
190
+ const { thoughtsTokenCount, toolUsePromptTokenCount, cachedContentTokenCount } = tokenCounts
191
+ // Gemini reports thinking and tool-use prompt tokens outside the prompt/candidates counts.
192
+ metrics.inputTokens = toolUsePromptTokenCount
193
+ ? (tokenCounts.promptTokenCount || 0) + toolUsePromptTokenCount
194
+ : tokenCounts.promptTokenCount
195
+ metrics.outputTokens = thoughtsTokenCount
196
+ ? (tokenCounts.candidatesTokenCount || 0) + thoughtsTokenCount
197
+ : tokenCounts.candidatesTokenCount
192
198
  metrics.totalTokens = tokenCounts.totalTokenCount
199
+ if (cachedContentTokenCount) metrics.cacheReadTokens = cachedContentTokenCount
200
+ if (thoughtsTokenCount) metrics.reasoningOutputTokens = thoughtsTokenCount
193
201
  }
194
202
 
195
203
  return metrics
@@ -361,6 +361,23 @@ class LLMObs extends NoopLLMObs {
361
361
  }
362
362
  }
363
363
 
364
+ /**
365
+ * Annotates an experiment row span with its inputs, outputs, and expected output.
366
+ *
367
+ * @param {import('../opentracing/span')} span
368
+ * @param {{
369
+ * inputData: unknown,
370
+ * outputData: unknown,
371
+ * expectedOutput: unknown,
372
+ * metadata: object,
373
+ * tags: object
374
+ * }} options
375
+ */
376
+ _annotateExperimentSpan (span, options) {
377
+ this.annotate(span, options)
378
+ this._tagger.tagExperimentExpectedOutput(span, options.expectedOutput)
379
+ }
380
+
364
381
  exportSpan (span) {
365
382
  span ||= this._active()
366
383
  let err = ''
@@ -728,6 +745,7 @@ class LLMObs extends NoopLLMObs {
728
745
  mlApp,
729
746
  version,
730
747
  _decorator,
748
+ _experimentTags,
731
749
  ...spanOptions
732
750
  } = options
733
751
 
@@ -747,6 +765,7 @@ class LLMObs extends NoopLLMObs {
747
765
  sessionId,
748
766
  agentVersion,
749
767
  _decorator,
768
+ _experimentTags,
750
769
  spanOptions,
751
770
  }
752
771
  }
@@ -16,6 +16,7 @@ const {
16
16
  SPAN_KIND,
17
17
  MODEL_NAME,
18
18
  MODEL_PROVIDER,
19
+ EXPERIMENT_EXPECTED_OUTPUT,
19
20
  METADATA,
20
21
  COST_TAGS,
21
22
  AGENT_MANIFEST,
@@ -267,6 +268,11 @@ class LLMObsSpanProcessor {
267
268
  const isExperiment = spanKind === 'experiment'
268
269
  const hasExperimentInput = isExperiment && Object.hasOwn(mlObsTags, EXPERIMENT_INPUT)
269
270
  const hasExperimentOutput = isExperiment && Object.hasOwn(mlObsTags, EXPERIMENT_OUTPUT)
271
+ const hasExperimentExpectedOutput = isExperiment && Object.hasOwn(mlObsTags, EXPERIMENT_EXPECTED_OUTPUT)
272
+
273
+ if (hasExperimentExpectedOutput) {
274
+ llmObsSpan.expectedOutput = mlObsTags[EXPERIMENT_EXPECTED_OUTPUT]
275
+ }
270
276
 
271
277
  if (hasExperimentInput) {
272
278
  llmObsSpan.input = [{ role: '', content: mlObsTags[EXPERIMENT_INPUT] }]
@@ -318,6 +324,9 @@ class LLMObsSpanProcessor {
318
324
  const [processedOutput] = processedSpan.output
319
325
  if (hasExperimentInput && processedInput !== undefined) meta.input = processedInput.content
320
326
  if (hasExperimentOutput && processedOutput !== undefined) meta.output = processedOutput.content
327
+ if (Object.hasOwn(processedSpan, 'expectedOutput') && processedSpan.expectedOutput !== undefined) {
328
+ meta.expected_output = processedSpan.expectedOutput
329
+ }
321
330
  } else {
322
331
  if (processedSpan.input) {
323
332
  if (inputType === 'messages') {
@@ -8,9 +8,11 @@ const {
8
8
  MODEL_NAME,
9
9
  MODEL_PROVIDER,
10
10
  SESSION_ID,
11
+ EXPERIMENT_TAGS,
11
12
  SESSION_ID_TRACE_DEFAULT_KEY,
12
13
  ML_APP,
13
14
  SPAN_KIND,
15
+ EXPERIMENT_EXPECTED_OUTPUT,
14
16
  EXPERIMENT_INPUT,
15
17
  EXPERIMENT_OUTPUT,
16
18
  INPUT_VALUE,
@@ -121,6 +123,7 @@ class LLMObsTagger {
121
123
  integration,
122
124
  agentVersion,
123
125
  _decorator,
126
+ _experimentTags,
124
127
  } = {}) {
125
128
  // Do not register it in the map if it does not have an LLMObs span kind.
126
129
  if (!this.#config.llmobs.DD_LLMOBS_ENABLED || !kind) return
@@ -188,6 +191,15 @@ class LLMObsTagger {
188
191
  const tags = annotationContext?.tags
189
192
  if (tags) this.tagSpanTags(span, tags)
190
193
 
194
+ // Experiment context flows down the span tree, matching Python, which carries it on the span context.
195
+ // It stays out of annotationContext and is applied after its tags, so a user's nested
196
+ // annotationContext({ tags }) can neither replace it nor reassign the span to another run.
197
+ const experimentTags = _experimentTags ?? registry.get(parent)?.[EXPERIMENT_TAGS]
198
+ if (experimentTags) {
199
+ this._setTag(span, EXPERIMENT_TAGS, experimentTags)
200
+ this.tagSpanTags(span, experimentTags)
201
+ }
202
+
191
203
  // apply after tags so only keys present at span start are accepted.
192
204
  if (annotationContext?.costTags != null) {
193
205
  this.tagCostTags(span, annotationContext.costTags, 'annotation_context')
@@ -342,6 +354,16 @@ class LLMObsTagger {
342
354
  this.#tagExperimentValue(span, outputData, EXPERIMENT_OUTPUT, 'output')
343
355
  }
344
356
 
357
+ /**
358
+ * Stores the expected output for an experiment span.
359
+ *
360
+ * @param {import('../opentracing/span')} span
361
+ * @param {unknown} expectedOutput
362
+ */
363
+ tagExperimentExpectedOutput (span, expectedOutput) {
364
+ this.#tagExperimentValue(span, expectedOutput, EXPERIMENT_EXPECTED_OUTPUT, 'expected output')
365
+ }
366
+
345
367
  tagTextIO (span, inputData, outputData) {
346
368
  this.#tagText(span, inputData, INPUT_VALUE)
347
369
  this.#tagText(span, outputData, OUTPUT_VALUE)
@@ -25,6 +25,10 @@ class LogChannel {
25
25
  this._level = getChannelLogLevel(level)
26
26
  }
27
27
 
28
+ getLevel () {
29
+ return Object.keys(Level).find(name => Level[name] === this._level) ?? 'none'
30
+ }
31
+
28
32
  subscribe (logger) {
29
33
  if (Level.trace >= this._level) {
30
34
  traceChannel.subscribe(logger.trace)
@@ -65,4 +65,9 @@ function trace (log) {
65
65
  withNoop(() => logger.debug(log))
66
66
  }
67
67
 
68
- module.exports = { configure, error, warn, info, debug, trace }
68
+ function getLogLevel () {
69
+ if (!enabled) return 'none'
70
+ return logChannel.getLevel()
71
+ }
72
+
73
+ module.exports = { configure, error, warn, info, debug, trace, getLogLevel }
@@ -7,6 +7,7 @@ const { setTimeout: sleep } = require('node:timers/promises')
7
7
  const request = require('../exporters/common/request')
8
8
  const { getClientLibraryHeaders } = require('../exporters/common/client-library-headers')
9
9
  const log = require('../log')
10
+ const { reportIgnoredFlagSelection } = require('./flag-selection')
10
11
 
11
12
  const MAX_ATTEMPTS = 3
12
13
  const FIRST_RETRY_MIN_MS = 2000
@@ -20,6 +21,7 @@ const POLL_FAILED_WITHOUT_CONFIGURATION = 'Feature Flags: agentless configuratio
20
21
  /**
21
22
  * @typedef {object} AgentlessSourceConfig
22
23
  * @property {URL} endpoint
24
+ * @property {boolean} [flagSelectionSent]
23
25
  * @property {number} pollIntervalMs
24
26
  * @property {number} requestTimeoutMs
25
27
  * @property {string | undefined} apiKey
@@ -248,6 +250,8 @@ class AgentlessConfigurationSource {
248
250
  return
249
251
  }
250
252
 
253
+ if (this.#config.flagSelectionSent) reportIgnoredFlagSelection(response.headers)
254
+
251
255
  const etag = response.headers?.etag
252
256
  const value = Array.isArray(etag) ? etag[0] : etag
253
257
  this.#etag = value?.trim() || undefined
@@ -2,6 +2,7 @@
2
2
 
3
3
  const { createSiteUrl } = require('../exporters/common/url')
4
4
  const log = require('../log')
5
+ const { warnRemoteConfigFlagSelection, withFlagSelection } = require('./flag-selection')
5
6
 
6
7
  const DEFAULT_AGENTLESS_PATH = '/api/v2/feature-flagging/config/rules-based/server'
7
8
  const MAX_POLL_INTERVAL_SECONDS = 60 * 60
@@ -10,12 +11,19 @@ const AGENTLESS_START_MESSAGE = 'Feature Flags: starting agentless configuration
10
11
  const REMOTE_CONFIG_DISABLED_WARNING = 'Feature Flags: configuration source is remote_config but Remote ' +
11
12
  'Configuration is disabled; flag evaluations will return their default values. Set ' +
12
13
  'DD_REMOTE_CONFIGURATION_ENABLED=true or DD_FEATURE_FLAGS_CONFIGURATION_SOURCE=agentless'
14
+ const MISSING_API_KEY_MESSAGE = 'DD_API_KEY is required for the default Datadog Feature Flagging endpoint; ' +
15
+ 'set DD_API_KEY, set DD_FEATURE_FLAGS_CONFIGURATION_SOURCE_AGENTLESS_BASE_URL, or set ' +
16
+ 'DD_FEATURE_FLAGS_CONFIGURATION_SOURCE=remote_config to load flags through the Datadog Agent'
13
17
 
14
18
  /**
15
19
  * @typedef {import('@datadog/openfeature-node-server').UniversalFlagConfigurationV1} UniversalFlagConfiguration
16
20
  */
17
21
 
18
22
  /**
23
+ * Creates the agentless source when it is the selected configuration source.
24
+ *
25
+ * Throws when the agentless source is selected but cannot start, so the provider can fail initialization.
26
+ *
19
27
  * @param {import('../config/config-base')} config
20
28
  * @param {(configuration: UniversalFlagConfiguration) => void} applyConfiguration
21
29
  */
@@ -26,46 +34,46 @@ function create (config, applyConfiguration) {
26
34
  DD_FEATURE_FLAGS_CONFIGURATION_SOURCE_AGENTLESS_POLL_INTERVAL_SECONDS: pollIntervalSeconds,
27
35
  DD_FEATURE_FLAGS_CONFIGURATION_SOURCE_AGENTLESS_REQUEST_TIMEOUT_SECONDS: requestTimeoutSeconds,
28
36
  DD_FEATURE_FLAGS_ENABLED: enabled,
37
+ flagSelection,
29
38
  } = config.featureFlags
30
39
 
31
40
  if (!enabled) return
32
41
 
33
42
  if (source !== 'agentless') {
34
43
  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)
44
+ if (source === 'remote_config') {
45
+ if (!config.remoteConfig?.DD_REMOTE_CONFIGURATION_ENABLED) log.warn(REMOTE_CONFIG_DISABLED_WARNING)
46
+ warnRemoteConfigFlagSelection(flagSelection)
37
47
  }
38
48
  return
39
49
  }
40
50
 
41
51
  const hasCustomEndpoint = Boolean(baseUrl?.trim())
42
52
 
43
- try {
44
- if (!hasCustomEndpoint && !config.DD_API_KEY) {
45
- throw new Error('DD_API_KEY is required for the default Datadog Feature Flagging endpoint')
46
- }
47
-
48
- const AgentlessConfigurationSource = require('./agentless_configuration_source')
49
- const resolvedEndpoint = endpoint(config, baseUrl)
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
- )
59
- return new AgentlessConfigurationSource({
60
- endpoint: resolvedEndpoint,
61
- pollIntervalMs: effectivePollIntervalSeconds * 1000,
62
- requestTimeoutMs: requestTimeoutSeconds * 1000,
63
- apiKey: hasCustomEndpoint ? undefined : config.DD_API_KEY,
64
- env: config.env,
65
- }, applyConfiguration)
66
- } catch (error) {
67
- log.error('Unable to configure Feature Flagging configuration source', error)
53
+ if (!hasCustomEndpoint && !config.DD_API_KEY?.trim()) {
54
+ throw new Error(MISSING_API_KEY_MESSAGE)
68
55
  }
56
+
57
+ const AgentlessConfigurationSource = require('./agentless_configuration_source')
58
+ const resolvedEndpoint = endpoint(config, baseUrl)
59
+ const selectedEndpoint = withFlagSelection(resolvedEndpoint, flagSelection)
60
+ const effectivePollIntervalSeconds = Math.min(pollIntervalSeconds, MAX_POLL_INTERVAL_SECONDS)
61
+ log.debug(
62
+ AGENTLESS_START_MESSAGE,
63
+ redactedUrl(resolvedEndpoint),
64
+ hasCustomEndpoint ? 'custom' : 'default',
65
+ effectivePollIntervalSeconds,
66
+ requestTimeoutSeconds,
67
+ hasCustomEndpoint ? 'not sent' : 'sent'
68
+ )
69
+ return new AgentlessConfigurationSource({
70
+ endpoint: selectedEndpoint ?? resolvedEndpoint,
71
+ flagSelectionSent: selectedEndpoint !== undefined,
72
+ pollIntervalMs: effectivePollIntervalSeconds * 1000,
73
+ requestTimeoutMs: requestTimeoutSeconds * 1000,
74
+ apiKey: hasCustomEndpoint ? undefined : config.DD_API_KEY,
75
+ env: config.env,
76
+ }, applyConfiguration)
69
77
  }
70
78
 
71
79
  /**
@@ -0,0 +1,152 @@
1
+ 'use strict'
2
+
3
+ const log = require('../log')
4
+ const telemetryMetrics = require('../telemetry/metrics')
5
+
6
+ // Fastly answers URLs over 8 KB with 414 URI Too Long: https://docs.fastly.com/products/network-services-resource-limits
7
+ const MAX_RULES_URL_BYTES = 8192
8
+ const NOT_SENT = 'featureFlags.flagSelection was not sent (%s: %s). Loading the full flag configuration.'
9
+ const IGNORED = 'featureFlags.flagSelection was ignored by the server (%s). Loaded the full flag configuration.'
10
+ const REMOTE_CONFIG_UNSUPPORTED = 'featureFlags.flagSelection is not supported when flags are delivered through ' +
11
+ 'Remote Config. Loading the full flag configuration.'
12
+ const MALFORMED_LIMIT = 'featureFlags.flagSelection must be an object with optional tags and keyPatterns string arrays'
13
+ const URL_LIMIT = `the request URL is at most ${MAX_RULES_URL_BYTES} bytes`
14
+ const IGNORED_REASONS = new Set([
15
+ 'malformed_selection',
16
+ 'too_many_values',
17
+ 'invalid_key_pattern',
18
+ 'invalid_tag',
19
+ 'tag_load_failed',
20
+ ])
21
+
22
+ const tracerMetrics = telemetryMetrics.manager.namespace('tracers')
23
+ const countedDroppedReasons = new Set()
24
+ const reportedIgnoredReasons = new Set()
25
+
26
+ /**
27
+ * @typedef {'malformed_selection' | 'too_many_values' | 'invalid_key_pattern' | 'invalid_tag'} DropReason
28
+ * @typedef {{ selection?: { tags: string[], keyPatterns: string[] }, error?: DropReason }} CanonicalizeResult
29
+ */
30
+
31
+ let flaggingCore
32
+
33
+ /**
34
+ * @param {unknown} option - Raw `featureFlags.flagSelection` value; must not be null or undefined.
35
+ * @returns {CanonicalizeResult}
36
+ */
37
+ function canonicalize (option) {
38
+ try {
39
+ flaggingCore ??= require('../../../../vendor/dist/@datadog/flagging-core')
40
+ return flaggingCore.canonicalizeFlagSelection(option)
41
+ } catch {
42
+ // Canonicalization failed or the vendored bundle could not load: nothing can be sent.
43
+ return { error: 'malformed_selection' }
44
+ }
45
+ }
46
+
47
+ /**
48
+ * @param {DropReason} reason
49
+ */
50
+ function limitDescription (reason) {
51
+ switch (reason) {
52
+ case 'malformed_selection':
53
+ return MALFORMED_LIMIT
54
+ case 'too_many_values':
55
+ return `each list accepts at most ${flaggingCore.MAX_FLAG_SELECTION_VALUES} values`
56
+ case 'invalid_key_pattern':
57
+ return `each key pattern is at most ${flaggingCore.MAX_FLAG_SELECTION_KEY_PATTERN_BYTES} UTF-8 bytes`
58
+ case 'invalid_tag':
59
+ return `each tag is at most ${flaggingCore.MAX_FLAG_SELECTION_TAG_BYTES} UTF-8 bytes`
60
+ }
61
+ }
62
+
63
+ /**
64
+ * @param {DropReason} reason
65
+ * @param {string} limit
66
+ */
67
+ function reportDropped (reason, limit) {
68
+ log.error(NOT_SENT, reason, limit)
69
+ if (countedDroppedReasons.has(reason)) return
70
+ countedDroppedReasons.add(reason)
71
+ tracerMetrics.count('flag_selection.dropped', { reason }).inc()
72
+ }
73
+
74
+ /**
75
+ * Percent-encodes everything outside the RFC 3986 unreserved set; `encodeURIComponent` keeps `!'()*`.
76
+ *
77
+ * @param {string} value
78
+ */
79
+ function encodeQueryValue (value) {
80
+ return encodeURIComponent(value)
81
+ .replaceAll(/[!'()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)
82
+ }
83
+
84
+ /**
85
+ * Adds the canonical selection to the rules endpoint query, or reports why it is not sent.
86
+ *
87
+ * @param {URL} endpoint
88
+ * @param {unknown} option - Raw `featureFlags.flagSelection` value.
89
+ * @returns {URL | undefined} The endpoint with the selection, or undefined when no selection is sent.
90
+ */
91
+ function withFlagSelection (endpoint, option) {
92
+ if (option === undefined || option === null) return
93
+
94
+ const { selection, error } = canonicalize(option)
95
+ if (error) {
96
+ reportDropped(error, limitDescription(error))
97
+ return
98
+ }
99
+ if (!selection) return
100
+
101
+ let parameters
102
+ try {
103
+ parameters = [
104
+ ...selection.tags.map(tag => `selected_flag_tags=${encodeQueryValue(tag)}`),
105
+ ...selection.keyPatterns.map(pattern => `selected_flag_key_patterns=${encodeQueryValue(pattern)}`),
106
+ ].join('&')
107
+ } catch {
108
+ // flagging-core validates entries by index but canonicalizes through the iterator, which can yield bad text.
109
+ reportDropped('malformed_selection', MALFORMED_LIMIT)
110
+ return
111
+ }
112
+ const url = new URL(endpoint)
113
+ const query = url.search.slice(1)
114
+ url.search = query ? `${query}&${parameters}` : parameters
115
+
116
+ if (Buffer.byteLength(url.href) > MAX_RULES_URL_BYTES) {
117
+ reportDropped('too_many_values', URL_LIMIT)
118
+ return
119
+ }
120
+ return url
121
+ }
122
+
123
+ /**
124
+ * @param {import('node:http').IncomingHttpHeaders | undefined} headers - Headers of an applied 200 response.
125
+ */
126
+ function reportIgnoredFlagSelection (headers) {
127
+ const value = headers?.['dd-flag-selection-ignored']
128
+ if (value === undefined || value === '') return
129
+
130
+ // Anything but an exact known reason is reported as unknown, so header content never reaches logs or telemetry.
131
+ const reason = typeof value === 'string' && IGNORED_REASONS.has(value) ? value : 'unknown'
132
+ if (reportedIgnoredReasons.has(reason)) return
133
+ reportedIgnoredReasons.add(reason)
134
+ log.error(IGNORED, reason)
135
+ tracerMetrics.count('flag_selection.ignored', { reason }).inc()
136
+ }
137
+
138
+ /**
139
+ * @param {unknown} option - Raw `featureFlags.flagSelection` value.
140
+ */
141
+ function warnRemoteConfigFlagSelection (option) {
142
+ if (option === undefined || option === null) return
143
+
144
+ const { selection, error } = canonicalize(option)
145
+ if (selection || error) log.warn(REMOTE_CONFIG_UNSUPPORTED)
146
+ }
147
+
148
+ module.exports = {
149
+ reportIgnoredFlagSelection,
150
+ warnRemoteConfigFlagSelection,
151
+ withFlagSelection,
152
+ }