For an overview, installation, and a quick example, see the README.
lightning-pool exports both a createPool() factory function and the Pool class itself. Either can be used to
instantiate a pool.
import { createPool } from 'lightning-pool';
const pool = createPool(factory, options);import { Pool } from 'lightning-pool';
const pool = new Pool(factory, options);Any object with the following properties:
create(info?: {tries: number, maxRetries: number}): Called when thePoolneeds a new resource. May return the resource directly or aPromisethat resolves to it.infois populated by thePoolitself on retry attempts (seeacquireMaxRetries) - it is not something a caller ofacquire()passes in.destroy(resource): Called when thePoolwants to destroy aresource(whereresourceis whateverfactory.createreturned). May returnvoidor aPromise<void>.reset(resource)(optional): Called before aresourceis returned to the idle pool. May returnvoidor aPromise<void>. If it throws or rejects, thePooldestroys and removes the resource instead of returning it to the idle pool.validate(resource)(optional): Called to validate aresourcebefore handing it out (see thevalidationoption). May returnvoid, aboolean, or aPromiseof either. If it throws, rejects, or resolves tofalse, thePooldestroys and removes the resource and tries the next one instead.
acquireMaxRetries: Maximum number of times thePoolwill retry creating a resource before giving up and returning the error to the caller. (Default0- fail on the first error, no retries)acquireRetryWait: Time in milliseconds thePoolwaits between retry attempts. (Default2000)acquireTimeoutMillis: Time in milliseconds anacquire()call will wait for a resource before failing with a timeout error. (Default0- no timeout)fifo: Iftrue, idle resources are handed out in first-in-first-out order (the longest-idle resource first). Iffalse, last-in-first-out (the most recently released resource first). (Defaulttrue)idleTimeoutMillis: The minimum amount of time in milliseconds a resource may sit idle in thePoolbefore the housekeeper is allowed to destroy it (subject tomin/minIdle). (Default30000)houseKeepInterval: Time in milliseconds between housekeeping passes, which enforceidleTimeoutMillisandmin/minIdle. (Default1000)min: Minimum number of resources thePooltries to keep alive in total. (Default0)minIdle: Minimum number of resources thePooltries to keep idle (immediately available). (Default0)max: Maximum number of resources thePoolwill create. (Default10)maxQueue: Maximum number ofacquire()requests that may be queued/pending at once; further requests fail immediately with an error instead of waiting. (Default1000)validation: Iftrue, thePoolcallsfactory.validate()on a resource before handing it out (when the factory provides one). Iffalse,validate()is never called. (Defaulttrue)
All options can also be read/written after construction via pool.options.<name> - see Properties.
Acquires a resource from the Pool, or creates a new one if none is idle.
acquire(): Promise<T>;
acquire(callback: Callback): void;const resource = await pool.acquire();
// or, callback style:
pool.acquire((err, resource) => {
if (err) {
/* handle error */
}
});Releases an acquired resource back to the Pool so it can be reused.
release(resource: T, callback?: Callback): void;
releaseAsync(resource: T): Promise<void>;release() always returns immediately (undefined) - it does not wait for factory.reset() (if any) to finish. Use
releaseAsync() (or pass a callback) if you need to know when the release has actually completed.
pool.release(resource);
// or, to wait for completion:
await pool.releaseAsync(resource);Releases, destroys, and removes a resource from the Pool entirely (it will not be reused).
destroy(resource: T, callback?: Callback): void;
destroyAsync(resource: T): Promise<void>;pool.destroy(resource);
// or, to wait for completion:
await pool.destroyAsync(resource);Returns whether a resource is currently acquired (not yet released or destroyed).
isAcquired(resource: T): boolean;Returns whether a resource belongs to this Pool (acquired, idle, or otherwise tracked - not yet destroyed).
includes(resource: T): boolean;Starts the Pool: begins creating resources to satisfy min/minIdle and starts the housekeeper.
Note: calling this explicitly is optional - the Pool starts itself automatically the first time acquire() is
called.
start(): void;Shuts down the Pool and destroys all of its resources. Any acquire() call still queued at the time close() is
invoked is rejected with an error.
close(): Promise<void>;
close(callback: Callback): void;
close(terminateWait: number, callback?: Callback): void;
close(force: boolean, callback?: Callback): void;
closeAsync(): Promise<void>;
closeAsync(terminateWait?: number): Promise<void>;
closeAsync(force?: boolean): Promise<void>;terminateWait(number): How long, in milliseconds, to wait for acquired resources to be released before forcibly destroying them anyway. Omit (or pass no argument) to wait indefinitely.force(boolean):trueis shorthand forterminateWait: 0(destroy acquired resources immediately, without waiting);falseis shorthand for waiting indefinitely.callback: If provided, it is called once thePoolhas fully closed. If omitted,close()/closeAsync()returns aPromiseinstead.
await pool.close(5000); // wait up to 5s for active resources, then force-close
await pool.close(0); // close immediately, destroying acquired resources without waiting
await pool.close(); // wait indefinitely for active resources to be releasedacquired(number): Number of resources currently acquired.available(number): Number of idle resources.creating(number): Number of resources currently being created.pending(number): Number ofacquire()requests currently queued/being processed.size(number): Total number of resources tracked by thePool(acquired + idle + being created).state(PoolState): Current lifecycle state of thePool- seePoolStatebelow.options(PoolOptions): A live, mutable options object - every option above is a get/set property on it, and changes take effect immediately (e.g.pool.options.max = 20).
Pool extends EventEmitter and emits the following events:
start: ThePoolhas started.closing: ThePoolhas begun shutting down (emitted at the start ofclose()).close: ThePoolhas finished shutting down and all resources have been destroyed.terminate: Emitted whenclose()'sterminateWaitelapses and acquired resources are force-released instead of waited for further.create(resource): A new resource was created and added to thePool.error(err, info):factory.create()failed.infois{ requestTime, tries, maxRetries }.acquire(resource): A resource was handed out to a caller.return(resource): A previously-acquired resource was released back to the idle pool.destroy(resource): A resource was destroyed and removed from thePool.destroy-error(err, resource):factory.destroy()failed while destroying a resource.validate-error(err, resource):factory.validate()failed (or returnedfalse) while validating a resource on borrow; the resource is destroyed and thePooltries the next one.request-timeout: Anacquire()call timed out (seeacquireTimeoutMillis).
pool.on('acquire', resource => {
/* ... */
});
pool.on('destroy-error', (err, resource) => {
/* log it */
});The state property (and the PoolState enum exported from the package):
IDLE(0): ThePoolhas not been started yet.STARTED(1): ThePoolis running.CLOSING(2): Shutdown is in progress.CLOSED(3): ThePoolhas fully shut down. Callingstart()again brings it back toSTARTED.
Internal per-resource state, also exported as an enum (mostly useful when inspecting events or writing tests):
IDLE(0): The resource is idle and available foracquire().ACQUIRED(1): The resource is currently acquired by a caller.VALIDATION(2): The resource is being validated (see thevalidationoption) before being handed out.