Skip to content

Commit

Permalink
Simplify async_hooks logic
Browse files Browse the repository at this point in the history
  • Loading branch information
watson committed Dec 21, 2017
1 parent 5ec35f3 commit 60e2bf7
Showing 1 changed file with 16 additions and 18 deletions.
34 changes: 16 additions & 18 deletions lib/instrumentation/async-hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,19 @@
const asyncHooks = require('async_hooks')

module.exports = function (ins) {
const asyncHook = asyncHooks.createHook({init, before, after, destroy})
const initState = new Map()
const beforeState = new Map()
const asyncHook = asyncHooks.createHook({init, destroy})
const transactions = new Map()

Object.defineProperty(ins, 'currentTransaction', {
get: function () {
const asyncId = asyncHooks.executionAsyncId()
return transactions.get(asyncId)
},
set: function (trans) {
const asyncId = asyncHooks.executionAsyncId()
transactions.set(asyncId, trans)
}
})

asyncHook.enable()

Expand All @@ -15,23 +25,11 @@ module.exports = function (ins) {
// type, which will init for each scheduled timer.
if (type === 'TIMERWRAP') return

initState.set(asyncId, ins.currentTransaction)
}

function before (asyncId) {
if (!initState.has(asyncId)) return // in case type === TIMERWRAP
beforeState.set(asyncId, ins.currentTransaction)
ins.currentTransaction = initState.get(asyncId)
}

function after (asyncId) {
if (!initState.has(asyncId)) return // in case type === TIMERWRAP
ins.currentTransaction = beforeState.get(asyncId)
transactions.set(asyncId, ins.currentTransaction)
}

function destroy (asyncId) {
if (!initState.has(asyncId)) return // in case type === TIMERWRAP
initState.delete(asyncId)
beforeState.delete(asyncId)
if (!transactions.has(asyncId)) return // in case type === TIMERWRAP
transactions.delete(asyncId)
}
}

0 comments on commit 60e2bf7

Please sign in to comment.