-
Notifications
You must be signed in to change notification settings - Fork 386
Expand file tree
/
Copy pathasync_resource.js
More file actions
104 lines (80 loc) · 2.24 KB
/
async_resource.js
File metadata and controls
104 lines (80 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
'use strict'
const { createHook, executionAsyncResource } = require('async_hooks')
const { channel } = require('../../../diagnostics_channel')
const beforeCh = channel('dd-trace:storage:before')
const afterCh = channel('dd-trace:storage:after')
let PrivateSymbol = Symbol
function makePrivateSymbol () {
// eslint-disable-next-line no-new-func
PrivateSymbol = new Function('name', 'return %CreatePrivateSymbol(name)')
}
try {
makePrivateSymbol()
} catch (e) {
try {
const v8 = require('v8')
v8.setFlagsFromString('--allow-natives-syntax')
makePrivateSymbol()
v8.setFlagsFromString('--no-allow-natives-syntax')
// eslint-disable-next-line no-empty
} catch (e) {}
}
class AsyncResourceStorage {
constructor () {
this._ddResourceStore = PrivateSymbol('ddResourceStore')
this._enabled = false
this._hook = createHook(this._createHook())
}
disable () {
if (!this._enabled) return
this._hook.disable()
this._enabled = false
}
getStore () {
if (!this._enabled) return
const resource = this._executionAsyncResource()
return resource[this._ddResourceStore]
}
enterWith (store) {
this._enable()
const resource = this._executionAsyncResource()
resource[this._ddResourceStore] = store
}
run (store, callback, ...args) {
this._enable()
const resource = this._executionAsyncResource()
const oldStore = resource[this._ddResourceStore]
resource[this._ddResourceStore] = store
try {
return callback(...args)
} finally {
resource[this._ddResourceStore] = oldStore
}
}
_createHook () {
return {
init: this._init.bind(this),
before () {
beforeCh.publish()
},
after () {
afterCh.publish()
}
}
}
_enable () {
if (this._enabled) return
this._enabled = true
this._hook.enable()
}
_init (asyncId, type, triggerAsyncId, resource) {
const currentResource = this._executionAsyncResource()
if (Object.prototype.hasOwnProperty.call(currentResource, this._ddResourceStore)) {
resource[this._ddResourceStore] = currentResource[this._ddResourceStore]
}
}
_executionAsyncResource () {
return executionAsyncResource() || {}
}
}
module.exports = AsyncResourceStorage