Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix AsyncResource.bind() binding this to itself by default #1942

Merged
merged 2 commits into from Mar 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 16 additions & 5 deletions packages/datadog-instrumentations/src/helpers/instrument.js
Expand Up @@ -88,7 +88,9 @@ function getBasedir (id) {
return parse(id).basedir.replace(pathSepExpr, '/')
}

if (semver.satisfies(process.versions.node, '>=16.0.0')) {
// AsyncResource.bind exists and binds `this` properly only from 17.8.0 and up.
// https://nodejs.org/api/async_context.html#asyncresourcebindfn-thisarg
if (semver.satisfies(process.versions.node, '>=17.8.0')) {
exports.AsyncResource = AsyncResource
} else {
exports.AsyncResource = class extends AsyncResource {
Expand All @@ -97,9 +99,18 @@ if (semver.satisfies(process.versions.node, '>=16.0.0')) {
return (new exports.AsyncResource(type || 'bound-anonymous-fn')).bind(fn, thisArg)
}

bind (fn, thisArg = this) {
const ret = this.runInAsyncScope.bind(this, fn, thisArg)
Object.defineProperties(ret, {
bind (fn, thisArg) {
let bound
if (thisArg === undefined) {
const resource = this
bound = function (...args) {
args.unshift(fn, this)
return Reflect.apply(resource.runInAsyncScope, resource, args)
}
} else {
bound = this.runInAsyncScope.bind(this, fn, thisArg)
}
Object.defineProperties(bound, {
'length': {
configurable: true,
enumerable: false,
Expand All @@ -113,7 +124,7 @@ if (semver.satisfies(process.versions.node, '>=16.0.0')) {
writable: true
}
})
return ret
return bound
}
}
}
3 changes: 2 additions & 1 deletion packages/datadog-plugin-net/test/index.spec.js
Expand Up @@ -220,7 +220,8 @@ describe('Plugin', () => {
const socket = new net.Socket()

tracer.scope().activate(parent, () => {
socket.connect({ port }, () => {
socket.connect({ port }, function () {
expect(this).to.equal(socket)
expect(tracer.scope().active()).to.equal(parent)
socket.destroy()
done()
Expand Down