Skip to content

fix: Connection timeout handling for native clients in connected state #3512

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
14 changes: 10 additions & 4 deletions packages/pg-pool/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -241,10 +241,16 @@ class Pool extends EventEmitter {
let timeoutHit = false
if (this.options.connectionTimeoutMillis) {
tid = setTimeout(() => {
this.log('ending client due to timeout')
timeoutHit = true
// force kill the node driver, and let libpq do its teardown
client.connection ? client.connection.stream.destroy() : client.end()
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()
}
}, this.options.connectionTimeoutMillis)
}

Expand Down
21 changes: 21 additions & 0 deletions packages/pg-pool/test/connection-timeout.js
Original file line number Diff line number Diff line change
Expand Up @@ -226,4 +226,25 @@ describe('connection timeout', () => {
})
})
})

it('should connect if timeout is passed, but native client in connected state', (done) => {
const Client = require('pg').native.Client

Client.prototype.connect = function (cb) {
this._connected = true

return setTimeout(() => {
cb()
}, 200)
}

const pool = new Pool({ connectionTimeoutMillis: 100, port: this.port, host: 'localhost' }, Client)

pool.connect((err, client, release) => {
expect(err).to.be(undefined)
expect(client).to.not.be(undefined)
expect(client.isConnected()).to.be(true)
done()
})
})
})
7 changes: 7 additions & 0 deletions packages/pg/lib/native/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,10 @@ Client.prototype.end = function (cb) {
cb = (err) => (err ? reject(err) : resolve())
})
}

this.native.end(function () {
self._connected = false

self._errorAllQueries(new Error('Connection terminated'))

process.nextTick(() => {
Expand Down Expand Up @@ -306,3 +309,7 @@ Client.prototype.setTypeParser = function (oid, format, parseFn) {
Client.prototype.getTypeParser = function (oid, format) {
return this._types.getTypeParser(oid, format)
}

Client.prototype.isConnected = function () {
return this._connected
}