lightning-pool 3.1.3 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [![NPM Version][npm-image]][npm-url]
4
4
  [![NPM Downloads][downloads-image]][downloads-url]
5
- [![Build Status][travis-image]][travis-url]
5
+ [![CircleCI][circleci-image]][circleci-url]
6
6
  [![Test Coverage][coveralls-image]][coveralls-url]
7
7
 
8
8
  ## About
@@ -362,15 +362,15 @@ Pool.PoolState (Number):
362
362
 
363
363
  ## Node Compatibility
364
364
 
365
- - node `>= 10.0`;
365
+ - node `>= 16.0`;
366
366
 
367
367
  ### License
368
368
  [MIT](LICENSE)
369
369
 
370
370
  [npm-image]: https://img.shields.io/npm/v/lightning-pool.svg
371
371
  [npm-url]: https://npmjs.org/package/lightning-pool
372
- [travis-image]: https://img.shields.io/travis/panates/lightning-pool/master.svg
373
- [travis-url]: https://travis-ci.com/panates/lightning-pool
372
+ [circleci-image]: https://circleci.com/gh/panates/lightning-pool/tree/master.svg?style=shield
373
+ [circleci-url]: https://circleci.com/gh/panates/lightning-pool/tree/master
374
374
  [coveralls-image]: https://img.shields.io/coveralls/panates/lightning-pool/master.svg
375
375
  [coveralls-url]: https://coveralls.io/r/panates/lightning-pool
376
376
  [downloads-image]: https://img.shields.io/npm/dm/lightning-pool.svg
File without changes
@@ -4,14 +4,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.Pool = void 0;
7
+ const doublylinked_1 = __importDefault(require("doublylinked"));
7
8
  const events_1 = require("events");
8
9
  const putil_promisify_1 = __importDefault(require("putil-promisify"));
9
- const doublylinked_1 = __importDefault(require("doublylinked"));
10
- const PoolRequest_1 = require("./PoolRequest");
11
- const AbortError_1 = require("./AbortError");
12
- const PoolOptions_1 = require("./PoolOptions");
13
- const ResourceItem_1 = require("./ResourceItem");
14
- const definitions_1 = require("./definitions");
10
+ const AbortError_js_1 = require("./AbortError.js");
11
+ const definitions_js_1 = require("./definitions.js");
12
+ const PoolOptions_js_1 = require("./PoolOptions.js");
13
+ const PoolRequest_js_1 = require("./PoolRequest.js");
14
+ const ResourceItem_js_1 = require("./ResourceItem.js");
15
15
  class Pool extends events_1.EventEmitter {
16
16
  constructor(factory, config) {
17
17
  super();
@@ -21,7 +21,7 @@ class Pool extends events_1.EventEmitter {
21
21
  this._idleResources = new doublylinked_1.default();
22
22
  this._creating = 0;
23
23
  this._requestsProcessing = 0;
24
- this._state = definitions_1.PoolState.IDLE;
24
+ this._state = definitions_js_1.PoolState.IDLE;
25
25
  if (typeof factory !== 'object')
26
26
  throw new TypeError('You must provide `factory` object');
27
27
  if (typeof factory.create !== 'function')
@@ -32,7 +32,7 @@ class Pool extends events_1.EventEmitter {
32
32
  throw new TypeError('factory.validate can be a function');
33
33
  if (factory.reset && typeof factory.reset !== 'function')
34
34
  throw new TypeError('factory.reset can be a function');
35
- const opts = this._options = new PoolOptions_1.PoolOptions(this);
35
+ const opts = this._options = new PoolOptions_js_1.PoolOptions(this);
36
36
  opts.on('change', (prop, val) => {
37
37
  if (prop === 'houseKeepInterval')
38
38
  this._setHouseKeep(val);
@@ -91,11 +91,11 @@ class Pool extends events_1.EventEmitter {
91
91
  * Note: This method is not need to be called. Pool instance will automatically be started when acquire() method is called
92
92
  */
93
93
  start() {
94
- if (this._state === definitions_1.PoolState.STARTED)
94
+ if (this._state === definitions_js_1.PoolState.STARTED)
95
95
  return;
96
- if (this._state >= definitions_1.PoolState.CLOSING)
96
+ if (this._state >= definitions_js_1.PoolState.CLOSING)
97
97
  throw new Error('Closed pool can not be started again');
98
- this._state = definitions_1.PoolState.STARTED;
98
+ this._state = definitions_js_1.PoolState.STARTED;
99
99
  this._setHouseKeep(this.options.houseKeepInterval);
100
100
  this._ensureMin();
101
101
  this.emit('start');
@@ -112,16 +112,16 @@ class Pool extends events_1.EventEmitter {
112
112
  }
113
113
  if (!callback)
114
114
  return putil_promisify_1.default.fromCallback(cb => this.close(terminateWait, cb));
115
- if (this._state === definitions_1.PoolState.CLOSED || this._state === definitions_1.PoolState.IDLE)
115
+ if (this._state === definitions_js_1.PoolState.CLOSED || this._state === definitions_js_1.PoolState.IDLE)
116
116
  return callback();
117
- if (this._state === definitions_1.PoolState.CLOSING) {
117
+ if (this._state === definitions_js_1.PoolState.CLOSING) {
118
118
  this.once('close', callback);
119
119
  return;
120
120
  }
121
121
  this.emit('closing');
122
122
  if (this._houseKeepTimer)
123
123
  clearTimeout(this._houseKeepTimer);
124
- this._state = definitions_1.PoolState.CLOSING;
124
+ this._state = definitions_js_1.PoolState.CLOSING;
125
125
  this._requestQueue.forEach(t => t.stopTimout());
126
126
  this._requestQueue = new doublylinked_1.default();
127
127
  this._requestsProcessing = 0;
@@ -162,7 +162,7 @@ class Pool extends events_1.EventEmitter {
162
162
  }
163
163
  if (this.options.maxQueue && this.pending >= this.options.maxQueue)
164
164
  return callback(new Error('Pool queue is full'));
165
- this._requestQueue.push(new PoolRequest_1.PoolRequest(this, callback));
165
+ this._requestQueue.push(new PoolRequest_js_1.PoolRequest(this, callback));
166
166
  this._processNextRequest();
167
167
  }
168
168
  /**
@@ -170,7 +170,7 @@ class Pool extends events_1.EventEmitter {
170
170
  */
171
171
  release(resource, callback) {
172
172
  const item = this._allResources.get(resource);
173
- if (item && item.state !== definitions_1.ResourceState.IDLE)
173
+ if (item && item.state !== definitions_js_1.ResourceState.IDLE)
174
174
  this._itemSetIdle(item, callback);
175
175
  this._processNextRequest();
176
176
  }
@@ -215,7 +215,7 @@ class Pool extends events_1.EventEmitter {
215
215
  return this._allResources.has(resource);
216
216
  }
217
217
  _processNextRequest() {
218
- if (this._state !== definitions_1.PoolState.STARTED ||
218
+ if (this._state !== definitions_js_1.PoolState.STARTED ||
219
219
  this._requestsProcessing >= this.options.max - this.acquired)
220
220
  return;
221
221
  const request = this._requestQueue.shift();
@@ -228,7 +228,7 @@ class Pool extends events_1.EventEmitter {
228
228
  try {
229
229
  if (item) {
230
230
  /* istanbul ignore next : Hard to simulate */
231
- if (this._state !== definitions_1.PoolState.STARTED) {
231
+ if (this._state !== definitions_js_1.PoolState.STARTED) {
232
232
  this._itemDestroy(item);
233
233
  return;
234
234
  }
@@ -294,7 +294,7 @@ class Pool extends events_1.EventEmitter {
294
294
  tries,
295
295
  maxRetries: this.options.acquireMaxRetries
296
296
  });
297
- if (err instanceof AbortError_1.AbortError || tries >= maxRetries) {
297
+ if (err instanceof AbortError_js_1.AbortError || tries >= maxRetries) {
298
298
  this._creating--;
299
299
  return callback && callback(err);
300
300
  }
@@ -304,7 +304,7 @@ class Pool extends events_1.EventEmitter {
304
304
  if (this._allResources.has(obj))
305
305
  return callback &&
306
306
  callback(new Error('Factory error. Resource already in pool'));
307
- const item = new ResourceItem_1.ResourceItem(obj);
307
+ const item = new ResourceItem_js_1.ResourceItem(obj);
308
308
  this._itemSetIdle(item);
309
309
  this._allResources.set(obj, item);
310
310
  if (callback)
@@ -316,7 +316,7 @@ class Pool extends events_1.EventEmitter {
316
316
  const o = this._factory.create({ tries, maxRetries });
317
317
  /* istanbul ignore next */
318
318
  if (!o)
319
- return handleCallback(new AbortError_1.AbortError('Factory returned no resource'));
319
+ return handleCallback(new AbortError_js_1.AbortError('Factory returned no resource'));
320
320
  putil_promisify_1.default.await(o, handleCallback);
321
321
  }
322
322
  catch (e) {
@@ -329,11 +329,11 @@ class Pool extends events_1.EventEmitter {
329
329
  if (this._houseKeepTimer)
330
330
  clearInterval(this._houseKeepTimer);
331
331
  this._houseKeepTimer = undefined;
332
- if (ms > 0 && this.state === definitions_1.PoolState.STARTED || this.state === definitions_1.PoolState.CLOSING)
332
+ if (ms > 0 && this.state === definitions_js_1.PoolState.STARTED || this.state === definitions_js_1.PoolState.CLOSING)
333
333
  this._houseKeepTimer = setInterval(() => this._houseKeep(), ms);
334
334
  }
335
335
  _houseKeep() {
336
- const isClosing = this._state === definitions_1.PoolState.CLOSING;
336
+ const isClosing = this._state === definitions_js_1.PoolState.CLOSING;
337
337
  const now = Date.now();
338
338
  let m = this._allResources.size - this.options.min;
339
339
  let n = this._idleResources.length - this.options.minIdle;
@@ -352,7 +352,7 @@ class Pool extends events_1.EventEmitter {
352
352
  if (this._allResources.size)
353
353
  return;
354
354
  clearInterval(this._houseKeepTimer);
355
- this._state = definitions_1.PoolState.CLOSED;
355
+ this._state = definitions_js_1.PoolState.CLOSED;
356
356
  this._requestsProcessing = 0;
357
357
  this.emit('close');
358
358
  }
@@ -365,24 +365,24 @@ class Pool extends events_1.EventEmitter {
365
365
  });
366
366
  }
367
367
  _itemSetAcquired(item) {
368
- if (item.state !== definitions_1.ResourceState.ACQUIRED) {
368
+ if (item.state !== definitions_js_1.ResourceState.ACQUIRED) {
369
369
  this._itemDetach(item);
370
- item.state = definitions_1.ResourceState.ACQUIRED;
370
+ item.state = definitions_js_1.ResourceState.ACQUIRED;
371
371
  this._acquiredResources.push(item);
372
372
  item.acquiredNode = this._acquiredResources.tail;
373
373
  }
374
374
  }
375
375
  _itemDetach(item) {
376
376
  switch (item.state) {
377
- case definitions_1.ResourceState.IDLE:
377
+ case definitions_js_1.ResourceState.IDLE:
378
378
  item.idleTime = 0;
379
379
  /* istanbul ignore next*/
380
380
  if (item.idleNode)
381
381
  item.idleNode.remove();
382
382
  item.idleNode = undefined;
383
383
  break;
384
- case definitions_1.ResourceState.ACQUIRED:
385
- case definitions_1.ResourceState.VALIDATION:
384
+ case definitions_js_1.ResourceState.ACQUIRED:
385
+ case definitions_js_1.ResourceState.VALIDATION:
386
386
  /* istanbul ignore next*/
387
387
  if (item.acquiredNode)
388
388
  item.acquiredNode.remove();
@@ -391,13 +391,13 @@ class Pool extends events_1.EventEmitter {
391
391
  }
392
392
  }
393
393
  _itemSetIdle(item, callback) {
394
- const isAcquired = item.state === definitions_1.ResourceState.ACQUIRED;
394
+ const isAcquired = item.state === definitions_js_1.ResourceState.ACQUIRED;
395
395
  const handleCallback = (err) => {
396
396
  if (err)
397
397
  return this._itemDestroy(item, callback);
398
398
  this._itemDetach(item);
399
399
  item.idleTime = Date.now();
400
- item.state = definitions_1.ResourceState.IDLE;
400
+ item.state = definitions_js_1.ResourceState.IDLE;
401
401
  if (this.options.fifo) {
402
402
  this._idleResources.push(item);
403
403
  item.idleNode = this._idleResources.tail;
@@ -449,9 +449,9 @@ class Pool extends events_1.EventEmitter {
449
449
  }
450
450
  }
451
451
  _itemValidate(item, callback) {
452
- item.state = definitions_1.ResourceState.VALIDATION;
452
+ item.state = definitions_js_1.ResourceState.VALIDATION;
453
453
  try {
454
- const o = this._factory.validate(item.resource);
454
+ const o = this._factory.validate?.(item.resource);
455
455
  // @ts-ignore
456
456
  putil_promisify_1.default.await(o, callback);
457
457
  }
File without changes
File without changes
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ResourceItem = void 0;
4
- const definitions_1 = require("./definitions");
4
+ const definitions_js_1 = require("./definitions.js");
5
5
  class ResourceItem {
6
6
  constructor(resource) {
7
- this.state = definitions_1.ResourceState.IDLE;
7
+ this.state = definitions_js_1.ResourceState.IDLE;
8
8
  this.idleTime = 0;
9
9
  this.destroyed = false;
10
10
  this.resource = resource;
File without changes
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -11,11 +15,11 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
11
15
  };
12
16
  Object.defineProperty(exports, "__esModule", { value: true });
13
17
  exports.createPool = void 0;
14
- const Pool_1 = require("./Pool");
15
- __exportStar(require("./definitions"), exports);
16
- __exportStar(require("./Pool"), exports);
17
- __exportStar(require("./AbortError"), exports);
18
+ const Pool_js_1 = require("./Pool.js");
19
+ __exportStar(require("./definitions.js"), exports);
20
+ __exportStar(require("./Pool.js"), exports);
21
+ __exportStar(require("./AbortError.js"), exports);
18
22
  function createPool(factory, config) {
19
- return new Pool_1.Pool(factory, config);
23
+ return new Pool_js_1.Pool(factory, config);
20
24
  }
21
25
  exports.createPool = createPool;
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
File without changes
@@ -0,0 +1,2 @@
1
+ export class AbortError extends Error {
2
+ }
@@ -1,7 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  import { EventEmitter } from 'events';
3
- import { PoolOptions } from './PoolOptions';
4
- import { Callback, PoolConfiguration, PoolFactory, PoolState } from './definitions';
3
+ import { Callback, PoolConfiguration, PoolFactory, PoolState } from './definitions.js';
4
+ import { PoolOptions } from './PoolOptions.js';
5
5
  export declare class Pool<T = any> extends EventEmitter {
6
6
  private readonly _options;
7
7
  private readonly _factory;
package/esm/Pool.js ADDED
@@ -0,0 +1,457 @@
1
+ import DoublyLinked from 'doublylinked';
2
+ import { EventEmitter } from 'events';
3
+ import promisify from 'putil-promisify';
4
+ import { AbortError } from './AbortError.js';
5
+ import { PoolState, ResourceState } from './definitions.js';
6
+ import { PoolOptions } from './PoolOptions.js';
7
+ import { PoolRequest } from './PoolRequest.js';
8
+ import { ResourceItem } from './ResourceItem.js';
9
+ export class Pool extends EventEmitter {
10
+ constructor(factory, config) {
11
+ super();
12
+ this._requestQueue = new DoublyLinked();
13
+ this._allResources = new Map();
14
+ this._acquiredResources = new DoublyLinked();
15
+ this._idleResources = new DoublyLinked();
16
+ this._creating = 0;
17
+ this._requestsProcessing = 0;
18
+ this._state = PoolState.IDLE;
19
+ if (typeof factory !== 'object')
20
+ throw new TypeError('You must provide `factory` object');
21
+ if (typeof factory.create !== 'function')
22
+ throw new TypeError('factory.create must be a function');
23
+ if (typeof factory.destroy !== 'function')
24
+ throw new TypeError('factory.destroy must be a function');
25
+ if (factory.validate && typeof factory.validate !== 'function')
26
+ throw new TypeError('factory.validate can be a function');
27
+ if (factory.reset && typeof factory.reset !== 'function')
28
+ throw new TypeError('factory.reset can be a function');
29
+ const opts = this._options = new PoolOptions(this);
30
+ opts.on('change', (prop, val) => {
31
+ if (prop === 'houseKeepInterval')
32
+ this._setHouseKeep(val);
33
+ if (prop === 'min' || prop === 'minIdle')
34
+ this._ensureMin();
35
+ });
36
+ if (config)
37
+ this.options.assign(config);
38
+ this._factory = factory;
39
+ }
40
+ /**
41
+ * Returns Pool options
42
+ */
43
+ get options() {
44
+ return this._options;
45
+ }
46
+ /**
47
+ * Returns number of resources that are currently acquired
48
+ */
49
+ get acquired() {
50
+ return this._acquiredResources.length;
51
+ }
52
+ /**
53
+ * Returns number of unused resources in the pool
54
+ */
55
+ get available() {
56
+ return this._idleResources.length;
57
+ }
58
+ /**
59
+ * Returns number of resources currently creating
60
+ */
61
+ get creating() {
62
+ return this._creating;
63
+ }
64
+ /**
65
+ * Returns number of callers waiting to acquire a resource
66
+ */
67
+ get pending() {
68
+ return this._requestQueue.length + this._requestsProcessing;
69
+ }
70
+ /**
71
+ * Returns number of resources in the pool
72
+ * regardless of whether they are idle or in use
73
+ */
74
+ get size() {
75
+ return this._allResources.size;
76
+ }
77
+ /**
78
+ * Returns state of the pool
79
+ */
80
+ get state() {
81
+ return this._state;
82
+ }
83
+ /**
84
+ * Starts the pool and begins creating of resources, starts house keeping and any other internal logic.
85
+ * Note: This method is not need to be called. Pool instance will automatically be started when acquire() method is called
86
+ */
87
+ start() {
88
+ if (this._state === PoolState.STARTED)
89
+ return;
90
+ if (this._state >= PoolState.CLOSING)
91
+ throw new Error('Closed pool can not be started again');
92
+ this._state = PoolState.STARTED;
93
+ this._setHouseKeep(this.options.houseKeepInterval);
94
+ this._ensureMin();
95
+ this.emit('start');
96
+ }
97
+ close(arg0, arg1) {
98
+ let terminateWait = Infinity;
99
+ let callback;
100
+ if (typeof arg0 === 'function')
101
+ callback = arg0;
102
+ else {
103
+ terminateWait = typeof arg0 === 'number' ? arg0 :
104
+ (!!arg0 ? 0 : Infinity);
105
+ callback = arg1;
106
+ }
107
+ if (!callback)
108
+ return promisify.fromCallback(cb => this.close(terminateWait, cb));
109
+ if (this._state === PoolState.CLOSED || this._state === PoolState.IDLE)
110
+ return callback();
111
+ if (this._state === PoolState.CLOSING) {
112
+ this.once('close', callback);
113
+ return;
114
+ }
115
+ this.emit('closing');
116
+ if (this._houseKeepTimer)
117
+ clearTimeout(this._houseKeepTimer);
118
+ this._state = PoolState.CLOSING;
119
+ this._requestQueue.forEach(t => t.stopTimout());
120
+ this._requestQueue = new DoublyLinked();
121
+ this._requestsProcessing = 0;
122
+ if (terminateWait <= 0) {
123
+ this._acquiredResources.forEach(t => this.destroy(t.resource));
124
+ }
125
+ else {
126
+ const startTime = Date.now();
127
+ this._closeWaitTimer = setInterval(() => {
128
+ if (!this._allResources.size) {
129
+ clearInterval(this._closeWaitTimer);
130
+ this._closeWaitTimer = undefined;
131
+ return;
132
+ }
133
+ if (Date.now() > startTime + terminateWait) {
134
+ clearInterval(this._closeWaitTimer);
135
+ this._closeWaitTimer = undefined;
136
+ this._acquiredResources.forEach(t => this.release(t.resource));
137
+ this.emit('terminate');
138
+ }
139
+ }, 50);
140
+ }
141
+ this._setHouseKeep(5);
142
+ this.once('close', callback);
143
+ }
144
+ closeAsync(arg0) {
145
+ return promisify.fromCallback(cb => this.close(arg0, cb));
146
+ }
147
+ acquire(arg0) {
148
+ if (!arg0)
149
+ return promisify.fromCallback(cb => this.acquire(cb));
150
+ const callback = arg0;
151
+ try {
152
+ this.start();
153
+ }
154
+ catch (e) {
155
+ return callback(e);
156
+ }
157
+ if (this.options.maxQueue && this.pending >= this.options.maxQueue)
158
+ return callback(new Error('Pool queue is full'));
159
+ this._requestQueue.push(new PoolRequest(this, callback));
160
+ this._processNextRequest();
161
+ }
162
+ /**
163
+ * Releases an allocated `resource` and let it back to pool.
164
+ */
165
+ release(resource, callback) {
166
+ const item = this._allResources.get(resource);
167
+ if (item && item.state !== ResourceState.IDLE)
168
+ this._itemSetIdle(item, callback);
169
+ this._processNextRequest();
170
+ }
171
+ /**
172
+ * Async version of release().
173
+ */
174
+ releaseAsync(resource) {
175
+ return promisify.fromCallback(cb => this.release(resource, cb));
176
+ }
177
+ /**
178
+ * Releases, destroys and removes any `resource` from `Pool`.
179
+ */
180
+ destroy(resource, callback) {
181
+ try {
182
+ const item = this._allResources.get(resource);
183
+ if (item)
184
+ this._itemDestroy(item, callback);
185
+ else if (callback)
186
+ callback();
187
+ }
188
+ finally {
189
+ this._processNextRequest();
190
+ }
191
+ }
192
+ /**
193
+ * Async version of destroy().
194
+ */
195
+ destroyAsync(resource) {
196
+ return promisify.fromCallback(cb => this.destroy(resource, cb));
197
+ }
198
+ /**
199
+ * Returns if a `resource` has been acquired from the pool and not yet released or destroyed.
200
+ */
201
+ isAcquired(resource) {
202
+ const item = this._allResources.get(resource);
203
+ return !!(item && item.acquiredNode);
204
+ }
205
+ /**
206
+ * Returns if the pool contains a `resource`
207
+ */
208
+ includes(resource) {
209
+ return this._allResources.has(resource);
210
+ }
211
+ _processNextRequest() {
212
+ if (this._state !== PoolState.STARTED ||
213
+ this._requestsProcessing >= this.options.max - this.acquired)
214
+ return;
215
+ const request = this._requestQueue.shift();
216
+ if (!request)
217
+ return;
218
+ this._requestsProcessing++;
219
+ const handleCallback = (err, item) => {
220
+ this._requestsProcessing--;
221
+ request.stopTimout();
222
+ try {
223
+ if (item) {
224
+ /* istanbul ignore next : Hard to simulate */
225
+ if (this._state !== PoolState.STARTED) {
226
+ this._itemDestroy(item);
227
+ return;
228
+ }
229
+ this._itemSetAcquired(item);
230
+ this._ensureMin();
231
+ request.callback(undefined, item.resource);
232
+ this.emit('acquire', item.resource);
233
+ }
234
+ else
235
+ request.callback(err);
236
+ }
237
+ catch (ignored) {
238
+ // ignored
239
+ }
240
+ this._processNextRequest();
241
+ };
242
+ const item = this._idleResources.shift();
243
+ if (item) {
244
+ /* Validate resource */
245
+ if (this.options.validation && this._factory.validate) {
246
+ this._itemValidate(item, (err) => {
247
+ /* Destroy resource on validation error */
248
+ if (err) {
249
+ this._itemDestroy(item);
250
+ this.emit('validate-error', err, item.resource);
251
+ this._requestsProcessing--;
252
+ this._requestQueue.unshift(request);
253
+ this._processNextRequest();
254
+ }
255
+ else
256
+ handleCallback(undefined, item);
257
+ });
258
+ return;
259
+ }
260
+ return handleCallback(undefined, item);
261
+ }
262
+ /** There is no idle resource. We need to create new one **/
263
+ this._createResource(request, handleCallback);
264
+ }
265
+ emit(event, ...args) {
266
+ // Prevents errors while calling emit()
267
+ try {
268
+ return super.emit(event, ...args);
269
+ }
270
+ catch (e) {
271
+ return true;
272
+ }
273
+ }
274
+ /**
275
+ * Creates new resource
276
+ */
277
+ _createResource(request, callback) {
278
+ const maxRetries = this.options.acquireMaxRetries;
279
+ let tries = 0;
280
+ this._creating++;
281
+ const handleCallback = (err, obj) => {
282
+ if (request && request.timedOut)
283
+ return;
284
+ if (err || !obj) {
285
+ tries++;
286
+ this.emit('error', err, {
287
+ requestTime: request ? request.created : Date.now(),
288
+ tries,
289
+ maxRetries: this.options.acquireMaxRetries
290
+ });
291
+ if (err instanceof AbortError || tries >= maxRetries) {
292
+ this._creating--;
293
+ return callback && callback(err);
294
+ }
295
+ return setTimeout(() => tryCreate(), this.options.acquireRetryWait);
296
+ }
297
+ this._creating--;
298
+ if (this._allResources.has(obj))
299
+ return callback &&
300
+ callback(new Error('Factory error. Resource already in pool'));
301
+ const item = new ResourceItem(obj);
302
+ this._itemSetIdle(item);
303
+ this._allResources.set(obj, item);
304
+ if (callback)
305
+ callback(undefined, item);
306
+ this.emit('create', obj);
307
+ };
308
+ const tryCreate = () => {
309
+ try {
310
+ const o = this._factory.create({ tries, maxRetries });
311
+ /* istanbul ignore next */
312
+ if (!o)
313
+ return handleCallback(new AbortError('Factory returned no resource'));
314
+ promisify.await(o, handleCallback);
315
+ }
316
+ catch (e) {
317
+ handleCallback(e);
318
+ }
319
+ };
320
+ tryCreate();
321
+ }
322
+ _setHouseKeep(ms) {
323
+ if (this._houseKeepTimer)
324
+ clearInterval(this._houseKeepTimer);
325
+ this._houseKeepTimer = undefined;
326
+ if (ms > 0 && this.state === PoolState.STARTED || this.state === PoolState.CLOSING)
327
+ this._houseKeepTimer = setInterval(() => this._houseKeep(), ms);
328
+ }
329
+ _houseKeep() {
330
+ const isClosing = this._state === PoolState.CLOSING;
331
+ const now = Date.now();
332
+ let m = this._allResources.size - this.options.min;
333
+ let n = this._idleResources.length - this.options.minIdle;
334
+ if (isClosing || (m > 0 && n > 0)) {
335
+ this._idleResources.every((item) => {
336
+ if (isClosing ||
337
+ item.idleTime + this.options.idleTimeoutMillis < now) {
338
+ this._itemDestroy(item);
339
+ return isClosing || !!((--n) && (--m));
340
+ }
341
+ return false;
342
+ });
343
+ }
344
+ if (isClosing) {
345
+ /* Check again 5 ms later */
346
+ if (this._allResources.size)
347
+ return;
348
+ clearInterval(this._houseKeepTimer);
349
+ this._state = PoolState.CLOSED;
350
+ this._requestsProcessing = 0;
351
+ this.emit('close');
352
+ }
353
+ }
354
+ _ensureMin() {
355
+ process.nextTick(() => {
356
+ let k = Math.max(this.options.min - this._allResources.size, this.options.minIdle - this._idleResources.length) - this.creating;
357
+ while (k-- > 0)
358
+ this._createResource();
359
+ });
360
+ }
361
+ _itemSetAcquired(item) {
362
+ if (item.state !== ResourceState.ACQUIRED) {
363
+ this._itemDetach(item);
364
+ item.state = ResourceState.ACQUIRED;
365
+ this._acquiredResources.push(item);
366
+ item.acquiredNode = this._acquiredResources.tail;
367
+ }
368
+ }
369
+ _itemDetach(item) {
370
+ switch (item.state) {
371
+ case ResourceState.IDLE:
372
+ item.idleTime = 0;
373
+ /* istanbul ignore next*/
374
+ if (item.idleNode)
375
+ item.idleNode.remove();
376
+ item.idleNode = undefined;
377
+ break;
378
+ case ResourceState.ACQUIRED:
379
+ case ResourceState.VALIDATION:
380
+ /* istanbul ignore next*/
381
+ if (item.acquiredNode)
382
+ item.acquiredNode.remove();
383
+ item.acquiredNode = undefined;
384
+ break;
385
+ }
386
+ }
387
+ _itemSetIdle(item, callback) {
388
+ const isAcquired = item.state === ResourceState.ACQUIRED;
389
+ const handleCallback = (err) => {
390
+ if (err)
391
+ return this._itemDestroy(item, callback);
392
+ this._itemDetach(item);
393
+ item.idleTime = Date.now();
394
+ item.state = ResourceState.IDLE;
395
+ if (this.options.fifo) {
396
+ this._idleResources.push(item);
397
+ item.idleNode = this._idleResources.tail;
398
+ }
399
+ else {
400
+ this._idleResources.unshift(item);
401
+ item.idleNode = this._idleResources.head;
402
+ }
403
+ if (isAcquired)
404
+ this.emit('return', item.resource);
405
+ if (callback)
406
+ callback();
407
+ // noinspection JSAccessibilityCheck
408
+ this._processNextRequest();
409
+ };
410
+ if (isAcquired && this._factory.reset) {
411
+ try {
412
+ const o = this._factory.reset(item.resource);
413
+ promisify.await(o, handleCallback);
414
+ }
415
+ catch (e) {
416
+ handleCallback(e);
417
+ }
418
+ }
419
+ else
420
+ handleCallback();
421
+ }
422
+ _itemDestroy(item, callback) {
423
+ this._itemDetach(item);
424
+ const handleCallback = (err) => {
425
+ if (err) {
426
+ this.emit('destroy-error', err, item.resource);
427
+ /* istanbul ignore next */
428
+ return callback && callback(err);
429
+ }
430
+ this.emit('destroy', item.resource);
431
+ item.destroyed = true;
432
+ if (callback)
433
+ callback();
434
+ };
435
+ try {
436
+ this._allResources.delete(item.resource);
437
+ this._processNextRequest();
438
+ const o = this._factory.destroy(item.resource);
439
+ promisify.await(o, handleCallback);
440
+ }
441
+ catch (e) {
442
+ handleCallback(e);
443
+ }
444
+ }
445
+ _itemValidate(item, callback) {
446
+ item.state = ResourceState.VALIDATION;
447
+ try {
448
+ const o = this._factory.validate?.(item.resource);
449
+ // @ts-ignore
450
+ promisify.await(o, callback);
451
+ }
452
+ catch (e) {
453
+ if (callback)
454
+ callback(e);
455
+ }
456
+ }
457
+ }
@@ -1,7 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  import { EventEmitter } from 'events';
3
- import { Pool } from './Pool';
4
- import { PoolConfiguration } from './definitions';
3
+ import { PoolConfiguration } from './definitions.js';
4
+ import { Pool } from './Pool.js';
5
5
  export declare class PoolOptions extends EventEmitter {
6
6
  readonly pool: Pool;
7
7
  private _acquireMaxRetries;
@@ -0,0 +1,123 @@
1
+ import { EventEmitter } from 'events';
2
+ const defaultValues = {
3
+ acquireMaxRetries: 0,
4
+ acquireRetryWait: 2000,
5
+ acquireTimeoutMillis: 0,
6
+ fifo: true,
7
+ idleTimeoutMillis: 30000,
8
+ houseKeepInterval: 1000,
9
+ min: 0,
10
+ minIdle: 0,
11
+ max: 10,
12
+ maxQueue: 1000,
13
+ validation: true
14
+ };
15
+ export class PoolOptions extends EventEmitter {
16
+ constructor(pool) {
17
+ super();
18
+ this.pool = pool;
19
+ this._acquireMaxRetries = defaultValues.acquireMaxRetries;
20
+ this._acquireRetryWait = defaultValues.acquireRetryWait;
21
+ this._acquireTimeoutMillis = defaultValues.acquireTimeoutMillis;
22
+ this._fifo = defaultValues.fifo;
23
+ this._idleTimeoutMillis = defaultValues.idleTimeoutMillis;
24
+ this._houseKeepInterval = defaultValues.houseKeepInterval;
25
+ this._min = defaultValues.min;
26
+ this._minIdle = defaultValues.minIdle;
27
+ this._max = defaultValues.max;
28
+ this._maxQueue = defaultValues.maxQueue;
29
+ this._validation = defaultValues.validation;
30
+ this.pool = pool;
31
+ }
32
+ get acquireMaxRetries() {
33
+ return this._acquireMaxRetries;
34
+ }
35
+ set acquireMaxRetries(val) {
36
+ this._acquireMaxRetries = val >= 0 ? val : defaultValues.acquireMaxRetries;
37
+ this.emit('change', 'acquireMaxRetries', this._acquireMaxRetries);
38
+ }
39
+ get acquireRetryWait() {
40
+ return this._acquireRetryWait;
41
+ }
42
+ set acquireRetryWait(val) {
43
+ this._acquireRetryWait = val >= 0 ? val : defaultValues.acquireRetryWait;
44
+ this.emit('change', 'acquireRetryWait', this._acquireRetryWait);
45
+ }
46
+ get acquireTimeoutMillis() {
47
+ return this._acquireTimeoutMillis;
48
+ }
49
+ set acquireTimeoutMillis(val) {
50
+ this._acquireTimeoutMillis = val >= 0 ? val : defaultValues.acquireTimeoutMillis;
51
+ this.emit('change', 'acquireTimeoutMillis', this._acquireTimeoutMillis);
52
+ }
53
+ get fifo() {
54
+ return this._fifo;
55
+ }
56
+ set fifo(val) {
57
+ // noinspection PointlessBooleanExpressionJS
58
+ this._fifo = !!val;
59
+ this.emit('change', 'fifo', this.fifo);
60
+ }
61
+ get idleTimeoutMillis() {
62
+ return this._idleTimeoutMillis;
63
+ }
64
+ set idleTimeoutMillis(val) {
65
+ this._idleTimeoutMillis = val >= 0 ? val : defaultValues.idleTimeoutMillis;
66
+ this.emit('change', 'idleTimeoutMillis', this._idleTimeoutMillis);
67
+ }
68
+ get houseKeepInterval() {
69
+ return this._houseKeepInterval;
70
+ }
71
+ set houseKeepInterval(val) {
72
+ this._houseKeepInterval = val >= 0 ? val : defaultValues.houseKeepInterval;
73
+ this.emit('change', 'houseKeepInterval', this._houseKeepInterval);
74
+ }
75
+ get min() {
76
+ return this._min;
77
+ }
78
+ set min(val) {
79
+ this._min = val >= 0 ? val : defaultValues.min;
80
+ if (this._min > this._max)
81
+ this._max = this._min;
82
+ this.emit('change', 'min', this._min);
83
+ }
84
+ get minIdle() {
85
+ return this._minIdle;
86
+ }
87
+ set minIdle(val) {
88
+ this._minIdle = val >= 0 ? val : defaultValues.minIdle;
89
+ this.emit('change', 'minIdle', this.minIdle);
90
+ }
91
+ get max() {
92
+ return this._max;
93
+ }
94
+ set max(val) {
95
+ this._max = val >= 0 ? Math.max(val, 1) : defaultValues.max;
96
+ if (this._min > this._max)
97
+ this._min = this._max;
98
+ this.emit('change', 'max', this._max);
99
+ }
100
+ get maxQueue() {
101
+ return this._maxQueue;
102
+ }
103
+ set maxQueue(val) {
104
+ this._maxQueue = val >= 0 ? Math.max(val, 1) : defaultValues.maxQueue;
105
+ this.emit('change', 'maxQueue', this._maxQueue);
106
+ }
107
+ get validation() {
108
+ return this._validation;
109
+ }
110
+ set validation(val) {
111
+ // noinspection PointlessBooleanExpressionJS
112
+ this._validation = !!val;
113
+ this.emit('change', 'validation', this._validation);
114
+ }
115
+ assign(values) {
116
+ const proto = Object.getPrototypeOf(this);
117
+ for (const k of Object.keys(values)) {
118
+ const desc = Object.getOwnPropertyDescriptor(proto, k);
119
+ if (desc && desc.set)
120
+ this[k] = values[k];
121
+ }
122
+ }
123
+ }
@@ -1,5 +1,5 @@
1
- import { Callback } from './definitions';
2
- import { Pool } from './Pool';
1
+ import { Callback } from './definitions.js';
2
+ import { Pool } from './Pool.js';
3
3
  export declare class PoolRequest {
4
4
  created: number;
5
5
  callback: Callback;
@@ -0,0 +1,22 @@
1
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
2
+ function noop() {
3
+ }
4
+ export class PoolRequest {
5
+ constructor(pool, callback) {
6
+ this.timedOut = false;
7
+ this.created = Date.now();
8
+ this.callback = callback || noop;
9
+ if (pool.options.acquireTimeoutMillis) {
10
+ this.timeoutHandle = setTimeout(() => {
11
+ this.timedOut = true;
12
+ this.stopTimout();
13
+ pool.emit('request-timeout');
14
+ this.callback(new Error('Request timed out'));
15
+ }, pool.options.acquireTimeoutMillis);
16
+ }
17
+ }
18
+ stopTimout() {
19
+ if (this.timeoutHandle)
20
+ clearTimeout(this.timeoutHandle);
21
+ }
22
+ }
@@ -1,5 +1,5 @@
1
- import { ResourceState } from './definitions';
2
1
  import { DoublyLinked } from 'doublylinked';
2
+ import { ResourceState } from './definitions.js';
3
3
  export declare class ResourceItem<T> {
4
4
  state: ResourceState;
5
5
  acquiredNode?: DoublyLinked.Node;
@@ -0,0 +1,9 @@
1
+ import { ResourceState } from './definitions.js';
2
+ export class ResourceItem {
3
+ constructor(resource) {
4
+ this.state = ResourceState.IDLE;
5
+ this.idleTime = 0;
6
+ this.destroyed = false;
7
+ this.resource = resource;
8
+ }
9
+ }
@@ -1,4 +1,3 @@
1
- export declare type Maybe<T> = T | undefined;
2
1
  export declare type Callback = (e?: Error, ...args: any[]) => void;
3
2
  export declare enum PoolState {
4
3
  IDLE = 0,
@@ -17,8 +16,8 @@ export interface PoolFactory<T = any> {
17
16
  maxRetries: number;
18
17
  }): Promise<T> | T;
19
18
  destroy(resource: T): Promise<void> | void;
20
- reset(resource: T): Promise<void> | void;
21
- validate(resource: T): Promise<void> | void;
19
+ reset?(resource: T): Promise<void> | void;
20
+ validate?(resource: T): Promise<void> | void;
22
21
  }
23
22
  export interface PoolConfiguration {
24
23
  acquireMaxRetries?: number;
@@ -0,0 +1,13 @@
1
+ export var PoolState;
2
+ (function (PoolState) {
3
+ PoolState[PoolState["IDLE"] = 0] = "IDLE";
4
+ PoolState[PoolState["STARTED"] = 1] = "STARTED";
5
+ PoolState[PoolState["CLOSING"] = 2] = "CLOSING";
6
+ PoolState[PoolState["CLOSED"] = 3] = "CLOSED";
7
+ })(PoolState || (PoolState = {}));
8
+ export var ResourceState;
9
+ (function (ResourceState) {
10
+ ResourceState[ResourceState["IDLE"] = 0] = "IDLE";
11
+ ResourceState[ResourceState["ACQUIRED"] = 1] = "ACQUIRED";
12
+ ResourceState[ResourceState["VALIDATION"] = 2] = "VALIDATION";
13
+ })(ResourceState || (ResourceState = {}));
package/esm/index.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { PoolConfiguration, PoolFactory } from './definitions.js';
2
+ import { Pool } from './Pool.js';
3
+ export * from './definitions.js';
4
+ export * from './Pool.js';
5
+ export * from './AbortError.js';
6
+ export declare function createPool<T = any>(factory: PoolFactory<T>, config?: PoolConfiguration): Pool<T>;
package/esm/index.js ADDED
@@ -0,0 +1,7 @@
1
+ import { Pool } from './Pool.js';
2
+ export * from './definitions.js';
3
+ export * from './Pool.js';
4
+ export * from './AbortError.js';
5
+ export function createPool(factory, config) {
6
+ return new Pool(factory, config);
7
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "lightning-pool",
3
3
  "description": "Fastest generic Pool written with TypeScript",
4
- "version": "3.1.3",
4
+ "version": "4.0.0",
5
5
  "author": "Panates Ltd.",
6
6
  "contributors": [
7
7
  "Eray Hanoglu <e.hanoglu@panates.com>"
@@ -9,59 +9,66 @@
9
9
  "license": "MIT",
10
10
  "repository": "panates/lightning-pool",
11
11
  "keywords": [
12
- "javascript",
13
- "typescript",
14
12
  "pool",
15
- "generic"
13
+ "generic",
14
+ "generic-pool"
16
15
  ],
17
16
  "dependencies": {
18
- "doublylinked": "^2.4.3",
19
- "putil-promisify": "^1.8.2"
17
+ "doublylinked": "^2.5.1",
18
+ "putil-promisify": "^1.8.5"
20
19
  },
21
20
  "devDependencies": {
22
- "@types/mocha": "^8.2.0",
23
- "@types/node": "^15.6.1",
24
- "@typescript-eslint/eslint-plugin": "^4.9.1",
25
- "@typescript-eslint/parser": "^4.9.1",
26
- "@babel/eslint-parser": "^7.14.7",
27
- "dotenv": "^10.0.0",
28
- "eslint": "^7.15.0",
21
+ "@babel/eslint-parser": "^7.19.1",
22
+ "@types/jest": "^29.0.2",
23
+ "@types/node": "^18.7.18",
24
+ "@typescript-eslint/eslint-plugin": "^5.37.0",
25
+ "@typescript-eslint/parser": "^5.37.0",
26
+ "dotenv": "^16.0.2",
27
+ "eslint": "^8.23.1",
29
28
  "eslint-config-google": "^0.14.0",
30
- "mocha": "^9.0.1",
31
- "npm-run-path": "^4.0.1",
32
- "nyc": "^15.1.0",
33
- "ts-cleanup": "^0.2.2",
34
- "ts-loader": "^9.2.3",
35
- "ts-node": "^10.0.0",
36
- "tsconfig-paths": "^3.9.0",
37
- "typescript": "^4.1.2"
29
+ "eslint-plugin-import": "^2.26.0",
30
+ "eslint-plugin-security": "^1.5.0",
31
+ "eslint-plugin-simple-import-sort": "^8.0.0",
32
+ "eslint-plugin-unused-imports": "^2.0.0",
33
+ "jest": "^29.0.3",
34
+ "npm-run-path": "^5.1.0",
35
+ "ts-cleanup": "^0.2.5",
36
+ "ts-jest": "^29.0.1",
37
+ "ts-loader": "^9.3.1",
38
+ "ts-node": "^10.9.1",
39
+ "tsconfig-paths": "^4.1.0",
40
+ "typescript": "^4.8.3"
38
41
  },
39
- "engines": {
40
- "node": ">= 10.0"
41
- },
42
- "main": "dist/index.js",
43
- "types": "dist/index.d.ts",
44
- "directories": {
45
- "lib": "dist",
46
- "test": "test"
42
+ "type": "module",
43
+ "main": "cjs/index.js",
44
+ "module": "esm/index.js",
45
+ "types": "esm/index.d.ts",
46
+ "exports": {
47
+ ".": "./cjs/index.js",
48
+ "./cjs": "./cjs/index.js",
49
+ "./esm": "./esm/index.js"
47
50
  },
48
51
  "files": [
52
+ "bin/",
53
+ "cjs/",
54
+ "esm/",
49
55
  "LICENSE",
50
- "README",
51
- "dist/"
56
+ "README.md"
52
57
  ],
53
- "nyc": {
54
- "temp-dir": "./coverage/.nyc_output"
55
- },
56
58
  "scripts": {
57
- "test": "TS_NODE_PROJECT='./test/tsconfig.json' mocha -r ts-node/register --reporter spec test/**/*.spec.ts",
58
- "cover": "nyc --reporter=cobertura --reporter html --reporter text npm run test",
59
+ "lint": "eslint .",
59
60
  "clean": "npm run clean:src && npm run clean:dist",
60
- "clean:dist": "ts-cleanup -d dist --remove-dirs --all",
61
+ "clean:dist": "rimraf cjs esm coverage",
61
62
  "clean:src": "ts-cleanup -s src --all | ts-cleanup -s test",
62
- "build": "tsc -b tsconfig-build.json",
63
- "compile": "tsc -b tsconfig.json",
64
- "lint": "eslint src/** --no-error-on-unmatched-pattern",
65
- "travis-cover": "nyc --reporter lcovonly npm run test"
63
+ "prebuild": "npm run clean:dist && npm run lint",
64
+ "build": "npm run build:cjs && npm run build:esm",
65
+ "build:cjs": "tsc -b tsconfig-build-cjs.json",
66
+ "build:esm": "tsc -b tsconfig-build-esm.json",
67
+ "postbuild": "cp package.cjs.json ./cjs/package.json",
68
+ "test": "jest --runInBand --detectOpenHandles",
69
+ "precover": "rimraf coverage",
70
+ "cover": "jest --maxWorkers=1 --coverage",
71
+ "precitest": "rimraf coverage",
72
+ "citest": "jest --coverage --coverageReporters=lcov"
66
73
  }
67
74
  }
package/dist/index.d.ts DELETED
@@ -1,6 +0,0 @@
1
- import { PoolConfiguration, PoolFactory } from './definitions';
2
- import { Pool } from './Pool';
3
- export * from './definitions';
4
- export * from './Pool';
5
- export * from './AbortError';
6
- export declare function createPool<T = any>(factory: PoolFactory<T>, config?: PoolConfiguration): Pool<T>;