Skip to content

Commit

Permalink
self-contain profiling's AsyncLocalStorage channel usage
Browse files Browse the repository at this point in the history
  • Loading branch information
bengl committed Oct 4, 2024
1 parent ed4975f commit 3c7db0f
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions packages/dd-trace/src/profiling/profilers/wall.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,43 @@ function getWebTags (startedSpans, i, span) {
return memoize(null)
}

let channelsActivated = false
function ensureChannelsActivated () {
if (channelsActivated) return

const { AsyncLocalStorage, createHook } = require('async_hooks')
const shimmer = require('../../../../datadog-shimmer')

createHook({ before: () => beforeCh.publish() }).enable()

shimmer.wrap(AsyncLocalStorage.prototype, 'enterWith', function (original) {
return function (...args) {
const retVal = original.apply(this, args)
enterCh.publish()
return retVal
}
})

// TODO this will change in the future. It won't be experimental forever.
const needsWrappedCb =
!process.execArgv.includes('--experimental-async-context-frame')
shimmer.wrap(AsyncLocalStorage.prototype, 'run', function (original) {
return function (store, callback, ...args) {
const wrappedCb = needsWrappedCb
? shimmer.wrapFunction(callback, cb => function (...args) {
enterCh.publish()
return cb.apply(this, args)
})
: callback
const retVal = original.call(this, store, wrappedCb, ...args)
enterCh.publish()
return retVal
}
})

channelsActivated = true
}

class NativeWallProfiler {
constructor (options = {}) {
this.type = 'wall'
Expand Down Expand Up @@ -121,6 +158,8 @@ class NativeWallProfiler {
start ({ mapper } = {}) {
if (this._started) return

ensureChannelsActivated()

this._mapper = mapper
this._pprof = require('@datadog/pprof')
kSampleCount = this._pprof.time.constants.kSampleCount
Expand Down

0 comments on commit 3c7db0f

Please sign in to comment.