@@ -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,17 @@ class Pool extends EventEmitter {
248
251
} else {
249
252
this . log ( 'new client connected' )
250
253
254
+ if ( this . options . maxLifetimeSeconds !== 0 ) {
255
+ setTimeout ( ( ) => {
256
+ this . log ( 'ending client due to expired lifetime' )
257
+ this . _expired . add ( client )
258
+ const idleIndex = this . _idle . findIndex ( idleItem => idleItem . client === client )
259
+ if ( idleIndex !== - 1 ) {
260
+ this . _acquireClient ( client , new PendingItem ( ( err , client , clientRelease ) => clientRelease ( ) ) , idleListener , false )
261
+ }
262
+ } , this . options . maxLifetimeSeconds * 1000 )
263
+ }
264
+
251
265
return this . _acquireClient ( client , pendingItem , idleListener , true )
252
266
}
253
267
} )
@@ -318,6 +332,15 @@ class Pool extends EventEmitter {
318
332
return
319
333
}
320
334
335
+ const isExpired = this . _expired . has ( client )
336
+ if ( isExpired ) {
337
+ this . log ( 'remove expired client' )
338
+ this . _expired . delete ( client )
339
+ this . _remove ( client )
340
+ this . _pulseQueue ( )
341
+ return
342
+ }
343
+
321
344
// idle timeout
322
345
let tid
323
346
if ( this . options . idleTimeoutMillis ) {
@@ -414,6 +437,10 @@ class Pool extends EventEmitter {
414
437
return this . _idle . length
415
438
}
416
439
440
+ get expiredCount ( ) {
441
+ return this . _clients . reduce ( ( acc , client ) => acc + ( this . _expired . has ( client ) ? 1 : 0 ) , 0 )
442
+ }
443
+
417
444
get totalCount ( ) {
418
445
return this . _clients . length
419
446
}
0 commit comments