Closed
Description
- Version: 10.0.0 and master
- Platform: all
- Subsystem: async_hooks
The following represent a pattern very commonly used by APMs:
'use strict'
const http = require('http')
const sleep = require('util').promisify(setTimeout)
const asyncHooks = require('async_hooks')
const asyncHook = asyncHooks.createHook({init, destroy})
const transactions = new Map()
asyncHook.enable()
function getCLS () {
const asyncId = asyncHooks.executionAsyncId()
return transactions.has(asyncId) ? transactions.get(asyncId) : null
}
function setCLS (value) {
const asyncId = asyncHooks.executionAsyncId()
transactions.set(asyncId, value)
}
function init (asyncId, type, triggerAsyncId, resource) {
transactions.set(asyncId, getCLS())
}
function destroy (asyncId) {
transactions.delete(asyncId)
}
http.createServer(function (req, res) {
handler().then(function (data) {
res.end(JSON.stringify(data))
}).catch(function (err) {
res.statusCode = 500
res.end(err.stack)
})
}).listen(3000)
var counter = 0
async function handler () {
setCLS(counter++)
await sleep(10)
return { cls: getCLS() }
}
Correct behavior (node 8.11.1):
$ curl localhost:3000
{"cls":0}
master:
$ curl localhost:3000
{"cls":null}