Skip to content

Commit 932c2d9

Browse files
gurgundayRafaelGSS
authored andcommitted
stream: preserve AsyncLocalStorage context in finished()
PR-URL: #57865 Reviewed-By: Raz Luvaton <[email protected]> Reviewed-By: Matteo Collina <[email protected]> Reviewed-By: Chengzhong Wu <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent afc49db commit 932c2d9

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

lib/internal/streams/end-of-stream.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ const {
4343
willEmitClose: _willEmitClose,
4444
kIsClosedPromise,
4545
} = require('internal/streams/utils');
46+
47+
// Lazy load
48+
let AsyncLocalStorage;
4649
let addAbortListener;
4750

4851
function isRequest(stream) {
@@ -63,7 +66,8 @@ function eos(stream, options, callback) {
6366
validateFunction(callback, 'callback');
6467
validateAbortSignal(options.signal, 'options.signal');
6568

66-
callback = once(callback);
69+
AsyncLocalStorage ??= require('async_hooks').AsyncLocalStorage;
70+
callback = once(AsyncLocalStorage.bind(callback));
6771

6872
if (isReadableStream(stream) || isWritableStream(stream)) {
6973
return eosWeb(stream, options, callback);
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const { Readable, finished } = require('stream');
5+
const { AsyncLocalStorage } = require('async_hooks');
6+
const { strictEqual } = require('assert');
7+
8+
// This test verifies that AsyncLocalStorage context is maintained
9+
// when using stream.finished()
10+
11+
const readable = new Readable();
12+
const als = new AsyncLocalStorage();
13+
14+
als.run(321, () => {
15+
finished(readable, common.mustCall(() => {
16+
strictEqual(als.getStore(), 321);
17+
}));
18+
});
19+
20+
readable.destroy();

0 commit comments

Comments
 (0)