fix: fix task stealing
[poolifier.git] / tests / pools / thread / fixed.test.js
CommitLineData
a61a0724 1const { expect } = require('expect')
cdace0e5 2const { FixedThreadPool, PoolEvents } = require('../../../lib')
dbca3be9 3const { TaskFunctions } = require('../../test-types')
1dcbfefc 4const { waitPoolEvents, waitWorkerEvents } = require('../../test-utils')
506c2a14 5
079de991 6describe('Fixed thread pool test suite', () => {
e1ffb94f 7 const numberOfThreads = 6
4e377863 8 const tasksConcurrency = 2
e1ffb94f
JB
9 const pool = new FixedThreadPool(
10 numberOfThreads,
11 './tests/worker-files/thread/testWorker.js',
12 {
8ebe6c30 13 errorHandler: (e) => console.error(e)
e1ffb94f
JB
14 }
15 )
594bfb84
JB
16 const queuePool = new FixedThreadPool(
17 numberOfThreads,
18 './tests/worker-files/thread/testWorker.js',
19 {
20 enableTasksQueue: true,
21 tasksQueueOptions: {
4e377863 22 concurrency: tasksConcurrency
594bfb84 23 },
8ebe6c30 24 errorHandler: (e) => console.error(e)
594bfb84
JB
25 }
26 )
e1ffb94f
JB
27 const emptyPool = new FixedThreadPool(
28 numberOfThreads,
29 './tests/worker-files/thread/emptyWorker.js',
73bfd59d 30 { exitHandler: () => console.info('empty pool worker exited') }
e1ffb94f
JB
31 )
32 const echoPool = new FixedThreadPool(
33 numberOfThreads,
34 './tests/worker-files/thread/echoWorker.js'
35 )
36 const errorPool = new FixedThreadPool(
37 numberOfThreads,
38 './tests/worker-files/thread/errorWorker.js',
39 {
8ebe6c30 40 errorHandler: (e) => console.error(e)
e1ffb94f
JB
41 }
42 )
43 const asyncErrorPool = new FixedThreadPool(
44 numberOfThreads,
45 './tests/worker-files/thread/asyncErrorWorker.js',
46 {
8ebe6c30 47 errorHandler: (e) => console.error(e)
e1ffb94f
JB
48 }
49 )
50 const asyncPool = new FixedThreadPool(
51 numberOfThreads,
52 './tests/worker-files/thread/asyncWorker.js'
53 )
54
0e2503fc
JB
55 after('Destroy all pools', async () => {
56 // We need to clean up the resources after our test
57 await echoPool.destroy()
58 await asyncPool.destroy()
59 await errorPool.destroy()
7c0ba920 60 await asyncErrorPool.destroy()
0e2503fc 61 await emptyPool.destroy()
594bfb84 62 await queuePool.destroy()
0e2503fc
JB
63 })
64
506c2a14 65 it('Verify that the function is executed in a worker thread', async () => {
6db75ad9 66 let result = await pool.execute({
dbca3be9 67 function: TaskFunctions.fibonacci
6db75ad9 68 })
024daf59 69 expect(result).toBe(75025)
6db75ad9 70 result = await pool.execute({
dbca3be9 71 function: TaskFunctions.factorial
6db75ad9 72 })
70a4f5ea 73 expect(result).toBe(9.33262154439441e157)
506c2a14 74 })
75
318d4156 76 it('Verify that is possible to invoke the execute() method without input', async () => {
106744f7 77 const result = await pool.execute()
30b963d4 78 expect(result).toStrictEqual({ ok: 1 })
106744f7 79 })
80
1dcbfefc 81 it("Verify that 'ready' event is emitted", async () => {
079de991
JB
82 const pool1 = new FixedThreadPool(
83 numberOfThreads,
84 './tests/worker-files/thread/testWorker.js',
85 {
8ebe6c30 86 errorHandler: (e) => console.error(e)
079de991
JB
87 }
88 )
89 let poolReady = 0
66293e7d 90 pool1.emitter.on(PoolEvents.ready, () => ++poolReady)
3e8611a8 91 await waitPoolEvents(pool1, PoolEvents.ready, 1)
216541b6
JB
92 expect(poolReady).toBe(1)
93 })
94
94407def
JB
95 it("Verify that 'busy' event is emitted", async () => {
96 const promises = new Set()
7c0ba920 97 let poolBusy = 0
aee46736 98 pool.emitter.on(PoolEvents.busy, () => ++poolBusy)
7c0ba920 99 for (let i = 0; i < numberOfThreads * 2; i++) {
94407def 100 promises.add(pool.execute())
7c0ba920 101 }
94407def 102 await Promise.all(promises)
14916bf9
JB
103 // The `busy` event is triggered when the number of submitted tasks at once reach the number of fixed pool workers.
104 // So in total numberOfThreads + 1 times for a loop submitting up to numberOfThreads * 2 tasks to the fixed pool.
105 expect(poolBusy).toBe(numberOfThreads + 1)
7c0ba920
JB
106 })
107
594bfb84 108 it('Verify that tasks queuing is working', async () => {
d3d4b67d 109 const promises = new Set()
4e377863 110 const maxMultiplier = 3 // Must be greater than tasksConcurrency
594bfb84 111 for (let i = 0; i < numberOfThreads * maxMultiplier; i++) {
d3d4b67d 112 promises.add(queuePool.execute())
594bfb84 113 }
d3d4b67d 114 expect(promises.size).toBe(numberOfThreads * maxMultiplier)
594bfb84 115 for (const workerNode of queuePool.workerNodes) {
5bb5be17 116 expect(workerNode.usage.tasks.executing).toBeGreaterThanOrEqual(0)
f59e1027 117 expect(workerNode.usage.tasks.executing).toBeLessThanOrEqual(
594bfb84
JB
118 queuePool.opts.tasksQueueOptions.concurrency
119 )
f59e1027 120 expect(workerNode.usage.tasks.executed).toBe(0)
4e377863
JB
121 expect(workerNode.usage.tasks.queued).toBe(
122 maxMultiplier - queuePool.opts.tasksQueueOptions.concurrency
123 )
124 expect(workerNode.usage.tasks.maxQueued).toBe(
125 maxMultiplier - queuePool.opts.tasksQueueOptions.concurrency
126 )
594bfb84 127 }
4e377863
JB
128 expect(queuePool.info.executingTasks).toBe(
129 numberOfThreads * queuePool.opts.tasksQueueOptions.concurrency
130 )
6b27d407 131 expect(queuePool.info.queuedTasks).toBe(
4e377863
JB
132 numberOfThreads *
133 (maxMultiplier - queuePool.opts.tasksQueueOptions.concurrency)
6b27d407
JB
134 )
135 expect(queuePool.info.maxQueuedTasks).toBe(
4e377863
JB
136 numberOfThreads *
137 (maxMultiplier - queuePool.opts.tasksQueueOptions.concurrency)
d3d4b67d 138 )
a1763c54 139 expect(queuePool.info.backPressure).toBe(false)
594bfb84
JB
140 await Promise.all(promises)
141 for (const workerNode of queuePool.workerNodes) {
a6b3272b
JB
142 expect(workerNode.usage.tasks.executing).toBeGreaterThanOrEqual(0)
143 expect(workerNode.usage.tasks.executing).toBeLessThanOrEqual(
144 numberOfThreads * maxMultiplier
145 )
4e377863 146 expect(workerNode.usage.tasks.executed).toBe(maxMultiplier)
f59e1027 147 expect(workerNode.usage.tasks.queued).toBe(0)
4e377863
JB
148 expect(workerNode.usage.tasks.maxQueued).toBe(
149 maxMultiplier - queuePool.opts.tasksQueueOptions.concurrency
150 )
594bfb84
JB
151 }
152 })
153
106744f7 154 it('Verify that is possible to have a worker that return undefined', async () => {
155 const result = await emptyPool.execute()
6db75ad9 156 expect(result).toBeUndefined()
106744f7 157 })
158
159 it('Verify that data are sent to the worker correctly', async () => {
160 const data = { f: 10 }
161 const result = await echoPool.execute(data)
e1ffb94f 162 expect(result).toStrictEqual(data)
106744f7 163 })
164
9ea61037 165 it('Verify that transferable objects are sent to the worker correctly', async () => {
9ea61037
JB
166 let error
167 let result
168 try {
f05314ff
JB
169 result = await pool.execute(undefined, undefined, [
170 new ArrayBuffer(16),
171 new MessageChannel().port1
172 ])
9ea61037
JB
173 } catch (e) {
174 error = e
175 }
176 expect(result).toStrictEqual({ ok: 1 })
177 expect(error).toBeUndefined()
f05314ff
JB
178 try {
179 result = await pool.execute(undefined, undefined, [
180 new SharedArrayBuffer(16)
181 ])
182 } catch (e) {
183 error = e
184 }
185 expect(result).toStrictEqual({ ok: 1 })
186 expect(error).toStrictEqual(
187 new TypeError('Found invalid object in transferList')
188 )
9ea61037
JB
189 })
190
7c0ba920 191 it('Verify that error handling is working properly:sync', async () => {
106744f7 192 const data = { f: 10 }
d46660cd 193 let taskError
8ebe6c30 194 errorPool.emitter.on(PoolEvents.taskError, (e) => {
d46660cd
JB
195 taskError = e
196 })
106744f7 197 let inError
198 try {
199 await errorPool.execute(data)
200 } catch (e) {
201 inError = e
202 }
7c0ba920
JB
203 expect(inError).toBeDefined()
204 expect(inError).toBeInstanceOf(Error)
205 expect(inError.message).toBeDefined()
8620fb25 206 expect(typeof inError.message === 'string').toBe(true)
985d0e79
JB
207 expect(inError.message).toBe('Error Message from ThreadWorker')
208 expect(taskError).toStrictEqual({
ff128cc9 209 name: 'default',
985d0e79
JB
210 message: new Error('Error Message from ThreadWorker'),
211 data
212 })
18482cec
JB
213 expect(
214 errorPool.workerNodes.some(
8ebe6c30 215 (workerNode) => workerNode.usage.tasks.failed === 1
18482cec
JB
216 )
217 ).toBe(true)
7c0ba920
JB
218 })
219
220 it('Verify that error handling is working properly:async', async () => {
221 const data = { f: 10 }
4f0b85b3 222 let taskError
8ebe6c30 223 asyncErrorPool.emitter.on(PoolEvents.taskError, (e) => {
4f0b85b3
JB
224 taskError = e
225 })
7c0ba920
JB
226 let inError
227 try {
228 await asyncErrorPool.execute(data)
229 } catch (e) {
230 inError = e
231 }
232 expect(inError).toBeDefined()
233 expect(inError).toBeInstanceOf(Error)
234 expect(inError.message).toBeDefined()
8620fb25 235 expect(typeof inError.message === 'string').toBe(true)
985d0e79
JB
236 expect(inError.message).toBe('Error Message from ThreadWorker:async')
237 expect(taskError).toStrictEqual({
ff128cc9 238 name: 'default',
985d0e79
JB
239 message: new Error('Error Message from ThreadWorker:async'),
240 data
241 })
18482cec
JB
242 expect(
243 asyncErrorPool.workerNodes.some(
8ebe6c30 244 (workerNode) => workerNode.usage.tasks.failed === 1
18482cec
JB
245 )
246 ).toBe(true)
106744f7 247 })
248
7784f548 249 it('Verify that async function is working properly', async () => {
250 const data = { f: 10 }
15e5141f 251 const startTime = performance.now()
7784f548 252 const result = await asyncPool.execute(data)
15e5141f 253 const usedTime = performance.now() - startTime
e1ffb94f 254 expect(result).toStrictEqual(data)
32d490eb 255 expect(usedTime).toBeGreaterThanOrEqual(2000)
7784f548 256 })
257
506c2a14 258 it('Shutdown test', async () => {
bac873bd 259 const exitPromise = waitWorkerEvents(pool, 'exit', numberOfThreads)
ef3891a3
JB
260 let poolDestroy = 0
261 pool.emitter.on(PoolEvents.destroy, () => ++poolDestroy)
1f9a5a44 262 await pool.destroy()
bdacc2d2
JB
263 const numberOfExitEvents = await exitPromise
264 expect(numberOfExitEvents).toBe(numberOfThreads)
ef3891a3 265 expect(poolDestroy).toBe(1)
506c2a14 266 })
267
90082c8c 268 it('Verify that thread pool options are checked', async () => {
f59e1027 269 const workerFilePath = './tests/worker-files/thread/testWorker.js'
90082c8c
JB
270 let pool1 = new FixedThreadPool(numberOfThreads, workerFilePath)
271 expect(pool1.opts.workerOptions).toBeUndefined()
272 await pool1.destroy()
273 pool1 = new FixedThreadPool(numberOfThreads, workerFilePath, {
274 workerOptions: {
275 env: { TEST: 'test' },
276 name: 'test'
277 }
278 })
279 expect(pool1.opts.workerOptions).toStrictEqual({
280 env: { TEST: 'test' },
281 name: 'test'
282 })
283 await pool1.destroy()
284 })
285
506c2a14 286 it('Should work even without opts in input', async () => {
76b1e974 287 const pool1 = new FixedThreadPool(
e1ffb94f 288 numberOfThreads,
76b1e974
S
289 './tests/worker-files/thread/testWorker.js'
290 )
6db75ad9 291 const res = await pool1.execute()
30b963d4 292 expect(res).toStrictEqual({ ok: 1 })
0e2503fc
JB
293 // We need to clean up the resources after our test
294 await pool1.destroy()
506c2a14 295 })
8d3782fa
JB
296
297 it('Verify that a pool with zero worker fails', async () => {
298 expect(
299 () => new FixedThreadPool(0, './tests/worker-files/thread/testWorker.js')
2431bdb4 300 ).toThrowError('Cannot instantiate a fixed pool with zero worker')
8d3782fa 301 })
506c2a14 302})