Adjust feature order
[poolifier.git] / README.md
1 <div align="center">
2 <img src="./docs/logo.png" width="475" height="400"/>
3 </div>
4
5 <h2 align="center">Node Thread Pool :arrow_double_up: :on:</h2>
6
7 <p align="center">
8 <a href="https://www.npmjs.com/package/poolifier">
9 <img alt="Weekly Downloads" src="https://img.shields.io/npm/dw/poolifier"></a>
10 <a href="https://github.com/pioardi/node-pool/actions">
11 <img alt="Actions Status" src="https://github.com/pioardi/node-pool/workflows/NodeCI/badge.svg"></a>
12 <a href="https://sonarcloud.io/dashboard?id=pioardi_poolifier">
13 <img alt="Quality Gate Status" src="https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=alert_status"></a>
14 <a href="https://sonarcloud.io/component_measures/metric/coverage/list?id=pioardi_poolifier">
15 <img alt="Code coverage" src="https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=coverage"></a>
16 <a href="https://standardjs.com">
17 <img alt="Javascript Standard Style Guide" src="https://img.shields.io/badge/code_style-standard-brightgreen.svg"></a>
18 <a href="https://gitter.im/poolifier/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge">
19 <img alt="Gitter chat" src="https://badges.gitter.im/poolifier/community.svg"></a>
20 <a href="https://badgen.net/dependabot/dependabot/dependabot-core/?icon=dependabot">
21 <img alt="Dependabot" src="https://badgen.net/dependabot/dependabot/dependabot-core/?icon=dependabot"></a>
22 <a href="http://makeapullrequest.com">
23 <img alt="PR Welcome" src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square"></a>
24 <a href="https://img.shields.io/static/v1?label=dependencies&message=no%20dependencies&color=brightgreen">
25 <img alt="No dependencies" src="https://img.shields.io/static/v1?label=dependencies&message=no%20dependencies&color=brightgreen"></a>
26
27 </p>
28
29
30
31
32 ## Why Poolifier?
33
34 Poolifier is used to perform heavy CPU bound tasks on nodejs servers, it implements thread pools (yes, more thread 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).
35 With poolifier you can improve your **performance** and resolve problems related to the event loop.
36 Moreover you can execute your CPU tasks using an API designed to improve the **developer experience**.
37
38 - Performance :racehorse:
39 - 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)
40 - Easy to use :couple:
41 - Easy switch from a pool to another, easy to tune :heavy_check_mark:
42 - Dynamic pool size :heavy_check_mark:
43 - No runtime dependencies :heavy_check_mark:
44 - Proper async integration with node async hooks :heavy_check_mark:
45 - Support for worker threads and cluster node modules :heavy_check_mark:
46 - Support sync and async tasks :heavy_check_mark:
47 - General guidance on pools to use :heavy_check_mark:
48 - Widely tested :heavy_check_mark:
49 - Error handling out of the box :heavy_check_mark:
50 - Active community :heavy_check_mark:
51 - Code quality :octocat: [![Bugs](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=bugs)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
52 [![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=code_smells)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
53 [![Duplicated Lines (%)](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=duplicated_lines_density)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
54 [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
55 [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
56 [![Technical Debt](https://sonarcloud.io/api/project_badges/measure?project=pioardi_poolifier&metric=sqale_index)](https://sonarcloud.io/dashboard?id=pioardi_poolifier)
57
58
59 ## Contents
60
61 <h3 align="center">
62 <a href="#overview">Overview</a>
63 <span> · </span>
64 <a href="#installation">Installation</a>
65 <span> · </span>
66 <a href="#usage">Usage</a>
67 <span> · </span>
68 <a href="#node-versions"> Node versions</a>
69 <span> · </span>
70 <a href="#api">API</a>
71 <span> · </span>
72 <a href="#choose-your-pool">Choose your pool</a>
73 <span> · </span>
74 <a href="#contribute">Contribute</a>
75 <span> · </span>
76 <a href="#team">Team</a>
77 <span> · </span>
78 <a href="#license">License</a>
79 </h3>
80
81 ## Overview
82
83 Node pool contains two [worker-threads](https://nodejs.org/api/worker_threads.html#worker_threads_worker_threads) pool implementations, you don't have to deal with worker-threads complexity.
84 The first implementation is a static thread pool, with a defined number of threads that are started at creation time and will be reused.
85 The second implementation is a dynamic thread pool with a number of threads started at creation time (these threads will be always active and reused) and other threads created when the load will increase (with an upper limit, these threads will be reused when active), the new created threads will be stopped after a configurable period of inactivity.
86 You have to implement your worker extending the ThreadWorker class
87
88 ## Installation
89
90 ```shell
91 npm install poolifier --save
92 ```
93
94 ## Usage
95
96 You can implement a worker in a simple way, extending the class ThreadWorker:
97
98 ```js
99 'use strict'
100 const { ThreadWorker } = require('poolifier')
101
102 function yourFunction (data) {
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
108 module.exports = new ThreadWorker(yourFunction, {
109 maxInactiveTime: 60000,
110 async: false
111 })
112 ```
113
114 Instantiate your pool based on your needed :
115
116 ```js
117 'use strict'
118 const { FixedThreadPool, DynamicThreadPool } = require('poolifier')
119
120 // a fixed thread pool
121 const pool = new FixedThreadPool(15,
122 './yourWorker.js',
123 { errorHandler: (e) => console.error(e), onlineHandler: () => console.log('worker is online') })
124
125 // or a dynamic thread pool
126 const pool = new DynamicThreadPool(10, 100,
127 './yourWorker.js',
128 { errorHandler: (e) => console.error(e), onlineHandler: () => console.log('worker is online') })
129
130 pool.emitter.on('FullPool', () => console.log('Pool is full'))
131
132 // the execute method signature is the same for both implementations,
133 // so you can easy switch from one to another
134 pool.execute({}).then(res => {
135 console.log(res)
136 }).catch ....
137
138 ```
139
140 **See examples folder for more details (in particular if you want to use a pool for [multiple functions](./examples/multiFunctionExample.js)).**
141 **Now type script is also supported, find how to use it into the example folder**
142
143 ## Node versions
144
145 You can use node versions 12.x, 13.x, 14.x
146
147 ## API
148
149 ### `pool = new FixedThreadPool(numThreads, filePath, opts)`
150
151 `numThreads` (mandatory) Num of threads for this worker pool
152 `filePath` (mandatory) Path to a file with a worker implementation
153 `opts` (optional) An object with these properties :
154
155 - `errorHandler` - A function that will listen for error event on each worker thread
156 - `onlineHandler` - A function that will listen for online event on each worker thread
157 - `exitHandler` - A function that will listen for exit event on each worker thread
158 - `maxTasks` - This is just to avoid not useful warnings message, is used to set [maxListeners](https://nodejs.org/dist/latest-v12.x/docs/api/events.html#events_emitter_setmaxlisteners_n) on event emitters (workers are event emitters)
159
160 ### `pool = new DynamicThreadPool(min, max, filePath, opts)`
161
162 `min` (mandatory) Same as FixedThreadPool numThreads, this number of threads will be always active
163 `max` (mandatory) Max number of workers that this pool can contain, the new created threads will die after a threshold (default is 1 minute, you can override it in your worker implementation).
164 `filePath` (mandatory) Same as FixedThreadPool
165 `opts` (optional) Same as FixedThreadPool
166
167 ### `pool.execute(data)`
168
169 Execute method is available on both pool implementations (return type : Promise):
170 `data` (mandatory) An object that you want to pass to your worker implementation
171
172 ### `pool.destroy()`
173
174 Destroy method is available on both pool implementations.
175 This method will call the terminate method on each worker.
176
177 ### `class YourWorker extends ThreadWorker`
178
179 `fn` (mandatory) The function that you want to execute on the worker thread
180 `opts` (optional) An object with these properties:
181
182 - `maxInactiveTime` - Max time to wait tasks to work on ( in ms) , after this period the new worker threads will die.
183 - `async` - true/false, true if your function contains async pieces else false
184
185 ## Choose your pool
186
187 Performance is one of the main target of these thread pool implementations, we want to have a strong focus on this.
188 We already have a bench folder where you can find some comparisons.
189 To choose your pool consider that with a FixedThreadPool or a DynamicThreadPool (in this case is important the min parameter passed to the constructor) your application memory footprint will increase.
190 Increasing the memory footprint, your application will be ready to accept more CPU bound tasks, but during idle time your application will consume more memory.
191 One good choose from my point of view is to profile your application using Fixed/Dynamic thread pool, and to see your application metrics when you increase/decrease the num of threads.
192 For example you could keep the memory footprint low choosing a DynamicThreadPool with 5 threads, and allow to create new threads until 50/100 when needed, this is the advantage to use the DynamicThreadPool.
193 But in general, **always profile your application**
194
195 ## Contribute
196
197 See guidelines [CONTRIBUTING](CONTRIBUTING.md)
198 Choose your task here [2.0.0](https://github.com/pioardi/poolifier/projects/1), propose an idea, a fix, an improvement.
199
200 ## Team
201
202 <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
203 <!-- prettier-ignore-start -->
204 <!-- markdownlint-disable -->
205
206 **Creator/Owner:**
207
208 - [**Alessandro Pio Ardizio**](https://github.com/pioardi)
209
210 **_Contributors_**
211
212 - [**Shinigami92**](https://github.com/Shinigami92)
213 - [**Jérôme Benoit**](https://github.com/jerome-benoit)
214
215 ## License
216
217 [MIT](./LICENSE)