Skip to content

Commit

Permalink
async_hooks: use resource stack for AsyncLocalStorage run
Browse files Browse the repository at this point in the history
PR-URL: #39890
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Vladimir de Turckheim <vlad2t@hotmail.com>
Reviewed-By: Gerhard Stöbich <deb2001-github@yahoo.de>
Reviewed-By: Minwoo Jung <nodecorelab@gmail.com>
Reviewed-By: Zijian Liu <lxxyxzj@gmail.com>
  • Loading branch information
Qard authored and targos committed Sep 6, 2021
1 parent b520dfa commit 2a453ff
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 38 deletions.
21 changes: 21 additions & 0 deletions benchmark/async_hooks/async-local-storage-run.js
@@ -0,0 +1,21 @@
'use strict';
const common = require('../common.js');
const { AsyncLocalStorage } = require('async_hooks');

const bench = common.createBenchmark(main, {
n: [1e7]
});

async function run(store, n) {
for (let i = 0; i < n; i++) {
await new Promise((resolve) => store.run(i, resolve));
}
}

function main({ n }) {
const store = new AsyncLocalStorage();
bench.start();
run(store, n).then(() => {
bench.end(n);
});
}
20 changes: 12 additions & 8 deletions lib/async_hooks.js
Expand Up @@ -263,7 +263,6 @@ const storageHook = createHook({
}
});

const defaultAlsResourceOpts = { requireManualDestroy: true };
class AsyncLocalStorage {
constructor() {
this.kResourceStore = Symbol('kResourceStore');
Expand Down Expand Up @@ -309,14 +308,19 @@ class AsyncLocalStorage {
if (ObjectIs(store, this.getStore())) {
return ReflectApply(callback, null, args);
}
const resource = new AsyncResource('AsyncLocalStorage',
defaultAlsResourceOpts);
// Calling emitDestroy before runInAsyncScope avoids a try/finally
// It is ok because emitDestroy only schedules calling the hook
return resource.emitDestroy().runInAsyncScope(() => {
this.enterWith(store);

this._enable();

const resource = executionAsyncResource();
const oldStore = resource[this.kResourceStore];

resource[this.kResourceStore] = store;

try {
return ReflectApply(callback, null, args);
});
} finally {
resource[this.kResourceStore] = oldStore;
}
}

exit(callback, ...args) {
Expand Down
30 changes: 0 additions & 30 deletions test/async-hooks/test-async-local-storage-run-resource.js

This file was deleted.

0 comments on commit 2a453ff

Please sign in to comment.