Skip to content

Commit 8e7ae60

Browse files
authored
async_hooks: enable AsyncLocalStorage once constructed
This fixes the leak behavior when using `enterWith` when no `AsyncLocalStorage`s were enabled inside a promise. PR-URL: #58029 Fixes: #53037 Refs: #58019 Reviewed-By: Gerhard Stöbich <[email protected]> Reviewed-By: Matteo Collina <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent c712dd2 commit 8e7ae60

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

lib/internal/async_local_storage/async_hooks.js

+2
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@ class AsyncLocalStorage {
5151
if (options.name !== undefined) {
5252
this.#name = `${options.name}`;
5353
}
54+
55+
this._enable();
5456
}
5557

5658
/** @type {string} */
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const { AsyncLocalStorage } = require('async_hooks');
5+
6+
// Verify that `enterWith()` does not leak the store to the parent context in a promise.
7+
8+
const als = new AsyncLocalStorage();
9+
10+
async function asyncFunctionAfterAwait() {
11+
await 0;
12+
als.enterWith('after await');
13+
}
14+
15+
function promiseThen() {
16+
return Promise.resolve()
17+
.then(() => {
18+
als.enterWith('inside then');
19+
});
20+
}
21+
22+
async function asyncFunctionBeforeAwait() {
23+
als.enterWith('before await');
24+
await 0;
25+
}
26+
27+
async function main() {
28+
await asyncFunctionAfterAwait();
29+
await promiseThen();
30+
assert.strictEqual(als.getStore(), undefined);
31+
32+
// This is a known limitation of the `enterWith` API.
33+
await asyncFunctionBeforeAwait();
34+
assert.strictEqual(als.getStore(), 'before await');
35+
}
36+
37+
main().then(common.mustCall());

0 commit comments

Comments
 (0)