test: add missing pool destroy() calls
[poolifier.git] / tests / pools / abstract / abstract-pool.test.js
index 03bcce050f35a2f8907f0974ddf8c1c8c828937d..75b0a35c288735450f0650bb81a88e22e639036d 100644 (file)
@@ -11,7 +11,8 @@ const {
   WorkerTypes
 } = require('../../../lib')
 const { CircularArray } = require('../../../lib/circular-array')
-const { Queue } = require('../../../lib/queue')
+const { Deque } = require('../../../lib/deque')
+const { DEFAULT_TASK_NAME } = require('../../../lib/utils')
 const { version } = require('../../../package.json')
 const { waitPoolEvents } = require('../../test-utils')
 
@@ -23,6 +24,10 @@ describe('Abstract pool test suite', () => {
     }
   }
 
+  afterEach(() => {
+    sinon.restore()
+  })
+
   it('Simulate pool creation from a non main thread/process', () => {
     expect(
       () =>
@@ -34,10 +39,23 @@ describe('Abstract pool test suite', () => {
           }
         )
     ).toThrowError(
-      'Cannot start a pool from a worker with the same type as the pool'
+      new Error(
+        'Cannot start a pool from a worker with the same type as the pool'
+      )
     )
   })
 
+  it('Verify that pool statuses properties are set', async () => {
+    const pool = new FixedThreadPool(
+      numberOfWorkers,
+      './tests/worker-files/thread/testWorker.js'
+    )
+    expect(pool.starting).toBe(false)
+    expect(pool.started).toBe(true)
+    await pool.destroy()
+    expect(pool.started).toBe(false)
+  })
+
   it('Verify that filePath is checked', () => {
     const expectedError = new Error(
       'Please specify a file with a worker implementation'
@@ -61,7 +79,9 @@ describe('Abstract pool test suite', () => {
 
   it('Verify that numberOfWorkers is checked', () => {
     expect(() => new FixedThreadPool()).toThrowError(
-      'Cannot instantiate a pool without specifying the number of workers'
+      new Error(
+        'Cannot instantiate a pool without specifying the number of workers'
+      )
     )
   })
 
@@ -134,22 +154,22 @@ describe('Abstract pool test suite', () => {
     )
     expect(
       () =>
-        new DynamicClusterPool(
-          1,
-          1,
-          './tests/worker-files/cluster/testWorker.js'
-        )
+        new DynamicThreadPool(0, 0, './tests/worker-files/thread/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'
+        'Cannot instantiate a dynamic pool with a maximum pool size equal to zero'
       )
     )
     expect(
       () =>
-        new DynamicThreadPool(0, 0, './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 maximum pool size equal to zero'
+        'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
       )
     )
   })
@@ -208,7 +228,10 @@ describe('Abstract pool test suite', () => {
     expect(pool.opts.enableEvents).toBe(false)
     expect(pool.opts.restartWorkerOnError).toBe(false)
     expect(pool.opts.enableTasksQueue).toBe(true)
-    expect(pool.opts.tasksQueueOptions).toStrictEqual({ concurrency: 2 })
+    expect(pool.opts.tasksQueueOptions).toStrictEqual({
+      concurrency: 2,
+      size: 4
+    })
     expect(pool.opts.workerChoiceStrategy).toBe(
       WorkerChoiceStrategies.LEAST_USED
     )
@@ -246,6 +269,38 @@ describe('Abstract pool test suite', () => {
     ).toThrowError(
       new Error("Invalid worker choice strategy 'invalidStrategy'")
     )
+    expect(
+      () =>
+        new FixedThreadPool(
+          numberOfWorkers,
+          './tests/worker-files/thread/testWorker.js',
+          {
+            workerChoiceStrategyOptions: {
+              choiceRetries: 'invalidChoiceRetries'
+            }
+          }
+        )
+    ).toThrowError(
+      new TypeError(
+        'Invalid worker choice strategy options: choice retries must be an integer'
+      )
+    )
+    expect(
+      () =>
+        new FixedThreadPool(
+          numberOfWorkers,
+          './tests/worker-files/thread/testWorker.js',
+          {
+            workerChoiceStrategyOptions: {
+              choiceRetries: -1
+            }
+          }
+        )
+    ).toThrowError(
+      new RangeError(
+        "Invalid worker choice strategy options: choice retries '-1' must be greater or equal than zero"
+      )
+    )
     expect(
       () =>
         new FixedThreadPool(
@@ -274,6 +329,19 @@ describe('Abstract pool test suite', () => {
         "Invalid worker choice strategy options: invalid measurement 'invalidMeasurement'"
       )
     )
+    expect(
+      () =>
+        new FixedThreadPool(
+          numberOfWorkers,
+          './tests/worker-files/thread/testWorker.js',
+          {
+            enableTasksQueue: true,
+            tasksQueueOptions: 'invalidTasksQueueOptions'
+          }
+        )
+    ).toThrowError(
+      new TypeError('Invalid tasks queue options: must be a plain object')
+    )
     expect(
       () =>
         new FixedThreadPool(
@@ -285,8 +353,8 @@ describe('Abstract pool test suite', () => {
           }
         )
     ).toThrowError(
-      new TypeError(
-        'Invalid worker tasks concurrency: 0 is a negative integer or zero'
+      new RangeError(
+        'Invalid worker node tasks concurrency: 0 is a negative integer or zero'
       )
     )
     expect(
@@ -296,11 +364,13 @@ describe('Abstract pool test suite', () => {
           './tests/worker-files/thread/testWorker.js',
           {
             enableTasksQueue: true,
-            tasksQueueOptions: 'invalidTasksQueueOptions'
+            tasksQueueOptions: { concurrency: -1 }
           }
         )
     ).toThrowError(
-      new TypeError('Invalid tasks queue options: must be a plain object')
+      new RangeError(
+        'Invalid worker node tasks concurrency: -1 is a negative integer or zero'
+      )
     )
     expect(
       () =>
@@ -313,7 +383,65 @@ describe('Abstract pool test suite', () => {
           }
         )
     ).toThrowError(
-      new TypeError('Invalid worker tasks concurrency: must be an integer')
+      new TypeError('Invalid worker node tasks concurrency: must be an integer')
+    )
+    expect(
+      () =>
+        new FixedThreadPool(
+          numberOfWorkers,
+          './tests/worker-files/thread/testWorker.js',
+          {
+            enableTasksQueue: true,
+            tasksQueueOptions: { queueMaxSize: 2 }
+          }
+        )
+    ).toThrowError(
+      new Error(
+        'Invalid tasks queue options: queueMaxSize is deprecated, please use size instead'
+      )
+    )
+    expect(
+      () =>
+        new FixedThreadPool(
+          numberOfWorkers,
+          './tests/worker-files/thread/testWorker.js',
+          {
+            enableTasksQueue: true,
+            tasksQueueOptions: { size: 0 }
+          }
+        )
+    ).toThrowError(
+      new RangeError(
+        'Invalid worker node tasks queue size: 0 is a negative integer or zero'
+      )
+    )
+    expect(
+      () =>
+        new FixedThreadPool(
+          numberOfWorkers,
+          './tests/worker-files/thread/testWorker.js',
+          {
+            enableTasksQueue: true,
+            tasksQueueOptions: { size: -1 }
+          }
+        )
+    ).toThrowError(
+      new RangeError(
+        'Invalid worker node tasks queue size: -1 is a negative integer or zero'
+      )
+    )
+    expect(
+      () =>
+        new FixedThreadPool(
+          numberOfWorkers,
+          './tests/worker-files/thread/testWorker.js',
+          {
+            enableTasksQueue: true,
+            tasksQueueOptions: { size: 0.2 }
+          }
+        )
+    ).toThrowError(
+      new TypeError('Invalid worker node tasks queue size: must be an integer')
     )
   })
 
@@ -458,6 +586,22 @@ describe('Abstract pool test suite', () => {
         'Invalid worker choice strategy options: must be a plain object'
       )
     )
+    expect(() =>
+      pool.setWorkerChoiceStrategyOptions({
+        choiceRetries: 'invalidChoiceRetries'
+      })
+    ).toThrowError(
+      new TypeError(
+        'Invalid worker choice strategy options: choice retries must be an integer'
+      )
+    )
+    expect(() =>
+      pool.setWorkerChoiceStrategyOptions({ choiceRetries: -1 })
+    ).toThrowError(
+      new RangeError(
+        "Invalid worker choice strategy options: choice retries '-1' must be greater or equal than zero"
+      )
+    )
     expect(() =>
       pool.setWorkerChoiceStrategyOptions({ weights: {} })
     ).toThrowError(
@@ -484,10 +628,16 @@ describe('Abstract pool test suite', () => {
     expect(pool.opts.tasksQueueOptions).toBeUndefined()
     pool.enableTasksQueue(true)
     expect(pool.opts.enableTasksQueue).toBe(true)
-    expect(pool.opts.tasksQueueOptions).toStrictEqual({ concurrency: 1 })
+    expect(pool.opts.tasksQueueOptions).toStrictEqual({
+      concurrency: 1,
+      size: 4
+    })
     pool.enableTasksQueue(true, { concurrency: 2 })
     expect(pool.opts.enableTasksQueue).toBe(true)
-    expect(pool.opts.tasksQueueOptions).toStrictEqual({ concurrency: 2 })
+    expect(pool.opts.tasksQueueOptions).toStrictEqual({
+      concurrency: 2,
+      size: 4
+    })
     pool.enableTasksQueue(false)
     expect(pool.opts.enableTasksQueue).toBe(false)
     expect(pool.opts.tasksQueueOptions).toBeUndefined()
@@ -500,26 +650,50 @@ describe('Abstract pool test suite', () => {
       './tests/worker-files/thread/testWorker.js',
       { enableTasksQueue: true }
     )
-    expect(pool.opts.tasksQueueOptions).toStrictEqual({ concurrency: 1 })
+    expect(pool.opts.tasksQueueOptions).toStrictEqual({
+      concurrency: 1,
+      size: 4
+    })
     pool.setTasksQueueOptions({ concurrency: 2 })
-    expect(pool.opts.tasksQueueOptions).toStrictEqual({ concurrency: 2 })
+    expect(pool.opts.tasksQueueOptions).toStrictEqual({
+      concurrency: 2,
+      size: 4
+    })
     expect(() =>
       pool.setTasksQueueOptions('invalidTasksQueueOptions')
     ).toThrowError(
       new TypeError('Invalid tasks queue options: must be a plain object')
     )
     expect(() => pool.setTasksQueueOptions({ concurrency: 0 })).toThrowError(
-      new Error(
-        'Invalid worker tasks concurrency: 0 is a negative integer or zero'
+      new RangeError(
+        'Invalid worker node tasks concurrency: 0 is a negative integer or zero'
       )
     )
     expect(() => pool.setTasksQueueOptions({ concurrency: -1 })).toThrowError(
-      new Error(
-        'Invalid worker tasks concurrency: -1 is a negative integer or zero'
+      new RangeError(
+        'Invalid worker node tasks concurrency: -1 is a negative integer or zero'
       )
     )
     expect(() => pool.setTasksQueueOptions({ concurrency: 0.2 })).toThrowError(
-      new TypeError('Invalid worker tasks concurrency: must be an integer')
+      new TypeError('Invalid worker node tasks concurrency: must be an integer')
+    )
+    expect(() => pool.setTasksQueueOptions({ queueMaxSize: 2 })).toThrowError(
+      new Error(
+        'Invalid tasks queue options: queueMaxSize is deprecated, please use size instead'
+      )
+    )
+    expect(() => pool.setTasksQueueOptions({ size: 0 })).toThrowError(
+      new RangeError(
+        'Invalid worker node tasks queue size: 0 is a negative integer or zero'
+      )
+    )
+    expect(() => pool.setTasksQueueOptions({ size: -1 })).toThrowError(
+      new RangeError(
+        'Invalid worker node tasks queue size: -1 is a negative integer or zero'
+      )
+    )
+    expect(() => pool.setTasksQueueOptions({ size: 0.2 })).toThrowError(
+      new TypeError('Invalid worker node tasks queue size: must be an integer')
     )
     await pool.destroy()
   })
@@ -580,6 +754,7 @@ describe('Abstract pool test suite', () => {
           executing: 0,
           queued: 0,
           maxQueued: 0,
+          stolen: 0,
           failed: 0
         },
         runTime: {
@@ -608,7 +783,7 @@ describe('Abstract pool test suite', () => {
     )
     for (const workerNode of pool.workerNodes) {
       expect(workerNode.tasksQueue).toBeDefined()
-      expect(workerNode.tasksQueue).toBeInstanceOf(Queue)
+      expect(workerNode.tasksQueue).toBeInstanceOf(Deque)
       expect(workerNode.tasksQueue.size).toBe(0)
       expect(workerNode.tasksQueue.maxSize).toBe(0)
     }
@@ -620,10 +795,11 @@ describe('Abstract pool test suite', () => {
     )
     for (const workerNode of pool.workerNodes) {
       expect(workerNode.tasksQueue).toBeDefined()
-      expect(workerNode.tasksQueue).toBeInstanceOf(Queue)
+      expect(workerNode.tasksQueue).toBeInstanceOf(Deque)
       expect(workerNode.tasksQueue.size).toBe(0)
       expect(workerNode.tasksQueue.maxSize).toBe(0)
     }
+    await pool.destroy()
   })
 
   it('Verify that pool worker info are initialized', async () => {
@@ -653,6 +829,30 @@ describe('Abstract pool test suite', () => {
         ready: true
       })
     }
+    await pool.destroy()
+  })
+
+  it('Verify that pool execute() arguments are checked', async () => {
+    const pool = new FixedClusterPool(
+      numberOfWorkers,
+      './tests/worker-files/cluster/testWorker.js'
+    )
+    await expect(pool.execute(undefined, 0)).rejects.toThrowError(
+      new TypeError('name argument must be a string')
+    )
+    await expect(pool.execute(undefined, '')).rejects.toThrowError(
+      new TypeError('name argument must not be an empty string')
+    )
+    await expect(pool.execute(undefined, undefined, {})).rejects.toThrowError(
+      new TypeError('transferList argument must be an array')
+    )
+    await expect(pool.execute(undefined, 'unknown')).rejects.toBe(
+      "Task function 'unknown' not found"
+    )
+    await pool.destroy()
+    await expect(pool.execute(undefined, undefined, {})).rejects.toThrowError(
+      new Error('Cannot execute a task on destroyed pool')
+    )
   })
 
   it('Verify that pool worker tasks usage are computed', async () => {
@@ -672,6 +872,7 @@ describe('Abstract pool test suite', () => {
           executing: maxMultiplier,
           queued: 0,
           maxQueued: 0,
+          stolen: 0,
           failed: 0
         },
         runTime: {
@@ -698,6 +899,7 @@ describe('Abstract pool test suite', () => {
           executing: 0,
           queued: 0,
           maxQueued: 0,
+          stolen: 0,
           failed: 0
         },
         runTime: {
@@ -738,6 +940,7 @@ describe('Abstract pool test suite', () => {
           executing: 0,
           queued: 0,
           maxQueued: 0,
+          stolen: 0,
           failed: 0
         },
         runTime: {
@@ -756,7 +959,9 @@ describe('Abstract pool test suite', () => {
         }
       })
       expect(workerNode.usage.tasks.executed).toBeGreaterThan(0)
-      expect(workerNode.usage.tasks.executed).toBeLessThanOrEqual(maxMultiplier)
+      expect(workerNode.usage.tasks.executed).toBeLessThanOrEqual(
+        numberOfWorkers * 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)
@@ -770,6 +975,7 @@ describe('Abstract pool test suite', () => {
           executing: 0,
           queued: 0,
           maxQueued: 0,
+          stolen: 0,
           failed: 0
         },
         runTime: {
@@ -900,7 +1106,7 @@ describe('Abstract pool test suite', () => {
     await pool.destroy()
   })
 
-  it.skip("Verify that pool event emitter 'backPressure' event can register a callback", async () => {
+  it("Verify that pool event emitter 'backPressure' event can register a callback", async () => {
     const pool = new FixedThreadPool(
       numberOfWorkers,
       './tests/worker-files/thread/testWorker.js',
@@ -908,13 +1114,7 @@ describe('Abstract pool test suite', () => {
         enableTasksQueue: true
       }
     )
-    for (const workerNode of pool.workerNodes) {
-      workerNode.hasBackPressure = sinon
-        .stub()
-        .onFirstCall()
-        .returns(true)
-        .returns(false)
-    }
+    sinon.stub(pool, 'hasBackPressure').returns(true)
     const promises = new Set()
     let poolBackPressure = 0
     let poolInfo
@@ -922,16 +1122,14 @@ describe('Abstract pool test suite', () => {
       ++poolBackPressure
       poolInfo = info
     })
-    for (let i = 0; i < numberOfWorkers * 2; i++) {
+    for (let i = 0; i < numberOfWorkers + 1; i++) {
       promises.add(pool.execute())
     }
-    // console.log(pool.info.backPressure)
     await Promise.all(promises)
-    // console.log(pool.info.backPressure)
     expect(poolBackPressure).toBe(1)
     expect(poolInfo).toStrictEqual({
       version,
-      type: PoolTypes.dynamic,
+      type: PoolTypes.fixed,
       worker: WorkerTypes.thread,
       ready: expect.any(Boolean),
       strategy: WorkerChoiceStrategies.ROUND_ROBIN,
@@ -942,8 +1140,13 @@ describe('Abstract pool test suite', () => {
       busyWorkerNodes: expect.any(Number),
       executedTasks: expect.any(Number),
       executingTasks: expect.any(Number),
+      maxQueuedTasks: expect.any(Number),
+      queuedTasks: expect.any(Number),
+      backPressure: true,
+      stolenTasks: expect.any(Number),
       failedTasks: expect.any(Number)
     })
+    expect(pool.hasBackPressure.called).toBe(true)
     await pool.destroy()
   })
 
@@ -955,7 +1158,7 @@ describe('Abstract pool test suite', () => {
     )
     await waitPoolEvents(dynamicThreadPool, PoolEvents.ready, 1)
     expect(dynamicThreadPool.listTaskFunctions()).toStrictEqual([
-      'default',
+      DEFAULT_TASK_NAME,
       'jsonIntegerSerialization',
       'factorial',
       'fibonacci'
@@ -966,11 +1169,13 @@ describe('Abstract pool test suite', () => {
     )
     await waitPoolEvents(fixedClusterPool, PoolEvents.ready, 1)
     expect(fixedClusterPool.listTaskFunctions()).toStrictEqual([
-      'default',
+      DEFAULT_TASK_NAME,
       'jsonIntegerSerialization',
       'factorial',
       'fibonacci'
     ])
+    await dynamicThreadPool.destroy()
+    await fixedClusterPool.destroy()
   })
 
   it('Verify that multiple task functions worker is working', async () => {
@@ -992,7 +1197,7 @@ describe('Abstract pool test suite', () => {
     expect(pool.info.executedTasks).toBe(4)
     for (const workerNode of pool.workerNodes) {
       expect(workerNode.info.taskFunctions).toStrictEqual([
-        'default',
+        DEFAULT_TASK_NAME,
         'jsonIntegerSerialization',
         'factorial',
         'fibonacci'
@@ -1004,7 +1209,8 @@ describe('Abstract pool test suite', () => {
             executed: expect.any(Number),
             executing: expect.any(Number),
             failed: 0,
-            queued: 0
+            queued: 0,
+            stolen: 0
           },
           runTime: {
             history: expect.any(CircularArray)
@@ -1026,5 +1232,6 @@ describe('Abstract pool test suite', () => {
         ).toBeGreaterThanOrEqual(0)
       }
     }
+    await pool.destroy()
   })
 })