This is an automated email from the ASF dual-hosted git repository. Xuanwo pushed a commit to branch xuanwo/fix-nodejs-exports-streams-and-sync-tests in repository https://gitbox.apache.org/repos/asf/opendal.git
commit 891c8e7b7519edfd6424b0ced9378198caf3d6ca Author: Xuanwo <[email protected]> AuthorDate: Tue Nov 24 02:47:16 2026 +0100 fix(bindings/nodejs): align CJS/ESM exports, stream error/encoding/destroy handling, and re-enable sync tests --- bindings/nodejs/index.cjs | 108 +++++++++++++---- bindings/nodejs/index.mjs | 83 ++++++++++--- bindings/nodejs/tests/entrypoint.test.mjs | 175 +++++++++++++++++++++++++++ bindings/nodejs/tests/suites/async.suite.mjs | 47 +++++++ bindings/nodejs/tests/suites/sync.suite.mjs | 101 +++++++++++++--- 5 files changed, 457 insertions(+), 57 deletions(-) diff --git a/bindings/nodejs/index.cjs b/bindings/nodejs/index.cjs index e4c5daacb9..9d7a61870e 100644 --- a/bindings/nodejs/index.cjs +++ b/bindings/nodejs/index.cjs @@ -21,6 +21,13 @@ const { Writable, Readable } = require('stream') +function toWriterInput(chunk, encoding) { + if (typeof chunk === 'string' && encoding && encoding !== 'utf8' && encoding !== 'utf-8') { + return Buffer.from(chunk, encoding) + } + return chunk +} + class ReadStream extends Readable { constructor(reader, options) { super(options) @@ -28,6 +35,9 @@ class ReadStream extends Readable { } async _read(size) { + if (this.destroyed || !this.reader) { + return + } try { // Node can request size 0 when highWaterMark is 0. const chunk = await this.reader.readChunk(Math.min(Math.max(size, 1), 0xffffffff)) @@ -52,19 +62,29 @@ class BlockingReadStream extends Readable { } _read(size) { + if (this.destroyed || !this.reader) { + return + } try { // Node can request size 0 when highWaterMark is 0. const buf = Buffer.alloc(Math.max(size, 1)) - let s = this.reader.read(buf) - if (s === 0n) { - this.push(null) - } else { - this.push(buf.subarray(0, Number(s))) + const s = this.reader.read(buf) + if (!this.destroyed) { + if (s === 0n) { + this.push(null) + } else { + this.push(buf.subarray(0, Number(s))) + } } - } catch (e) { - this.emit('error', e) + } catch (error) { + this.destroy(error) } } + + _destroy(error, callback) { + this.reader = null + callback(error) + } } class WriteStream extends Writable { @@ -74,13 +94,21 @@ class WriteStream extends Writable { } _write(chunk, encoding, callback) { + let data + try { + data = toWriterInput(chunk, encoding) + } catch (error) { + callback(error) + return + } + this.writer - .write(chunk) + .write(data) .then(() => { callback() }) - .catch((e) => { - callback(e) + .catch((error) => { + callback(error) }) } @@ -90,10 +118,15 @@ class WriteStream extends Writable { .then(() => { callback() }) - .catch((e) => { - callback(e) + .catch((error) => { + callback(error) }) } + + _destroy(error, callback) { + this.writer = null + callback(error) + } } class BlockingWriteStream extends Writable { @@ -104,10 +137,10 @@ class BlockingWriteStream extends Writable { _write(chunk, encoding, callback) { try { - this.writer.write(chunk) + this.writer.write(toWriterInput(chunk, encoding)) callback() - } catch (e) { - callback(e) + } catch (error) { + callback(error) } } @@ -115,21 +148,30 @@ class BlockingWriteStream extends Writable { try { this.writer.close() callback() - } catch (e) { - callback(e) + } catch (error) { + callback(error) } } + + _destroy(error, callback) { + this.writer = null + callback(error) + } } +const generated = require('./generated.js') const { - Operator, - RetryLayer, + CapabilityOverrideLayer, ConcurrentLimitLayer, + LoggingLayer, + RetryLayer, + ThrottleLayer, + TimeoutLayer, BlockingReader, Reader, BlockingWriter, Writer, -} = require('./generated.js') +} = generated BlockingReader.prototype.createReadStream = function (options) { return new BlockingReadStream(this, options) @@ -147,8 +189,30 @@ Writer.prototype.createWriteStream = function (options) { return new WriteStream(this, options) } -module.exports.Operator = Operator +module.exports = { ...generated } +module.exports.BlockingLister = generated.BlockingLister +module.exports.BlockingReader = generated.BlockingReader +module.exports.BlockingWriter = generated.BlockingWriter +module.exports.Capability = generated.Capability +module.exports.CapabilityOverrideLayer = generated.CapabilityOverrideLayer +module.exports.ConcurrentLimitLayer = generated.ConcurrentLimitLayer +module.exports.Entry = generated.Entry +module.exports.EntryMode = generated.EntryMode +module.exports.Layer = generated.Layer +module.exports.Lister = generated.Lister +module.exports.LoggingLayer = generated.LoggingLayer +module.exports.Metadata = generated.Metadata +module.exports.Operator = generated.Operator +module.exports.Reader = generated.Reader +module.exports.RetryLayer = generated.RetryLayer +module.exports.ThrottleLayer = generated.ThrottleLayer +module.exports.TimeoutLayer = generated.TimeoutLayer +module.exports.Writer = generated.Writer module.exports.layers = { - RetryLayer, + CapabilityOverrideLayer, ConcurrentLimitLayer, + LoggingLayer, + RetryLayer, + ThrottleLayer, + TimeoutLayer, } diff --git a/bindings/nodejs/index.mjs b/bindings/nodejs/index.mjs index 679a8872c8..7675b9856a 100644 --- a/bindings/nodejs/index.mjs +++ b/bindings/nodejs/index.mjs @@ -21,6 +21,13 @@ import { Writable, Readable } from 'node:stream' +function toWriterInput(chunk, encoding) { + if (typeof chunk === 'string' && encoding && encoding !== 'utf8' && encoding !== 'utf-8') { + return Buffer.from(chunk, encoding) + } + return chunk +} + class ReadStream extends Readable { constructor(reader, options) { super(options) @@ -28,6 +35,9 @@ class ReadStream extends Readable { } async _read(size) { + if (this.destroyed || !this.reader) { + return + } try { // Node can request size 0 when highWaterMark is 0. const chunk = await this.reader.readChunk(Math.min(Math.max(size, 1), 0xffffffff)) @@ -52,19 +62,29 @@ class BlockingReadStream extends Readable { } _read(size) { + if (this.destroyed || !this.reader) { + return + } try { // Node can request size 0 when highWaterMark is 0. const buf = Buffer.alloc(Math.max(size, 1)) - let s = this.reader.read(buf) - if (s === 0n) { - this.push(null) - } else { - this.push(buf.subarray(0, Number(s))) + const s = this.reader.read(buf) + if (!this.destroyed) { + if (s === 0n) { + this.push(null) + } else { + this.push(buf.subarray(0, Number(s))) + } } - } catch (e) { - this.emit('error', e) + } catch (error) { + this.destroy(error) } } + + _destroy(error, callback) { + this.reader = null + callback(error) + } } class WriteStream extends Writable { @@ -74,13 +94,21 @@ class WriteStream extends Writable { } _write(chunk, encoding, callback) { + let data + try { + data = toWriterInput(chunk, encoding) + } catch (error) { + callback(error) + return + } + this.writer - .write(chunk) + .write(data) .then(() => { callback() }) - .catch((e) => { - callback(e) + .catch((error) => { + callback(error) }) } @@ -90,10 +118,15 @@ class WriteStream extends Writable { .then(() => { callback() }) - .catch((e) => { - callback(e) + .catch((error) => { + callback(error) }) } + + _destroy(error, callback) { + this.writer = null + callback(error) + } } class BlockingWriteStream extends Writable { @@ -104,10 +137,10 @@ class BlockingWriteStream extends Writable { _write(chunk, encoding, callback) { try { - this.writer.write(chunk) + this.writer.write(toWriterInput(chunk, encoding)) callback() - } catch (e) { - callback(e) + } catch (error) { + callback(error) } } @@ -115,18 +148,25 @@ class BlockingWriteStream extends Writable { try { this.writer.close() callback() - } catch (e) { - callback(e) + } catch (error) { + callback(error) } } + + _destroy(error, callback) { + this.writer = null + callback(error) + } } import * as generated from './generated.js' const { - Operator, CapabilityOverrideLayer, - RetryLayer, ConcurrentLimitLayer, + LoggingLayer, + RetryLayer, + ThrottleLayer, + TimeoutLayer, BlockingReader, Reader, BlockingWriter, @@ -151,8 +191,11 @@ Writer.prototype.createWriteStream = function (options) { export const layers = { CapabilityOverrideLayer, - RetryLayer, ConcurrentLimitLayer, + LoggingLayer, + RetryLayer, + ThrottleLayer, + TimeoutLayer, } export * from './generated.js' diff --git a/bindings/nodejs/tests/entrypoint.test.mjs b/bindings/nodejs/tests/entrypoint.test.mjs new file mode 100644 index 0000000000..927641d5ae --- /dev/null +++ b/bindings/nodejs/tests/entrypoint.test.mjs @@ -0,0 +1,175 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { execFileSync } from 'node:child_process' +import { readFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { fileURLToPath } from 'node:url' +import { describe, expect, test } from 'vitest' + +import * as esm from '../index.mjs' + +const require = createRequire(import.meta.url) +const cjs = require('../index.cjs') +const cjsEntryPath = fileURLToPath(new URL('../index.cjs', import.meta.url)) +const generatedDtsPath = fileURLToPath(new URL('../generated.d.ts', import.meta.url)) + +function parseRuntimeExportsFromDts() { + const source = readFileSync(generatedDtsPath, 'utf8') + const names = [] + for (const match of source.matchAll(/^export declare (?:class|const enum) (\w+)/gm)) { + const name = match[1] + // ExternalObject is a type-only wrapper emitted by napi-rs. + if (name !== 'ExternalObject') { + names.push(name) + } + } + return names.sort() +} + +describe('entrypoint exports parity', () => { + const declaredExports = parseRuntimeExportsFromDts() + const declaredLayers = declaredExports.filter((name) => name.endsWith('Layer') && name !== 'Layer') + + test('ESM and CJS export every runtime symbol declared in generated.d.ts', async () => { + for (const name of declaredExports) { + expect(esm[name], `ESM missing ${name}`).toBeDefined() + expect(cjs[name], `CJS missing ${name}`).toBeDefined() + expect(cjs[name]).toBe(esm[name]) + } + + const esmKeys = Object.keys(esm) + .filter((key) => key !== 'default') + .sort() + const cjsKeys = Object.keys(cjs).sort() + expect(cjsKeys).toEqual(esmKeys) + expect(cjsKeys).toEqual([...declaredExports, 'layers'].sort()) + + // Verify Node's static CJS module lexer exposes every named export to ESM importers. + const cjsViaImport = await import('../index.cjs') + const cjsImportKeys = Object.keys(cjsViaImport) + .filter((key) => key !== 'default') + .sort() + expect(cjsImportKeys).toEqual(cjsKeys) + }) + + test('ESM and CJS layers namespace expose every layer class', () => { + expect(Object.keys(esm.layers).sort()).toEqual(declaredLayers) + expect(Object.keys(cjs.layers).sort()).toEqual(declaredLayers) + + for (const name of declaredLayers) { + expect(esm.layers[name]).toBe(esm[name]) + expect(cjs.layers[name]).toBe(cjs[name]) + } + + expect(new cjs.layers.CapabilityOverrideLayer('read=false').build()).toBeTruthy() + expect(new cjs.layers.ConcurrentLimitLayer(4).build()).toBeTruthy() + expect(new cjs.layers.LoggingLayer().build()).toBeTruthy() + expect(new cjs.layers.RetryLayer().build()).toBeTruthy() + expect(new cjs.layers.ThrottleLayer(1024, 2048).build()).toBeTruthy() + expect(new cjs.layers.TimeoutLayer().build()).toBeTruthy() + }) + + test('CJS stream wrappers handle errors, string encodings, and destroy in isolation', () => { + // Run in a fresh Node process so index.mjs does not overwrite shared prototypes. + const script = ` + const assert = require('node:assert/strict') + const { once } = require('node:events') + const { finished } = require('node:stream/promises') + const od = require(${JSON.stringify(cjsEntryPath)}) + + ;(async () => { + const op = new od.Operator('memory') + + // BlockingReadStream error destroys stream and stops _read re-entry. + const reader = op.readerSync('missing') + const originalRead = reader.read.bind(reader) + let readCalls = 0 + reader.read = (buf) => { + readCalls += 1 + return originalRead(buf) + } + const rs = reader.createReadStream() + let closed = false + rs.on('close', () => { closed = true }) + const ended = finished(rs) + rs.resume() + await assert.rejects(ended, /NotFound/) + assert.equal(rs.destroyed, true) + assert.equal(closed, true) + assert.equal(rs.reader, null) + assert.equal(rs.read(), null) + assert.equal(readCalls, 1) + + // WriteStream and BlockingWriteStream respect encodings with decodeStrings: false. + const expected = Buffer.concat([ + Buffer.from('hello'), + Buffer.from('hello'), + Buffer.from('hi', 'utf16le'), + Buffer.from([0xff]), + Buffer.from('utf8'), + Buffer.from('!?'), + ]) + + const asyncWs = (await op.writer('cjs-async.bin')).createWriteStream({ decodeStrings: false }) + asyncWs.write('68656c6c6f', 'hex') + asyncWs.write('aGVsbG8=', 'base64') + asyncWs.write('hi', 'utf16le') + asyncWs.write('\\xff', 'latin1') + asyncWs.write('utf8', 'utf8') + asyncWs.write(Buffer.from('!')) + asyncWs.end(new Uint8Array([63])) + await finished(asyncWs) + assert.equal(asyncWs.writer, null) + assert.deepEqual(await op.read('cjs-async.bin'), expected) + + const syncWs = op.writerSync('cjs-sync.bin').createWriteStream({ decodeStrings: false }) + syncWs.write('68656c6c6f', 'hex') + syncWs.write('aGVsbG8=', 'base64') + syncWs.write('hi', 'utf16le') + syncWs.write('\\xff', 'latin1') + syncWs.write('utf8', 'utf8') + syncWs.write(Buffer.from('!')) + syncWs.end(new Uint8Array([63])) + await finished(syncWs) + assert.equal(syncWs.writer, null) + assert.deepEqual(op.readSync('cjs-sync.bin'), expected) + + // Destroying WriteStream / BlockingWriteStream clears writer without closing. + for (const ws of [ + (await op.writer('cjs-abort-async.bin')).createWriteStream(), + op.writerSync('cjs-abort-sync.bin').createWriteStream(), + ]) { + const wsClosed = once(ws, 'close') + ws.destroy() + await wsClosed + assert.equal(ws.destroyed, true) + assert.equal(ws.writer, null) + } + assert.equal(await op.exists('cjs-abort-async.bin'), false) + assert.equal(op.existsSync('cjs-abort-sync.bin'), false) + })().catch((err) => { + console.error(err) + process.exit(1) + }) + ` + + execFileSync(process.execPath, ['-e', script], { stdio: 'inherit' }) + }) +}) diff --git a/bindings/nodejs/tests/suites/async.suite.mjs b/bindings/nodejs/tests/suites/async.suite.mjs index 90c898cf25..353530fc38 100644 --- a/bindings/nodejs/tests/suites/async.suite.mjs +++ b/bindings/nodejs/tests/suites/async.suite.mjs @@ -385,6 +385,53 @@ export function run(op) { expect(stream.destroyed).toBe(true) }) + test('write stream respects string encodings with decodeStrings: false', async () => { + const memory = new Operator('memory') + const writer = await memory.writer('encoded.bin') + const ws = writer.createWriteStream({ decodeStrings: false }) + ws.write('68656c6c6f', 'hex') + ws.write('aGVsbG8=', 'base64') + ws.write('hi', 'utf16le') + ws.write('\xff', 'latin1') + ws.write('utf8', 'utf8') + ws.write(Buffer.from('!')) + ws.end(new Uint8Array([63])) + + await finished(ws) + expect(ws.writer).toBeNull() + + const expected = Buffer.concat([ + Buffer.from('hello'), + Buffer.from('hello'), + Buffer.from('hi', 'utf16le'), + Buffer.from([0xff]), + Buffer.from('utf8'), + Buffer.from('!?'), + ]) + expect(await memory.read('encoded.bin')).toEqual(expected) + }) + + test('write stream destroy releases writer without closing', async () => { + const memory = new Operator('memory') + const writer = await memory.writer('aborted.bin') + let closeCalled = false + const originalClose = writer.close.bind(writer) + writer.close = () => { + closeCalled = true + return originalClose() + } + + const ws = writer.createWriteStream() + const closed = once(ws, 'close') + ws.destroy() + await closed + + expect(ws.destroyed).toBe(true) + expect(ws.writer).toBeNull() + expect(closeCalled).toBe(false) + expect(await memory.exists('aborted.bin')).toBe(false) + }) + test.each(['index.mjs', 'index.cjs'])( '%s releases a pending GET when its worker terminates', async (entry) => { diff --git a/bindings/nodejs/tests/suites/sync.suite.mjs b/bindings/nodejs/tests/suites/sync.suite.mjs index b4f3db6609..0d6972af66 100644 --- a/bindings/nodejs/tests/suites/sync.suite.mjs +++ b/bindings/nodejs/tests/suites/sync.suite.mjs @@ -18,20 +18,19 @@ */ import { randomUUID } from 'node:crypto' +import { once } from 'node:events' +import { Readable } from 'node:stream' +import { finished, pipeline } from 'node:stream/promises' import { test } from 'vitest' +import { Operator } from '../../index.mjs' import { generateFixedBytes } from '../utils.mjs' -import { Readable } from 'node:stream' export function run(op) { - describe.runIf(op.capability().blocking)('sync tests', () => { + describe('sync tests', () => { test('sync stat not exist files', () => { const filename = `random_file_${randomUUID()}` - try { - op.statSync(filename) - } catch (error) { - assert.include(error.message, 'NotFound') - } + assert.throws(() => op.statSync(filename), /NotFound/) }) test.runIf(op.capability().read && op.capability().write && op.capability().writeCanMulti)( @@ -44,20 +43,92 @@ export function run(op) { }) const w = op.writerSync(filename) const ws = w.createWriteStream() - rs.pipe(ws) + await pipeline(rs, ws) + await finished(ws) - ws.on('finish', () => { - const t = op.statSync(filename) - assert.equal(t.contentLength, buf.length) + const t = op.statSync(filename) + assert.equal(t.contentLength, BigInt(buf.length)) - const content = op.readSync(filename) - assert.equal(Buffer.compare(content, buf), 0) // 0 means equal + const content = op.readSync(filename) + assert.equal(Buffer.compare(content, buf), 0) // 0 means equal - op.deleteSync(filename) - }) + op.deleteSync(filename) }, ) + test('a blocking read error destroys the stream', async () => { + const memory = new Operator('memory') + const reader = memory.readerSync('missing') + const originalRead = reader.read.bind(reader) + let readCalls = 0 + reader.read = (buf) => { + readCalls += 1 + return originalRead(buf) + } + + const stream = reader.createReadStream() + let closed = false + stream.on('close', () => { + closed = true + }) + + const ended = finished(stream) + stream.resume() + await expect(ended).rejects.toThrow('NotFound') + expect(stream.destroyed).toBe(true) + expect(stream.errored?.message).toContain('NotFound') + expect(closed).toBe(true) + expect(stream.reader).toBeNull() + expect(stream.read()).toBeNull() + expect(readCalls).toBe(1) + }) + + test('blocking write stream respects string encodings with decodeStrings: false', async () => { + const memory = new Operator('memory') + const ws = memory.writerSync('encoded.bin').createWriteStream({ decodeStrings: false }) + ws.write('68656c6c6f', 'hex') + ws.write('aGVsbG8=', 'base64') + ws.write('hi', 'utf16le') + ws.write('\xff', 'latin1') + ws.write('utf8', 'utf8') + ws.write(Buffer.from('!')) + ws.end(new Uint8Array([63])) + + await finished(ws) + expect(ws.writer).toBeNull() + + const expected = Buffer.concat([ + Buffer.from('hello'), + Buffer.from('hello'), + Buffer.from('hi', 'utf16le'), + Buffer.from([0xff]), + Buffer.from('utf8'), + Buffer.from('!?'), + ]) + expect(memory.readSync('encoded.bin')).toEqual(expected) + }) + + test('blocking write stream destroy releases writer without closing', async () => { + const memory = new Operator('memory') + const writer = memory.writerSync('aborted.bin') + let closeCalled = false + const originalClose = writer.close.bind(writer) + writer.close = () => { + closeCalled = true + return originalClose() + } + + const ws = writer.createWriteStream() + const closed = once(ws, 'close') + ws.destroy() + await closed + + expect(ws.destroyed).toBe(true) + expect(ws.writer).toBeNull() + expect(closeCalled).toBe(false) + expect(memory.existsSync('aborted.bin')).toBe(false) + }) + test.runIf(op.capability().read && op.capability().write)('blocking write with behavior', () => { let c = Buffer.from('hello world') const filename = `random_file_${randomUUID()}`
