lightning-pool 4.13.0 → 4.14.2

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/pool-options.js CHANGED
@@ -12,6 +12,14 @@ const defaultValues = {
12
12
  maxQueue: 1000,
13
13
  validation: true,
14
14
  };
15
+ /**
16
+ * Live, mutable configuration for a `Pool`, exposed as `pool.options`. Every
17
+ * property is a get/set pair - assigning one takes effect immediately (e.g.
18
+ * `pool.options.max = 20`) and emits a `'change'` event that `Pool` reacts
19
+ * to (adjusting the housekeeper interval, topping up `min`/`minIdle`, etc.).
20
+ * See `PoolConfiguration` for what each option means; the defaults are the
21
+ * same for both.
22
+ */
15
23
  export class PoolOptions extends EventEmitter {
16
24
  pool;
17
25
  _acquireMaxRetries = defaultValues.acquireMaxRetries;
@@ -30,28 +38,40 @@ export class PoolOptions extends EventEmitter {
30
38
  this.pool = pool;
31
39
  this.pool = pool;
32
40
  }
41
+ /** @defaultValue `0` - fail on the first error, no retries. */
33
42
  get acquireMaxRetries() {
34
43
  return this._acquireMaxRetries;
35
44
  }
45
+ /** Negative values reset to the default instead of being applied. */
36
46
  set acquireMaxRetries(val) {
37
47
  this._acquireMaxRetries = val >= 0 ? val : defaultValues.acquireMaxRetries;
38
48
  this.emit('change', 'acquireMaxRetries', this._acquireMaxRetries);
39
49
  }
50
+ /** @defaultValue `2000` (milliseconds) */
40
51
  get acquireRetryWait() {
41
52
  return this._acquireRetryWait;
42
53
  }
54
+ /** Negative values reset to the default instead of being applied. */
43
55
  set acquireRetryWait(val) {
44
56
  this._acquireRetryWait = val >= 0 ? val : defaultValues.acquireRetryWait;
45
57
  this.emit('change', 'acquireRetryWait', this._acquireRetryWait);
46
58
  }
59
+ /** @defaultValue `0` (milliseconds) - no timeout. */
47
60
  get acquireTimeoutMillis() {
48
61
  return this._acquireTimeoutMillis;
49
62
  }
63
+ /** Negative values reset to the default instead of being applied. */
50
64
  set acquireTimeoutMillis(val) {
51
65
  this._acquireTimeoutMillis =
52
66
  val >= 0 ? val : defaultValues.acquireTimeoutMillis;
53
67
  this.emit('change', 'acquireTimeoutMillis', this._acquireTimeoutMillis);
54
68
  }
69
+ /**
70
+ * If `true`, idle resources are handed out first-in-first-out; if
71
+ * `false`, last-in-first-out.
72
+ *
73
+ * @defaultValue `true`
74
+ */
55
75
  get fifo() {
56
76
  return this._fifo;
57
77
  }
@@ -60,52 +80,95 @@ export class PoolOptions extends EventEmitter {
60
80
  this._fifo = !!val;
61
81
  this.emit('change', 'fifo', this.fifo);
62
82
  }
83
+ /** @defaultValue `30000` (milliseconds) */
63
84
  get idleTimeoutMillis() {
64
85
  return this._idleTimeoutMillis;
65
86
  }
87
+ /** Negative values reset to the default instead of being applied. */
66
88
  set idleTimeoutMillis(val) {
67
89
  this._idleTimeoutMillis = val >= 0 ? val : defaultValues.idleTimeoutMillis;
68
90
  this.emit('change', 'idleTimeoutMillis', this._idleTimeoutMillis);
69
91
  }
92
+ /** @defaultValue `1000` (milliseconds) */
70
93
  get houseKeepInterval() {
71
94
  return this._houseKeepInterval;
72
95
  }
96
+ /**
97
+ * Negative values reset to the default instead of being applied.
98
+ *
99
+ * @remarks Setting this restarts the housekeeper timer on the running
100
+ * `Pool` with the new interval.
101
+ */
73
102
  set houseKeepInterval(val) {
74
103
  this._houseKeepInterval = val >= 0 ? val : defaultValues.houseKeepInterval;
75
104
  this.emit('change', 'houseKeepInterval', this._houseKeepInterval);
76
105
  }
106
+ /** @defaultValue `0` */
77
107
  get min() {
78
108
  return this._min;
79
109
  }
110
+ /**
111
+ * Negative values reset to the default instead of being applied.
112
+ *
113
+ * @remarks Raising this above the current `max` also raises `max` to
114
+ * match, since `min` can never exceed `max`. On a running `Pool`, raising
115
+ * `min` triggers creating resources to satisfy the new minimum.
116
+ */
80
117
  set min(val) {
81
118
  this._min = val >= 0 ? val : defaultValues.min;
82
119
  if (this._min > this._max)
83
120
  this._max = this._min;
84
121
  this.emit('change', 'min', this._min);
85
122
  }
123
+ /** @defaultValue `0` */
86
124
  get minIdle() {
87
125
  return this._minIdle;
88
126
  }
127
+ /**
128
+ * Negative values reset to the default instead of being applied.
129
+ *
130
+ * @remarks On a running `Pool`, raising this triggers creating resources
131
+ * to satisfy the new minimum idle count.
132
+ */
89
133
  set minIdle(val) {
90
134
  this._minIdle = val >= 0 ? val : defaultValues.minIdle;
91
135
  this.emit('change', 'minIdle', this.minIdle);
92
136
  }
137
+ /** @defaultValue `10` */
93
138
  get max() {
94
139
  return this._max;
95
140
  }
141
+ /**
142
+ * Negative values reset to the default instead of being applied; `0` or
143
+ * below the current `min` is clamped up to at least `1`/`min`.
144
+ *
145
+ * @remarks Lowering this below the current `min` also lowers `min` to
146
+ * match, since `min` can never exceed `max`.
147
+ */
96
148
  set max(val) {
97
149
  this._max = val >= 0 ? Math.max(val, 1) : defaultValues.max;
98
150
  if (this._min > this._max)
99
151
  this._min = this._max;
100
152
  this.emit('change', 'max', this._max);
101
153
  }
154
+ /** @defaultValue `1000` */
102
155
  get maxQueue() {
103
156
  return this._maxQueue;
104
157
  }
158
+ /**
159
+ * Negative values reset to the default instead of being applied;
160
+ * otherwise clamped up to at least `1`.
161
+ */
105
162
  set maxQueue(val) {
106
163
  this._maxQueue = val >= 0 ? Math.max(val, 1) : defaultValues.maxQueue;
107
164
  this.emit('change', 'maxQueue', this._maxQueue);
108
165
  }
166
+ /**
167
+ * If `true`, a resource is validated via `factory.validate()` before
168
+ * being handed out (when the factory provides one).
169
+ *
170
+ * @defaultValue `true`
171
+ */
109
172
  get validation() {
110
173
  return this._validation;
111
174
  }
@@ -114,12 +177,27 @@ export class PoolOptions extends EventEmitter {
114
177
  this._validation = !!val;
115
178
  this.emit('change', 'validation', this._validation);
116
179
  }
180
+ /**
181
+ * Copies every recognized option from `values` onto this instance,
182
+ * emitting a `'change'` event per option (same as assigning each
183
+ * individually). Unknown keys are silently ignored.
184
+ *
185
+ * @param values - A plain `PoolConfiguration` object, or another
186
+ * `PoolOptions` instance to copy settings from (e.g. to clone one pool's
187
+ * configuration onto another).
188
+ */
117
189
  assign(values) {
118
190
  const proto = Object.getPrototypeOf(this);
119
- for (const k of Object.keys(values)) {
191
+ // A PoolOptions instance only owns underscored private fields, so its
192
+ // public getter/setter names must be read from the canonical key list.
193
+ const keys = values instanceof PoolOptions
194
+ ? Object.keys(defaultValues)
195
+ : Object.keys(values);
196
+ for (const k of keys) {
120
197
  const desc = Object.getOwnPropertyDescriptor(proto, k);
121
- if (desc && desc.set)
122
- this[k] = values[k];
198
+ const val = values[k];
199
+ if (desc && desc.set && val !== undefined)
200
+ this[k] = val;
123
201
  }
124
202
  }
125
203
  }
package/pool-request.d.ts CHANGED
@@ -1,11 +1,26 @@
1
1
  import type { Pool } from './pool.js';
2
2
  import type { Callback } from './types.js';
3
+ /**
4
+ * Internal bookkeeping for one pending `acquire()` call while it's queued
5
+ * or being processed. Not part of the public API.
6
+ */
3
7
  export declare class PoolRequest {
8
+ /** `Date.now()` when this request was created - used as `error` event's `requestTime`. */
4
9
  created: number;
10
+ /** The caller's callback (or a resolved-Promise wrapper), invoked with the acquired resource or an error. */
5
11
  callback: Callback;
6
12
  options?: any;
13
+ /** The pending `acquireTimeoutMillis` timer, if one is running. */
7
14
  timeoutHandle: any;
15
+ /** Set once `acquireTimeoutMillis` has elapsed for this request. */
8
16
  timedOut: boolean;
17
+ /**
18
+ * Called when `acquireTimeoutMillis` elapses, before `request-timeout` is
19
+ * emitted and the callback is rejected. The pool uses it to drop the
20
+ * request from its queue, so `pending` no longer counts it.
21
+ */
22
+ onTimeout?: () => void;
9
23
  constructor(pool: Pool, callback?: Callback, options?: any);
24
+ /** Clears the pending timeout timer, if any (does not affect `timedOut`). */
10
25
  stopTimout(): void;
11
26
  }
package/pool-request.js CHANGED
@@ -1,10 +1,24 @@
1
1
  function noop() { }
2
+ /**
3
+ * Internal bookkeeping for one pending `acquire()` call while it's queued
4
+ * or being processed. Not part of the public API.
5
+ */
2
6
  export class PoolRequest {
7
+ /** `Date.now()` when this request was created - used as `error` event's `requestTime`. */
3
8
  created;
9
+ /** The caller's callback (or a resolved-Promise wrapper), invoked with the acquired resource or an error. */
4
10
  callback;
5
11
  options;
12
+ /** The pending `acquireTimeoutMillis` timer, if one is running. */
6
13
  timeoutHandle;
14
+ /** Set once `acquireTimeoutMillis` has elapsed for this request. */
7
15
  timedOut = false;
16
+ /**
17
+ * Called when `acquireTimeoutMillis` elapses, before `request-timeout` is
18
+ * emitted and the callback is rejected. The pool uses it to drop the
19
+ * request from its queue, so `pending` no longer counts it.
20
+ */
21
+ onTimeout;
8
22
  constructor(pool, callback, options) {
9
23
  this.created = Date.now();
10
24
  this.callback = callback || noop;
@@ -13,11 +27,14 @@ export class PoolRequest {
13
27
  this.timeoutHandle = setTimeout(() => {
14
28
  this.timedOut = true;
15
29
  this.stopTimout();
30
+ if (this.onTimeout)
31
+ this.onTimeout();
16
32
  pool.emit('request-timeout');
17
33
  this.callback(new Error('Request timed out'));
18
34
  }, pool.options.acquireTimeoutMillis);
19
35
  }
20
36
  }
37
+ /** Clears the pending timeout timer, if any (does not affect `timedOut`). */
21
38
  stopTimout() {
22
39
  if (this.timeoutHandle)
23
40
  clearTimeout(this.timeoutHandle);
package/pool.d.ts CHANGED
@@ -2,6 +2,12 @@ import { EventEmitter } from 'events';
2
2
  import { PoolState } from './constants.js';
3
3
  import { PoolOptions } from './pool-options.js';
4
4
  import type { Callback, PoolConfiguration, PoolFactory } from './types.js';
5
+ /**
6
+ * A generic resource pool: acquires, reuses, and (when idle too long or on
7
+ * validation failure) discards resources created by a `PoolFactory`.
8
+ *
9
+ * @typeParam T - The resource type this pool manages (e.g. a DB connection).
10
+ */
5
11
  export declare class Pool<T = any> extends EventEmitter {
6
12
  private readonly _options;
7
13
  private readonly _factory;
@@ -14,6 +20,12 @@ export declare class Pool<T = any> extends EventEmitter {
14
20
  private _state;
15
21
  private _houseKeepTimer;
16
22
  private _closeWaitTimer;
23
+ /**
24
+ * @param factory - Creates, destroys, and (optionally) resets/validates resources.
25
+ * @param config - Initial options; every option can also be changed later via `pool.options`.
26
+ * @throws \{@link TypeError\} If `factory` isn't an object, or `create`/`destroy` aren't
27
+ * functions, or `reset`/`validate` are present but aren't functions.
28
+ */
17
29
  constructor(factory: PoolFactory<T>, config?: PoolConfiguration);
18
30
  /**
19
31
  * Returns Pool options
@@ -47,59 +59,162 @@ export declare class Pool<T = any> extends EventEmitter {
47
59
  /**
48
60
  * Starts the pool and begins creating of resources, starts the housekeeper and any other internal logic.
49
61
  * Note: This method is not needed to be called. Pool instance will automatically be started when acquire() method is called
62
+ *
63
+ * @throws \{@link Error\} If the pool is currently `CLOSING`.
50
64
  */
51
65
  start(): void;
52
66
  /**
53
- * Shuts down the pool and destroys all resources.
67
+ * Shuts down the pool and destroys all resources. Any `acquire()` call
68
+ * still queued at the time this is invoked is rejected with an error.
69
+ *
70
+ * @returns A `Promise` that resolves once fully closed (only when no `callback` is given).
71
+ */
72
+ close(): Promise<void>;
73
+ /** @param callback - Called once the pool has fully closed. */
74
+ close(callback: Callback): void;
75
+ /**
76
+ * @param terminateWait - How long, in milliseconds, to wait for acquired
77
+ * resources to be released before forcibly destroying them anyway. Waits
78
+ * indefinitely if omitted.
79
+ * @param callback - Called once the pool has fully closed; if omitted, returns a `Promise` instead.
54
80
  */
55
- close(): void;
56
- close(callback?: Callback): void;
57
81
  close(terminateWait?: number, callback?: Callback): void;
82
+ /**
83
+ * @param force - `true` is shorthand for `terminateWait: 0` (destroy
84
+ * acquired resources immediately, without waiting); `false` is shorthand
85
+ * for waiting indefinitely.
86
+ * @param callback - Called once the pool has fully closed; if omitted, returns a `Promise` instead.
87
+ */
58
88
  close(force?: boolean, callback?: Callback): void;
89
+ /** Promise-returning equivalent of `close()` - see it for what each overload does. */
59
90
  closeAsync(): Promise<void>;
60
91
  closeAsync(terminateWait?: number): Promise<void>;
61
92
  closeAsync(force?: boolean): Promise<void>;
62
93
  /**
63
- * Acquires `resource` from the pool or create a new one
94
+ * Acquires a resource from the pool, or creates a new one if none is idle.
95
+ * Starts the pool (see `start()`) if it hasn't been already.
96
+ *
97
+ * @returns A `Promise` resolving to the resource (only when no `callback` is given).
98
+ * @throws \{@link Error\} (via the `Promise` rejection or `callback`) If the pool is
99
+ * `CLOSING`, if `maxQueue` is exceeded, or if resource creation ultimately fails.
64
100
  */
65
101
  acquire(): Promise<T>;
102
+ /** @param callback - Called with the acquired resource, or an error. */
66
103
  acquire(callback: Callback): void;
67
104
  /**
68
- * Releases an allocated `resource` and let it back to pool.
105
+ * Releases a previously-acquired `resource` back to the pool so it can be
106
+ * reused (running `factory.reset()` first, if provided).
107
+ *
108
+ * @param resource - A previously acquired resource. A no-op (aside from invoking
109
+ * `callback`) if it isn't currently acquired or isn't in this pool.
110
+ * @param callback - Called once released (and `reset()`, if any, has finished).
111
+ * @remarks Returns immediately (`undefined`) regardless of `callback` -
112
+ * it does not wait for `reset()` to finish. Use `releaseAsync()` (or pass
113
+ * `callback`) to know when the release has actually completed.
69
114
  */
70
115
  release(resource: T, callback?: Callback): void;
71
116
  /**
72
- * Async version of release().
117
+ * Promise-returning equivalent of `release()`.
118
+ *
119
+ * @param resource - A previously acquired resource.
120
+ * @returns A `Promise` that resolves once released (and `reset()`, if any, has finished).
73
121
  */
74
122
  releaseAsync(resource: T): Promise<void>;
75
123
  /**
76
- * Releases, destroys and removes any `resource` from `Pool`.
124
+ * Releases, destroys, and removes a `resource` from the pool entirely -
125
+ * it will not be reused (running `factory.destroy()`).
126
+ *
127
+ * @param resource - A previously acquired (or idle) resource. A no-op
128
+ * (aside from invoking `callback`) if it isn't in this pool.
129
+ * @param callback - Called once destroyed (or on `factory.destroy()` failure).
77
130
  */
78
131
  destroy(resource: T, callback?: Callback): any;
79
132
  /**
80
- * Async version of destroy().
133
+ * Promise-returning equivalent of `destroy()`.
134
+ *
135
+ * @param resource - A previously acquired (or idle) resource.
136
+ * @returns A `Promise` that resolves once destroyed.
81
137
  */
82
138
  destroyAsync(resource: T): Promise<void>;
83
139
  /**
84
140
  * Returns if a `resource` has been acquired from the pool and not yet released or destroyed.
141
+ *
142
+ * @param resource - The resource to check.
85
143
  */
86
144
  isAcquired(resource: T): boolean;
87
145
  /**
88
- * Returns if the pool contains a `resource`
146
+ * Returns if the pool contains a `resource` - acquired, idle, or being
147
+ * validated (not yet destroyed).
148
+ *
149
+ * @param resource - The resource to check.
89
150
  */
90
151
  includes(resource: T): boolean;
152
+ /**
153
+ * Serves the next queued `acquire()` request, if any and if capacity
154
+ * allows: from an idle resource (validating it first if enabled), or by
155
+ * creating a new one. Called after anything that could free up capacity
156
+ * or add a request (release, destroy, acquire, options change).
157
+ */
91
158
  private _processNextRequest;
159
+ /**
160
+ * Overrides `EventEmitter.emit()`: identical, except an error thrown by a
161
+ * listener is swallowed instead of propagating out of `emit()` - a
162
+ * misbehaving listener on, say, `'acquire'` can't take down the internal
163
+ * code path that just emitted it.
164
+ *
165
+ * @param event - Event name. See the class-level events list in `docs/API.md`
166
+ * (`start`, `closing`, `close`, `terminate`, `create`, `error`, `acquire`,
167
+ * `return`, `destroy`, `destroy-error`, `validate-error`, `request-timeout`).
168
+ * @param args - Arguments passed to each listener.
169
+ * @returns `true` if the event had listeners, `false` otherwise (same as
170
+ * `EventEmitter.emit()`); also `true` if a listener threw.
171
+ */
92
172
  emit(event: string | symbol, ...args: any[]): boolean;
93
173
  /**
94
- * Creates new resource
174
+ * Creates a new resource via `factory.create()`, retrying on failure up
175
+ * to `acquireMaxRetries` times (waiting `acquireRetryWait` between
176
+ * attempts), unless `request` has already timed out or the factory threw
177
+ * an `AbortError`. On success, adds the resource to the pool as idle.
178
+ *
179
+ * @param request - The acquire request this creation is for, if any (`_ensureMin()`
180
+ * creates resources with no associated request).
181
+ * @param callback - Called with the new `ResourceItem`, or the final error.
95
182
  */
96
183
  private _createResource;
184
+ /**
185
+ * (Re)starts the housekeeper timer at interval `ms`, or leaves it stopped
186
+ * if the pool isn't `STARTED`/`CLOSING`. Called on `start()`, whenever
187
+ * `houseKeepInterval` changes, and (with a short fixed interval) while
188
+ * closing.
189
+ */
97
190
  private _setHouseKeep;
191
+ /**
192
+ * One housekeeping pass: destroys idle resources past `idleTimeoutMillis`
193
+ * (as long as doing so doesn't drop below `min`/`minIdle`), or - while
194
+ * `CLOSING` - destroys every idle resource unconditionally and, once no
195
+ * resources remain at all, finishes the transition to `CLOSED`.
196
+ */
98
197
  private _houseKeep;
198
+ /**
199
+ * Schedules (via `process.nextTick`) creating however many resources are
200
+ * needed to satisfy `min`/`minIdle`, accounting for creations already in
201
+ * flight. Called after start, after every successful acquire, and
202
+ * whenever `min`/`minIdle` change.
203
+ */
99
204
  private _ensureMin;
205
+ /** Moves `item` into the acquired list, detaching it from wherever it was first. */
100
206
  private _itemSetAcquired;
207
+ /** Removes `item` from whichever tracked list (idle/acquired) its current `state` puts it in. */
101
208
  private _itemDetach;
209
+ /**
210
+ * Runs `factory.reset()` (if the item was acquired and a `reset` is
211
+ * provided), then moves `item` to the idle list (FIFO or LIFO end per
212
+ * `fifo`) and processes the next queued request. Destroys the item
213
+ * instead if `reset()` fails.
214
+ */
102
215
  private _itemSetIdle;
216
+ /** Detaches `item`, runs `factory.destroy()`, and removes it from the pool entirely. */
103
217
  private _itemDestroy;
218
+ /** Runs `factory.validate()` on `item` before it's handed out to a caller. */
104
219
  private _itemValidate;
105
220
  }