test: improve multiple task functions worker usage test
[poolifier.git] / tests / pools / abstract / abstract-pool.test.js
index 6c340ed9f089ea6f9fd5deeb126480dc0e0ab3df..0929adc36a60dcfa0422ad6908041484736ee28c 100644 (file)
@@ -5,8 +5,8 @@ const {
   FixedClusterPool,
   FixedThreadPool,
   PoolEvents,
-  WorkerChoiceStrategies,
   PoolTypes,
+  WorkerChoiceStrategies,
   WorkerTypes
 } = require('../../../lib')
 const { CircularArray } = require('../../../lib/circular-array')
@@ -29,10 +29,12 @@ describe('Abstract pool test suite', () => {
           numberOfWorkers,
           './tests/worker-files/thread/testWorker.js',
           {
-            errorHandler: e => console.error(e)
+            errorHandler: (e) => console.error(e)
           }
         )
-    ).toThrowError('Cannot start a pool from a worker!')
+    ).toThrowError(
+      'Cannot start a pool from a worker with the same type as the pool'
+    )
   })
 
   it('Verify that filePath is checked', () => {
@@ -45,6 +47,15 @@ describe('Abstract pool test suite', () => {
     expect(() => new FixedThreadPool(numberOfWorkers, '')).toThrowError(
       expectedError
     )
+    expect(() => new FixedThreadPool(numberOfWorkers, 0)).toThrowError(
+      expectedError
+    )
+    expect(() => new FixedThreadPool(numberOfWorkers, true)).toThrowError(
+      expectedError
+    )
+    expect(
+      () => new FixedThreadPool(numberOfWorkers, './dummyWorker.ts')
+    ).toThrowError(new Error("Cannot find the worker file './dummyWorker.ts'"))
   })
 
   it('Verify that numberOfWorkers is checked', () => {
@@ -75,7 +86,43 @@ describe('Abstract pool test suite', () => {
     )
   })
 
-  it('Verify dynamic pool sizing', () => {
+  it('Verify that dynamic pool sizing is checked', () => {
+    expect(
+      () =>
+        new DynamicClusterPool(
+          1,
+          undefined,
+          './tests/worker-files/cluster/testWorker.js'
+        )
+    ).toThrowError(
+      new TypeError(
+        'Cannot instantiate a dynamic pool without specifying the maximum pool size'
+      )
+    )
+    expect(
+      () =>
+        new DynamicThreadPool(
+          0.5,
+          1,
+          './tests/worker-files/thread/testWorker.js'
+        )
+    ).toThrowError(
+      new TypeError(
+        'Cannot instantiate a pool with a non safe integer number of workers'
+      )
+    )
+    expect(
+      () =>
+        new DynamicClusterPool(
+          0,
+          0.5,
+          './tests/worker-files/cluster/testWorker.js'
+        )
+    ).toThrowError(
+      new TypeError(
+        'Cannot instantiate a dynamic pool with a non safe integer maximum pool size'
+      )
+    )
     expect(
       () =>
         new DynamicThreadPool(2, 1, './tests/worker-files/thread/testWorker.js')
@@ -86,7 +133,11 @@ describe('Abstract pool test suite', () => {
     )
     expect(
       () =>
-        new DynamicThreadPool(1, 1, './tests/worker-files/thread/testWorker.js')
+        new DynamicClusterPool(
+          1,
+          1,
+          './tests/worker-files/cluster/testWorker.js'
+        )
     ).toThrowError(
       new RangeError(
         'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
@@ -97,7 +148,7 @@ describe('Abstract pool test suite', () => {
         new DynamicThreadPool(0, 0, './tests/worker-files/thread/testWorker.js')
     ).toThrowError(
       new RangeError(
-        'Cannot instantiate a dynamic pool with a minimum pool size and a maximum pool size equal to zero'
+        'Cannot instantiate a dynamic pool with a maximum pool size equal to zero'
       )
     )
   })
@@ -116,6 +167,13 @@ describe('Abstract pool test suite', () => {
       WorkerChoiceStrategies.ROUND_ROBIN
     )
     expect(pool.opts.workerChoiceStrategyOptions).toStrictEqual({
+      choiceRetries: 6,
+      runTime: { median: false },
+      waitTime: { median: false },
+      elu: { median: false }
+    })
+    expect(pool.workerChoiceStrategyContext.opts).toStrictEqual({
+      choiceRetries: 6,
       runTime: { median: false },
       waitTime: { median: false },
       elu: { median: false }
@@ -125,7 +183,7 @@ describe('Abstract pool test suite', () => {
     expect(pool.opts.onlineHandler).toBeUndefined()
     expect(pool.opts.exitHandler).toBeUndefined()
     await pool.destroy()
-    const testHandler = () => console.log('test handler executed')
+    const testHandler = () => console.info('test handler executed')
     pool = new FixedThreadPool(
       numberOfWorkers,
       './tests/worker-files/thread/testWorker.js',
@@ -154,7 +212,17 @@ describe('Abstract pool test suite', () => {
       WorkerChoiceStrategies.LEAST_USED
     )
     expect(pool.opts.workerChoiceStrategyOptions).toStrictEqual({
+      choiceRetries: 6,
       runTime: { median: true },
+      waitTime: { median: false },
+      elu: { median: false },
+      weights: { 0: 300, 1: 200 }
+    })
+    expect(pool.workerChoiceStrategyContext.opts).toStrictEqual({
+      choiceRetries: 6,
+      runTime: { median: true },
+      waitTime: { median: false },
+      elu: { median: false },
       weights: { 0: 300, 1: 200 }
     })
     expect(pool.opts.messageHandler).toStrictEqual(testHandler)
@@ -175,18 +243,6 @@ describe('Abstract pool test suite', () => {
           }
         )
     ).toThrowError("Invalid worker choice strategy 'invalidStrategy'")
-    expect(
-      () =>
-        new FixedThreadPool(
-          numberOfWorkers,
-          './tests/worker-files/thread/testWorker.js',
-          {
-            workerChoiceStrategyOptions: 'invalidOptions'
-          }
-        )
-    ).toThrowError(
-      'Invalid worker choice strategy options: must be a plain object'
-    )
     expect(
       () =>
         new FixedThreadPool(
@@ -253,6 +309,13 @@ describe('Abstract pool test suite', () => {
       { workerChoiceStrategy: WorkerChoiceStrategies.FAIR_SHARE }
     )
     expect(pool.opts.workerChoiceStrategyOptions).toStrictEqual({
+      choiceRetries: 6,
+      runTime: { median: false },
+      waitTime: { median: false },
+      elu: { median: false }
+    })
+    expect(pool.workerChoiceStrategyContext.opts).toStrictEqual({
+      choiceRetries: 6,
       runTime: { median: false },
       waitTime: { median: false },
       elu: { median: false }
@@ -260,6 +323,7 @@ describe('Abstract pool test suite', () => {
     for (const [, workerChoiceStrategy] of pool.workerChoiceStrategyContext
       .workerChoiceStrategies) {
       expect(workerChoiceStrategy.opts).toStrictEqual({
+        choiceRetries: 6,
         runTime: { median: false },
         waitTime: { median: false },
         elu: { median: false }
@@ -289,13 +353,23 @@ describe('Abstract pool test suite', () => {
       elu: { median: true }
     })
     expect(pool.opts.workerChoiceStrategyOptions).toStrictEqual({
+      choiceRetries: 6,
       runTime: { median: true },
+      waitTime: { median: false },
+      elu: { median: true }
+    })
+    expect(pool.workerChoiceStrategyContext.opts).toStrictEqual({
+      choiceRetries: 6,
+      runTime: { median: true },
+      waitTime: { median: false },
       elu: { median: true }
     })
     for (const [, workerChoiceStrategy] of pool.workerChoiceStrategyContext
       .workerChoiceStrategies) {
       expect(workerChoiceStrategy.opts).toStrictEqual({
+        choiceRetries: 6,
         runTime: { median: true },
+        waitTime: { median: false },
         elu: { median: true }
       })
     }
@@ -323,13 +397,23 @@ describe('Abstract pool test suite', () => {
       elu: { median: false }
     })
     expect(pool.opts.workerChoiceStrategyOptions).toStrictEqual({
+      choiceRetries: 6,
       runTime: { median: false },
+      waitTime: { median: false },
+      elu: { median: false }
+    })
+    expect(pool.workerChoiceStrategyContext.opts).toStrictEqual({
+      choiceRetries: 6,
+      runTime: { median: false },
+      waitTime: { median: false },
       elu: { median: false }
     })
     for (const [, workerChoiceStrategy] of pool.workerChoiceStrategyContext
       .workerChoiceStrategies) {
       expect(workerChoiceStrategy.opts).toStrictEqual({
+        choiceRetries: 6,
         runTime: { median: false },
+        waitTime: { median: false },
         elu: { median: false }
       })
     }
@@ -419,7 +503,7 @@ describe('Abstract pool test suite', () => {
       version,
       type: PoolTypes.fixed,
       worker: WorkerTypes.thread,
-      ready: false,
+      ready: true,
       strategy: WorkerChoiceStrategies.ROUND_ROBIN,
       minSize: numberOfWorkers,
       maxSize: numberOfWorkers,
@@ -428,8 +512,6 @@ describe('Abstract pool test suite', () => {
       busyWorkerNodes: 0,
       executedTasks: 0,
       executingTasks: 0,
-      queuedTasks: 0,
-      maxQueuedTasks: 0,
       failedTasks: 0
     })
     await pool.destroy()
@@ -442,7 +524,7 @@ describe('Abstract pool test suite', () => {
       version,
       type: PoolTypes.dynamic,
       worker: WorkerTypes.cluster,
-      ready: false,
+      ready: true,
       strategy: WorkerChoiceStrategies.ROUND_ROBIN,
       minSize: Math.floor(numberOfWorkers / 2),
       maxSize: numberOfWorkers,
@@ -451,8 +533,6 @@ describe('Abstract pool test suite', () => {
       busyWorkerNodes: 0,
       executedTasks: 0,
       executingTasks: 0,
-      queuedTasks: 0,
-      maxQueuedTasks: 0,
       failedTasks: 0
     })
     await pool.destroy()
@@ -526,7 +606,7 @@ describe('Abstract pool test suite', () => {
         id: expect.any(Number),
         type: WorkerTypes.cluster,
         dynamic: false,
-        ready: false
+        ready: true
       })
     }
     await pool.destroy()
@@ -540,7 +620,7 @@ describe('Abstract pool test suite', () => {
         id: expect.any(Number),
         type: WorkerTypes.thread,
         dynamic: false,
-        ready: false
+        ready: true
       })
     }
   })
@@ -647,6 +727,10 @@ describe('Abstract pool test suite', () => {
       })
       expect(workerNode.usage.tasks.executed).toBeGreaterThan(0)
       expect(workerNode.usage.tasks.executed).toBeLessThanOrEqual(maxMultiplier)
+      expect(workerNode.usage.runTime.history.length).toBe(0)
+      expect(workerNode.usage.waitTime.history.length).toBe(0)
+      expect(workerNode.usage.elu.idle.history.length).toBe(0)
+      expect(workerNode.usage.elu.active.history.length).toBe(0)
     }
     pool.setWorkerChoiceStrategy(WorkerChoiceStrategies.FAIR_SHARE)
     for (const workerNode of pool.workerNodes) {
@@ -675,6 +759,8 @@ describe('Abstract pool test suite', () => {
       })
       expect(workerNode.usage.runTime.history.length).toBe(0)
       expect(workerNode.usage.waitTime.history.length).toBe(0)
+      expect(workerNode.usage.elu.idle.history.length).toBe(0)
+      expect(workerNode.usage.elu.active.history.length).toBe(0)
     }
     await pool.destroy()
   })
@@ -688,7 +774,7 @@ describe('Abstract pool test suite', () => {
     const promises = new Set()
     let poolFull = 0
     let poolInfo
-    pool.emitter.on(PoolEvents.full, info => {
+    pool.emitter.on(PoolEvents.full, (info) => {
       ++poolFull
       poolInfo = info
     })
@@ -712,21 +798,20 @@ describe('Abstract pool test suite', () => {
       busyWorkerNodes: expect.any(Number),
       executedTasks: expect.any(Number),
       executingTasks: expect.any(Number),
-      queuedTasks: expect.any(Number),
-      maxQueuedTasks: expect.any(Number),
       failedTasks: expect.any(Number)
     })
     await pool.destroy()
   })
 
   it("Verify that pool event emitter 'ready' event can register a callback", async () => {
-    const pool = new FixedClusterPool(
+    const pool = new DynamicClusterPool(
+      Math.floor(numberOfWorkers / 2),
       numberOfWorkers,
       './tests/worker-files/cluster/testWorker.js'
     )
-    let poolReady = 0
     let poolInfo
-    pool.emitter.on(PoolEvents.ready, info => {
+    let poolReady = 0
+    pool.emitter.on(PoolEvents.ready, (info) => {
       ++poolReady
       poolInfo = info
     })
@@ -734,7 +819,7 @@ describe('Abstract pool test suite', () => {
     expect(poolReady).toBe(1)
     expect(poolInfo).toStrictEqual({
       version,
-      type: PoolTypes.fixed,
+      type: PoolTypes.dynamic,
       worker: WorkerTypes.cluster,
       ready: true,
       strategy: WorkerChoiceStrategies.ROUND_ROBIN,
@@ -745,8 +830,6 @@ describe('Abstract pool test suite', () => {
       busyWorkerNodes: expect.any(Number),
       executedTasks: expect.any(Number),
       executingTasks: expect.any(Number),
-      queuedTasks: expect.any(Number),
-      maxQueuedTasks: expect.any(Number),
       failedTasks: expect.any(Number)
     })
     await pool.destroy()
@@ -760,7 +843,7 @@ describe('Abstract pool test suite', () => {
     const promises = new Set()
     let poolBusy = 0
     let poolInfo
-    pool.emitter.on(PoolEvents.busy, info => {
+    pool.emitter.on(PoolEvents.busy, (info) => {
       ++poolBusy
       poolInfo = info
     })
@@ -784,18 +867,42 @@ describe('Abstract pool test suite', () => {
       busyWorkerNodes: expect.any(Number),
       executedTasks: expect.any(Number),
       executingTasks: expect.any(Number),
-      queuedTasks: expect.any(Number),
-      maxQueuedTasks: expect.any(Number),
       failedTasks: expect.any(Number)
     })
     await pool.destroy()
   })
 
-  it('Verify that multiple tasks worker is working', async () => {
+  it('Verify that listTaskFunctions() is working', async () => {
+    const dynamicThreadPool = new DynamicThreadPool(
+      Math.floor(numberOfWorkers / 2),
+      numberOfWorkers,
+      './tests/worker-files/thread/testMultipleTaskFunctionsWorker.js'
+    )
+    await waitPoolEvents(dynamicThreadPool, PoolEvents.ready, 1)
+    expect(dynamicThreadPool.listTaskFunctions()).toStrictEqual([
+      'default',
+      'jsonIntegerSerialization',
+      'factorial',
+      'fibonacci'
+    ])
+    const fixedClusterPool = new FixedClusterPool(
+      numberOfWorkers,
+      './tests/worker-files/cluster/testMultipleTaskFunctionsWorker.js'
+    )
+    await waitPoolEvents(fixedClusterPool, PoolEvents.ready, 1)
+    expect(fixedClusterPool.listTaskFunctions()).toStrictEqual([
+      'default',
+      'jsonIntegerSerialization',
+      'factorial',
+      'fibonacci'
+    ])
+  })
+
+  it('Verify that multiple task functions worker is working', async () => {
     const pool = new DynamicClusterPool(
       Math.floor(numberOfWorkers / 2),
       numberOfWorkers,
-      './tests/worker-files/cluster/testMultiTasksWorker.js'
+      './tests/worker-files/cluster/testMultipleTaskFunctionsWorker.js'
     )
     const data = { n: 10 }
     const result0 = await pool.execute(data)
@@ -806,5 +913,43 @@ describe('Abstract pool test suite', () => {
     expect(result2).toBe(3628800)
     const result3 = await pool.execute(data, 'fibonacci')
     expect(result3).toBe(55)
+    expect(pool.info.executingTasks).toBe(0)
+    expect(pool.info.executedTasks).toBe(4)
+    for (const workerNode of pool.workerNodes) {
+      expect(workerNode.info.taskFunctions).toStrictEqual([
+        'default',
+        'jsonIntegerSerialization',
+        'factorial',
+        'fibonacci'
+      ])
+      expect(workerNode.taskFunctionsUsage.size).toBe(3)
+      for (const name of pool.listTaskFunctions()) {
+        expect(workerNode.getTaskFunctionWorkerUsage(name)).toStrictEqual({
+          tasks: {
+            executed: expect.any(Number),
+            executing: expect.any(Number),
+            failed: 0,
+            queued: 0
+          },
+          runTime: {
+            history: expect.any(CircularArray)
+          },
+          waitTime: {
+            history: expect.any(CircularArray)
+          },
+          elu: {
+            idle: {
+              history: expect.any(CircularArray)
+            },
+            active: {
+              history: expect.any(CircularArray)
+            }
+          }
+        })
+        expect(
+          workerNode.getTaskFunctionWorkerUsage(name).tasks.executing
+        ).toBeGreaterThanOrEqual(0)
+      }
+    }
   })
 })