]> Piment Noir Git Repositories - poolifier.git/blame - docs/api.md
build(deps): bump the regular group across 11 directories with 1 update (#2926)
[poolifier.git] / docs / api.md
CommitLineData
92daba40 1# API
a47027a0
JB
2
3## Table of contents
4
5- [Pool](#pool)
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)
f4289ecb
JB
8 - [`pool.execute(data, name, abortSignal, transferList)`](#poolexecutedata-name-abortsignal-transferlist)
9 - [`pool.mapExecute(data, name, abortSignals, transferList)`](#poolmapexecutedata-name-abortsignals-transferlist)
47352846 10 - [`pool.start()`](#poolstart)
a47027a0 11 - [`pool.destroy()`](#pooldestroy)
9eae3c69
JB
12 - [`pool.hasTaskFunction(name)`](#poolhastaskfunctionname)
13 - [`pool.addTaskFunction(name, fn)`](#pooladdtaskfunctionname-fn)
14 - [`pool.removeTaskFunction(name)`](#poolremovetaskfunctionname)
31847469 15 - [`pool.listTaskFunctionsProperties()`](#poollisttaskfunctionsproperties)
9eae3c69 16 - [`pool.setDefaultTaskFunction(name)`](#poolsetdefaulttaskfunctionname)
31d71267 17 - [Pool options](#pool-options)
a47027a0
JB
18- [Worker](#worker)
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)
31847469 23 - [`YourWorker.listTaskFunctionsProperties()`](#yourworkerlisttaskfunctionsproperties)
a47027a0
JB
24 - [`YourWorker.setDefaultTaskFunction(name)`](#yourworkersetdefaulttaskfunctionname)
25
26## Pool
27
28### `pool = new FixedThreadPool/FixedClusterPool(numberOfThreads/numberOfWorkers, filePath, opts)`
29
8c445a4e
JB
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.
a47027a0
JB
33
34### `pool = new DynamicThreadPool/DynamicClusterPool(min, max, filePath, opts)`
35
8c445a4e 36`min` (mandatory) Same as _FixedThreadPool_/_FixedClusterPool_ numberOfThreads/numberOfWorkers, this number of workers will be always active.
a36b9e1f 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).
8c445a4e
JB
38`filePath` (mandatory) Path to a file with a worker implementation.
39`opts` (optional) An object with the pool options properties described below.
a47027a0 40
f4289ecb 41### `pool.execute(data, name, abortSignal, transferList)`
a47027a0 42
b51d8596 43`data` (optional) An object that you want to pass to your worker task function implementation.
637100d9 44`name` (optional) A string with the task function name that you want to execute on the worker. Default: `'default'`
f4289ecb 45`abortSignal` (optional) An abort signal to abort the task function execution.
5e4dbac9 46`transferList` (optional) An array of transferable objects that you want to transfer to your [`ThreadWorker`](#class-yourworker-extends-threadworkerclusterworker) worker implementation.
a47027a0
JB
47
48This method is available on both pool implementations and returns a promise with the task function execution response.
49
f4289ecb 50### `pool.mapExecute(data, name, abortSignals, transferList)`
d0798374 51
f4289ecb 52`data` An iterable of objects that you want to pass to your worker task function implementation.
d0798374 53`name` (optional) A string with the task function name that you want to execute on the worker. Default: `'default'`
f4289ecb 54`abortSignals` (optional) An iterable of AbortSignal to abort the matching object task function execution.
d0798374
JB
55`transferList` (optional) An array of transferable objects that you want to transfer to your [`ThreadWorker`](#class-yourworker-extends-threadworkerclusterworker) worker implementation.
56
57This method is available on both pool implementations and returns a promise with the task function execution responses array.
58
47352846
JB
59### `pool.start()`
60
61This method is available on both pool implementations and will start the minimum number of workers.
62
a47027a0
JB
63### `pool.destroy()`
64
65This method is available on both pool implementations and will call the terminate method on each worker.
66
30500265
JB
67### `pool.hasTaskFunction(name)`
68
679e657a 69`name` (mandatory) The task function name.
30500265
JB
70
71This method is available on both pool implementations and returns a boolean.
72
9eae3c69
JB
73### `pool.addTaskFunction(name, fn)`
74
e7277e38 75`name` (mandatory) The task function name.
3e3e2e5d 76`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.
9eae3c69
JB
77
78This method is available on both pool implementations and returns a boolean promise.
79
80### `pool.removeTaskFunction(name)`
81
82`name` (mandatory) The task function name.
83
84This method is available on both pool implementations and returns a boolean promise.
85
31847469 86### `pool.listTaskFunctionsProperties()`
90d7d101 87
31847469 88This method is available on both pool implementations and returns an array of the task function properties.
90d7d101 89
9eae3c69
JB
90### `pool.setDefaultTaskFunction(name)`
91
92`name` (mandatory) The task function name.
93
94This method is available on both pool implementations and returns a boolean promise.
95
31d71267 96### Pool options
a47027a0
JB
97
98An object with these properties:
99
d293923f
JB
100- `onlineHandler` (optional) - A function that will listen for online event on each worker.
101 Default: `() => {}`
102- `messageHandler` (optional) - A function that will listen for message event on each worker.
103 Default: `() => {}`
104- `errorHandler` (optional) - A function that will listen for error event on each worker.
105 Default: `() => {}`
106- `exitHandler` (optional) - A function that will listen for exit event on each worker.
107 Default: `() => {}`
108
bcfb06ce 109- `workerChoiceStrategy` (optional) - The default worker choice strategy to use in this pool:
a47027a0 110 - `WorkerChoiceStrategies.ROUND_ROBIN`: Submit tasks to worker in a round robin fashion
e0843544 111 - `WorkerChoiceStrategies.LEAST_USED`: Submit tasks to the worker with the minimum number of executing and queued tasks
b2940269 112 - `WorkerChoiceStrategies.LEAST_BUSY`: Submit tasks to the worker with the minimum tasks execution time
a71b05bc 113 - `WorkerChoiceStrategies.LEAST_ELU`: Submit tasks to the worker with the minimum event loop utilization (ELU)
92daba40
JB
114 - `WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN`: Submit tasks to worker by using a [weighted round robin scheduling algorithm](./worker-choice-strategies.md) based on tasks execution time
115 - `WorkerChoiceStrategies.INTERLEAVED_WEIGHTED_ROUND_ROBIN`: Submit tasks to worker by using an [interleaved weighted round robin scheduling algorithm](./worker-choice-strategies.md) based on tasks execution time (experimental)
116 - `WorkerChoiceStrategies.FAIR_SHARE`: Submit tasks to worker by using a [fair share scheduling algorithm](./worker-choice-strategies.md) based on tasks execution time (the default) or ELU active time
a47027a0
JB
117
118 `WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN`, `WorkerChoiceStrategies.INTERLEAVED_WEIGHTED_ROUND_ROBIN` and `WorkerChoiceStrategies.FAIR_SHARE` strategies are targeted to heavy and long tasks.
119 Default: `WorkerChoiceStrategies.ROUND_ROBIN`
120
121- `workerChoiceStrategyOptions` (optional) - The worker choice strategy options object to use in this pool.
122 Properties:
a47027a0 123 - `measurement` (optional) - The measurement to use in worker choice strategies: `runTime`, `waitTime` or `elu`.
92daba40
JB
124 - `runTime` (optional) - Use the tasks [simple moving median](./worker-choice-strategies.md) 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) 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) ELU instead of the tasks simple moving average ELU in worker choice strategies.
181af286 127 - `weights` (optional) - The worker weights to use in weighted round robin worker choice strategies: `Record<number, number>`.
a47027a0 128
26ce26ca 129 Default: `{ runTime: { median: false }, waitTime: { median: false }, elu: { median: false } }`
a47027a0 130
ce0ab2d7 131- `startWorkers` (optional) - Start the minimum number of workers at pool initialization.
d293923f 132 Default: `true`
a47027a0
JB
133- `restartWorkerOnError` (optional) - Restart worker on uncaught error in this pool.
134 Default: `true`
d67bed32 135- `enableEvents` (optional) - Pool events integrated with async resource emission enablement.
a47027a0
JB
136 Default: `true`
137- `enableTasksQueue` (optional) - Tasks queue per worker enablement in this pool.
138 Default: `false`
139
140- `tasksQueueOptions` (optional) - The worker tasks queue options object to use in this pool.
141 Properties:
fa3cc835 142 - `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.
5137e2ae 143 - `concurrency` (optional) - The maximum number of tasks that can be executed concurrently on a worker. It must be a positive integer.
65542a35 144 - `taskStealing` (optional) - Task stealing enablement on idle.
af98b972 145 - `tasksStealingOnBackPressure` (optional) - Tasks stealing enablement under back pressure.
453c6467 146 - `tasksStealingRatio` (optional) - The ratio of worker nodes that can steal tasks from another worker node. It must be a number between 0 and 1.
32b141fd 147 - `tasksFinishedTimeout` (optional) - Queued tasks finished timeout in milliseconds at worker termination.
445264e8 148
f09b1954 149 Default: `{ size: (pool maximum size)^2, concurrency: 1, taskStealing: true, tasksStealingOnBackPressure: true, tasksStealingRatio: 0.6, tasksFinishedTimeout: 2000 }`
a47027a0 150
a47027a0
JB
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.
152
a47027a0
JB
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.
154
155- `settings` (optional) - An object with the cluster settings. See [cluster](https://nodejs.org/api/cluster.html#cluster_cluster_settings) for more details.
156
157## Worker
158
159### `class YourWorker extends ThreadWorker/ClusterWorker`
160
3e3e2e5d 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.
a47027a0
JB
162`opts` (optional) An object with these properties:
163
968dbbe7 164- `killBehavior` (optional) - Dictates if your worker will be deleted in case a task is active on it.
152e87a8
JB
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.
968dbbe7
JB
167 This option only apply to the newly created workers.
168 Default: `KillBehaviors.SOFT`
169
c20084b6 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.
a47027a0
JB
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.
174 Default: `60000`
175
968dbbe7
JB
176- `killHandler` (optional) - A function that will be called when a worker is killed.
177 Default: `() => {}`
a47027a0
JB
178
179#### `YourWorker.hasTaskFunction(name)`
180
8c445a4e 181`name` (mandatory) The task function name.
a47027a0 182
30500265 183This method is available on both worker implementations and returns `{ status: boolean, error?: Error }`.
a47027a0
JB
184
185#### `YourWorker.addTaskFunction(name, fn)`
186
8c445a4e 187`name` (mandatory) The task function name.
3e3e2e5d 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.
a47027a0 189
30500265 190This method is available on both worker implementations and returns `{ status: boolean, error?: Error }`.
a47027a0
JB
191
192#### `YourWorker.removeTaskFunction(name)`
193
8c445a4e 194`name` (mandatory) The task function name.
a47027a0 195
30500265 196This method is available on both worker implementations and returns `{ status: boolean, error?: Error }`.
a47027a0 197
31847469 198#### `YourWorker.listTaskFunctionsProperties()`
a47027a0 199
31847469 200This method is available on both worker implementations and returns an array of the task function properties.
a47027a0
JB
201
202#### `YourWorker.setDefaultTaskFunction(name)`
203
8c445a4e 204`name` (mandatory) The task function name.
a47027a0 205
30500265 206This method is available on both worker implementations and returns `{ status: boolean, error?: Error }`.