Skip to content
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
17 changes: 13 additions & 4 deletions packages/pg-pool/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ class Pool extends EventEmitter {
this._idle = []
this._expired = new WeakSet()
this._pendingQueue = []
this._closingClients = 0
this._endCallback = undefined
this.ending = false
this.ended = false
Expand Down Expand Up @@ -137,10 +138,7 @@ class Pool extends EventEmitter {
this._remove(item.client)
})
}
if (!this._clients.length) {
this.ended = true
this._endCallback()
}
this._finishEnding()
return
}

Expand Down Expand Up @@ -169,6 +167,13 @@ class Pool extends EventEmitter {
throw new Error('unexpected condition')
}

_finishEnding() {
if (this.ending && !this.ended && !this._clients.length && !this._closingClients) {
this.ended = true
this._endCallback()
}
}

_remove(client, callback) {
const removed = removeWhere(this._idle, (item) => item.client === client)

Expand All @@ -177,12 +182,16 @@ class Pool extends EventEmitter {
}

this._clients = this._clients.filter((c) => c !== client)
this._closingClients++
const context = this
client.end(() => {
context.emit('remove', client)
context._closingClients--

if (typeof callback === 'function') {
callback()
} else {
context._finishEnding()
}
})
}
Expand Down
36 changes: 36 additions & 0 deletions packages/pg-pool/test/ending.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict'
const co = require('co')
const expect = require('expect.js')
const { EventEmitter } = require('events')

const describe = require('mocha').describe
const it = require('mocha').it
Expand All @@ -17,6 +18,41 @@ describe('pool ending', () => {
return new Pool().end()
})

for (const idle of [true, false]) {
it(`waits for both ${idle ? 'idle' : 'checked-out'} clients to close`, async () => {
class Client extends EventEmitter {
constructor() {
super()
this._queryable = true
}

connect(cb) {
process.nextTick(cb)
}

end(cb) {
this.finishClosing = cb
}
}

const pool = new Pool({ Client, max: 2, idleTimeoutMillis: 0 })
const clients = await Promise.all([pool.connect(), pool.connect()])
const events = []
pool.on('remove', (client) => events.push(client))

if (idle) clients.forEach((client) => client.release())
const ending = pool.end().then(() => events.push('ended'))
if (!idle) clients.forEach((client) => client.release())

clients[0].finishClosing()
await new Promise(setImmediate)
clients[1].finishClosing()
await ending

expect(events).to.eql([...clients, 'ended'])
})
}

it(
'ends with clients',
co.wrap(function* () {
Expand Down
Loading