async_hooks: introduce async-context API

Adding AsyncLocalStorage class to async_hooks
 module.
This API provide a simple CLS-like set
of features.

Co-authored-by: Andrey Pechkurov <apechkurov@gmail.com>

PR-URL: https://github.com/nodejs/node/pull/26540
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
Reviewed-By: Gireesh Punathil <gpunathi@in.ibm.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
This commit is contained in:
vdeturckheim 2019-03-01 21:31:36 +01:00
parent 72b6cea25d
commit 9c702922cd
No known key found for this signature in database
GPG key ID: 78A7A2EB0AA81A1B
13 changed files with 667 additions and 3 deletions

View file

@ -8,7 +8,8 @@ const common = require('../common.js');
const {
createHook,
executionAsyncResource,
executionAsyncId
executionAsyncId,
AsyncLocalStorage
} = require('async_hooks');
const { createServer } = require('http');
@ -18,7 +19,7 @@ const connections = 500;
const path = '/';
const bench = common.createBenchmark(main, {
type: ['async-resource', 'destroy'],
type: ['async-resource', 'destroy', 'async-local-storage'],
asyncMethod: ['callbacks', 'async'],
n: [1e6]
});
@ -102,6 +103,35 @@ function buildDestroy(getServe) {
}
}
function buildAsyncLocalStorage(getServe) {
const asyncLocalStorage = new AsyncLocalStorage();
const server = createServer((req, res) => {
asyncLocalStorage.runSyncAndReturn(() => {
getServe(getCLS, setCLS)(req, res);
});
});
return {
server,
close
};
function getCLS() {
const store = asyncLocalStorage.getStore();
return store.get('store');
}
function setCLS(state) {
const store = asyncLocalStorage.getStore();
store.set('store', state);
}
function close() {
asyncLocalStorage.disable();
server.close();
}
}
function getServeAwait(getCLS, setCLS) {
return async function serve(req, res) {
setCLS(Math.random());
@ -126,7 +156,8 @@ function getServeCallbacks(getCLS, setCLS) {
const types = {
'async-resource': buildCurrentResource,
'destroy': buildDestroy
'destroy': buildDestroy,
'async-local-storage': buildAsyncLocalStorage
};
const asyncMethods = {