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 <[email protected]>
Reviewed-By: Vladimir de Turckheim <[email protected]>
Reviewed-By: Gerhard Stöbich <[email protected]>
Reviewed-By: Minwoo Jung <[email protected]>
Reviewed-By: Zijian Liu <[email protected]>
  • Loading branch information
Stephen Belanger authored and nodejs-github-bot committed Aug 31, 2021
1 parent 508890d commit 926152a
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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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 926152a

Please sign in to comment.