1 # [API](https://poolifier.github.io/poolifier/)
6 - [`pool = new FixedThreadPool/FixedClusterPool(numberOfThreads/numberOfWorkers, filePath, opts)`](#pool--new-fixedthreadpoolfixedclusterpoolnumberofthreadsnumberofworkers-filepath-opts)
7 - [`pool = new DynamicThreadPool/DynamicClusterPool(min, max, filePath, opts)`](#pool--new-dynamicthreadpooldynamicclusterpoolmin-max-filepath-opts)
8 - [`pool.execute(data, name, transferList)`](#poolexecutedata-name-transferlist)
9 - [`pool.mapExecute(data, name, transferList)`](#poolmapexecutedata-name-transferlist)
10 - [`pool.start()`](#poolstart)
11 - [`pool.destroy()`](#pooldestroy)
12 - [`pool.hasTaskFunction(name)`](#poolhastaskfunctionname)
13 - [`pool.addTaskFunction(name, fn)`](#pooladdtaskfunctionname-fn)
14 - [`pool.removeTaskFunction(name)`](#poolremovetaskfunctionname)
15 - [`pool.listTaskFunctionsProperties()`](#poollisttaskfunctionsproperties)
16 - [`pool.setDefaultTaskFunction(name)`](#poolsetdefaulttaskfunctionname)
17 - [Pool options](#pool-options)
19 - [`class YourWorker extends ThreadWorker/ClusterWorker`](#class-yourworker-extends-threadworkerclusterworker)
20 - [`YourWorker.hasTaskFunction(name)`](#yourworkerhastaskfunctionname)
21 - [`YourWorker.addTaskFunction(name, fn)`](#yourworkeraddtaskfunctionname-fn)
22 - [`YourWorker.removeTaskFunction(name)`](#yourworkerremovetaskfunctionname)
23 - [`YourWorker.listTaskFunctionsProperties()`](#yourworkerlisttaskfunctionsproperties)
24 - [`YourWorker.setDefaultTaskFunction(name)`](#yourworkersetdefaulttaskfunctionname)
28 ### `pool = new FixedThreadPool/FixedClusterPool(numberOfThreads/numberOfWorkers, filePath, opts)`
30 `numberOfThreads/numberOfWorkers` (mandatory) Number of workers for this pool.
31 `filePath` (mandatory) Path to a file with a worker implementation.
32 `opts` (optional) An object with the pool options properties described below.
34 ### `pool = new DynamicThreadPool/DynamicClusterPool(min, max, filePath, opts)`
36 `min` (mandatory) Same as _FixedThreadPool_/_FixedClusterPool_ numberOfThreads/numberOfWorkers, this number of workers will be always active.
37 `max` (mandatory) Max number of workers that this pool can contain, the newly created workers will die after a threshold (default is 1 minute, you can override it in your worker implementation).
38 `filePath` (mandatory) Path to a file with a worker implementation.
39 `opts` (optional) An object with the pool options properties described below.
41 ### `pool.execute(data, name, transferList)`
43 `data` (optional) An object that you want to pass to your worker task function implementation.
44 `name` (optional) A string with the task function name that you want to execute on the worker. Default: `'default'`
45 `transferList` (optional) An array of transferable objects that you want to transfer to your [`ThreadWorker`](#class-yourworker-extends-threadworkerclusterworker) worker implementation.
47 This method is available on both pool implementations and returns a promise with the task function execution response.
49 ### `pool.mapExecute(data, name, transferList)`
51 `data` Iterable objects that you want to pass to your worker task function implementation.
52 `name` (optional) A string with the task function name that you want to execute on the worker. Default: `'default'`
53 `transferList` (optional) An array of transferable objects that you want to transfer to your [`ThreadWorker`](#class-yourworker-extends-threadworkerclusterworker) worker implementation.
55 This method is available on both pool implementations and returns a promise with the task function execution responses array.
59 This method is available on both pool implementations and will start the minimum number of workers.
63 This method is available on both pool implementations and will call the terminate method on each worker.
65 ### `pool.hasTaskFunction(name)`
67 `name` (mandatory) The task function name.
69 This method is available on both pool implementations and returns a boolean.
71 ### `pool.addTaskFunction(name, fn)`
73 `name` (mandatory) The task function name.
74 `fn` (mandatory) The task function `(data?: Data) => Response | Promise<Response>` or task function object `{ taskFunction: (data?: Data) => Response | Promise<Response>, priority?: number, strategy?: WorkerChoiceStrategy }`. Priority range is the same as Unix nice levels.
76 This method is available on both pool implementations and returns a boolean promise.
78 ### `pool.removeTaskFunction(name)`
80 `name` (mandatory) The task function name.
82 This method is available on both pool implementations and returns a boolean promise.
84 ### `pool.listTaskFunctionsProperties()`
86 This method is available on both pool implementations and returns an array of the task function properties.
88 ### `pool.setDefaultTaskFunction(name)`
90 `name` (mandatory) The task function name.
92 This method is available on both pool implementations and returns a boolean promise.
96 An object with these properties:
98 - `onlineHandler` (optional) - A function that will listen for online event on each worker.
100 - `messageHandler` (optional) - A function that will listen for message event on each worker.
102 - `errorHandler` (optional) - A function that will listen for error event on each worker.
104 - `exitHandler` (optional) - A function that will listen for exit event on each worker.
107 - `workerChoiceStrategy` (optional) - The default worker choice strategy to use in this pool:
109 - `WorkerChoiceStrategies.ROUND_ROBIN`: Submit tasks to worker in a round robin fashion
110 - `WorkerChoiceStrategies.LEAST_USED`: Submit tasks to the worker with the minimum number of executing and queued tasks
111 - `WorkerChoiceStrategies.LEAST_BUSY`: Submit tasks to the worker with the minimum tasks execution time
112 - `WorkerChoiceStrategies.LEAST_ELU`: Submit tasks to the worker with the minimum event loop utilization (ELU)
113 - `WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN`: Submit tasks to worker by using a [weighted round robin scheduling algorithm](./worker-choice-strategies.md#weighted-round-robin) based on tasks execution time
114 - `WorkerChoiceStrategies.INTERLEAVED_WEIGHTED_ROUND_ROBIN`: Submit tasks to worker by using an [interleaved weighted round robin scheduling algorithm](./worker-choice-strategies.md#interleaved-weighted-round-robin-experimental) based on tasks execution time (experimental)
115 - `WorkerChoiceStrategies.FAIR_SHARE`: Submit tasks to worker by using a [fair share scheduling algorithm](./worker-choice-strategies.md#fair-share) based on tasks execution time (the default) or ELU active time
117 `WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN`, `WorkerChoiceStrategies.INTERLEAVED_WEIGHTED_ROUND_ROBIN` and `WorkerChoiceStrategies.FAIR_SHARE` strategies are targeted to heavy and long tasks.
118 Default: `WorkerChoiceStrategies.ROUND_ROBIN`
120 - `workerChoiceStrategyOptions` (optional) - The worker choice strategy options object to use in this pool.
123 - `measurement` (optional) - The measurement to use in worker choice strategies: `runTime`, `waitTime` or `elu`.
124 - `runTime` (optional) - Use the tasks [simple moving median](./worker-choice-strategies.md#simple-moving-median) runtime instead of the tasks simple moving average runtime in worker choice strategies.
125 - `waitTime` (optional) - Use the tasks [simple moving median](./worker-choice-strategies.md#simple-moving-median) wait time instead of the tasks simple moving average wait time in worker choice strategies.
126 - `elu` (optional) - Use the tasks [simple moving median](./worker-choice-strategies.md#simple-moving-median) ELU instead of the tasks simple moving average ELU in worker choice strategies.
127 - `weights` (optional) - The worker weights to use in weighted round robin worker choice strategies: `Record<number, number>`.
129 Default: `{ runTime: { median: false }, waitTime: { median: false }, elu: { median: false } }`
131 - `startWorkers` (optional) - Start the minimum number of workers at pool initialization.
133 - `restartWorkerOnError` (optional) - Restart worker on uncaught error in this pool.
135 - `enableEvents` (optional) - Pool events integrated with async resource emission enablement.
137 - `enableTasksQueue` (optional) - Tasks queue per worker enablement in this pool.
140 - `tasksQueueOptions` (optional) - The worker tasks queue options object to use in this pool.
143 - `size` (optional) - The maximum number of tasks that can be queued on a worker before flagging it as back pressured. It must be a positive integer.
144 - `concurrency` (optional) - The maximum number of tasks that can be executed concurrently on a worker. It must be a positive integer.
145 - `taskStealing` (optional) - Task stealing enablement on idle.
146 - `tasksStealingOnBackPressure` (optional) - Tasks stealing enablement under back pressure.
147 - `tasksFinishedTimeout` (optional) - Queued tasks finished timeout in milliseconds at worker termination.
149 Default: `{ size: (pool maximum size)^2, concurrency: 1, taskStealing: true, tasksStealingOnBackPressure: false, tasksFinishedTimeout: 2000 }`
151 - `workerOptions` (optional) - An object with the worker options to pass to worker. See [worker_threads](https://nodejs.org/api/worker_threads.html#worker_threads_new_worker_filename_options) for more details.
153 - `env` (optional) - An object with the environment variables to pass to worker. See [cluster](https://nodejs.org/api/cluster.html#cluster_cluster_fork_env) for more details.
155 - `settings` (optional) - An object with the cluster settings. See [cluster](https://nodejs.org/api/cluster.html#cluster_cluster_settings) for more details.
159 ### `class YourWorker extends ThreadWorker/ClusterWorker`
161 `taskFunctions` (mandatory) The task function or task functions object `Record<string, (data?: Data) => Response | Promise<Response> | { taskFunction: (data?: Data) => Response | Promise<Response>, priority?: number, strategy?: WorkerChoiceStrategy }>` that you want to execute on the worker. Priority range is the same as Unix nice levels.
162 `opts` (optional) An object with these properties:
164 - `killBehavior` (optional) - Dictates if your worker will be deleted in case a task is active on it.
165 **KillBehaviors.SOFT**: If `currentTime - lastActiveTime` is greater than `maxInactiveTime` but the worker is stealing tasks or a task is executing or queued, then the worker **won't** be deleted.
166 **KillBehaviors.HARD**: If `currentTime - lastActiveTime` is greater than `maxInactiveTime` but the worker is stealing tasks or a task is executing or queued, then the worker will be deleted.
167 This option only apply to the newly created workers.
168 Default: `KillBehaviors.SOFT`
170 - `maxInactiveTime` (optional) - Maximum waiting time in milliseconds for tasks on newly created workers. After this time newly created workers will die. It must be a positive integer greater or equal than 5.
171 The last active time of your worker will be updated when it terminates a task.
172 If `killBehavior` is set to `KillBehaviors.HARD` this value represents also the timeout for the tasks that you submit to the pool, when this timeout expires your tasks is interrupted before completion and removed. The worker is killed if is not part of the minimum size of the pool.
173 If `killBehavior` is set to `KillBehaviors.SOFT` your tasks have no timeout and your workers will not be terminated until your task is completed.
176 - `killHandler` (optional) - A function that will be called when a worker is killed.
179 #### `YourWorker.hasTaskFunction(name)`
181 `name` (mandatory) The task function name.
183 This method is available on both worker implementations and returns `{ status: boolean, error?: Error }`.
185 #### `YourWorker.addTaskFunction(name, fn)`
187 `name` (mandatory) The task function name.
188 `fn` (mandatory) The task function `(data?: Data) => Response | Promise<Response>` or task function object `{ taskFunction: (data?: Data) => Response | Promise<Response>, priority?: number, strategy?: WorkerChoiceStrategy }`. Priority range is the same as Unix nice levels.
190 This method is available on both worker implementations and returns `{ status: boolean, error?: Error }`.
192 #### `YourWorker.removeTaskFunction(name)`
194 `name` (mandatory) The task function name.
196 This method is available on both worker implementations and returns `{ status: boolean, error?: Error }`.
198 #### `YourWorker.listTaskFunctionsProperties()`
200 This method is available on both worker implementations and returns an array of the task function properties.
202 #### `YourWorker.setDefaultTaskFunction(name)`
204 `name` (mandatory) The task function name.
206 This method is available on both worker implementations and returns `{ status: boolean, error?: Error }`.