resource-pools
Purpose
This Javascript module introduces a ResourcePool class as an abstraction to manage objects that can be pooled and allocated on demand.
Usage
Once your resource class is compatible with the pool interface (see the Pooled resources paragraph below) you provide a new pool with some basic settings:
const resources = config; // create the pool object
...and simply request the pool to allocate a resource wherever it is needed (you always get a promise in return):
resources;// orobj = await resources;
Config parameters
A config object has some required and optional parameters:
const config = // required parameters:
Log function
The arguments of log function are logLevel and the message. Logging levels are:
- 0: errors
- 1: resource assign / release messages
- 2: internal pool events
Example log function
{ /* errors & logs to console */ iflogLevel < 1 console; else console; }
Timeouts
If any of the timeouts is not set explicitly, its internal default value is used:
- requestTimeout: 1 minute
- busyTimeout: 1 minute
- idleTimeout: 24 hours
NB: busyTimeout should be greater than it takes a new resource to get ready for being allocated, otherwise new resources will be continuously created and closed until the allocation request timeout is reached and the request id finally rejected.
Pooled resources
Pooled objects must implement the following interface:
- emit a specific event when it is ready to be allocated for the next task (referenced by a readyEventSym symbol);
- emit a specific event on error, when the resource is no longer capable of operating and should be deleted from the pool (referenced by an errorEventSym symbol);
- have a method to properly be shutdown by the pool object (referenced by a closeMethodSym symbol).
Example 1, declaration of a pooled 'tedious' connection:
This implementation is available as a resource-pools-connection package
const Connection = ;const readyEventSym errorEventSym closeMethodSym = ; { super...args; this; this; this; } { super; request; }ConnectionResourceprototypecloseMethodSym = { this };
Example 2, declaration of a pooled worker:
This implementation is available as a resource-pools-worker package
const Worker = ;const readyEventSym errorEventSym closeMethodSym = ; { super...args; this; this; this; }WorkerResourceprototypecloseMethodSym = { this };