Simplify transforms implementation (#755)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent a12c8e9 · Browse files · 4 files·+98 added−75 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+98 added−75 removed
- tests:+43 added−14 removed
- other:+55 added−61 removed
Provenance
- Commit
14fca86- Tree
3b9753c- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
a12c8e9
4 files changed+98 added−75 removed
deleted:lib/stdio/duplex.js-59 removed
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import {Duplex, Readable, PassThrough, getDefaultHighWaterMark} from 'node:stream';
/*Transform an array of generator functions into a `Duplex`.
The `Duplex` is created by `Duplex.from()` made of a writable stream and a readable stream, piped to each other.- The writable stream is a simple `PassThrough`, so it only forwards data to the readable part.- The `PassThrough` is read as an iterable using `passThrough.iterator()`.- This iterable is transformed to another iterable, by applying the encoding generators. Those convert the chunk type from `Buffer` to `string | Uint8Array` depending on the encoding option.- This new iterable is transformed again to another one, this time by applying the user-supplied generator.- Finally, `Readable.from()` is used to convert this final iterable to a `Readable` stream.*/export const generatorsToDuplex = (generators, {writableObjectMode, readableObjectMode}) => { const passThrough = new PassThrough({ objectMode: writableObjectMode, highWaterMark: getDefaultHighWaterMark(writableObjectMode), destroy: destroyPassThrough, }); let iterable = passThrough.iterator();
for (const generator of generators) { iterable = applyGenerator(generator, iterable); }
const readableStream = Readable.from(iterable, { objectMode: readableObjectMode, highWaterMark: getDefaultHighWaterMark(readableObjectMode), }); const duplexStream = Duplex.from({writable: passThrough, readable: readableStream}); return duplexStream;};
const applyGenerator = async function * ({transform, final}, chunks) { for await (const chunk of chunks) { yield * transform(chunk); }
if (final !== undefined) { yield * final(); }};
/*When an error is thrown in a generator, the PassThrough is aborted.
This creates a race condition for which error is propagated, due to the Duplex throwing twice:- The writable side is aborted (PassThrough)- The readable side propagate the generator's error
In order for the later to win that race, we need to wait one microtask.- However we wait one macrotask instead to be on the safe side- See https://github.com/sindresorhus/execa/pull/693#discussion_r1453809450*/const destroyPassThrough = (error, done) => { setImmediate(() => { done(error); });};modified:lib/stdio/generator.js+2 added-2 removed
11234570 unmodified lines7677787980808182838436 unmodified linesimport {generatorsToDuplex} from './duplex.js';import {generatorsToTransform} from './transform.js';import {getEncodingStartGenerator} from './encoding.js';import {getLinesGenerator} from './lines.js';import {isGeneratorOptions} from './type.js';import {isBinary, pipeStreams} from './utils.js';70 unmodified lines getLinesGenerator(encoding, binary), {transform, final}, {transform: getValidateTransformReturn(readableObjectMode, optionName)}, ].filter(Boolean); const duplexStream = generatorsToDuplex(generators, {writableObjectMode, readableObjectMode}); const duplexStream = generatorsToTransform(generators, {writableObjectMode, readableObjectMode}); return {value: duplexStream};};
const getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode36 unmodified linesadded:lib/stdio/transform.js+53 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253import {Transform, getDefaultHighWaterMark} from 'node:stream';import {callbackify} from 'node:util';
// Transform an array of generator functions into a `Transform` stream.// `Duplex.from(generator)` cannot be used because it does not allow setting the `objectMode` and `highWaterMark`.export const generatorsToTransform = (generators, {writableObjectMode, readableObjectMode}) => new Transform({ writableObjectMode, writableHighWaterMark: getDefaultHighWaterMark(writableObjectMode), readableObjectMode, readableHighWaterMark: getDefaultHighWaterMark(readableObjectMode), transform(chunk, encoding, done) { pushChunks(transformChunk.bind(undefined, chunk, generators, 0), this, done); }, flush(done) { pushChunks(finalChunks.bind(undefined, generators), this, done); },});
const pushChunks = callbackify(async (getChunks, transformStream) => { for await (const chunk of getChunks()) { transformStream.push(chunk); }});
// For each new chunk, apply each `transform()` methodconst transformChunk = async function * (chunk, generators, index) { if (index === generators.length) { yield chunk; return; }
const {transform} = generators[index]; for await (const transformedChunk of transform(chunk)) { yield * transformChunk(transformedChunk, generators, index + 1); }};
// At the end, apply each `final()` method, followed by the `transform()` method of the next transformsconst finalChunks = async function * (generators) { for (const [index, {final}] of Object.entries(generators)) { yield * generatorFinalChunks(final, Number(index), generators); }};
const generatorFinalChunks = async function * (final, index, generators) { if (final === undefined) { return; }
for await (const finalChunk of final()) { yield * transformChunk(finalChunk, generators, index + 1); }};modified:test/stdio/generator.js+43 added-14 removed
1 import {Buffer} from 'node:buffer';2 import {readFile, writeFile, rm} from 'node:fs/promises';3 import {getDefaultHighWaterMark, PassThrough} from 'node:stream';4-import {setTimeout, setImmediate} from 'node:timers/promises';4+import {setTimeout, scheduler} from 'node:timers/promises';5 import test from 'ava';6 import getStream, {getStreamAsArray} from 'get-stream';7 import tempfile from 'tempfile';8 import {execa, execaSync} from '../../index.js';282 unmodified lines291 test('Cannot use generators with sync methods and stdout', testSyncMethods, 1);292 test('Cannot use generators with sync methods and stderr', testSyncMethods, 2);293 test('Cannot use generators with sync methods and stdio[*]', testSyncMethods, 3);294 295-const repeatHighWaterMark = 10;295+const repeatCount = getDefaultHighWaterMark() * 3;296 297 const writerGenerator = function * () {298- for (let index = 0; index < getDefaultHighWaterMark() * repeatHighWaterMark; index += 1) {298+ for (let index = 0; index < repeatCount; index += 1) {299 yield '\n';300 }301 };302 303-const getLengthGenerator = function * (chunk) {304- yield `${chunk.length}`;303+const getLengthGenerator = function * (t, chunk) {304+ t.is(chunk.length, 1);305+ yield chunk;306 };307 308 const testHighWaterMark = async (t, passThrough, binary, objectMode) => {309 const {stdout} = await execa('noop.js', {310 stdout: [311 ...(objectMode ? [outputObjectGenerator] : []),312 writerGenerator,313 ...(passThrough ? [noopGenerator(false, binary)] : []),313- {transform: getLengthGenerator, binary: true},314+ {transform: getLengthGenerator.bind(undefined, t), binary: true, objectMode: true},315 ],316 });316- t.is(stdout, `${getDefaultHighWaterMark()}`.repeat(repeatHighWaterMark));317+ t.is(stdout.length, repeatCount);318+ t.true(stdout.every(chunk => chunk.toString() === '\n'));319 };320 319-test('Stream respects highWaterMark, no passThrough', testHighWaterMark, false, false, false);320-test('Stream respects highWaterMark, line-wise passThrough', testHighWaterMark, true, false, false);321-test('Stream respects highWaterMark, binary passThrough', testHighWaterMark, true, true, false);322-test('Stream respects highWaterMark, objectMode as input but not output', testHighWaterMark, false, false, true);321+test('Synchronous yields are not buffered, no passThrough', testHighWaterMark, false, false, false);322+test('Synchronous yields are not buffered, line-wise passThrough', testHighWaterMark, true, false, false);323+test('Synchronous yields are not buffered, binary passThrough', testHighWaterMark, true, true, false);324+test('Synchronous yields are not buffered, objectMode as input but not output', testHighWaterMark, false, false, true);325 326 const getTypeofGenerator = objectMode => ({327 * transform(line) {328 yield Object.prototype.toString.call(line);152 unmodified lines481 482 const testMultibyte = async (t, objectMode) => {483 const childProcess = execa('stdin.js', {stdin: noopGenerator(objectMode)});484 childProcess.stdin.write(multibyteUint8Array.slice(0, breakingLength));483- await setImmediate();485+ await scheduler.yield();486 childProcess.stdin.end(multibyteUint8Array.slice(breakingLength));487 const {stdout} = await childProcess;488 t.is(stdout, multibyteString);489 };23 unmodified lines513 const suffix = ' <';514 515 const multipleYieldGenerator = async function * (line = foobarString) {516 yield prefix;515- await setImmediate();517+ await scheduler.yield();518 yield line;517- await setImmediate();519+ await scheduler.yield();520 yield suffix;521 };522 523 const testMultipleYields = async (t, final) => {3 unmodified lines527 528 test('Generator can yield "transform" multiple times at different moments', testMultipleYields, false);529 test('Generator can yield "final" multiple times at different moments', testMultipleYields, true);530 531+const partsPerChunk = 4;532+const chunksPerCall = 10;533+const callCount = 5;534+const fullString = '\n'.repeat(getDefaultHighWaterMark(false) / partsPerChunk);535+536+const yieldFullStrings = function * () {537+ yield * Array.from({length: partsPerChunk * chunksPerCall}).fill(fullString);538+};539+540+const manyYieldGenerator = async function * () {541+ for (let index = 0; index < callCount; index += 1) {542+ yield * yieldFullStrings();543+ // eslint-disable-next-line no-await-in-loop544+ await scheduler.yield();545+ }546+};547+548+const testManyYields = async (t, final) => {549+ const childProcess = execa('noop.js', {stdout: convertTransformToFinal(manyYieldGenerator, final), buffer: false});550+ const [chunks] = await Promise.all([getStreamAsArray(childProcess.stdout), childProcess]);551+ const expectedChunk = Buffer.alloc(getDefaultHighWaterMark(false) * chunksPerCall).fill('\n');552+ t.deepEqual(chunks, Array.from({length: callCount}).fill(expectedChunk));553+};554+555+test('Generator "transform" yields are sent right away', testManyYields, false);556+test('Generator "final" yields are sent right away', testManyYields, true);557+558 const testInputFile = async (t, getOptions, reversed) => {559 const filePath = tempfile();560 await writeFile(filePath, foobarString);561 const {stdin, ...options} = getOptions(filePath);142 unmodified lines