GeezerVison is showing github.com — stream: check stream/iter pipe writes more cheaply · nodejs/node@b360014
File treeExpand file treeCollapse file tree Open diff view settings lib/internal/streams/iter
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: lib/internal/streams/iter/pull.js +40Lines changed: 40 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -62,10 +62,13 @@ const { | 62 | 62 | kResolvedPromise, | 63 | 63 | kStart, | 64 | 64 | callWithByteView, | | 65 | + checkFixedBatchChunk, | 65 | 66 | createBatchEntry, | 66 | 67 | createOperationQueue, | | 68 | + fixedBatchToEntry, | 67 | 69 | isTransformObject, | 68 | 70 | parsePullArgs, | | 71 | + snapshotFixedBatch, | 69 | 72 | snapshotTransform, | 70 | 73 | toUint8Array, | 71 | 74 | validateBatchEntry, | @@ -1546,6 +1549,24 @@ function pipeToSync(source, ...args) { | 1546 | 1549 | totalBytes += TypedArrayPrototypeGetByteLength(chunk); | 1547 | 1550 | continue; | 1548 | 1551 | } | | 1552 | + if (!hasWritevSync) { | | 1553 | + // Chunks written one at a time: snapshot them without an object for | | 1554 | + // every chunk when possible. | | 1555 | + const fixed = snapshotFixedBatch(batch); | | 1556 | + if (fixed !== null) { | | 1557 | + for (let i = 0; i < batch.length; i++) { | | 1558 | + const chunk = checkFixedBatchChunk(fixed, i); | | 1559 | + const accepted = writer.writeSync(chunk); | | 1560 | + checkFixedBatchChunk(fixed, i); | | 1561 | + if (accepted === false) { | | 1562 | + throw new ERR_OUT_OF_RANGE( | | 1563 | + 'write', 'within byte budget', 'budget exhausted'); | | 1564 | + } | | 1565 | + totalBytes += fixed.byteLengths[i]; | | 1566 | + } | | 1567 | + continue; | | 1568 | + } | | 1569 | + } | 1549 | 1570 | const entry = createBatchEntry(batch); | 1550 | 1571 | if (hasWritevSync && batch.length > 1) { | 1551 | 1572 | const accepted = writer.writevSync(validateBatchEntry(entry)); | @@ -1672,6 +1693,21 @@ async function pipeTo(source, ...args) { | 1672 | 1693 | // Write a batch using try-fallback: sync first, async if needed. | 1673 | 1694 | // Returns undefined on sync success, or a Promise when async fallback | 1674 | 1695 | // is required. Callers must check: const p = writeBatch(b); if (p) await p; | | 1696 | + // Write a FixedBatch with writeSync(), like the loop at the end of | | 1697 | + // writeBatch(), falling back to the async path for the rest of the batch. | | 1698 | + function writeFixedBatch(fixed) { | | 1699 | + const { chunks } = fixed; | | 1700 | + for (let i = 0; i < chunks.length; i++) { | | 1701 | + const chunk = checkFixedBatchChunk(fixed, i); | | 1702 | + if (!writer.writeSync(chunk)) { | | 1703 | + checkFixedBatchChunk(fixed, i); | | 1704 | + return writeBatchAsyncFallback(fixedBatchToEntry(fixed), i); | | 1705 | + } | | 1706 | + checkFixedBatchChunk(fixed, i); | | 1707 | + totalBytes += fixed.byteLengths[i]; | | 1708 | + } | | 1709 | + } | | 1710 | + | 1675 | 1711 | function writeBatch(batch) { | 1676 | 1712 | // Single chunk, the common case: check the view around writeSync() | 1677 | 1713 | // without allocating a batch entry, and create one only to fall back to | @@ -1684,6 +1720,10 @@ async function pipeTo(source, ...args) { | 1684 | 1720 | } | 1685 | 1721 | return writeBatchAsyncFallback(createBatchEntry(batch), 0); | 1686 | 1722 | } | | 1723 | + if (!hasWritev && hasWriteSync) { | | 1724 | + const fixed = snapshotFixedBatch(batch); | | 1725 | + if (fixed !== null) return writeFixedBatch(fixed); | | 1726 | + } | 1687 | 1727 | const entry = createBatchEntry(batch); | 1688 | 1728 | if (hasWritev && batch.length > 1) { | 1689 | 1729 | if (!hasWritevSync || | |
Collapse file Copy file name to clipboardExpand all lines: lib/internal/streams/iter/utils.js +79Lines changed: 79 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -468,6 +468,20 @@ function validateByteView(snapshot) { | 468 | 468 | */ | 469 | 469 | function callWithByteView(value, method, receiver) { | 470 | 470 | const buffer = TypedArrayPrototypeGetBuffer(value); | | 471 | + if (!isSharedArrayBuffer(buffer) && !ArrayBufferPrototypeGetResizable(buffer)) { | | 472 | + // A non-empty view of a fixed-length, non-shared ArrayBuffer can only | | 473 | + // change by the buffer being detached, which makes its byteLength 0 (see | | 474 | + // FixedByteView), so checking its byteLength is enough. | | 475 | + const byteLength = TypedArrayPrototypeGetByteLength(value); | | 476 | + if (byteLength !== 0) { | | 477 | + const result = FunctionPrototypeCall(method, receiver, value); | | 478 | + if (TypedArrayPrototypeGetByteLength(value) !== byteLength) { | | 479 | + throw new ERR_INVALID_STATE.TypeError( | | 480 | + 'Byte view was resized or detached after being accepted'); | | 481 | + } | | 482 | + return result; | | 483 | + } | | 484 | + } | 471 | 485 | if (isSharedArrayBuffer(buffer)) { | 472 | 486 | const snapshot = snapshotByteView(value); | 473 | 487 | const result = FunctionPrototypeCall(method, receiver, value); | @@ -607,6 +621,68 @@ function validateRecordedChunks(chunks, checks) { | 607 | 621 | return chunks; | 608 | 622 | } | 609 | 623 |
| | 624 | +// A batch accepted for writing one chunk at a time: its chunks, and their | | 625 | +// byteLengths when accepted (see snapshotFixedBatch()). | | 626 | +function FixedBatch(chunks, byteLengths, byteLength) { | | 627 | + this.chunks = chunks; | | 628 | + this.byteLengths = byteLengths; | | 629 | + this.byteLength = byteLength; | | 630 | +} | | 631 | +FixedBatch.prototype = ObjectFreeze({ __proto__: null }); | | 632 | + | | 633 | +/** | | 634 | + * Snapshot a batch of Uint8Arrays like createBatchEntry(), without an object | | 635 | + * for every chunk, when every chunk is a non-empty view of a fixed-length, | | 636 | + * non-shared ArrayBuffer: such views can only change by being detached, | | 637 | + * which makes their byteLength 0 (see FixedByteView), so their byteLengths | | 638 | + * are all that needs to be recorded. Check a chunk with checkFixedBatchChunk() | | 639 | + * before and after using it. | | 640 | + * @param {Uint8Array[]} chunks | | 641 | + * @returns {FixedBatch|null} null if a chunk needs a full snapshot. | | 642 | + */ | | 643 | +function snapshotFixedBatch(chunks) { | | 644 | + const count = chunks.length; | | 645 | + const byteLengths = new Array(count); | | 646 | + let byteLength = 0; | | 647 | + let checkedBuffer; | | 648 | + for (let i = 0; i < count; i++) { | | 649 | + const view = chunks[i]; | | 650 | + const buffer = TypedArrayPrototypeGetBuffer(view); | | 651 | + // Chunks often share a buffer: check each buffer once. | | 652 | + if (buffer !== checkedBuffer) { | | 653 | + if (isSharedArrayBuffer(buffer) || | | 654 | + ArrayBufferPrototypeGetResizable(buffer)) { | | 655 | + return null; | | 656 | + } | | 657 | + checkedBuffer = buffer; | | 658 | + } | | 659 | + const length = TypedArrayPrototypeGetByteLength(view); | | 660 | + if (length === 0) return null; | | 661 | + byteLengths[i] = length; | | 662 | + byteLength += length; | | 663 | + } | | 664 | + return new FixedBatch(ArrayPrototypeSlice(chunks), byteLengths, byteLength); | | 665 | +} | | 666 | + | | 667 | +function checkFixedBatchChunk(batch, index) { | | 668 | + const chunk = batch.chunks[index]; | | 669 | + if (TypedArrayPrototypeGetByteLength(chunk) !== batch.byteLengths[index]) { | | 670 | + throw new ERR_INVALID_STATE.TypeError( | | 671 | + 'Byte view was resized or detached after being accepted'); | | 672 | + } | | 673 | + return chunk; | | 674 | +} | | 675 | + | | 676 | +// The batch entry of a FixedBatch, to continue writing it asynchronously. | | 677 | +function fixedBatchToEntry(batch) { | | 678 | + const { chunks, byteLengths } = batch; | | 679 | + const views = new Array(chunks.length); | | 680 | + for (let i = 0; i < chunks.length; i++) { | | 681 | + views[i] = new FixedByteView(chunks[i], byteLengths[i]); | | 682 | + } | | 683 | + return new BatchEntry(views, batch.byteLength); | | 684 | +} | | 685 | + | 610 | 686 | function createBatchEntry(chunks) { | 611 | 687 | const views = new Array(chunks.length); | 612 | 688 | let byteLength = 0; | @@ -870,7 +946,10 @@ module.exports = { | 870 | 946 | concatBytes, | 871 | 947 | createOperationQueue, | 872 | 948 | convertChunks, | | 949 | + checkFixedBatchChunk, | 873 | 950 | createBatchEntry, | | 951 | + fixedBatchToEntry, | | 952 | + snapshotFixedBatch, | 874 | 953 | recordChunk, | 875 | 954 | splitBatchEntry, | 876 | 955 | getProtocolMethod, | |
Collapse file Copy file name to clipboardExpand all lines: test/parallel/test-stream-iter-resizable-buffers.js +48Lines changed: 48 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -210,6 +210,53 @@ async function testPipeRejectsSyncWriteDetachOrResize() { | 210 | 210 | assert.deepStrictEqual(written, [chunk]); | 211 | 211 | } | 212 | 212 |
| | 213 | +// Batches of several chunks written one at a time are checked against the | | 214 | +// byteLengths recorded when the batch was accepted, before and after each | | 215 | +// writeSync(). Detaching a later chunk, or the chunk being written, must be | | 216 | +// rejected. | | 217 | +async function testPipeRejectsDetachInMultiChunkBatch() { | | 218 | + for (const detachIndex of [1, 0]) { | | 219 | + const asyncBuffers = [new ArrayBuffer(2), new ArrayBuffer(2)]; | | 220 | + const asyncWritten = []; | | 221 | + await assert.rejects(pipeTo([asyncBuffers.map((b) => new Uint8Array(b))], { | | 222 | + writeSync(chunk) { | | 223 | + asyncWritten.push(chunk.byteLength); | | 224 | + if (asyncWritten.length === 1) asyncBuffers[detachIndex].transfer(); | | 225 | + return true; | | 226 | + }, | | 227 | + write: common.mustNotCall(), | | 228 | + fail: common.mustCall(), | | 229 | + }), kResizeError); | | 230 | + assert.deepStrictEqual(asyncWritten, [2]); | | 231 | + | | 232 | + const syncBuffers = [new ArrayBuffer(2), new ArrayBuffer(2)]; | | 233 | + const syncWritten = []; | | 234 | + assert.throws(() => pipeToSync([syncBuffers.map((b) => new Uint8Array(b))], { | | 235 | + writeSync(chunk) { | | 236 | + syncWritten.push(chunk.byteLength); | | 237 | + if (syncWritten.length === 1) syncBuffers[detachIndex].transfer(); | | 238 | + return true; | | 239 | + }, | | 240 | + fail: common.mustCall(), | | 241 | + }, { preventClose: true }), kResizeError); | | 242 | + assert.deepStrictEqual(syncWritten, [2]); | | 243 | + } | | 244 | + | | 245 | + // When writeSync() declines a chunk, pipeTo() writes the rest of the batch | | 246 | + // with write(). | | 247 | + const chunks = [Uint8Array.of(1), Uint8Array.of(2, 3), Uint8Array.of(4)]; | | 248 | + const written = []; | | 249 | + assert.strictEqual(await pipeTo([chunks], { | | 250 | + writeSync(chunk) { | | 251 | + if (chunk === chunks[1]) return false; | | 252 | + written.push(chunk); | | 253 | + return true; | | 254 | + }, | | 255 | + write(chunk) { written.push(chunk); }, | | 256 | + }, { preventClose: true }), 4); | | 257 | + assert.deepStrictEqual(written, chunks); | | 258 | +} | | 259 | + | 213 | 260 | async function testConsumersRejectDetachedViews() { | 214 | 261 | // Views of fixed-length buffers are tracked without a full snapshot; they | 215 | 262 | // must still be rejected when detached after being accepted. | @@ -249,4 +296,5 @@ Promise.all([ | 249 | 296 | testConsumersRejectDetachedViews(), | 250 | 297 | testPipeRejectsWriterResize(), | 251 | 298 | testPipeRejectsSyncWriteDetachOrResize(), | | 299 | + testPipeRejectsDetachInMultiChunkBatch(), | 252 | 300 | ]).then(common.mustCall()); |
|