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
8 changes: 7 additions & 1 deletion lib/internal/http/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -900,7 +900,12 @@ function socketOnData(d) {
!statusIsInformational(parser.incoming.statusCode)) {
socket.removeListener('data', socketOnData);
socket.removeListener('end', socketOnEnd);
socket.removeListener('drain', ondrain);
// The request may still be writing its body and waiting for 'drain'
// (e.g. the server replied before reading all of it). Keep forwarding
// 'drain' until the request has ended; responseKeepAlive() removes the
// listener when the socket is released.
if (req.finished)
socket.removeListener('drain', ondrain);
freeParser(parser, req, socket);
}
}
Expand Down Expand Up @@ -1042,6 +1047,7 @@ function responseKeepAlive(req) {
socket.removeListener('error', socketErrorListener);
socket.removeListener('data', socketOnData);
socket.removeListener('end', socketOnEnd);
socket.removeListener('drain', ondrain);

// TODO(ronag): Between here and emitFreeNT the socket
// has no 'error' handler.
Expand Down
50 changes: 50 additions & 0 deletions test/parallel/test-http-client-drain-after-early-response.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const http = require('http');

// The server replies as soon as it has the request headers, while the client
// is still writing a large body with backpressure. Once the response is
// complete the client must keep forwarding the socket's 'drain' to the
// request, otherwise a writer that honors backpressure (for example a stream
// piped into the request) can never finish writing.

const BODY = 8 * 1024 * 1024;
const chunk = Buffer.alloc(64 * 1024);

const server = http.createServer(common.mustCall((req, res) => {
res.writeHead(201, { 'Content-Length': '0' });
res.end();
req.resume();
}));

server.listen(0, common.mustCall(() => {
const req = http.request({
port: server.address().port,
method: 'PUT',
headers: { 'Content-Length': BODY },
}, common.mustCall((res) => {
assert.strictEqual(res.statusCode, 201);
res.resume();
}));

req.on('finish', common.mustCall(() => {
assert.strictEqual(req.writableNeedDrain, false);
assert.strictEqual(req.writableFinished, true);
server.close();
}));

let left = BODY;
function write() {
while (left > 0) {
const n = Math.min(left, chunk.length);
left -= n;
if (!req.write(chunk.subarray(0, n))) {
req.once('drain', write);
return;
}
}
req.end();
}
write();
}));
Loading