forked from naugtur/blocked-at
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
73 lines (63 loc) · 1.85 KB
/
index.js
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
'use strict'
const asyncHooks = require('async_hooks')
const cache = new Map()// WeakMap maybe?
function cleanStack (stack) {
const frames = stack.split('\n')
let i = 0
while (i < 5 && frames[0] && (i < 2 || frames[0].includes('(async_hooks.js'))) {
frames.shift()
i++
}
return frames
}
module.exports = (callback, options) => {
let continuityId
options = options || {}
options.threshold = (options.threshold || 20)
Error.stackTraceLimit = Infinity
const asyncHook = asyncHooks.createHook({ init, before, after, destroy })
const dispatchCallback = (dt, stack) => setImmediate(callback, dt, stack)
const debugLog = (title, message) => (options.debug && process._rawDebug(title, message))
function init (asyncId, type, triggerAsyncId, resource) {
const e = {}
Error.captureStackTrace(e)
debugLog('init', asyncId)
cache.set(asyncId, {asyncId, type, stack: e.stack})
}
function before (asyncId) {
debugLog('before', asyncId)
if (options.trimFalsePositives) {
continuityId = asyncId
}
const cached = cache.get(asyncId)
if (!cached) { return }
cached.t0 = hrtime()
}
function after (asyncId) {
debugLog('after', asyncId)
if (options.trimFalsePositives && continuityId !== asyncId) {
// drop for interuptions
return
}
const cached = cache.get(asyncId)
if (!cached) { return }
const t1 = hrtime()
const dt = (t1 - cached.t0) / 1000
// process._rawDebug(dt > options.threshold, options.threshold, dt, cached)
if (dt > options.threshold) {
debugLog('stack', cached.stack)
dispatchCallback(dt, cleanStack(cached.stack))
}
}
function destroy (asyncId) {
cache.delete(asyncId)
}
asyncHook.enable()
return {
stop: asyncHook.disable
}
}
function hrtime () {
const t = process.hrtime()
return t[0] * 1000000 + t[1] / 1000
}