Skip to content

Commit 8a7b43a

Browse files
committed
Attempt to handle a stream being silently killed in the background
1 parent 11d7c59 commit 8a7b43a

File tree

2 files changed

+43
-3
lines changed

2 files changed

+43
-3
lines changed

packages/pg-pool/index.js

+12-3
Original file line numberDiff line numberDiff line change
@@ -116,11 +116,20 @@ class Pool extends EventEmitter {
116116
const pendingItem = this._pendingQueue.shift()
117117
if (this._idle.length) {
118118
const idleItem = this._idle.pop()
119-
clearTimeout(idleItem.timeoutId)
120119
const client = idleItem.client
121-
const idleListener = idleItem.idleListener
120+
clearTimeout(idleItem.timeoutId)
122121

123-
return this._acquireClient(client, pendingItem, idleListener, false)
122+
// TODO(bmc): we need a better state represetation on the client itself
123+
// to indicate if it's connecting, idle, running a query, closed, etc...
124+
// but for now we can look at it's stream.
125+
// remove this client, it's died in the background - this can happen
126+
// in aws lambdas - they go idle and the streams are closed without an error
127+
if (client.connection.stream.readyState !== 'open') {
128+
this._remove(client)
129+
} else {
130+
const idleListener = idleItem.idleListener
131+
return this._acquireClient(client, pendingItem, idleListener, false)
132+
}
124133
}
125134
if (!this._isFull()) {
126135
return this.newClient(pendingItem)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
'use strict'
2+
const net = require('net')
3+
const co = require('co')
4+
const expect = require('expect.js')
5+
6+
const describe = require('mocha').describe
7+
const it = require('mocha').it
8+
9+
const Pool = require('../')
10+
11+
describe('a socket disconnecting in the background', () => {
12+
it('should leave the pool in a usable state', async () => {
13+
const pool = new Pool({ max: 1 })
14+
// just run any arbitrary query
15+
const client = await pool.connect()
16+
await client.query('SELECT NOW()')
17+
// return the client
18+
client.release()
19+
20+
// now kill the socket in the background
21+
client.connection.stream.end()
22+
23+
// now try to query again, it should work
24+
await pool.query('SELECT NOW()')
25+
await pool.query('SELECT NOW()')
26+
await pool.query('SELECT NOW()')
27+
await pool.query('SELECT NOW()')
28+
29+
await pool.end()
30+
})
31+
})

0 commit comments

Comments
 (0)