dd-trace 5.0.0-pre-17fa54d → 5.0.0-pre-4d7a058

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.
@@ -28,6 +28,7 @@ require,msgpack-lite,MIT,Copyright 2015 Yusuke Kawasaki
28
28
  require,node-abort-controller,MIT,Copyright (c) 2019 Steve Faulkner
29
29
  require,opentracing,MIT,Copyright 2016 Resonance Labs Inc
30
30
  require,path-to-regexp,MIT,Copyright 2014 Blake Embrey
31
+ require,pprof-format,MIT,Copyright 2022 Stephen Belanger
31
32
  require,protobufjs,BSD-3-Clause,Copyright 2016 Daniel Wirtz
32
33
  require,retry,MIT,Copyright 2011 Tim Koschützki Felix Geisendörfer
33
34
  require,semver,ISC,Copyright Isaac Z. Schlueter and Contributors
@@ -62,7 +63,6 @@ dev,mocha,MIT,Copyright 2011-2018 JS Foundation and contributors https://js.foun
62
63
  dev,multer,MIT,Copyright 2014 Hage Yaapa
63
64
  dev,nock,MIT,Copyright 2017 Pedro Teixeira and other contributors
64
65
  dev,nyc,ISC,Copyright 2015 Contributors
65
- dev,pprof-format,MIT,Copyright 2022 Stephen Belanger
66
66
  dev,proxyquire,MIT,Copyright 2013 Thorsten Lorenz
67
67
  dev,rimraf,ISC,Copyright Isaac Z. Schlueter and Contributors
68
68
  dev,sinon,BSD-3-Clause,Copyright 2010-2017 Christian Johansen
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dd-trace",
3
- "version": "5.0.0-pre-17fa54d",
3
+ "version": "5.0.0-pre-4d7a058",
4
4
  "description": "Datadog APM tracing client for JavaScript",
5
5
  "main": "index.js",
6
6
  "typings": "index.d.ts",
@@ -97,6 +97,7 @@
97
97
  "node-abort-controller": "^3.1.1",
98
98
  "opentracing": ">=0.12.1",
99
99
  "path-to-regexp": "^0.1.2",
100
+ "pprof-format": "^2.0.7",
100
101
  "protobufjs": "^7.2.4",
101
102
  "retry": "^0.13.1",
102
103
  "semver": "^7.5.4"
@@ -133,7 +134,6 @@
133
134
  "multer": "^1.4.5-lts.1",
134
135
  "nock": "^11.3.3",
135
136
  "nyc": "^15.1.0",
136
- "pprof-format": "^2.0.7",
137
137
  "proxyquire": "^1.8.0",
138
138
  "rimraf": "^3.0.0",
139
139
  "sinon": "^15.2.0",
@@ -3,6 +3,7 @@
3
3
  const Limiter = require('../rate_limiter')
4
4
  const { storage } = require('../../../datadog-core')
5
5
  const web = require('../plugins/util/web')
6
+ const { ipHeaderList } = require('../plugins/util/ip_extractor')
6
7
  const {
7
8
  incrementWafInitMetric,
8
9
  updateWafRequestsMetricTags,
@@ -13,54 +14,49 @@ const {
13
14
  // default limiter, configurable with setRateLimit()
14
15
  let limiter = new Limiter(100)
15
16
 
16
- // TODO: use precomputed maps instead
17
- const REQUEST_HEADERS_PASSLIST = [
18
- 'accept',
19
- 'accept-encoding',
20
- 'accept-language',
17
+ const metricsQueue = new Map()
18
+
19
+ const contentHeaderList = [
21
20
  'content-encoding',
22
21
  'content-language',
23
22
  'content-length',
24
- 'content-type',
25
- 'forwarded',
26
- 'forwarded-for',
23
+ 'content-type'
24
+ ]
25
+
26
+ const REQUEST_HEADERS_MAP = mapHeaderAndTags([
27
+ 'accept',
28
+ 'accept-encoding',
29
+ 'accept-language',
27
30
  'host',
28
- 'true-client-ip',
29
31
  'user-agent',
32
+ 'forwarded',
30
33
  'via',
31
- 'x-client-ip',
32
- 'x-cluster-client-ip',
33
- 'x-forwarded',
34
- 'x-forwarded-for',
35
- 'x-real-ip'
36
- ]
37
34
 
38
- const RESPONSE_HEADERS_PASSLIST = [
39
- 'content-encoding',
40
- 'content-language',
41
- 'content-length',
42
- 'content-type'
43
- ]
35
+ ...ipHeaderList,
36
+ ...contentHeaderList
37
+ ], 'http.request.headers.')
44
38
 
45
- const metricsQueue = new Map()
39
+ const RESPONSE_HEADERS_MAP = mapHeaderAndTags(contentHeaderList, 'http.response.headers.')
46
40
 
47
- function filterHeaders (headers, passlist, prefix) {
41
+ function mapHeaderAndTags (headerList, tagPrefix) {
42
+ return new Map(headerList.map(headerName => [headerName, `${tagPrefix}${formatHeaderName(headerName)}`]))
43
+ }
44
+
45
+ function filterHeaders (headers, map) {
48
46
  const result = {}
49
47
 
50
48
  if (!headers) return result
51
49
 
52
- for (let i = 0; i < passlist.length; ++i) {
53
- const headerName = passlist[i]
54
-
55
- if (headers[headerName]) {
56
- result[`${prefix}${formatHeaderName(headerName)}`] = '' + headers[headerName]
50
+ for (const [headerName, tagName] of map) {
51
+ const headerValue = headers[headerName]
52
+ if (headerValue) {
53
+ result[tagName] = '' + headerValue
57
54
  }
58
55
  }
59
56
 
60
57
  return result
61
58
  }
62
59
 
63
- // TODO: this can be precomputed at start time
64
60
  function formatHeaderName (name) {
65
61
  return name
66
62
  .trim()
@@ -86,7 +82,7 @@ function reportWafInit (wafVersion, rulesVersion, diagnosticsRules = {}) {
86
82
  function reportMetrics (metrics) {
87
83
  // TODO: metrics should be incremental, there already is an RFC to report metrics
88
84
  const store = storage.getStore()
89
- const rootSpan = store && store.req && web.root(store.req)
85
+ const rootSpan = store?.req && web.root(store.req)
90
86
  if (!rootSpan) return
91
87
 
92
88
  if (metrics.duration) {
@@ -106,13 +102,13 @@ function reportMetrics (metrics) {
106
102
 
107
103
  function reportAttack (attackData) {
108
104
  const store = storage.getStore()
109
- const req = store && store.req
105
+ const req = store?.req
110
106
  const rootSpan = web.root(req)
111
107
  if (!rootSpan) return
112
108
 
113
109
  const currentTags = rootSpan.context()._tags
114
110
 
115
- const newTags = filterHeaders(req.headers, REQUEST_HEADERS_PASSLIST, 'http.request.headers.')
111
+ const newTags = filterHeaders(req.headers, REQUEST_HEADERS_MAP)
116
112
 
117
113
  newTags['appsec.event'] = 'true'
118
114
 
@@ -158,7 +154,7 @@ function finishRequest (req, res) {
158
154
 
159
155
  if (!rootSpan.context()._tags['appsec.event']) return
160
156
 
161
- const newTags = filterHeaders(res.getHeaders(), RESPONSE_HEADERS_PASSLIST, 'http.response.headers.')
157
+ const newTags = filterHeaders(res.getHeaders(), RESPONSE_HEADERS_MAP)
162
158
 
163
159
  if (req.route && typeof req.route.path === 'string') {
164
160
  newTags['http.endpoint'] = req.route.path
@@ -180,5 +176,6 @@ module.exports = {
180
176
  reportAttack,
181
177
  reportWafUpdate: incrementWafUpdatesMetric,
182
178
  finishRequest,
183
- setRateLimit
179
+ setRateLimit,
180
+ mapHeaderAndTags
184
181
  }
@@ -12,6 +12,7 @@ const runtimeMetrics = require('../runtime_metrics')
12
12
  const log = require('../log')
13
13
  const { storage } = require('../../../datadog-core')
14
14
  const telemetryMetrics = require('../telemetry/metrics')
15
+ const { channel } = require('dc-polyfill')
15
16
 
16
17
  const tracerMetrics = telemetryMetrics.manager.namespace('tracers')
17
18
 
@@ -30,6 +31,8 @@ const integrationCounters = {
30
31
  span_finished: {}
31
32
  }
32
33
 
34
+ const finishCh = channel('dd-trace:span:finish')
35
+
33
36
  function getIntegrationCounter (event, integration) {
34
37
  const counters = integrationCounters[event]
35
38
 
@@ -176,6 +179,7 @@ class DatadogSpan {
176
179
  this._duration = finishTime - this._startTime
177
180
  this._spanContext._trace.finished.push(this)
178
181
  this._spanContext._isFinished = true
182
+ finishCh.publish(this)
179
183
  this._processor.process(this)
180
184
  }
181
185
 
@@ -1,5 +1,3 @@
1
- const URL = require('url').URL
2
-
3
1
  const {
4
2
  GIT_BRANCH,
5
3
  GIT_COMMIT_SHA,
@@ -24,6 +22,7 @@ const {
24
22
  CI_NODE_LABELS,
25
23
  CI_NODE_NAME
26
24
  } = require('./tags')
25
+ const { filterSensitiveInfoFromRepository } = require('./url')
27
26
 
28
27
  // Receives a string with the form 'John Doe <john.doe@gmail.com>'
29
28
  // and returns { name: 'John Doe', email: 'john.doe@gmail.com' }
@@ -67,20 +66,6 @@ function normalizeRef (ref) {
67
66
  return ref.replace(/origin\/|refs\/heads\/|tags\//gm, '')
68
67
  }
69
68
 
70
- function filterSensitiveInfoFromRepository (repositoryUrl) {
71
- if (repositoryUrl.startsWith('git@')) {
72
- return repositoryUrl
73
- }
74
-
75
- try {
76
- const { protocol, hostname, pathname } = new URL(repositoryUrl)
77
-
78
- return `${protocol}//${hostname}${pathname}`
79
- } catch (e) {
80
- return ''
81
- }
82
- }
83
-
84
69
  function resolveTilde (filePath) {
85
70
  if (!filePath || typeof filePath !== 'string') {
86
71
  return ''
@@ -271,20 +256,22 @@ module.exports = {
271
256
  const ref = GITHUB_HEAD_REF || GITHUB_REF || ''
272
257
  const refKey = ref.includes('tags/') ? GIT_TAG : GIT_BRANCH
273
258
 
259
+ // Both pipeline URL and job URL include GITHUB_SERVER_URL, which can include user credentials,
260
+ // so we pass them through `filterSensitiveInfoFromRepository`.
274
261
  tags = {
275
262
  [CI_PIPELINE_ID]: GITHUB_RUN_ID,
276
263
  [CI_PIPELINE_NAME]: GITHUB_WORKFLOW,
277
264
  [CI_PIPELINE_NUMBER]: GITHUB_RUN_NUMBER,
278
- [CI_PIPELINE_URL]: pipelineURL,
265
+ [CI_PIPELINE_URL]: filterSensitiveInfoFromRepository(pipelineURL),
279
266
  [CI_PROVIDER_NAME]: 'github',
280
267
  [GIT_COMMIT_SHA]: GITHUB_SHA,
281
268
  [GIT_REPOSITORY_URL]: repositoryURL,
282
- [CI_JOB_URL]: jobUrl,
269
+ [CI_JOB_URL]: filterSensitiveInfoFromRepository(jobUrl),
283
270
  [CI_JOB_NAME]: GITHUB_JOB,
284
271
  [CI_WORKSPACE_PATH]: GITHUB_WORKSPACE,
285
272
  [refKey]: ref,
286
273
  [CI_ENV_VARS]: JSON.stringify({
287
- GITHUB_SERVER_URL,
274
+ GITHUB_SERVER_URL: filterSensitiveInfoFromRepository(GITHUB_SERVER_URL),
288
275
  GITHUB_REPOSITORY,
289
276
  GITHUB_RUN_ID,
290
277
  GITHUB_RUN_ATTEMPT
@@ -19,6 +19,7 @@ const {
19
19
  GIT_COMMIT_AUTHOR_NAME,
20
20
  CI_WORKSPACE_PATH
21
21
  } = require('./tags')
22
+ const { filterSensitiveInfoFromRepository } = require('./url')
22
23
 
23
24
  const GIT_REV_LIST_MAX_BUFFER = 8 * 1024 * 1024 // 8MB
24
25
 
@@ -214,7 +215,7 @@ function getGitMetadata (ciMetadata) {
214
215
 
215
216
  return {
216
217
  [GIT_REPOSITORY_URL]:
217
- repositoryUrl || sanitizedExec('git', ['ls-remote', '--get-url']),
218
+ filterSensitiveInfoFromRepository(repositoryUrl || sanitizedExec('git', ['ls-remote', '--get-url'])),
218
219
  [GIT_COMMIT_MESSAGE]:
219
220
  commitMessage || sanitizedExec('git', ['show', '-s', '--format=%s']),
220
221
  [GIT_COMMIT_AUTHOR_DATE]: authorDate,
@@ -48,8 +48,8 @@ function extractIp (config, req) {
48
48
 
49
49
  let firstPrivateIp
50
50
  if (headers) {
51
- for (let i = 0; i < ipHeaderList.length; i++) {
52
- const firstIp = findFirstIp(headers[ipHeaderList[i]])
51
+ for (const ipHeaderName of ipHeaderList) {
52
+ const firstIp = findFirstIp(headers[ipHeaderName])
53
53
 
54
54
  if (firstIp.public) {
55
55
  return firstIp.public
@@ -59,7 +59,7 @@ function extractIp (config, req) {
59
59
  }
60
60
  }
61
61
 
62
- return firstPrivateIp || (req.socket && req.socket.remoteAddress)
62
+ return firstPrivateIp || req.socket?.remoteAddress
63
63
  }
64
64
 
65
65
  function findFirstIp (str) {
@@ -68,8 +68,8 @@ function findFirstIp (str) {
68
68
 
69
69
  const splitted = str.split(',')
70
70
 
71
- for (let i = 0; i < splitted.length; i++) {
72
- const chunk = splitted[i].trim()
71
+ for (const part of splitted) {
72
+ const chunk = part.trim()
73
73
 
74
74
  // TODO: strip port and interface data ?
75
75
 
@@ -90,5 +90,6 @@ function findFirstIp (str) {
90
90
  }
91
91
 
92
92
  module.exports = {
93
- extractIp
93
+ extractIp,
94
+ ipHeaderList
94
95
  }
@@ -0,0 +1,26 @@
1
+ const { URL } = require('url')
2
+
3
+ function filterSensitiveInfoFromRepository (repositoryUrl) {
4
+ if (!repositoryUrl) {
5
+ return ''
6
+ }
7
+ if (repositoryUrl.startsWith('git@')) {
8
+ return repositoryUrl
9
+ }
10
+
11
+ // Remove the username from ssh URLs
12
+ if (repositoryUrl.startsWith('ssh://')) {
13
+ const sshRegex = /^(ssh:\/\/)[^@/]*@/
14
+ return repositoryUrl.replace(sshRegex, '$1')
15
+ }
16
+
17
+ try {
18
+ const { protocol, host, pathname } = new URL(repositoryUrl)
19
+
20
+ return `${protocol}//${host}${pathname === '/' ? '' : pathname}`
21
+ } catch (e) {
22
+ return ''
23
+ }
24
+ }
25
+
26
+ module.exports = { filterSensitiveInfoFromRepository }
@@ -13,7 +13,7 @@ const {
13
13
  } = require('./tags')
14
14
 
15
15
  const { normalizeRef } = require('./ci')
16
- const { URL } = require('url')
16
+ const { filterSensitiveInfoFromRepository } = require('./url')
17
17
 
18
18
  function removeEmptyValues (tags) {
19
19
  return Object.keys(tags).reduce((filteredTags, tag) => {
@@ -27,19 +27,6 @@ function removeEmptyValues (tags) {
27
27
  }, {})
28
28
  }
29
29
 
30
- function filterSensitiveInfoFromRepository (repositoryUrl) {
31
- try {
32
- if (repositoryUrl.startsWith('git@')) {
33
- return repositoryUrl
34
- }
35
- const { protocol, hostname, pathname } = new URL(repositoryUrl)
36
-
37
- return `${protocol}//${hostname}${pathname}`
38
- } catch (e) {
39
- return repositoryUrl
40
- }
41
- }
42
-
43
30
  // The regex is extracted from
44
31
  // https://github.com/jonschlinkert/is-git-url/blob/396965ffabf2f46656c8af4c47bef1d69f09292e/index.js#L9C15-L9C87
45
32
  function validateGitRepositoryUrl (repoUrl) {
@@ -9,6 +9,7 @@ const { FileExporter } = require('./exporters/file')
9
9
  const { ConsoleLogger } = require('./loggers/console')
10
10
  const WallProfiler = require('./profilers/wall')
11
11
  const SpaceProfiler = require('./profilers/space')
12
+ const EventsProfiler = require('./profilers/events')
12
13
  const { oomExportStrategies, snapshotKinds } = require('./constants')
13
14
  const { tagger } = require('./tagger')
14
15
  const { isFalse, isTrue } = require('../util')
@@ -37,6 +38,7 @@ class Config {
37
38
  DD_PROFILING_EXPERIMENTAL_OOM_HEAP_LIMIT_EXTENSION_SIZE,
38
39
  DD_PROFILING_EXPERIMENTAL_OOM_MAX_HEAP_EXTENSION_COUNT,
39
40
  DD_PROFILING_EXPERIMENTAL_OOM_EXPORT_STRATEGIES,
41
+ DD_PROFILING_EXPERIMENTAL_TIMELINE_ENABLED,
40
42
  DD_PROFILING_CODEHOTSPOTS_ENABLED,
41
43
  DD_PROFILING_ENDPOINT_COLLECTION_ENABLED,
42
44
  DD_PROFILING_EXPERIMENTAL_CODEHOTSPOTS_ENABLED,
@@ -126,7 +128,12 @@ class Config {
126
128
 
127
129
  const profilers = options.profilers
128
130
  ? options.profilers
129
- : getProfilers({ DD_PROFILING_HEAP_ENABLED, DD_PROFILING_WALLTIME_ENABLED, DD_PROFILING_PROFILERS })
131
+ : getProfilers({
132
+ DD_PROFILING_HEAP_ENABLED,
133
+ DD_PROFILING_WALLTIME_ENABLED,
134
+ DD_PROFILING_EXPERIMENTAL_TIMELINE_ENABLED,
135
+ DD_PROFILING_PROFILERS
136
+ })
130
137
 
131
138
  this.codeHotspotsEnabled = isTrue(coalesce(options.codeHotspotsEnabled,
132
139
  DD_PROFILING_CODEHOTSPOTS_ENABLED,
@@ -139,7 +146,10 @@ class Config {
139
146
 
140
147
  module.exports = { Config }
141
148
 
142
- function getProfilers ({ DD_PROFILING_HEAP_ENABLED, DD_PROFILING_WALLTIME_ENABLED, DD_PROFILING_PROFILERS }) {
149
+ function getProfilers ({
150
+ DD_PROFILING_HEAP_ENABLED, DD_PROFILING_WALLTIME_ENABLED,
151
+ DD_PROFILING_PROFILERS, DD_PROFILING_EXPERIMENTAL_TIMELINE_ENABLED
152
+ }) {
143
153
  // First consider "legacy" DD_PROFILING_PROFILERS env variable, defaulting to wall + space
144
154
  // Use a Set to avoid duplicates
145
155
  const profilers = new Set(coalesce(DD_PROFILING_PROFILERS, 'wall,space').split(','))
@@ -162,6 +172,11 @@ function getProfilers ({ DD_PROFILING_HEAP_ENABLED, DD_PROFILING_WALLTIME_ENABLE
162
172
  }
163
173
  }
164
174
 
175
+ // Events profiler is a profiler for timeline events that goes with the wall
176
+ // profiler
177
+ if (profilers.has('wall') && DD_PROFILING_EXPERIMENTAL_TIMELINE_ENABLED) {
178
+ profilers.add('events')
179
+ }
165
180
  return [...profilers]
166
181
  }
167
182
 
@@ -223,6 +238,8 @@ function getProfiler (name, options) {
223
238
  return new WallProfiler(options)
224
239
  case 'space':
225
240
  return new SpaceProfiler(options)
241
+ case 'events':
242
+ return new EventsProfiler(options)
226
243
  default:
227
244
  options.logger.error(`Unknown profiler "${name}"`)
228
245
  }
@@ -0,0 +1,161 @@
1
+ const { performance, constants, PerformanceObserver } = require('node:perf_hooks')
2
+ const { END_TIMESTAMP, THREAD_NAME, threadNamePrefix } = require('./shared')
3
+ const semver = require('semver')
4
+ const { Function, Label, Line, Location, Profile, Sample, StringTable, ValueType } = require('pprof-format')
5
+ const pprof = require('@datadog/pprof/')
6
+
7
+ // Format of perf_hooks events changed with Node 16, we need to be mindful of it.
8
+ const node16 = semver.gte(process.version, '16.0.0')
9
+
10
+ // perf_hooks uses millis, with fractional part representing nanos. We emit nanos into the pprof file.
11
+ const MS_TO_NS = 1000000
12
+
13
+ // While this is an "events profiler", meaning it emits a pprof file based on events observed as
14
+ // perf_hooks events, the emitted pprof file uses the type "timeline".
15
+ const pprofValueType = 'timeline'
16
+ const pprofValueUnit = 'nanoseconds'
17
+ const threadName = `${threadNamePrefix} GC`
18
+
19
+ /**
20
+ * This class generates pprof files with timeline events sourced from Node.js
21
+ * performance measurement APIs.
22
+ */
23
+ class EventsProfiler {
24
+ constructor (options = {}) {
25
+ this.type = 'events'
26
+ this._flushIntervalNanos = (options.flushInterval || 60000) * 1e6 // 60 sec
27
+ this._observer = undefined
28
+ this.entries = []
29
+ }
30
+
31
+ start () {
32
+ function add (items) {
33
+ this.entries.push(...items.getEntries())
34
+ }
35
+ if (!this._observer) {
36
+ this._observer = new PerformanceObserver(add.bind(this))
37
+ }
38
+ // Currently only support GC
39
+ this._observer.observe({ type: 'gc' })
40
+ }
41
+
42
+ stop () {
43
+ if (this._observer) {
44
+ this._observer.disconnect()
45
+ }
46
+ }
47
+
48
+ profile () {
49
+ const stringTable = new StringTable()
50
+ const timestampLabelKey = stringTable.dedup(END_TIMESTAMP)
51
+ const kindLabelKey = stringTable.dedup('gc type')
52
+ const reasonLabelKey = stringTable.dedup('gc reason')
53
+ const kindLabels = []
54
+ const reasonLabels = []
55
+ const locations = []
56
+ const functions = []
57
+ const locationsPerKind = []
58
+ const flagObj = {}
59
+
60
+ function labelFromStr (key, valStr) {
61
+ return new Label({ key, str: stringTable.dedup(valStr) })
62
+ }
63
+
64
+ function labelFromStrStr (keyStr, valStr) {
65
+ return labelFromStr(stringTable.dedup(keyStr), valStr)
66
+ }
67
+
68
+ // Create labels for all GC performance flags and kinds of GC
69
+ for (const [key, value] of Object.entries(constants)) {
70
+ if (key.startsWith('NODE_PERFORMANCE_GC_FLAGS_')) {
71
+ flagObj[key.substring(26).toLowerCase()] = value
72
+ } else if (key.startsWith('NODE_PERFORMANCE_GC_')) {
73
+ // It's a constant for a kind of GC
74
+ const kind = key.substring(20).toLowerCase()
75
+ kindLabels[value] = labelFromStr(kindLabelKey, kind)
76
+ // Construct a single-frame "location" too
77
+ const fn = new Function({ id: functions.length + 1, name: stringTable.dedup(`${kind} GC`) })
78
+ functions.push(fn)
79
+ const line = new Line({ functionId: fn.id })
80
+ const location = new Location({ id: locations.length + 1, line: [line] })
81
+ locations.push(location)
82
+ locationsPerKind[value] = [location.id]
83
+ }
84
+ }
85
+
86
+ const gcEventLabel = labelFromStrStr('event', 'gc')
87
+ const threadLabel = labelFromStrStr(THREAD_NAME, threadName)
88
+
89
+ function getReasonLabel (flags) {
90
+ if (flags === 0) {
91
+ return null
92
+ }
93
+ let reasonLabel = reasonLabels[flags]
94
+ if (!reasonLabel) {
95
+ const reasons = []
96
+ for (const [key, value] of Object.entries(flagObj)) {
97
+ if (value & flags) {
98
+ reasons.push(key)
99
+ }
100
+ }
101
+ const reasonStr = reasons.join(',')
102
+ reasonLabel = labelFromStr(reasonLabelKey, reasonStr)
103
+ reasonLabels[flags] = reasonLabel
104
+ }
105
+ return reasonLabel
106
+ }
107
+
108
+ let durationFrom = Number.POSITIVE_INFINITY
109
+ let durationTo = 0
110
+ const dateOffset = BigInt(Math.round(performance.timeOrigin * MS_TO_NS))
111
+
112
+ const samples = this.entries.map((item) => {
113
+ const { startTime, duration } = item
114
+ const { kind, flags } = node16 ? item.detail : item
115
+ const endTime = startTime + duration
116
+ if (durationFrom > startTime) durationFrom = startTime
117
+ if (durationTo < endTime) durationTo = endTime
118
+ const labels = [
119
+ gcEventLabel,
120
+ threadLabel,
121
+ new Label({ key: timestampLabelKey, num: dateOffset + BigInt(Math.round(endTime * MS_TO_NS)) }),
122
+ kindLabels[kind]
123
+ ]
124
+ const reasonLabel = getReasonLabel(flags)
125
+ if (reasonLabel) {
126
+ labels.push(reasonLabel)
127
+ }
128
+ const sample = new Sample({
129
+ value: [Math.round(duration * MS_TO_NS)],
130
+ label: labels,
131
+ locationId: locationsPerKind[kind]
132
+ })
133
+ return sample
134
+ })
135
+
136
+ this.entries = []
137
+
138
+ const timeValueType = new ValueType({
139
+ type: stringTable.dedup(pprofValueType),
140
+ unit: stringTable.dedup(pprofValueUnit)
141
+ })
142
+
143
+ return new Profile({
144
+ sampleType: [timeValueType],
145
+ timeNanos: dateOffset + BigInt(Math.round(durationFrom * MS_TO_NS)),
146
+ periodType: timeValueType,
147
+ period: this._flushIntervalNanos,
148
+ durationNanos: Math.max(0, Math.round((durationTo - durationFrom) * MS_TO_NS)),
149
+ sample: samples,
150
+ location: locations,
151
+ function: functions,
152
+ stringTable: stringTable
153
+ })
154
+ }
155
+
156
+ encode (profile) {
157
+ return pprof.encode(profile)
158
+ }
159
+ }
160
+
161
+ module.exports = EventsProfiler
@@ -0,0 +1,9 @@
1
+ 'use strict'
2
+
3
+ const { isMainThread, threadId } = require('node:worker_threads')
4
+
5
+ module.exports = {
6
+ END_TIMESTAMP: 'end_timestamp_ns',
7
+ THREAD_NAME: 'thread name',
8
+ threadNamePrefix: isMainThread ? 'Main' : `Worker #${threadId}`
9
+ }
@@ -7,16 +7,15 @@ const { HTTP_METHOD, HTTP_ROUTE, RESOURCE_NAME, SPAN_TYPE } = require('../../../
7
7
  const { WEB } = require('../../../../../ext/types')
8
8
  const runtimeMetrics = require('../../runtime_metrics')
9
9
  const telemetryMetrics = require('../../telemetry/metrics')
10
+ const { END_TIMESTAMP, THREAD_NAME, threadNamePrefix } = require('./shared')
10
11
 
11
12
  const beforeCh = dc.channel('dd-trace:storage:before')
12
13
  const enterCh = dc.channel('dd-trace:storage:enter')
14
+ const spanFinishCh = dc.channel('dd-trace:span:finish')
13
15
  const profilerTelemetryMetrics = telemetryMetrics.manager.namespace('profilers')
16
+ const threadName = `${threadNamePrefix} Event Loop`
14
17
 
15
- const threadName = (function () {
16
- const { isMainThread, threadId } = require('node:worker_threads')
17
- const name = isMainThread ? 'Main' : `Worker #${threadId}`
18
- return `${name} Event Loop`
19
- })()
18
+ const CachedWebTags = Symbol('NativeWallProfiler.CachedWebTags')
20
19
 
21
20
  let kSampleCount
22
21
 
@@ -30,7 +29,11 @@ function getStartedSpans (context) {
30
29
  }
31
30
 
32
31
  function generateLabels ({ context: { spanId, rootSpanId, webTags, endpoint }, timestamp }) {
33
- const labels = { 'thread name': threadName }
32
+ const labels = {
33
+ [THREAD_NAME]: threadName,
34
+ // Incoming timestamps are in microseconds, we emit nanos.
35
+ [END_TIMESTAMP]: timestamp * 1000n
36
+ }
34
37
  if (spanId) {
35
38
  labels['span id'] = spanId
36
39
  }
@@ -43,16 +46,10 @@ function generateLabels ({ context: { spanId, rootSpanId, webTags, endpoint }, t
43
46
  // fallback to endpoint computed when sample was taken
44
47
  labels['trace endpoint'] = endpoint
45
48
  }
46
- // Incoming timestamps are in microseconds, we emit nanos.
47
- labels['end_timestamp_ns'] = timestamp * 1000n
48
49
 
49
50
  return labels
50
51
  }
51
52
 
52
- function getSpanContextTags (span) {
53
- return span.context()._tags
54
- }
55
-
56
53
  function isWebServerSpan (tags) {
57
54
  return tags[SPAN_TYPE] === WEB
58
55
  }
@@ -78,6 +75,7 @@ class NativeWallProfiler {
78
75
 
79
76
  // Bind to this so the same value can be used to unsubscribe later
80
77
  this._enter = this._enter.bind(this)
78
+ this._spanFinished = this._spanFinished.bind(this)
81
79
  this._logger = options.logger
82
80
  this._started = false
83
81
  }
@@ -120,10 +118,12 @@ class NativeWallProfiler {
120
118
  this._pprof.time.setContext(this._currentContext)
121
119
  this._lastSpan = undefined
122
120
  this._lastStartedSpans = undefined
121
+ this._lastWebTags = undefined
123
122
  this._lastSampleCount = 0
124
123
 
125
124
  beforeCh.subscribe(this._enter)
126
125
  enterCh.subscribe(this._enter)
126
+ spanFinishCh.subscribe(this._spanFinished)
127
127
  }
128
128
 
129
129
  this._started = true
@@ -144,11 +144,43 @@ class NativeWallProfiler {
144
144
 
145
145
  const span = getActiveSpan()
146
146
  if (span) {
147
+ const context = span.context()
147
148
  this._lastSpan = span
148
- this._lastStartedSpans = getStartedSpans(span.context())
149
+ const startedSpans = getStartedSpans(context)
150
+ this._lastStartedSpans = startedSpans
151
+ if (this._endpointCollectionEnabled) {
152
+ const cachedWebTags = span[CachedWebTags]
153
+ if (cachedWebTags === undefined) {
154
+ let found = false
155
+ // Find the first webspan starting from the end:
156
+ // There might be several webspans, for example with next.js, http plugin creates a first span
157
+ // and then next.js plugin creates a child span, and this child span has the correct endpoint information.
158
+ let nextSpanId = context._spanId
159
+ for (let i = startedSpans.length - 1; i >= 0; i--) {
160
+ const nextContext = startedSpans[i].context()
161
+ if (nextContext._spanId === nextSpanId) {
162
+ const tags = nextContext._tags
163
+ if (isWebServerSpan(tags)) {
164
+ this._lastWebTags = tags
165
+ span[CachedWebTags] = tags
166
+ found = true
167
+ break
168
+ }
169
+ nextSpanId = nextContext._parentId
170
+ }
171
+ }
172
+ if (!found) {
173
+ this._lastWebTags = undefined
174
+ span[CachedWebTags] = null // cache negative lookup result
175
+ }
176
+ } else {
177
+ this._lastWebTags = cachedWebTags
178
+ }
179
+ }
149
180
  } else {
150
181
  this._lastStartedSpans = undefined
151
182
  this._lastSpan = undefined
183
+ this._lastWebTags = undefined
152
184
  }
153
185
  }
154
186
 
@@ -163,21 +195,17 @@ class NativeWallProfiler {
163
195
  context.rootSpanId = rootSpan.context().toSpanId()
164
196
  }
165
197
  }
166
- if (this._endpointCollectionEnabled) {
167
- const startedSpans = this._lastStartedSpans
168
- // Find the first webspan starting from the end:
169
- // There might be several webspans, for example with next.js, http plugin creates a first span
170
- // and then next.js plugin creates a child span, and this child span haves the correct endpoint information.
171
- for (let i = startedSpans.length - 1; i >= 0; i--) {
172
- const tags = getSpanContextTags(startedSpans[i])
173
- if (isWebServerSpan(tags)) {
174
- context.webTags = tags
175
- // endpoint may not be determined yet, but keep it as fallback
176
- // if tags are not available anymore during serialization
177
- context.endpoint = endpointNameFromTags(tags)
178
- break
179
- }
180
- }
198
+ if (this._lastWebTags) {
199
+ context.webTags = this._lastWebTags
200
+ // endpoint may not be determined yet, but keep it as fallback
201
+ // if tags are not available anymore during serialization
202
+ context.endpoint = endpointNameFromTags(this._lastWebTags)
203
+ }
204
+ }
205
+
206
+ _spanFinished (span) {
207
+ if (span[CachedWebTags]) {
208
+ span[CachedWebTags] = undefined
181
209
  }
182
210
  }
183
211
 
@@ -223,7 +251,11 @@ class NativeWallProfiler {
223
251
  if (this._withContexts) {
224
252
  beforeCh.unsubscribe(this._enter)
225
253
  enterCh.unsubscribe(this._enter)
254
+ spanFinishCh.unsubscribe(this._spanFinished)
226
255
  this._profilerState = undefined
256
+ this._lastSpan = undefined
257
+ this._lastStartedSpans = undefined
258
+ this._lastWebTags = undefined
227
259
  }
228
260
 
229
261
  this._started = false
@@ -138,6 +138,10 @@ class SpanProcessor {
138
138
  }
139
139
  }
140
140
 
141
+ for (const span of trace.finished) {
142
+ span.context()._tags = {}
143
+ }
144
+
141
145
  trace.started = active
142
146
  trace.finished = []
143
147
  }