Skip to content

Commit 89f9729

Browse files
gurgundaymarco-ippolito
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 5ca9616 commit 89f9729

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
@@ -44,6 +44,9 @@ const {
4444
willEmitClose: _willEmitClose,
4545
kIsClosedPromise,
4646
} = require('internal/streams/utils');
47+
48+
// Lazy load
49+
let AsyncLocalStorage;
4750
let addAbortListener;
4851

4952
function isRequest(stream) {
@@ -64,7 +67,8 @@ function eos(stream, options, callback) {
6467
validateFunction(callback, 'callback');
6568
validateAbortSignal(options.signal, 'options.signal');
6669

67-
callback = once(callback);
70+
AsyncLocalStorage ??= require('async_hooks').AsyncLocalStorage;
71+
callback = once(AsyncLocalStorage.bind(callback));
6872

6973
if (isReadableStream(stream) || isWritableStream(stream)) {
7074
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)