Skip to content

Commit

Permalink
Better Pool.ready()
Browse files Browse the repository at this point in the history
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
  • Loading branch information
joshbetz committed Nov 21, 2022
1 parent b834de6 commit a68426e
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions src/pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ export default class Pool extends EventEmitter {
opts: any;
pool: GenericPool<Memcached>;
failures: number;
closing: boolean;

constructor( port: number, host: string, opts?: any ) {
super();

this.failures = 0;
this.closing = false;

this.opts = Object.assign( {
failures: 5,
Expand Down Expand Up @@ -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();
} );
}

Expand Down Expand Up @@ -105,6 +122,7 @@ export default class Pool extends EventEmitter {
}

async end() {
this.closing = true;
await this.pool.drain();
await this.pool.clear();
}
Expand Down

0 comments on commit a68426e

Please sign in to comment.