index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. 'use strict'
  2. const EventEmitter = require('events').EventEmitter
  3. const NOOP = function () {}
  4. const removeWhere = (list, predicate) => {
  5. const i = list.findIndex(predicate)
  6. return i === -1 ? undefined : list.splice(i, 1)[0]
  7. }
  8. class IdleItem {
  9. constructor(client, idleListener, timeoutId) {
  10. this.client = client
  11. this.idleListener = idleListener
  12. this.timeoutId = timeoutId
  13. }
  14. }
  15. class PendingItem {
  16. constructor(callback) {
  17. this.callback = callback
  18. }
  19. }
  20. function throwOnDoubleRelease() {
  21. throw new Error('Release called on client which has already been released to the pool.')
  22. }
  23. function promisify(Promise, callback) {
  24. if (callback) {
  25. return { callback: callback, result: undefined }
  26. }
  27. let rej
  28. let res
  29. const cb = function (err, client) {
  30. err ? rej(err) : res(client)
  31. }
  32. const result = new Promise(function (resolve, reject) {
  33. res = resolve
  34. rej = reject
  35. }).catch((err) => {
  36. // replace the stack trace that leads to `TCP.onStreamRead` with one that leads back to the
  37. // application that created the query
  38. Error.captureStackTrace(err)
  39. throw err
  40. })
  41. return { callback: cb, result: result }
  42. }
  43. function makeIdleListener(pool, client) {
  44. return function idleListener(err) {
  45. err.client = client
  46. client.removeListener('error', idleListener)
  47. client.on('error', () => {
  48. pool.log('additional client error after disconnection due to error', err)
  49. })
  50. pool._remove(client)
  51. // TODO - document that once the pool emits an error
  52. // the client has already been closed & purged and is unusable
  53. pool.emit('error', err, client)
  54. }
  55. }
  56. class Pool extends EventEmitter {
  57. constructor(options, Client) {
  58. super()
  59. this.options = Object.assign({}, options)
  60. if (options != null && 'password' in options) {
  61. // "hiding" the password so it doesn't show up in stack traces
  62. // or if the client is console.logged
  63. Object.defineProperty(this.options, 'password', {
  64. configurable: true,
  65. enumerable: false,
  66. writable: true,
  67. value: options.password,
  68. })
  69. }
  70. if (options != null && options.ssl && options.ssl.key) {
  71. // "hiding" the ssl->key so it doesn't show up in stack traces
  72. // or if the client is console.logged
  73. Object.defineProperty(this.options.ssl, 'key', {
  74. enumerable: false,
  75. })
  76. }
  77. this.options.max = this.options.max || this.options.poolSize || 10
  78. this.options.min = this.options.min || 0
  79. this.options.maxUses = this.options.maxUses || Infinity
  80. this.options.allowExitOnIdle = this.options.allowExitOnIdle || false
  81. this.options.maxLifetimeSeconds = this.options.maxLifetimeSeconds || 0
  82. this.log = this.options.log || function () {}
  83. this.Client = this.options.Client || Client || require('pg').Client
  84. this.Promise = this.options.Promise || global.Promise
  85. if (typeof this.options.idleTimeoutMillis === 'undefined') {
  86. this.options.idleTimeoutMillis = 10000
  87. }
  88. this._clients = []
  89. this._idle = []
  90. this._expired = new WeakSet()
  91. this._pendingQueue = []
  92. this._endCallback = undefined
  93. this.ending = false
  94. this.ended = false
  95. }
  96. _promiseTry(f) {
  97. const Promise = this.Promise
  98. if (typeof Promise.try === 'function') {
  99. return Promise.try(f)
  100. }
  101. return new Promise((resolve) => resolve(f()))
  102. }
  103. _isFull() {
  104. return this._clients.length >= this.options.max
  105. }
  106. _isAboveMin() {
  107. return this._clients.length > this.options.min
  108. }
  109. _pulseQueue() {
  110. this.log('pulse queue')
  111. if (this.ended) {
  112. this.log('pulse queue ended')
  113. return
  114. }
  115. if (this.ending) {
  116. this.log('pulse queue on ending')
  117. if (this._idle.length) {
  118. this._idle.slice().map((item) => {
  119. this._remove(item.client)
  120. })
  121. }
  122. if (!this._clients.length) {
  123. this.ended = true
  124. this._endCallback()
  125. }
  126. return
  127. }
  128. // if we don't have any waiting, do nothing
  129. if (!this._pendingQueue.length) {
  130. this.log('no queued requests')
  131. return
  132. }
  133. // if we don't have any idle clients and we have no more room do nothing
  134. if (!this._idle.length && this._isFull()) {
  135. return
  136. }
  137. const pendingItem = this._pendingQueue.shift()
  138. if (this._idle.length) {
  139. const idleItem = this._idle.pop()
  140. clearTimeout(idleItem.timeoutId)
  141. const client = idleItem.client
  142. client.ref && client.ref()
  143. const idleListener = idleItem.idleListener
  144. return this._acquireClient(client, pendingItem, idleListener, false)
  145. }
  146. if (!this._isFull()) {
  147. return this.newClient(pendingItem)
  148. }
  149. throw new Error('unexpected condition')
  150. }
  151. _remove(client, callback) {
  152. const removed = removeWhere(this._idle, (item) => item.client === client)
  153. if (removed !== undefined) {
  154. clearTimeout(removed.timeoutId)
  155. }
  156. this._clients = this._clients.filter((c) => c !== client)
  157. const context = this
  158. client.end(() => {
  159. context.emit('remove', client)
  160. if (typeof callback === 'function') {
  161. callback()
  162. }
  163. })
  164. }
  165. connect(cb) {
  166. if (this.ending) {
  167. const err = new Error('Cannot use a pool after calling end on the pool')
  168. return cb ? cb(err) : this.Promise.reject(err)
  169. }
  170. const response = promisify(this.Promise, cb)
  171. const result = response.result
  172. // if we don't have to connect a new client, don't do so
  173. if (this._isFull() || this._idle.length) {
  174. // if we have idle clients schedule a pulse immediately
  175. if (this._idle.length) {
  176. process.nextTick(() => this._pulseQueue())
  177. }
  178. if (!this.options.connectionTimeoutMillis) {
  179. this._pendingQueue.push(new PendingItem(response.callback))
  180. return result
  181. }
  182. const queueCallback = (err, res, done) => {
  183. clearTimeout(tid)
  184. response.callback(err, res, done)
  185. }
  186. const pendingItem = new PendingItem(queueCallback)
  187. // set connection timeout on checking out an existing client
  188. const tid = setTimeout(() => {
  189. // remove the callback from pending waiters because
  190. // we're going to call it with a timeout error
  191. removeWhere(this._pendingQueue, (i) => i.callback === queueCallback)
  192. pendingItem.timedOut = true
  193. response.callback(new Error('timeout exceeded when trying to connect'))
  194. }, this.options.connectionTimeoutMillis)
  195. if (tid.unref) {
  196. tid.unref()
  197. }
  198. this._pendingQueue.push(pendingItem)
  199. return result
  200. }
  201. this.newClient(new PendingItem(response.callback))
  202. return result
  203. }
  204. newClient(pendingItem) {
  205. const client = new this.Client(this.options)
  206. this._clients.push(client)
  207. const idleListener = makeIdleListener(this, client)
  208. this.log('checking client timeout')
  209. // connection timeout logic
  210. let tid
  211. let timeoutHit = false
  212. if (this.options.connectionTimeoutMillis) {
  213. tid = setTimeout(() => {
  214. if (client.connection) {
  215. this.log('ending client due to timeout')
  216. timeoutHit = true
  217. client.connection.stream.destroy()
  218. } else if (!client.isConnected()) {
  219. this.log('ending client due to timeout')
  220. timeoutHit = true
  221. // force kill the node driver, and let libpq do its teardown
  222. client.end()
  223. }
  224. }, this.options.connectionTimeoutMillis)
  225. }
  226. this.log('connecting new client')
  227. client.connect((err) => {
  228. if (tid) {
  229. clearTimeout(tid)
  230. }
  231. client.on('error', idleListener)
  232. if (err) {
  233. this.log('client failed to connect', err)
  234. // remove the dead client from our list of clients
  235. this._clients = this._clients.filter((c) => c !== client)
  236. if (timeoutHit) {
  237. err = new Error('Connection terminated due to connection timeout', { cause: err })
  238. }
  239. // this client won’t be released, so move on immediately
  240. this._pulseQueue()
  241. if (!pendingItem.timedOut) {
  242. pendingItem.callback(err, undefined, NOOP)
  243. }
  244. } else {
  245. this.log('new client connected')
  246. if (this.options.onConnect) {
  247. this._promiseTry(() => this.options.onConnect(client)).then(
  248. () => {
  249. this._afterConnect(client, pendingItem, idleListener)
  250. },
  251. (hookErr) => {
  252. this._clients = this._clients.filter((c) => c !== client)
  253. client.end(() => {
  254. this._pulseQueue()
  255. if (!pendingItem.timedOut) {
  256. pendingItem.callback(hookErr, undefined, NOOP)
  257. }
  258. })
  259. }
  260. )
  261. return
  262. }
  263. return this._afterConnect(client, pendingItem, idleListener)
  264. }
  265. })
  266. }
  267. _afterConnect(client, pendingItem, idleListener) {
  268. if (this.options.maxLifetimeSeconds !== 0) {
  269. const maxLifetimeTimeout = setTimeout(() => {
  270. this.log('ending client due to expired lifetime')
  271. this._expired.add(client)
  272. const idleIndex = this._idle.findIndex((idleItem) => idleItem.client === client)
  273. if (idleIndex !== -1) {
  274. this._acquireClient(
  275. client,
  276. new PendingItem((err, client, clientRelease) => clientRelease()),
  277. idleListener,
  278. false
  279. )
  280. }
  281. }, this.options.maxLifetimeSeconds * 1000)
  282. maxLifetimeTimeout.unref()
  283. client.once('end', () => clearTimeout(maxLifetimeTimeout))
  284. }
  285. return this._acquireClient(client, pendingItem, idleListener, true)
  286. }
  287. // acquire a client for a pending work item
  288. _acquireClient(client, pendingItem, idleListener, isNew) {
  289. if (isNew) {
  290. this.emit('connect', client)
  291. }
  292. this.emit('acquire', client)
  293. client.release = this._releaseOnce(client, idleListener)
  294. client.removeListener('error', idleListener)
  295. if (!pendingItem.timedOut) {
  296. if (isNew && this.options.verify) {
  297. this.options.verify(client, (err) => {
  298. if (err) {
  299. client.release(err)
  300. return pendingItem.callback(err, undefined, NOOP)
  301. }
  302. pendingItem.callback(undefined, client, client.release)
  303. })
  304. } else {
  305. pendingItem.callback(undefined, client, client.release)
  306. }
  307. } else {
  308. if (isNew && this.options.verify) {
  309. this.options.verify(client, client.release)
  310. } else {
  311. client.release()
  312. }
  313. }
  314. }
  315. // returns a function that wraps _release and throws if called more than once
  316. _releaseOnce(client, idleListener) {
  317. let released = false
  318. return (err) => {
  319. if (released) {
  320. throwOnDoubleRelease()
  321. }
  322. released = true
  323. this._release(client, idleListener, err)
  324. }
  325. }
  326. // release a client back to the poll, include an error
  327. // to remove it from the pool
  328. _release(client, idleListener, err) {
  329. client.on('error', idleListener)
  330. client._poolUseCount = (client._poolUseCount || 0) + 1
  331. this.emit('release', err, client)
  332. // TODO(bmc): expose a proper, public interface _queryable and _ending
  333. if (err || this.ending || !client._queryable || client._ending || client._poolUseCount >= this.options.maxUses) {
  334. if (client._poolUseCount >= this.options.maxUses) {
  335. this.log('remove expended client')
  336. }
  337. return this._remove(client, this._pulseQueue.bind(this))
  338. }
  339. const isExpired = this._expired.has(client)
  340. if (isExpired) {
  341. this.log('remove expired client')
  342. this._expired.delete(client)
  343. return this._remove(client, this._pulseQueue.bind(this))
  344. }
  345. // idle timeout
  346. let tid
  347. if (this.options.idleTimeoutMillis && this._isAboveMin()) {
  348. tid = setTimeout(() => {
  349. if (this._isAboveMin()) {
  350. this.log('remove idle client')
  351. this._remove(client, this._pulseQueue.bind(this))
  352. }
  353. }, this.options.idleTimeoutMillis)
  354. if (this.options.allowExitOnIdle) {
  355. // allow Node to exit if this is all that's left
  356. tid.unref()
  357. }
  358. }
  359. if (this.options.allowExitOnIdle) {
  360. client.unref()
  361. }
  362. this._idle.push(new IdleItem(client, idleListener, tid))
  363. this._pulseQueue()
  364. }
  365. query(text, values, cb) {
  366. // guard clause against passing a function as the first parameter
  367. if (typeof text === 'function') {
  368. const response = promisify(this.Promise, text)
  369. setImmediate(function () {
  370. return response.callback(new Error('Passing a function as the first parameter to pool.query is not supported'))
  371. })
  372. return response.result
  373. }
  374. // allow plain text query without values
  375. if (typeof values === 'function') {
  376. cb = values
  377. values = undefined
  378. }
  379. const response = promisify(this.Promise, cb)
  380. cb = response.callback
  381. this.connect((err, client) => {
  382. if (err) {
  383. return cb(err)
  384. }
  385. let clientReleased = false
  386. const onError = (err) => {
  387. if (clientReleased) {
  388. return
  389. }
  390. clientReleased = true
  391. client.release(err)
  392. cb(err)
  393. }
  394. client.once('error', onError)
  395. this.log('dispatching query')
  396. try {
  397. client.query(text, values, (err, res) => {
  398. this.log('query dispatched')
  399. client.removeListener('error', onError)
  400. if (clientReleased) {
  401. return
  402. }
  403. clientReleased = true
  404. client.release(err)
  405. if (err) {
  406. return cb(err)
  407. }
  408. return cb(undefined, res)
  409. })
  410. } catch (err) {
  411. client.release(err)
  412. return cb(err)
  413. }
  414. })
  415. return response.result
  416. }
  417. end(cb) {
  418. this.log('ending')
  419. if (this.ending) {
  420. const err = new Error('Called end on pool more than once')
  421. return cb ? cb(err) : this.Promise.reject(err)
  422. }
  423. this.ending = true
  424. const promised = promisify(this.Promise, cb)
  425. this._endCallback = promised.callback
  426. this._pulseQueue()
  427. return promised.result
  428. }
  429. get waitingCount() {
  430. return this._pendingQueue.length
  431. }
  432. get idleCount() {
  433. return this._idle.length
  434. }
  435. get expiredCount() {
  436. return this._clients.reduce((acc, client) => acc + (this._expired.has(client) ? 1 : 0), 0)
  437. }
  438. get totalCount() {
  439. return this._clients.length
  440. }
  441. }
  442. module.exports = Pool