Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

generic-pool

coopernurse12.9mMIT3.9.0TypeScript support: included

Generic resource pooling for Node.JS

pool, pooling, throttle

readme

build status

Generic Pool

About

Generic resource pool with Promise based API. Can be used to reuse or throttle usage of expensive resources such as database connections.

V3 upgrade warning

Version 3 contains many breaking changes. The differences are mostly minor and I hope easy to accommodate. There is a very rough and basic upgrade guide I've written, improvements and other attempts most welcome.

If you are after the older version 2 of this library you should look at the current github branch for it.

History

The history has been moved to the CHANGELOG

Installation

$ npm install generic-pool [--save]

Example

Here is an example using a fictional generic database driver that doesn't implement any pooling whatsoever itself.

const genericPool = require("generic-pool");
const DbDriver = require("some-db-driver");

/**
 * Step 1 - Create pool using a factory object
 */
const factory = {
  create: function() {
    return DbDriver.createClient();
  },
  destroy: function(client) {
    client.disconnect();
  }
};

const opts = {
  max: 10, // maximum size of the pool
  min: 2 // minimum size of the pool
};

const myPool = genericPool.createPool(factory, opts);

/**
 * Step 2 - Use pool in your code to acquire/release resources
 */

// acquire connection - Promise is resolved
// once a resource becomes available
const resourcePromise = myPool.acquire();

resourcePromise
  .then(function(client) {
    client.query("select * from foo", [], function() {
      // return object back to pool
      myPool.release(client);
    });
  })
  .catch(function(err) {
    // handle error - this is generally a timeout or maxWaitingClients
    // error
  });

/**
 * Step 3 - Drain pool during shutdown (optional)
 */
// Only call this once in your application -- at the point you want
// to shutdown and stop using this pool.
myPool.drain().then(function() {
  myPool.clear();
});

Documentation

Creating a pool

Whilst it is possible to directly instantiate the Pool class directly, it is recommended to use the createPool function exported by module as the constructor method signature may change in the future.

createPool

The createPool function takes two arguments:

  • factory : an object containing functions to create/destroy/test resources for the Pool
  • opts : an optional object/dictonary to allow configuring/altering behaviour of the Pool
const genericPool = require('generic-pool')
const pool = genericPool.createPool(factory, opts)

factory

Can be any object/instance but must have the following properties:

  • create : a function that the pool will call when it wants a new resource. It should return a Promise that either resolves to a resource or rejects to an Error if it is unable to create a resource for whatever reason.
  • destroy: a function that the pool will call when it wants to destroy a resource. It should accept one argument resource where resource is whatever factory.create made. The destroy function should return a Promise that resolves once it has destroyed the resource.

optionally it can also have the following property:

  • validate: a function that the pool will call if it wants to validate a resource. It should accept one argument resource where resource is whatever factory.create made. Should return a Promise that resolves a boolean where true indicates the resource is still valid or false if the resource is invalid.

Note: The values returned from create, destroy, and validate are all wrapped in a Promise.resolve by the pool before being used internally.

opts

An optional object/dictionary with the any of the following properties:

  • max: maximum number of resources to create at any given time. (default=1)
  • min: minimum number of resources to keep in pool at any given time. If this is set >= max, the pool will silently set the min to equal max. (default=0)
  • maxWaitingClients: maximum number of queued requests allowed, additional acquire calls will be callback with an err in a future cycle of the event loop.
  • testOnBorrow: boolean: should the pool validate resources before giving them to clients. Requires that factory.validate is specified.
  • acquireTimeoutMillis: max milliseconds an acquire call will wait for a resource before timing out. (default no limit), if supplied should non-zero positive integer.
  • destroyTimeoutMillis: max milliseconds a destroy call will wait for a resource before timing out. (default no limit), if supplied should non-zero positive integer.
  • fifo : if true the oldest resources will be first to be allocated. If false the most recently released resources will be the first to be allocated. This in effect turns the pool's behaviour from a queue into a stack. boolean, (default true)
  • priorityRange: int between 1 and x - if set, borrowers can specify their relative priority in the queue if no resources are available.
                       see example.  (default 1)
  • autostart: boolean, should the pool start creating resources, initialize the evictor, etc once the constructor is called. If false, the pool can be started by calling pool.start, otherwise the first call to acquire will start the pool. (default true)
  • evictionRunIntervalMillis: How often to run eviction checks. Default: 0 (does not run).
  • numTestsPerEvictionRun: Number of resources to check each eviction run. Default: 3.
  • softIdleTimeoutMillis: amount of time an object may sit idle in the pool before it is eligible for eviction by the idle object evictor (if any), with the extra condition that at least "min idle" object instances remain in the pool. Default -1 (nothing can get evicted)
  • idleTimeoutMillis: the minimum amount of time that an object may sit idle in the pool before it is eligible for eviction due to idle time. Supercedes softIdleTimeoutMillis Default: 30000
  • Promise: Promise lib, a Promises/A+ implementation that the pool should use. Defaults to whatever global.Promise is (usually native promises).

pool.acquire

const onfulfilled = function(resource){
    resource.doStuff()
    // release/destroy/etc
}

pool.acquire().then(onfulfilled)
//or
const priority = 2
pool.acquire(priority).then(onfulfilled)

This function is for when you want to "borrow" a resource from the pool.

acquire takes one optional argument:

  • priority: optional, number, see Priority Queueing below.

and returns a Promise Once a resource in the pool is available, the promise will be resolved with a resource (whatever factory.create makes for you). If the Pool is unable to give a resource (e.g timeout) then the promise will be rejected with an Error

pool.release

pool.release(resource)

This function is for when you want to return a resource to the pool.

release takes one required argument:

  • resource: a previously borrowed resource

and returns a Promise. This promise will resolve once the resource is accepted by the pool, or reject if the pool is unable to accept the resource for any reason (e.g resource is not a resource or object that came from the pool). If you do not care the outcome it is safe to ignore this promise.

pool.isBorrowedResource

pool.isBorrowedResource(resource)

This function is for when you need to check if a resource has been acquired from the pool and not yet released/destroyed.

isBorrowedResource takes one required argument:

  • resource: any object which you need to test

and returns true (primitive, not Promise) if resource is currently borrowed from the pool, false otherwise.

pool.destroy

pool.destroy(resource)

This function is for when you want to return a resource to the pool but want it destroyed rather than being made available to other resources. E.g you may know the resource has timed out or crashed.

destroy takes one required argument:

  • resource: a previously borrowed resource

and returns a Promise. This promise will resolve once the resource is accepted by the pool, or reject if the pool is unable to accept the resource for any reason (e.g resource is not a resource or object that came from the pool). If you do not care the outcome it is safe to ignore this promise.

pool.on

pool.on('factoryCreateError', function(err){
  //log stuff maybe
})

pool.on('factoryDestroyError', function(err){
  //log stuff maybe
})

The pool is an event emitter. Below are the events it emits and any args for those events

  • factoryCreateError : emitted when a promise returned by factory.create is rejected. If this event has no listeners then the error will be silently discarded

    • error: whatever reason the promise was rejected with.
  • factoryDestroyError : emitted when a promise returned by factory.destroy is rejected. If this event has no listeners then the error will be silently discarded

    • error: whatever reason the promise was rejected with.

pool.start

pool.start()

If autostart is false then this method can be used to start the pool and therefore begin creation of resources, start the evictor, and any other internal logic.

pool.ready

pool.ready()

Waits for the pool to fully start.

pool.use


const myTask = dbClient => {
  return new Promise( (resolve, reject) => {
    // do something with the client and resolve/reject
    })
}

pool.use(myTask).then(/* a promise that will run after myTask resolves */)

This method handles acquiring a resource from the pool, handing it to your function and then calling pool.release or pool.destroy with resource after your function has finished.

use takes one required argument:

  • fn: a function that accepts a resource and returns a Promise. Once that promise resolves the resource is returned to the pool, else if it rejects then the resource is destroyed.
  • priority: Optionally, you can specify the priority as number. See Priority Queueing section.

and returns a Promise that either resolves with the value from the user supplied fn or rejects with an error.

Idle Object Eviction

The pool has an evictor (off by default) which will inspect idle items in the pool and destroy them if they are too old.

By default the evictor does not run, to enable it you must set the evictionRunIntervalMillis option to a non-zero value. Once enable the evictor will check at most numTestsPerEvictionRun each time, this is to stop it blocking your application if you have lots of resources in the pool.

Priority Queueing

The pool supports optional priority queueing. This becomes relevant when no resources are available and the caller has to wait. acquire() accepts an optional priority int which specifies the caller's relative position in the queue. Each priority slot has it's own internal queue created for it. When a resource is available for borrowing, the first request in the highest priority queue will be given it.

Specifying a priority to acquire that is outside the priorityRange set at Pool creation time will result in the priority being converted the lowest possible priority

// create pool with priorityRange of 3
// borrowers can specify a priority 0 to 2
const opts = {
  priorityRange : 3
}
const pool = genericPool.createPool(someFactory,opts);

// acquire connection - no priority specified - will go onto lowest priority queue
pool.acquire().then(function(client) {
    pool.release(client);
});

// acquire connection - high priority - will go into highest priority queue
pool.acquire(0).then(function(client) {
    pool.release(client);
});

// acquire connection - medium priority - will go into 'mid' priority queue
pool.acquire(1).then(function(client) {
    pool.release(client);
});

// etc..

Draining

If you are shutting down a long-lived process, you may notice that node fails to exit for 30 seconds or so. This is a side effect of the idleTimeoutMillis behavior -- the pool has a setTimeout() call registered that is in the event loop queue, so node won't terminate until all resources have timed out, and the pool stops trying to manage them.

This behavior will be more problematic when you set factory.min > 0, as the pool will never become empty, and the setTimeout calls will never end.

In these cases, use the pool.drain() function. This sets the pool into a "draining" state which will gracefully wait until all idle resources have timed out. For example, you can call:

If you do this, your node process will exit gracefully.

If you know you would like to terminate all the available resources in your pool before any timeouts they might have are reached, you can use clear() in conjunction with drain():

const p = pool.drain()
.then(function() {
    return pool.clear();
});

The promise returned will resolve once all waiting clients have acquired and return resources, and any available resources have been destroyed

One side-effect of calling drain() is that subsequent calls to acquire() will throw an Error.

Pooled function decoration

This has now been extracted out it's own module generic-pool-decorator

Pool info

The following properties will let you get information about the pool:


// How many many more resources can the pool manage/create
pool.spareResourceCapacity

// returns number of resources in the pool regardless of
// whether they are free or in use
pool.size

// returns number of unused resources in the pool
pool.available

// number of resources that are currently acquired by userland code
pool.borrowed

// returns number of callers waiting to acquire a resource
pool.pending

// returns number of maxixmum number of resources allowed by pool
pool.max

// returns number of minimum number of resources allowed by pool
pool.min

Run Tests

$ npm install
$ npm test

The tests are run/written using Tap. Most are ports from the old espresso tests and are not in great condition. Most cases are inside test/generic-pool-test.js with newer cases in their own files (legacy reasons).

Linting

We use eslint combined with prettier

License

(The MIT License)

Copyright (c) 2010-2016 James Cooper <james@bitmechanic.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

3.9.0 (2022-09-10)

Bug Fixes

  • add ready function to index.d.ts (0a5ef1d)
  • unref setTimeout in pool (e94fd37)

3.7.1 - March 28 2019

  • fix #257 - pool.use now destroys resources on rejection, matching the docs.

3.6.1 - Febuary 6 2019

  • fix #251 - silence bluebird warning about side-effect only handler (@sandfox)
  • Pool.clear no longer resolves to pointless array on undefineds (@restjohn)

3.6.0 - Febuary 4 2019

  • update docs (@chdh)
  • fix #159 - pool.clear can no longer "skip" clearing up resources when called early in pool lifecycle (@sandfox)

3.5.0 - January 17 2019

  • update nodejs versions tested by travis
  • eviction iterator no longer stops when reaching end of object list #243 (@DiegoRBaquero)
  • fix #192 softIdleTimeoutMillis = -1 no longer triggers evictor to run #242 (@DiegoRBaquero)
  • fix #234 maxWaitingClients = 0 is no longer ignored #247 (@anupbaldawa)

3.4.2 - Febuary 16 2018

  • fix pool.use to resolve after user supplied function has finished. (@asannes)

3.4.1 - Febuary 1 2018

  • prevent timed-out resource requests from being issued resources (@rebareba)

3.4.0 - December 27 2017

  • 218 fix numerous docblock annotations and minor errors in internal classes (@geovanisouza92)

3.3.0 - December 27 2017

  • add use method to simplify basic pool usage (@san00)

3.2.0 - October 15 2017

  • add isBorrowedResource method to check if objects are currently on loan from pool (@C-h-e-r-r-y)

3.1.8 - September 14 2017

  • fix undefined and annoying autostart=false behaviour (@sushantdhiman)
  • document autostart behaviour (@sandfox)
  • fix typos (@wvanderdeijl @AlexTes)

3.1.7 - Febuary 9 2017

  • fix warning when using bluebird promise impl (@benny-medflyt)

3.1.6 - December 28 2016

  • fix #173 where pool would not attempt to dispense reources upon pool.destroy
  • fix some out of date readme section
  • fix test warning for unhandled rejection on dispense

3.1.5 - December 20 2016

  • fix drain code to correctly wait on borrowed resources (@drew-r)
  • fix drain example in readme (@watson)

3.1.4 - November 28 2016

  • fix faulty Promise detection where user supplied promise lib would be ignored

3.1.3 - November 26 2016

  • internal refactoring and comment improvements
  • fix #159 so draining and closing don't leave resources behind
  • stop the evictor from keeping the event loop open after draining

3.1.2 - November 22 2016

  • Readme tidy up
  • Add missing changelog entry

3.1.1 - November 18 2016

  • Add Readme link for legacy branch

3.1.0 - November 6 2016

  • Inject dependencies into Pool to allow easier user extension

3.0.1 - November 1 2016

  • Passthrough Pool's promise impl to deferreds so they are used internally and exposed correctly on pool.acquire (@eide)

3.0.0 - October 30 2016

  • This is pretty big and the migration guide in the README has more detailed set of changes!
  • switch support to nodejs v4 and above
  • change external interfaces to use promises instead of callbacks
  • remove logging
  • decouple create/destroy operations from acquire/release operations
  • pool should now be created via poolCreate factory method instead of constructor.
  • huge internal rewrite and flow control changes
  • Pool is now an eventEmitter

2.4.3 - October 15 2016

  • Use domain.bind to preserve domain context (@LewisJEllis)

2.4.2 - March 26 2016

  • Travis now runs and fails lint checks (@kevinburke)
  • fixed bug #128 where using async validation incorrectly tracked resource state (@johnjdooley and @robfyfe)
  • fixed broken readme example that had aged badly

2.4.1 - February 20 2016

  • Documented previously created/fixed bug #122 (thanks @jasonrhodes)
  • Improved Makefile and test runner docs thanks (@kevinburke)
  • fixed bug documented in #121 where pool could make incorrect decisions about which resources were eligible for removal. (thanks @mikemorris)

2.4.0 - January 18 2016

  • Merged #118 - closes #110 - optional eslinting for test and lib using "standard" ruleset
  • Merged #114 - closes #113 - "classes" now used internally instead of object literals and exports support being called as a constructor (along with old factory behaviour) (contributed by @felixfbecker)
  • Move history from README.md to CHANGELOG.md and reformat
  • Closes #122 - fixes trapped connection bug when destroying a connection while others are in use

2.3.1 - January 7 2016

  • Documentation fixes and widened number of nodejs versions tested on travis

2.3.0 - January 1 2016

  • Merged #105 - allow asynchronous validate functions (contributed by @felipou)

2.2.2 - December 13 2015

  • Merged #106 - fix condition where non "resource pool" created objects could be returned to the pool. (contributed by @devzer01)

2.2.1 - October 30 2015

  • Merged #104 - fix #103 - condition where pool can create > specified max number of connections (contributed by @devzer01)

2.2.0 - March 26 2015

  • Merged #92 - add getMaxPoolSize function (contributed by platypusMaximus)

2.1.1 - July 5 2015

  • fix README error about priority queueing (spotted by @kmdm)

2.1.0 - June 19 2014

  • Merged #72 - Add optional returnToHead flag, if true, resources are returned to head of queue (stack like behaviour) upon release (contributed by calibr), also see #68 for further discussion.

2.0.4 - July 27 2013

  • Merged #64 - Fix for not removing idle objects (contributed by PiotrWpl)

2.0.3 - January 16 2013

  • Merged #56/#57 - Add optional refreshIdle flag. If false, idle resources at the pool minimum will not be destroyed/re-created. (contributed by wshaver)
  • Merged #54 - Factory can be asked to validate pooled objects (contributed by tikonen)

2.0.2 - October 22 2012

  • Fix #51, #48 - createResource() should check for null clientCb in err case (contributed by pooyasencha)
  • Merged #52 - fix bug of infinite wait when create object aync error (contributed by windyrobin)
  • Merged #53 - change the position of dispense and callback to ensure the time order (contributed by windyrobin)

2.0.1 - August 29 2012

  • Fix #44 - leak of 'err' and 'obj' in createResource()
  • Add devDependencies block to package.json
  • Add travis-ci.org integration

2.0.0 - July 31 2012

  • Non-backwards compatible change: remove adjustCallback
    • acquire() callback must accept two params: (err, obj)
  • Add optional 'min' param to factory object that specifies minimum number of resources to keep in pool
  • Merged #38 (package.json/Makefile changes - contributed by strk)

[1.0.12] - June 27 2012

  • Merged #37 (Clear remove idle timer after destroyAllNow - contributed by dougwilson)

[1.0.11] - June 17 2012

  • Merged #36 ("pooled" method to perform function decoration for pooled methods - contributed by cosbynator)

[1.0.10] - May 3 2012

  • Merged #35 (Remove client from availbleObjects on destroy(client) - contributed by blax)

[1.0.9] - Dec 18 2011

  • Merged #25 (add getName() - contributed by BryanDonovan)
  • Merged #27 (remove sys import - contributed by botker)
  • Merged #26 (log levels - contributed by JoeZ99)

[1.0.8] - Nov 16 2011

  • Merged #21 (add getter methods to see pool size, etc. - contributed by BryanDonovan)

[1.0.7] - Oct 17 2011

  • Merged #19 (prevent release on the same obj twice - contributed by tkrynski)
  • Merged #20 (acquire() returns boolean indicating whether pool is full - contributed by tilgovi)

[1.0.6] - May 23 2011

  • Merged #13 (support error variable in acquire callback - contributed by tmcw)
    • Note: This change is backwards compatible. But new code should use the two parameter callback format in pool.create() functions from now on.
  • Merged #15 (variable scope issue in dispense() - contributed by eevans)

[1.0.5] - Apr 20 2011

  • Merged #12 (ability to drain pool - contributed by gdusbabek)

[1.0.4] - Jan 25 2011

  • Fixed #6 (objects reaped with undefined timeouts)
  • Fixed #7 (objectTimeout issue)

[1.0.3] - Dec 9 2010

  • Added priority queueing (thanks to sylvinus)
  • Contributions from Poetro
    • Name changes to match conventions described here: http://en.wikipedia.org/wiki/Object_pool_pattern
      • borrow() renamed to acquire()
      • returnToPool() renamed to release()
    • destroy() removed from public interface
    • added JsDoc comments
    • Priority queueing enhancements

[1.0.2] - Nov 9 2010

  • First NPM release

=======