pax_global_header00006660000000000000000000000064143070321650014513gustar00rootroot0000000000000052 comment=89080aea76252728aeabd28d36ef3e2e77fc950b node-pool-3.9.0/000077500000000000000000000000001430703216500134205ustar00rootroot00000000000000node-pool-3.9.0/.eslintignore000066400000000000000000000000161430703216500161200ustar00rootroot00000000000000!.eslintrc.js node-pool-3.9.0/.eslintrc.js000066400000000000000000000002351430703216500156570ustar00rootroot00000000000000module.exports = { parserOptions: { ecmaVersion: 6 }, plugins: ["prettier"], rules: { "prettier/prettier": "error" }, extends: ["prettier"] }; node-pool-3.9.0/.gitignore000066400000000000000000000000701430703216500154050ustar00rootroot00000000000000fabfile.pyc node-pool.iml node-pool.tmproj node_modules node-pool-3.9.0/.npmignore000066400000000000000000000001051430703216500154130ustar00rootroot00000000000000.eslintignore .eslintrc.js .travis.yml Makefile tsconfig.json test/* node-pool-3.9.0/.travis.yml000066400000000000000000000003031430703216500155250ustar00rootroot00000000000000language: node_js arch: - amd64 - ppc64le node_js: - "6" - "8" - "10" - "11" install: - make install script: - make lint - make test sudo: false matrix: fast_finish: true node-pool-3.9.0/CHANGELOG.md000066400000000000000000000264621430703216500152430ustar00rootroot00000000000000# Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ## [3.9.0](https://github.com/coopernurse/node-pool/compare/v3.8.2...v3.9.0) (2022-09-10) ### Bug Fixes * add ready function to index.d.ts ([0a5ef1d](https://github.com/coopernurse/node-pool/commit/0a5ef1dd9124ea7d56626c7cc295e181c15ad4e2)) * unref setTimeout in pool ([e94fd37](https://github.com/coopernurse/node-pool/commit/e94fd374266acb1531b986050ba7486b03b18250)) ## [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 ======= [unreleased]: https://github.com/coopernurse/node-pool/compare/v3.7.1...HEAD [3.7.1]: https://github.com/coopernurse/node-pool/compare/v3.6.1...v3.7.1 [3.6.1]: https://github.com/coopernurse/node-pool/compare/v3.6.0...v3.6.1 [3.6.0]: https://github.com/coopernurse/node-pool/compare/v3.5.0...v3.6.0 [3.5.0]: https://github.com/coopernurse/node-pool/compare/v3.4.2...v3.5.0 [3.4.2]: https://github.com/coopernurse/node-pool/compare/v3.4.1...v3.4.2 [3.4.1]: https://github.com/coopernurse/node-pool/compare/v3.4.0...v3.4.1 [3.4.0]: https://github.com/coopernurse/node-pool/compare/v3.3.0...v3.4.0 [3.3.0]: https://github.com/coopernurse/node-pool/compare/v3.2.0...v3.3.0 [3.2.0]: https://github.com/coopernurse/node-pool/compare/v3.1.8...v3.2.0 [3.1.8]: https://github.com/coopernurse/node-pool/compare/v3.1.7...v3.1.8 [3.1.7]: https://github.com/coopernurse/node-pool/compare/v3.1.6...v3.1.7 [3.1.6]: https://github.com/coopernurse/node-pool/compare/v3.1.5...v3.1.6 [3.1.5]: https://github.com/coopernurse/node-pool/compare/v3.1.4...v3.1.5 [3.1.4]: https://github.com/coopernurse/node-pool/compare/v3.1.3...v3.1.4 [3.1.3]: https://github.com/coopernurse/node-pool/compare/v3.1.2...v3.1.3 [3.1.2]: https://github.com/coopernurse/node-pool/compare/v3.1.1...v3.1.2 [3.1.1]: https://github.com/coopernurse/node-pool/compare/v3.1.0...v3.1.1 [3.1.0]: https://github.com/coopernurse/node-pool/compare/v3.0.1...v3.1.0 [3.0.1]: https://github.com/coopernurse/node-pool/compare/v3.0.0...v3.0.1 [3.0.0]: https://github.com/coopernurse/node-pool/compare/v2.4.3...v3.0.0 [2.4.3]: https://github.com/coopernurse/node-pool/compare/v2.4.2...v2.4.3 [2.4.2]: https://github.com/coopernurse/node-pool/compare/v2.4.1...v2.4.2 [2.4.1]: https://github.com/coopernurse/node-pool/compare/v2.4.0...v2.4.1 [2.4.0]: https://github.com/coopernurse/node-pool/compare/v2.3.1...v2.4.0 [2.3.1]: https://github.com/coopernurse/node-pool/compare/v2.3.0...v2.3.1 [2.3.0]: https://github.com/coopernurse/node-pool/compare/v2.2.2...v2.3.0 [2.2.2]: https://github.com/coopernurse/node-pool/compare/v2.2.1...v2.2.2 [2.2.1]: https://github.com/coopernurse/node-pool/compare/v2.2.0...v2.2.1 [2.2.0]: https://github.com/coopernurse/node-pool/compare/v2.1.1...v2.2.0 [2.1.1]: https://github.com/coopernurse/node-pool/compare/v2.1.0...v2.1.1 [2.1.0]: https://github.com/coopernurse/node-pool/compare/v2.0.4...v2.1.0 [2.0.4]: https://github.com/coopernurse/node-pool/compare/v2.0.3...v2.0.4 [2.0.3]: https://github.com/coopernurse/node-pool/compare/v2.0.2...v2.0.3 [2.0.2]: https://github.com/coopernurse/node-pool/compare/v2.0.1...v2.0.2 [2.0.1]: https://github.com/coopernurse/node-pool/compare/v2.0.0...v2.0.1 [2.0.0]: https://github.com/coopernurse/node-pool/compare/v1.0.12...v2.0.0 node-pool-3.9.0/Makefile000066400000000000000000000002341430703216500150570ustar00rootroot00000000000000.PHONY: all clean install check test lint all: clean: rm -rf node_modules install: npm install check: npm test test: npm test lint: npm run lint node-pool-3.9.0/README.md000066400000000000000000000364651430703216500147150ustar00rootroot00000000000000[![build status](https://secure.travis-ci.org/coopernurse/node-pool.png)](http://travis-ci.org/coopernurse/node-pool) # 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](https://gist.github.com/sandfox/5ca20648b60a0cb959638c0cd6fcd02d) 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](https://github.com/coopernurse/node-pool/tree/v2.5) for it. ## History The history has been moved to the [CHANGELOG](CHANGELOG.md) ## Installation ```sh $ npm install generic-pool [--save] ``` ## Example Here is an example using a fictional generic database driver that doesn't implement any pooling whatsoever itself. ```js 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` ```js 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 ```js 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 ```js 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 ```js 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 ```js 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 ```js 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 ```js 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 ```js pool.ready() ``` Waits for the pool to fully start. ### pool.use ```js 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 `resolve`s the `resource` is returned to the pool, else if it `reject`s then the resource is destroyed. - `priority`: Optionally, you can specify the priority as number. See [Priority Queueing](#priority-queueing) section. and returns a `Promise` that either `resolve`s with the value from the user supplied `fn` or `reject`s 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` ```js // 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()`: ```js 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](https://github.com/sandfox/generic-pool-decorator) ## Pool info The following properties will let you get information about the pool: ```js // 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. node-pool-3.9.0/index.d.ts000066400000000000000000000027021430703216500153220ustar00rootroot00000000000000// Type definitions for node-pool 3.1 // Derived from https://github.com/DefinitelyTyped/DefinitelyTyped // -> https://github.com/DefinitelyTyped/DefinitelyTyped/blob/454dcbcbe5e932010b128dca9793758dd28adb45/types/generic-pool/index.d.ts /// import { EventEmitter } from "events"; export class Pool extends EventEmitter { spareResourceCapacity: number; size: number; available: number; borrowed: number; pending: number; max: number; min: number; start(): void; acquire(priority?: number): Promise; release(resource: T): Promise; destroy(resource: T): Promise; drain(): Promise; clear(): Promise; use(cb: (resource: T) => U | Promise): Promise; isBorrowedResource(resource: T): boolean; ready(): Promise; } export interface Factory { create(): Promise; destroy(client: T): Promise; validate?(client: T): Promise; } export interface Options { max?: number; min?: number; maxWaitingClients?: number; testOnBorrow?: boolean; testOnReturn?: boolean; acquireTimeoutMillis?: number; fifo?: boolean; priorityRange?: number; autostart?: boolean; evictionRunIntervalMillis?: number; numTestsPerEvictionRun?: number; softIdleTimeoutMillis?: number; idleTimeoutMillis?: number; } export function createPool(factory: Factory, opts?: Options): Pool; node-pool-3.9.0/index.js000066400000000000000000000006501430703216500150660ustar00rootroot00000000000000const Pool = require("./lib/Pool"); const Deque = require("./lib/Deque"); const PriorityQueue = require("./lib/PriorityQueue"); const DefaultEvictor = require("./lib/DefaultEvictor"); module.exports = { Pool: Pool, Deque: Deque, PriorityQueue: PriorityQueue, DefaultEvictor: DefaultEvictor, createPool: function(factory, config) { return new Pool(DefaultEvictor, Deque, PriorityQueue, factory, config); } }; node-pool-3.9.0/lib/000077500000000000000000000000001430703216500141665ustar00rootroot00000000000000node-pool-3.9.0/lib/DefaultEvictor.js000066400000000000000000000007211430703216500174440ustar00rootroot00000000000000"use strict"; class DefaultEvictor { evict(config, pooledResource, availableObjectsCount) { const idleTime = Date.now() - pooledResource.lastIdleTime; if ( config.softIdleTimeoutMillis > 0 && config.softIdleTimeoutMillis < idleTime && config.min < availableObjectsCount ) { return true; } if (config.idleTimeoutMillis < idleTime) { return true; } return false; } } module.exports = DefaultEvictor; node-pool-3.9.0/lib/Deferred.js000066400000000000000000000016701430703216500162500ustar00rootroot00000000000000"use strict"; /** * This is apparently a bit like a Jquery deferred, hence the name */ class Deferred { constructor(Promise) { this._state = Deferred.PENDING; this._resolve = undefined; this._reject = undefined; this._promise = new Promise((resolve, reject) => { this._resolve = resolve; this._reject = reject; }); } get state() { return this._state; } get promise() { return this._promise; } reject(reason) { if (this._state !== Deferred.PENDING) { return; } this._state = Deferred.REJECTED; this._reject(reason); } resolve(value) { if (this._state !== Deferred.PENDING) { return; } this._state = Deferred.FULFILLED; this._resolve(value); } } // TODO: should these really live here? or be a seperate 'state' enum Deferred.PENDING = "PENDING"; Deferred.FULFILLED = "FULFILLED"; Deferred.REJECTED = "REJECTED"; module.exports = Deferred; node-pool-3.9.0/lib/Deque.js000066400000000000000000000040161430703216500155700ustar00rootroot00000000000000"use strict"; const DoublyLinkedList = require("./DoublyLinkedList"); const DequeIterator = require("./DequeIterator"); /** * DoublyLinkedList backed double ended queue * implements just enough to keep the Pool */ class Deque { constructor() { this._list = new DoublyLinkedList(); } /** * removes and returns the first element from the queue * @return {any} [description] */ shift() { if (this.length === 0) { return undefined; } const node = this._list.head; this._list.remove(node); return node.data; } /** * adds one elemts to the beginning of the queue * @param {any} element [description] * @return {any} [description] */ unshift(element) { const node = DoublyLinkedList.createNode(element); this._list.insertBeginning(node); } /** * adds one to the end of the queue * @param {any} element [description] * @return {any} [description] */ push(element) { const node = DoublyLinkedList.createNode(element); this._list.insertEnd(node); } /** * removes and returns the last element from the queue */ pop() { if (this.length === 0) { return undefined; } const node = this._list.tail; this._list.remove(node); return node.data; } [Symbol.iterator]() { return new DequeIterator(this._list); } iterator() { return new DequeIterator(this._list); } reverseIterator() { return new DequeIterator(this._list, true); } /** * get a reference to the item at the head of the queue * @return {any} [description] */ get head() { if (this.length === 0) { return undefined; } const node = this._list.head; return node.data; } /** * get a reference to the item at the tail of the queue * @return {any} [description] */ get tail() { if (this.length === 0) { return undefined; } const node = this._list.tail; return node.data; } get length() { return this._list.length; } } module.exports = Deque; node-pool-3.9.0/lib/DequeIterator.js000066400000000000000000000006201430703216500172770ustar00rootroot00000000000000"use strict"; const DoublyLinkedListIterator = require("./DoublyLinkedListIterator"); /** * Thin wrapper around an underlying DDL iterator */ class DequeIterator extends DoublyLinkedListIterator { next() { const result = super.next(); // unwrap the node... if (result.value) { result.value = result.value.data; } return result; } } module.exports = DequeIterator; node-pool-3.9.0/lib/DoublyLinkedList.js000066400000000000000000000036061430703216500177520ustar00rootroot00000000000000"use strict"; /** * A Doubly Linked List, because there aren't enough in the world... * this is pretty much a direct JS port of the one wikipedia * https://en.wikipedia.org/wiki/Doubly_linked_list * * For most usage 'insertBeginning' and 'insertEnd' should be enough * * nodes are expected to something like a POJSO like * { * prev: null, * next: null, * something: 'whatever you like' * } */ class DoublyLinkedList { constructor() { this.head = null; this.tail = null; this.length = 0; } insertBeginning(node) { if (this.head === null) { this.head = node; this.tail = node; node.prev = null; node.next = null; this.length++; } else { this.insertBefore(this.head, node); } } insertEnd(node) { if (this.tail === null) { this.insertBeginning(node); } else { this.insertAfter(this.tail, node); } } insertAfter(node, newNode) { newNode.prev = node; newNode.next = node.next; if (node.next === null) { this.tail = newNode; } else { node.next.prev = newNode; } node.next = newNode; this.length++; } insertBefore(node, newNode) { newNode.prev = node.prev; newNode.next = node; if (node.prev === null) { this.head = newNode; } else { node.prev.next = newNode; } node.prev = newNode; this.length++; } remove(node) { if (node.prev === null) { this.head = node.next; } else { node.prev.next = node.next; } if (node.next === null) { this.tail = node.prev; } else { node.next.prev = node.prev; } node.prev = null; node.next = null; this.length--; } // FIXME: this should not live here and has become a dumping ground... static createNode(data) { return { prev: null, next: null, data: data }; } } module.exports = DoublyLinkedList; node-pool-3.9.0/lib/DoublyLinkedListIterator.js000066400000000000000000000057561430703216500214740ustar00rootroot00000000000000"use strict"; /** * Creates an interator for a DoublyLinkedList starting at the given node * It's internal cursor will remains relative to the last "iterated" node as that * node moves through the list until it either iterates to the end of the list, * or the the node it's tracking is removed from the list. Until the first 'next' * call it tracks the head/tail of the linked list. This means that one can create * an iterator on an empty list, then add nodes, and then the iterator will follow * those nodes. Because the DoublyLinkedList nodes don't track their owning "list" and * it's highly inefficient to walk the list for every iteration, the iterator won't know * if the node has been detached from one List and added to another list, or if the iterator * * The created object is an es6 compatible iterator */ class DoublyLinkedListIterator { /** * @param {Object} doublyLinkedList a node that is part of a doublyLinkedList * @param {Boolean} [reverse=false] is this a reverse iterator? default: false */ constructor(doublyLinkedList, reverse) { this._list = doublyLinkedList; // NOTE: these key names are tied to the DoublyLinkedListIterator this._direction = reverse === true ? "prev" : "next"; this._startPosition = reverse === true ? "tail" : "head"; this._started = false; this._cursor = null; this._done = false; } _start() { this._cursor = this._list[this._startPosition]; this._started = true; } _advanceCursor() { if (this._started === false) { this._started = true; this._cursor = this._list[this._startPosition]; return; } this._cursor = this._cursor[this._direction]; } reset() { this._done = false; this._started = false; this._cursor = null; } remove() { if ( this._started === false || this._done === true || this._isCursorDetached() ) { return false; } this._list.remove(this._cursor); } next() { if (this._done === true) { return { done: true }; } this._advanceCursor(); // if there is no node at the cursor or the node at the cursor is no longer part of // a doubly linked list then we are done/finished/kaput if (this._cursor === null || this._isCursorDetached()) { this._done = true; return { done: true }; } return { value: this._cursor, done: false }; } /** * Is the node detached from a list? * NOTE: you can trick/bypass/confuse this check by removing a node from one DoublyLinkedList * and adding it to another. * TODO: We can make this smarter by checking the direction of travel and only checking * the required next/prev/head/tail rather than all of them * @return {Boolean} [description] */ _isCursorDetached() { return ( this._cursor.prev === null && this._cursor.next === null && this._list.tail !== this._cursor && this._list.head !== this._cursor ); } } module.exports = DoublyLinkedListIterator; node-pool-3.9.0/lib/Pool.js000066400000000000000000000525111430703216500154410ustar00rootroot00000000000000"use strict"; const EventEmitter = require("events").EventEmitter; const factoryValidator = require("./factoryValidator"); const PoolOptions = require("./PoolOptions"); const ResourceRequest = require("./ResourceRequest"); const ResourceLoan = require("./ResourceLoan"); const PooledResource = require("./PooledResource"); const DefaultEvictor = require("./DefaultEvictor"); const Deque = require("./Deque"); const Deferred = require("./Deferred"); const PriorityQueue = require("./PriorityQueue"); const DequeIterator = require("./DequeIterator"); const reflector = require("./utils").reflector; /** * TODO: move me */ const FACTORY_CREATE_ERROR = "factoryCreateError"; const FACTORY_DESTROY_ERROR = "factoryDestroyError"; class Pool extends EventEmitter { /** * Generate an Object pool with a specified `factory` and `config`. * * @param {typeof DefaultEvictor} Evictor * @param {typeof Deque} Deque * @param {typeof PriorityQueue} PriorityQueue * @param {Object} factory * Factory to be used for generating and destroying the items. * @param {Function} factory.create * Should create the item to be acquired, * and call it's first callback argument with the generated item as it's argument. * @param {Function} factory.destroy * Should gently close any resources that the item is using. * Called before the items is destroyed. * @param {Function} factory.validate * Test if a resource is still valid .Should return a promise that resolves to a boolean, true if resource is still valid and false * If it should be removed from pool. * @param {Object} options */ constructor(Evictor, Deque, PriorityQueue, factory, options) { super(); factoryValidator(factory); this._config = new PoolOptions(options); // TODO: fix up this ugly glue-ing this._Promise = this._config.Promise; this._factory = factory; this._draining = false; this._started = false; /** * Holds waiting clients * @type {PriorityQueue} */ this._waitingClientsQueue = new PriorityQueue(this._config.priorityRange); /** * Collection of promises for resource creation calls made by the pool to factory.create * @type {Set} */ this._factoryCreateOperations = new Set(); /** * Collection of promises for resource destruction calls made by the pool to factory.destroy * @type {Set} */ this._factoryDestroyOperations = new Set(); /** * A queue/stack of pooledResources awaiting acquisition * TODO: replace with LinkedList backed array * @type {Deque} */ this._availableObjects = new Deque(); /** * Collection of references for any resource that are undergoing validation before being acquired * @type {Set} */ this._testOnBorrowResources = new Set(); /** * Collection of references for any resource that are undergoing validation before being returned * @type {Set} */ this._testOnReturnResources = new Set(); /** * Collection of promises for any validations currently in process * @type {Set} */ this._validationOperations = new Set(); /** * All objects associated with this pool in any state (except destroyed) * @type {Set} */ this._allObjects = new Set(); /** * Loans keyed by the borrowed resource * @type {Map} */ this._resourceLoans = new Map(); /** * Infinitely looping iterator over available object * @type {DequeIterator} */ this._evictionIterator = this._availableObjects.iterator(); this._evictor = new Evictor(); /** * handle for setTimeout for next eviction run * @type {(number|null)} */ this._scheduledEviction = null; // create initial resources (if factory.min > 0) if (this._config.autostart === true) { this.start(); } } _destroy(pooledResource) { // FIXME: do we need another state for "in destruction"? pooledResource.invalidate(); this._allObjects.delete(pooledResource); // NOTE: this maybe very bad promise usage? const destroyPromise = this._factory.destroy(pooledResource.obj); const wrappedDestroyPromise = this._config.destroyTimeoutMillis ? this._Promise.resolve(this._applyDestroyTimeout(destroyPromise)) : this._Promise.resolve(destroyPromise); this._trackOperation( wrappedDestroyPromise, this._factoryDestroyOperations ).catch(reason => { this.emit(FACTORY_DESTROY_ERROR, reason); }); // TODO: maybe ensuring minimum pool size should live outside here this._ensureMinimum(); } _applyDestroyTimeout(promise) { const timeoutPromise = new this._Promise((resolve, reject) => { setTimeout(() => { reject(new Error("destroy timed out")); }, this._config.destroyTimeoutMillis).unref(); }); return this._Promise.race([timeoutPromise, promise]); } /** * Attempt to move an available resource into test and then onto a waiting client * @return {Boolean} could we move an available resource into test */ _testOnBorrow() { if (this._availableObjects.length < 1) { return false; } const pooledResource = this._availableObjects.shift(); // Mark the resource as in test pooledResource.test(); this._testOnBorrowResources.add(pooledResource); const validationPromise = this._factory.validate(pooledResource.obj); const wrappedValidationPromise = this._Promise.resolve(validationPromise); this._trackOperation( wrappedValidationPromise, this._validationOperations ).then(isValid => { this._testOnBorrowResources.delete(pooledResource); if (isValid === false) { pooledResource.invalidate(); this._destroy(pooledResource); this._dispense(); return; } this._dispatchPooledResourceToNextWaitingClient(pooledResource); }); return true; } /** * Attempt to move an available resource to a waiting client * @return {Boolean} [description] */ _dispatchResource() { if (this._availableObjects.length < 1) { return false; } const pooledResource = this._availableObjects.shift(); this._dispatchPooledResourceToNextWaitingClient(pooledResource); return false; } /** * Attempt to resolve an outstanding resource request using an available resource from * the pool, or creating new ones * * @private */ _dispense() { /** * Local variables for ease of reading/writing * these don't (shouldn't) change across the execution of this fn */ const numWaitingClients = this._waitingClientsQueue.length; // If there aren't any waiting requests then there is nothing to do // so lets short-circuit if (numWaitingClients < 1) { return; } const resourceShortfall = numWaitingClients - this._potentiallyAllocableResourceCount; const actualNumberOfResourcesToCreate = Math.min( this.spareResourceCapacity, resourceShortfall ); for (let i = 0; actualNumberOfResourcesToCreate > i; i++) { this._createResource(); } // If we are doing test-on-borrow see how many more resources need to be moved into test // to help satisfy waitingClients if (this._config.testOnBorrow === true) { // how many available resources do we need to shift into test const desiredNumberOfResourcesToMoveIntoTest = numWaitingClients - this._testOnBorrowResources.size; const actualNumberOfResourcesToMoveIntoTest = Math.min( this._availableObjects.length, desiredNumberOfResourcesToMoveIntoTest ); for (let i = 0; actualNumberOfResourcesToMoveIntoTest > i; i++) { this._testOnBorrow(); } } // if we aren't testing-on-borrow then lets try to allocate what we can if (this._config.testOnBorrow === false) { const actualNumberOfResourcesToDispatch = Math.min( this._availableObjects.length, numWaitingClients ); for (let i = 0; actualNumberOfResourcesToDispatch > i; i++) { this._dispatchResource(); } } } /** * Dispatches a pooledResource to the next waiting client (if any) else * puts the PooledResource back on the available list * @param {PooledResource} pooledResource [description] * @return {Boolean} [description] */ _dispatchPooledResourceToNextWaitingClient(pooledResource) { const clientResourceRequest = this._waitingClientsQueue.dequeue(); if ( clientResourceRequest === undefined || clientResourceRequest.state !== Deferred.PENDING ) { // While we were away either all the waiting clients timed out // or were somehow fulfilled. put our pooledResource back. this._addPooledResourceToAvailableObjects(pooledResource); // TODO: do need to trigger anything before we leave? return false; } const loan = new ResourceLoan(pooledResource, this._Promise); this._resourceLoans.set(pooledResource.obj, loan); pooledResource.allocate(); clientResourceRequest.resolve(pooledResource.obj); return true; } /** * tracks on operation using given set * handles adding/removing from the set and resolve/rejects the value/reason * @param {Promise} operation * @param {Set} set Set holding operations * @return {Promise} Promise that resolves once operation has been removed from set */ _trackOperation(operation, set) { set.add(operation); return operation.then( v => { set.delete(operation); return this._Promise.resolve(v); }, e => { set.delete(operation); return this._Promise.reject(e); } ); } /** * @private */ _createResource() { // An attempt to create a resource const factoryPromise = this._factory.create(); const wrappedFactoryPromise = this._Promise .resolve(factoryPromise) .then(resource => { const pooledResource = new PooledResource(resource); this._allObjects.add(pooledResource); this._addPooledResourceToAvailableObjects(pooledResource); }); this._trackOperation(wrappedFactoryPromise, this._factoryCreateOperations) .then(() => { this._dispense(); // Stop bluebird complaining about this side-effect only handler // - a promise was created in a handler but was not returned from it // https://goo.gl/rRqMUw return null; }) .catch(reason => { this.emit(FACTORY_CREATE_ERROR, reason); this._dispense(); }); } /** * @private */ _ensureMinimum() { if (this._draining === true) { return; } const minShortfall = this._config.min - this._count; for (let i = 0; i < minShortfall; i++) { this._createResource(); } } _evict() { const testsToRun = Math.min( this._config.numTestsPerEvictionRun, this._availableObjects.length ); const evictionConfig = { softIdleTimeoutMillis: this._config.softIdleTimeoutMillis, idleTimeoutMillis: this._config.idleTimeoutMillis, min: this._config.min }; for (let testsHaveRun = 0; testsHaveRun < testsToRun; ) { const iterationResult = this._evictionIterator.next(); // Safety check incase we could get stuck in infinite loop because we // somehow emptied the array after checking its length. if (iterationResult.done === true && this._availableObjects.length < 1) { this._evictionIterator.reset(); return; } // If this happens it should just mean we reached the end of the // list and can reset the cursor. if (iterationResult.done === true && this._availableObjects.length > 0) { this._evictionIterator.reset(); continue; } const resource = iterationResult.value; const shouldEvict = this._evictor.evict( evictionConfig, resource, this._availableObjects.length ); testsHaveRun++; if (shouldEvict === true) { // take it out of the _availableObjects list this._evictionIterator.remove(); this._destroy(resource); } } } _scheduleEvictorRun() { // Start eviction if set if (this._config.evictionRunIntervalMillis > 0) { // @ts-ignore this._scheduledEviction = setTimeout(() => { this._evict(); this._scheduleEvictorRun(); }, this._config.evictionRunIntervalMillis).unref(); } } _descheduleEvictorRun() { if (this._scheduledEviction) { clearTimeout(this._scheduledEviction); } this._scheduledEviction = null; } start() { if (this._draining === true) { return; } if (this._started === true) { return; } this._started = true; this._scheduleEvictorRun(); this._ensureMinimum(); } /** * Request a new resource. The callback will be called, * when a new resource is available, passing the resource to the callback. * TODO: should we add a seperate "acquireWithPriority" function * * @param {Number} [priority=0] * Optional. Integer between 0 and (priorityRange - 1). Specifies the priority * of the caller if there are no available resources. Lower numbers mean higher * priority. * * @returns {Promise} */ acquire(priority) { if (this._started === false && this._config.autostart === false) { this.start(); } if (this._draining) { return this._Promise.reject( new Error("pool is draining and cannot accept work") ); } // TODO: should we defer this check till after this event loop incase "the situation" changes in the meantime if ( this.spareResourceCapacity < 1 && this._availableObjects.length < 1 && this._config.maxWaitingClients !== undefined && this._waitingClientsQueue.length >= this._config.maxWaitingClients ) { return this._Promise.reject( new Error("max waitingClients count exceeded") ); } const resourceRequest = new ResourceRequest( this._config.acquireTimeoutMillis, this._Promise ); this._waitingClientsQueue.enqueue(resourceRequest, priority); this._dispense(); return resourceRequest.promise; } /** * [use method, aquires a resource, passes the resource to a user supplied function and releases it] * @param {Function} fn [a function that accepts a resource and returns a promise that resolves/rejects once it has finished using the resource] * @return {Promise} [resolves once the resource is released to the pool] */ use(fn, priority) { return this.acquire(priority).then(resource => { return fn(resource).then( result => { this.release(resource); return result; }, err => { this.destroy(resource); throw err; } ); }); } /** * Check if resource is currently on loan from the pool * * @param {Function} resource * Resource for checking. * * @returns {Boolean} * True if resource belongs to this pool and false otherwise */ isBorrowedResource(resource) { return this._resourceLoans.has(resource); } /** * Return the resource to the pool when it is no longer required. * * @param {Object} resource * The acquired object to be put back to the pool. */ release(resource) { // check for an outstanding loan const loan = this._resourceLoans.get(resource); if (loan === undefined) { return this._Promise.reject( new Error("Resource not currently part of this pool") ); } this._resourceLoans.delete(resource); loan.resolve(); const pooledResource = loan.pooledResource; pooledResource.deallocate(); this._addPooledResourceToAvailableObjects(pooledResource); this._dispense(); return this._Promise.resolve(); } /** * Request the resource to be destroyed. The factory's destroy handler * will also be called. * * This should be called within an acquire() block as an alternative to release(). * * @param {Object} resource * The acquired resource to be destoyed. */ destroy(resource) { // check for an outstanding loan const loan = this._resourceLoans.get(resource); if (loan === undefined) { return this._Promise.reject( new Error("Resource not currently part of this pool") ); } this._resourceLoans.delete(resource); loan.resolve(); const pooledResource = loan.pooledResource; pooledResource.deallocate(); this._destroy(pooledResource); this._dispense(); return this._Promise.resolve(); } _addPooledResourceToAvailableObjects(pooledResource) { pooledResource.idle(); if (this._config.fifo === true) { this._availableObjects.push(pooledResource); } else { this._availableObjects.unshift(pooledResource); } } /** * Disallow any new acquire calls and let the request backlog dissapate. * The Pool will no longer attempt to maintain a "min" number of resources * and will only make new resources on demand. * Resolves once all resource requests are fulfilled and all resources are returned to pool and available... * Should probably be called "drain work" * @returns {Promise} */ drain() { this._draining = true; return this.__allResourceRequestsSettled() .then(() => { return this.__allResourcesReturned(); }) .then(() => { this._descheduleEvictorRun(); }); } __allResourceRequestsSettled() { if (this._waitingClientsQueue.length > 0) { // wait for last waiting client to be settled // FIXME: what if they can "resolve" out of order....? return reflector(this._waitingClientsQueue.tail.promise); } return this._Promise.resolve(); } // FIXME: this is a horrific mess __allResourcesReturned() { const ps = Array.from(this._resourceLoans.values()) .map(loan => loan.promise) .map(reflector); return this._Promise.all(ps); } /** * Forcibly destroys all available resources regardless of timeout. Intended to be * invoked as part of a drain. Does not prevent the creation of new * resources as a result of subsequent calls to acquire. * * Note that if factory.min > 0 and the pool isn't "draining", the pool will destroy all idle resources * in the pool, but replace them with newly created resources up to the * specified factory.min value. If this is not desired, set factory.min * to zero before calling clear() * */ clear() { const reflectedCreatePromises = Array.from( this._factoryCreateOperations ).map(reflector); // wait for outstanding factory.create to complete return this._Promise.all(reflectedCreatePromises).then(() => { // Destroy existing resources // @ts-ignore for (const resource of this._availableObjects) { this._destroy(resource); } const reflectedDestroyPromises = Array.from( this._factoryDestroyOperations ).map(reflector); return reflector(this._Promise.all(reflectedDestroyPromises)); }); } /** * Waits until the pool is ready. * We define ready by checking if the current resource number is at least * the minimum number defined. * @returns {Promise} that resolves when the minimum number is ready. */ ready() { return new this._Promise(resolve => { const isReady = () => { if (this.available >= this.min) { resolve(); } else { setTimeout(isReady, 100); } }; isReady(); }); } /** * How many resources are available to allocated * (includes resources that have not been tested and may faul validation) * NOTE: internal for now as the name is awful and might not be useful to anyone * @return {Number} number of resources the pool has to allocate */ get _potentiallyAllocableResourceCount() { return ( this._availableObjects.length + this._testOnBorrowResources.size + this._testOnReturnResources.size + this._factoryCreateOperations.size ); } /** * The combined count of the currently created objects and those in the * process of being created * Does NOT include resources in the process of being destroyed * sort of legacy... * @return {Number} */ get _count() { return this._allObjects.size + this._factoryCreateOperations.size; } /** * How many more resources does the pool have room for * @return {Number} number of resources the pool could create before hitting any limits */ get spareResourceCapacity() { return ( this._config.max - (this._allObjects.size + this._factoryCreateOperations.size) ); } /** * see _count above * @return {Number} [description] */ get size() { return this._count; } /** * number of available resources * @return {Number} [description] */ get available() { return this._availableObjects.length; } /** * number of resources that are currently acquired * @return {Number} [description] */ get borrowed() { return this._resourceLoans.size; } /** * number of waiting acquire calls * @return {Number} [description] */ get pending() { return this._waitingClientsQueue.length; } /** * maximum size of the pool * @return {Number} [description] */ get max() { return this._config.max; } /** * minimum size of the pool * @return {Number} [description] */ get min() { return this._config.min; } } module.exports = Pool; node-pool-3.9.0/lib/PoolDefaults.js000066400000000000000000000012641430703216500171300ustar00rootroot00000000000000"use strict"; /** * Create the default settings used by the pool * * @class */ class PoolDefaults { constructor() { this.fifo = true; this.priorityRange = 1; this.testOnBorrow = false; this.testOnReturn = false; this.autostart = true; this.evictionRunIntervalMillis = 0; this.numTestsPerEvictionRun = 3; this.softIdleTimeoutMillis = -1; this.idleTimeoutMillis = 30000; // FIXME: no defaults! this.acquireTimeoutMillis = null; this.destroyTimeoutMillis = null; this.maxWaitingClients = null; this.min = null; this.max = null; // FIXME: this seems odd? this.Promise = Promise; } } module.exports = PoolDefaults; node-pool-3.9.0/lib/PoolOptions.js000066400000000000000000000112001430703216500170030ustar00rootroot00000000000000"use strict"; const PoolDefaults = require("./PoolDefaults"); class PoolOptions { /** * @param {Object} opts * configuration for the pool * @param {Number} [opts.max=null] * Maximum number of items that can exist at the same time. Default: 1. * Any further acquire requests will be pushed to the waiting list. * @param {Number} [opts.min=null] * Minimum number of items in pool (including in-use). Default: 0. * When the pool is created, or a resource destroyed, this minimum will * be checked. If the pool resource count is below the minimum, a new * resource will be created and added to the pool. * @param {Number} [opts.maxWaitingClients=null] * maximum number of queued requests allowed after which acquire calls will be rejected * @param {Boolean} [opts.testOnBorrow=false] * should the pool validate resources before giving them to clients. Requires that * `factory.validate` is specified. * @param {Boolean} [opts.testOnReturn=false] * should the pool validate resources before returning them to the pool. * @param {Number} [opts.acquireTimeoutMillis=null] * Delay in milliseconds after which the an `acquire` call will fail. optional. * Default: undefined. Should be positive and non-zero * @param {Number} [opts.destroyTimeoutMillis=null] * Delay in milliseconds after which the an `destroy` call will fail, causing it to emit a factoryDestroyError event. optional. * Default: undefined. Should be positive and non-zero * @param {Number} [opts.priorityRange=1] * The range from 1 to be treated as a valid priority * @param {Boolean} [opts.fifo=true] * Sets whether the pool has LIFO (last in, first out) behaviour with respect to idle objects. * if false then pool has FIFO behaviour * @param {Boolean} [opts.autostart=true] * Should the pool start creating resources etc once the constructor is called * @param {Number} [opts.evictionRunIntervalMillis=0] * How often to run eviction checks. Default: 0 (does not run). * @param {Number} [opts.numTestsPerEvictionRun=3] * Number of resources to check each eviction run. Default: 3. * @param {Number} [opts.softIdleTimeoutMillis=-1] * 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) * @param {Number} [opts.idleTimeoutMillis=30000] * 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 * @param {typeof Promise} [opts.Promise=Promise] * What promise implementation should the pool use, defaults to native promises. */ constructor(opts) { const poolDefaults = new PoolDefaults(); opts = opts || {}; this.fifo = typeof opts.fifo === "boolean" ? opts.fifo : poolDefaults.fifo; this.priorityRange = opts.priorityRange || poolDefaults.priorityRange; this.testOnBorrow = typeof opts.testOnBorrow === "boolean" ? opts.testOnBorrow : poolDefaults.testOnBorrow; this.testOnReturn = typeof opts.testOnReturn === "boolean" ? opts.testOnReturn : poolDefaults.testOnReturn; this.autostart = typeof opts.autostart === "boolean" ? opts.autostart : poolDefaults.autostart; if (opts.acquireTimeoutMillis) { // @ts-ignore this.acquireTimeoutMillis = parseInt(opts.acquireTimeoutMillis, 10); } if (opts.destroyTimeoutMillis) { // @ts-ignore this.destroyTimeoutMillis = parseInt(opts.destroyTimeoutMillis, 10); } if (opts.maxWaitingClients !== undefined) { // @ts-ignore this.maxWaitingClients = parseInt(opts.maxWaitingClients, 10); } // @ts-ignore this.max = parseInt(opts.max, 10); // @ts-ignore this.min = parseInt(opts.min, 10); this.max = Math.max(isNaN(this.max) ? 1 : this.max, 1); this.min = Math.min(isNaN(this.min) ? 0 : this.min, this.max); this.evictionRunIntervalMillis = opts.evictionRunIntervalMillis || poolDefaults.evictionRunIntervalMillis; this.numTestsPerEvictionRun = opts.numTestsPerEvictionRun || poolDefaults.numTestsPerEvictionRun; this.softIdleTimeoutMillis = opts.softIdleTimeoutMillis || poolDefaults.softIdleTimeoutMillis; this.idleTimeoutMillis = opts.idleTimeoutMillis || poolDefaults.idleTimeoutMillis; this.Promise = opts.Promise != null ? opts.Promise : poolDefaults.Promise; } } module.exports = PoolOptions; node-pool-3.9.0/lib/PooledResource.js000066400000000000000000000017671430703216500174710ustar00rootroot00000000000000"use strict"; const PooledResourceStateEnum = require("./PooledResourceStateEnum"); /** * @class * @private */ class PooledResource { constructor(resource) { this.creationTime = Date.now(); this.lastReturnTime = null; this.lastBorrowTime = null; this.lastIdleTime = null; this.obj = resource; this.state = PooledResourceStateEnum.IDLE; } // mark the resource as "allocated" allocate() { this.lastBorrowTime = Date.now(); this.state = PooledResourceStateEnum.ALLOCATED; } // mark the resource as "deallocated" deallocate() { this.lastReturnTime = Date.now(); this.state = PooledResourceStateEnum.IDLE; } invalidate() { this.state = PooledResourceStateEnum.INVALID; } test() { this.state = PooledResourceStateEnum.VALIDATION; } idle() { this.lastIdleTime = Date.now(); this.state = PooledResourceStateEnum.IDLE; } returning() { this.state = PooledResourceStateEnum.RETURNING; } } module.exports = PooledResource; node-pool-3.9.0/lib/PooledResourceStateEnum.js000066400000000000000000000005211430703216500213020ustar00rootroot00000000000000"use strict"; const PooledResourceStateEnum = { ALLOCATED: "ALLOCATED", // In use IDLE: "IDLE", // In the queue, not in use. INVALID: "INVALID", // Failed validation RETURNING: "RETURNING", // Resource is in process of returning VALIDATION: "VALIDATION" // Currently being tested }; module.exports = PooledResourceStateEnum; node-pool-3.9.0/lib/PriorityQueue.js000066400000000000000000000026401430703216500173540ustar00rootroot00000000000000"use strict"; const Queue = require("./Queue"); /** * @class * @private */ class PriorityQueue { constructor(size) { this._size = Math.max(+size | 0, 1); /** @type {Queue[]} */ this._slots = []; // initialize arrays to hold queue elements for (let i = 0; i < this._size; i++) { this._slots.push(new Queue()); } } get length() { let _length = 0; for (let i = 0, slots = this._slots.length; i < slots; i++) { _length += this._slots[i].length; } return _length; } enqueue(obj, priority) { // Convert to integer with a default value of 0. priority = (priority && +priority | 0) || 0; if (priority) { if (priority < 0 || priority >= this._size) { priority = this._size - 1; // put obj at the end of the line } } this._slots[priority].push(obj); } dequeue() { for (let i = 0, sl = this._slots.length; i < sl; i += 1) { if (this._slots[i].length) { return this._slots[i].shift(); } } return; } get head() { for (let i = 0, sl = this._slots.length; i < sl; i += 1) { if (this._slots[i].length > 0) { return this._slots[i].head; } } return; } get tail() { for (let i = this._slots.length - 1; i >= 0; i--) { if (this._slots[i].length > 0) { return this._slots[i].tail; } } return; } } module.exports = PriorityQueue; node-pool-3.9.0/lib/Queue.js000066400000000000000000000020001430703216500156000ustar00rootroot00000000000000"use strict"; const DoublyLinkedList = require("./DoublyLinkedList"); const Deque = require("./Deque"); /** * Sort of a internal queue for holding the waiting * resource requets for a given "priority". * Also handles managing timeouts rejections on items (is this the best place for this?) * This is the last point where we know which queue a resourceRequest is in * */ class Queue extends Deque { /** * Adds the obj to the end of the list for this slot * we completely override the parent method because we need access to the * node for our rejection handler * @param {any} resourceRequest [description] */ push(resourceRequest) { const node = DoublyLinkedList.createNode(resourceRequest); resourceRequest.promise.catch(this._createTimeoutRejectionHandler(node)); this._list.insertEnd(node); } _createTimeoutRejectionHandler(node) { return reason => { if (reason.name === "TimeoutError") { this._list.remove(node); } }; } } module.exports = Queue; node-pool-3.9.0/lib/ResourceLoan.js000066400000000000000000000011061430703216500171230ustar00rootroot00000000000000"use strict"; const Deferred = require("./Deferred"); /** * Plan is to maybe add tracking via Error objects * and other fun stuff! */ class ResourceLoan extends Deferred { /** * * @param {any} pooledResource the PooledResource this loan belongs to * @return {any} [description] */ constructor(pooledResource, Promise) { super(Promise); this._creationTimestamp = Date.now(); this.pooledResource = pooledResource; } reject() { /** * Loans can only be resolved at the moment */ } } module.exports = ResourceLoan; node-pool-3.9.0/lib/ResourceRequest.js000066400000000000000000000026651430703216500176750ustar00rootroot00000000000000"use strict"; const Deferred = require("./Deferred"); const errors = require("./errors"); function fbind(fn, ctx) { return function bound() { return fn.apply(ctx, arguments); }; } /** * Wraps a users request for a resource * Basically a promise mashed in with a timeout * @private */ class ResourceRequest extends Deferred { /** * [constructor description] * @param {Number} ttl timeout */ constructor(ttl, Promise) { super(Promise); this._creationTimestamp = Date.now(); this._timeout = null; if (ttl !== undefined) { this.setTimeout(ttl); } } setTimeout(delay) { if (this._state !== ResourceRequest.PENDING) { return; } const ttl = parseInt(delay, 10); if (isNaN(ttl) || ttl <= 0) { throw new Error("delay must be a positive int"); } const age = Date.now() - this._creationTimestamp; if (this._timeout) { this.removeTimeout(); } this._timeout = setTimeout( fbind(this._fireTimeout, this), Math.max(ttl - age, 0) ); } removeTimeout() { if (this._timeout) { clearTimeout(this._timeout); } this._timeout = null; } _fireTimeout() { this.reject(new errors.TimeoutError("ResourceRequest timed out")); } reject(reason) { this.removeTimeout(); super.reject(reason); } resolve(value) { this.removeTimeout(); super.resolve(value); } } module.exports = ResourceRequest; node-pool-3.9.0/lib/errors.js000066400000000000000000000011151430703216500160360ustar00rootroot00000000000000"use strict"; class ExtendableError extends Error { constructor(message) { super(message); // @ts-ignore this.name = this.constructor.name; this.message = message; if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, this.constructor); } else { this.stack = new Error(message).stack; } } } /* eslint-disable no-useless-constructor */ class TimeoutError extends ExtendableError { constructor(m) { super(m); } } /* eslint-enable no-useless-constructor */ module.exports = { TimeoutError: TimeoutError }; node-pool-3.9.0/lib/factoryValidator.js000066400000000000000000000006671430703216500200520ustar00rootroot00000000000000module.exports = function(factory) { if (typeof factory.create !== "function") { throw new TypeError("factory.create must be a function"); } if (typeof factory.destroy !== "function") { throw new TypeError("factory.destroy must be a function"); } if ( typeof factory.validate !== "undefined" && typeof factory.validate !== "function" ) { throw new TypeError("factory.validate must be a function"); } }; node-pool-3.9.0/lib/utils.js000066400000000000000000000004611430703216500156650ustar00rootroot00000000000000"use strict"; function noop() {} /** * Reflects a promise but does not expose any * underlying value or rejection from that promise. * @param {Promise} promise [description] * @return {Promise} [description] */ exports.reflector = function(promise) { return promise.then(noop, noop); }; node-pool-3.9.0/package.json000066400000000000000000000140571430703216500157150ustar00rootroot00000000000000{ "name": "generic-pool", "description": "Generic resource pooling for Node.JS", "homepage": "https://github.com/coopernurse/node-pool#readme", "version": "3.9.0", "main": "index.js", "author": { "email": "james@bitmechanic.com", "name": "James Cooper" }, "contributors": [ { "name": "James Butler", "email": "james.butler@sandfox.co.uk" }, { "name": "Kiko Beats", "email": "josefrancisco.verdu@gmail.com" }, { "name": "Felipe Machado", "email": "felipou@gmail.com" }, { "name": "Idan Attias", "email": "idana@wix.com" }, { "name": "Bryan Donovan", "email": "bdondo@gmail.com" }, { "name": "C-h-e-r-r-y", "email": "C-h-e-r-r-y@users.noreply.github.com" }, { "name": "rebareba", "email": "forcdc1990@gmail.com" }, { "name": "t3hmrman", "email": "t3hmrman@gmail.com" }, { "name": "Thomas Dimson", "email": "tdimson@gmail.com" }, { "name": "Anup Baldawa", "email": "anup@joinhoney.com" }, { "name": "Kevin Burke", "email": "burke@shyp.com" }, { "name": "Teow Hua Jun", "email": "huajun@Teows-MacBook-Pro.local" }, { "name": "Joe Z", "email": "jzarate@gmail.com" }, { "name": "Peter Galiba", "email": "poetro@poetro.hu" }, { "name": "Asbjørn Sannes", "email": "asbjorn.sannes@interhost.no" }, { "name": "san00", "email": "c5d59d07@opayq.com" }, { "name": "Christian d'Heureuse", "email": "chdh@inventec.ch" }, { "name": "Ryan Dao", "email": "ddao@paypal.com" }, { "name": "Diego Rodríguez Baquero", "email": "diegorbaquero@gmail.com" }, { "name": "Felix Becker", "email": "felix.b@outlook.com" }, { "name": "Geovani de Souza", "email": "geovanisouza92@gmail.com" }, { "name": "Jemila", "email": "jemila.abulhawa@gmail.com" }, { "name": "Justin Robinson", "email": "jrobinson@redventures.com" }, { "name": "linchuang", "email": "linchuang@tencent.com" }, { "name": "Nayana Hettiarachchi", "email": "nayana@corp-gems.com" }, { "name": "restjohn", "email": "restjohn@users.noreply.github.com" }, { "name": "Sushant", "email": "sushantdhiman@outlook.com" }, { "name": "travis4all", "email": "travis4all@diamon.dz" }, { "name": "Will Shaver", "email": "will.shaver@emberex.com" }, { "name": "windyrobin", "email": "windyrobin@Gmail.com" }, { "name": "王秋石", "email": "12qiushi@163.com" }, { "name": "Stephen Cresswell", "email": "229672+cressie176@users.noreply.github.com" }, { "name": "Arek Flinik", "email": "aflinik@gmail.com" }, { "name": "Alexander Tesfamichael", "email": "Alex.Tesfamichael@gmail.com" }, { "name": "calibr", "email": "awcalibr@gmail.com" }, { "name": "benny-medflyt", "email": "benny@medflyt.com" }, { "name": "Bryan Kaplan", "email": "bryan@pinchit.com" }, { "name": "Dumitru Uzun", "email": "contact@duzun.me" }, { "name": "Douglas Christopher Wilson", "email": "doug@somethingdoug.com" }, { "name": "Drew R", "email": "drewrathbone@gmail.com" }, { "name": "Magnus Eide", "email": "eide@iterate.no" }, { "name": "gdusbabek", "email": "gdusbabek@gmail.com" }, { "name": "Jason Rhodes", "email": "jason.matthew.rhodes@gmail.com" }, { "name": "John Dooley", "email": "john.j.dooley@gmail.com" }, { "name": "Lewis Ellis", "email": "lewis@getsentry.com" }, { "name": "Tom MacWright", "email": "macwright@gmail.com" }, { "name": "Louis Roché", "email": "mail+github@louisroche.net" }, { "name": "Mike Morris", "email": "mikemorris@users.noreply.github.com" }, { "name": "molipet", "email": "molipet@gmail.com" }, { "name": "An Nguyen Le", "email": "nguyenan169@gmail.com" }, { "name": "Piotr", "email": "pwalc@agora.pl" }, { "name": "Randall Leeds", "email": "randall.leeds@gmail.com" }, { "name": "Roy Binux", "email": "root@binux.me" }, { "name": "Sandro Santilli", "email": "strk@keybit.net" }, { "name": "Teemu Ikonen", "email": "teemu.ikonen@iki.fi" }, { "name": "Tevye Krynski", "email": "tevye@mog.com" }, { "name": "Thom Seddon", "email": "thom@nightworld.com" }, { "name": "Thomas Watson Steen", "email": "w@tson.dk" }, { "name": "Wilfred van der Deijl", "email": "wilfred@vanderdeijl.com" }, { "name": "Yanlong Wang", "email": "yanlong.wang@naiver.org" }, { "name": "Young Hahn", "email": "young@developmentseed.org" }, { "name": "Rajesh kumar", "email": "zazzel.cvs@gmail.com" } ], "repository": { "type": "git", "url": "git+ssh://git@github.com/coopernurse/node-pool.git" }, "bugs": { "url": "https://github.com/coopernurse/node-pool/issues" }, "keywords": [ "pool", "pooling", "throttle" ], "devDependencies": { "@types/node": "^8.5.1", "eslint": "^4.9.0", "eslint-config-prettier": "^2.6.0", "eslint-plugin-prettier": "^2.3.1", "eslint-plugin-promise": "^3.3.0", "prettier": "^1.7.4", "tap": "^8.0.0", "typescript": "^2.6.2" }, "engines": { "node": ">= 4" }, "files": [ "index.d.ts", "index.js", "lib" ], "scripts": { "lint": "eslint lib test index.js .eslintrc.js", "lint-fix": "eslint --fix lib test index.js .eslintrc.js", "test": "tap test/*-test.js " }, "license": "MIT" } node-pool-3.9.0/test/000077500000000000000000000000001430703216500143775ustar00rootroot00000000000000node-pool-3.9.0/test/GH-159-test.js000066400000000000000000000032311430703216500165230ustar00rootroot00000000000000const tap = require("tap"); const createPool = require("../").createPool; const utils = require("./utils"); const ResourceFactory = utils.ResourceFactory; class ResourceFactoryDelayCreateEachSecond { constructor() { this.callCreate = 0; this.created = 0; this.destroyed = 0; this.bin = []; } create() { const that = this; console.log(`** create call ${that.callCreate}`); return new Promise(resolve => { if (that.callCreate % 2 === 0) { setTimeout(function() { console.log(`** created ${that.created}`); resolve({ id: that.created++ }); }, 10); } else { console.log(`** created ${that.created}`); resolve({ id: that.created++ }); } that.callCreate++; }); } validate() { return Promise.resolve(true); } destroy(resource) { console.log(`** destroying ${resource.id}`); this.destroyed++; this.bin.push(resource); return Promise.resolve(); } } tap.test("tests drain clear with autostart and min > 0", function(t) { const count = 5; let acquired = 0; const resourceFactory = new ResourceFactoryDelayCreateEachSecond(); const config = { max: 10, min: 1, evictionRunIntervalMillis: 500, idleTimeoutMillis: 30000, testOnBorrow: true, autostart: true }; const pool = createPool(resourceFactory, config); return pool .drain() .then(function() { console.log("** pool drained"); return pool.clear(); }) .then(function() { console.log("** pool cleared"); t.equal(resourceFactory.created, resourceFactory.destroyed); }) .then(function() { t.end(); }); }); node-pool-3.9.0/test/doubly-linked-list-iterator-test.js000066400000000000000000000066671430703216500232730ustar00rootroot00000000000000const tap = require("tap"); const DLL = require("../lib/DoublyLinkedList"); const Iterator = require("../lib/DoublyLinkedListIterator"); tap.test("iterates forward", function(t) { const dll = new DLL(); const node1 = DLL.createNode({ id: 1 }); const node2 = DLL.createNode({ id: 2 }); const node3 = DLL.createNode({ id: 3 }); const node4 = DLL.createNode({ id: 4 }); dll.insertBeginning(node1); dll.insertBeginning(node2); dll.insertBeginning(node3); dll.insertBeginning(node4); const iterator = new Iterator(dll); const iterationResult1 = iterator.next(); t.notOk(iterationResult1.done); t.same(iterationResult1.value, node4); iterator.next(); iterator.next(); const iterationResult4 = iterator.next(); t.notOk(iterationResult4.done); t.same(iterationResult4.value, node1); const iterationResult5 = iterator.next(); t.ok(iterationResult5.done); t.end(); }); tap.test("iterates backwards", function(t) { const dll = new DLL(); const node1 = DLL.createNode({ id: 1 }); const node2 = DLL.createNode({ id: 2 }); const node3 = DLL.createNode({ id: 3 }); const node4 = DLL.createNode({ id: 4 }); dll.insertBeginning(node1); dll.insertBeginning(node2); dll.insertBeginning(node3); dll.insertBeginning(node4); const iterator = new Iterator(dll, true); const iterationResult1 = iterator.next(); t.notOk(iterationResult1.done); t.same(iterationResult1.value, node1); iterator.next(); iterator.next(); const iterationResult4 = iterator.next(); t.notOk(iterationResult4.done); t.same(iterationResult4.value, node4); const iterationResult5 = iterator.next(); t.ok(iterationResult5.done); t.end(); }); tap.test("iterates forward when adding nodes after creating iterator", function( t ) { const dll = new DLL(); const node1 = DLL.createNode({ id: 1 }); const node2 = DLL.createNode({ id: 2 }); const iterator = new Iterator(dll); dll.insertBeginning(node1); dll.insertBeginning(node2); const iterationResult1 = iterator.next(); t.notOk(iterationResult1.done); t.same(iterationResult1.value, node2); const iterationResult2 = iterator.next(); t.notOk(iterationResult2.done); t.same(iterationResult2.value, node1); const iterationResult3 = iterator.next(); t.ok(iterationResult3.done); t.end(); }); tap.test( "iterates backwards when adding nodes after creating iterator", function(t) { const dll = new DLL(); const node1 = DLL.createNode({ id: 1 }); const node2 = DLL.createNode({ id: 2 }); const iterator = new Iterator(dll, true); dll.insertBeginning(node1); dll.insertBeginning(node2); const iterationResult1 = iterator.next(); t.notOk(iterationResult1.done); t.same(iterationResult1.value, node1); const iterationResult2 = iterator.next(); t.notOk(iterationResult2.done); t.same(iterationResult2.value, node2); const iterationResult3 = iterator.next(); t.ok(iterationResult3.done); t.end(); } ); tap.test("stops iterating when node is detached", function(t) { const dll = new DLL(); const iterator = new Iterator(dll); const node1 = DLL.createNode({ id: 1 }); const node2 = DLL.createNode({ id: 2 }); dll.insertBeginning(node1); dll.insertBeginning(node2); const iterationResult1 = iterator.next(); t.notOk(iterationResult1.done); t.same(iterationResult1.value, node2); dll.remove(node1); const iterationResult3 = iterator.next(); t.ok(iterationResult3.done); t.end(); }); node-pool-3.9.0/test/doubly-linked-list-test.js000066400000000000000000000011731430703216500214270ustar00rootroot00000000000000var tap = require("tap"); var DLL = require("../lib/DoublyLinkedList"); tap.test("operations", function(t) { var dll = new DLL(); var item1 = { id: 1 }; var item2 = { id: 2 }; var item3 = { id: 3 }; var item4 = { id: 4 }; dll.insertBeginning(DLL.createNode(item1)); t.equal(dll.head.data, item1); dll.insertEnd(DLL.createNode(item2)); t.equal(dll.tail.data, item2); dll.insertAfter(dll.tail, DLL.createNode(item3)); t.equal(dll.tail.data, item3); dll.insertBefore(dll.tail, DLL.createNode(item4)); t.equal(dll.tail.data, item3); dll.remove(dll.tail); t.equal(dll.tail.data, item4); t.end(); }); node-pool-3.9.0/test/generic-pool-acquiretimeout-test.js000066400000000000000000000030601430703216500233320ustar00rootroot00000000000000"use strict"; const tap = require("tap"); const createPool = require("../").createPool; tap.test("acquireTimeout handles timed out acquire calls", function(t) { const factory = { create: function() { return new Promise(function(resolve) { setTimeout(function() { resolve({}); }, 100); }); }, destroy: function() { return Promise.resolve(); } }; const config = { acquireTimeoutMillis: 20, idleTimeoutMillis: 150, log: false }; const pool = createPool(factory, config); pool .acquire() .then(function(resource) { t.fail("wooops"); }) .catch(function(err) { t.match(err, /ResourceRequest timed out/); return pool.drain(); }) .then(function() { return pool.clear(); }) .then(function() {}) .then(t.end) .catch(t.error); }); tap.test("acquireTimeout handles non timed out acquire calls", function(t) { const myResource = {}; const factory = { create: function() { return new Promise(function(resolve) { setTimeout(function() { resolve(myResource); }, 10); }); }, destroy: function() { return Promise.resolve(); } }; const config = { acquireTimeoutMillis: 400 }; const pool = createPool(factory, config); pool .acquire() .then(function(resource) { t.equal(resource, myResource); pool.release(resource); return pool.drain(); }) .then(function() { return pool.clear(); }) .then(t.end) .catch(t.error); }); node-pool-3.9.0/test/generic-pool-destroytimeout-test.js000066400000000000000000000031041430703216500233710ustar00rootroot00000000000000"use strict"; const tap = require("tap"); const createPool = require("../").createPool; tap.test("destroyTimeout handles timed out destroy calls", function(t) { const factory = { create: function() { return Promise.resolve({}); }, destroy: function() { return new Promise(function(resolve) { setTimeout(function() { resolve(); }, 100); }); } }; const config = { destroyTimeoutMillis: 20 }; const pool = createPool(factory, config); pool .acquire() .then(function(resource) { pool.destroy(resource); return new Promise(function(resolve, reject) { pool.on("factoryDestroyError", function(err) { t.match(err, /destroy timed out/); resolve(); }); }); }) .then(t.end) .catch(t.error); }); tap.test("destroyTimeout handles non timed out destroy calls", function(t) { const myResource = {}; const factory = { create: function() { return Promise.resolve({}); }, destroy: function() { return new Promise(function(resolve) { setTimeout(function() { resolve(); }, 10); }); } }; const config = { destroyTimeoutMillis: 400 }; const pool = createPool(factory, config); pool .acquire() .then(function(resource) { pool.destroy(resource); return new Promise(function(resolve) { pool.on("factoryDestroyError", function(err) { t.fail("wooops"); }); setTimeout(resolve, 20); }); }) .then(t.end) .catch(t.error); }); node-pool-3.9.0/test/generic-pool-test.js000066400000000000000000000500161430703216500202770ustar00rootroot00000000000000"use strict"; const tap = require("tap"); const createPool = require("../").createPool; const utils = require("./utils"); const ResourceFactory = utils.ResourceFactory; // tap.test('Pool expands only to max limit', function (t) { // const resourceFactory = new ResourceFactory() // const config = { // max: 1 // } // const pool = createPool(resourceFactory, config) // // NOTES: // // - request a resource // // - once we have it, request another and check the pool is fool // pool.acquire(function (err, obj) { // t.error(err) // const poolIsFull = !pool.acquire(function (err, obj) { // t.error(err) // t.equal(1, resourceFactory.created) // pool.release(obj) // utils.stopPool(pool) // t.end() // }) // t.ok(poolIsFull) // t.equal(1, resourceFactory.created) // pool.release(obj) // }) // }) // tap.test('Pool respects min limit', function (t) { // const resourceFactory = new ResourceFactory() // const config // min: 1, // max: 2 // } // const pool = createPool(resourceFactory, config) // // FIXME: this logic only works because we know it takes ~1ms to create a resource // // we need better hooks into the pool probably to observe this... // setTimeout(function () { // t.equal(resourceFactory.created, 1) // utils.stopPool(pool) // t.end() // }, 10) // }) tap.test("min and max limit defaults", function(t) { const resourceFactory = new ResourceFactory(); const pool = createPool(resourceFactory); t.equal(1, pool.max); t.equal(0, pool.min); utils.stopPool(pool); t.end(); }); tap.test("malformed min and max limits are ignored", function(t) { const resourceFactory = new ResourceFactory(); const config = { min: "asf", max: [] }; const pool = createPool(resourceFactory, config); t.equal(1, pool.max); t.equal(0, pool.min); utils.stopPool(pool); t.end(); }); tap.test("min greater than max sets to max", function(t) { const resourceFactory = new ResourceFactory(); const config = { min: 5, max: 3 }; const pool = createPool(resourceFactory, config); t.equal(3, pool.max); t.equal(3, pool.min); utils.stopPool(pool); t.end(); }); tap.test("supports priority on borrow", function(t) { // NOTE: this test is pretty opaque about what it's really testing/expecting... let borrowTimeLow = 0; let borrowTimeHigh = 0; let borrowCount = 0; const resourceFactory = new ResourceFactory(); const config = { max: 1, priorityRange: 2 }; const pool = createPool(resourceFactory, config); function lowPriorityOnFulfilled(obj) { const time = Date.now(); if (time > borrowTimeLow) { borrowTimeLow = time; } borrowCount++; pool.release(obj); } function highPriorityOnFulfilled(obj) { const time = Date.now(); if (time > borrowTimeHigh) { borrowTimeHigh = time; } borrowCount++; pool.release(obj); } const operations = []; for (let i = 0; i < 10; i++) { const op = pool.acquire(1).then(lowPriorityOnFulfilled); operations.push(op); } for (let i = 0; i < 10; i++) { const op = pool.acquire(0).then(highPriorityOnFulfilled); operations.push(op); } Promise.all(operations) .then(function() { t.equal(20, borrowCount); t.equal(true, borrowTimeLow >= borrowTimeHigh); utils.stopPool(pool); t.end(); }) .catch(t.threw); }); // FIXME: bad test! // pool.destroy makes no obligations to user about when it will destroy the resource // we should test that "destroyed" objects are not acquired again instead // tap.test('removes correct object on reap', function (t) { // const resourceFactory = new ResourceFactory() // const config // max: 2 // } // const pool = createPool(resourceFactory, config) // const op1 = pool.acquire() // .then(function (client) { // return new Promise(function (resolve, reject) { // // should be removed second // setTimeout(function () { // pool.destroy(client) // resolve() // }, 5) // }) // }) // const op2 = pool.acquire() // .then(function (client) { // pool.destroy(client) // }) // Promise.all([op1, op2]).then(function () { // t.equal(1, resourceFactory.bin[0].id) // t.equal(0, resourceFactory.bin[1].id) // utils.stopPool(pool) // t.end() // }) // .catch(t.threw) // }) tap.test("evictor removes instances on idletimeout", function(t) { const resourceFactory = new ResourceFactory(); const config = { min: 2, max: 2, idleTimeoutMillis: 50, evictionRunIntervalMillis: 10 }; const pool = createPool(resourceFactory, config); setTimeout(function() { pool .acquire() .then(res => { t.ok(res.id > 1); return pool.release(res); }) .then(() => { utils.stopPool(pool); t.end(); }); }, 120); }); tap.test("tests drain", function(t) { const count = 5; let acquired = 0; const resourceFactory = new ResourceFactory(); const config = { max: 2, idletimeoutMillis: 300000 }; const pool = createPool(resourceFactory, config); const operations = []; function onAcquire(client) { acquired += 1; t.equal(typeof client.id, "number"); setTimeout(function() { pool.release(client); }, 250); } // request 5 resources that release after 250ms for (let i = 0; i < count; i++) { const op = pool.acquire().then(onAcquire); operations.push(op); } // FIXME: what does this assertion prove? t.notEqual(count, acquired); Promise.all(operations) .then(function() { return pool.drain(); }) .then(function() { t.equal(count, acquired); // short circuit the absurdly long timeouts above. pool.clear(); }) .then(function() { // subsequent calls to acquire should resolve an error. return pool.acquire().then(t.fail, function(e) { t.type(e, Error); }); }) .then(function() { t.end(); }); }); tap.test("clear promise resolves with no value", function(t) { let resources = []; const factory = { create: function create() { return new Promise(function tryCreate(resolve, reject) { let resource = resources.shift(); if (resource) { resolve(resource); } else { process.nextTick(tryCreate.bind(this, resolve, reject)); } }); }, destroy: function() { return Promise.resolve(); } }; const pool = createPool(factory, { max: 3, min: 3 }); Promise.all([pool.acquire(), pool.acquire(), pool.acquire()]).then(all => { all.forEach(resource => { process.nextTick(pool.release.bind(pool), resource); }); }); t.equal(pool.pending, 3, "all acquisitions pending"); pool .drain() .then(() => pool.clear()) .then(resolved => { t.equal(resolved, undefined, "clear promise resolves with no value"); t.end(); }); process.nextTick(() => { resources.push("a"); resources.push("b"); resources.push("c"); }); }); tap.test("handle creation errors", function(t) { let created = 0; const resourceFactory = { create: function() { created++; if (created < 5) { return Promise.reject(new Error("Error occurred.")); } else { return Promise.resolve({ id: created }); } }, destroy: function(client) {} }; const config = { max: 1 }; const pool = createPool(resourceFactory, config); // FIXME: this section no longer proves anything as factory // errors no longer bubble up through the acquire call // we need to make the Pool an Emitter // ensure that creation errors do not populate the pool. // for (const i = 0; i < 5; i++) { // pool.acquire(function (err, client) { // t.ok(err instanceof Error) // t.ok(client === null) // }) // } let called = false; pool .acquire() .then(function(client) { t.equal(typeof client.id, "number"); called = true; pool.release(client); }) .then(function() { t.ok(called); t.equal(pool.pending, 0); utils.stopPool(pool); t.end(); }) .catch(t.threw); }); tap.test("handle creation errors for delayed creates", function(t) { let attempts = 0; const resourceFactory = { create: function() { attempts++; if (attempts <= 5) { return Promise.reject(new Error("Error occurred.")); } else { return Promise.resolve({ id: attempts }); } }, destroy: function(client) { return Promise.resolve(); } }; const config = { max: 1 }; const pool = createPool(resourceFactory, config); let errorCount = 0; pool.on("factoryCreateError", function(err) { t.ok(err instanceof Error); errorCount++; }); let called = false; pool .acquire() .then(function(client) { t.equal(typeof client.id, "number"); called = true; pool.release(client); }) .then(function() { t.ok(called); t.equal(errorCount, 5); t.equal(pool.pending, 0); utils.stopPool(pool); t.end(); }) .catch(t.threw); }); tap.test("getPoolSize", function(t) { let assertionCount = 0; const resourceFactory = new ResourceFactory(); const config = { max: 2 }; const pool = createPool(resourceFactory, config); const borrowedResources = []; t.equal(pool.size, 0); assertionCount += 1; pool .acquire() .then(function(obj) { borrowedResources.push(obj); t.equal(pool.size, 1); assertionCount += 1; }) .then(function() { return pool.acquire(); }) .then(function(obj) { borrowedResources.push(obj); t.equal(pool.size, 2); assertionCount += 1; }) .then(function() { pool.release(borrowedResources.shift()); pool.release(borrowedResources.shift()); }) .then(function() { return pool.acquire(); }) .then(function(obj) { // should still be 2 t.equal(pool.size, 2); assertionCount += 1; pool.release(obj); }) .then(function() { t.equal(assertionCount, 4); utils.stopPool(pool); t.end(); }) .catch(t.threw); }); tap.test("availableObjectsCount", function(t) { let assertionCount = 0; const resourceFactory = new ResourceFactory(); const config = { max: 2 }; const pool = createPool(resourceFactory, config); const borrowedResources = []; t.equal(pool.available, 0); assertionCount += 1; pool .acquire() .then(function(obj) { borrowedResources.push(obj); t.equal(pool.available, 0); assertionCount += 1; }) .then(function() { return pool.acquire(); }) .then(function(obj) { borrowedResources.push(obj); t.equal(pool.available, 0); assertionCount += 1; }) .then(function() { pool.release(borrowedResources.shift()); t.equal(pool.available, 1); assertionCount += 1; pool.release(borrowedResources.shift()); t.equal(pool.available, 2); assertionCount += 1; }) .then(function() { return pool.acquire(); }) .then(function(obj) { t.equal(pool.available, 1); assertionCount += 1; pool.release(obj); t.equal(pool.available, 2); assertionCount += 1; }) .then(function() { t.equal(assertionCount, 7); utils.stopPool(pool); t.end(); }) .catch(t.threw); }); // FIXME: bad test! // pool.destroy makes no obligations to user about when it will destroy the resource // we should test that "destroyed" objects are not acquired again instead // tap.test('removes from available objects on destroy', function (t) { // let destroyCalled = false // const factory = { // create: function () { return Promise.resolve({}) }, // destroy: function (client) { destroyCalled = true; return Promise.resolve() } // } // const config // max: 2 // } // const pool = createPool(factory, config) // pool.acquire().then(function (obj) { // pool.destroy(obj) // }) // .then(function () { // t.equal(destroyCalled, true) // t.equal(pool.available, 0) // utils.stopPool(pool) // t.end() // }) // .catch(t.threw) // }) // FIXME: bad test! // pool.destroy makes no obligations to user about when it will destroy the resource // we should test that "destroyed" objects are not acquired again instead // tap.test('removes from available objects on validation failure', function (t) { // const destroyCalled = false // const validateCalled = false // const count = 0 // const factory = { // create: function () { return Promise.resolve({count: count++}) }, // destroy: function (client) { destroyCalled = client.count }, // validate: function (client) { // validateCalled = true // return Promise.resolve(client.count > 0) // } // } // const config // max: 2, // testOnBorrow: true // } // const pool = createPool(factory, config) // pool.acquire() // .then(function (obj) { // pool.release(obj) // t.equal(obj.count, 0) // }) // .then(function () { // return pool.acquire() // }) // .then(function (obj2) { // pool.release(obj2) // t.equal(obj2.count, 1) // }) // .then(function () { // t.equal(validateCalled, true) // t.equal(destroyCalled, 0) // t.equal(pool.available, 1) // utils.stopPool(pool) // t.end() // }) // .catch(t.threw) // }) tap.test( "do schedule again if error occured when creating new Objects async", function(t) { // NOTE: we're simulating the first few resource attempts failing let resourceCreationAttempts = 0; const factory = { create: function() { resourceCreationAttempts++; if (resourceCreationAttempts < 2) { return Promise.reject(new Error("Create Error")); } return Promise.resolve({}); }, destroy: function(client) {} }; const config = { max: 1 }; const pool = createPool(factory, config); // pool.acquire(function () {}) pool .acquire() .then(function(obj) { t.equal(pool.available, 0); pool.release(obj); utils.stopPool(pool); t.end(); }) .catch(t.threw); } ); tap.test("returns only valid object to the pool", function(t) { const pool = createPool(new ResourceFactory(), { max: 1 }); pool .acquire() .then(function(obj) { t.equal(pool.available, 0); t.equal(pool.borrowed, 1); // Invalid release pool .release({}) .catch(function(err) { t.match(err.message, /Resource not currently part of this pool/); }) .then(function() { t.equal(pool.available, 0); t.equal(pool.borrowed, 1); // Valid release pool.release(obj).catch(t.error); t.equal(pool.available, 1); t.equal(pool.borrowed, 0); utils.stopPool(pool); t.end(); }); }) .catch(t.threw); }); tap.test("validate acquires object from the pool", function(t) { const pool = createPool(new ResourceFactory(), { max: 1 }); pool .acquire() .then(function(obj) { t.equal(pool.available, 0); t.equal(pool.borrowed, 1); pool.release(obj); utils.stopPool(pool); t.end(); }) .catch(t.threw); }); tap.test("release to pool should work", function(t) { const pool = createPool(new ResourceFactory(), { max: 1 }); pool .acquire() .then(function(obj) { t.equal(pool.available, 0); t.equal(pool.borrowed, 1); t.equal(pool.pending, 1); pool.release(obj); }) .catch(t.threw); pool .acquire() .then(function(obj) { t.equal(pool.available, 0); t.equal(pool.borrowed, 1); t.equal(pool.pending, 0); pool.release(obj); utils.stopPool(pool); t.end(); }) .catch(t.threw); }); tap.test( "isBorrowedResource should return true for borrowed resource", function(t) { const pool = createPool(new ResourceFactory(), { max: 1 }); pool .acquire() .then(function(obj) { t.equal(pool.isBorrowedResource(obj), true); pool.release(obj); utils.stopPool(pool); t.end(); }) .catch(t.threw); } ); tap.test( "isBorrowedResource should return false for released resource", function(t) { const pool = createPool(new ResourceFactory(), { max: 1 }); pool .acquire() .then(function(obj) { pool.release(obj); return obj; }) .then(function(obj) { t.equal(pool.isBorrowedResource(obj), false); utils.stopPool(pool); t.end(); }) .catch(t.threw); } ); tap.test("destroy should redispense", function(t) { const pool = createPool(new ResourceFactory(), { max: 1 }); pool .acquire() .then(function(obj) { t.equal(pool.available, 0); t.equal(pool.borrowed, 1); t.equal(pool.pending, 1); pool.destroy(obj); }) .catch(t.threw); pool .acquire() .then(function(obj) { t.equal(pool.available, 0); t.equal(pool.borrowed, 1); t.equal(pool.pending, 0); pool.release(obj); utils.stopPool(pool); t.end(); }) .catch(t.threw); }); tap.test("evictor start with acquire when autostart is false", function(t) { const pool = createPool(new ResourceFactory(), { evictionRunIntervalMillis: 10000, autostart: false }); t.equal(pool._scheduledEviction, null); pool .acquire() .then(function(obj) { t.notEqual(pool._scheduledEviction, null); pool.release(obj); utils.stopPool(pool); t.end(); }) .catch(t.threw); }); tap.test("use method", function(t) { const pool = createPool(new ResourceFactory()); const result = pool.use(function(resource) { t.equal(0, resource.id); return Promise.resolve(); }); result.then(function() { t.end(); }); }); tap.test("use method should resolve after fn promise is resolved", function(t) { const pool = createPool(new ResourceFactory()); let done_with_resource = false; const result = pool.use(function(resource) { return new Promise(function(resolve, reject) { setImmediate(function() { done_with_resource = true; resolve("value"); }); }); }); result.then(val => { t.equal(done_with_resource, true); t.equal(val, "value"); t.end(); }); }); tap.test("evictor should not run when softIdleTimeoutMillis is -1", function( t ) { const resourceFactory = new ResourceFactory(); const pool = createPool(resourceFactory, { evictionRunIntervalMillis: 10 }); pool .acquire() .then(res => pool.release(res)) .then(() => { return new Promise(res => setTimeout(res, 30)); }) .then(() => t.equal(resourceFactory.destroyed, 0)) .then(() => { utils.stopPool(pool); t.end(); }); }); tap.test("should respect when maxWaitingClients is set to 0 ", function(t) { let assertionCount = 0; const resourceFactory = new ResourceFactory(); const config = { max: 2, maxWaitingClients: 0 }; const pool = createPool(resourceFactory, config); const borrowedResources = []; t.equal(pool.size, 0); assertionCount += 1; pool .acquire() .then(function(obj) { borrowedResources.push(obj); t.equal(pool.size, 1); assertionCount += 1; }) .then(function() { return pool.acquire(); }) .then(function(obj) { borrowedResources.push(obj); t.equal(pool.size, 2); assertionCount += 1; }) .then(function() { return pool.acquire(); }) .then(function(obj) { // should not go in here t.equal(1, 2); }) .catch(error => { t.equal(error.message, "max waitingClients count exceeded"); t.end(); }); }); tap.test("should provide a way to wait until the pool is ready", function(t) { const resourceFactory = new ResourceFactory(); const config = { min: 2, max: 4 }; const pool = createPool(resourceFactory, config); pool.ready().then(() => { t.ok( pool.available >= config.min, "expected available resources to be at least as the minimum" ); t.end(); }); }); node-pool-3.9.0/test/resource-request-test.js000066400000000000000000000030041430703216500212240ustar00rootroot00000000000000var tap = require("tap"); var ResourceRequest = require("../lib/ResourceRequest"); tap.test("can be created", function(t) { var create = function() { var request = new ResourceRequest(undefined, Promise); // eslint-disable-line no-unused-vars }; t.doesNotThrow(create); t.end(); }); tap.test("times out when created with a ttl", function(t) { var reject = function(err) { t.match(err, /ResourceRequest timed out/); t.end(); }; var resolve = function(r) { t.fail("should not resolve"); }; var request = new ResourceRequest(10, Promise); // eslint-disable-line no-unused-vars request.promise.then(resolve, reject); }); tap.test("calls resolve when resolved", function(t) { var resource = {}; var resolve = function(r) { t.equal(r, resource); t.end(); }; var reject = function(err) { t.error(err); }; var request = new ResourceRequest(undefined, Promise); request.promise.then(resolve, reject); request.resolve(resource); }); tap.test("removeTimeout removes the timeout", function(t) { var reject = function(err) { t.error(err); }; var request = new ResourceRequest(10, Promise); request.promise.then(undefined, reject); request.removeTimeout(); setTimeout(function() { t.end(); }, 20); }); tap.test("does nothing if resolved more than once", function(t) { var request = new ResourceRequest(undefined, Promise); t.doesNotThrow(function() { request.resolve({}); }); t.doesNotThrow(function() { request.resolve({}); }); t.end(); }); node-pool-3.9.0/test/utils.js000066400000000000000000000013551430703216500161010ustar00rootroot00000000000000"use strict"; const Pool = require("../lib/Pool"); /** * Generic class for handling creation of resources * for testing */ class ResourceFactory { constructor() { this.created = 0; this.destroyed = 0; this.bin = []; } create() { return Promise.resolve({ id: this.created++ }); } validate() { return Promise.resolve(true); } destroy(resource) { this.destroyed++; this.bin.push(resource); return Promise.resolve(); } } exports.ResourceFactory = ResourceFactory; /** * drains and terminates the pool * * @param {Pool} pool [description] * @return {Promise} [description] */ exports.stopPool = function(pool) { return pool.drain().then(function() { return pool.clear(); }); }; node-pool-3.9.0/tsconfig.json000066400000000000000000000003521430703216500161270ustar00rootroot00000000000000{ "compilerOptions": { "target": "es5", "module": "commonjs", "lib": ["es6", "dom"], "outDir": "dist/", "allowJs": true, "checkJs": true, "declaration": true, "noEmit": true, "strict": false } }