dd-trace 5.0.0-pre-069b62a → 5.0.0-pre-e2df7ec

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 (76) hide show
  1. package/LICENSE-3rdparty.csv +1 -0
  2. package/index.d.ts +5 -0
  3. package/package.json +4 -3
  4. package/packages/datadog-instrumentations/src/apollo-server-core.js +41 -0
  5. package/packages/datadog-instrumentations/src/apollo-server.js +83 -0
  6. package/packages/datadog-instrumentations/src/child-process.js +4 -5
  7. package/packages/datadog-instrumentations/src/crypto.js +2 -1
  8. package/packages/datadog-instrumentations/src/dns.js +2 -1
  9. package/packages/datadog-instrumentations/src/graphql.js +18 -4
  10. package/packages/datadog-instrumentations/src/helpers/hooks.js +9 -2
  11. package/packages/datadog-instrumentations/src/helpers/instrument.js +8 -3
  12. package/packages/datadog-instrumentations/src/helpers/register.js +18 -2
  13. package/packages/datadog-instrumentations/src/http/client.js +4 -16
  14. package/packages/datadog-instrumentations/src/http/server.js +7 -4
  15. package/packages/datadog-instrumentations/src/http2/client.js +3 -1
  16. package/packages/datadog-instrumentations/src/http2/server.js +3 -1
  17. package/packages/datadog-instrumentations/src/jest.js +1 -1
  18. package/packages/datadog-instrumentations/src/kafkajs.js +27 -0
  19. package/packages/datadog-instrumentations/src/net.js +10 -2
  20. package/packages/datadog-instrumentations/src/next.js +15 -5
  21. package/packages/datadog-instrumentations/src/restify.js +1 -1
  22. package/packages/datadog-instrumentations/src/rhea.js +15 -9
  23. package/packages/datadog-plugin-cucumber/src/index.js +34 -2
  24. package/packages/datadog-plugin-cypress/src/plugin.js +60 -8
  25. package/packages/datadog-plugin-graphql/src/resolve.js +26 -18
  26. package/packages/datadog-plugin-http/src/client.js +1 -1
  27. package/packages/datadog-plugin-jest/src/index.js +38 -4
  28. package/packages/datadog-plugin-kafkajs/src/consumer.js +51 -0
  29. package/packages/datadog-plugin-kafkajs/src/producer.js +55 -0
  30. package/packages/datadog-plugin-mocha/src/index.js +32 -1
  31. package/packages/datadog-plugin-next/src/index.js +32 -6
  32. package/packages/datadog-plugin-playwright/src/index.js +17 -1
  33. package/packages/dd-trace/src/appsec/activation.js +29 -0
  34. package/packages/dd-trace/src/appsec/addresses.js +1 -0
  35. package/packages/dd-trace/src/appsec/api_security_sampler.js +48 -0
  36. package/packages/dd-trace/src/appsec/blocked_templates.js +4 -1
  37. package/packages/dd-trace/src/appsec/blocking.js +95 -43
  38. package/packages/dd-trace/src/appsec/channels.js +4 -1
  39. package/packages/dd-trace/src/appsec/graphql.js +146 -0
  40. package/packages/dd-trace/src/appsec/iast/analyzers/header-injection-analyzer.js +16 -7
  41. package/packages/dd-trace/src/appsec/index.js +29 -40
  42. package/packages/dd-trace/src/appsec/recommended.json +1395 -2
  43. package/packages/dd-trace/src/appsec/remote_config/capabilities.js +6 -1
  44. package/packages/dd-trace/src/appsec/remote_config/index.js +40 -15
  45. package/packages/dd-trace/src/appsec/reporter.js +2 -4
  46. package/packages/dd-trace/src/appsec/sdk/user_blocking.js +1 -1
  47. package/packages/dd-trace/src/appsec/waf/waf_context_wrapper.js +25 -13
  48. package/packages/dd-trace/src/ci-visibility/exporters/agentless/coverage-writer.js +30 -1
  49. package/packages/dd-trace/src/ci-visibility/exporters/agentless/writer.js +30 -1
  50. package/packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js +36 -4
  51. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-itr-configuration.js +18 -1
  52. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +26 -1
  53. package/packages/dd-trace/src/ci-visibility/telemetry.js +130 -0
  54. package/packages/dd-trace/src/config.js +110 -56
  55. package/packages/dd-trace/src/datastreams/processor.js +107 -12
  56. package/packages/dd-trace/src/encode/agentless-ci-visibility.js +14 -1
  57. package/packages/dd-trace/src/encode/coverage-ci-visibility.js +14 -0
  58. package/packages/dd-trace/src/exporters/common/agent-info-exporter.js +4 -0
  59. package/packages/dd-trace/src/exporters/common/form-data.js +4 -0
  60. package/packages/dd-trace/src/opentracing/span.js +2 -0
  61. package/packages/dd-trace/src/opentracing/tracer.js +2 -2
  62. package/packages/dd-trace/src/plugins/ci_plugin.js +44 -8
  63. package/packages/dd-trace/src/plugins/index.js +5 -0
  64. package/packages/dd-trace/src/plugins/util/exec.js +23 -2
  65. package/packages/dd-trace/src/plugins/util/git.js +94 -19
  66. package/packages/dd-trace/src/plugins/util/user-provided-git.js +3 -2
  67. package/packages/dd-trace/src/profiling/exporters/agent.js +1 -0
  68. package/packages/dd-trace/src/profiling/profiler.js +7 -6
  69. package/packages/dd-trace/src/profiling/profilers/events.js +19 -51
  70. package/packages/dd-trace/src/profiling/profilers/shared.js +34 -4
  71. package/packages/dd-trace/src/profiling/profilers/space.js +2 -1
  72. package/packages/dd-trace/src/profiling/profilers/wall.js +17 -12
  73. package/packages/dd-trace/src/proxy.js +14 -0
  74. package/packages/dd-trace/src/spanleak.js +98 -0
  75. package/packages/dd-trace/src/telemetry/index.js +43 -5
  76. package/packages/dd-trace/src/tracer.js +4 -0
@@ -20,6 +20,14 @@ const {
20
20
  const Plugin = require('./plugin')
21
21
  const { COMPONENT } = require('../constants')
22
22
  const log = require('../log')
23
+ const {
24
+ incrementCountMetric,
25
+ distributionMetric,
26
+ TELEMETRY_EVENT_CREATED,
27
+ TELEMETRY_ITR_SKIPPED
28
+ } = require('../ci-visibility/telemetry')
29
+ const { CI_PROVIDER_NAME, GIT_REPOSITORY_URL, GIT_COMMIT_SHA, GIT_BRANCH } = require('./util/tags')
30
+ const { OS_VERSION, OS_PLATFORM, OS_ARCHITECTURE, RUNTIME_NAME, RUNTIME_VERSION } = require('./util/env')
23
31
 
24
32
  module.exports = class CiPlugin extends Plugin {
25
33
  constructor (...args) {
@@ -71,6 +79,7 @@ module.exports = class CiPlugin extends Plugin {
71
79
  ...testSessionSpanMetadata
72
80
  }
73
81
  })
82
+ this.telemetry.ciVisEvent(TELEMETRY_EVENT_CREATED, 'session')
74
83
  this.testModuleSpan = this.tracer.startSpan(`${this.constructor.id}.test_module`, {
75
84
  childOf: this.testSessionSpan,
76
85
  tags: {
@@ -79,6 +88,7 @@ module.exports = class CiPlugin extends Plugin {
79
88
  ...testModuleSpanMetadata
80
89
  }
81
90
  })
91
+ this.telemetry.ciVisEvent(TELEMETRY_EVENT_CREATED, 'module')
82
92
  })
83
93
 
84
94
  this.addSub(`ci:${this.constructor.id}:itr:skipped-suites`, ({ skippedSuites, frameworkVersion }) => {
@@ -97,25 +107,49 @@ module.exports = class CiPlugin extends Plugin {
97
107
  }
98
108
  }).finish()
99
109
  })
110
+ this.telemetry.count(TELEMETRY_ITR_SKIPPED, { testLevel: 'suite' }, skippedSuites.length)
100
111
  })
101
112
  }
102
113
 
114
+ get telemetry () {
115
+ const testFramework = this.constructor.id
116
+ return {
117
+ ciVisEvent: function (name, testLevel, tags = {}) {
118
+ incrementCountMetric(name, {
119
+ testLevel,
120
+ testFramework,
121
+ isUnsupportedCIProvider: this.isUnsupportedCIProvider,
122
+ ...tags
123
+ })
124
+ },
125
+ count: function (name, tags, value = 1) {
126
+ incrementCountMetric(name, tags, value)
127
+ },
128
+ distribution: function (name, tags, measure) {
129
+ distributionMetric(name, tags, measure)
130
+ }
131
+ }
132
+ }
133
+
103
134
  configure (config) {
104
135
  super.configure(config)
105
136
  this.testEnvironmentMetadata = getTestEnvironmentMetadata(this.constructor.id, this.config)
106
137
  this.codeOwnersEntries = getCodeOwnersFileEntries()
107
138
 
108
139
  const {
109
- 'git.repository_url': repositoryUrl,
110
- 'git.commit.sha': sha,
111
- 'os.version': osVersion,
112
- 'os.platform': osPlatform,
113
- 'os.architecture': osArchitecture,
114
- 'runtime.name': runtimeName,
115
- 'runtime.version': runtimeVersion,
116
- 'git.branch': branch
140
+ [GIT_REPOSITORY_URL]: repositoryUrl,
141
+ [GIT_COMMIT_SHA]: sha,
142
+ [OS_VERSION]: osVersion,
143
+ [OS_PLATFORM]: osPlatform,
144
+ [OS_ARCHITECTURE]: osArchitecture,
145
+ [RUNTIME_NAME]: runtimeName,
146
+ [RUNTIME_VERSION]: runtimeVersion,
147
+ [GIT_BRANCH]: branch,
148
+ [CI_PROVIDER_NAME]: ciProviderName
117
149
  } = this.testEnvironmentMetadata
118
150
 
151
+ this.isUnsupportedCIProvider = !ciProviderName
152
+
119
153
  this.testConfiguration = {
120
154
  repositoryUrl,
121
155
  sha,
@@ -170,6 +204,8 @@ module.exports = class CiPlugin extends Plugin {
170
204
  }
171
205
  }
172
206
 
207
+ this.telemetry.ciVisEvent(TELEMETRY_EVENT_CREATED, 'test', { hasCodeOwners: !!codeOwners })
208
+
173
209
  const testSpan = this.tracer
174
210
  .startSpan(`${this.constructor.id}.test`, {
175
211
  childOf,
@@ -59,6 +59,11 @@ module.exports = {
59
59
  get 'mysql2' () { return require('../../../datadog-plugin-mysql2/src') },
60
60
  get 'net' () { return require('../../../datadog-plugin-net/src') },
61
61
  get 'next' () { return require('../../../datadog-plugin-next/src') },
62
+ get 'node:dns' () { return require('../../../datadog-plugin-dns/src') },
63
+ get 'node:http' () { return require('../../../datadog-plugin-http/src') },
64
+ get 'node:http2' () { return require('../../../datadog-plugin-http2/src') },
65
+ get 'node:https' () { return require('../../../datadog-plugin-http/src') },
66
+ get 'node:net' () { return require('../../../datadog-plugin-net/src') },
62
67
  get 'oracledb' () { return require('../../../datadog-plugin-oracledb/src') },
63
68
  get 'openai' () { return require('../../../datadog-plugin-openai/src') },
64
69
  get 'paperplane' () { return require('../../../datadog-plugin-paperplane/src') },
@@ -1,10 +1,31 @@
1
1
  const cp = require('child_process')
2
2
  const log = require('../../log')
3
+ const { distributionMetric, incrementCountMetric } = require('../../ci-visibility/telemetry')
3
4
 
4
- const sanitizedExec = (cmd, flags, options = { stdio: 'pipe' }) => {
5
+ const sanitizedExec = (
6
+ cmd,
7
+ flags,
8
+ operationMetric,
9
+ durationMetric,
10
+ errorMetric
11
+ ) => {
12
+ let startTime
13
+ if (operationMetric) {
14
+ incrementCountMetric(operationMetric.name, operationMetric.tags)
15
+ }
16
+ if (durationMetric) {
17
+ startTime = Date.now()
18
+ }
5
19
  try {
6
- return cp.execFileSync(cmd, flags, options).toString().replace(/(\r\n|\n|\r)/gm, '')
20
+ const result = cp.execFileSync(cmd, flags, { stdio: 'pipe' }).toString().replace(/(\r\n|\n|\r)/gm, '')
21
+ if (durationMetric) {
22
+ distributionMetric(durationMetric.name, durationMetric.tags, Date.now() - startTime)
23
+ }
24
+ return result
7
25
  } catch (e) {
26
+ if (errorMetric) {
27
+ incrementCountMetric(errorMetric.name, { ...errorMetric.tags, exitCode: e.status })
28
+ }
8
29
  log.error(e)
9
30
  return ''
10
31
  }
@@ -1,10 +1,9 @@
1
- const { execFileSync } = require('child_process')
1
+ const cp = require('child_process')
2
2
  const os = require('os')
3
3
  const path = require('path')
4
4
  const fs = require('fs')
5
5
 
6
6
  const log = require('../../log')
7
- const { sanitizedExec } = require('./exec')
8
7
  const {
9
8
  GIT_COMMIT_SHA,
10
9
  GIT_BRANCH,
@@ -19,10 +18,46 @@ const {
19
18
  GIT_COMMIT_AUTHOR_NAME,
20
19
  CI_WORKSPACE_PATH
21
20
  } = require('./tags')
21
+ const {
22
+ incrementCountMetric,
23
+ distributionMetric,
24
+ TELEMETRY_GIT_COMMAND,
25
+ TELEMETRY_GIT_COMMAND_MS,
26
+ TELEMETRY_GIT_COMMAND_ERRORS
27
+ } = require('../../ci-visibility/telemetry')
22
28
  const { filterSensitiveInfoFromRepository } = require('./url')
23
29
 
24
30
  const GIT_REV_LIST_MAX_BUFFER = 8 * 1024 * 1024 // 8MB
25
31
 
32
+ function sanitizedExec (
33
+ cmd,
34
+ flags,
35
+ operationMetric,
36
+ durationMetric,
37
+ errorMetric
38
+ ) {
39
+ let startTime
40
+ if (operationMetric) {
41
+ incrementCountMetric(operationMetric.name, operationMetric.tags)
42
+ }
43
+ if (durationMetric) {
44
+ startTime = Date.now()
45
+ }
46
+ try {
47
+ const result = cp.execFileSync(cmd, flags, { stdio: 'pipe' }).toString().replace(/(\r\n|\n|\r)/gm, '')
48
+ if (durationMetric) {
49
+ distributionMetric(durationMetric.name, durationMetric.tags, Date.now() - startTime)
50
+ }
51
+ return result
52
+ } catch (e) {
53
+ if (errorMetric) {
54
+ incrementCountMetric(errorMetric.name, { ...errorMetric.tags, exitCode: e.status })
55
+ }
56
+ log.error(e)
57
+ return ''
58
+ }
59
+ }
60
+
26
61
  function isDirectory (path) {
27
62
  try {
28
63
  const stats = fs.statSync(path)
@@ -33,7 +68,13 @@ function isDirectory (path) {
33
68
  }
34
69
 
35
70
  function isShallowRepository () {
36
- return sanitizedExec('git', ['rev-parse', '--is-shallow-repository']) === 'true'
71
+ return sanitizedExec(
72
+ 'git',
73
+ ['rev-parse', '--is-shallow-repository'],
74
+ { name: TELEMETRY_GIT_COMMAND, tags: { command: 'check_shallow' } },
75
+ { name: TELEMETRY_GIT_COMMAND_MS, tags: { command: 'check_shallow' } },
76
+ { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'check_shallow' } }
77
+ ) === 'true'
37
78
  }
38
79
 
39
80
  function getGitVersion () {
@@ -72,50 +113,76 @@ function unshallowRepository () {
72
113
  defaultRemoteName
73
114
  ]
74
115
 
116
+ incrementCountMetric(TELEMETRY_GIT_COMMAND, { command: 'unshallow' })
117
+ const start = Date.now()
75
118
  try {
76
- execFileSync('git', [
119
+ cp.execFileSync('git', [
77
120
  ...baseGitOptions,
78
121
  revParseHead
79
122
  ], { stdio: 'pipe' })
80
- } catch (e) {
123
+ } catch (err) {
81
124
  // If the local HEAD is a commit that has not been pushed to the remote, the above command will fail.
82
- log.error(e)
125
+ log.error(err)
126
+ incrementCountMetric(TELEMETRY_GIT_COMMAND_ERRORS, { command: 'unshallow', exitCode: err.status })
83
127
  const upstreamRemote = sanitizedExec('git', ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'])
84
128
  try {
85
- execFileSync('git', [
129
+ cp.execFileSync('git', [
86
130
  ...baseGitOptions,
87
131
  upstreamRemote
88
132
  ], { stdio: 'pipe' })
89
- } catch (e) {
133
+ } catch (err) {
90
134
  // If the CI is working on a detached HEAD or branch tracking hasn’t been set up, the above command will fail.
91
- log.error(e)
135
+ log.error(err)
136
+ incrementCountMetric(TELEMETRY_GIT_COMMAND_ERRORS, { command: 'unshallow', exitCode: err.status })
92
137
  // We use sanitizedExec here because if this last option fails, we'll give up.
93
- sanitizedExec('git', baseGitOptions)
138
+ sanitizedExec(
139
+ 'git',
140
+ baseGitOptions,
141
+ null,
142
+ null,
143
+ { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'unshallow' } } // we log the error in sanitizedExec
144
+ )
94
145
  }
95
146
  }
147
+ distributionMetric(TELEMETRY_GIT_COMMAND_MS, { command: 'unshallow' }, Date.now() - start)
96
148
  }
97
149
 
98
150
  function getRepositoryUrl () {
99
- return sanitizedExec('git', ['config', '--get', 'remote.origin.url'])
151
+ return sanitizedExec(
152
+ 'git',
153
+ ['config', '--get', 'remote.origin.url'],
154
+ { name: TELEMETRY_GIT_COMMAND, tags: { command: 'get_repository' } },
155
+ { name: TELEMETRY_GIT_COMMAND_MS, tags: { command: 'get_repository' } },
156
+ { name: TELEMETRY_GIT_COMMAND_ERRORS, tags: { command: 'get_repository' } }
157
+ )
100
158
  }
101
159
 
102
160
  function getLatestCommits () {
161
+ incrementCountMetric(TELEMETRY_GIT_COMMAND, { command: 'get_local_commits' })
162
+ const startTime = Date.now()
103
163
  try {
104
- return execFileSync('git', ['log', '--format=%H', '-n 1000', '--since="1 month ago"'], { stdio: 'pipe' })
164
+ const result = cp.execFileSync('git', ['log', '--format=%H', '-n 1000', '--since="1 month ago"'], { stdio: 'pipe' })
105
165
  .toString()
106
166
  .split('\n')
107
167
  .filter(commit => commit)
168
+ distributionMetric(TELEMETRY_GIT_COMMAND_MS, { command: 'get_local_commits' }, Date.now() - startTime)
169
+ return result
108
170
  } catch (err) {
109
171
  log.error(`Get latest commits failed: ${err.message}`)
172
+ incrementCountMetric(TELEMETRY_GIT_COMMAND_ERRORS, { command: 'get_local_commits', errorType: err.status })
110
173
  return []
111
174
  }
112
175
  }
113
176
 
114
177
  function getCommitsRevList (commitsToExclude, commitsToInclude) {
178
+ let result = []
179
+
115
180
  const commitsToExcludeString = commitsToExclude.map(commit => `^${commit}`)
116
181
 
182
+ incrementCountMetric(TELEMETRY_GIT_COMMAND, { command: 'get_objects' })
183
+ const startTime = Date.now()
117
184
  try {
118
- return execFileSync(
185
+ result = cp.execFileSync(
119
186
  'git',
120
187
  [
121
188
  'rev-list',
@@ -132,11 +199,14 @@ function getCommitsRevList (commitsToExclude, commitsToInclude) {
132
199
  .filter(commit => commit)
133
200
  } catch (err) {
134
201
  log.error(`Get commits to upload failed: ${err.message}`)
135
- return []
202
+ incrementCountMetric(TELEMETRY_GIT_COMMAND_ERRORS, { command: 'get_objects', errorType: err.status })
136
203
  }
204
+ distributionMetric(TELEMETRY_GIT_COMMAND_MS, { command: 'get_objects' }, Date.now() - startTime)
205
+ return result
137
206
  }
138
207
 
139
208
  function generatePackFilesForCommits (commitsToUpload) {
209
+ let result = []
140
210
  const tmpFolder = os.tmpdir()
141
211
 
142
212
  if (!isDirectory(tmpFolder)) {
@@ -148,10 +218,12 @@ function generatePackFilesForCommits (commitsToUpload) {
148
218
  const temporaryPath = path.join(tmpFolder, randomPrefix)
149
219
  const cwdPath = path.join(process.cwd(), randomPrefix)
150
220
 
221
+ incrementCountMetric(TELEMETRY_GIT_COMMAND, { command: 'pack_objects' })
222
+ const startTime = Date.now()
151
223
  // Generates pack files to upload and
152
224
  // returns the ordered list of packfiles' paths
153
225
  function execGitPackObjects (targetPath) {
154
- return execFileSync(
226
+ return cp.execFileSync(
155
227
  'git',
156
228
  [
157
229
  'pack-objects',
@@ -164,9 +236,10 @@ function generatePackFilesForCommits (commitsToUpload) {
164
236
  }
165
237
 
166
238
  try {
167
- return execGitPackObjects(temporaryPath)
239
+ result = execGitPackObjects(temporaryPath)
168
240
  } catch (err) {
169
241
  log.error(err)
242
+ incrementCountMetric(TELEMETRY_GIT_COMMAND_ERRORS, { command: 'pack_objects', errorType: err.status })
170
243
  /**
171
244
  * The generation of pack files in the temporary folder (from `os.tmpdir()`)
172
245
  * sometimes fails in certain CI setups with the error message
@@ -180,13 +253,15 @@ function generatePackFilesForCommits (commitsToUpload) {
180
253
  * TODO: fix issue and remove workaround.
181
254
  */
182
255
  try {
183
- return execGitPackObjects(cwdPath)
256
+ result = execGitPackObjects(cwdPath)
184
257
  } catch (err) {
185
258
  log.error(err)
259
+ incrementCountMetric(TELEMETRY_GIT_COMMAND_ERRORS, { command: 'pack_objects', errorType: err.status })
186
260
  }
187
-
188
- return []
189
261
  }
262
+ distributionMetric(TELEMETRY_GIT_COMMAND_MS, { command: 'pack_objects' }, Date.now() - startTime)
263
+
264
+ return result
190
265
  }
191
266
 
192
267
  // If there is ciMetadata, it takes precedence.
@@ -27,10 +27,11 @@ function removeEmptyValues (tags) {
27
27
  }, {})
28
28
  }
29
29
 
30
- // The regex is extracted from
30
+ // The regex is inspired by
31
31
  // https://github.com/jonschlinkert/is-git-url/blob/396965ffabf2f46656c8af4c47bef1d69f09292e/index.js#L9C15-L9C87
32
+ // The `.git` suffix is optional in this version
32
33
  function validateGitRepositoryUrl (repoUrl) {
33
- return /(?:git|ssh|https?|git@[-\w.]+):(\/\/)?(.*?)(\.git)(\/?|#[-\d\w._]+?)$/.test(repoUrl)
34
+ return /(?:git|ssh|https?|git@[-\w.]+):(\/\/)?(.*?)(\/?|#[-\d\w._]+?)$/.test(repoUrl)
34
35
  }
35
36
 
36
37
  function validateGitCommitSha (gitCommitSha) {
@@ -75,6 +75,7 @@ class AgentExporter {
75
75
  ['tags[]', 'language:javascript'],
76
76
  ['tags[]', 'runtime:nodejs'],
77
77
  ['tags[]', `runtime_version:${process.version}`],
78
+ ['tags[]', `process_id:${process.pid}`],
78
79
  ['tags[]', `profiler_version:${version}`],
79
80
  ['tags[]', 'format:pprof'],
80
81
  ...Object.entries(tags).map(([key, value]) => ['tags[]', `${key}:${value}`])
@@ -61,6 +61,7 @@ class Profiler extends EventEmitter {
61
61
  }
62
62
 
63
63
  try {
64
+ const start = new Date()
64
65
  for (const profiler of config.profilers) {
65
66
  // TODO: move this out of Profiler when restoring sourcemap support
66
67
  profiler.start({
@@ -70,7 +71,7 @@ class Profiler extends EventEmitter {
70
71
  this._logger.debug(`Started ${profiler.type} profiler`)
71
72
  }
72
73
 
73
- this._capture(this._timeoutInterval)
74
+ this._capture(this._timeoutInterval, start)
74
75
  return true
75
76
  } catch (e) {
76
77
  this._logger.error(e)
@@ -116,9 +117,9 @@ class Profiler extends EventEmitter {
116
117
  return this
117
118
  }
118
119
 
119
- _capture (timeout) {
120
+ _capture (timeout, start) {
120
121
  if (!this._enabled) return
121
- this._lastStart = new Date()
122
+ this._lastStart = start
122
123
  if (!this._timer || timeout !== this._timeoutInterval) {
123
124
  this._timer = setTimeout(() => this._collect(snapshotKinds.PERIODIC), timeout)
124
125
  this._timer.unref()
@@ -138,7 +139,7 @@ class Profiler extends EventEmitter {
138
139
  try {
139
140
  // collect profiles synchronously so that profilers can be safely stopped asynchronously
140
141
  for (const profiler of this._config.profilers) {
141
- const profile = profiler.profile()
142
+ const profile = profiler.profile(start, end)
142
143
  if (!profile) continue
143
144
  profiles.push({ profiler, profile })
144
145
  }
@@ -154,7 +155,7 @@ class Profiler extends EventEmitter {
154
155
  })
155
156
  }
156
157
 
157
- this._capture(this._timeoutInterval)
158
+ this._capture(this._timeoutInterval, end)
158
159
  await this._submit(encodedProfiles, start, end, snapshotKind)
159
160
  this._logger.debug('Submitted profiles')
160
161
  } catch (err) {
@@ -201,7 +202,7 @@ class ServerlessProfiler extends Profiler {
201
202
  await super._collect(snapshotKind)
202
203
  } else {
203
204
  this._profiledIntervals += 1
204
- this._capture(this._timeoutInterval)
205
+ this._capture(this._timeoutInterval, new Date())
205
206
  // Don't submit profile until 65 (flushAfterIntervals) intervals have elapsed
206
207
  }
207
208
  }
@@ -1,5 +1,5 @@
1
- const { performance, constants, PerformanceObserver } = require('node:perf_hooks')
2
- const { END_TIMESTAMP, THREAD_NAME, threadNamePrefix } = require('./shared')
1
+ const { performance, constants, PerformanceObserver } = require('perf_hooks')
2
+ const { END_TIMESTAMP_LABEL } = require('./shared')
3
3
  const semver = require('semver')
4
4
  const { Function, Label, Line, Location, Profile, Sample, StringTable, ValueType } = require('pprof-format')
5
5
  const pprof = require('@datadog/pprof/')
@@ -74,39 +74,6 @@ class GCDecorator {
74
74
  }
75
75
  }
76
76
 
77
- // Maintains "lanes" (or virtual threads) to avoid overlaps in events. The
78
- // decorator starts out with no lanes, and dynamically adds them as needed.
79
- // Every event is put in the first lane where it doesn't overlap with the last
80
- // event in that lane. If there's no lane without overlaps, a new lane is
81
- // created.
82
- class Lanes {
83
- constructor (stringTable, name) {
84
- this.stringTable = stringTable
85
- this.name = name
86
- this.lanes = []
87
- }
88
-
89
- getLabelFor (item) {
90
- const startTime = item.startTime
91
- const endTime = startTime + item.duration
92
-
93
- // Biases towards populating earlier lanes, but at least it's simple
94
- for (const lane of this.lanes) {
95
- if (lane.endTime <= startTime) {
96
- lane.endTime = endTime
97
- return lane.label
98
- }
99
- }
100
- const label = labelFromStrStr(
101
- this.stringTable,
102
- THREAD_NAME,
103
- `${this.name}-${this.lanes.length}`
104
- )
105
- this.lanes.push({ endTime, label })
106
- return label
107
- }
108
- }
109
-
110
77
  class DNSDecorator {
111
78
  constructor (stringTable) {
112
79
  this.stringTable = stringTable
@@ -114,7 +81,6 @@ class DNSDecorator {
114
81
  this.hostLabelKey = stringTable.dedup('host')
115
82
  this.addressLabelKey = stringTable.dedup('address')
116
83
  this.portLabelKey = stringTable.dedup('port')
117
- this.lanes = new Lanes(stringTable, `${threadNamePrefix} DNS`)
118
84
  }
119
85
 
120
86
  decorateSample (sampleInput, item) {
@@ -142,7 +108,6 @@ class DNSDecorator {
142
108
  addLabel(this.hostLabelKey, detail.host)
143
109
  }
144
110
  }
145
- labels.push(this.lanes.getLabelFor(item))
146
111
  }
147
112
  }
148
113
 
@@ -152,7 +117,6 @@ class NetDecorator {
152
117
  this.operationNameLabelKey = stringTable.dedup('operation')
153
118
  this.hostLabelKey = stringTable.dedup('host')
154
119
  this.portLabelKey = stringTable.dedup('port')
155
- this.lanes = new Lanes(stringTable, `${threadNamePrefix} Net`)
156
120
  }
157
121
 
158
122
  decorateSample (sampleInput, item) {
@@ -165,10 +129,9 @@ class NetDecorator {
165
129
  addLabel(this.operationNameLabelKey, op)
166
130
  if (op === 'connect') {
167
131
  const detail = item.detail
168
- addLabel(this.stringTable, this.hostLabelKey, detail.host)
132
+ addLabel(this.hostLabelKey, detail.host)
169
133
  labels.push(new Label({ key: this.portLabelKey, num: detail.port }))
170
134
  }
171
- labels.push(this.lanes.getLabelFor(item))
172
135
  }
173
136
  }
174
137
 
@@ -211,7 +174,7 @@ class EventsProfiler {
211
174
  }
212
175
  }
213
176
 
214
- profile () {
177
+ profile (startDate, endDate) {
215
178
  if (this.entries.length === 0) {
216
179
  // No events in the period; don't produce a profile
217
180
  return null
@@ -239,12 +202,11 @@ class EventsProfiler {
239
202
  decorator.eventTypeLabel = labelFromStrStr(stringTable, 'event', eventType)
240
203
  decorators[eventType] = decorator
241
204
  }
242
- const timestampLabelKey = stringTable.dedup(END_TIMESTAMP)
205
+ const timestampLabelKey = stringTable.dedup(END_TIMESTAMP_LABEL)
243
206
 
244
- let durationFrom = Number.POSITIVE_INFINITY
245
- let durationTo = 0
246
207
  const dateOffset = BigInt(Math.round(performance.timeOrigin * MS_TO_NS))
247
-
208
+ const lateEntries = []
209
+ const perfEndDate = endDate.getTime() - performance.timeOrigin
248
210
  const samples = this.entries.map((item) => {
249
211
  const decorator = decorators[item.entryType]
250
212
  if (!decorator) {
@@ -253,9 +215,15 @@ class EventsProfiler {
253
215
  return null
254
216
  }
255
217
  const { startTime, duration } = item
218
+ if (startTime >= perfEndDate) {
219
+ // An event past the current recording end date; save it for the next
220
+ // profile. Not supposed to happen as long as there's no async activity
221
+ // between capture of the endDate value in profiler.js _collect() and
222
+ // here, but better be safe than sorry.
223
+ lateEntries.push(item)
224
+ return null
225
+ }
256
226
  const endTime = startTime + duration
257
- if (durationFrom > startTime) durationFrom = startTime
258
- if (durationTo < endTime) durationTo = endTime
259
227
  const sampleInput = {
260
228
  value: [Math.round(duration * MS_TO_NS)],
261
229
  locationId,
@@ -268,7 +236,7 @@ class EventsProfiler {
268
236
  return new Sample(sampleInput)
269
237
  }).filter(v => v)
270
238
 
271
- this.entries = []
239
+ this.entries = lateEntries
272
240
 
273
241
  const timeValueType = new ValueType({
274
242
  type: stringTable.dedup(pprofValueType),
@@ -277,10 +245,10 @@ class EventsProfiler {
277
245
 
278
246
  return new Profile({
279
247
  sampleType: [timeValueType],
280
- timeNanos: dateOffset + BigInt(Math.round(durationFrom * MS_TO_NS)),
248
+ timeNanos: endDate.getTime() * MS_TO_NS,
281
249
  periodType: timeValueType,
282
- period: this._flushIntervalNanos,
283
- durationNanos: Math.max(0, Math.round((durationTo - durationFrom) * MS_TO_NS)),
250
+ period: 1,
251
+ durationNanos: (endDate.getTime() - startDate.getTime()) * MS_TO_NS,
284
252
  sample: samples,
285
253
  location: locations,
286
254
  function: functions,
@@ -1,9 +1,39 @@
1
1
  'use strict'
2
2
 
3
- const { isMainThread, threadId } = require('node:worker_threads')
3
+ const { isMainThread, threadId } = require('worker_threads')
4
+
5
+ const END_TIMESTAMP_LABEL = 'end_timestamp_ns'
6
+ const THREAD_NAME_LABEL = 'thread name'
7
+ const OS_THREAD_ID_LABEL = 'os thread id'
8
+ const THREAD_ID_LABEL = 'thread id'
9
+ const threadNamePrefix = isMainThread ? 'Main' : `Worker #${threadId}`
10
+ const eventLoopThreadName = `${threadNamePrefix} Event Loop`
11
+
12
+ function getThreadLabels () {
13
+ const pprof = require('@datadog/pprof')
14
+ const nativeThreadId = pprof.getNativeThreadId()
15
+ return {
16
+ [THREAD_NAME_LABEL]: eventLoopThreadName,
17
+ [THREAD_ID_LABEL]: `${threadId}`,
18
+ [OS_THREAD_ID_LABEL]: `${nativeThreadId}`
19
+ }
20
+ }
21
+
22
+ function cacheThreadLabels () {
23
+ let labels
24
+ return () => {
25
+ if (!labels) {
26
+ labels = getThreadLabels()
27
+ }
28
+ return labels
29
+ }
30
+ }
4
31
 
5
32
  module.exports = {
6
- END_TIMESTAMP: 'end_timestamp_ns',
7
- THREAD_NAME: 'thread name',
8
- threadNamePrefix: isMainThread ? 'Main' : `Worker #${threadId}`
33
+ END_TIMESTAMP_LABEL,
34
+ THREAD_NAME_LABEL,
35
+ THREAD_ID_LABEL,
36
+ threadNamePrefix,
37
+ eventLoopThreadName,
38
+ getThreadLabels: cacheThreadLabels()
9
39
  }
@@ -1,6 +1,7 @@
1
1
  'use strict'
2
2
 
3
3
  const { oomExportStrategies } = require('../constants')
4
+ const { getThreadLabels } = require('./shared')
4
5
 
5
6
  function strategiesToCallbackMode (strategies, callbackMode) {
6
7
  return strategies.includes(oomExportStrategies.ASYNC_CALLBACK) ? callbackMode.Async : 0
@@ -33,7 +34,7 @@ class NativeSpaceProfiler {
33
34
  }
34
35
 
35
36
  profile () {
36
- return this._pprof.heap.profile(undefined, this._mapper)
37
+ return this._pprof.heap.profile(undefined, this._mapper, getThreadLabels)
37
38
  }
38
39
 
39
40
  encode (profile) {