Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 81 additions & 16 deletions lib/requester.js
Original file line number Diff line number Diff line change
Expand Up @@ -543,29 +543,94 @@ function multipartRequester(request) {
multipartStream.pipe(request);
} else {
const parts = operation.requestPartList;
// Stream-driven PassThroughs receive writes asynchronously (after listeners are
// attached), so multipart-stream works correctly for them on all Node.js versions.
// Only the all-synchronous case triggers the Node.js v26+ 'readable' regression.
const hasStreamContent = Array.isArray(parts) &&
parts.some(p => p.content !== null && typeof p.content.pipe === 'function');
parts.some(p => p.content != null && typeof p.content.pipe === 'function');

if (hasStreamContent) {
const multipartStream = new Multipart(boundary);
let index = 0;
let written = 0;
let activeStream = null;
let activeEndListener = null;
const streams = parts.filter(part => part.headers != null && part.content != null &&
typeof part.content.pipe === 'function').map(part => part.content);
operation.logger.debug('writing %s parts', parts.length);
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
const headers = part.headers;
const content = part.content;
if ((headers !== null) && (content !== null)) {
operation.logger.debug('starting part %s', i);
multipartStream.addPart({ headers: headers, body: content });
operation.logger.debug('finished part %s', i);

function cleanupStream(content) {
content.removeListener('error', onStreamError);
content.removeListener('close', onStreamClose);
}
function onStreamError(err) {
if (!request.destroyed) {
request.destroy(err);
} else {
operation.logger.debug('nothing to write for part %d', i);
operation.logError(err);
}
if (this.closed) {
cleanupStream(this);
}
}
function onStreamClose() {
cleanupStream(this);
if (!this.readableEnded && !request.destroyed) {
request.destroy(new Error('multipart content stream closed before ending'));
}
}
streams.forEach(content => {
content.on('error', onStreamError);
content.once('close', onStreamClose);
});
request.once('close', function() {
if (activeStream !== null) {
activeStream.unpipe(request);
activeStream.removeListener('end', activeEndListener);
}
// Keep error handlers attached while cancelled sources finish shutting down.
streams.forEach(content => {
if (content.readableEnded && !content.destroyed) {
cleanupStream(content);
} else if (!content.readableEnded && typeof content.destroy === 'function') {
content.destroy();
}
});
});

function writeNextPart() {
while (index < parts.length && !request.destroyed) {
const partIndex = index++;
const part = parts[partIndex];
const headers = part.headers;
const content = part.content;
if (headers == null || content == null) {
operation.logger.debug('nothing to write for part %d', partIndex);
continue;
}

operation.logger.debug('starting part %s', partIndex);
request.write(Buffer.from((written++ === 0 ? '--' : CRNL + '--') + boundary + CRNL));
Object.entries(headers).forEach(([k, v]) => request.write(Buffer.from(k + ': ' + v + CRNL)));
request.write(Buffer.from(CRNL));

if (typeof content.pipe === 'function') {
activeStream = content;
activeEndListener = function() {
activeStream = null;
activeEndListener = null;
operation.logger.debug('finished part %s', partIndex);
writeNextPart();
};
content.once('end', activeEndListener);
content.pipe(request, {end: false});
return;
}

request.write(Buffer.isBuffer(content) ? content : Buffer.from(content));
operation.logger.debug('finished part %s', partIndex);
}
if (!request.destroyed) {
request.end(Buffer.from(CRNL + '--' + boundary + '--'));
}
}
multipartStream.on('error', err => request.destroy(err));
multipartStream.pipe(request);
writeNextPart();
} else {
// All synchronous content: build body directly as Buffers to avoid
// sandwich-stream's 'readable' event regression on Node.js v26+.
Expand Down
37 changes: 36 additions & 1 deletion test-basic/documents-core.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2015-2025 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
* Copyright (c) 2015-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
*/
var should = require('should');

Expand Down Expand Up @@ -358,6 +358,41 @@ describe('document content', function(){
});
});

describe('mixed plain and stream content', function(){
it('should write and read both documents and their metadata', function(){
this.timeout(10000);
var binaryPath = './test-basic/data/mlfavicon.png';
var jsonUri = '/test/mixed.json';
var binaryUri = '/test/mixed.png';

return db.documents.write([{
uri: jsonUri,
contentType: 'application/json',
collections: ['test-mixed-json'],
content: '{"key1":"value 1"}'
}, {
uri: binaryUri,
contentType: 'image/png',
collections: ['test-mixed-binary'],
content: fs.createReadStream(binaryPath)
}]).result()
.then(function() {
return Promise.all([
db.documents.read({uris: jsonUri, categories: ['metadata', 'content']}).result(),
db.documents.read({uris: binaryUri, categories: ['metadata', 'content']}).result()
]);
})
.then(function(results) {
results[0].length.should.equal(1);
results[0][0].content.should.eql({key1: 'value 1'});
results[0][0].collections.should.containEql('test-mixed-json');
results[1].length.should.equal(1);
results[1][0].content.should.eql(fs.readFileSync(binaryPath));
results[1][0].collections.should.containEql('test-mixed-binary');
});
});
});

// write and read arity
describe('two JSON documents', function(){
before(function(done){
Expand Down
163 changes: 163 additions & 0 deletions test-basic/documents-multipart-header-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
*/
const http = require('http');
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const Readable = require('stream').Readable;
const should = require('should');
const marklogic = require('../');
const op = marklogic.planBuilder;
Expand All @@ -16,6 +19,166 @@ describe('documents.write multipart headers', function() {
authType: 'basic'
});

describe('documents.write multipart content', function() {
async function captureWrite(documents) {
let captured;
const server = http.createServer(function(request, response) {
const chunks = [];
request.on('data', chunk => chunks.push(chunk));
request.on('end', function() {
captured = {
body: Buffer.concat(chunks),
contentType: request.headers['content-type']
};
response.writeHead(204);
response.end();
});
});

await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
try {
const db = marklogic.createDatabaseClient({
host: '127.0.0.1',
port: server.address().port,
user: 'u',
password: 'p',
authType: 'basic'
});
await db.documents.write(documents).result();
return captured;
} finally {
await new Promise(resolve => server.close(resolve));
}
}

function expectedBody(contentType, parts) {
const boundary = /boundary="?([^";]+)"?/i.exec(contentType)[1];
const chunks = [];
parts.forEach(function(part, index) {
chunks.push(Buffer.from((index === 0 ? '--' : '\r\n--') + boundary + '\r\n' +
'Content-Type: ' + part.type + '\r\n' +
'Content-Disposition: attachment; filename="' + part.uri + '"; category=' + part.category + '\r\n\r\n'));
chunks.push(Buffer.isBuffer(part.content) ? part.content : Buffer.from(part.content));
});
chunks.push(Buffer.from('\r\n--' + boundary + '--'));
return Buffer.concat(chunks);
}

it('preserves metadata, binary bytes and order across mixed and multiple streams', async function() {
const binary = Buffer.from([0, 255, 13, 10, 128]);
const result = await captureWrite([{
uri: '/a-plain.json', contentType: 'application/json',
collections: ['mixed'], content: '{"key1":"value 1"}'
}, {
uri: '/b-stream.png', contentType: 'image/png',
collections: ['binary'], content: Readable.from([binary.subarray(0, 2), binary.subarray(2)])
}, {
uri: '/c-after.txt', contentType: 'text/plain', content: 'after'
}, {
uri: '/d-last.txt', contentType: 'text/plain', content: Readable.from(['last', ' stream'])
}]);
assert.deepStrictEqual(result.body, expectedBody(result.contentType, [
{uri: '/a-plain.json', type: 'application/json', category: 'metadata', content: '{"collections":["mixed"]}'},
{uri: '/a-plain.json', type: 'application/json', category: 'content', content: '{"key1":"value 1"}'},
{uri: '/b-stream.png', type: 'application/json', category: 'metadata', content: '{"collections":["binary"]}'},
{uri: '/b-stream.png', type: 'image/png', category: 'content', content: binary},
{uri: '/c-after.txt', type: 'text/plain', category: 'content', content: 'after'},
{uri: '/d-last.txt', type: 'text/plain', category: 'content', content: 'last stream'}
]));
});

for (const streamed of [false, true]) {
it('preserves ' + (streamed ? 'stream-only' : 'plain-only') + ' batches', async function() {
const result = await captureWrite(['/first.txt', '/second.txt'].map(function(uri, index) {
const content = index === 0 ? 'first' : 'second';
return {uri: uri, contentType: 'text/plain', content: streamed ? Readable.from([content]) : content};
}));
assert.deepStrictEqual(result.body, expectedBody(result.contentType, [
{uri: '/first.txt', type: 'text/plain', category: 'content', content: 'first'},
{uri: '/second.txt', type: 'text/plain', category: 'content', content: 'second'}
]));
});
}

it('sends a plain JSON document with a file stream', async function() {
const binaryPath = path.join(__dirname, 'data/mlfavicon.png');
const result = await captureWrite([{
uri: '/mixed.json', contentType: 'application/json', content: '{"key1":"value 1"}'
}, {
uri: '/mixed.png', contentType: 'image/png', content: fs.createReadStream(binaryPath)
}]);
assert.deepStrictEqual(result.body, expectedBody(result.contentType, [
{uri: '/mixed.json', type: 'application/json', category: 'content', content: '{"key1":"value 1"}'},
{uri: '/mixed.png', type: 'image/png', category: 'content', content: fs.readFileSync(binaryPath)}
]));
});

it('reports a stream error instead of completing the request', async function() {
const source = new Readable({
read() { this.destroy(new Error('source failed')); }
});
await assert.rejects(captureWrite([
{uri: '/first.txt', contentType: 'text/plain', content: 'first'},
{uri: '/failed.txt', contentType: 'text/plain', content: source}
]), /source failed/);
});

it('reports errors from a stream before its turn', async function() {
const second = new Readable({read() {}});
const first = new Readable({
read() { second.destroy(new Error('later source failed')); }
});
await assert.rejects(captureWrite([
{uri: '/first.txt', contentType: 'text/plain', content: first},
{uri: '/second.txt', contentType: 'text/plain', content: second}
]), /later source failed/);
});

it('cancels unfinished streams and handles errors during their shutdown', async function() {
const second = new Readable({
read() {},
destroy(error, callback) {
setTimeout(() => callback(new Error('shutdown failed')), 20);
}
});
const closed = new Promise(resolve => second.once('close', resolve));
const first = new Readable({
read() { this.destroy(new Error('first source failed')); }
});

await assert.rejects(captureWrite([
{uri: '/first.txt', contentType: 'text/plain', content: first},
{uri: '/second.txt', contentType: 'text/plain', content: second}
]), /first source failed/);
await closed;
assert.strictEqual(second.destroyed, true);
assert.strictEqual(second.listenerCount('error'), 0);
});

it('removes handlers from completed streams that stay open', async function() {
const source = new Readable({
autoDestroy: false,
read() { this.push('stream'); this.push(null); }
});
await captureWrite([
{uri: '/first.txt', contentType: 'text/plain', content: 'plain'},
{uri: '/second.txt', contentType: 'text/plain', content: source}
]);
assert.strictEqual(source.destroyed, false);
assert.strictEqual(source.listenerCount('error'), 0);
});

it('reports a stream that closes before ending', async function() {
const source = new Readable({
read() { this.destroy(); }
});
await assert.rejects(captureWrite([
{uri: '/first.txt', contentType: 'text/plain', content: 'first'},
{uri: '/second.txt', contentType: 'text/plain', content: source}
]), /stream closed before ending/);
});
});

it('rejects CR, LF, NUL, and double quotes in uri and temporalDocument', function() {
const invalidSuffixes = ['\r', '\n', '\0', '"', '"; filename="y.json'];
for (const suffix of invalidSuffixes) {
Expand Down
Loading