@@ -84,6 +84,7 @@ class Pool extends EventEmitter {
84
84
this . options . max = this . options . max || this . options . poolSize || 10
85
85
this . options . maxUses = this . options . maxUses || Infinity
86
86
this . options . allowExitOnIdle = this . options . allowExitOnIdle || false
87
+ this . options . maxLifetimeSeconds = this . options . maxLifetimeSeconds || 0
87
88
this . log = this . options . log || function ( ) { }
88
89
this . Client = this . options . Client || Client || require ( 'pg' ) . Client
89
90
this . Promise = this . options . Promise || global . Promise
@@ -94,6 +95,7 @@ class Pool extends EventEmitter {
94
95
95
96
this . _clients = [ ]
96
97
this . _idle = [ ]
98
+ this . _expired = new WeakSet ( )
97
99
this . _pendingQueue = [ ]
98
100
this . _endCallback = undefined
99
101
this . ending = false
@@ -123,6 +125,7 @@ class Pool extends EventEmitter {
123
125
}
124
126
return
125
127
}
128
+
126
129
// if we don't have any waiting, do nothing
127
130
if ( ! this . _pendingQueue . length ) {
128
131
this . log ( 'no queued requests' )
@@ -248,6 +251,19 @@ class Pool extends EventEmitter {
248
251
} else {
249
252
this . log ( 'new client connected' )
250
253
254
+ if ( 0 !== this . options . maxLifetimeSeconds ) {
255
+ setTimeout ( ( ) => {
256
+ this . log ( 'ending client due to expired lifetime' )
257
+ this . _expired . add ( client )
258
+ if ( this . _idle . length ) {
259
+ const idleIndex = this . _idle . findIndex ( idleItem => idleItem . client === client )
260
+ if ( - 1 !== idleIndex ) {
261
+ this . _acquireClient ( client , new PendingItem ( ( err , client , clientRelease ) => clientRelease ( ) ) , idleListener , false )
262
+ }
263
+ }
264
+ } , this . options . maxLifetimeSeconds * 1000 )
265
+ }
266
+
251
267
return this . _acquireClient ( client , pendingItem , idleListener , true )
252
268
}
253
269
} )
@@ -318,6 +334,15 @@ class Pool extends EventEmitter {
318
334
return
319
335
}
320
336
337
+ const isExpired = this . _expired . has ( client )
338
+ if ( isExpired ) {
339
+ this . log ( 'remove expired client' )
340
+ this . _expired . delete ( client )
341
+ this . _remove ( client )
342
+ this . _pulseQueue ( )
343
+ return
344
+ }
345
+
321
346
// idle timeout
322
347
let tid
323
348
if ( this . options . idleTimeoutMillis ) {
@@ -414,6 +439,10 @@ class Pool extends EventEmitter {
414
439
return this . _idle . length
415
440
}
416
441
442
+ get expiredCount ( ) {
443
+ return this . _clients . reduce ( ( acc , client ) => acc + ( this . _expired . has ( client ) ? 1 : 0 ) , 0 )
444
+ }
445
+
417
446
get totalCount ( ) {
418
447
return this . _clients . length
419
448
}
0 commit comments