diff --git a/lib/internal/streams/fast-utf8-stream.js b/lib/internal/streams/fast-utf8-stream.js index e4d48c17c41d..8960f5056f8a 100644 --- a/lib/internal/streams/fast-utf8-stream.js +++ b/lib/internal/streams/fast-utf8-stream.js @@ -131,6 +131,10 @@ class Utf8Stream extends EventEmitter { #maxWriteRetries = 0; #writeRetries = 0; #writingBuf = ''; + // In utf8 mode, the bytes of a character that a partial write split and that + // are still to be written. Its leading bytes are already in the destination, + // so these must follow them before anything else is written. + #partialChar = kEmptyBuffer; #write; #flush; #flushSync; @@ -246,11 +250,20 @@ class Utf8Stream extends EventEmitter { this.#flush = (...args) => this.#flushUtf8(...args); this.#flushSync = (...args) => this.#flushSyncUtf8(...args); this.#actualWrite = (...args) => this.#actualWriteUtf8(...args); - this.#fsWriteSync = () => this.#fs.writeSync(this.#fd, this.#writingBuf, 'utf8'); + this.#fsWriteSync = () => { + if (this.#partialChar.length > 0) { + return this.#fs.writeSync(this.#fd, this.#partialChar); + } + return this.#fs.writeSync(this.#fd, this.#writingBuf, 'utf8'); + }; this.#fsWrite = () => { this.#writeInFlight = true; try { - this.#fs.write(this.#fd, this.#writingBuf, 'utf8', (err, n) => this.#writeDone(err, n)); + if (this.#partialChar.length > 0) { + this.#fs.write(this.#fd, this.#partialChar, (err, n) => this.#writeDone(err, n)); + } else { + this.#fs.write(this.#fd, this.#writingBuf, 'utf8', (err, n) => this.#writeDone(err, n)); + } } catch (err) { this.#writeInFlight = false; throw err; @@ -385,7 +398,7 @@ class Utf8Stream extends EventEmitter { return; } - if (this.#len > 0 && this.#fd >= 0) { + if ((this.#len > 0 || this.#partialChar.length > 0) && this.#fd >= 0) { this.#actualWrite(); } else { this.#finishEnding(); @@ -486,9 +499,7 @@ class Utf8Stream extends EventEmitter { this.#writeRetries = 0; } - const releasedBufObj = releaseWritingBuf(this.#writingBuf, this.#len, n); - this.#len = releasedBufObj.len; - this.#writingBuf = releasedBufObj.writingBuf; + this.#releaseWritten(n); // Emit 'write' after the written bytes have been released so that a // listener calling flushSync() sees a consistent state with no I/O in @@ -500,7 +511,7 @@ class Utf8Stream extends EventEmitter { this.#emittingWrite = false; } - if (this.#writingBuf.length) { + if (this.#writingBuf.length || this.#partialChar.length) { if (!this.#sync) { this.#fsWrite(); return; @@ -508,11 +519,8 @@ class Utf8Stream extends EventEmitter { try { do { - const n = this.#fsWriteSync(); - const releasedBufObj = releaseWritingBuf(this.#writingBuf, this.#len, n); - this.#len = releasedBufObj.len; - this.#writingBuf = releasedBufObj.writingBuf; - } while (this.#writingBuf.length); + this.#releaseWritten(this.#fsWriteSync()); + } while (this.#writingBuf.length || this.#partialChar.length); } catch (err) { this.#release(err); return; @@ -556,6 +564,22 @@ class Utf8Stream extends EventEmitter { } } + /** + * Accounts for the `n` bytes that the last write of #partialChar or + * #writingBuf committed. + * @param {number} n + */ + #releaseWritten(n) { + if (this.#partialChar.length > 0) { + this.#partialChar = this.#partialChar.subarray(n); + return; + } + const releasedBufObj = releaseWritingBuf(this.#writingBuf, this.#len, n); + this.#len = releasedBufObj.len; + this.#writingBuf = releasedBufObj.writingBuf; + this.#partialChar = releasedBufObj.partialChar; + } + #openFile(file) { this.#opening = true; this.#writing = true; @@ -656,7 +680,7 @@ class Utf8Stream extends EventEmitter { #finishEnding() { if (!this.#ending || this.#writing || this.#destroyed) return; - if (this.#len > 0) { + if (this.#len > 0 || this.#partialChar.length > 0) { this.#actualWrite(); return; } @@ -732,7 +756,8 @@ class Utf8Stream extends EventEmitter { } // destroy() may have dropped buffered data or a failed write. - if (this.#ending && !this.#writing && this.#len === 0) { + if (this.#ending && !this.#writing && this.#len === 0 && + this.#partialChar.length === 0) { this.emit('finish'); } this.emit('close'); @@ -780,7 +805,7 @@ class Utf8Stream extends EventEmitter { if (this.#sync) { try { - const written = this.#fs.writeSync(this.#fd, this.#writingBuf, 'utf8'); + const written = this.#fsWriteSync(); this.#release(null, written); } catch (err) { this.#release(err); @@ -838,8 +863,9 @@ class Utf8Stream extends EventEmitter { this.reopen(); } else if (this.#ending) { this.#finishEnding(); - } else if (this.#len > 0 && - (this.#len > this.#minLength || this.#flushPending)) { + } else if (this.#partialChar.length > 0 || + (this.#len > 0 && + (this.#len > this.#minLength || this.#flushPending))) { this.#actualWrite(); } else { this.#emitDrain(); @@ -915,19 +941,33 @@ class Utf8Stream extends EventEmitter { this.#writingBuf = ''; } + // The rest of a split character goes out before any queued string. While + // an fs.write() is in flight it is left to that write, like #writingBuf. + let partialChar = kEmptyBuffer; + if (state !== kFlushSyncInFlight) { + partialChar = this.#partialChar; + this.#partialChar = kEmptyBuffer; + } + + // The string being written is taken out of #bufs and, if a write throws, + // what is left of it is put back. let buf = ''; - while (this.#bufs.length || buf) { - if (buf.length <= 0) { - buf = this.#bufs[0]; + while (this.#bufs.length || buf.length || partialChar.length) { + if (buf.length <= 0 && partialChar.length <= 0) { + buf = this.#bufs.shift(); } try { - const n = this.#fs.writeSync(this.#fd, buf, 'utf8'); - this.#writeRetries = 0; - const releasedBufObj = releaseWritingBuf(buf, this.#len, n); - buf = releasedBufObj.writingBuf; - this.#len = releasedBufObj.len; - if (buf.length <= 0) { - this.#bufs.shift(); + if (partialChar.length > 0) { + const n = this.#fs.writeSync(this.#fd, partialChar); + this.#writeRetries = 0; + partialChar = partialChar.subarray(n); + } else { + const n = this.#fs.writeSync(this.#fd, buf, 'utf8'); + this.#writeRetries = 0; + const releasedBufObj = releaseWritingBuf(buf, this.#len, n); + buf = releasedBufObj.writingBuf; + this.#len = releasedBufObj.len; + partialChar = releasedBufObj.partialChar; } } catch (err) { const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'; @@ -936,6 +976,13 @@ class Utf8Stream extends EventEmitter { } const retriesExhausted = this.#maxWriteRetries > 0 && this.#writeRetries > this.#maxWriteRetries; if (!shouldRetry || retriesExhausted || !this.#retryEAGAIN(err, buf.length, this.#len - buf.length)) { + if (buf.length > 0) { + ArrayPrototypeUnshift(this.#bufs, buf); + } + if (state !== kFlushSyncInFlight) { + // Keep the rest of the character so that a later write completes it. + this.#partialChar = partialChar; + } throw err; } @@ -1048,7 +1095,8 @@ class Utf8Stream extends EventEmitter { throw error; } - if (this.#minLength <= 0 && !this.#writing && this.#len === 0) { + if (this.#minLength <= 0 && !this.#writing && this.#len === 0 && + this.#partialChar.length === 0) { cb?.(); return; } @@ -1150,9 +1198,11 @@ class Utf8Stream extends EventEmitter { * @param {string | Buffer} writingBuf - currently writing buffer, usually be instance._writingBuf. * @param {number} len - currently buffer length, usually be instance._len. * @param {number} n - number of bytes fs already written - * @returns {{writingBuf: string | Buffer, len: number}} released writingBuf and length + * @returns {{writingBuf: string | Buffer, len: number, partialChar: Buffer}} released writingBuf + * and length, and the unwritten bytes of the character that the write split, if any */ function releaseWritingBuf(writingBuf, len, n) { + let partialChar = kEmptyBuffer; if (typeof writingBuf === 'string') { const byteLength = Buffer.byteLength(writingBuf); // `fs.write` returns the number of bytes written, but `len` is tracked in @@ -1162,22 +1212,26 @@ function releaseWritingBuf(writingBuf, len, n) { // The whole string was written: advance past every character. n = writingBuf.length; } else { - // A partial write may split a multi-byte UTF-8 character, so we must back - // up to the start of that character to avoid data corruption. const buf = Buffer.from(writingBuf); - // Back up from position n to find a valid UTF-8 character boundary. - // UTF-8 continuation bytes have the pattern 10xxxxxx (0x80-0xBF). - // We need to find the start of the character that was split. - while (n > 0 && (buf[n] & 0xC0) === 0x80) { - n--; + // UTF-8 continuation bytes have the pattern 10xxxxxx (0x80-0xBF). If the + // first unwritten byte is one, the write split a multi-byte character. + // Its leading bytes are already in the destination and can't be taken + // back, so writing the character again would duplicate them. Release the + // whole character and hand its unwritten bytes back to the caller. + let end = n; + while (end < byteLength && (buf[end] & 0xC0) === 0x80) { + end++; + } + if (end > n) { + partialChar = buf.subarray(n, end); } // Decode the properly-aligned bytes to get the character count. - n = buf.subarray(0, n).toString().length; + n = buf.subarray(0, end).toString().length; } } len = MathMax(len - n, 0); writingBuf = writingBuf.slice(n); - return { writingBuf, len }; + return { writingBuf, len, partialChar }; } function mergeBuf(bufs, len) { diff --git a/test/parallel/test-fastutf8stream-partial-write-utf8.js b/test/parallel/test-fastutf8stream-partial-write-utf8.js index 3a56fcf71a7b..eb04dc4db47c 100644 --- a/test/parallel/test-fastutf8stream-partial-write-utf8.js +++ b/test/parallel/test-fastutf8stream-partial-write-utf8.js @@ -1,14 +1,16 @@ 'use strict'; -// Tests for UTF-8 character preservation when partial writes split multi-byte characters. +// Tests that no byte is lost or written twice when a partial write splits a +// multi-byte UTF-8 character. // See: https://github.com/nodejs/node/issues/61744 +// See: https://github.com/nodejs/node/issues/67679 const common = require('../common'); const tmpdir = require('../common/tmpdir'); const assert = require('node:assert'); const { openSync, - write, + readFileSync, writeSync, } = require('node:fs'); const { Utf8Stream } = require('node:fs'); @@ -26,297 +28,175 @@ function getTempFile() { return join(tmpdir.path, `fastutf8stream-partial-${process.pid}-${Date.now()}-${fileCounter++}.log`); } -runTests(false); -runTests(true); - -function runTests(sync) { - // Test 1: Partial write splitting a 3-byte UTF-8 character (CJK) - // "abc中def" where "中" is 3 bytes (E4 B8 AD) - // Simulate partial write of 4 bytes: "abc" (3 bytes) + first byte of "中" - // The remaining buffer should be "中def" (not "def") - { - const dest = getTempFile(); - const fd = openSync(dest, 'w'); - - let firstWrite = true; - const writtenChunks = []; - const fsOverride = {}; - - if (sync) { - fsOverride.writeSync = common.mustCall((...args) => { - const data = args[1]; - writtenChunks.push(typeof data === 'string' ? data : data.toString()); - if (firstWrite) { - firstWrite = false; - // Simulate partial write: only 4 bytes written out of 9 - // This splits the 3-byte "中" character - return 4; - } - return writeSync(...args); - }, 2); - } else { - fsOverride.write = common.mustCall((...args) => { - const data = args[1]; - writtenChunks.push(typeof data === 'string' ? data : data.toString()); - const callback = args[args.length - 1]; - if (firstWrite) { - firstWrite = false; - // Simulate partial write: only 4 bytes written out of 9 - process.nextTick(callback, null, 4); - return; - } - return write(...args); - }, 2); +// Returns write() and writeSync() replacements whose first calls are short +// writes: call number i commits at most limits[i] bytes to the fd and reports +// that count, the way a full pipe or disk does. A limit that is an Error makes +// that call fail with it instead. Later calls write everything. +function shortWrites(limits) { + limits = [...limits]; + + function commit(fd, data) { + const bytes = Buffer.from(data); + const limit = limits.length > 0 ? limits.shift() : bytes.length; + if (limit instanceof Error) { + throw limit; } - - const stream = new Utf8Stream({ - fd, - sync, - minLength: 0, - fs: fsOverride, - }); - - stream.on('ready', common.mustCall(() => { - stream.write('abc中def'); - stream.end(); - - stream.on('finish', common.mustCall(() => { - // Verify the second chunk contains the preserved CJK character - assert.strictEqual(writtenChunks.length, 2); - assert.strictEqual(writtenChunks[0], 'abc中def'); // First attempt - assert.strictEqual(writtenChunks[1], '中def'); // Retry with preserved char - })); - })); + const chunk = bytes.subarray(0, limit); + let written = 0; + while (written < chunk.length) { + written += writeSync(fd, chunk, written); + } + return written; } - // Test 2: Partial write splitting a 4-byte UTF-8 character (emoji) - // "hello🌍world" where "🌍" is 4 bytes (F0 9F 8C 8D) - // Simulate partial write of 7 bytes: "hello" (5 bytes) + first 2 bytes of "🌍" - // The remaining buffer should be "🌍world" (not a lone surrogate + "world") - { - const dest = getTempFile(); - const fd = openSync(dest, 'w'); + return { + write(fd, data, ...args) { + const callback = args.at(-1); + let written; + try { + written = commit(fd, data); + } catch (err) { + process.nextTick(callback, err); + return; + } + process.nextTick(callback, null, written); + }, + writeSync(fd, data) { + return commit(fd, data); + }, + }; +} - let firstWrite = true; - const writtenChunks = []; - const fsOverride = {}; +const cases = [ + // "中" is e4 b8 ad. The first write stops after its first byte. + { text: 'abc中def', limits: [4] }, + // The first write stops after the second byte of "中". + { text: 'abc中def', limits: [5] }, + // "é" is c3 a9. The first write stops between its two bytes. + { text: 'café!', limits: [4] }, + // "🌍" is f0 9f 8c 8d. The first write stops in the middle of it. + { text: 'hello🌍world', limits: [7] }, + // The rest of "🌍" also needs more than one write. + { text: 'hello🌍world', limits: [6, 1, 1] }, + // The whole string is a single character. + { text: '中', limits: [1] }, + // Nothing is written at first. + { text: '中文', limits: [0] }, + // The first write stops between two characters. + { text: 'abc中def', limits: [3] }, + // Every write commits a single byte. + { text: 'a中é🌍', limits: Array.from({ length: 40 }, () => 1) }, +]; + +for (const sync of [false, true]) { + for (const { text, limits } of cases) { + // Short writes while the stream writes on its own. + { + const dest = getTempFile(); + const fd = openSync(dest, 'w'); + const stream = new Utf8Stream({ fd, sync, minLength: 0, fs: shortWrites(limits) }); + + stream.on('ready', common.mustCall(() => { + stream.write(text); + stream.write(text); + stream.end(); + })); - if (sync) { - fsOverride.writeSync = common.mustCall((...args) => { - const data = args[1]; - writtenChunks.push(typeof data === 'string' ? data : data.toString()); - if (firstWrite) { - firstWrite = false; - // Simulate partial write: only 7 bytes written - return 7; - } - return writeSync(...args); - }, 2); - } else { - fsOverride.write = common.mustCall((...args) => { - const data = args[1]; - writtenChunks.push(typeof data === 'string' ? data : data.toString()); - const callback = args[args.length - 1]; - if (firstWrite) { - firstWrite = false; - process.nextTick(callback, null, 7); - return; - } - return write(...args); - }, 2); + stream.on('finish', common.mustCall()); + stream.on('close', common.mustCall(() => { + assert.strictEqual(readFileSync(dest, 'utf8'), text + text); + })); } - const stream = new Utf8Stream({ - fd, - sync, - minLength: 0, - fs: fsOverride, - }); - - stream.on('ready', common.mustCall(() => { - stream.write('hello🌍world'); - stream.end(); - - stream.on('finish', common.mustCall(() => { - assert.strictEqual(writtenChunks.length, 2); - assert.strictEqual(writtenChunks[0], 'hello🌍world'); // First attempt - assert.strictEqual(writtenChunks[1], '🌍world'); // Retry with preserved emoji + // Short writes during flushSync(). + { + const dest = getTempFile(); + const fd = openSync(dest, 'w'); + const stream = new Utf8Stream({ fd, sync, minLength: 4096, fs: shortWrites(limits) }); + + stream.on('ready', common.mustCall(() => { + stream.write(text); + stream.write(text); + stream.flushSync(); + assert.strictEqual(readFileSync(dest, 'utf8'), text + text); + stream.end(); + })); - // Verify no lone surrogates in the retry chunk - const retryChunk = writtenChunks[1]; - for (let i = 0; i < retryChunk.length; i++) { - const code = retryChunk.charCodeAt(i); - if (code >= 0xD800 && code <= 0xDBFF) { - // High surrogate - next must be low surrogate - const next = retryChunk.charCodeAt(i + 1); - assert.ok(next >= 0xDC00 && next <= 0xDFFF, - `Found lone high surrogate at position ${i}`); - i++; // Skip the low surrogate we just verified - } else if (code >= 0xDC00 && code <= 0xDFFF) { - // Low surrogate without preceding high surrogate - assert.fail(`Found lone low surrogate at position ${i}: 0x${code.toString(16)}`); - } - } + stream.on('close', common.mustCall(() => { + assert.strictEqual(readFileSync(dest, 'utf8'), text + text); })); - })); + } } +} - // Test 3: Partial write at exactly 0 bytes (edge case) +for (const sync of [false, true]) { + // A 'write' listener queues more data and calls flushSync() while the rest + // of a split character is still to be written. { const dest = getTempFile(); const fd = openSync(dest, 'w'); - - let firstWrite = true; - const writtenChunks = []; - const fsOverride = {}; - - if (sync) { - fsOverride.writeSync = common.mustCall((...args) => { - const data = args[1]; - writtenChunks.push(typeof data === 'string' ? data : data.toString()); - if (firstWrite) { - firstWrite = false; - return 0; // No bytes written - } - return writeSync(...args); - }, 2); - } else { - fsOverride.write = common.mustCall((...args) => { - const data = args[1]; - writtenChunks.push(typeof data === 'string' ? data : data.toString()); - const callback = args[args.length - 1]; - if (firstWrite) { - firstWrite = false; - process.nextTick(callback, null, 0); - return; - } - return write(...args); - }, 2); - } - - const stream = new Utf8Stream({ - fd, - sync, - minLength: 0, - fs: fsOverride, - }); + const stream = new Utf8Stream({ fd, sync, minLength: 0, fs: shortWrites([1]) }); stream.on('ready', common.mustCall(() => { - stream.write('中文'); + stream.once('write', common.mustCall(() => { + stream.write('NEXT'); + stream.flushSync(); + assert.strictEqual(readFileSync(dest, 'utf8'), '中NEXT'); + })); + stream.write('中'); stream.end(); + })); - stream.on('finish', common.mustCall(() => { - assert.strictEqual(writtenChunks.length, 2); - assert.strictEqual(writtenChunks[0], '中文'); - assert.strictEqual(writtenChunks[1], '中文'); // Entire string retried - })); + stream.on('finish', common.mustCall()); + stream.on('close', common.mustCall(() => { + assert.strictEqual(readFileSync(dest, 'utf8'), '中NEXT'); })); } - // Test 4: Partial write splitting between characters (not mid-character) - // This should work the same as before - no character preservation needed + // Writing the rest of a split character fails once. The stream still has to + // write it before a flush succeeds or the stream finishes. { const dest = getTempFile(); const fd = openSync(dest, 'w'); - - let firstWrite = true; - const writtenChunks = []; - const fsOverride = {}; - - if (sync) { - fsOverride.writeSync = common.mustCall((...args) => { - const data = args[1]; - writtenChunks.push(typeof data === 'string' ? data : data.toString()); - if (firstWrite) { - firstWrite = false; - // Write exactly 3 bytes ("abc"), which is a clean character boundary - return 3; - } - return writeSync(...args); - }, 2); - } else { - fsOverride.write = common.mustCall((...args) => { - const data = args[1]; - writtenChunks.push(typeof data === 'string' ? data : data.toString()); - const callback = args[args.length - 1]; - if (firstWrite) { - firstWrite = false; - process.nextTick(callback, null, 3); - return; - } - return write(...args); - }, 2); - } - - const stream = new Utf8Stream({ - fd, - sync, - minLength: 0, - fs: fsOverride, - }); + const eio = Object.assign(new Error('EIO'), { code: 'EIO' }); + const stream = new Utf8Stream({ fd, sync, minLength: 0, fs: shortWrites([1, eio]) }); stream.on('ready', common.mustCall(() => { - stream.write('abc中def'); - stream.end(); - - stream.on('finish', common.mustCall(() => { - assert.strictEqual(writtenChunks.length, 2); - assert.strictEqual(writtenChunks[0], 'abc中def'); - assert.strictEqual(writtenChunks[1], '中def'); // Remaining after 3 bytes + stream.once('error', common.mustCall((err) => { + assert.strictEqual(err, eio); + assert.deepStrictEqual(readFileSync(dest), Buffer.from([0xe4])); + stream.flush(common.mustSucceed(() => { + assert.strictEqual(readFileSync(dest, 'utf8'), '中'); + })); + stream.end(); })); + stream.write('中'); + })); + + stream.on('finish', common.mustCall()); + stream.on('close', common.mustCall(() => { + assert.strictEqual(readFileSync(dest, 'utf8'), '中'); })); } - // Test 5: Single multi-byte character with partial write of 1 byte + // flushSync() fails while writing the rest of a split character. A later + // flushSync() writes the rest of it and then the rest of the string, once. { const dest = getTempFile(); const fd = openSync(dest, 'w'); - - let firstWrite = true; - const writtenChunks = []; - const fsOverride = {}; - - if (sync) { - fsOverride.writeSync = common.mustCall((...args) => { - const data = args[1]; - writtenChunks.push(typeof data === 'string' ? data : data.toString()); - if (firstWrite) { - firstWrite = false; - // Write only 1 byte of a 3-byte character - return 1; - } - return writeSync(...args); - }, 2); - } else { - fsOverride.write = common.mustCall((...args) => { - const data = args[1]; - writtenChunks.push(typeof data === 'string' ? data : data.toString()); - const callback = args[args.length - 1]; - if (firstWrite) { - firstWrite = false; - process.nextTick(callback, null, 1); - return; - } - return write(...args); - }, 2); - } - - const stream = new Utf8Stream({ - fd, - sync, - minLength: 0, - fs: fsOverride, - }); + const eio = Object.assign(new Error('EIO'), { code: 'EIO' }); + const stream = new Utf8Stream({ fd, sync, minLength: 4096, fs: shortWrites([4, eio]) }); stream.on('ready', common.mustCall(() => { - stream.write('中'); + stream.write('abc中def'); + assert.throws(() => stream.flushSync(), eio); + stream.flushSync(); + assert.strictEqual(readFileSync(dest, 'utf8'), 'abc中def'); stream.end(); + })); - stream.on('finish', common.mustCall(() => { - assert.strictEqual(writtenChunks.length, 2); - assert.strictEqual(writtenChunks[0], '中'); - assert.strictEqual(writtenChunks[1], '中'); // Full character retried - })); + stream.on('close', common.mustCall(() => { + assert.strictEqual(readFileSync(dest, 'utf8'), 'abc中def'); })); } }