-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.js
More file actions
97 lines (83 loc) · 2.16 KB
/
index.js
File metadata and controls
97 lines (83 loc) · 2.16 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
var assert = require('assert')
var NS_PER_SEC = 1e9
module.exports = onAsyncHook
function onAsyncHook (opts, cb) {
if (!cb) {
cb = opts
opts = {}
}
assert.strictEqual(typeof opts, 'object', 'on-async-hook: opts should be type object')
assert.strictEqual(typeof cb, 'function', 'on-async-hook: cb should be type function')
// catch this if we are not in node 8
try {
var asyncHooks = require('async_hooks')
} catch (e) {
return function () {}
}
var links = {}
var traces = {}
var spans = {}
var hooks = {
init: init,
destroy: destroy
}
var asyncHook = asyncHooks.createHook(hooks)
asyncHook.enable()
return function () {
asyncHook.disable()
}
function init (asyncId, type, triggerId) {
var currentId = asyncHooks.executionAsyncId()
// don't want the initial start TCPWRAP
if (currentId === 1 && type === 'TCPWRAP') return
if (triggerId === 0) return
var time = process.hrtime()
var span = createSpan(asyncId, type, triggerId, time)
var traceId = links[triggerId]
var trace = null
if (!traceId) {
traceId = asyncId
trace = createTrace(time, traceId)
} else {
trace = traces[traceId]
}
traces[asyncId] = trace
links[asyncId] = traceId
spans[asyncId] = span
trace.spans.push(span)
}
function destroy (asyncId) {
var time = process.hrtime()
var span = spans[asyncId]
if (!span) return
span.endTime = time[0] * NS_PER_SEC + time[1]
span.duration = span.endTime - span.startTime
var trace = traces[asyncId]
if (!trace) return
trace.endTime = time[0] * NS_PER_SEC + time[1]
trace.duration = trace.endTime - trace.startTime
links[asyncId] = null
traces[asyncId] = null
trace.spans.forEach(function (span) {
var id = span.id
links[id] = null
spans[id] = null
})
cb(trace)
}
function createSpan (id, type, parent, time) {
return {
id: id,
type: type,
parent: parent,
startTime: time[0] * NS_PER_SEC + time[1]
}
}
function createTrace (time, id) {
return {
startTime: time[0] * NS_PER_SEC + time[1],
id: id,
spans: []
}
}
}