mirror of
https://github.com/nodejs/node.git
synced 2025-08-15 21:58:48 +02:00
async_hooks: add executionAsyncResource
Remove the need for the destroy hook in the basic APM case. Co-authored-by: Stephen Belanger <admin@stephenbelanger.com> PR-URL: https://github.com/nodejs/node/pull/30959 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Vladimir de Turckheim <vlad2t@hotmail.com> Reviewed-By: Chengzhong Wu <legendecas@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
parent
1c11ea4388
commit
9fdb6e6aaf
19 changed files with 458 additions and 57 deletions
|
@ -0,0 +1,54 @@
|
|||
'use strict';
|
||||
|
||||
const common = require('../common');
|
||||
const sleep = require('util').promisify(setTimeout);
|
||||
const assert = require('assert');
|
||||
const { executionAsyncResource, createHook } = require('async_hooks');
|
||||
const { createServer, get } = require('http');
|
||||
const sym = Symbol('cls');
|
||||
|
||||
// Tests continuation local storage with the currentResource API
|
||||
// through an async function
|
||||
|
||||
assert.ok(executionAsyncResource());
|
||||
|
||||
createHook({
|
||||
init(asyncId, type, triggerAsyncId, resource) {
|
||||
const cr = executionAsyncResource();
|
||||
resource[sym] = cr[sym];
|
||||
}
|
||||
}).enable();
|
||||
|
||||
async function handler(req, res) {
|
||||
executionAsyncResource()[sym] = { state: req.url };
|
||||
await sleep(10);
|
||||
const { state } = executionAsyncResource()[sym];
|
||||
res.setHeader('content-type', 'application/json');
|
||||
res.end(JSON.stringify({ state }));
|
||||
}
|
||||
|
||||
const server = createServer(function(req, res) {
|
||||
handler(req, res);
|
||||
});
|
||||
|
||||
function test(n) {
|
||||
get(`http://localhost:${server.address().port}/${n}`, common.mustCall(function(res) {
|
||||
res.setEncoding('utf8');
|
||||
|
||||
let body = '';
|
||||
res.on('data', function(chunk) {
|
||||
body += chunk;
|
||||
});
|
||||
|
||||
res.on('end', common.mustCall(function() {
|
||||
assert.deepStrictEqual(JSON.parse(body), { state: `/${n}` });
|
||||
}));
|
||||
}));
|
||||
}
|
||||
|
||||
server.listen(0, common.mustCall(function() {
|
||||
server.unref();
|
||||
for (let i = 0; i < 10; i++) {
|
||||
test(i);
|
||||
}
|
||||
}));
|
Loading…
Add table
Add a link
Reference in a new issue