diff --git a/index.js b/index.js index 2fbdb78d5ef9aaf09c01cacae651a5d96cbcfed7..b07f3b4fa5899200fea7cd8c4577df4fda85e07d 100644 --- a/index.js +++ b/index.js @@ -102,6 +102,7 @@ class Pool extends EventEmitter { this._clients = [] this._idle = [] this._expired = new WeakSet() + this._endingClients = new Set() this._pendingQueue = [] this._endCallback = undefined this.ending = false @@ -119,3 +120,3 @@ class Pool extends EventEmitter { _isFull() { - return this._clients.length >= this.options.max + return this._clients.length + this._endingClients.size >= this.options.max } @@ -137,7 +138,7 @@ class Pool extends EventEmitter { this._remove(item.client) }) } - if (!this._clients.length) { + if (!this._clients.length && !this._endingClients.size) { this.ended = true this._endCallback() } @@ -249,15 +250,47 @@ class Pool extends EventEmitter { let timeoutHit = false if (this.options.connectionTimeoutMillis) { tid = setTimeout(() => { + // the native client reports itself connected before its connect callback fires + if (!client.connection && client.isConnected()) { + return + } + + this.log('ending client due to timeout') + timeoutHit = true + this._endingClients.add(client) + this._clients = this._clients.filter((c) => c !== client) + if (!pendingItem.timedOut) { + pendingItem.timedOut = true + pendingItem.callback(new Error('Connection terminated due to connection timeout'), undefined, NOOP) + } + this._pulseQueue() + client.removeAllListeners('error') + client.on('error', () => {}) + let forceEndTimer + let endHandled = false + const handleEnd = () => { + if (endHandled) { + return + } + endHandled = true + if (forceEndTimer) { + clearTimeout(forceEndTimer) + } + this._endingClients.delete(client) + this._pulseQueue() + } if (client.connection) { - this.log('ending client due to timeout') - timeoutHit = true - client.connection.stream.destroy() - } else if (!client.isConnected()) { - this.log('ending client due to timeout') - timeoutHit = true - // force kill the node driver, and let libpq do its teardown - client.end() + const connection = client.connection + client.once('end', handleEnd) + forceEndTimer = setTimeout(() => { + connection.stream.destroy() + }, this.options.connectionTimeoutMillis) + if (forceEndTimer.unref) { + forceEndTimer.unref() + } + connection.end() + } else { + client.end(handleEnd) } }, this.options.connectionTimeoutMillis) } @@ -282,5 +316,9 @@ class Pool extends EventEmitter { if (!pendingItem.timedOut) { pendingItem.callback(err, undefined, NOOP) } + } else if (timeoutHit) { + this.log('client connected after timeout, discarding') + client.removeAllListeners('error') + client.on('error', () => {}) } else { this.log('new client connected')