Skip to content

Commit 1871d0f

Browse files
charmanderbrianc
authored andcommitted
Remove timed-out checkouts from queue correctly (brianc#86)
* Add failing test for correct removal from checkout queue on timeout * Remove timed-out checkouts from queue correctly Fixes brianc#85.
1 parent fabf39c commit 1871d0f

File tree

2 files changed

+37
-5
lines changed

2 files changed

+37
-5
lines changed

index.js

+15-5
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,14 @@ const EventEmitter = require('events').EventEmitter
33

44
const NOOP = function () { }
55

6+
const remove = (list, value) => {
7+
const i = list.indexOf(value)
8+
9+
if (i !== -1) {
10+
list.splice(i, 1)
11+
}
12+
}
13+
614
const removeWhere = (list, predicate) => {
715
const i = list.findIndex(predicate)
816

@@ -157,18 +165,20 @@ class Pool extends EventEmitter {
157165
return result
158166
}
159167

168+
const queueCallback = (err, res, done) => {
169+
clearTimeout(tid)
170+
response.callback(err, res, done)
171+
}
172+
160173
// set connection timeout on checking out an existing client
161174
const tid = setTimeout(() => {
162175
// remove the callback from pending waiters because
163176
// we're going to call it with a timeout error
164-
this._pendingQueue = this._pendingQueue.filter(cb => cb === response.callback)
177+
remove(this._pendingQueue, queueCallback)
165178
response.callback(new Error('timeout exceeded when trying to connect'))
166179
}, this.options.connectionTimeoutMillis)
167180

168-
this._pendingQueue.push(function (err, res, done) {
169-
clearTimeout(tid)
170-
response.callback(err, res, done)
171-
})
181+
this._pendingQueue.push(queueCallback)
172182
return result
173183
}
174184

test/connection-timeout.js

+22
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,28 @@ describe('connection timeout', () => {
7373
})
7474
})
7575

76+
it('should not break further pending checkouts on a timeout', (done) => {
77+
const pool = new Pool({ connectionTimeoutMillis: 200, max: 1 })
78+
pool.connect((err, client, releaseOuter) => {
79+
expect(err).to.be(undefined)
80+
81+
pool.connect((err, client) => {
82+
expect(err).to.be.an(Error)
83+
expect(client).to.be(undefined)
84+
releaseOuter()
85+
})
86+
87+
setTimeout(() => {
88+
pool.connect((err, client, releaseInner) => {
89+
expect(err).to.be(undefined)
90+
expect(client).to.not.be(undefined)
91+
releaseInner()
92+
pool.end(done)
93+
})
94+
}, 100)
95+
})
96+
})
97+
7698
it('should timeout on query if all clients are busy', (done) => {
7799
const pool = new Pool({ connectionTimeoutMillis: 100, max: 1 })
78100
pool.connect((err, client, release) => {

0 commit comments

Comments
 (0)