feat: conditional task performance computation at the worker level
[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(pool.workerChoiceStrategyContext.getTaskStatistics()).toStrictEqual({
197 runTime: true,
198 avgRunTime: true,
199 medRunTime: false,
200 waitTime: false,
201 avgWaitTime: false,
202 medWaitTime: false,
203 elu: false
204 })
205 pool.setWorkerChoiceStrategyOptions({ medRunTime: true })
206 expect(pool.opts.workerChoiceStrategyOptions).toStrictEqual({
207 medRunTime: true
208 })
209 for (const [, workerChoiceStrategy] of pool.workerChoiceStrategyContext
210 .workerChoiceStrategies) {
211 expect(workerChoiceStrategy.opts).toStrictEqual({ medRunTime: true })
212 }
213 expect(pool.workerChoiceStrategyContext.getTaskStatistics()).toStrictEqual({
214 runTime: true,
215 avgRunTime: false,
216 medRunTime: true,
217 waitTime: false,
218 avgWaitTime: false,
219 medWaitTime: false,
220 elu: false
221 })
222 pool.setWorkerChoiceStrategyOptions({ medRunTime: false })
223 expect(pool.opts.workerChoiceStrategyOptions).toStrictEqual({
224 medRunTime: false
225 })
226 for (const [, workerChoiceStrategy] of pool.workerChoiceStrategyContext
227 .workerChoiceStrategies) {
228 expect(workerChoiceStrategy.opts).toStrictEqual({ medRunTime: false })
229 }
230 expect(pool.workerChoiceStrategyContext.getTaskStatistics()).toStrictEqual({
231 runTime: true,
232 avgRunTime: true,
233 medRunTime: false,
234 waitTime: false,
235 avgWaitTime: false,
236 medWaitTime: false,
237 elu: false
238 })
239 await pool.destroy()
240 })
241
242 it('Verify that tasks queue can be enabled/disabled', async () => {
243 const pool = new FixedThreadPool(
244 numberOfWorkers,
245 './tests/worker-files/thread/testWorker.js'
246 )
247 expect(pool.opts.enableTasksQueue).toBe(false)
248 expect(pool.opts.tasksQueueOptions).toBeUndefined()
249 pool.enableTasksQueue(true)
250 expect(pool.opts.enableTasksQueue).toBe(true)
251 expect(pool.opts.tasksQueueOptions).toStrictEqual({ concurrency: 1 })
252 pool.enableTasksQueue(true, { concurrency: 2 })
253 expect(pool.opts.enableTasksQueue).toBe(true)
254 expect(pool.opts.tasksQueueOptions).toStrictEqual({ concurrency: 2 })
255 pool.enableTasksQueue(false)
256 expect(pool.opts.enableTasksQueue).toBe(false)
257 expect(pool.opts.tasksQueueOptions).toBeUndefined()
258 await pool.destroy()
259 })
260
261 it('Verify that tasks queue options can be set', async () => {
262 const pool = new FixedThreadPool(
263 numberOfWorkers,
264 './tests/worker-files/thread/testWorker.js',
265 { enableTasksQueue: true }
266 )
267 expect(pool.opts.tasksQueueOptions).toStrictEqual({ concurrency: 1 })
268 pool.setTasksQueueOptions({ concurrency: 2 })
269 expect(pool.opts.tasksQueueOptions).toStrictEqual({ concurrency: 2 })
270 expect(() => pool.setTasksQueueOptions({ concurrency: 0 })).toThrowError(
271 "Invalid worker tasks concurrency '0'"
272 )
273 await pool.destroy()
274 })
275
276 it('Verify that pool info is set', async () => {
277 let pool = new FixedThreadPool(
278 numberOfWorkers,
279 './tests/worker-files/thread/testWorker.js'
280 )
281 expect(pool.info).toStrictEqual({
282 type: PoolTypes.fixed,
283 worker: WorkerTypes.thread,
284 minSize: numberOfWorkers,
285 maxSize: numberOfWorkers,
286 workerNodes: numberOfWorkers,
287 idleWorkerNodes: numberOfWorkers,
288 busyWorkerNodes: 0,
289 runningTasks: 0,
290 queuedTasks: 0,
291 maxQueuedTasks: 0
292 })
293 await pool.destroy()
294 pool = new DynamicClusterPool(
295 numberOfWorkers,
296 numberOfWorkers * 2,
297 './tests/worker-files/thread/testWorker.js'
298 )
299 expect(pool.info).toStrictEqual({
300 type: PoolTypes.dynamic,
301 worker: WorkerTypes.cluster,
302 minSize: numberOfWorkers,
303 maxSize: numberOfWorkers * 2,
304 workerNodes: numberOfWorkers,
305 idleWorkerNodes: numberOfWorkers,
306 busyWorkerNodes: 0,
307 runningTasks: 0,
308 queuedTasks: 0,
309 maxQueuedTasks: 0
310 })
311 await pool.destroy()
312 })
313
314 it('Simulate worker not found', async () => {
315 const pool = new StubPoolWithRemoveAllWorker(
316 numberOfWorkers,
317 './tests/worker-files/cluster/testWorker.js',
318 {
319 errorHandler: e => console.error(e)
320 }
321 )
322 expect(pool.workerNodes.length).toBe(numberOfWorkers)
323 // Simulate worker not found.
324 pool.removeAllWorker()
325 expect(pool.workerNodes.length).toBe(0)
326 await pool.destroy()
327 })
328
329 it('Verify that worker pool tasks usage are initialized', async () => {
330 const pool = new FixedClusterPool(
331 numberOfWorkers,
332 './tests/worker-files/cluster/testWorker.js'
333 )
334 for (const workerNode of pool.workerNodes) {
335 expect(workerNode.tasksUsage).toStrictEqual({
336 ran: 0,
337 running: 0,
338 runTime: 0,
339 runTimeHistory: expect.any(CircularArray),
340 avgRunTime: 0,
341 medRunTime: 0,
342 waitTime: 0,
343 waitTimeHistory: expect.any(CircularArray),
344 avgWaitTime: 0,
345 medWaitTime: 0,
346 error: 0,
347 elu: undefined
348 })
349 }
350 await pool.destroy()
351 })
352
353 it('Verify that worker pool tasks queue are initialized', async () => {
354 const pool = new FixedClusterPool(
355 numberOfWorkers,
356 './tests/worker-files/cluster/testWorker.js'
357 )
358 for (const workerNode of pool.workerNodes) {
359 expect(workerNode.tasksQueue).toBeDefined()
360 expect(workerNode.tasksQueue).toBeInstanceOf(Queue)
361 expect(workerNode.tasksQueue.size).toBe(0)
362 }
363 await pool.destroy()
364 })
365
366 it('Verify that worker pool tasks usage are computed', async () => {
367 const pool = new FixedClusterPool(
368 numberOfWorkers,
369 './tests/worker-files/cluster/testWorker.js'
370 )
371 const promises = new Set()
372 const maxMultiplier = 2
373 for (let i = 0; i < numberOfWorkers * maxMultiplier; i++) {
374 promises.add(pool.execute())
375 }
376 for (const workerNode of pool.workerNodes) {
377 expect(workerNode.tasksUsage).toStrictEqual({
378 ran: 0,
379 running: maxMultiplier,
380 runTime: 0,
381 runTimeHistory: expect.any(CircularArray),
382 avgRunTime: 0,
383 medRunTime: 0,
384 waitTime: 0,
385 waitTimeHistory: expect.any(CircularArray),
386 avgWaitTime: 0,
387 medWaitTime: 0,
388 error: 0,
389 elu: undefined
390 })
391 }
392 await Promise.all(promises)
393 for (const workerNode of pool.workerNodes) {
394 expect(workerNode.tasksUsage).toStrictEqual({
395 ran: maxMultiplier,
396 running: 0,
397 runTime: 0,
398 runTimeHistory: expect.any(CircularArray),
399 avgRunTime: 0,
400 medRunTime: 0,
401 waitTime: 0,
402 waitTimeHistory: expect.any(CircularArray),
403 avgWaitTime: 0,
404 medWaitTime: 0,
405 error: 0,
406 elu: undefined
407 })
408 }
409 await pool.destroy()
410 })
411
412 it('Verify that worker pool tasks usage are reset at worker choice strategy change', async () => {
413 const pool = new DynamicThreadPool(
414 numberOfWorkers,
415 numberOfWorkers,
416 './tests/worker-files/thread/testWorker.js'
417 )
418 const promises = new Set()
419 const maxMultiplier = 2
420 for (let i = 0; i < numberOfWorkers * maxMultiplier; i++) {
421 promises.add(pool.execute())
422 }
423 await Promise.all(promises)
424 for (const workerNode of pool.workerNodes) {
425 expect(workerNode.tasksUsage).toStrictEqual({
426 ran: expect.any(Number),
427 running: 0,
428 runTime: 0,
429 runTimeHistory: expect.any(CircularArray),
430 avgRunTime: 0,
431 medRunTime: 0,
432 waitTime: 0,
433 waitTimeHistory: expect.any(CircularArray),
434 avgWaitTime: 0,
435 medWaitTime: 0,
436 error: 0,
437 elu: undefined
438 })
439 expect(workerNode.tasksUsage.ran).toBeGreaterThan(0)
440 expect(workerNode.tasksUsage.ran).toBeLessThanOrEqual(maxMultiplier)
441 }
442 pool.setWorkerChoiceStrategy(WorkerChoiceStrategies.FAIR_SHARE)
443 for (const workerNode of pool.workerNodes) {
444 expect(workerNode.tasksUsage).toStrictEqual({
445 ran: 0,
446 running: 0,
447 runTime: 0,
448 runTimeHistory: expect.any(CircularArray),
449 avgRunTime: 0,
450 medRunTime: 0,
451 waitTime: 0,
452 waitTimeHistory: expect.any(CircularArray),
453 avgWaitTime: 0,
454 medWaitTime: 0,
455 error: 0,
456 elu: undefined
457 })
458 expect(workerNode.tasksUsage.runTimeHistory.length).toBe(0)
459 expect(workerNode.tasksUsage.waitTimeHistory.length).toBe(0)
460 }
461 await pool.destroy()
462 })
463
464 it("Verify that pool event emitter 'full' event can register a callback", async () => {
465 const pool = new DynamicThreadPool(
466 numberOfWorkers,
467 numberOfWorkers,
468 './tests/worker-files/thread/testWorker.js'
469 )
470 const promises = new Set()
471 let poolFull = 0
472 pool.emitter.on(PoolEvents.full, () => ++poolFull)
473 for (let i = 0; i < numberOfWorkers * 2; i++) {
474 promises.add(pool.execute())
475 }
476 await Promise.all(promises)
477 // The `full` event is triggered when the number of submitted tasks at once reach the max number of workers in the dynamic pool.
478 // So in total numberOfWorkers * 2 times for a loop submitting up to numberOfWorkers * 2 tasks to the dynamic pool with min = max = numberOfWorkers.
479 expect(poolFull).toBe(numberOfWorkers * 2)
480 await pool.destroy()
481 })
482
483 it("Verify that pool event emitter 'busy' event can register a callback", async () => {
484 const pool = new FixedThreadPool(
485 numberOfWorkers,
486 './tests/worker-files/thread/testWorker.js'
487 )
488 const promises = new Set()
489 let poolBusy = 0
490 pool.emitter.on(PoolEvents.busy, () => ++poolBusy)
491 for (let i = 0; i < numberOfWorkers * 2; i++) {
492 promises.add(pool.execute())
493 }
494 await Promise.all(promises)
495 // The `busy` event is triggered when the number of submitted tasks at once reach the number of fixed pool workers.
496 // So in total numberOfWorkers + 1 times for a loop submitting up to numberOfWorkers * 2 tasks to the fixed pool.
497 expect(poolBusy).toBe(numberOfWorkers + 1)
498 await pool.destroy()
499 })
500
501 it('Verify that multiple tasks worker is working', async () => {
502 const pool = new DynamicClusterPool(
503 numberOfWorkers,
504 numberOfWorkers * 2,
505 './tests/worker-files/cluster/testMultiTasksWorker.js'
506 )
507 const data = { n: 10 }
508 const result0 = await pool.execute(data)
509 expect(result0).toBe(false)
510 const result1 = await pool.execute(data, 'jsonIntegerSerialization')
511 expect(result1).toBe(false)
512 const result2 = await pool.execute(data, 'factorial')
513 expect(result2).toBe(3628800)
514 const result3 = await pool.execute(data, 'fibonacci')
515 expect(result3).toBe(89)
516 })
517 })