chore(deps-dev): apply updates
[poolifier.git] / docs / api.md
CommitLineData
a47027a0
JB
1# [API](https://poolifier.github.io/poolifier/)
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)
7d91a8cd 8 - [`pool.execute(data, name, transferList)`](#poolexecutedata-name-transferlist)
989a71a5 9 - [`pool.mapExecute(data, name, transferList)`](#poolmapexecutedata-name-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
7d91a8cd 41### `pool.execute(data, name, 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'`
5e4dbac9 45`transferList` (optional) An array of transferable objects that you want to transfer to your [`ThreadWorker`](#class-yourworker-extends-threadworkerclusterworker) worker implementation.
a47027a0
JB
46
47This method is available on both pool implementations and returns a promise with the task function execution response.
48
d0798374
JB
49### `pool.mapExecute(data, name, transferList)`
50
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.
54
55This method is available on both pool implementations and returns a promise with the task function execution responses array.
56
47352846
JB
57### `pool.start()`
58
59This method is available on both pool implementations and will start the minimum number of workers.
60
a47027a0
JB
61### `pool.destroy()`
62
63This method is available on both pool implementations and will call the terminate method on each worker.
64
30500265
JB
65### `pool.hasTaskFunction(name)`
66
679e657a 67`name` (mandatory) The task function name.
30500265
JB
68
69This method is available on both pool implementations and returns a boolean.
70
9eae3c69
JB
71### `pool.addTaskFunction(name, fn)`
72
e7277e38 73`name` (mandatory) The task function name.
3e3e2e5d 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.
9eae3c69
JB
75
76This method is available on both pool implementations and returns a boolean promise.
77
78### `pool.removeTaskFunction(name)`
79
80`name` (mandatory) The task function name.
81
82This method is available on both pool implementations and returns a boolean promise.
83
31847469 84### `pool.listTaskFunctionsProperties()`
90d7d101 85
31847469 86This method is available on both pool implementations and returns an array of the task function properties.
90d7d101 87
9eae3c69
JB
88### `pool.setDefaultTaskFunction(name)`
89
90`name` (mandatory) The task function name.
91
92This method is available on both pool implementations and returns a boolean promise.
93
31d71267 94### Pool options
a47027a0
JB
95
96An object with these properties:
97
d293923f
JB
98- `onlineHandler` (optional) - A function that will listen for online event on each worker.
99 Default: `() => {}`
100- `messageHandler` (optional) - A function that will listen for message event on each worker.
101 Default: `() => {}`
102- `errorHandler` (optional) - A function that will listen for error event on each worker.
103 Default: `() => {}`
104- `exitHandler` (optional) - A function that will listen for exit event on each worker.
105 Default: `() => {}`
106
bcfb06ce 107- `workerChoiceStrategy` (optional) - The default worker choice strategy to use in this pool:
a47027a0
JB
108
109 - `WorkerChoiceStrategies.ROUND_ROBIN`: Submit tasks to worker in a round robin fashion
e0843544 110 - `WorkerChoiceStrategies.LEAST_USED`: Submit tasks to the worker with the minimum number of executing and queued tasks
b2940269 111 - `WorkerChoiceStrategies.LEAST_BUSY`: Submit tasks to the worker with the minimum tasks execution time
a71b05bc 112 - `WorkerChoiceStrategies.LEAST_ELU`: Submit tasks to the worker with the minimum event loop utilization (ELU)
2904fcdb 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
bde1a004 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)
2904fcdb 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
a47027a0
JB
116
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`
119
120- `workerChoiceStrategyOptions` (optional) - The worker choice strategy options object to use in this pool.
121 Properties:
122
123 - `measurement` (optional) - The measurement to use in worker choice strategies: `runTime`, `waitTime` or `elu`.
06916f85
JB
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.
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:
142
fa3cc835 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.
5137e2ae 144 - `concurrency` (optional) - The maximum number of tasks that can be executed concurrently on a worker. It must be a positive integer.
65542a35 145 - `taskStealing` (optional) - Task stealing enablement on idle.
af98b972 146 - `tasksStealingOnBackPressure` (optional) - Tasks stealing enablement under back pressure.
453c6467 147 - `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 148 - `tasksFinishedTimeout` (optional) - Queued tasks finished timeout in milliseconds at worker termination.
445264e8 149
f09b1954 150 Default: `{ size: (pool maximum size)^2, concurrency: 1, taskStealing: true, tasksStealingOnBackPressure: true, tasksStealingRatio: 0.6, tasksFinishedTimeout: 2000 }`
a47027a0 151
a47027a0
JB
152- `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
a47027a0
JB
154- `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
156- `settings` (optional) - An object with the cluster settings. See [cluster](https://nodejs.org/api/cluster.html#cluster_cluster_settings) for more details.
157
158## Worker
159
160### `class YourWorker extends ThreadWorker/ClusterWorker`
161
3e3e2e5d 162`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
163`opts` (optional) An object with these properties:
164
968dbbe7 165- `killBehavior` (optional) - Dictates if your worker will be deleted in case a task is active on it.
152e87a8
JB
166 **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.
167 **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
168 This option only apply to the newly created workers.
169 Default: `KillBehaviors.SOFT`
170
c20084b6 171- `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
172 The last active time of your worker will be updated when it terminates a task.
173 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.
174 If `killBehavior` is set to `KillBehaviors.SOFT` your tasks have no timeout and your workers will not be terminated until your task is completed.
175 Default: `60000`
176
968dbbe7
JB
177- `killHandler` (optional) - A function that will be called when a worker is killed.
178 Default: `() => {}`
a47027a0
JB
179
180#### `YourWorker.hasTaskFunction(name)`
181
8c445a4e 182`name` (mandatory) The task function name.
a47027a0 183
30500265 184This method is available on both worker implementations and returns `{ status: boolean, error?: Error }`.
a47027a0
JB
185
186#### `YourWorker.addTaskFunction(name, fn)`
187
8c445a4e 188`name` (mandatory) The task function name.
3e3e2e5d 189`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 190
30500265 191This method is available on both worker implementations and returns `{ status: boolean, error?: Error }`.
a47027a0
JB
192
193#### `YourWorker.removeTaskFunction(name)`
194
8c445a4e 195`name` (mandatory) The task function name.
a47027a0 196
30500265 197This method is available on both worker implementations and returns `{ status: boolean, error?: Error }`.
a47027a0 198
31847469 199#### `YourWorker.listTaskFunctionsProperties()`
a47027a0 200
31847469 201This method is available on both worker implementations and returns an array of the task function properties.
a47027a0
JB
202
203#### `YourWorker.setDefaultTaskFunction(name)`
204
8c445a4e 205`name` (mandatory) The task function name.
a47027a0 206
30500265 207This method is available on both worker implementations and returns `{ status: boolean, error?: Error }`.