Skip to content

Commit de0250d

Browse files
author
Stephen Belanger
committed
async_hooks: use resource stack for AsyncLocalStorage run
PR-URL: nodejs#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]>
1 parent c4ff5e4 commit de0250d

File tree

3 files changed

+33
-38
lines changed

3 files changed

+33
-38
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
'use strict';
2+
const common = require('../common.js');
3+
const { AsyncLocalStorage } = require('async_hooks');
4+
5+
const bench = common.createBenchmark(main, {
6+
n: [1e7]
7+
});
8+
9+
async function run(store, n) {
10+
for (let i = 0; i < n; i++) {
11+
await new Promise((resolve) => store.run(i, resolve));
12+
}
13+
}
14+
15+
function main({ n }) {
16+
const store = new AsyncLocalStorage();
17+
bench.start();
18+
run(store, n).then(() => {
19+
bench.end(n);
20+
});
21+
}

lib/async_hooks.js

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,6 @@ const storageHook = createHook({
257257
}
258258
});
259259

260-
const defaultAlsResourceOpts = { requireManualDestroy: true };
261260
class AsyncLocalStorage {
262261
constructor() {
263262
this.kResourceStore = Symbol('kResourceStore');
@@ -303,14 +302,19 @@ class AsyncLocalStorage {
303302
if (ObjectIs(store, this.getStore())) {
304303
return ReflectApply(callback, null, args);
305304
}
306-
const resource = new AsyncResource('AsyncLocalStorage',
307-
defaultAlsResourceOpts);
308-
// Calling emitDestroy before runInAsyncScope avoids a try/finally
309-
// It is ok because emitDestroy only schedules calling the hook
310-
return resource.emitDestroy().runInAsyncScope(() => {
311-
this.enterWith(store);
305+
306+
this._enable();
307+
308+
const resource = executionAsyncResource();
309+
const oldStore = resource[this.kResourceStore];
310+
311+
resource[this.kResourceStore] = store;
312+
313+
try {
312314
return ReflectApply(callback, null, args);
313-
});
315+
} finally {
316+
resource[this.kResourceStore] = oldStore;
317+
}
314318
}
315319

316320
exit(callback, ...args) {

test/async-hooks/test-async-local-storage-run-resource.js

Lines changed: 0 additions & 30 deletions
This file was deleted.

0 commit comments

Comments
 (0)