lightning-pool 4.4.3 → 4.6.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/esm/pool.js DELETED
@@ -1,471 +0,0 @@
1
- import DoublyLinked from 'doublylinked';
2
- import { EventEmitter } from 'events';
3
- import promisify from 'putil-promisify';
4
- import { AbortError } from './abort-error.js';
5
- import { PoolState, ResourceState, } from './definitions.js';
6
- import { PoolOptions } from './pool-options.js';
7
- import { PoolRequest } from './pool-request.js';
8
- import { ResourceItem } from './resource-item.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
- }
22
- if (typeof factory.create !== 'function') {
23
- throw new TypeError('factory.create must be a function');
24
- }
25
- if (typeof factory.destroy !== 'function') {
26
- throw new TypeError('factory.destroy must be a function');
27
- }
28
- if (factory.validate && typeof factory.validate !== 'function') {
29
- throw new TypeError('factory.validate can be a function');
30
- }
31
- if (factory.reset && typeof factory.reset !== 'function') {
32
- throw new TypeError('factory.reset can be a function');
33
- }
34
- const opts = (this._options = new PoolOptions(this));
35
- opts.on('change', (prop, val) => {
36
- if (prop === 'houseKeepInterval')
37
- this._setHouseKeep(val);
38
- if (prop === 'min' || prop === 'minIdle')
39
- this._ensureMin();
40
- });
41
- if (config)
42
- this.options.assign(config);
43
- this._factory = factory;
44
- }
45
- /**
46
- * Returns Pool options
47
- */
48
- get options() {
49
- return this._options;
50
- }
51
- /**
52
- * Returns number of resources that are currently acquired
53
- */
54
- get acquired() {
55
- return this._acquiredResources.length;
56
- }
57
- /**
58
- * Returns number of unused resources in the pool
59
- */
60
- get available() {
61
- return this._idleResources.length;
62
- }
63
- /**
64
- * Returns number of resources currently creating
65
- */
66
- get creating() {
67
- return this._creating;
68
- }
69
- /**
70
- * Returns number of callers waiting to acquire a resource
71
- */
72
- get pending() {
73
- return this._requestQueue.length + this._requestsProcessing;
74
- }
75
- /**
76
- * Returns number of resources in the pool
77
- * regardless of whether they are idle or in use
78
- */
79
- get size() {
80
- return this._allResources.size;
81
- }
82
- /**
83
- * Returns state of the pool
84
- */
85
- get state() {
86
- return this._state;
87
- }
88
- /**
89
- * Starts the pool and begins creating of resources, starts house keeping and any other internal logic.
90
- * Note: This method is not need to be called. Pool instance will automatically be started when acquire() method is called
91
- */
92
- start() {
93
- if (this._state === PoolState.STARTED)
94
- return;
95
- if (this._state >= PoolState.CLOSING) {
96
- throw new Error('Closed pool can not be started again');
97
- }
98
- this._state = PoolState.STARTED;
99
- this._setHouseKeep(this.options.houseKeepInterval);
100
- this._ensureMin();
101
- this.emit('start');
102
- }
103
- close(arg0, arg1) {
104
- let terminateWait = Infinity;
105
- let callback;
106
- if (typeof arg0 === 'function')
107
- callback = arg0;
108
- else {
109
- terminateWait = typeof arg0 === 'number' ? arg0 : arg0 ? 0 : Infinity;
110
- callback = arg1;
111
- }
112
- if (!callback) {
113
- return promisify.fromCallback(cb => this.close(terminateWait, cb));
114
- }
115
- if (this._state === PoolState.CLOSED || this._state === PoolState.IDLE) {
116
- return callback();
117
- }
118
- if (this._state === PoolState.CLOSING) {
119
- this.once('close', callback);
120
- return;
121
- }
122
- this.emit('closing');
123
- if (this._houseKeepTimer)
124
- clearTimeout(this._houseKeepTimer);
125
- this._state = PoolState.CLOSING;
126
- this._requestQueue.forEach(t => t.stopTimout());
127
- this._requestQueue = new DoublyLinked();
128
- this._requestsProcessing = 0;
129
- if (terminateWait <= 0) {
130
- this._acquiredResources.forEach(t => this.destroy(t.resource));
131
- }
132
- else {
133
- const startTime = Date.now();
134
- this._closeWaitTimer = setInterval(() => {
135
- if (!this._allResources.size) {
136
- clearInterval(this._closeWaitTimer);
137
- this._closeWaitTimer = undefined;
138
- return;
139
- }
140
- if (Date.now() > startTime + terminateWait) {
141
- clearInterval(this._closeWaitTimer);
142
- this._closeWaitTimer = undefined;
143
- this._acquiredResources.forEach(t => this.release(t.resource));
144
- this.emit('terminate');
145
- }
146
- }, 50);
147
- }
148
- this._setHouseKeep(5);
149
- this.once('close', callback);
150
- }
151
- closeAsync(arg0) {
152
- return promisify.fromCallback(cb => this.close(arg0, cb));
153
- }
154
- acquire(callback) {
155
- if (!callback)
156
- return promisify.fromCallback(cb => this.acquire(cb));
157
- try {
158
- this.start();
159
- }
160
- catch (e) {
161
- return callback(e);
162
- }
163
- if (this.options.maxQueue && this.pending >= this.options.maxQueue) {
164
- return callback(new Error('Pool queue is full'));
165
- }
166
- this._requestQueue.push(new PoolRequest(this, callback));
167
- this._processNextRequest();
168
- }
169
- /**
170
- * Releases an allocated `resource` and let it back to pool.
171
- */
172
- release(resource, callback) {
173
- const item = this._allResources.get(resource);
174
- if (item && item.state !== ResourceState.IDLE) {
175
- this._itemSetIdle(item, callback);
176
- }
177
- this._processNextRequest();
178
- }
179
- /**
180
- * Async version of release().
181
- */
182
- releaseAsync(resource) {
183
- return promisify.fromCallback(cb => this.release(resource, cb));
184
- }
185
- /**
186
- * Releases, destroys and removes any `resource` from `Pool`.
187
- */
188
- destroy(resource, callback) {
189
- try {
190
- const item = this._allResources.get(resource);
191
- if (item)
192
- this._itemDestroy(item, callback);
193
- else if (callback)
194
- callback();
195
- }
196
- finally {
197
- this._processNextRequest();
198
- }
199
- }
200
- /**
201
- * Async version of destroy().
202
- */
203
- destroyAsync(resource) {
204
- return promisify.fromCallback(cb => this.destroy(resource, cb));
205
- }
206
- /**
207
- * Returns if a `resource` has been acquired from the pool and not yet released or destroyed.
208
- */
209
- isAcquired(resource) {
210
- const item = this._allResources.get(resource);
211
- return !!(item && item.acquiredNode);
212
- }
213
- /**
214
- * Returns if the pool contains a `resource`
215
- */
216
- includes(resource) {
217
- return this._allResources.has(resource);
218
- }
219
- _processNextRequest() {
220
- if (this._state !== PoolState.STARTED ||
221
- this._requestsProcessing >= this.options.max - this.acquired) {
222
- return;
223
- }
224
- const request = this._requestQueue.shift();
225
- if (!request)
226
- return;
227
- this._requestsProcessing++;
228
- const handleCallback = (err, item) => {
229
- this._requestsProcessing--;
230
- request.stopTimout();
231
- try {
232
- if (item) {
233
- /* istanbul ignore next : Hard to simulate */
234
- if (this._state !== PoolState.STARTED) {
235
- this._itemDestroy(item);
236
- return;
237
- }
238
- this._itemSetAcquired(item);
239
- this._ensureMin();
240
- request.callback(undefined, item.resource);
241
- this.emit('acquire', item.resource);
242
- }
243
- else
244
- request.callback(err);
245
- }
246
- catch (ignored) {
247
- // ignored
248
- }
249
- this._processNextRequest();
250
- };
251
- const item = this._idleResources.shift();
252
- if (item) {
253
- /* Validate resource */
254
- if (this.options.validation && this._factory.validate) {
255
- this._itemValidate(item, (err) => {
256
- /* Destroy resource on validation error */
257
- if (err) {
258
- this._itemDestroy(item);
259
- this.emit('validate-error', err, item.resource);
260
- this._requestsProcessing--;
261
- this._requestQueue.unshift(request);
262
- this._processNextRequest();
263
- }
264
- else
265
- handleCallback(undefined, item);
266
- });
267
- return;
268
- }
269
- return handleCallback(undefined, item);
270
- }
271
- /** There is no idle resource. We need to create new one **/
272
- this._createResource(request, handleCallback);
273
- }
274
- emit(event, ...args) {
275
- // Prevents errors while calling emit()
276
- try {
277
- return super.emit(event, ...args);
278
- }
279
- catch (e) {
280
- return true;
281
- }
282
- }
283
- /**
284
- * Creates new resource
285
- */
286
- _createResource(request, callback) {
287
- const maxRetries = this.options.acquireMaxRetries;
288
- let tries = 0;
289
- this._creating++;
290
- const handleCallback = (err, obj) => {
291
- if (request && request.timedOut)
292
- return;
293
- if (err || !obj) {
294
- tries++;
295
- this.emit('error', err, {
296
- requestTime: request ? request.created : Date.now(),
297
- tries,
298
- maxRetries: this.options.acquireMaxRetries,
299
- });
300
- if (err instanceof AbortError || tries >= maxRetries) {
301
- this._creating--;
302
- return callback && callback(err);
303
- }
304
- return setTimeout(() => tryCreate(), this.options.acquireRetryWait);
305
- }
306
- this._creating--;
307
- if (this._allResources.has(obj)) {
308
- return (callback &&
309
- callback(new Error('Factory error. Resource already in pool')));
310
- }
311
- const item = new ResourceItem(obj);
312
- this._itemSetIdle(item);
313
- this._allResources.set(obj, item);
314
- if (callback)
315
- callback(undefined, item);
316
- this.emit('create', obj);
317
- };
318
- const tryCreate = () => {
319
- try {
320
- const o = this._factory.create({ tries, maxRetries });
321
- /* istanbul ignore next */
322
- if (!o) {
323
- return handleCallback(new AbortError('Factory returned no resource'));
324
- }
325
- promisify.await(o, handleCallback);
326
- }
327
- catch (e) {
328
- handleCallback(e);
329
- }
330
- };
331
- tryCreate();
332
- }
333
- _setHouseKeep(ms) {
334
- if (this._houseKeepTimer)
335
- clearInterval(this._houseKeepTimer);
336
- this._houseKeepTimer = undefined;
337
- if ((ms > 0 && this.state === PoolState.STARTED) ||
338
- this.state === PoolState.CLOSING) {
339
- this._houseKeepTimer = setInterval(() => this._houseKeep(), ms);
340
- }
341
- }
342
- _houseKeep() {
343
- const isClosing = this._state === PoolState.CLOSING;
344
- const now = Date.now();
345
- let m = this._allResources.size - this.options.min;
346
- let n = this._idleResources.length - this.options.minIdle;
347
- if (isClosing || (m > 0 && n > 0)) {
348
- this._idleResources.every((item) => {
349
- if (isClosing || item.idleTime + this.options.idleTimeoutMillis < now) {
350
- this._itemDestroy(item);
351
- return isClosing || !!(--n && --m);
352
- }
353
- return false;
354
- });
355
- }
356
- if (isClosing) {
357
- /* Check again 5 ms later */
358
- if (this._allResources.size)
359
- return;
360
- clearInterval(this._houseKeepTimer);
361
- this._state = PoolState.CLOSED;
362
- this._requestsProcessing = 0;
363
- this.emit('close');
364
- }
365
- }
366
- _ensureMin() {
367
- process.nextTick(() => {
368
- let k = Math.max(this.options.min - this._allResources.size, this.options.minIdle - this._idleResources.length) - this.creating;
369
- while (k-- > 0)
370
- this._createResource();
371
- });
372
- }
373
- _itemSetAcquired(item) {
374
- if (item.state !== ResourceState.ACQUIRED) {
375
- this._itemDetach(item);
376
- item.state = ResourceState.ACQUIRED;
377
- this._acquiredResources.push(item);
378
- item.acquiredNode = this._acquiredResources.tail;
379
- }
380
- }
381
- _itemDetach(item) {
382
- switch (item.state) {
383
- case ResourceState.IDLE:
384
- item.idleTime = 0;
385
- /* istanbul ignore next*/
386
- if (item.idleNode)
387
- item.idleNode.remove();
388
- item.idleNode = undefined;
389
- break;
390
- case ResourceState.ACQUIRED:
391
- case ResourceState.VALIDATION:
392
- /* istanbul ignore next*/
393
- if (item.acquiredNode)
394
- item.acquiredNode.remove();
395
- item.acquiredNode = undefined;
396
- break;
397
- default:
398
- break;
399
- }
400
- }
401
- _itemSetIdle(item, callback) {
402
- const isAcquired = item.state === ResourceState.ACQUIRED;
403
- const handleCallback = (err) => {
404
- if (err)
405
- return this._itemDestroy(item, callback);
406
- this._itemDetach(item);
407
- item.idleTime = Date.now();
408
- item.state = ResourceState.IDLE;
409
- if (this.options.fifo) {
410
- this._idleResources.push(item);
411
- item.idleNode = this._idleResources.tail;
412
- }
413
- else {
414
- this._idleResources.unshift(item);
415
- item.idleNode = this._idleResources.head;
416
- }
417
- if (isAcquired)
418
- this.emit('return', item.resource);
419
- if (callback)
420
- callback();
421
- // noinspection JSAccessibilityCheck
422
- this._processNextRequest();
423
- };
424
- if (isAcquired && this._factory.reset) {
425
- try {
426
- const o = this._factory.reset(item.resource);
427
- promisify.await(o, handleCallback);
428
- }
429
- catch (e) {
430
- handleCallback(e);
431
- }
432
- }
433
- else
434
- handleCallback();
435
- }
436
- _itemDestroy(item, callback) {
437
- this._itemDetach(item);
438
- const handleCallback = (err) => {
439
- if (err) {
440
- this.emit('destroy-error', err, item.resource);
441
- /* istanbul ignore next */
442
- return callback && callback(err);
443
- }
444
- this.emit('destroy', item.resource);
445
- item.destroyed = true;
446
- if (callback)
447
- callback();
448
- };
449
- try {
450
- this._allResources.delete(item.resource);
451
- this._processNextRequest();
452
- const o = this._factory.destroy(item.resource);
453
- promisify.await(o, handleCallback);
454
- }
455
- catch (e) {
456
- handleCallback(e);
457
- }
458
- }
459
- _itemValidate(item, callback) {
460
- item.state = ResourceState.VALIDATION;
461
- try {
462
- const o = this._factory.validate?.(item.resource);
463
- // @ts-ignore
464
- promisify.await(o, callback);
465
- }
466
- catch (e) {
467
- if (callback)
468
- callback(e);
469
- }
470
- }
471
- }
@@ -1,9 +0,0 @@
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,2 +0,0 @@
1
- export declare class AbortError extends Error {
2
- }
@@ -1,34 +0,0 @@
1
- export type Callback = (e?: unknown, ...args: any[]) => void;
2
- export declare enum PoolState {
3
- IDLE = 0,
4
- STARTED = 1,
5
- CLOSING = 2,
6
- CLOSED = 3
7
- }
8
- export declare enum ResourceState {
9
- IDLE = 0,
10
- ACQUIRED = 1,
11
- VALIDATION = 2
12
- }
13
- export interface PoolFactory<T = any> {
14
- create(info?: {
15
- tries: number;
16
- maxRetries: number;
17
- }): Promise<T> | T;
18
- destroy(resource: T): Promise<void> | void;
19
- reset?(resource: T): Promise<void> | void;
20
- validate?(resource: T): Promise<void> | void;
21
- }
22
- export interface PoolConfiguration {
23
- acquireMaxRetries?: number;
24
- acquireRetryWait?: number;
25
- acquireTimeoutMillis?: number;
26
- fifo?: boolean;
27
- idleTimeoutMillis?: number;
28
- houseKeepInterval?: number;
29
- min?: number;
30
- minIdle?: number;
31
- max?: number;
32
- maxQueue?: number;
33
- validation?: boolean;
34
- }
@@ -1,6 +0,0 @@
1
- import { PoolConfiguration, PoolFactory } from './definitions.js';
2
- import { Pool } from './pool.js';
3
- export * from './abort-error.js';
4
- export * from './definitions.js';
5
- export * from './pool.js';
6
- export declare function createPool<T = any>(factory: PoolFactory<T>, config?: PoolConfiguration): Pool<T>;
@@ -1,41 +0,0 @@
1
- import { EventEmitter } from 'events';
2
- import { PoolConfiguration } from './definitions.js';
3
- import { Pool } from './pool.js';
4
- export declare class PoolOptions extends EventEmitter {
5
- readonly pool: Pool;
6
- private _acquireMaxRetries;
7
- private _acquireRetryWait;
8
- private _acquireTimeoutMillis;
9
- private _fifo;
10
- private _idleTimeoutMillis;
11
- private _houseKeepInterval;
12
- private _min;
13
- private _minIdle;
14
- private _max;
15
- private _maxQueue;
16
- private _validation;
17
- constructor(pool: Pool);
18
- get acquireMaxRetries(): number;
19
- set acquireMaxRetries(val: number);
20
- get acquireRetryWait(): number;
21
- set acquireRetryWait(val: number);
22
- get acquireTimeoutMillis(): number;
23
- set acquireTimeoutMillis(val: number);
24
- get fifo(): boolean;
25
- set fifo(val: boolean);
26
- get idleTimeoutMillis(): number;
27
- set idleTimeoutMillis(val: number);
28
- get houseKeepInterval(): number;
29
- set houseKeepInterval(val: number);
30
- get min(): number;
31
- set min(val: number);
32
- get minIdle(): number;
33
- set minIdle(val: number);
34
- get max(): number;
35
- set max(val: number);
36
- get maxQueue(): number;
37
- set maxQueue(val: number);
38
- get validation(): boolean;
39
- set validation(val: boolean);
40
- assign(values: PoolConfiguration | PoolOptions): void;
41
- }
@@ -1,11 +0,0 @@
1
- import { Callback } from './definitions.js';
2
- import { Pool } from './pool.js';
3
- export declare class PoolRequest {
4
- created: number;
5
- callback: Callback;
6
- options?: any;
7
- timeoutHandle: any;
8
- timedOut: boolean;
9
- constructor(pool: Pool, callback?: Callback, options?: any);
10
- stopTimout(): void;
11
- }
package/typings/pool.d.ts DELETED
@@ -1,103 +0,0 @@
1
- import { EventEmitter } from 'events';
2
- import { Callback, PoolConfiguration, PoolFactory, PoolState } from './definitions.js';
3
- import { PoolOptions } from './pool-options.js';
4
- export declare class Pool<T = any> extends EventEmitter {
5
- private readonly _options;
6
- private readonly _factory;
7
- private _requestQueue;
8
- private _allResources;
9
- private _acquiredResources;
10
- private _idleResources;
11
- private _creating;
12
- private _requestsProcessing;
13
- private _state;
14
- private _houseKeepTimer;
15
- private _closeWaitTimer;
16
- constructor(factory: PoolFactory<T>, config?: PoolConfiguration);
17
- /**
18
- * Returns Pool options
19
- */
20
- get options(): PoolOptions;
21
- /**
22
- * Returns number of resources that are currently acquired
23
- */
24
- get acquired(): number;
25
- /**
26
- * Returns number of unused resources in the pool
27
- */
28
- get available(): number;
29
- /**
30
- * Returns number of resources currently creating
31
- */
32
- get creating(): number;
33
- /**
34
- * Returns number of callers waiting to acquire a resource
35
- */
36
- get pending(): number;
37
- /**
38
- * Returns number of resources in the pool
39
- * regardless of whether they are idle or in use
40
- */
41
- get size(): number;
42
- /**
43
- * Returns state of the pool
44
- */
45
- get state(): PoolState;
46
- /**
47
- * Starts the pool and begins creating of resources, starts house keeping and any other internal logic.
48
- * Note: This method is not need to be called. Pool instance will automatically be started when acquire() method is called
49
- */
50
- start(): void;
51
- /**
52
- * Shuts down the pool and destroys all resources.
53
- */
54
- close(callback?: Callback): void;
55
- close(terminateWait: number, callback?: Callback): void;
56
- close(force: boolean, callback?: Callback): void;
57
- closeAsync(): Promise<void>;
58
- closeAsync(terminateWait: number): Promise<void>;
59
- closeAsync(force: boolean): Promise<void>;
60
- /**
61
- * Acquires `resource` from the pool or create a new one
62
- */
63
- acquire(): Promise<T>;
64
- acquire(callback: Callback): void;
65
- /**
66
- * Releases an allocated `resource` and let it back to pool.
67
- */
68
- release(resource: T, callback?: Callback): void;
69
- /**
70
- * Async version of release().
71
- */
72
- releaseAsync(resource: T): Promise<void>;
73
- /**
74
- * Releases, destroys and removes any `resource` from `Pool`.
75
- */
76
- destroy(resource: T, callback?: Callback): any;
77
- /**
78
- * Async version of destroy().
79
- */
80
- destroyAsync(resource: T): Promise<void>;
81
- /**
82
- * Returns if a `resource` has been acquired from the pool and not yet released or destroyed.
83
- */
84
- isAcquired(resource: T): boolean;
85
- /**
86
- * Returns if the pool contains a `resource`
87
- */
88
- includes(resource: T): boolean;
89
- private _processNextRequest;
90
- emit(event: string | symbol, ...args: any[]): boolean;
91
- /**
92
- * Creates new resource
93
- */
94
- private _createResource;
95
- private _setHouseKeep;
96
- private _houseKeep;
97
- private _ensureMin;
98
- private _itemSetAcquired;
99
- private _itemDetach;
100
- private _itemSetIdle;
101
- private _itemDestroy;
102
- private _itemValidate;
103
- }
@@ -1,11 +0,0 @@
1
- import { DoublyLinked } from 'doublylinked';
2
- import { ResourceState } from './definitions.js';
3
- export declare class ResourceItem<T> {
4
- state: ResourceState;
5
- acquiredNode?: DoublyLinked.Node;
6
- idleNode?: DoublyLinked.Node;
7
- resource: T;
8
- idleTime: number;
9
- destroyed: boolean;
10
- constructor(resource: T);
11
- }