From f3fac17d0d1b21775dbc6f9b48398b6f48911c3a Mon Sep 17 00:00:00 2001 From: Rusty Conover Date: Tue, 28 Jan 2020 10:53:21 -0500 Subject: [PATCH] net: Track state of setKeepAlive and prevent unnecessary system calls The state of .setKeepAlive() is now tracked and code will prevent repeated system calls to setsockopt() when the value has already been set to the desired value for the socket. --- lib/net.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/net.js b/lib/net.js index 9ff6f12b9bc0e6..f90b0afad97712 100644 --- a/lib/net.js +++ b/lib/net.js @@ -258,6 +258,7 @@ function initSocketHandle(self) { const kBytesRead = Symbol('kBytesRead'); const kBytesWritten = Symbol('kBytesWritten'); const kSetNoDelay = Symbol('kSetNoDelay'); +const kSetKeepAlive = Symbol('kSetKeepAlive'); function Socket(options) { if (!(this instanceof Socket)) return new Socket(options); @@ -273,6 +274,7 @@ function Socket(options) { this._host = null; this[kSetNoDelay] = false; this[kLastWriteQueueSize] = 0; + this[kSetKeepAlive] = null; this[kTimeout] = null; this[kBuffer] = null; this[kBufferCb] = null; @@ -500,13 +502,26 @@ Socket.prototype.setNoDelay = function(enable) { Socket.prototype.setKeepAlive = function(setting, msecs) { + if (setting != null && typeof setting !== 'boolean') + throw new ERR_INVALID_ARG_TYPE('enable', 'boolean', setting); + + if (msecs != null && typeof msecs !== 'number') + throw new ERR_INVALID_ARG_TYPE('msecs', 'number', msecs); + + if (msecs === 0) { + return; + } + if (!this._handle) { this.once('connect', () => this.setKeepAlive(setting, msecs)); return this; } - if (this._handle.setKeepAlive) + if (this._handle.setKeepAlive && + this[kSetKeepAlive] !== setting) { this._handle.setKeepAlive(setting, ~~(msecs / 1000)); + this[kSetKeepAlive] = setting; + } return this; };