perf: optimize tasks stealing in corner case
[poolifier.git] / tests / pools / abstract-pool.test.mjs
... / ...
CommitLineData
1import { EventEmitterAsyncResource } from 'node:events'
2import { dirname, join } from 'node:path'
3import { readFileSync } from 'node:fs'
4import { fileURLToPath } from 'node:url'
5import { expect } from 'expect'
6import { restore, stub } from 'sinon'
7import {
8 DynamicClusterPool,
9 DynamicThreadPool,
10 FixedClusterPool,
11 FixedThreadPool,
12 PoolEvents,
13 PoolTypes,
14 WorkerChoiceStrategies,
15 WorkerTypes
16} from '../../lib/index.js'
17import { CircularArray } from '../../lib/circular-array.js'
18import { Deque } from '../../lib/deque.js'
19import { DEFAULT_TASK_NAME } from '../../lib/utils.js'
20import { waitPoolEvents } from '../test-utils.js'
21import { WorkerNode } from '../../lib/pools/worker-node.js'
22
23describe('Abstract pool test suite', () => {
24 const version = JSON.parse(
25 readFileSync(
26 join(dirname(fileURLToPath(import.meta.url)), '../..', 'package.json'),
27 'utf8'
28 )
29 ).version
30 const numberOfWorkers = 2
31 class StubPoolWithIsMain extends FixedThreadPool {
32 isMain () {
33 return false
34 }
35 }
36
37 afterEach(() => {
38 restore()
39 })
40
41 it('Verify that pool can be created and destroyed', async () => {
42 const pool = new FixedThreadPool(
43 numberOfWorkers,
44 './tests/worker-files/thread/testWorker.mjs'
45 )
46 expect(pool).toBeInstanceOf(FixedThreadPool)
47 await pool.destroy()
48 })
49
50 it('Verify that pool cannot be created from a non main thread/process', () => {
51 expect(
52 () =>
53 new StubPoolWithIsMain(
54 numberOfWorkers,
55 './tests/worker-files/thread/testWorker.mjs',
56 {
57 errorHandler: e => console.error(e)
58 }
59 )
60 ).toThrow(
61 new Error(
62 'Cannot start a pool from a worker with the same type as the pool'
63 )
64 )
65 })
66
67 it('Verify that pool statuses properties are set', async () => {
68 const pool = new FixedThreadPool(
69 numberOfWorkers,
70 './tests/worker-files/thread/testWorker.mjs'
71 )
72 expect(pool.started).toBe(true)
73 expect(pool.starting).toBe(false)
74 expect(pool.destroying).toBe(false)
75 await pool.destroy()
76 })
77
78 it('Verify that filePath is checked', () => {
79 expect(() => new FixedThreadPool(numberOfWorkers)).toThrow(
80 new Error("Cannot find the worker file 'undefined'")
81 )
82 expect(
83 () => new FixedThreadPool(numberOfWorkers, './dummyWorker.ts')
84 ).toThrow(new Error("Cannot find the worker file './dummyWorker.ts'"))
85 })
86
87 it('Verify that numberOfWorkers is checked', () => {
88 expect(
89 () =>
90 new FixedThreadPool(
91 undefined,
92 './tests/worker-files/thread/testWorker.mjs'
93 )
94 ).toThrow(
95 new Error(
96 'Cannot instantiate a pool without specifying the number of workers'
97 )
98 )
99 })
100
101 it('Verify that a negative number of workers is checked', () => {
102 expect(
103 () =>
104 new FixedClusterPool(-1, './tests/worker-files/cluster/testWorker.js')
105 ).toThrow(
106 new RangeError(
107 'Cannot instantiate a pool with a negative number of workers'
108 )
109 )
110 })
111
112 it('Verify that a non integer number of workers is checked', () => {
113 expect(
114 () =>
115 new FixedThreadPool(0.25, './tests/worker-files/thread/testWorker.mjs')
116 ).toThrow(
117 new TypeError(
118 'Cannot instantiate a pool with a non safe integer number of workers'
119 )
120 )
121 })
122
123 it('Verify that dynamic pool sizing is checked', () => {
124 expect(
125 () =>
126 new DynamicClusterPool(
127 1,
128 undefined,
129 './tests/worker-files/cluster/testWorker.js'
130 )
131 ).toThrow(
132 new TypeError(
133 'Cannot instantiate a dynamic pool without specifying the maximum pool size'
134 )
135 )
136 expect(
137 () =>
138 new DynamicThreadPool(
139 0.5,
140 1,
141 './tests/worker-files/thread/testWorker.mjs'
142 )
143 ).toThrow(
144 new TypeError(
145 'Cannot instantiate a pool with a non safe integer number of workers'
146 )
147 )
148 expect(
149 () =>
150 new DynamicClusterPool(
151 0,
152 0.5,
153 './tests/worker-files/cluster/testWorker.js'
154 )
155 ).toThrow(
156 new TypeError(
157 'Cannot instantiate a dynamic pool with a non safe integer maximum pool size'
158 )
159 )
160 expect(
161 () =>
162 new DynamicThreadPool(
163 2,
164 1,
165 './tests/worker-files/thread/testWorker.mjs'
166 )
167 ).toThrow(
168 new RangeError(
169 'Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size'
170 )
171 )
172 expect(
173 () =>
174 new DynamicThreadPool(
175 0,
176 0,
177 './tests/worker-files/thread/testWorker.mjs'
178 )
179 ).toThrow(
180 new RangeError(
181 'Cannot instantiate a dynamic pool with a maximum pool size equal to zero'
182 )
183 )
184 expect(
185 () =>
186 new DynamicClusterPool(
187 1,
188 1,
189 './tests/worker-files/cluster/testWorker.js'
190 )
191 ).toThrow(
192 new RangeError(
193 'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
194 )
195 )
196 })
197
198 it('Verify that pool options are checked', async () => {
199 let pool = new FixedThreadPool(
200 numberOfWorkers,
201 './tests/worker-files/thread/testWorker.mjs'
202 )
203 expect(pool.emitter).toBeInstanceOf(EventEmitterAsyncResource)
204 expect(pool.opts).toStrictEqual({
205 startWorkers: true,
206 enableEvents: true,
207 restartWorkerOnError: true,
208 enableTasksQueue: false,
209 workerChoiceStrategy: WorkerChoiceStrategies.ROUND_ROBIN,
210 workerChoiceStrategyOptions: {
211 retries: 6,
212 runTime: { median: false },
213 waitTime: { median: false },
214 elu: { median: false }
215 }
216 })
217 expect(pool.workerChoiceStrategyContext.opts).toStrictEqual({
218 retries: 6,
219 runTime: { median: false },
220 waitTime: { median: false },
221 elu: { median: false }
222 })
223 for (const [, workerChoiceStrategy] of pool.workerChoiceStrategyContext
224 .workerChoiceStrategies) {
225 expect(workerChoiceStrategy.opts).toStrictEqual({
226 retries: 6,
227 runTime: { median: false },
228 waitTime: { median: false },
229 elu: { median: false }
230 })
231 }
232 await pool.destroy()
233 const testHandler = () => console.info('test handler executed')
234 pool = new FixedThreadPool(
235 numberOfWorkers,
236 './tests/worker-files/thread/testWorker.mjs',
237 {
238 workerChoiceStrategy: WorkerChoiceStrategies.LEAST_USED,
239 workerChoiceStrategyOptions: {
240 runTime: { median: true },
241 weights: { 0: 300, 1: 200 }
242 },
243 enableEvents: false,
244 restartWorkerOnError: false,
245 enableTasksQueue: true,
246 tasksQueueOptions: { concurrency: 2 },
247 messageHandler: testHandler,
248 errorHandler: testHandler,
249 onlineHandler: testHandler,
250 exitHandler: testHandler
251 }
252 )
253 expect(pool.emitter).toBeUndefined()
254 expect(pool.opts).toStrictEqual({
255 startWorkers: true,
256 enableEvents: false,
257 restartWorkerOnError: false,
258 enableTasksQueue: true,
259 tasksQueueOptions: {
260 concurrency: 2,
261 size: Math.pow(numberOfWorkers, 2),
262 taskStealing: true,
263 tasksStealingOnBackPressure: true
264 },
265 workerChoiceStrategy: WorkerChoiceStrategies.LEAST_USED,
266 workerChoiceStrategyOptions: {
267 retries: 6,
268 runTime: { median: true },
269 waitTime: { median: false },
270 elu: { median: false },
271 weights: { 0: 300, 1: 200 }
272 },
273 onlineHandler: testHandler,
274 messageHandler: testHandler,
275 errorHandler: testHandler,
276 exitHandler: testHandler
277 })
278 expect(pool.workerChoiceStrategyContext.opts).toStrictEqual({
279 retries: 6,
280 runTime: { median: true },
281 waitTime: { median: false },
282 elu: { median: false },
283 weights: { 0: 300, 1: 200 }
284 })
285 for (const [, workerChoiceStrategy] of pool.workerChoiceStrategyContext
286 .workerChoiceStrategies) {
287 expect(workerChoiceStrategy.opts).toStrictEqual({
288 retries: 6,
289 runTime: { median: true },
290 waitTime: { median: false },
291 elu: { median: false },
292 weights: { 0: 300, 1: 200 }
293 })
294 }
295 await pool.destroy()
296 })
297
298 it('Verify that pool options are validated', () => {
299 expect(
300 () =>
301 new FixedThreadPool(
302 numberOfWorkers,
303 './tests/worker-files/thread/testWorker.mjs',
304 {
305 workerChoiceStrategy: 'invalidStrategy'
306 }
307 )
308 ).toThrow(new Error("Invalid worker choice strategy 'invalidStrategy'"))
309 expect(
310 () =>
311 new FixedThreadPool(
312 numberOfWorkers,
313 './tests/worker-files/thread/testWorker.mjs',
314 {
315 workerChoiceStrategyOptions: {
316 retries: 'invalidChoiceRetries'
317 }
318 }
319 )
320 ).toThrow(
321 new TypeError(
322 'Invalid worker choice strategy options: retries must be an integer'
323 )
324 )
325 expect(
326 () =>
327 new FixedThreadPool(
328 numberOfWorkers,
329 './tests/worker-files/thread/testWorker.mjs',
330 {
331 workerChoiceStrategyOptions: {
332 retries: -1
333 }
334 }
335 )
336 ).toThrow(
337 new RangeError(
338 "Invalid worker choice strategy options: retries '-1' must be greater or equal than zero"
339 )
340 )
341 expect(
342 () =>
343 new FixedThreadPool(
344 numberOfWorkers,
345 './tests/worker-files/thread/testWorker.mjs',
346 {
347 workerChoiceStrategyOptions: { weights: {} }
348 }
349 )
350 ).toThrow(
351 new Error(
352 'Invalid worker choice strategy options: must have a weight for each worker node'
353 )
354 )
355 expect(
356 () =>
357 new FixedThreadPool(
358 numberOfWorkers,
359 './tests/worker-files/thread/testWorker.mjs',
360 {
361 workerChoiceStrategyOptions: { measurement: 'invalidMeasurement' }
362 }
363 )
364 ).toThrow(
365 new Error(
366 "Invalid worker choice strategy options: invalid measurement 'invalidMeasurement'"
367 )
368 )
369 expect(
370 () =>
371 new FixedThreadPool(
372 numberOfWorkers,
373 './tests/worker-files/thread/testWorker.mjs',
374 {
375 enableTasksQueue: true,
376 tasksQueueOptions: 'invalidTasksQueueOptions'
377 }
378 )
379 ).toThrow(
380 new TypeError('Invalid tasks queue options: must be a plain object')
381 )
382 expect(
383 () =>
384 new FixedThreadPool(
385 numberOfWorkers,
386 './tests/worker-files/thread/testWorker.mjs',
387 {
388 enableTasksQueue: true,
389 tasksQueueOptions: { concurrency: 0 }
390 }
391 )
392 ).toThrow(
393 new RangeError(
394 'Invalid worker node tasks concurrency: 0 is a negative integer or zero'
395 )
396 )
397 expect(
398 () =>
399 new FixedThreadPool(
400 numberOfWorkers,
401 './tests/worker-files/thread/testWorker.mjs',
402 {
403 enableTasksQueue: true,
404 tasksQueueOptions: { concurrency: -1 }
405 }
406 )
407 ).toThrow(
408 new RangeError(
409 'Invalid worker node tasks concurrency: -1 is a negative integer or zero'
410 )
411 )
412 expect(
413 () =>
414 new FixedThreadPool(
415 numberOfWorkers,
416 './tests/worker-files/thread/testWorker.mjs',
417 {
418 enableTasksQueue: true,
419 tasksQueueOptions: { concurrency: 0.2 }
420 }
421 )
422 ).toThrow(
423 new TypeError('Invalid worker node tasks concurrency: must be an integer')
424 )
425 expect(
426 () =>
427 new FixedThreadPool(
428 numberOfWorkers,
429 './tests/worker-files/thread/testWorker.mjs',
430 {
431 enableTasksQueue: true,
432 tasksQueueOptions: { size: 0 }
433 }
434 )
435 ).toThrow(
436 new RangeError(
437 'Invalid worker node tasks queue size: 0 is a negative integer or zero'
438 )
439 )
440 expect(
441 () =>
442 new FixedThreadPool(
443 numberOfWorkers,
444 './tests/worker-files/thread/testWorker.mjs',
445 {
446 enableTasksQueue: true,
447 tasksQueueOptions: { size: -1 }
448 }
449 )
450 ).toThrow(
451 new RangeError(
452 'Invalid worker node tasks queue size: -1 is a negative integer or zero'
453 )
454 )
455 expect(
456 () =>
457 new FixedThreadPool(
458 numberOfWorkers,
459 './tests/worker-files/thread/testWorker.mjs',
460 {
461 enableTasksQueue: true,
462 tasksQueueOptions: { size: 0.2 }
463 }
464 )
465 ).toThrow(
466 new TypeError('Invalid worker node tasks queue size: must be an integer')
467 )
468 })
469
470 it('Verify that pool worker choice strategy options can be set', async () => {
471 const pool = new FixedThreadPool(
472 numberOfWorkers,
473 './tests/worker-files/thread/testWorker.mjs',
474 { workerChoiceStrategy: WorkerChoiceStrategies.FAIR_SHARE }
475 )
476 expect(pool.opts.workerChoiceStrategyOptions).toStrictEqual({
477 retries: 6,
478 runTime: { median: false },
479 waitTime: { median: false },
480 elu: { median: false }
481 })
482 expect(pool.workerChoiceStrategyContext.opts).toStrictEqual({
483 retries: 6,
484 runTime: { median: false },
485 waitTime: { median: false },
486 elu: { median: false }
487 })
488 for (const [, workerChoiceStrategy] of pool.workerChoiceStrategyContext
489 .workerChoiceStrategies) {
490 expect(workerChoiceStrategy.opts).toStrictEqual({
491 retries: 6,
492 runTime: { median: false },
493 waitTime: { median: false },
494 elu: { median: false }
495 })
496 }
497 expect(
498 pool.workerChoiceStrategyContext.getTaskStatisticsRequirements()
499 ).toStrictEqual({
500 runTime: {
501 aggregate: true,
502 average: true,
503 median: false
504 },
505 waitTime: {
506 aggregate: false,
507 average: false,
508 median: false
509 },
510 elu: {
511 aggregate: true,
512 average: true,
513 median: false
514 }
515 })
516 pool.setWorkerChoiceStrategyOptions({
517 runTime: { median: true },
518 elu: { median: true }
519 })
520 expect(pool.opts.workerChoiceStrategyOptions).toStrictEqual({
521 retries: 6,
522 runTime: { median: true },
523 waitTime: { median: false },
524 elu: { median: true }
525 })
526 expect(pool.workerChoiceStrategyContext.opts).toStrictEqual({
527 retries: 6,
528 runTime: { median: true },
529 waitTime: { median: false },
530 elu: { median: true }
531 })
532 for (const [, workerChoiceStrategy] of pool.workerChoiceStrategyContext
533 .workerChoiceStrategies) {
534 expect(workerChoiceStrategy.opts).toStrictEqual({
535 retries: 6,
536 runTime: { median: true },
537 waitTime: { median: false },
538 elu: { median: true }
539 })
540 }
541 expect(
542 pool.workerChoiceStrategyContext.getTaskStatisticsRequirements()
543 ).toStrictEqual({
544 runTime: {
545 aggregate: true,
546 average: false,
547 median: true
548 },
549 waitTime: {
550 aggregate: false,
551 average: false,
552 median: false
553 },
554 elu: {
555 aggregate: true,
556 average: false,
557 median: true
558 }
559 })
560 pool.setWorkerChoiceStrategyOptions({
561 runTime: { median: false },
562 elu: { median: false }
563 })
564 expect(pool.opts.workerChoiceStrategyOptions).toStrictEqual({
565 retries: 6,
566 runTime: { median: false },
567 waitTime: { median: false },
568 elu: { median: false }
569 })
570 expect(pool.workerChoiceStrategyContext.opts).toStrictEqual({
571 retries: 6,
572 runTime: { median: false },
573 waitTime: { median: false },
574 elu: { median: false }
575 })
576 for (const [, workerChoiceStrategy] of pool.workerChoiceStrategyContext
577 .workerChoiceStrategies) {
578 expect(workerChoiceStrategy.opts).toStrictEqual({
579 retries: 6,
580 runTime: { median: false },
581 waitTime: { median: false },
582 elu: { median: false }
583 })
584 }
585 expect(
586 pool.workerChoiceStrategyContext.getTaskStatisticsRequirements()
587 ).toStrictEqual({
588 runTime: {
589 aggregate: true,
590 average: true,
591 median: false
592 },
593 waitTime: {
594 aggregate: false,
595 average: false,
596 median: false
597 },
598 elu: {
599 aggregate: true,
600 average: true,
601 median: false
602 }
603 })
604 expect(() =>
605 pool.setWorkerChoiceStrategyOptions('invalidWorkerChoiceStrategyOptions')
606 ).toThrow(
607 new TypeError(
608 'Invalid worker choice strategy options: must be a plain object'
609 )
610 )
611 expect(() =>
612 pool.setWorkerChoiceStrategyOptions({
613 retries: 'invalidChoiceRetries'
614 })
615 ).toThrow(
616 new TypeError(
617 'Invalid worker choice strategy options: retries must be an integer'
618 )
619 )
620 expect(() => pool.setWorkerChoiceStrategyOptions({ retries: -1 })).toThrow(
621 new RangeError(
622 "Invalid worker choice strategy options: retries '-1' must be greater or equal than zero"
623 )
624 )
625 expect(() => pool.setWorkerChoiceStrategyOptions({ weights: {} })).toThrow(
626 new Error(
627 'Invalid worker choice strategy options: must have a weight for each worker node'
628 )
629 )
630 expect(() =>
631 pool.setWorkerChoiceStrategyOptions({ measurement: 'invalidMeasurement' })
632 ).toThrow(
633 new Error(
634 "Invalid worker choice strategy options: invalid measurement 'invalidMeasurement'"
635 )
636 )
637 await pool.destroy()
638 })
639
640 it('Verify that pool tasks queue can be enabled/disabled', async () => {
641 const pool = new FixedThreadPool(
642 numberOfWorkers,
643 './tests/worker-files/thread/testWorker.mjs'
644 )
645 expect(pool.opts.enableTasksQueue).toBe(false)
646 expect(pool.opts.tasksQueueOptions).toBeUndefined()
647 pool.enableTasksQueue(true)
648 expect(pool.opts.enableTasksQueue).toBe(true)
649 expect(pool.opts.tasksQueueOptions).toStrictEqual({
650 concurrency: 1,
651 size: Math.pow(numberOfWorkers, 2),
652 taskStealing: true,
653 tasksStealingOnBackPressure: true
654 })
655 pool.enableTasksQueue(true, { concurrency: 2 })
656 expect(pool.opts.enableTasksQueue).toBe(true)
657 expect(pool.opts.tasksQueueOptions).toStrictEqual({
658 concurrency: 2,
659 size: Math.pow(numberOfWorkers, 2),
660 taskStealing: true,
661 tasksStealingOnBackPressure: true
662 })
663 pool.enableTasksQueue(false)
664 expect(pool.opts.enableTasksQueue).toBe(false)
665 expect(pool.opts.tasksQueueOptions).toBeUndefined()
666 await pool.destroy()
667 })
668
669 it('Verify that pool tasks queue options can be set', async () => {
670 const pool = new FixedThreadPool(
671 numberOfWorkers,
672 './tests/worker-files/thread/testWorker.mjs',
673 { enableTasksQueue: true }
674 )
675 expect(pool.opts.tasksQueueOptions).toStrictEqual({
676 concurrency: 1,
677 size: Math.pow(numberOfWorkers, 2),
678 taskStealing: true,
679 tasksStealingOnBackPressure: true
680 })
681 for (const workerNode of pool.workerNodes) {
682 expect(workerNode.tasksQueueBackPressureSize).toBe(
683 pool.opts.tasksQueueOptions.size
684 )
685 }
686 pool.setTasksQueueOptions({
687 concurrency: 2,
688 size: 2,
689 taskStealing: false,
690 tasksStealingOnBackPressure: false
691 })
692 expect(pool.opts.tasksQueueOptions).toStrictEqual({
693 concurrency: 2,
694 size: 2,
695 taskStealing: false,
696 tasksStealingOnBackPressure: false
697 })
698 for (const workerNode of pool.workerNodes) {
699 expect(workerNode.tasksQueueBackPressureSize).toBe(
700 pool.opts.tasksQueueOptions.size
701 )
702 }
703 pool.setTasksQueueOptions({
704 concurrency: 1,
705 taskStealing: true,
706 tasksStealingOnBackPressure: true
707 })
708 expect(pool.opts.tasksQueueOptions).toStrictEqual({
709 concurrency: 1,
710 size: Math.pow(numberOfWorkers, 2),
711 taskStealing: true,
712 tasksStealingOnBackPressure: true
713 })
714 for (const workerNode of pool.workerNodes) {
715 expect(workerNode.tasksQueueBackPressureSize).toBe(
716 pool.opts.tasksQueueOptions.size
717 )
718 }
719 expect(() => pool.setTasksQueueOptions('invalidTasksQueueOptions')).toThrow(
720 new TypeError('Invalid tasks queue options: must be a plain object')
721 )
722 expect(() => pool.setTasksQueueOptions({ concurrency: 0 })).toThrow(
723 new RangeError(
724 'Invalid worker node tasks concurrency: 0 is a negative integer or zero'
725 )
726 )
727 expect(() => pool.setTasksQueueOptions({ concurrency: -1 })).toThrow(
728 new RangeError(
729 'Invalid worker node tasks concurrency: -1 is a negative integer or zero'
730 )
731 )
732 expect(() => pool.setTasksQueueOptions({ concurrency: 0.2 })).toThrow(
733 new TypeError('Invalid worker node tasks concurrency: must be an integer')
734 )
735 expect(() => pool.setTasksQueueOptions({ size: 0 })).toThrow(
736 new RangeError(
737 'Invalid worker node tasks queue size: 0 is a negative integer or zero'
738 )
739 )
740 expect(() => pool.setTasksQueueOptions({ size: -1 })).toThrow(
741 new RangeError(
742 'Invalid worker node tasks queue size: -1 is a negative integer or zero'
743 )
744 )
745 expect(() => pool.setTasksQueueOptions({ size: 0.2 })).toThrow(
746 new TypeError('Invalid worker node tasks queue size: must be an integer')
747 )
748 await pool.destroy()
749 })
750
751 it('Verify that pool info is set', async () => {
752 let pool = new FixedThreadPool(
753 numberOfWorkers,
754 './tests/worker-files/thread/testWorker.mjs'
755 )
756 expect(pool.info).toStrictEqual({
757 version,
758 type: PoolTypes.fixed,
759 worker: WorkerTypes.thread,
760 started: true,
761 ready: true,
762 strategy: WorkerChoiceStrategies.ROUND_ROBIN,
763 minSize: numberOfWorkers,
764 maxSize: numberOfWorkers,
765 workerNodes: numberOfWorkers,
766 idleWorkerNodes: numberOfWorkers,
767 busyWorkerNodes: 0,
768 executedTasks: 0,
769 executingTasks: 0,
770 failedTasks: 0
771 })
772 await pool.destroy()
773 pool = new DynamicClusterPool(
774 Math.floor(numberOfWorkers / 2),
775 numberOfWorkers,
776 './tests/worker-files/cluster/testWorker.js'
777 )
778 expect(pool.info).toStrictEqual({
779 version,
780 type: PoolTypes.dynamic,
781 worker: WorkerTypes.cluster,
782 started: true,
783 ready: true,
784 strategy: WorkerChoiceStrategies.ROUND_ROBIN,
785 minSize: Math.floor(numberOfWorkers / 2),
786 maxSize: numberOfWorkers,
787 workerNodes: Math.floor(numberOfWorkers / 2),
788 idleWorkerNodes: Math.floor(numberOfWorkers / 2),
789 busyWorkerNodes: 0,
790 executedTasks: 0,
791 executingTasks: 0,
792 failedTasks: 0
793 })
794 await pool.destroy()
795 })
796
797 it('Verify that pool worker tasks usage are initialized', async () => {
798 const pool = new FixedClusterPool(
799 numberOfWorkers,
800 './tests/worker-files/cluster/testWorker.js'
801 )
802 for (const workerNode of pool.workerNodes) {
803 expect(workerNode).toBeInstanceOf(WorkerNode)
804 expect(workerNode.usage).toStrictEqual({
805 tasks: {
806 executed: 0,
807 executing: 0,
808 queued: 0,
809 maxQueued: 0,
810 sequentiallyStolen: 0,
811 stolen: 0,
812 failed: 0
813 },
814 runTime: {
815 history: new CircularArray()
816 },
817 waitTime: {
818 history: new CircularArray()
819 },
820 elu: {
821 idle: {
822 history: new CircularArray()
823 },
824 active: {
825 history: new CircularArray()
826 }
827 }
828 })
829 }
830 await pool.destroy()
831 })
832
833 it('Verify that pool worker tasks queue are initialized', async () => {
834 let pool = new FixedClusterPool(
835 numberOfWorkers,
836 './tests/worker-files/cluster/testWorker.js'
837 )
838 for (const workerNode of pool.workerNodes) {
839 expect(workerNode).toBeInstanceOf(WorkerNode)
840 expect(workerNode.tasksQueue).toBeInstanceOf(Deque)
841 expect(workerNode.tasksQueue.size).toBe(0)
842 expect(workerNode.tasksQueue.maxSize).toBe(0)
843 }
844 await pool.destroy()
845 pool = new DynamicThreadPool(
846 Math.floor(numberOfWorkers / 2),
847 numberOfWorkers,
848 './tests/worker-files/thread/testWorker.mjs'
849 )
850 for (const workerNode of pool.workerNodes) {
851 expect(workerNode).toBeInstanceOf(WorkerNode)
852 expect(workerNode.tasksQueue).toBeInstanceOf(Deque)
853 expect(workerNode.tasksQueue.size).toBe(0)
854 expect(workerNode.tasksQueue.maxSize).toBe(0)
855 }
856 await pool.destroy()
857 })
858
859 it('Verify that pool worker info are initialized', async () => {
860 let pool = new FixedClusterPool(
861 numberOfWorkers,
862 './tests/worker-files/cluster/testWorker.js'
863 )
864 for (const workerNode of pool.workerNodes) {
865 expect(workerNode).toBeInstanceOf(WorkerNode)
866 expect(workerNode.info).toStrictEqual({
867 id: expect.any(Number),
868 type: WorkerTypes.cluster,
869 dynamic: false,
870 ready: true
871 })
872 }
873 await pool.destroy()
874 pool = new DynamicThreadPool(
875 Math.floor(numberOfWorkers / 2),
876 numberOfWorkers,
877 './tests/worker-files/thread/testWorker.mjs'
878 )
879 for (const workerNode of pool.workerNodes) {
880 expect(workerNode).toBeInstanceOf(WorkerNode)
881 expect(workerNode.info).toStrictEqual({
882 id: expect.any(Number),
883 type: WorkerTypes.thread,
884 dynamic: false,
885 ready: true
886 })
887 }
888 await pool.destroy()
889 })
890
891 it('Verify that pool statuses are checked at start or destroy', async () => {
892 const pool = new FixedThreadPool(
893 numberOfWorkers,
894 './tests/worker-files/thread/testWorker.mjs'
895 )
896 expect(pool.info.started).toBe(true)
897 expect(pool.info.ready).toBe(true)
898 expect(() => pool.start()).toThrow(
899 new Error('Cannot start an already started pool')
900 )
901 await pool.destroy()
902 expect(pool.info.started).toBe(false)
903 expect(pool.info.ready).toBe(false)
904 await expect(pool.destroy()).rejects.toThrow(
905 new Error('Cannot destroy an already destroyed pool')
906 )
907 })
908
909 it('Verify that pool can be started after initialization', async () => {
910 const pool = new FixedClusterPool(
911 numberOfWorkers,
912 './tests/worker-files/cluster/testWorker.js',
913 {
914 startWorkers: false
915 }
916 )
917 expect(pool.info.started).toBe(false)
918 expect(pool.info.ready).toBe(false)
919 expect(pool.readyEventEmitted).toBe(false)
920 expect(pool.workerNodes).toStrictEqual([])
921 await expect(pool.execute()).rejects.toThrow(
922 new Error('Cannot execute a task on not started pool')
923 )
924 pool.start()
925 expect(pool.info.started).toBe(true)
926 expect(pool.info.ready).toBe(true)
927 await waitPoolEvents(pool, PoolEvents.ready, 1)
928 expect(pool.readyEventEmitted).toBe(true)
929 expect(pool.workerNodes.length).toBe(numberOfWorkers)
930 for (const workerNode of pool.workerNodes) {
931 expect(workerNode).toBeInstanceOf(WorkerNode)
932 }
933 await pool.destroy()
934 })
935
936 it('Verify that pool execute() arguments are checked', async () => {
937 const pool = new FixedClusterPool(
938 numberOfWorkers,
939 './tests/worker-files/cluster/testWorker.js'
940 )
941 await expect(pool.execute(undefined, 0)).rejects.toThrow(
942 new TypeError('name argument must be a string')
943 )
944 await expect(pool.execute(undefined, '')).rejects.toThrow(
945 new TypeError('name argument must not be an empty string')
946 )
947 await expect(pool.execute(undefined, undefined, {})).rejects.toThrow(
948 new TypeError('transferList argument must be an array')
949 )
950 await expect(pool.execute(undefined, 'unknown')).rejects.toBe(
951 "Task function 'unknown' not found"
952 )
953 await pool.destroy()
954 await expect(pool.execute()).rejects.toThrow(
955 new Error('Cannot execute a task on not started pool')
956 )
957 })
958
959 it('Verify that pool worker tasks usage are computed', async () => {
960 const pool = new FixedClusterPool(
961 numberOfWorkers,
962 './tests/worker-files/cluster/testWorker.js'
963 )
964 const promises = new Set()
965 const maxMultiplier = 2
966 for (let i = 0; i < numberOfWorkers * maxMultiplier; i++) {
967 promises.add(pool.execute())
968 }
969 for (const workerNode of pool.workerNodes) {
970 expect(workerNode.usage).toStrictEqual({
971 tasks: {
972 executed: 0,
973 executing: maxMultiplier,
974 queued: 0,
975 maxQueued: 0,
976 sequentiallyStolen: 0,
977 stolen: 0,
978 failed: 0
979 },
980 runTime: {
981 history: expect.any(CircularArray)
982 },
983 waitTime: {
984 history: expect.any(CircularArray)
985 },
986 elu: {
987 idle: {
988 history: expect.any(CircularArray)
989 },
990 active: {
991 history: expect.any(CircularArray)
992 }
993 }
994 })
995 }
996 await Promise.all(promises)
997 for (const workerNode of pool.workerNodes) {
998 expect(workerNode.usage).toStrictEqual({
999 tasks: {
1000 executed: maxMultiplier,
1001 executing: 0,
1002 queued: 0,
1003 maxQueued: 0,
1004 sequentiallyStolen: 0,
1005 stolen: 0,
1006 failed: 0
1007 },
1008 runTime: {
1009 history: expect.any(CircularArray)
1010 },
1011 waitTime: {
1012 history: expect.any(CircularArray)
1013 },
1014 elu: {
1015 idle: {
1016 history: expect.any(CircularArray)
1017 },
1018 active: {
1019 history: expect.any(CircularArray)
1020 }
1021 }
1022 })
1023 }
1024 await pool.destroy()
1025 })
1026
1027 it('Verify that pool worker tasks usage are reset at worker choice strategy change', async () => {
1028 const pool = new DynamicThreadPool(
1029 Math.floor(numberOfWorkers / 2),
1030 numberOfWorkers,
1031 './tests/worker-files/thread/testWorker.mjs'
1032 )
1033 const promises = new Set()
1034 const maxMultiplier = 2
1035 for (let i = 0; i < numberOfWorkers * maxMultiplier; i++) {
1036 promises.add(pool.execute())
1037 }
1038 await Promise.all(promises)
1039 for (const workerNode of pool.workerNodes) {
1040 expect(workerNode.usage).toStrictEqual({
1041 tasks: {
1042 executed: expect.any(Number),
1043 executing: 0,
1044 queued: 0,
1045 maxQueued: 0,
1046 sequentiallyStolen: 0,
1047 stolen: 0,
1048 failed: 0
1049 },
1050 runTime: {
1051 history: expect.any(CircularArray)
1052 },
1053 waitTime: {
1054 history: expect.any(CircularArray)
1055 },
1056 elu: {
1057 idle: {
1058 history: expect.any(CircularArray)
1059 },
1060 active: {
1061 history: expect.any(CircularArray)
1062 }
1063 }
1064 })
1065 expect(workerNode.usage.tasks.executed).toBeGreaterThan(0)
1066 expect(workerNode.usage.tasks.executed).toBeLessThanOrEqual(
1067 numberOfWorkers * maxMultiplier
1068 )
1069 expect(workerNode.usage.runTime.history.length).toBe(0)
1070 expect(workerNode.usage.waitTime.history.length).toBe(0)
1071 expect(workerNode.usage.elu.idle.history.length).toBe(0)
1072 expect(workerNode.usage.elu.active.history.length).toBe(0)
1073 }
1074 pool.setWorkerChoiceStrategy(WorkerChoiceStrategies.FAIR_SHARE)
1075 for (const workerNode of pool.workerNodes) {
1076 expect(workerNode.usage).toStrictEqual({
1077 tasks: {
1078 executed: 0,
1079 executing: 0,
1080 queued: 0,
1081 maxQueued: 0,
1082 sequentiallyStolen: 0,
1083 stolen: 0,
1084 failed: 0
1085 },
1086 runTime: {
1087 history: expect.any(CircularArray)
1088 },
1089 waitTime: {
1090 history: expect.any(CircularArray)
1091 },
1092 elu: {
1093 idle: {
1094 history: expect.any(CircularArray)
1095 },
1096 active: {
1097 history: expect.any(CircularArray)
1098 }
1099 }
1100 })
1101 expect(workerNode.usage.runTime.history.length).toBe(0)
1102 expect(workerNode.usage.waitTime.history.length).toBe(0)
1103 expect(workerNode.usage.elu.idle.history.length).toBe(0)
1104 expect(workerNode.usage.elu.active.history.length).toBe(0)
1105 }
1106 await pool.destroy()
1107 })
1108
1109 it("Verify that pool event emitter 'ready' event can register a callback", async () => {
1110 const pool = new DynamicClusterPool(
1111 Math.floor(numberOfWorkers / 2),
1112 numberOfWorkers,
1113 './tests/worker-files/cluster/testWorker.js'
1114 )
1115 expect(pool.emitter.eventNames()).toStrictEqual([])
1116 let poolInfo
1117 let poolReady = 0
1118 pool.emitter.on(PoolEvents.ready, info => {
1119 ++poolReady
1120 poolInfo = info
1121 })
1122 await waitPoolEvents(pool, PoolEvents.ready, 1)
1123 expect(pool.emitter.eventNames()).toStrictEqual([PoolEvents.ready])
1124 expect(poolReady).toBe(1)
1125 expect(poolInfo).toStrictEqual({
1126 version,
1127 type: PoolTypes.dynamic,
1128 worker: WorkerTypes.cluster,
1129 started: true,
1130 ready: true,
1131 strategy: WorkerChoiceStrategies.ROUND_ROBIN,
1132 minSize: expect.any(Number),
1133 maxSize: expect.any(Number),
1134 workerNodes: expect.any(Number),
1135 idleWorkerNodes: expect.any(Number),
1136 busyWorkerNodes: expect.any(Number),
1137 executedTasks: expect.any(Number),
1138 executingTasks: expect.any(Number),
1139 failedTasks: expect.any(Number)
1140 })
1141 await pool.destroy()
1142 })
1143
1144 it("Verify that pool event emitter 'busy' event can register a callback", async () => {
1145 const pool = new FixedThreadPool(
1146 numberOfWorkers,
1147 './tests/worker-files/thread/testWorker.mjs'
1148 )
1149 expect(pool.emitter.eventNames()).toStrictEqual([])
1150 const promises = new Set()
1151 let poolBusy = 0
1152 let poolInfo
1153 pool.emitter.on(PoolEvents.busy, info => {
1154 ++poolBusy
1155 poolInfo = info
1156 })
1157 expect(pool.emitter.eventNames()).toStrictEqual([PoolEvents.busy])
1158 for (let i = 0; i < numberOfWorkers * 2; i++) {
1159 promises.add(pool.execute())
1160 }
1161 await Promise.all(promises)
1162 // The `busy` event is triggered when the number of submitted tasks at once reach the number of fixed pool workers.
1163 // So in total numberOfWorkers + 1 times for a loop submitting up to numberOfWorkers * 2 tasks to the fixed pool.
1164 expect(poolBusy).toBe(numberOfWorkers + 1)
1165 expect(poolInfo).toStrictEqual({
1166 version,
1167 type: PoolTypes.fixed,
1168 worker: WorkerTypes.thread,
1169 started: true,
1170 ready: true,
1171 strategy: WorkerChoiceStrategies.ROUND_ROBIN,
1172 minSize: expect.any(Number),
1173 maxSize: expect.any(Number),
1174 workerNodes: expect.any(Number),
1175 idleWorkerNodes: expect.any(Number),
1176 busyWorkerNodes: expect.any(Number),
1177 executedTasks: expect.any(Number),
1178 executingTasks: expect.any(Number),
1179 failedTasks: expect.any(Number)
1180 })
1181 await pool.destroy()
1182 })
1183
1184 it("Verify that pool event emitter 'full' event can register a callback", async () => {
1185 const pool = new DynamicThreadPool(
1186 Math.floor(numberOfWorkers / 2),
1187 numberOfWorkers,
1188 './tests/worker-files/thread/testWorker.mjs'
1189 )
1190 expect(pool.emitter.eventNames()).toStrictEqual([])
1191 const promises = new Set()
1192 let poolFull = 0
1193 let poolInfo
1194 pool.emitter.on(PoolEvents.full, info => {
1195 ++poolFull
1196 poolInfo = info
1197 })
1198 expect(pool.emitter.eventNames()).toStrictEqual([PoolEvents.full])
1199 for (let i = 0; i < numberOfWorkers * 2; i++) {
1200 promises.add(pool.execute())
1201 }
1202 await Promise.all(promises)
1203 expect(poolFull).toBe(1)
1204 expect(poolInfo).toStrictEqual({
1205 version,
1206 type: PoolTypes.dynamic,
1207 worker: WorkerTypes.thread,
1208 started: true,
1209 ready: true,
1210 strategy: WorkerChoiceStrategies.ROUND_ROBIN,
1211 minSize: expect.any(Number),
1212 maxSize: expect.any(Number),
1213 workerNodes: expect.any(Number),
1214 idleWorkerNodes: expect.any(Number),
1215 busyWorkerNodes: expect.any(Number),
1216 executedTasks: expect.any(Number),
1217 executingTasks: expect.any(Number),
1218 failedTasks: expect.any(Number)
1219 })
1220 await pool.destroy()
1221 })
1222
1223 it("Verify that pool event emitter 'backPressure' event can register a callback", async () => {
1224 const pool = new FixedThreadPool(
1225 numberOfWorkers,
1226 './tests/worker-files/thread/testWorker.mjs',
1227 {
1228 enableTasksQueue: true
1229 }
1230 )
1231 stub(pool, 'hasBackPressure').returns(true)
1232 expect(pool.emitter.eventNames()).toStrictEqual([])
1233 const promises = new Set()
1234 let poolBackPressure = 0
1235 let poolInfo
1236 pool.emitter.on(PoolEvents.backPressure, info => {
1237 ++poolBackPressure
1238 poolInfo = info
1239 })
1240 expect(pool.emitter.eventNames()).toStrictEqual([PoolEvents.backPressure])
1241 for (let i = 0; i < numberOfWorkers + 1; i++) {
1242 promises.add(pool.execute())
1243 }
1244 await Promise.all(promises)
1245 expect(poolBackPressure).toBe(1)
1246 expect(poolInfo).toStrictEqual({
1247 version,
1248 type: PoolTypes.fixed,
1249 worker: WorkerTypes.thread,
1250 started: true,
1251 ready: true,
1252 strategy: WorkerChoiceStrategies.ROUND_ROBIN,
1253 minSize: expect.any(Number),
1254 maxSize: expect.any(Number),
1255 workerNodes: expect.any(Number),
1256 idleWorkerNodes: expect.any(Number),
1257 busyWorkerNodes: expect.any(Number),
1258 executedTasks: expect.any(Number),
1259 executingTasks: expect.any(Number),
1260 maxQueuedTasks: expect.any(Number),
1261 queuedTasks: expect.any(Number),
1262 backPressure: true,
1263 stolenTasks: expect.any(Number),
1264 failedTasks: expect.any(Number)
1265 })
1266 expect(pool.hasBackPressure.called).toBe(true)
1267 await pool.destroy()
1268 })
1269
1270 it('Verify that hasTaskFunction() is working', async () => {
1271 const dynamicThreadPool = new DynamicThreadPool(
1272 Math.floor(numberOfWorkers / 2),
1273 numberOfWorkers,
1274 './tests/worker-files/thread/testMultipleTaskFunctionsWorker.mjs'
1275 )
1276 await waitPoolEvents(dynamicThreadPool, PoolEvents.ready, 1)
1277 expect(dynamicThreadPool.hasTaskFunction(DEFAULT_TASK_NAME)).toBe(true)
1278 expect(dynamicThreadPool.hasTaskFunction('jsonIntegerSerialization')).toBe(
1279 true
1280 )
1281 expect(dynamicThreadPool.hasTaskFunction('factorial')).toBe(true)
1282 expect(dynamicThreadPool.hasTaskFunction('fibonacci')).toBe(true)
1283 expect(dynamicThreadPool.hasTaskFunction('unknown')).toBe(false)
1284 await dynamicThreadPool.destroy()
1285 const fixedClusterPool = new FixedClusterPool(
1286 numberOfWorkers,
1287 './tests/worker-files/cluster/testMultipleTaskFunctionsWorker.js'
1288 )
1289 await waitPoolEvents(fixedClusterPool, PoolEvents.ready, 1)
1290 expect(fixedClusterPool.hasTaskFunction(DEFAULT_TASK_NAME)).toBe(true)
1291 expect(fixedClusterPool.hasTaskFunction('jsonIntegerSerialization')).toBe(
1292 true
1293 )
1294 expect(fixedClusterPool.hasTaskFunction('factorial')).toBe(true)
1295 expect(fixedClusterPool.hasTaskFunction('fibonacci')).toBe(true)
1296 expect(fixedClusterPool.hasTaskFunction('unknown')).toBe(false)
1297 await fixedClusterPool.destroy()
1298 })
1299
1300 it('Verify that addTaskFunction() is working', async () => {
1301 const dynamicThreadPool = new DynamicThreadPool(
1302 Math.floor(numberOfWorkers / 2),
1303 numberOfWorkers,
1304 './tests/worker-files/thread/testWorker.mjs'
1305 )
1306 await waitPoolEvents(dynamicThreadPool, PoolEvents.ready, 1)
1307 await expect(
1308 dynamicThreadPool.addTaskFunction(0, () => {})
1309 ).rejects.toThrow(new TypeError('name argument must be a string'))
1310 await expect(
1311 dynamicThreadPool.addTaskFunction('', () => {})
1312 ).rejects.toThrow(
1313 new TypeError('name argument must not be an empty string')
1314 )
1315 await expect(dynamicThreadPool.addTaskFunction('test', 0)).rejects.toThrow(
1316 new TypeError('fn argument must be a function')
1317 )
1318 await expect(dynamicThreadPool.addTaskFunction('test', '')).rejects.toThrow(
1319 new TypeError('fn argument must be a function')
1320 )
1321 expect(dynamicThreadPool.listTaskFunctionNames()).toStrictEqual([
1322 DEFAULT_TASK_NAME,
1323 'test'
1324 ])
1325 const echoTaskFunction = data => {
1326 return data
1327 }
1328 await expect(
1329 dynamicThreadPool.addTaskFunction('echo', echoTaskFunction)
1330 ).resolves.toBe(true)
1331 expect(dynamicThreadPool.taskFunctions.size).toBe(1)
1332 expect(dynamicThreadPool.taskFunctions.get('echo')).toStrictEqual(
1333 echoTaskFunction
1334 )
1335 expect(dynamicThreadPool.listTaskFunctionNames()).toStrictEqual([
1336 DEFAULT_TASK_NAME,
1337 'test',
1338 'echo'
1339 ])
1340 const taskFunctionData = { test: 'test' }
1341 const echoResult = await dynamicThreadPool.execute(taskFunctionData, 'echo')
1342 expect(echoResult).toStrictEqual(taskFunctionData)
1343 for (const workerNode of dynamicThreadPool.workerNodes) {
1344 expect(workerNode.getTaskFunctionWorkerUsage('echo')).toStrictEqual({
1345 tasks: {
1346 executed: expect.any(Number),
1347 executing: 0,
1348 queued: 0,
1349 sequentiallyStolen: 0,
1350 stolen: 0,
1351 failed: 0
1352 },
1353 runTime: {
1354 history: new CircularArray()
1355 },
1356 waitTime: {
1357 history: new CircularArray()
1358 },
1359 elu: {
1360 idle: {
1361 history: new CircularArray()
1362 },
1363 active: {
1364 history: new CircularArray()
1365 }
1366 }
1367 })
1368 }
1369 await dynamicThreadPool.destroy()
1370 })
1371
1372 it('Verify that removeTaskFunction() is working', async () => {
1373 const dynamicThreadPool = new DynamicThreadPool(
1374 Math.floor(numberOfWorkers / 2),
1375 numberOfWorkers,
1376 './tests/worker-files/thread/testWorker.mjs'
1377 )
1378 await waitPoolEvents(dynamicThreadPool, PoolEvents.ready, 1)
1379 expect(dynamicThreadPool.listTaskFunctionNames()).toStrictEqual([
1380 DEFAULT_TASK_NAME,
1381 'test'
1382 ])
1383 await expect(dynamicThreadPool.removeTaskFunction('test')).rejects.toThrow(
1384 new Error('Cannot remove a task function not handled on the pool side')
1385 )
1386 const echoTaskFunction = data => {
1387 return data
1388 }
1389 await dynamicThreadPool.addTaskFunction('echo', echoTaskFunction)
1390 expect(dynamicThreadPool.taskFunctions.size).toBe(1)
1391 expect(dynamicThreadPool.taskFunctions.get('echo')).toStrictEqual(
1392 echoTaskFunction
1393 )
1394 expect(dynamicThreadPool.listTaskFunctionNames()).toStrictEqual([
1395 DEFAULT_TASK_NAME,
1396 'test',
1397 'echo'
1398 ])
1399 await expect(dynamicThreadPool.removeTaskFunction('echo')).resolves.toBe(
1400 true
1401 )
1402 expect(dynamicThreadPool.taskFunctions.size).toBe(0)
1403 expect(dynamicThreadPool.taskFunctions.get('echo')).toBeUndefined()
1404 expect(dynamicThreadPool.listTaskFunctionNames()).toStrictEqual([
1405 DEFAULT_TASK_NAME,
1406 'test'
1407 ])
1408 await dynamicThreadPool.destroy()
1409 })
1410
1411 it('Verify that listTaskFunctionNames() is working', async () => {
1412 const dynamicThreadPool = new DynamicThreadPool(
1413 Math.floor(numberOfWorkers / 2),
1414 numberOfWorkers,
1415 './tests/worker-files/thread/testMultipleTaskFunctionsWorker.mjs'
1416 )
1417 await waitPoolEvents(dynamicThreadPool, PoolEvents.ready, 1)
1418 expect(dynamicThreadPool.listTaskFunctionNames()).toStrictEqual([
1419 DEFAULT_TASK_NAME,
1420 'jsonIntegerSerialization',
1421 'factorial',
1422 'fibonacci'
1423 ])
1424 await dynamicThreadPool.destroy()
1425 const fixedClusterPool = new FixedClusterPool(
1426 numberOfWorkers,
1427 './tests/worker-files/cluster/testMultipleTaskFunctionsWorker.js'
1428 )
1429 await waitPoolEvents(fixedClusterPool, PoolEvents.ready, 1)
1430 expect(fixedClusterPool.listTaskFunctionNames()).toStrictEqual([
1431 DEFAULT_TASK_NAME,
1432 'jsonIntegerSerialization',
1433 'factorial',
1434 'fibonacci'
1435 ])
1436 await fixedClusterPool.destroy()
1437 })
1438
1439 it('Verify that setDefaultTaskFunction() is working', async () => {
1440 const dynamicThreadPool = new DynamicThreadPool(
1441 Math.floor(numberOfWorkers / 2),
1442 numberOfWorkers,
1443 './tests/worker-files/thread/testMultipleTaskFunctionsWorker.mjs'
1444 )
1445 await waitPoolEvents(dynamicThreadPool, PoolEvents.ready, 1)
1446 const workerId = dynamicThreadPool.workerNodes[0].info.id
1447 await expect(dynamicThreadPool.setDefaultTaskFunction(0)).rejects.toThrow(
1448 new Error(
1449 `Task function operation 'default' failed on worker ${workerId} with error: 'TypeError: name parameter is not a string'`
1450 )
1451 )
1452 await expect(
1453 dynamicThreadPool.setDefaultTaskFunction(DEFAULT_TASK_NAME)
1454 ).rejects.toThrow(
1455 new Error(
1456 `Task function operation 'default' failed on worker ${workerId} with error: 'Error: Cannot set the default task function reserved name as the default task function'`
1457 )
1458 )
1459 await expect(
1460 dynamicThreadPool.setDefaultTaskFunction('unknown')
1461 ).rejects.toThrow(
1462 new Error(
1463 `Task function operation 'default' failed on worker ${workerId} with error: 'Error: Cannot set the default task function to a non-existing task function'`
1464 )
1465 )
1466 expect(dynamicThreadPool.listTaskFunctionNames()).toStrictEqual([
1467 DEFAULT_TASK_NAME,
1468 'jsonIntegerSerialization',
1469 'factorial',
1470 'fibonacci'
1471 ])
1472 await expect(
1473 dynamicThreadPool.setDefaultTaskFunction('factorial')
1474 ).resolves.toBe(true)
1475 expect(dynamicThreadPool.listTaskFunctionNames()).toStrictEqual([
1476 DEFAULT_TASK_NAME,
1477 'factorial',
1478 'jsonIntegerSerialization',
1479 'fibonacci'
1480 ])
1481 await expect(
1482 dynamicThreadPool.setDefaultTaskFunction('fibonacci')
1483 ).resolves.toBe(true)
1484 expect(dynamicThreadPool.listTaskFunctionNames()).toStrictEqual([
1485 DEFAULT_TASK_NAME,
1486 'fibonacci',
1487 'jsonIntegerSerialization',
1488 'factorial'
1489 ])
1490 await dynamicThreadPool.destroy()
1491 })
1492
1493 it('Verify that multiple task functions worker is working', async () => {
1494 const pool = new DynamicClusterPool(
1495 Math.floor(numberOfWorkers / 2),
1496 numberOfWorkers,
1497 './tests/worker-files/cluster/testMultipleTaskFunctionsWorker.js'
1498 )
1499 const data = { n: 10 }
1500 const result0 = await pool.execute(data)
1501 expect(result0).toStrictEqual({ ok: 1 })
1502 const result1 = await pool.execute(data, 'jsonIntegerSerialization')
1503 expect(result1).toStrictEqual({ ok: 1 })
1504 const result2 = await pool.execute(data, 'factorial')
1505 expect(result2).toBe(3628800)
1506 const result3 = await pool.execute(data, 'fibonacci')
1507 expect(result3).toBe(55)
1508 expect(pool.info.executingTasks).toBe(0)
1509 expect(pool.info.executedTasks).toBe(4)
1510 for (const workerNode of pool.workerNodes) {
1511 expect(workerNode.info.taskFunctionNames).toStrictEqual([
1512 DEFAULT_TASK_NAME,
1513 'jsonIntegerSerialization',
1514 'factorial',
1515 'fibonacci'
1516 ])
1517 expect(workerNode.taskFunctionsUsage.size).toBe(3)
1518 for (const name of pool.listTaskFunctionNames()) {
1519 expect(workerNode.getTaskFunctionWorkerUsage(name)).toStrictEqual({
1520 tasks: {
1521 executed: expect.any(Number),
1522 executing: 0,
1523 failed: 0,
1524 queued: 0,
1525 sequentiallyStolen: 0,
1526 stolen: 0
1527 },
1528 runTime: {
1529 history: expect.any(CircularArray)
1530 },
1531 waitTime: {
1532 history: expect.any(CircularArray)
1533 },
1534 elu: {
1535 idle: {
1536 history: expect.any(CircularArray)
1537 },
1538 active: {
1539 history: expect.any(CircularArray)
1540 }
1541 }
1542 })
1543 expect(
1544 workerNode.getTaskFunctionWorkerUsage(name).tasks.executed
1545 ).toBeGreaterThan(0)
1546 }
1547 expect(
1548 workerNode.getTaskFunctionWorkerUsage(DEFAULT_TASK_NAME)
1549 ).toStrictEqual(
1550 workerNode.getTaskFunctionWorkerUsage(
1551 workerNode.info.taskFunctionNames[1]
1552 )
1553 )
1554 }
1555 await pool.destroy()
1556 })
1557
1558 it('Verify sendKillMessageToWorker()', async () => {
1559 const pool = new DynamicClusterPool(
1560 Math.floor(numberOfWorkers / 2),
1561 numberOfWorkers,
1562 './tests/worker-files/cluster/testWorker.js'
1563 )
1564 const workerNodeKey = 0
1565 await expect(
1566 pool.sendKillMessageToWorker(workerNodeKey)
1567 ).resolves.toBeUndefined()
1568 await pool.destroy()
1569 })
1570
1571 it('Verify sendTaskFunctionOperationToWorker()', async () => {
1572 const pool = new DynamicClusterPool(
1573 Math.floor(numberOfWorkers / 2),
1574 numberOfWorkers,
1575 './tests/worker-files/cluster/testWorker.js'
1576 )
1577 const workerNodeKey = 0
1578 await expect(
1579 pool.sendTaskFunctionOperationToWorker(workerNodeKey, {
1580 taskFunctionOperation: 'add',
1581 taskFunctionName: 'empty',
1582 taskFunction: (() => {}).toString()
1583 })
1584 ).resolves.toBe(true)
1585 expect(
1586 pool.workerNodes[workerNodeKey].info.taskFunctionNames
1587 ).toStrictEqual([DEFAULT_TASK_NAME, 'test', 'empty'])
1588 await pool.destroy()
1589 })
1590
1591 it('Verify sendTaskFunctionOperationToWorkers()', async () => {
1592 const pool = new DynamicClusterPool(
1593 Math.floor(numberOfWorkers / 2),
1594 numberOfWorkers,
1595 './tests/worker-files/cluster/testWorker.js'
1596 )
1597 await expect(
1598 pool.sendTaskFunctionOperationToWorkers({
1599 taskFunctionOperation: 'add',
1600 taskFunctionName: 'empty',
1601 taskFunction: (() => {}).toString()
1602 })
1603 ).resolves.toBe(true)
1604 for (const workerNode of pool.workerNodes) {
1605 expect(workerNode.info.taskFunctionNames).toStrictEqual([
1606 DEFAULT_TASK_NAME,
1607 'test',
1608 'empty'
1609 ])
1610 }
1611 await pool.destroy()
1612 })
1613})