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