|
| 1 | +'use strict'; |
| 2 | +// fs.readFileSync(fd, 'utf8') collects short reads in a growing string and |
| 3 | +// only moves to a heap buffer at the first full 8 KiB read. On a pipe, more |
| 4 | +// than 64 KiB (the heap buffer's first size) can arrive in short reads before |
| 5 | +// that happens. |
| 6 | +// Refs: https://github.com/nodejs/node/issues/66341 |
| 7 | +const common = require('../common'); |
| 8 | + |
| 9 | +if (!common.isLinux) |
| 10 | + common.skip('Paces the writes with /proc/<pid>/io.'); |
| 11 | + |
| 12 | +const assert = require('assert'); |
| 13 | +const { spawn } = require('child_process'); |
| 14 | +const fs = require('fs'); |
| 15 | + |
| 16 | +const kShortWrite = 4000; |
| 17 | +const kShortWrites = 20; |
| 18 | +const kTail = 100_000; |
| 19 | +const expected = 'x'.repeat(kShortWrite * kShortWrites) + 'y'.repeat(kTail); |
| 20 | + |
| 21 | +if (process.argv[2] === 'child') { |
| 22 | + fs.writeSync(1, 'ready\n'); |
| 23 | + assert.strictEqual(fs.readFileSync(0, 'utf8'), expected); |
| 24 | + return; |
| 25 | +} |
| 26 | + |
| 27 | +// Bytes the process has received from read() and similar calls. |
| 28 | +function readBytes(pid) { |
| 29 | + const io = fs.readFileSync(`/proc/${pid}/io`, 'latin1'); |
| 30 | + return Number(/^rchar: (\d+)$/m.exec(io)[1]); |
| 31 | +} |
| 32 | + |
| 33 | +const child = spawn(process.execPath, [__filename, 'child'], { |
| 34 | + stdio: ['pipe', 'pipe', 'inherit'], |
| 35 | +}); |
| 36 | + |
| 37 | +child.stdout.once('data', common.mustCall(() => { |
| 38 | + // Each short write waits until the child, blocked in readFileSync(), has |
| 39 | + // read everything sent before it, so no two of them can be merged into a |
| 40 | + // full read. |
| 41 | + const start = readBytes(child.pid); |
| 42 | + let sent = 0; |
| 43 | + function writeNext() { |
| 44 | + if (readBytes(child.pid) - start < sent) { |
| 45 | + setTimeout(writeNext, 1); |
| 46 | + } else if (sent < kShortWrite * kShortWrites) { |
| 47 | + child.stdin.write('x'.repeat(kShortWrite)); |
| 48 | + sent += kShortWrite; |
| 49 | + setTimeout(writeNext, 1); |
| 50 | + } else { |
| 51 | + child.stdin.end('y'.repeat(kTail)); |
| 52 | + } |
| 53 | + } |
| 54 | + writeNext(); |
| 55 | +})); |
| 56 | + |
| 57 | +child.on('exit', common.mustCall((code, signal) => { |
| 58 | + assert.deepStrictEqual({ code, signal }, { code: 0, signal: null }); |
| 59 | +})); |