b88e489b7f05065b6ad780f454789b853cb8e85f
[poolifier.git] / tests / pools / abstract / abstract-pool.test.js
1 const { expect } = require('expect')
2 const {
3 DynamicClusterPool,
4 DynamicThreadPool,
5 FixedClusterPool,
6 FixedThreadPool,
7 PoolEvents,
8 WorkerChoiceStrategies,
9 PoolTypes,
10 WorkerTypes
11 } = require('../../../lib')
12 const { CircularArray } = require('../../../lib/circular-array')
13 const { Queue } = require('../../../lib/queue')
14
15 describe('Abstract pool test suite', () => {
16 const numberOfWorkers = 2
17 class StubPoolWithRemoveAllWorker extends FixedThreadPool {
18 removeAllWorker () {
19 this.workerNodes = []
20 this.promiseResponseMap.clear()
21 }
22 }
23 class StubPoolWithIsMain extends FixedThreadPool {
24 isMain () {
25 return false
26 }
27 }
28
29 it('Simulate pool creation from a non main thread/process', () => {
30 expect(
31 () =>
32 new StubPoolWithIsMain(
33 numberOfWorkers,
34 './tests/worker-files/thread/testWorker.js',
35 {
36 errorHandler: e => console.error(e)
37 }
38 )
39 ).toThrowError('Cannot start a pool from a worker!')
40 })
41
42 it('Verify that filePath is checked', () => {
43 const expectedError = new Error(
44 'Please specify a file with a worker implementation'
45 )
46 expect(() => new FixedThreadPool(numberOfWorkers)).toThrowError(
47 expectedError
48 )
49 expect(() => new FixedThreadPool(numberOfWorkers, '')).toThrowError(
50 expectedError
51 )
52 })
53
54 it('Verify that numberOfWorkers is checked', () => {
55 expect(() => new FixedThreadPool()).toThrowError(
56 'Cannot instantiate a pool without specifying the number of workers'
57 )
58 })
59
60 it('Verify that a negative number of workers is checked', () => {
61 expect(
62 () =>
63 new FixedClusterPool(-1, './tests/worker-files/cluster/testWorker.js')
64 ).toThrowError(
65 new RangeError(
66 'Cannot instantiate a pool with a negative number of workers'
67 )
68 )
69 })
70
71 it('Verify that a non integer number of workers is checked', () => {
72 expect(
73 () =>
74 new FixedThreadPool(0.25, './tests/worker-files/thread/testWorker.js')
75 ).toThrowError(
76 new TypeError(
77 'Cannot instantiate a pool with a non safe integer number of workers'
78 )
79 )
80 })
81
82 it('Verify that pool options are checked', async () => {
83 let pool = new FixedThreadPool(
84 numberOfWorkers,
85 './tests/worker-files/thread/testWorker.js'
86 )
87 expect(pool.emitter).toBeDefined()
88 expect(pool.opts.enableEvents).toBe(true)
89 expect(pool.opts.restartWorkerOnError).toBe(true)
90 expect(pool.opts.enableTasksQueue).toBe(false)
91 expect(pool.opts.tasksQueueOptions).toBeUndefined()
92 expect(pool.opts.workerChoiceStrategy).toBe(
93 WorkerChoiceStrategies.ROUND_ROBIN
94 )
95 expect(pool.opts.workerChoiceStrategyOptions).toStrictEqual({
96 medRunTime: false,
97 medWaitTime: false
98 })
99 expect(pool.opts.messageHandler).toBeUndefined()
100 expect(pool.opts.errorHandler).toBeUndefined()
101 expect(pool.opts.onlineHandler).toBeUndefined()
102 expect(pool.opts.exitHandler).toBeUndefined()
103 await pool.destroy()
104 const testHandler = () => console.log('test handler executed')
105 pool = new FixedThreadPool(
106 numberOfWorkers,
107 './tests/worker-files/thread/testWorker.js',
108 {
109 workerChoiceStrategy: WorkerChoiceStrategies.LEAST_USED,
110 workerChoiceStrategyOptions: {
111 medRunTime: true,
112 weights: { 0: 300, 1: 200 }
113 },
114 enableEvents: false,
115 restartWorkerOnError: false,
116 enableTasksQueue: true,
117 tasksQueueOptions: { concurrency: 2 },
118 messageHandler: testHandler,
119 errorHandler: testHandler,
120 onlineHandler: testHandler,
121 exitHandler: testHandler
122 }
123 )
124 expect(pool.emitter).toBeUndefined()
125 expect(pool.opts.enableEvents).toBe(false)
126 expect(pool.opts.restartWorkerOnError).toBe(false)
127 expect(pool.opts.enableTasksQueue).toBe(true)
128 expect(pool.opts.tasksQueueOptions).toStrictEqual({ concurrency: 2 })
129 expect(pool.opts.workerChoiceStrategy).toBe(
130 WorkerChoiceStrategies.LEAST_USED
131 )
132 expect(pool.opts.workerChoiceStrategyOptions).toStrictEqual({
133 medRunTime: true,
134 weights: { 0: 300, 1: 200 }
135 })
136 expect(pool.opts.messageHandler).toStrictEqual(testHandler)
137 expect(pool.opts.errorHandler).toStrictEqual(testHandler)
138 expect(pool.opts.onlineHandler).toStrictEqual(testHandler)
139 expect(pool.opts.exitHandler).toStrictEqual(testHandler)
140 await pool.destroy()
141 })
142
143 it('Verify that pool options are validated', async () => {
144 expect(
145 () =>
146 new FixedThreadPool(
147 numberOfWorkers,
148 './tests/worker-files/thread/testWorker.js',
149 {
150 enableTasksQueue: true,
151 tasksQueueOptions: { concurrency: 0 }
152 }
153 )
154 ).toThrowError("Invalid worker tasks concurrency '0'")
155 expect(
156 () =>
157 new FixedThreadPool(
158 numberOfWorkers,
159 './tests/worker-files/thread/testWorker.js',
160 {
161 workerChoiceStrategy: 'invalidStrategy'
162 }
163 )
164 ).toThrowError("Invalid worker choice strategy 'invalidStrategy'")
165 expect(
166 () =>
167 new FixedThreadPool(
168 numberOfWorkers,
169 './tests/worker-files/thread/testWorker.js',
170 {
171 workerChoiceStrategyOptions: { weights: {} }
172 }
173 )
174 ).toThrowError(
175 'Invalid worker choice strategy options: must have a weight for each worker node'
176 )
177 })
178
179 it('Verify that worker choice strategy options can be set', async () => {
180 const pool = new FixedThreadPool(
181 numberOfWorkers,
182 './tests/worker-files/thread/testWorker.js',
183 { workerChoiceStrategy: WorkerChoiceStrategies.FAIR_SHARE }
184 )
185 expect(pool.opts.workerChoiceStrategyOptions).toStrictEqual({
186 medRunTime: false,
187 medWaitTime: false
188 })
189 for (const [, workerChoiceStrategy] of pool.workerChoiceStrategyContext
190 .workerChoiceStrategies) {
191 expect(workerChoiceStrategy.opts).toStrictEqual({
192 medRunTime: false,
193 medWaitTime: false
194 })
195 }
196 expect(
197 pool.workerChoiceStrategyContext.getRequiredStatistics()
198 ).toStrictEqual({
199 runTime: true,
200 avgRunTime: true,
201 medRunTime: false,
202 waitTime: false,
203 avgWaitTime: false,
204 medWaitTime: false,
205 elu: false
206 })
207 pool.setWorkerChoiceStrategyOptions({ medRunTime: true })
208 expect(pool.opts.workerChoiceStrategyOptions).toStrictEqual({
209 medRunTime: true
210 })
211 for (const [, workerChoiceStrategy] of pool.workerChoiceStrategyContext
212 .workerChoiceStrategies) {
213 expect(workerChoiceStrategy.opts).toStrictEqual({ medRunTime: true })
214 }
215 expect(
216 pool.workerChoiceStrategyContext.getRequiredStatistics()
217 ).toStrictEqual({
218 runTime: true,
219 avgRunTime: false,
220 medRunTime: true,
221 waitTime: false,
222 avgWaitTime: false,
223 medWaitTime: false,
224 elu: false
225 })
226 pool.setWorkerChoiceStrategyOptions({ medRunTime: false })
227 expect(pool.opts.workerChoiceStrategyOptions).toStrictEqual({
228 medRunTime: false
229 })
230 for (const [, workerChoiceStrategy] of pool.workerChoiceStrategyContext
231 .workerChoiceStrategies) {
232 expect(workerChoiceStrategy.opts).toStrictEqual({ medRunTime: false })
233 }
234 expect(
235 pool.workerChoiceStrategyContext.getRequiredStatistics()
236 ).toStrictEqual({
237 runTime: true,
238 avgRunTime: true,
239 medRunTime: false,
240 waitTime: false,
241 avgWaitTime: false,
242 medWaitTime: false,
243 elu: false
244 })
245 await pool.destroy()
246 })
247
248 it('Verify that tasks queue can be enabled/disabled', async () => {
249 const pool = new FixedThreadPool(
250 numberOfWorkers,
251 './tests/worker-files/thread/testWorker.js'
252 )
253 expect(pool.opts.enableTasksQueue).toBe(false)
254 expect(pool.opts.tasksQueueOptions).toBeUndefined()
255 pool.enableTasksQueue(true)
256 expect(pool.opts.enableTasksQueue).toBe(true)
257 expect(pool.opts.tasksQueueOptions).toStrictEqual({ concurrency: 1 })
258 pool.enableTasksQueue(true, { concurrency: 2 })
259 expect(pool.opts.enableTasksQueue).toBe(true)
260 expect(pool.opts.tasksQueueOptions).toStrictEqual({ concurrency: 2 })
261 pool.enableTasksQueue(false)
262 expect(pool.opts.enableTasksQueue).toBe(false)
263 expect(pool.opts.tasksQueueOptions).toBeUndefined()
264 await pool.destroy()
265 })
266
267 it('Verify that tasks queue options can be set', async () => {
268 const pool = new FixedThreadPool(
269 numberOfWorkers,
270 './tests/worker-files/thread/testWorker.js',
271 { enableTasksQueue: true }
272 )
273 expect(pool.opts.tasksQueueOptions).toStrictEqual({ concurrency: 1 })
274 pool.setTasksQueueOptions({ concurrency: 2 })
275 expect(pool.opts.tasksQueueOptions).toStrictEqual({ concurrency: 2 })
276 expect(() => pool.setTasksQueueOptions({ concurrency: 0 })).toThrowError(
277 "Invalid worker tasks concurrency '0'"
278 )
279 await pool.destroy()
280 })
281
282 it('Verify that pool info is set', async () => {
283 let pool = new FixedThreadPool(
284 numberOfWorkers,
285 './tests/worker-files/thread/testWorker.js'
286 )
287 expect(pool.info).toStrictEqual({
288 type: PoolTypes.fixed,
289 worker: WorkerTypes.thread,
290 minSize: numberOfWorkers,
291 maxSize: numberOfWorkers,
292 workerNodes: numberOfWorkers,
293 idleWorkerNodes: numberOfWorkers,
294 busyWorkerNodes: 0,
295 runningTasks: 0,
296 queuedTasks: 0,
297 maxQueuedTasks: 0
298 })
299 await pool.destroy()
300 pool = new DynamicClusterPool(
301 numberOfWorkers,
302 numberOfWorkers * 2,
303 './tests/worker-files/thread/testWorker.js'
304 )
305 expect(pool.info).toStrictEqual({
306 type: PoolTypes.dynamic,
307 worker: WorkerTypes.cluster,
308 minSize: numberOfWorkers,
309 maxSize: numberOfWorkers * 2,
310 workerNodes: numberOfWorkers,
311 idleWorkerNodes: numberOfWorkers,
312 busyWorkerNodes: 0,
313 runningTasks: 0,
314 queuedTasks: 0,
315 maxQueuedTasks: 0
316 })
317 await pool.destroy()
318 })
319
320 it('Simulate worker not found', async () => {
321 const pool = new StubPoolWithRemoveAllWorker(
322 numberOfWorkers,
323 './tests/worker-files/cluster/testWorker.js',
324 {
325 errorHandler: e => console.error(e)
326 }
327 )
328 expect(pool.workerNodes.length).toBe(numberOfWorkers)
329 // Simulate worker not found.
330 pool.removeAllWorker()
331 expect(pool.workerNodes.length).toBe(0)
332 await pool.destroy()
333 })
334
335 it('Verify that worker pool tasks usage are initialized', async () => {
336 const pool = new FixedClusterPool(
337 numberOfWorkers,
338 './tests/worker-files/cluster/testWorker.js'
339 )
340 for (const workerNode of pool.workerNodes) {
341 expect(workerNode.tasksUsage).toStrictEqual({
342 ran: 0,
343 running: 0,
344 runTime: 0,
345 runTimeHistory: expect.any(CircularArray),
346 avgRunTime: 0,
347 medRunTime: 0,
348 waitTime: 0,
349 waitTimeHistory: expect.any(CircularArray),
350 avgWaitTime: 0,
351 medWaitTime: 0,
352 error: 0,
353 elu: undefined
354 })
355 }
356 await pool.destroy()
357 })
358
359 it('Verify that worker pool tasks queue are initialized', async () => {
360 const pool = new FixedClusterPool(
361 numberOfWorkers,
362 './tests/worker-files/cluster/testWorker.js'
363 )
364 for (const workerNode of pool.workerNodes) {
365 expect(workerNode.tasksQueue).toBeDefined()
366 expect(workerNode.tasksQueue).toBeInstanceOf(Queue)
367 expect(workerNode.tasksQueue.size).toBe(0)
368 }
369 await pool.destroy()
370 })
371
372 it('Verify that worker pool tasks usage are computed', async () => {
373 const pool = new FixedClusterPool(
374 numberOfWorkers,
375 './tests/worker-files/cluster/testWorker.js'
376 )
377 const promises = new Set()
378 const maxMultiplier = 2
379 for (let i = 0; i < numberOfWorkers * maxMultiplier; i++) {
380 promises.add(pool.execute())
381 }
382 for (const workerNode of pool.workerNodes) {
383 expect(workerNode.tasksUsage).toStrictEqual({
384 ran: 0,
385 running: maxMultiplier,
386 runTime: 0,
387 runTimeHistory: expect.any(CircularArray),
388 avgRunTime: 0,
389 medRunTime: 0,
390 waitTime: 0,
391 waitTimeHistory: expect.any(CircularArray),
392 avgWaitTime: 0,
393 medWaitTime: 0,
394 error: 0,
395 elu: undefined
396 })
397 }
398 await Promise.all(promises)
399 for (const workerNode of pool.workerNodes) {
400 expect(workerNode.tasksUsage).toStrictEqual({
401 ran: maxMultiplier,
402 running: 0,
403 runTime: 0,
404 runTimeHistory: expect.any(CircularArray),
405 avgRunTime: 0,
406 medRunTime: 0,
407 waitTime: 0,
408 waitTimeHistory: expect.any(CircularArray),
409 avgWaitTime: 0,
410 medWaitTime: 0,
411 error: 0,
412 elu: undefined
413 })
414 }
415 await pool.destroy()
416 })
417
418 it('Verify that worker pool tasks usage are reset at worker choice strategy change', async () => {
419 const pool = new DynamicThreadPool(
420 numberOfWorkers,
421 numberOfWorkers,
422 './tests/worker-files/thread/testWorker.js'
423 )
424 const promises = new Set()
425 const maxMultiplier = 2
426 for (let i = 0; i < numberOfWorkers * maxMultiplier; i++) {
427 promises.add(pool.execute())
428 }
429 await Promise.all(promises)
430 for (const workerNode of pool.workerNodes) {
431 expect(workerNode.tasksUsage).toStrictEqual({
432 ran: expect.any(Number),
433 running: 0,
434 runTime: 0,
435 runTimeHistory: expect.any(CircularArray),
436 avgRunTime: 0,
437 medRunTime: 0,
438 waitTime: 0,
439 waitTimeHistory: expect.any(CircularArray),
440 avgWaitTime: 0,
441 medWaitTime: 0,
442 error: 0,
443 elu: undefined
444 })
445 expect(workerNode.tasksUsage.ran).toBeGreaterThan(0)
446 expect(workerNode.tasksUsage.ran).toBeLessThanOrEqual(maxMultiplier)
447 }
448 pool.setWorkerChoiceStrategy(WorkerChoiceStrategies.FAIR_SHARE)
449 for (const workerNode of pool.workerNodes) {
450 expect(workerNode.tasksUsage).toStrictEqual({
451 ran: 0,
452 running: 0,
453 runTime: 0,
454 runTimeHistory: expect.any(CircularArray),
455 avgRunTime: 0,
456 medRunTime: 0,
457 waitTime: 0,
458 waitTimeHistory: expect.any(CircularArray),
459 avgWaitTime: 0,
460 medWaitTime: 0,
461 error: 0,
462 elu: undefined
463 })
464 expect(workerNode.tasksUsage.runTimeHistory.length).toBe(0)
465 expect(workerNode.tasksUsage.waitTimeHistory.length).toBe(0)
466 }
467 await pool.destroy()
468 })
469
470 it("Verify that pool event emitter 'full' event can register a callback", async () => {
471 const pool = new DynamicThreadPool(
472 numberOfWorkers,
473 numberOfWorkers,
474 './tests/worker-files/thread/testWorker.js'
475 )
476 const promises = new Set()
477 let poolFull = 0
478 pool.emitter.on(PoolEvents.full, () => ++poolFull)
479 for (let i = 0; i < numberOfWorkers * 2; i++) {
480 promises.add(pool.execute())
481 }
482 await Promise.all(promises)
483 // The `full` event is triggered when the number of submitted tasks at once reach the max number of workers in the dynamic pool.
484 // So in total numberOfWorkers * 2 times for a loop submitting up to numberOfWorkers * 2 tasks to the dynamic pool with min = max = numberOfWorkers.
485 expect(poolFull).toBe(numberOfWorkers * 2)
486 await pool.destroy()
487 })
488
489 it("Verify that pool event emitter 'busy' event can register a callback", async () => {
490 const pool = new FixedThreadPool(
491 numberOfWorkers,
492 './tests/worker-files/thread/testWorker.js'
493 )
494 const promises = new Set()
495 let poolBusy = 0
496 pool.emitter.on(PoolEvents.busy, () => ++poolBusy)
497 for (let i = 0; i < numberOfWorkers * 2; i++) {
498 promises.add(pool.execute())
499 }
500 await Promise.all(promises)
501 // The `busy` event is triggered when the number of submitted tasks at once reach the number of fixed pool workers.
502 // So in total numberOfWorkers + 1 times for a loop submitting up to numberOfWorkers * 2 tasks to the fixed pool.
503 expect(poolBusy).toBe(numberOfWorkers + 1)
504 await pool.destroy()
505 })
506
507 it('Verify that multiple tasks worker is working', async () => {
508 const pool = new DynamicClusterPool(
509 numberOfWorkers,
510 numberOfWorkers * 2,
511 './tests/worker-files/cluster/testMultiTasksWorker.js'
512 )
513 const data = { n: 10 }
514 const result0 = await pool.execute(data)
515 expect(result0).toBe(false)
516 const result1 = await pool.execute(data, 'jsonIntegerSerialization')
517 expect(result1).toBe(false)
518 const result2 = await pool.execute(data, 'factorial')
519 expect(result2).toBe(3628800)
520 const result3 = await pool.execute(data, 'fibonacci')
521 expect(result3).toBe(89)
522 })
523 })