Skip to content

Commit

Permalink
http: cleanup ClientRequest oncreate
Browse files Browse the repository at this point in the history
PR-URL: #36862
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Daniele Belardi <dwon.dnl@gmail.com>
  • Loading branch information
ronag authored and ruyadorno committed Jan 21, 2021
1 parent eaf378a commit 80051ab
Showing 1 changed file with 17 additions and 22 deletions.
39 changes: 17 additions & 22 deletions lib/_http_client.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const {
const net = require('net');
const url = require('url');
const assert = require('internal/assert');
const { once } = require('internal/util');
const {
_checkIsHttpToken: checkIsHttpToken,
debug,
Expand Down Expand Up @@ -240,8 +241,6 @@ function ClientRequest(input, options, cb) {
this.host = host;
this.protocol = protocol;

let called = false;

if (this.agent) {
// If there is an agent we should default to Connection:keep-alive,
// but only if the Agent will actually reuse the connection!
Expand Down Expand Up @@ -305,18 +304,6 @@ function ClientRequest(input, options, cb) {
options.headers);
}

const oncreate = (err, socket) => {
if (called)
return;
called = true;
if (err) {
process.nextTick(() => this.emit('error', err));
return;
}
this.onSocket(socket);
this._deferToConnect(null, null, () => this._flush());
};

// initiate connection
if (this.agent) {
this.agent.addRequest(this, options);
Expand All @@ -325,20 +312,27 @@ function ClientRequest(input, options, cb) {
this._last = true;
this.shouldKeepAlive = false;
if (typeof options.createConnection === 'function') {
const newSocket = options.createConnection(options, oncreate);
if (newSocket && !called) {
called = true;
this.onSocket(newSocket);
} else {
return;
const oncreate = once((err, socket) => {
if (err) {
process.nextTick(() => this.emit('error', err));
} else {
this.onSocket(socket);
}
});

try {
const newSocket = options.createConnection(options, oncreate);
if (newSocket) {
oncreate(null, newSocket);
}
} catch (err) {
oncreate(err);
}
} else {
debug('CLIENT use net.createConnection', options);
this.onSocket(net.createConnection(options));
}
}

this._deferToConnect(null, null, () => this._flush());
}
ObjectSetPrototypeOf(ClientRequest.prototype, OutgoingMessage.prototype);
ObjectSetPrototypeOf(ClientRequest, OutgoingMessage);
Expand Down Expand Up @@ -843,6 +837,7 @@ function onSocketNT(req, socket, err) {
_destroy(req, null, err);
} else {
tickOnSocket(req, socket);
req._flush();
}
}

Expand Down

0 comments on commit 80051ab

Please sign in to comment.