Tests: simplify tasks usage reset
[poolifier.git] / README.md
CommitLineData
f2b5671a 1<div align="center">
5ea22628 2<img src="./images/logo.png" width="340px" height="266px"/>
ddaa3a76 3</div>
4
063f8c5b 5<h2 align="center">Node Thread Pool and Cluster Pool :arrow_double_up: :on:</h2>
75876e4c
APA
6<h2 align="center">
7 <a href="https://ko-fi.com/Q5Q31D6QY">
8 <img alt="Ko-fi" src="https://ko-fi.com/img/githubbutton_sm.svg"></a>
9</h2>
1d4f79e7
APA
10
11<p align="center">
12 <a href="https://www.npmjs.com/package/poolifier">
13 <img alt="Weekly Downloads" src="https://img.shields.io/npm/dw/poolifier"></a>
6ccc1262
JB
14 <a href="https://github.com/poolifier/poolifier/actions">
15 <img alt="Actions Status" src="https://github.com/poolifier/poolifier/workflows/NodeCI/badge.svg"></a>
1d4f79e7
APA
16 <a href="https://sonarcloud.io/dashboard?id=pioardi_poolifier">
17 <img alt="Quality Gate Status" src="https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=alert_status"></a>
18 <a href="https://sonarcloud.io/component_measures/metric/coverage/list?id=pioardi_poolifier">
19 <img alt="Code coverage" src="https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=coverage"></a>
20 <a href="https://standardjs.com">
21 <img alt="Javascript Standard Style Guide" src="https://img.shields.io/badge/code_style-standard-brightgreen.svg"></a>
22 <a href="https://gitter.im/poolifier/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge">
23 <img alt="Gitter chat" src="https://badges.gitter.im/poolifier/community.svg"></a>
8f8dc0e0
JB
24 <a href="https://badgen.net/badge/Dependabot/enabled/green?icon=dependabot">
25 <img alt="Dependabot" src="https://badgen.net/badge/Dependabot/enabled/green?icon=dependabot"></a>
1d4f79e7
APA
26 <a href="http://makeapullrequest.com">
27 <img alt="PR Welcome" src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square"></a>
28 <a href="https://img.shields.io/static/v1?label=dependencies&message=no%20dependencies&color=brightgreen">
29 <img alt="No dependencies" src="https://img.shields.io/static/v1?label=dependencies&message=no%20dependencies&color=brightgreen"></a>
1d4f79e7
APA
30</p>
31
74750c7f 32## Why Poolifier?
e76f5485 33
c868b39b 34Poolifier is used to perform CPU intensive and I/O intensive tasks on nodejs servers, it implements worker pools (yes, more worker pool implementations, so you can choose which one fit better for you) using [worker-threads](https://nodejs.org/api/worker_threads.html#worker_threads_worker_threads) and cluster pools using [Node.js cluster](https://nodejs.org/api/cluster.html) modules.
50aa7901 35With poolifier you can improve your **performance** and resolve problems related to the event loop.
063f8c5b 36Moreover you can execute your tasks using an API designed to improve the **developer experience**.
e36cfb13 37Please consult our <a href="#general-guidance">general guidelines</a>
e76f5485 38
64060857 39- Performance :racehorse: [benchmarks](./benchmarks/README.md)
f2b5671a 40- Security :bank: :cop: [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=security_rating)](https://sonarcloud.io/dashboard?id=pioardi_poolifier) [![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=vulnerabilities)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
b1b24f66 41- Easy to use :couple:
38553e6e 42- Easy switch from a pool to another, easy to tune :heavy_check_mark:
43- Dynamic pool size :heavy_check_mark:
d28c7996 44- No runtime dependencies :heavy_check_mark:
38553e6e 45- Proper async integration with node async hooks :heavy_check_mark:
46- Support for worker threads and cluster node modules :heavy_check_mark:
38553e6e 47- Support sync and async tasks :heavy_check_mark:
48- General guidance on pools to use :heavy_check_mark:
49- Widely tested :heavy_check_mark:
50- Error handling out of the box :heavy_check_mark:
ed93dc74 51- Active community :heavy_check_mark:
5fd75a2e 52- Code quality :octocat: [![Bugs](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=bugs)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
d28c7996
JB
53 [![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=code_smells)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
54 [![Duplicated Lines (%)](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=duplicated_lines_density)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
55 [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
56 [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
57 [![Technical Debt](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=sqale_index)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
ddaa3a76 58
50aa7901 59## Contents
e76f5485 60
34a572eb 61<h3 align="center">
50aa7901
S
62 <a href="#overview">Overview</a>
63 <span> · </span>
34a572eb 64 <a href="#installation">Installation</a>
65 <span> · </span>
66 <a href="#usage">Usage</a>
67 <span> · </span>
4f4ae1cb 68 <a href="#node-versions">Node versions</a>
50aa7901 69 <span> · </span>
34a572eb 70 <a href="#api">API</a>
71 <span> · </span>
e36cfb13 72 <a href="#general-guidance">General guidance</a>
48211d04 73 <span> · </span>
34a572eb 74 <a href="#contribute">Contribute</a>
75 <span> · </span>
50aa7901 76 <a href="#team">Team</a>
34a572eb 77 <span> · </span>
78 <a href="#license">License</a>
79</h3>
80
50aa7901 81## Overview
13031992 82
31b90205
JB
83Node pool contains two [worker-threads](https://nodejs.org/api/worker_threads.html#worker_threads_worker_threads)/[cluster worker](https://nodejs.org/api/cluster.html#cluster_class_worker) pool implementations, you don't have to deal with worker-threads/cluster worker complexity.
84The first implementation is a static worker pool, with a defined number of workers that are started at creation time and will be reused.
85The second implementation is a dynamic worker pool with a number of worker started at creation time (these workers will be always active and reused) and other workers created when the load will increase (with an upper limit, these workers will be reused when active), the new created workers will be stopped after a configurable period of inactivity.
86You have to implement your worker extending the ThreadWorker or ClusterWorker class
50aa7901
S
87
88## Installation
89
90```shell
27c5fb75 91npm install poolifier --save
1a4ec243 92```
1a4ec243 93
50aa7901
S
94## Usage
95
31b90205 96You can implement a worker-threads worker in a simple way by extending the class ThreadWorker:
1a4ec243
APA
97
98```js
99'use strict'
d2eb4964 100const { ThreadWorker } = require('poolifier')
1a4ec243 101
4a297cd5 102function yourFunction (data) {
106744f7 103 // this will be executed in the worker thread,
104 // the data will be received by using the execute method
105 return { ok: 1 }
106}
107
50aa7901
S
108module.exports = new ThreadWorker(yourFunction, {
109 maxInactiveTime: 60000,
110 async: false
111})
1a4ec243
APA
112```
113
1f9a5a44 114Instantiate your pool based on your needed :
1a4ec243
APA
115
116```js
117'use strict'
d2eb4964 118const { FixedThreadPool, DynamicThreadPool } = require('poolifier')
1a4ec243 119
31b90205 120// a fixed worker-threads pool
1a4ec243 121const pool = new FixedThreadPool(15,
106744f7 122 './yourWorker.js',
123 { errorHandler: (e) => console.error(e), onlineHandler: () => console.log('worker is online') })
1a4ec243 124
31b90205 125// or a dynamic worker-threads pool
1a4ec243 126const pool = new DynamicThreadPool(10, 100,
106744f7 127 './yourWorker.js',
128 { errorHandler: (e) => console.error(e), onlineHandler: () => console.log('worker is online') })
129
a72f2599 130pool.emitter.on('busy', () => console.log('Pool is busy'))
1a4ec243
APA
131
132// the execute method signature is the same for both implementations,
133// so you can easy switch from one to another
134pool.execute({}).then(res => {
135 console.log(res)
777b7824 136}).catch ....
1a4ec243
APA
137
138```
139
17a9a094 140You can do the same with the classes ClusterWorker, FixedClusterPool and DynamicClusterPool.
31b90205 141
17a9a094
JB
142**See examples folder for more details (in particular if you want to use a pool for [multiple functions](./examples/multiFunctionExample.js)).**
143**Now TypeScript is also supported, find how to use it into the example folder**.
1a4ec243 144
ec2ccfc8 145Remember that workers can only send and receive serializable data.
deb85c12 146
50aa7901 147## Node versions
34a572eb 148
d4161a8e 149You can use node versions >= 12.x for thread pool, and node versions >= 16.x for cluster pool.
1a4ec243 150
50aa7901 151## API
34a572eb 152
31b90205 153### `pool = new FixedThreadPool/FixedClusterPool(numberOfThreads/numberOfWorkers, filePath, opts)`
50aa7901 154
f42ca86f 155`numberOfThreads/numberOfWorkers` (mandatory) Number of workers for this pool
50aa7901 156`filePath` (mandatory) Path to a file with a worker implementation
f42ca86f 157`opts` (optional) An object with these properties:
50aa7901 158
f42ca86f
JB
159- `errorHandler` (optional) - A function that will listen for error event on each worker
160- `onlineHandler` (optional) - A function that will listen for online event on each worker
161- `exitHandler` (optional) - A function that will listen for exit event on each worker
162- `workerChoiceStrategy` (optional) - The work choice strategy to use in this pool:
5519f8f3 163
f42ca86f 164 - `WorkerChoiceStrategies.ROUND_ROBIN`: Submit tasks to worker in this pool in a round robbin fashion
5519f8f3 165 - `WorkerChoiceStrategies.LESS_RECENTLY_USED`: Submit tasks to the less recently used worker in the pool
23ff945a
JB
166 - `WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN` Submit tasks to worker using a weighted round robin scheduling algorithm based on tasks execution time for now
167 - `WorkerChoiceStrategies.FAIR_SHARE`: Submit tasks to worker using a fair share tasks scheduling algorithm
5519f8f3 168
f42ca86f 169 Default: `WorkerChoiceStrategies.ROUND_ROBIN`
5519f8f3 170
f42ca86f 171- `enableEvents` (optional) - Events emission enablement in this pool. Default: true
34a572eb 172
31b90205 173### `pool = new DynamicThreadPool/DynamicClusterPool(min, max, filePath, opts)`
50aa7901 174
31b90205
JB
175`min` (mandatory) Same as FixedThreadPool/FixedClusterPool numberOfThreads/numberOfWorkers, this number of workers will be always active
176`max` (mandatory) Max number of workers that this pool can contain, the new created workers will die after a threshold (default is 1 minute, you can override it in your worker implementation).
177`filePath` (mandatory) Same as FixedThreadPool/FixedClusterPool
178`opts` (optional) Same as FixedThreadPool/FixedClusterPool
34a572eb 179
180### `pool.execute(data)`
50aa7901 181
f42ca86f 182Execute method is available on both pool implementations (return type: Promise):
50aa7901 183`data` (mandatory) An object that you want to pass to your worker implementation
34a572eb 184
185### `pool.destroy()`
34a572eb 186
50aa7901
S
187Destroy method is available on both pool implementations.
188This method will call the terminate method on each worker.
34a572eb 189
31b90205 190### `class YourWorker extends ThreadWorker/ClusterWorker`
50aa7901 191
31b90205 192`fn` (mandatory) The function that you want to execute on the worker
50aa7901
S
193`opts` (optional) An object with these properties:
194
31b90205 195- `maxInactiveTime` - Max time to wait tasks to work on (in ms), after this period the new worker will die.
3832ad95
S
196 The last active time of your worker unit will be updated when a task is submitted to a worker or when a worker terminate a task.
197 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 and the worker is killed if is not part of the minimum size of the pool.
198 If `killBehavior` is set to `KillBehaviors.SOFT` your tasks have no timeout and your workers will not be terminated until your task is completed.
bf9549ae 199 Default: 60000 ms
15eacd5d 200
50aa7901 201- `async` - true/false, true if your function contains async pieces else false
15eacd5d 202- `killBehavior` - Dictates if your async unit (worker/process) will be deleted in case that a task is active on it.
f42ca86f
JB
203 **KillBehaviors.SOFT**: If `currentTime - lastActiveTime` is greater than `maxInactiveTime` but a task is still running, then the worker **won't** be deleted.
204 **KillBehaviors.HARD**: If `lastActiveTime` is greater than `maxInactiveTime` but a task is still running, then the worker will be deleted.
3832ad95 205 This option only apply to the newly created workers.
f42ca86f 206 Default: `KillBehaviors.SOFT`
50aa7901 207
e36cfb13 208## General guidance
34a572eb 209
31b90205 210Performance is one of the main target of these worker pool implementations, we want to have a strong focus on this.
e36cfb13
APA
211We already have a bench folder where you can find some comparisons.
212
213### Internal Node.js thread pool
214
215Before to jump into each poolifier pool type, let highlight that **Node.js comes with a thread pool already**, the libuv thread pool where some particular tasks already run by default.
216Please take a look at [which tasks run on the libuv thread pool](https://nodejs.org/en/docs/guides/dont-block-the-event-loop/#what-code-runs-on-the-worker-pool).
217
e843b904 218**If your task runs on libuv thread pool**, you can try to:
e36cfb13
APA
219
220- Tune the libuv thread pool size setting the [UV_THREADPOOL_SIZE](https://nodejs.org/api/cli.html#cli_uv_threadpool_size_size)
221
222and/or
223
224- Use poolifier cluster pool that spawning child processes will also increase the number of libuv threads since that any new child process comes with a separated libuv thread pool. **More threads does not mean more fast, so please tune your application.**
225
226### Cluster vs Threads worker pools
227
228**If your task does not run into libuv thread pool** and is CPU intensive then poolifier **thread pools** (FixedThreadPool and DynamicThreadPool) are suggested to run CPU intensive tasks, you can still run I/O intensive tasks into thread pools, but performance enhancement is expected to be minimal.
063f8c5b 229Thread pools are built on top of Node.js [worker-threads](https://nodejs.org/api/worker_threads.html#worker_threads_worker_threads) module.
230
e36cfb13
APA
231**If your task does not run into libuv thread pool** and is I/O intensive then poolifier **cluster pools** (FixedClusterPool and DynamicClusterPool) are suggested to run I/O intensive tasks, again you can still run CPU intensive tasks into cluster pools, but performance enhancement is expected to be minimal.
232Consider that by default Node.js already has great performance for I/O tasks (asynchronous I/O).
4a6952ff 233Cluster pools are built on top of Node.js [cluster](https://nodejs.org/api/cluster.html) module.
75876e4c 234
e36cfb13
APA
235If your task contains code that runs on libuv plus code that is CPU intensive or I/O intensive you either split it either combine more strategies (i.e. tune the number of libuv threads and use cluster/thread pools).
236But in general, **always profile your application**
237
238### Fixed vs Dynamic pools
063f8c5b 239
31b90205 240To choose your pool consider that with a FixedThreadPool/FixedClusterPool or a DynamicThreadPool/DynamicClusterPool (in this case is important the min parameter passed to the constructor) your application memory footprint will increase.
063f8c5b 241Increasing the memory footprint, your application will be ready to accept more tasks, but during idle time your application will consume more memory.
31b90205
JB
242One good choose from my point of view is to profile your application using Fixed/Dynamic worker pool, and to see your application metrics when you increase/decrease the num of workers.
243For example you could keep the memory footprint low choosing a DynamicThreadPool/DynamicClusterPool with 5 workers, and allow to create new workers until 50/100 when needed, this is the advantage to use the DynamicThreadPool/DynamicClusterPool.
50aa7901 244But in general, **always profile your application**
48211d04 245
50aa7901 246## Contribute
34a572eb 247
50aa7901 248See guidelines [CONTRIBUTING](CONTRIBUTING.md)
ae965d5b 249Choose your task here [2.3.0](https://github.com/orgs/poolifier/projects/1), propose an idea, a fix, an improvement.
1a4ec243 250
50aa7901 251## Team
1a4ec243 252
39deb558 253<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
39deb558 254
255**Creator/Owner:**
39deb558 256
50aa7901
S
257- [**Alessandro Pio Ardizio**](https://github.com/pioardi)
258
259**_Contributors_**
260
261- [**Shinigami92**](https://github.com/Shinigami92)
262- [**Jérôme Benoit**](https://github.com/jerome-benoit)
39deb558 263
50aa7901 264## License
1a4ec243 265
9507c1d4 266[MIT](./LICENSE)