dd-trace 6.0.0-pre-4a869d5 → 6.0.0-pre-5359bfc

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 (51) hide show
  1. package/LICENSE-3rdparty.csv +1 -3
  2. package/ci/init.js +1 -0
  3. package/package.json +2 -4
  4. package/packages/datadog-instrumentations/src/amqplib.js +2 -2
  5. package/packages/datadog-instrumentations/src/child_process.js +150 -0
  6. package/packages/datadog-instrumentations/src/cucumber.js +2 -2
  7. package/packages/datadog-instrumentations/src/helpers/hooks.js +3 -2
  8. package/packages/datadog-instrumentations/src/jest.js +6 -6
  9. package/packages/datadog-instrumentations/src/mocha.js +3 -3
  10. package/packages/datadog-instrumentations/src/mquery.js +65 -0
  11. package/packages/datadog-plugin-amqplib/src/consumer.js +10 -1
  12. package/packages/datadog-plugin-amqplib/src/producer.js +14 -1
  13. package/packages/datadog-plugin-aws-sdk/src/services/kinesis.js +134 -1
  14. package/packages/datadog-plugin-aws-sdk/src/services/sns.js +19 -1
  15. package/packages/datadog-plugin-aws-sdk/src/services/sqs.js +83 -10
  16. package/packages/datadog-plugin-child_process/src/index.js +91 -0
  17. package/packages/datadog-plugin-child_process/src/scrub-cmd-params.js +125 -0
  18. package/packages/datadog-plugin-cucumber/src/index.js +4 -4
  19. package/packages/datadog-plugin-cypress/src/plugin.js +8 -8
  20. package/packages/datadog-plugin-graphql/src/index.js +1 -6
  21. package/packages/datadog-plugin-grpc/src/util.js +1 -1
  22. package/packages/datadog-plugin-jest/src/index.js +1 -1
  23. package/packages/datadog-plugin-mocha/src/index.js +4 -4
  24. package/packages/datadog-plugin-rhea/src/consumer.js +11 -1
  25. package/packages/datadog-plugin-rhea/src/producer.js +11 -0
  26. package/packages/dd-trace/src/appsec/iast/analyzers/command-injection-analyzer.js +1 -1
  27. package/packages/dd-trace/src/appsec/iast/analyzers/nosql-injection-mongodb-analyzer.js +22 -17
  28. package/packages/dd-trace/src/appsec/iast/analyzers/sql-injection-analyzer.js +7 -28
  29. package/packages/dd-trace/src/appsec/iast/analyzers/vulnerability-analyzer.js +10 -6
  30. package/packages/dd-trace/src/appsec/iast/iast-plugin.js +4 -1
  31. package/packages/dd-trace/src/appsec/rule_manager.js +2 -2
  32. package/packages/dd-trace/src/ci-visibility/exporters/agent-proxy/index.js +25 -6
  33. package/packages/dd-trace/src/ci-visibility/exporters/agentless/index.js +2 -0
  34. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +31 -23
  35. package/packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js +30 -8
  36. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +7 -1
  37. package/packages/dd-trace/src/ci-visibility/{intelligent-test-runner/get-itr-configuration.js → requests/get-library-configuration.js} +5 -4
  38. package/packages/dd-trace/src/datastreams/processor.js +36 -5
  39. package/packages/dd-trace/src/datastreams/writer.js +9 -0
  40. package/packages/dd-trace/src/exporters/common/request.js +21 -3
  41. package/packages/dd-trace/src/opentracing/propagation/text_map.js +1 -1
  42. package/packages/dd-trace/src/plugins/ci_plugin.js +5 -5
  43. package/packages/dd-trace/src/plugins/index.js +1 -0
  44. package/packages/dd-trace/src/plugins/util/git.js +6 -0
  45. package/packages/dd-trace/src/plugins/util/web.js +1 -1
  46. package/packages/dd-trace/src/tracer.js +1 -0
  47. package/packages/utils/src/kebabcase.js +16 -0
  48. package/packages/utils/src/pick.js +11 -0
  49. package/packages/utils/src/uniq.js +5 -0
  50. package/packages/datadog-instrumentations/src/child-process.js +0 -29
  51. package/packages/dd-trace/src/plugins/util/exec.js +0 -34
@@ -17,10 +17,7 @@ require,istanbul-lib-coverage,BSD-3-Clause,Copyright 2012-2015 Yahoo! Inc.
17
17
  require,jest-docblock,MIT,Copyright Meta Platforms, Inc. and affiliates.
18
18
  require,koalas,MIT,Copyright 2013-2017 Brian Woodward
19
19
  require,limiter,MIT,Copyright 2011 John Hurliman
20
- require,lodash.kebabcase,MIT,Copyright JS Foundation and other contributors
21
- require,lodash.pick,MIT,Copyright JS Foundation and other contributors
22
20
  require,lodash.sortby,MIT,Copyright JS Foundation and other contributors
23
- require,lodash.uniq,MIT,Copyright JS Foundation and other contributors
24
21
  require,lru-cache,ISC,Copyright (c) 2010-2022 Isaac Z. Schlueter and Contributors
25
22
  require,methods,MIT,Copyright 2013-2014 TJ Holowaychuk
26
23
  require,module-details-from-path,MIT,Copyright 2016 Thomas Watson Steen
@@ -33,6 +30,7 @@ require,protobufjs,BSD-3-Clause,Copyright 2016 Daniel Wirtz
33
30
  require,tlhunter-sorted-set,MIT,Copyright (c) 2023 Datadog Inc.
34
31
  require,retry,MIT,Copyright 2011 Tim Koschützki Felix Geisendörfer
35
32
  require,semver,ISC,Copyright Isaac Z. Schlueter and Contributors
33
+ require,shell-quote,mit,Copyright (c) 2013 James Halliday
36
34
  dev,@types/node,MIT,Copyright Authors
37
35
  dev,autocannon,MIT,Copyright 2016 Matteo Collina
38
36
  dev,aws-sdk,Apache 2.0,Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
package/ci/init.js CHANGED
@@ -44,6 +44,7 @@ if (isJestWorker) {
44
44
  if (shouldInit) {
45
45
  tracer.init(options)
46
46
  tracer.use('fs', false)
47
+ tracer.use('child_process', false)
47
48
  }
48
49
 
49
50
  module.exports = tracer
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dd-trace",
3
- "version": "6.0.0-pre-4a869d5",
3
+ "version": "6.0.0-pre-5359bfc",
4
4
  "description": "Datadog APM tracing client for JavaScript",
5
5
  "main": "index.js",
6
6
  "typings": "index.d.ts",
@@ -87,10 +87,7 @@
87
87
  "jest-docblock": "^29.7.0",
88
88
  "koalas": "^1.0.2",
89
89
  "limiter": "1.1.5",
90
- "lodash.kebabcase": "^4.1.1",
91
- "lodash.pick": "^4.4.0",
92
90
  "lodash.sortby": "^4.7.0",
93
- "lodash.uniq": "^4.5.0",
94
91
  "lru-cache": "^7.14.0",
95
92
  "methods": "^1.1.2",
96
93
  "module-details-from-path": "^1.0.3",
@@ -102,6 +99,7 @@
102
99
  "protobufjs": "^7.2.5",
103
100
  "retry": "^0.13.1",
104
101
  "semver": "^7.5.4",
102
+ "shell-quote": "^1.8.1",
105
103
  "tlhunter-sorted-set": "^0.1.0"
106
104
  },
107
105
  "devDependencies": {
@@ -5,7 +5,7 @@ const {
5
5
  addHook,
6
6
  AsyncResource
7
7
  } = require('./helpers/instrument')
8
- const kebabCase = require('lodash.kebabcase')
8
+ const kebabCase = require('../../utils/src/kebabcase')
9
9
  const shimmer = require('../../datadog-shimmer')
10
10
 
11
11
  const startCh = channel('apm:amqplib:command:start')
@@ -28,7 +28,7 @@ addHook({ name: 'amqplib', file: 'lib/channel.js', versions: ['>=0.5'] }, channe
28
28
  })
29
29
 
30
30
  shimmer.wrap(channel.Channel.prototype, 'sendMessage', sendMessage => function (fields) {
31
- return instrument(sendMessage, this, arguments, 'basic.publish', fields)
31
+ return instrument(sendMessage, this, arguments, 'basic.publish', fields, arguments[2])
32
32
  })
33
33
 
34
34
  shimmer.wrap(channel.BaseChannel.prototype, 'dispatchMessage', dispatchMessage => function (fields, message) {
@@ -0,0 +1,150 @@
1
+ 'use strict'
2
+
3
+ const util = require('util')
4
+
5
+ const {
6
+ addHook,
7
+ AsyncResource
8
+ } = require('./helpers/instrument')
9
+ const shimmer = require('../../datadog-shimmer')
10
+ const dc = require('dc-polyfill')
11
+
12
+ const childProcessChannel = dc.tracingChannel('datadog:child_process:execution')
13
+
14
+ // ignored exec method because it calls to execFile directly
15
+ const execAsyncMethods = ['execFile', 'spawn']
16
+ const execSyncMethods = ['execFileSync', 'spawnSync']
17
+
18
+ const names = ['child_process', 'node:child_process']
19
+
20
+ // child_process and node:child_process returns the same object instance, we only want to add hooks once
21
+ let patched = false
22
+ names.forEach(name => {
23
+ addHook({ name }, childProcess => {
24
+ if (!patched) {
25
+ patched = true
26
+ shimmer.massWrap(childProcess, execAsyncMethods, wrapChildProcessAsyncMethod())
27
+ shimmer.massWrap(childProcess, execSyncMethods, wrapChildProcessSyncMethod())
28
+ shimmer.wrap(childProcess, 'execSync', wrapChildProcessSyncMethod(true))
29
+ }
30
+
31
+ return childProcess
32
+ })
33
+ })
34
+
35
+ function normalizeArgs (args, shell) {
36
+ const childProcessInfo = {
37
+ command: args[0]
38
+ }
39
+
40
+ if (Array.isArray(args[1])) {
41
+ childProcessInfo.command = childProcessInfo.command + ' ' + args[1].join(' ')
42
+ if (args[2] != null && typeof args[2] === 'object') {
43
+ childProcessInfo.options = args[2]
44
+ }
45
+ } else if (args[1] != null && typeof args[1] === 'object') {
46
+ childProcessInfo.options = args[1]
47
+ }
48
+ childProcessInfo.shell = shell ||
49
+ childProcessInfo.options?.shell === true ||
50
+ typeof childProcessInfo.options?.shell === 'string'
51
+
52
+ return childProcessInfo
53
+ }
54
+
55
+ function wrapChildProcessSyncMethod (shell = false) {
56
+ return function wrapMethod (childProcessMethod) {
57
+ return function () {
58
+ if (!childProcessChannel.start.hasSubscribers || arguments.length === 0) {
59
+ return childProcessMethod.apply(this, arguments)
60
+ }
61
+
62
+ const childProcessInfo = normalizeArgs(arguments, shell)
63
+
64
+ return childProcessChannel.traceSync(
65
+ childProcessMethod,
66
+ {
67
+ command: childProcessInfo.command,
68
+ shell: childProcessInfo.shell
69
+ },
70
+ this,
71
+ ...arguments)
72
+ }
73
+ }
74
+ }
75
+
76
+ function wrapChildProcessCustomPromisifyMethod (customPromisifyMethod, shell) {
77
+ return function () {
78
+ if (!childProcessChannel.start.hasSubscribers || arguments.length === 0) {
79
+ return customPromisifyMethod.apply(this, arguments)
80
+ }
81
+
82
+ const childProcessInfo = normalizeArgs(arguments, shell)
83
+
84
+ return childProcessChannel.tracePromise(
85
+ customPromisifyMethod,
86
+ {
87
+ command: childProcessInfo.command,
88
+ shell: childProcessInfo.shell
89
+ },
90
+ this,
91
+ ...arguments)
92
+ }
93
+ }
94
+
95
+ function wrapChildProcessAsyncMethod (shell = false) {
96
+ return function wrapMethod (childProcessMethod) {
97
+ function wrappedChildProcessMethod () {
98
+ if (!childProcessChannel.start.hasSubscribers || arguments.length === 0) {
99
+ return childProcessMethod.apply(this, arguments)
100
+ }
101
+
102
+ const childProcessInfo = normalizeArgs(arguments, shell)
103
+
104
+ const innerResource = new AsyncResource('bound-anonymous-fn')
105
+ return innerResource.runInAsyncScope(() => {
106
+ childProcessChannel.start.publish({ command: childProcessInfo.command, shell: childProcessInfo.shell })
107
+
108
+ const childProcess = childProcessMethod.apply(this, arguments)
109
+ if (childProcess) {
110
+ let errorExecuted = false
111
+
112
+ childProcess.on('error', (e) => {
113
+ errorExecuted = true
114
+ childProcessChannel.error.publish(e)
115
+ })
116
+
117
+ childProcess.on('close', (code) => {
118
+ code = code || 0
119
+ if (!errorExecuted && code !== 0) {
120
+ childProcessChannel.error.publish()
121
+ }
122
+ childProcessChannel.asyncEnd.publish({
123
+ command: childProcessInfo.command,
124
+ shell: childProcessInfo.shell,
125
+ result: code
126
+ })
127
+ })
128
+ }
129
+
130
+ return childProcess
131
+ })
132
+ }
133
+
134
+ if (childProcessMethod[util.promisify.custom]) {
135
+ const wrapedChildProcessCustomPromisifyMethod =
136
+ shimmer.wrap(childProcessMethod[util.promisify.custom],
137
+ wrapChildProcessCustomPromisifyMethod(childProcessMethod[util.promisify.custom]), shell)
138
+
139
+ // should do it in this way because the original property is readonly
140
+ const descriptor = Object.getOwnPropertyDescriptor(childProcessMethod, util.promisify.custom)
141
+ Object.defineProperty(wrappedChildProcessMethod,
142
+ util.promisify.custom,
143
+ {
144
+ ...descriptor,
145
+ value: wrapedChildProcessCustomPromisifyMethod
146
+ })
147
+ }
148
+ return wrappedChildProcessMethod
149
+ }
150
+ }
@@ -16,7 +16,7 @@ const testSuiteStartCh = channel('ci:cucumber:test-suite:start')
16
16
  const testSuiteFinishCh = channel('ci:cucumber:test-suite:finish')
17
17
  const testSuiteCodeCoverageCh = channel('ci:cucumber:test-suite:code-coverage')
18
18
 
19
- const itrConfigurationCh = channel('ci:cucumber:itr-configuration')
19
+ const libraryConfigurationCh = channel('ci:cucumber:library-configuration')
20
20
  const skippableSuitesCh = channel('ci:cucumber:test-suite:skippable')
21
21
  const sessionStartCh = channel('ci:cucumber:session:start')
22
22
  const sessionFinishCh = channel('ci:cucumber:session:finish')
@@ -272,7 +272,7 @@ addHook({
272
272
  })
273
273
 
274
274
  asyncResource.runInAsyncScope(() => {
275
- itrConfigurationCh.publish({ onDone })
275
+ libraryConfigurationCh.publish({ onDone })
276
276
  })
277
277
 
278
278
  await configPromise
@@ -30,7 +30,7 @@ module.exports = {
30
30
  'body-parser': () => require('../body-parser'),
31
31
  'bunyan': () => require('../bunyan'),
32
32
  'cassandra-driver': () => require('../cassandra-driver'),
33
- 'child_process': () => require('../child-process'),
33
+ 'child_process': () => require('../child_process'),
34
34
  'connect': () => require('../connect'),
35
35
  'cookie': () => require('../cookie'),
36
36
  'cookie-parser': () => require('../cookie-parser'),
@@ -73,11 +73,12 @@ module.exports = {
73
73
  'mongodb': () => require('../mongodb'),
74
74
  'mongodb-core': () => require('../mongodb-core'),
75
75
  'mongoose': () => require('../mongoose'),
76
+ 'mquery': () => require('../mquery'),
76
77
  'mysql': () => require('../mysql'),
77
78
  'mysql2': () => require('../mysql2'),
78
79
  'net': () => require('../net'),
79
80
  'next': () => require('../next'),
80
- 'node:child_process': () => require('../child-process'),
81
+ 'node:child_process': () => require('../child_process'),
81
82
  'node:crypto': () => require('../crypto'),
82
83
  'node:dns': () => require('../dns'),
83
84
  'node:http': () => require('../http'),
@@ -37,7 +37,7 @@ const testRunFinishCh = channel('ci:jest:test:finish')
37
37
  const testErrCh = channel('ci:jest:test:err')
38
38
 
39
39
  const skippableSuitesCh = channel('ci:jest:test-suite:skippable')
40
- const jestItrConfigurationCh = channel('ci:jest:itr-configuration')
40
+ const libraryConfigurationCh = channel('ci:jest:library-configuration')
41
41
 
42
42
  const itrSkippedSuitesCh = channel('ci:jest:itr:skipped-suites')
43
43
 
@@ -234,19 +234,19 @@ function cliWrapper (cli, jestVersion) {
234
234
  const configurationPromise = new Promise((resolve) => {
235
235
  onDone = resolve
236
236
  })
237
- if (!jestItrConfigurationCh.hasSubscribers) {
237
+ if (!libraryConfigurationCh.hasSubscribers) {
238
238
  return runCLI.apply(this, arguments)
239
239
  }
240
240
 
241
241
  sessionAsyncResource.runInAsyncScope(() => {
242
- jestItrConfigurationCh.publish({ onDone })
242
+ libraryConfigurationCh.publish({ onDone })
243
243
  })
244
244
 
245
245
  try {
246
- const { err, itrConfig } = await configurationPromise
246
+ const { err, libraryConfig } = await configurationPromise
247
247
  if (!err) {
248
- isCodeCoverageEnabled = itrConfig.isCodeCoverageEnabled
249
- isSuitesSkippingEnabled = itrConfig.isSuitesSkippingEnabled
248
+ isCodeCoverageEnabled = libraryConfig.isCodeCoverageEnabled
249
+ isSuitesSkippingEnabled = libraryConfig.isSuitesSkippingEnabled
250
250
  }
251
251
  } catch (err) {
252
252
  log.error(err)
@@ -20,7 +20,7 @@ const skipCh = channel('ci:mocha:test:skip')
20
20
  const testFinishCh = channel('ci:mocha:test:finish')
21
21
  const parameterizedTestCh = channel('ci:mocha:test:parameterize')
22
22
 
23
- const itrConfigurationCh = channel('ci:mocha:itr-configuration')
23
+ const libraryConfigurationCh = channel('ci:mocha:library-configuration')
24
24
  const skippableSuitesCh = channel('ci:mocha:test-suite:skippable')
25
25
 
26
26
  const testSessionStartCh = channel('ci:mocha:session:start')
@@ -384,7 +384,7 @@ addHook({
384
384
  return run.apply(this, arguments)
385
385
  }
386
386
 
387
- if (!itrConfigurationCh.hasSubscribers || this.isWorker) {
387
+ if (!libraryConfigurationCh.hasSubscribers || this.isWorker) {
388
388
  if (this.isWorker) {
389
389
  isWorker = true
390
390
  }
@@ -439,7 +439,7 @@ addHook({
439
439
  }
440
440
 
441
441
  mochaRunAsyncResource.runInAsyncScope(() => {
442
- itrConfigurationCh.publish({
442
+ libraryConfigurationCh.publish({
443
443
  onDone: mochaRunAsyncResource.bind(onReceivedConfiguration)
444
444
  })
445
445
  })
@@ -0,0 +1,65 @@
1
+ 'use strict'
2
+
3
+ const dc = require('dc-polyfill')
4
+ const {
5
+ channel,
6
+ addHook
7
+ } = require('./helpers/instrument')
8
+ const shimmer = require('../../datadog-shimmer')
9
+
10
+ const prepareCh = channel('datadog:mquery:filter:prepare')
11
+ const tracingCh = dc.tracingChannel('datadog:mquery:filter')
12
+
13
+ const methods = [
14
+ 'find',
15
+ 'findOne',
16
+ 'findOneAndRemove',
17
+ 'findOneAndDelete',
18
+ 'count',
19
+ 'distinct',
20
+ 'where'
21
+ ]
22
+
23
+ const methodsOptionalArgs = ['findOneAndUpdate']
24
+
25
+ function getFilters (args, methodName) {
26
+ const [arg0, arg1] = args
27
+
28
+ const filters = arg0 && typeof arg0 === 'object' ? [arg0] : []
29
+
30
+ if (arg1 && typeof arg1 === 'object' && methodsOptionalArgs.includes(methodName)) {
31
+ filters.push(arg1)
32
+ }
33
+
34
+ return filters
35
+ }
36
+
37
+ addHook({
38
+ name: 'mquery',
39
+ versions: ['>=5.0.0']
40
+ }, Query => {
41
+ [...methods, ...methodsOptionalArgs].forEach(methodName => {
42
+ if (!(methodName in Query.prototype)) return
43
+
44
+ shimmer.wrap(Query.prototype, methodName, method => {
45
+ return function () {
46
+ if (prepareCh.hasSubscribers) {
47
+ const filters = getFilters(arguments, methodName)
48
+ if (filters?.length) {
49
+ prepareCh.publish({ filters })
50
+ }
51
+ }
52
+
53
+ return method.apply(this, arguments)
54
+ }
55
+ })
56
+ })
57
+
58
+ shimmer.wrap(Query.prototype, 'exec', originalExec => {
59
+ return function wrappedExec () {
60
+ return tracingCh.tracePromise(originalExec, {}, this, arguments)
61
+ }
62
+ })
63
+
64
+ return Query
65
+ })
@@ -2,6 +2,7 @@
2
2
 
3
3
  const { TEXT_MAP } = require('../../../ext/formats')
4
4
  const ConsumerPlugin = require('../../dd-trace/src/plugins/consumer')
5
+ const { getAmqpMessageSize, CONTEXT_PROPAGATION_KEY } = require('../../dd-trace/src/datastreams/processor')
5
6
  const { getResourceName } = require('./util')
6
7
 
7
8
  class AmqplibConsumerPlugin extends ConsumerPlugin {
@@ -13,7 +14,7 @@ class AmqplibConsumerPlugin extends ConsumerPlugin {
13
14
 
14
15
  const childOf = extract(this.tracer, message)
15
16
 
16
- this.startSpan({
17
+ const span = this.startSpan({
17
18
  childOf,
18
19
  resource: getResourceName(method, fields),
19
20
  type: 'worker',
@@ -26,6 +27,14 @@ class AmqplibConsumerPlugin extends ConsumerPlugin {
26
27
  'amqp.destination': fields.destination
27
28
  }
28
29
  })
30
+
31
+ if (this.config.dsmEnabled && message) {
32
+ const payloadSize = getAmqpMessageSize({ headers: message.properties.headers, content: message.content })
33
+ const queue = fields.queue ?? fields.routingKey
34
+ this.tracer.decodeDataStreamsContext(message.properties.headers[CONTEXT_PROPAGATION_KEY])
35
+ this.tracer
36
+ .setCheckpoint(['direction:in', `topic:${queue}`, 'type:rabbitmq'], span, payloadSize)
37
+ }
29
38
  }
30
39
  }
31
40
 
@@ -3,13 +3,15 @@
3
3
  const { TEXT_MAP } = require('../../../ext/formats')
4
4
  const { CLIENT_PORT_KEY } = require('../../dd-trace/src/constants')
5
5
  const ProducerPlugin = require('../../dd-trace/src/plugins/producer')
6
+ const { encodePathwayContext } = require('../../dd-trace/src/datastreams/pathway')
7
+ const { getAmqpMessageSize, CONTEXT_PROPAGATION_KEY } = require('../../dd-trace/src/datastreams/processor')
6
8
  const { getResourceName } = require('./util')
7
9
 
8
10
  class AmqplibProducerPlugin extends ProducerPlugin {
9
11
  static get id () { return 'amqplib' }
10
12
  static get operation () { return 'command' }
11
13
 
12
- start ({ channel = {}, method, fields }) {
14
+ start ({ channel = {}, method, fields, message }) {
13
15
  if (method !== 'basic.publish') return
14
16
 
15
17
  const stream = (channel.connection && channel.connection.stream) || {}
@@ -30,6 +32,17 @@ class AmqplibProducerPlugin extends ProducerPlugin {
30
32
  fields.headers = fields.headers || {}
31
33
 
32
34
  this.tracer.inject(span, TEXT_MAP, fields.headers)
35
+
36
+ if (this.config.dsmEnabled) {
37
+ const hasRoutingKey = fields.routingKey != null
38
+ const payloadSize = getAmqpMessageSize({ content: message, headers: fields.headers })
39
+ const dataStreamsContext = this.tracer
40
+ .setCheckpoint(
41
+ ['direction:out', `exchange:${fields.exchange}`, `has_routing_key:${hasRoutingKey}`, 'type:rabbitmq']
42
+ , span, payloadSize)
43
+ const pathwayCtx = encodePathwayContext(dataStreamsContext)
44
+ fields.headers[CONTEXT_PROPAGATION_KEY] = pathwayCtx
45
+ }
33
46
  }
34
47
  }
35
48
 
@@ -1,10 +1,69 @@
1
1
  'use strict'
2
+ const {
3
+ CONTEXT_PROPAGATION_KEY,
4
+ getSizeOrZero
5
+ } = require('../../../dd-trace/src/datastreams/processor')
6
+ const { encodePathwayContext } = require('../../../dd-trace/src/datastreams/pathway')
2
7
  const log = require('../../../dd-trace/src/log')
3
8
  const BaseAwsSdkPlugin = require('../base')
9
+ const { storage } = require('../../../datadog-core')
10
+
4
11
  class Kinesis extends BaseAwsSdkPlugin {
5
12
  static get id () { return 'kinesis' }
6
13
  static get peerServicePrecursors () { return ['streamname'] }
7
14
 
15
+ constructor (...args) {
16
+ super(...args)
17
+
18
+ // TODO(bengl) Find a way to create the response span tags without this WeakMap being populated
19
+ // in the base class
20
+ this.requestTags = new WeakMap()
21
+
22
+ this.addSub('apm:aws:response:start:kinesis', obj => {
23
+ const { request, response } = obj
24
+ const store = storage.getStore()
25
+ const plugin = this
26
+
27
+ // if we have either of these operations, we want to store the streamName param
28
+ // since it is not typically available during get/put records requests
29
+ if (request.operation === 'getShardIterator' || request.operation === 'listShards') {
30
+ this.storeStreamName(request.params, request.operation, store)
31
+ return
32
+ }
33
+
34
+ if (request.operation === 'getRecords') {
35
+ let span
36
+ const responseExtraction = this.responseExtract(request.params, request.operation, response)
37
+ if (responseExtraction && responseExtraction.maybeChildOf) {
38
+ obj.needsFinish = true
39
+ const options = {
40
+ childOf: responseExtraction.maybeChildOf,
41
+ tags: Object.assign(
42
+ {},
43
+ this.requestTags.get(request) || {},
44
+ { 'span.kind': 'server' }
45
+ )
46
+ }
47
+ span = plugin.tracer.startSpan('aws.response', options)
48
+ this.enter(span, store)
49
+ }
50
+
51
+ // get the stream name that should have been stored previously
52
+ const { streamName } = storage.getStore()
53
+
54
+ // extract DSM context after as we might not have a parent-child but may have a DSM context
55
+ this.responseExtractDSMContext(
56
+ request.operation, response, span ?? null, streamName
57
+ )
58
+ }
59
+ })
60
+
61
+ this.addSub('apm:aws:response:finish:kinesis', err => {
62
+ const { span } = storage.getStore()
63
+ this.finish(span, null, err)
64
+ })
65
+ }
66
+
8
67
  generateTags (params, operation, response) {
9
68
  if (!params || !params.StreamName) return {}
10
69
 
@@ -15,6 +74,58 @@ class Kinesis extends BaseAwsSdkPlugin {
15
74
  }
16
75
  }
17
76
 
77
+ storeStreamName (params, operation, store) {
78
+ if (!operation || (operation !== 'getShardIterator' && operation !== 'listShards')) return
79
+ if (!params || !params.StreamName) return
80
+
81
+ const streamName = params.StreamName
82
+ storage.enterWith({ ...store, streamName })
83
+ }
84
+
85
+ responseExtract (params, operation, response) {
86
+ if (operation !== 'getRecords') return
87
+ if (params.Limit && params.Limit !== 1) return
88
+ if (!response || !response.Records || !response.Records[0]) return
89
+
90
+ const record = response.Records[0]
91
+
92
+ try {
93
+ const decodedData = JSON.parse(Buffer.from(record.Data).toString())
94
+
95
+ return {
96
+ maybeChildOf: this.tracer.extract('text_map', decodedData._datadog),
97
+ parsedAttributes: decodedData._datadog
98
+ }
99
+ } catch (e) {
100
+ log.error(e)
101
+ }
102
+ }
103
+
104
+ responseExtractDSMContext (operation, response, span, streamName) {
105
+ if (!this.config.dsmEnabled) return
106
+ if (operation !== 'getRecords') return
107
+ if (!response || !response.Records || !response.Records[0]) return
108
+
109
+ // we only want to set the payloadSize on the span if we have one message, not repeatedly
110
+ span = response.Records.length > 1 ? null : span
111
+
112
+ response.Records.forEach(record => {
113
+ const parsedAttributes = JSON.parse(Buffer.from(record.Data).toString())
114
+
115
+ if (
116
+ parsedAttributes &&
117
+ parsedAttributes._datadog &&
118
+ parsedAttributes._datadog[CONTEXT_PROPAGATION_KEY] &&
119
+ streamName
120
+ ) {
121
+ const payloadSize = getSizeOrZero(record.Data)
122
+ this.tracer.decodeDataStreamsContext(Buffer.from(parsedAttributes._datadog[CONTEXT_PROPAGATION_KEY]))
123
+ this.tracer
124
+ .setCheckpoint(['direction:in', `topic:${streamName}`, 'type:kinesis'], span, payloadSize)
125
+ }
126
+ })
127
+ }
128
+
18
129
  // AWS-SDK will b64 kinesis payloads
19
130
  // or will accept an already b64 encoded payload
20
131
  // This method handles both
@@ -37,8 +148,9 @@ class Kinesis extends BaseAwsSdkPlugin {
37
148
  if (!request.params) {
38
149
  return
39
150
  }
40
-
41
151
  const traceData = {}
152
+
153
+ // inject data with DD context
42
154
  this.tracer.inject(span, 'text_map', traceData)
43
155
  let injectPath
44
156
  if (request.params.Records && request.params.Records.length > 0) {
@@ -49,9 +161,30 @@ class Kinesis extends BaseAwsSdkPlugin {
49
161
  log.error('No valid payload passed, unable to pass trace context')
50
162
  return
51
163
  }
164
+
52
165
  const parsedData = this._tryParse(injectPath.Data)
53
166
  if (parsedData) {
54
167
  parsedData._datadog = traceData
168
+
169
+ // set DSM hash if enabled
170
+ if (this.config.dsmEnabled) {
171
+ // get payload size of request data
172
+ const payloadSize = Buffer.from(JSON.stringify(parsedData)).byteLength
173
+ let stream
174
+ // users can optionally use either stream name or stream arn
175
+ if (request.params && request.params.StreamArn) {
176
+ stream = request.params.StreamArn
177
+ } else if (request.params && request.params.StreamName) {
178
+ stream = request.params.StreamName
179
+ }
180
+ const dataStreamsContext = this.tracer
181
+ .setCheckpoint(['direction:out', `topic:${stream}`, 'type:kinesis'], span, payloadSize)
182
+ if (dataStreamsContext) {
183
+ const pathwayCtx = encodePathwayContext(dataStreamsContext)
184
+ parsedData._datadog[CONTEXT_PROPAGATION_KEY] = pathwayCtx.toJSON()
185
+ }
186
+ }
187
+
55
188
  const finalData = Buffer.from(JSON.stringify(parsedData))
56
189
  const byteSize = finalData.length
57
190
  // Kinesis max payload size is 1MB
@@ -1,4 +1,6 @@
1
1
  'use strict'
2
+ const { CONTEXT_PROPAGATION_KEY, getHeadersSize } = require('../../../dd-trace/src/datastreams/processor')
3
+ const { encodePathwayContext } = require('../../../dd-trace/src/datastreams/pathway')
2
4
  const log = require('../../../dd-trace/src/log')
3
5
  const BaseAwsSdkPlugin = require('../base')
4
6
 
@@ -11,6 +13,7 @@ class Sns extends BaseAwsSdkPlugin {
11
13
 
12
14
  if (!params.TopicArn && !(response.data && response.data.TopicArn)) return {}
13
15
  const TopicArn = params.TopicArn || response.data.TopicArn
16
+
14
17
  // Split the ARN into its parts
15
18
  // ex.'arn:aws:sns:us-east-1:123456789012:my-topic'
16
19
  const arnParts = TopicArn.split(':')
@@ -72,10 +75,25 @@ class Sns extends BaseAwsSdkPlugin {
72
75
  }
73
76
  const ddInfo = {}
74
77
  this.tracer.inject(span, 'text_map', ddInfo)
78
+ // add ddInfo before checking DSM so we can include DD attributes in payload size
75
79
  params.MessageAttributes._datadog = {
76
80
  DataType: 'Binary',
77
- BinaryValue: Buffer.from(JSON.stringify(ddInfo)) // BINARY types are automatically base64 encoded
81
+ BinaryValue: ddInfo
82
+ }
83
+ if (this.config.dsmEnabled) {
84
+ const payloadSize = getHeadersSize({
85
+ Message: params.Message,
86
+ MessageAttributes: params.MessageAttributes
87
+ })
88
+ const dataStreamsContext = this.tracer
89
+ .setCheckpoint(['direction:out', `topic:${params.TopicArn}`, 'type:sns'], span, payloadSize)
90
+ if (dataStreamsContext) {
91
+ const pathwayCtx = encodePathwayContext(dataStreamsContext)
92
+ ddInfo[CONTEXT_PROPAGATION_KEY] = pathwayCtx.toJSON()
93
+ }
78
94
  }
95
+ // BINARY types are automatically base64 encoded
96
+ params.MessageAttributes._datadog.BinaryValue = Buffer.from(JSON.stringify(ddInfo))
79
97
  }
80
98
  }
81
99