GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — stream: keep async context of the pipeTo pump · nodejs/node@b6386d5

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • lib/internal/webstreams
    • readablestream.js
  • test/parallel
    • test-whatwg-readablestream-pipeto-async-context.js
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎lib/internal/webstreams/readablestream.js‎

Copy file name to clipboardExpand all lines: lib/internal/webstreams/readablestream.js
+28Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,14 @@ const {
4949

5050
const AsyncContextFrame = require('internal/async_context_frame');
5151

52+
// The pipe checks the async context frame on every pump step; the
53+
// intrinsics reduce to a field access in optimized code, which the
54+
// AsyncContextFrame wrappers would put behind another inlining level.
55+
const {
56+
getContinuationPreservedEmbedderData: currentContextFrame,
57+
setContinuationPreservedEmbedderData: setContextFrame,
58+
} = internalBinding('async_context_frame');
59+
5260
const {
5361
isArrayBufferView,
5462
isDataView,
@@ -1791,6 +1799,20 @@ function readableStreamPipeTo(
17911799
let readRequest;
17921800
let readyHook;
17931801

1802+
// The pump re-enters from the ready hook and from the chunk steps, which
1803+
// run in the async context of whoever cleared the backpressure or
1804+
// enqueued the chunk. Resume it in the context of the pipeTo() call, as
1805+
// the promise-based pump did.
1806+
const pipeContextFrame = currentContextFrame();
1807+
function pumpInPipeContext(prior) {
1808+
setContextFrame(pipeContextFrame);
1809+
try {
1810+
pump();
1811+
} finally {
1812+
setContextFrame(prior);
1813+
}
1814+
}
1815+
17941816
// Ready promise rejection is handled by the destination-errored
17951817
// watcher.
17961818
function ignoreReadyRejection() {}
@@ -1825,6 +1847,12 @@ function readableStreamPipeTo(
18251847
function pump() {
18261848
if (shuttingDown) return;
18271849

1850+
const contextFrame = currentContextFrame();
1851+
if (contextFrame !== pipeContextFrame) {
1852+
pumpInPipeContext(contextFrame);
1853+
return;
1854+
}
1855+
18281856
if (dest[kState].backpressure) {
18291857
parkOnReady();
18301858
return;
Collapse file

‎test/parallel/test-whatwg-readablestream-pipeto-async-context.js‎

Copy file name to clipboard
+157Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
'use strict';
2+
3+
// The pipeTo() pump must keep running in the async context of the
4+
// pipeTo() call when it resumes after backpressure or after a chunk
5+
// arrives, instead of taking the context of the code that cleared the
6+
// backpressure or enqueued the chunk. The source pulls and the writes the
7+
// pump issues are checked.
8+
9+
const common = require('../common');
10+
const assert = require('assert');
11+
const { AsyncLocalStorage } = require('async_hooks');
12+
const { setImmediate: tick } = require('timers/promises');
13+
14+
const als = new AsyncLocalStorage();
15+
16+
function store() {
17+
return als.getStore() ?? 'none';
18+
}
19+
20+
// Settles the pending callbacks from the given context until `promise`
21+
// settles.
22+
async function settleUntil(promise, ctx, pending) {
23+
let finished = false;
24+
promise.then(common.mustCall(() => { finished = true; }));
25+
while (!finished) {
26+
await tick();
27+
while (pending.length > 0) als.run(ctx, pending.shift());
28+
}
29+
await promise;
30+
}
31+
32+
const tests = [];
33+
function test(name, expected, fn) {
34+
tests.push({ name, expected, fn });
35+
}
36+
37+
test('sink writes resolved from another context', [
38+
// The first pull and write follow the source's start step.
39+
'pull:creator', 'write-1:creator',
40+
'pull:piper', 'write-2:piper',
41+
'pull:piper', 'write-3:piper',
42+
'pull:piper',
43+
], async (seen) => {
44+
let n = 0;
45+
const pending = [];
46+
const rs = als.run('creator', () => new ReadableStream({
47+
pull(c) {
48+
seen.push(`pull:${store()}`);
49+
if (++n > 3) c.close(); else c.enqueue(n);
50+
},
51+
}, { highWaterMark: 0 }));
52+
const ws = als.run('creator', () => new WritableStream({
53+
write(chunk) {
54+
seen.push(`write-${chunk}:${store()}`);
55+
const { promise, resolve } = Promise.withResolvers();
56+
pending.push(resolve);
57+
return promise;
58+
},
59+
}, { highWaterMark: 1 }));
60+
await settleUntil(als.run('piper', () => rs.pipeTo(ws)), 'releaser', pending);
61+
});
62+
63+
test('push source under backpressure', [
64+
'write-a:pusher-a', 'write-b:piper', 'write-c:piper', 'write-d:piper',
65+
], async (seen) => {
66+
let controller;
67+
const pending = [];
68+
const rs = als.run('creator', () => new ReadableStream({
69+
start(c) { controller = c; },
70+
}, { highWaterMark: 0 }));
71+
const ws = als.run('creator', () => new WritableStream({
72+
write(chunk) {
73+
seen.push(`write-${chunk}:${store()}`);
74+
const { promise, resolve } = Promise.withResolvers();
75+
pending.push(resolve);
76+
return promise;
77+
},
78+
}, { highWaterMark: 1 }));
79+
const piped = als.run('piper', () => rs.pipeTo(ws));
80+
await tick();
81+
for (const chunk of 'abcd')
82+
als.run(`pusher-${chunk}`, () => controller.enqueue(chunk));
83+
als.run('closer', () => controller.close());
84+
await settleUntil(piped, 'releaser', pending);
85+
});
86+
87+
test('pipeThrough() with pulls resolved from another context', [
88+
'pull:piper', 'transform-1:resolver',
89+
'pull:piper', 'transform-2:resolver',
90+
'pull:piper', 'transform-3:resolver',
91+
'pull:piper',
92+
], async (seen) => {
93+
let n = 0;
94+
const pending = [];
95+
const readable = als.run('piper', () => new ReadableStream({
96+
pull(c) {
97+
seen.push(`pull:${store()}`);
98+
const { promise, resolve } = Promise.withResolvers();
99+
pending.push(() => {
100+
if (++n > 3) c.close(); else c.enqueue(n);
101+
resolve();
102+
});
103+
return promise;
104+
},
105+
}, { highWaterMark: 0 }).pipeThrough(new TransformStream({
106+
transform(chunk, c) {
107+
seen.push(`transform-${chunk}:${store()}`);
108+
c.enqueue(chunk);
109+
},
110+
})));
111+
const consumed = als.run('reader', async () => {
112+
// eslint-disable-next-line no-unused-vars
113+
for await (const _ of readable);
114+
});
115+
await settleUntil(consumed, 'resolver', pending);
116+
});
117+
118+
test('pipeThrough() chain into a slow sink', [
119+
'pull:creator', 't1-1:piper', 't2-1:piper', 'write-1:piper',
120+
'pull:piper', 't1-2:piper', 't2-2:piper', 'write-2:piper',
121+
'pull:piper', 't1-3:piper', 't2-3:piper', 'write-3:piper',
122+
'pull:piper',
123+
], async (seen) => {
124+
let n = 0;
125+
function transform(name) {
126+
return new TransformStream({
127+
transform(chunk, c) {
128+
seen.push(`${name}-${chunk}:${store()}`);
129+
c.enqueue(chunk);
130+
},
131+
});
132+
}
133+
const rs = als.run('creator', () => new ReadableStream({
134+
pull(c) {
135+
seen.push(`pull:${store()}`);
136+
if (++n > 3) c.close(); else c.enqueue(n);
137+
},
138+
}, { highWaterMark: 0 }));
139+
const ws = als.run('creator', () => new WritableStream({
140+
async write(chunk) {
141+
seen.push(`write-${chunk}:${store()}`);
142+
await tick();
143+
},
144+
}, { highWaterMark: 1 }));
145+
await als.run('piper', () => rs.pipeThrough(transform('t1'))
146+
.pipeThrough(transform('t2')).pipeTo(ws));
147+
});
148+
149+
(async () => {
150+
for (const { name, expected, fn } of tests) {
151+
const seen = [];
152+
await fn(seen);
153+
// Only the context of each callback is checked, not how the callbacks
154+
// of different streams interleave.
155+
assert.deepStrictEqual(seen.sort(), expected.toSorted(), name);
156+
}
157+
})().then(common.mustCall());

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.