From a68426eca880f2ca2656d6a4f292163557905ea6 Mon Sep 17 00:00:00 2001 From: Josh Betz Date: Mon, 21 Nov 2022 15:43:36 -0600 Subject: [PATCH] Better Pool.ready() 1. If the pool is closing, throw immediately 2. If the pool is already ready, don't pool 3. Unref the timeout so we don't block shutdown --- src/pool.ts | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/src/pool.ts b/src/pool.ts index a2171f7..07b423e 100644 --- a/src/pool.ts +++ b/src/pool.ts @@ -6,11 +6,13 @@ export default class Pool extends EventEmitter { opts: any; pool: GenericPool; failures: number; + closing: boolean; constructor( port: number, host: string, opts?: any ) { super(); this.failures = 0; + this.closing = false; this.opts = Object.assign( { failures: 5, @@ -53,12 +55,27 @@ export default class Pool extends EventEmitter { } async ready() { + if ( this.closing ) { + throw new Error( 'Closing' ); + } + + if ( this.pool.available >= this.pool.min ) { + return true; + } + return new Promise( ( resolve, reject ) => { const timeout = setTimeout( () => reject( new Error( 'Timeout' ) ), this.opts.timeout ).unref(); - this.pool.ready().then( () => { - clearTimeout( timeout ); - resolve( true ); - } ); + + const isReady = () => { + if ( this.pool.available >= this.pool.min ) { + clearTimeout( timeout ); + resolve( true ); + } else { + setTimeout( isReady, 100 ).unref(); + } + }; + + isReady(); } ); } @@ -105,6 +122,7 @@ export default class Pool extends EventEmitter { } async end() { + this.closing = true; await this.pool.drain(); await this.pool.clear(); }