Skip to content

Commit 2343c39

Browse files
Stephen Belangertargos
Stephen Belanger
authored andcommitted
async_hooks: use resource stack for AsyncLocalStorage run
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]>
1 parent ca9b781 commit 2343c39

File tree

3 files changed

+33
-38
lines changed

3 files changed

+33
-38
lines changed
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

+12-8
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,6 @@ const storageHook = createHook({
263263
}
264264
});
265265

266-
const defaultAlsResourceOpts = { requireManualDestroy: true };
267266
class AsyncLocalStorage {
268267
constructor() {
269268
this.kResourceStore = Symbol('kResourceStore');
@@ -309,14 +308,19 @@ class AsyncLocalStorage {
309308
if (ObjectIs(store, this.getStore())) {
310309
return ReflectApply(callback, null, args);
311310
}
312-
const resource = new AsyncResource('AsyncLocalStorage',
313-
defaultAlsResourceOpts);
314-
// Calling emitDestroy before runInAsyncScope avoids a try/finally
315-
// It is ok because emitDestroy only schedules calling the hook
316-
return resource.emitDestroy().runInAsyncScope(() => {
317-
this.enterWith(store);
311+
312+
this._enable();
313+
314+
const resource = executionAsyncResource();
315+
const oldStore = resource[this.kResourceStore];
316+
317+
resource[this.kResourceStore] = store;
318+
319+
try {
318320
return ReflectApply(callback, null, args);
319-
});
321+
} finally {
322+
resource[this.kResourceStore] = oldStore;
323+
}
320324
}
321325

322326
exit(callback, ...args) {

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

-30
This file was deleted.

0 commit comments

Comments
 (0)