perf: use a single map to store pool workers and their related data
authorJérôme Benoit <jerome.benoit@sap.com>
Sun, 2 Apr 2023 11:55:59 +0000 (13:55 +0200)
committerJérôme Benoit <jerome.benoit@sap.com>
Sun, 2 Apr 2023 11:55:59 +0000 (13:55 +0200)
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
18 files changed:
CHANGELOG.md
src/pools/abstract-pool.ts
src/pools/cluster/dynamic.ts
src/pools/pool-internal.ts
src/pools/selection-strategies/fair-share-worker-choice-strategy.ts
src/pools/selection-strategies/less-recently-used-worker-choice-strategy.ts
src/pools/selection-strategies/round-robin-worker-choice-strategy.ts
src/pools/selection-strategies/weighted-round-robin-worker-choice-strategy.ts
src/pools/thread/dynamic.ts
tests/pools/abstract/abstract-pool.test.js
tests/pools/cluster/dynamic.test.js
tests/pools/cluster/fixed.test.js
tests/pools/selection-strategies/selection-strategies.test.js
tests/pools/selection-strategies/weighted-round-robin-worker-choice-strategy.test.js
tests/pools/thread/dynamic.test.js
tests/pools/thread/fixed.test.js
tests/test-utils.js
tests/worker/thread-worker.test.js

index dc393afa0c3f7d7f15f55cf4875b89130d91617d..36db7f829fa91065b5fda757ae6753ed32faf0a6 100644 (file)
@@ -9,8 +9,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 
 ### Changed
 
+- Optimize worker storage in pool.
 - Optimize worker alive status check.
 
+### Fixed
+
+- Ensure trimmable characters are checked at pool initialization.
+
 ## [2.3.10] - 2023-03-18
 
 ### Fixed
index 122e9fa5c9dbbad12f7eaf01b1db4f0b38ab35e4..1d4e7ae0d07f18ede013a5fefda5f7430302584c 100644 (file)
@@ -6,7 +6,7 @@ import { EMPTY_FUNCTION } from '../utils'
 import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
 import type { PoolOptions } from './pool'
 import { PoolEmitter } from './pool'
-import type { IPoolInternal, TasksUsage } from './pool-internal'
+import type { IPoolInternal, TasksUsage, WorkerType } from './pool-internal'
 import { PoolType } from './pool-internal'
 import type { IPoolWorker } from './pool-worker'
 import {
@@ -28,21 +28,23 @@ export abstract class AbstractPool<
   Response = unknown
 > implements IPoolInternal<Worker, Data, Response> {
   /** {@inheritDoc} */
-  public readonly workers: Worker[] = []
-
-  /** {@inheritDoc} */
-  public readonly workersTasksUsage: Map<Worker, TasksUsage> = new Map<
-  Worker,
-  TasksUsage
+  public readonly workers: Map<number, WorkerType<Worker>> = new Map<
+  number,
+  WorkerType<Worker>
   >()
 
   /** {@inheritDoc} */
   public readonly emitter?: PoolEmitter
 
+  /**
+   * Id of the next worker.
+   */
+  protected nextWorkerId: number = 0
+
   /**
    * The promise map.
    *
-   * - `key`: This is the message Id of each submitted task.
+   * - `key`: This is the message id of each submitted task.
    * - `value`: An object that contains the worker, the resolve function and the reject function.
    *
    * When we receive a message from the worker we get a map entry and resolve/reject the promise based on the message.
@@ -115,7 +117,10 @@ export abstract class AbstractPool<
   }
 
   private checkFilePath (filePath: string): void {
-    if (filePath == null || filePath.length === 0) {
+    if (
+      filePath == null ||
+      (typeof filePath === 'string' && filePath.trim().length === 0)
+    ) {
       throw new Error('Please specify a file with a worker implementation')
     }
   }
@@ -152,19 +157,26 @@ export abstract class AbstractPool<
     return this.promiseMap.size
   }
 
-  /** {@inheritDoc} */
-  public getWorkerIndex (worker: Worker): number {
-    return this.workers.indexOf(worker)
+  /**
+   * Gets worker key.
+   *
+   * @param worker - The worker.
+   * @returns The worker key.
+   */
+  private getWorkerKey (worker: Worker): number | undefined {
+    return [...this.workers].find(([, value]) => value.worker === worker)?.[0]
   }
 
   /** {@inheritDoc} */
   public getWorkerRunningTasks (worker: Worker): number | undefined {
-    return this.workersTasksUsage.get(worker)?.running
+    return this.workers.get(this.getWorkerKey(worker) as number)?.tasksUsage
+      ?.running
   }
 
   /** {@inheritDoc} */
   public getWorkerAverageTasksRunTime (worker: Worker): number | undefined {
-    return this.workersTasksUsage.get(worker)?.avgRunTime
+    return this.workers.get(this.getWorkerKey(worker) as number)?.tasksUsage
+      ?.avgRunTime
   }
 
   /** {@inheritDoc} */
@@ -172,8 +184,13 @@ export abstract class AbstractPool<
     workerChoiceStrategy: WorkerChoiceStrategy
   ): void {
     this.opts.workerChoiceStrategy = workerChoiceStrategy
-    for (const worker of this.workers) {
-      this.resetWorkerTasksUsage(worker)
+    for (const [key, value] of this.workers) {
+      this.setWorker(key, value.worker, {
+        run: 0,
+        running: 0,
+        runTime: 0,
+        avgRunTime: 0
+      })
     }
     this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
       workerChoiceStrategy
@@ -192,10 +209,10 @@ export abstract class AbstractPool<
 
   /** {@inheritDoc} */
   public findFreeWorker (): Worker | false {
-    for (const worker of this.workers) {
-      if (this.getWorkerRunningTasks(worker) === 0) {
+    for (const value of this.workers.values()) {
+      if (value.tasksUsage.running === 0) {
         // A worker is free, return the matching worker
-        return worker
+        return value.worker
       }
     }
     return false
@@ -220,8 +237,8 @@ export abstract class AbstractPool<
   /** {@inheritDoc} */
   public async destroy (): Promise<void> {
     await Promise.all(
-      this.workers.map(async worker => {
-        await this.destroyWorker(worker)
+      [...this.workers].map(async ([, value]) => {
+        await this.destroyWorker(value.worker)
       })
     )
   }
@@ -278,9 +295,8 @@ export abstract class AbstractPool<
    * @param worker - The worker that will be removed.
    */
   protected removeWorker (worker: Worker): void {
-    // Clean worker from data structure
-    this.workers.splice(this.getWorkerIndex(worker), 1)
-    this.removeWorkerTasksUsage(worker)
+    this.workers.delete(this.getWorkerKey(worker) as number)
+    --this.nextWorkerId
   }
 
   /**
@@ -345,10 +361,13 @@ export abstract class AbstractPool<
       this.removeWorker(worker)
     })
 
-    this.workers.push(worker)
-
-    // Init worker tasks usage map
-    this.initWorkerTasksUsage(worker)
+    this.setWorker(this.nextWorkerId, worker, {
+      run: 0,
+      running: 0,
+      runTime: 0,
+      avgRunTime: 0
+    })
+    ++this.nextWorkerId
 
     this.afterWorkerSetup(worker)
 
@@ -411,6 +430,19 @@ export abstract class AbstractPool<
     this.stepWorkerRunningTasks(worker, -1)
   }
 
+  /**
+   * Get tasks usage of the given worker.
+   *
+   * @param worker - Worker which tasks usage is returned.
+   */
+  private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
+    if (this.checkWorker(worker)) {
+      const workerKey = this.getWorkerKey(worker) as number
+      const workerEntry = this.workers.get(workerKey) as WorkerType<Worker>
+      return workerEntry.tasksUsage
+    }
+  }
+
   /**
    * Steps the number of tasks that the given worker has applied.
    *
@@ -418,11 +450,8 @@ export abstract class AbstractPool<
    * @param step - Number of running tasks step.
    */
   private stepWorkerRunningTasks (worker: Worker, step: number): void {
-    if (this.checkWorkerTasksUsage(worker)) {
-      const tasksUsage = this.workersTasksUsage.get(worker) as TasksUsage
-      tasksUsage.running = tasksUsage.running + step
-      this.workersTasksUsage.set(worker, tasksUsage)
-    }
+    // prettier-ignore
+    (this.getWorkerTasksUsage(worker) as TasksUsage).running += step
   }
 
   /**
@@ -432,11 +461,8 @@ export abstract class AbstractPool<
    * @param step - Number of run tasks step.
    */
   private stepWorkerRunTasks (worker: Worker, step: number): void {
-    if (this.checkWorkerTasksUsage(worker)) {
-      const tasksUsage = this.workersTasksUsage.get(worker) as TasksUsage
-      tasksUsage.run = tasksUsage.run + step
-      this.workersTasksUsage.set(worker, tasksUsage)
-    }
+    // prettier-ignore
+    (this.getWorkerTasksUsage(worker) as TasksUsage).run += step
   }
 
   /**
@@ -451,62 +477,45 @@ export abstract class AbstractPool<
   ): void {
     if (
       this.workerChoiceStrategyContext.getWorkerChoiceStrategy()
-        .requiredStatistics.runTime &&
-      this.checkWorkerTasksUsage(worker)
+        .requiredStatistics.runTime
     ) {
-      const tasksUsage = this.workersTasksUsage.get(worker) as TasksUsage
-      tasksUsage.runTime += taskRunTime ?? 0
-      if (tasksUsage.run !== 0) {
-        tasksUsage.avgRunTime = tasksUsage.runTime / tasksUsage.run
+      const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage
+      workerTasksUsage.runTime += taskRunTime ?? 0
+      if (workerTasksUsage.run !== 0) {
+        workerTasksUsage.avgRunTime =
+          workerTasksUsage.runTime / workerTasksUsage.run
       }
-      this.workersTasksUsage.set(worker, tasksUsage)
     }
   }
 
   /**
-   * Checks if the given worker is registered in the workers tasks usage map.
-   *
-   * @param worker - Worker to check.
-   * @returns `true` if the worker is registered in the workers tasks usage map. `false` otherwise.
-   */
-  private checkWorkerTasksUsage (worker: Worker): boolean {
-    const hasTasksUsage = this.workersTasksUsage.has(worker)
-    if (!hasTasksUsage) {
-      throw new Error('Worker could not be found in workers tasks usage map')
-    }
-    return hasTasksUsage
-  }
-
-  /**
-   * Initializes tasks usage statistics.
+   * Sets the given worker.
    *
+   * @param workerKey - The worker key.
    * @param worker - The worker.
+   * @param tasksUsage - The worker tasks usage.
    */
-  private initWorkerTasksUsage (worker: Worker): void {
-    this.workersTasksUsage.set(worker, {
-      run: 0,
-      running: 0,
-      runTime: 0,
-      avgRunTime: 0
+  private setWorker (
+    workerKey: number,
+    worker: Worker,
+    tasksUsage: TasksUsage
+  ): void {
+    this.workers.set(workerKey, {
+      worker,
+      tasksUsage
     })
   }
 
   /**
-   * Removes worker tasks usage statistics.
-   *
-   * @param worker - The worker.
-   */
-  private removeWorkerTasksUsage (worker: Worker): void {
-    this.workersTasksUsage.delete(worker)
-  }
-
-  /**
-   * Resets worker tasks usage statistics.
+   * Checks if the given worker is registered in the pool.
    *
-   * @param worker - The worker.
+   * @param worker - Worker to check.
+   * @returns `true` if the worker is registered in the pool.
    */
-  private resetWorkerTasksUsage (worker: Worker): void {
-    this.removeWorkerTasksUsage(worker)
-    this.initWorkerTasksUsage(worker)
+  private checkWorker (worker: Worker): boolean {
+    if (this.getWorkerKey(worker) == null) {
+      throw new Error('Worker could not be found in the pool')
+    }
+    return true
   }
 }
index 8b8c5185772dbea59bc0d22b2e1cb90b9383d507..0a2d0f3879fc6ab44129608fec6d9c6624cd4c1a 100644 (file)
@@ -41,6 +41,6 @@ export class DynamicClusterPool<
 
   /** {@inheritDoc} */
   public get busy (): boolean {
-    return this.workers.length === this.max
+    return this.workers.size === this.max
   }
 }
index e0d0534f83a846cbfac77eb87e305e0975c49abf..97e5d5d2d56ae75435b19d1ccb8afae10ff2e8ed 100644 (file)
@@ -19,6 +19,16 @@ export interface TasksUsage {
   avgRunTime: number
 }
 
+/**
+ * Internal worker type.
+ *
+ * @typeParam Worker - Type of worker which manages this pool.
+ */
+export interface WorkerType<Worker extends IPoolWorker> {
+  worker: Worker
+  tasksUsage: TasksUsage
+}
+
 /**
  * Internal contract definition for a poolifier pool.
  *
@@ -32,17 +42,9 @@ export interface IPoolInternal<
   Response = unknown
 > extends IPool<Data, Response> {
   /**
-   * List of currently available workers.
+   * Map of workers.
    */
-  readonly workers: Worker[]
-
-  /**
-   * The workers tasks usage map.
-   *
-   *  `key`: The `Worker`
-   *  `value`: Worker tasks usage statistics.
-   */
-  readonly workersTasksUsage: Map<Worker, TasksUsage>
+  readonly workers: Map<number, WorkerType<Worker>>
 
   /**
    * Pool type.
@@ -74,14 +76,6 @@ export interface IPoolInternal<
    */
   findFreeWorker: () => Worker | false
 
-  /**
-   * Gets worker index.
-   *
-   * @param worker - The worker.
-   * @returns The worker index.
-   */
-  getWorkerIndex: (worker: Worker) => number
-
   /**
    * Gets worker running tasks.
    *
index 00ed1c90aa53592ca1de2b067273f4e6f1de2693..8b063119f95e2df2714e57f26bff13404e3b3e0c 100644 (file)
@@ -46,7 +46,8 @@ export class FairShareWorkerChoiceStrategy<
   public choose (): Worker {
     let minWorkerVirtualTaskEndTimestamp = Infinity
     let chosenWorker!: Worker
-    for (const worker of this.pool.workers) {
+    for (const value of this.pool.workers.values()) {
+      const worker = value.worker
       this.computeWorkerLastVirtualTaskTimestamp(worker)
       const workerLastVirtualTaskEndTimestamp =
         this.workerLastVirtualTaskTimestamp.get(worker)?.end ?? 0
index e62d9cdf83bd9a5ae472bc08296dfbe18b96e806..467cf2c6e39ff102360e6df25617134fa7129885 100644 (file)
@@ -23,7 +23,8 @@ export class LessRecentlyUsedWorkerChoiceStrategy<
     let minNumberOfRunningTasks = Infinity
     // A worker is always found because it picks the one with fewer tasks
     let lessRecentlyUsedWorker!: Worker
-    for (const worker of this.pool.workers) {
+    for (const value of this.pool.workers.values()) {
+      const worker = value.worker
       const workerRunningTasks = this.pool.getWorkerRunningTasks(
         worker
       ) as number
index 76cdd4abac3ff7a2c5a5988cf76e66d87ab9be9b..44dfa4b76a941fe6caa005fe07bf5dc5ccd34644 100644 (file)
@@ -14,23 +14,24 @@ export class RoundRobinWorkerChoiceStrategy<
   Response
 > extends AbstractWorkerChoiceStrategy<Worker, Data, Response> {
   /**
-   * Index for the next worker.
+   * Id of the next worker.
    */
-  private nextWorkerIndex: number = 0
+  private nextWorkerId: number = 0
 
   /** {@inheritDoc} */
   public reset (): boolean {
-    this.nextWorkerIndex = 0
+    this.nextWorkerId = 0
     return true
   }
 
   /** {@inheritDoc} */
   public choose (): Worker {
-    const chosenWorker = this.pool.workers[this.nextWorkerIndex]
-    this.nextWorkerIndex =
-      this.nextWorkerIndex === this.pool.workers.length - 1
+    const chosenWorker = this.pool.workers.get(this.nextWorkerId)
+      ?.worker as Worker
+    this.nextWorkerId =
+      this.nextWorkerId === this.pool.workers.size - 1
         ? 0
-        : this.nextWorkerIndex + 1
+        : this.nextWorkerId + 1
     return chosenWorker
   }
 }
index 2b7cd9420d209effcf8fc0b251c805770c30c0b2..fc9b069522c8366226836a28bac08518dc23b969 100644 (file)
@@ -31,9 +31,9 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
   }
 
   /**
-   * Worker index where the current task will be submitted.
+   * Worker id where the current task will be submitted.
    */
-  private currentWorkerIndex: number = 0
+  private currentWorkerId: number = 0
   /**
    * Default worker weight.
    */
@@ -59,7 +59,7 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
 
   /** {@inheritDoc} */
   public reset (): boolean {
-    this.currentWorkerIndex = 0
+    this.currentWorkerId = 0
     this.workersTaskRunTime.clear()
     this.initWorkersTaskRunTime()
     return true
@@ -67,7 +67,8 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
 
   /** {@inheritDoc} */
   public choose (): Worker {
-    const chosenWorker = this.pool.workers[this.currentWorkerIndex]
+    const chosenWorker = this.pool.workers.get(this.currentWorkerId)
+      ?.worker as Worker
     if (this.isDynamicPool && !this.workersTaskRunTime.has(chosenWorker)) {
       this.initWorkerTaskRunTime(chosenWorker)
     }
@@ -84,12 +85,12 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
           (this.getWorkerVirtualTaskRunTime(chosenWorker) ?? 0)
       )
     } else {
-      this.currentWorkerIndex =
-        this.currentWorkerIndex === this.pool.workers.length - 1
+      this.currentWorkerId =
+        this.currentWorkerId === this.pool.workers.size - 1
           ? 0
-          : this.currentWorkerIndex + 1
+          : this.currentWorkerId + 1
       this.setWorkerTaskRunTime(
-        this.pool.workers[this.currentWorkerIndex],
+        this.pool.workers.get(this.currentWorkerId)?.worker as Worker,
         workerTaskWeight,
         0
       )
@@ -98,8 +99,8 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
   }
 
   private initWorkersTaskRunTime (): void {
-    for (const worker of this.pool.workers) {
-      this.initWorkerTaskRunTime(worker)
+    for (const value of this.pool.workers.values()) {
+      this.initWorkerTaskRunTime(value.worker)
     }
   }
 
index 19cb9fbf6b9a21a649c9fe548955e62abc6c750f..d5be43f189f469b46ce16ef9bcdbf4720e33b593 100644 (file)
@@ -42,6 +42,6 @@ export class DynamicThreadPool<
 
   /** {@inheritDoc} */
   public get busy (): boolean {
-    return this.workers.length === this.max
+    return this.workers.size === this.max
   }
 }
index 80ebdb9e7e5a04b07f71f7878ed46318cbcd4fdb..e6a7ad36cc5ae2ae5839fdd42497bbd86ce0cd9c 100644 (file)
@@ -9,12 +9,11 @@ const {
 describe('Abstract pool test suite', () => {
   const numberOfWorkers = 1
   const workerNotFoundInTasksUsageMapError = new Error(
-    'Worker could not be found in workers tasks usage map'
+    'Worker could not be found in the pool'
   )
   class StubPoolWithRemoveAllWorker extends FixedThreadPool {
     removeAllWorker () {
-      this.workers = []
-      this.workersTasksUsage.clear()
+      this.workers = new Map()
       this.promiseMap.clear()
     }
   }
@@ -200,12 +199,12 @@ describe('Abstract pool test suite', () => {
       numberOfWorkers,
       './tests/worker-files/cluster/testWorker.js'
     )
-    for (const tasksUsage of pool.workersTasksUsage.values()) {
-      expect(tasksUsage).toBeDefined()
-      expect(tasksUsage.run).toBe(0)
-      expect(tasksUsage.running).toBe(0)
-      expect(tasksUsage.runTime).toBe(0)
-      expect(tasksUsage.avgRunTime).toBe(0)
+    for (const value of pool.workers.values()) {
+      expect(value.tasksUsage).toBeDefined()
+      expect(value.tasksUsage.run).toBe(0)
+      expect(value.tasksUsage.running).toBe(0)
+      expect(value.tasksUsage.runTime).toBe(0)
+      expect(value.tasksUsage.avgRunTime).toBe(0)
     }
     await pool.destroy()
   })
@@ -219,20 +218,20 @@ describe('Abstract pool test suite', () => {
     for (let i = 0; i < numberOfWorkers * 2; i++) {
       promises.push(pool.execute())
     }
-    for (const tasksUsage of pool.workersTasksUsage.values()) {
-      expect(tasksUsage).toBeDefined()
-      expect(tasksUsage.run).toBe(0)
-      expect(tasksUsage.running).toBe(numberOfWorkers * 2)
-      expect(tasksUsage.runTime).toBe(0)
-      expect(tasksUsage.avgRunTime).toBe(0)
+    for (const value of pool.workers.values()) {
+      expect(value.tasksUsage).toBeDefined()
+      expect(value.tasksUsage.run).toBe(0)
+      expect(value.tasksUsage.running).toBe(numberOfWorkers * 2)
+      expect(value.tasksUsage.runTime).toBe(0)
+      expect(value.tasksUsage.avgRunTime).toBe(0)
     }
     await Promise.all(promises)
-    for (const tasksUsage of pool.workersTasksUsage.values()) {
-      expect(tasksUsage).toBeDefined()
-      expect(tasksUsage.run).toBe(numberOfWorkers * 2)
-      expect(tasksUsage.running).toBe(0)
-      expect(tasksUsage.runTime).toBeGreaterThanOrEqual(0)
-      expect(tasksUsage.avgRunTime).toBeGreaterThanOrEqual(0)
+    for (const value of pool.workers.values()) {
+      expect(value.tasksUsage).toBeDefined()
+      expect(value.tasksUsage.run).toBe(numberOfWorkers * 2)
+      expect(value.tasksUsage.running).toBe(0)
+      expect(value.tasksUsage.runTime).toBeGreaterThanOrEqual(0)
+      expect(value.tasksUsage.avgRunTime).toBeGreaterThanOrEqual(0)
     }
     await pool.destroy()
   })
@@ -248,20 +247,20 @@ describe('Abstract pool test suite', () => {
       promises.push(pool.execute())
     }
     await Promise.all(promises)
-    for (const tasksUsage of pool.workersTasksUsage.values()) {
-      expect(tasksUsage).toBeDefined()
-      expect(tasksUsage.run).toBe(numberOfWorkers * 2)
-      expect(tasksUsage.running).toBe(0)
-      expect(tasksUsage.runTime).toBeGreaterThanOrEqual(0)
-      expect(tasksUsage.avgRunTime).toBeGreaterThanOrEqual(0)
+    for (const value of pool.workers.values()) {
+      expect(value.tasksUsage).toBeDefined()
+      expect(value.tasksUsage.run).toBe(numberOfWorkers * 2)
+      expect(value.tasksUsage.running).toBe(0)
+      expect(value.tasksUsage.runTime).toBeGreaterThanOrEqual(0)
+      expect(value.tasksUsage.avgRunTime).toBeGreaterThanOrEqual(0)
     }
     pool.setWorkerChoiceStrategy(WorkerChoiceStrategies.FAIR_SHARE)
-    for (const tasksUsage of pool.workersTasksUsage.values()) {
-      expect(tasksUsage).toBeDefined()
-      expect(tasksUsage.run).toBe(0)
-      expect(tasksUsage.running).toBe(0)
-      expect(tasksUsage.runTime).toBe(0)
-      expect(tasksUsage.avgRunTime).toBe(0)
+    for (const value of pool.workers.values()) {
+      expect(value.tasksUsage).toBeDefined()
+      expect(value.tasksUsage.run).toBe(0)
+      expect(value.tasksUsage.running).toBe(0)
+      expect(value.tasksUsage.runTime).toBe(0)
+      expect(value.tasksUsage.avgRunTime).toBe(0)
     }
     await pool.destroy()
   })
index b1fd166e87b6be473d9e697a57af7fbc017e9ea9..7a834ca237d64df507036ee797b7c6e315d140fe 100644 (file)
@@ -28,12 +28,12 @@ describe('Dynamic cluster pool test suite', () => {
 
   it('Verify that new workers are created when required, max size is not exceeded and that after a while new workers will die', async () => {
     let poolBusy = 0
-    pool.emitter.on('busy', () => poolBusy++)
+    pool.emitter.on('busy', () => ++poolBusy)
     for (let i = 0; i < max * 2; i++) {
       pool.execute()
     }
-    expect(pool.workers.length).toBeLessThanOrEqual(max)
-    expect(pool.workers.length).toBeGreaterThan(min)
+    expect(pool.workers.size).toBeLessThanOrEqual(max)
+    expect(pool.workers.size).toBeGreaterThan(min)
     // The `busy` event is triggered when the number of submitted tasks at once reach the max number of workers in the dynamic pool.
     // So in total numberOfWorkers + 1 times for a loop submitting up to numberOfWorkers * 2 tasks to the dynamic pool.
     expect(poolBusy).toBe(max + 1)
@@ -42,19 +42,19 @@ describe('Dynamic cluster pool test suite', () => {
   })
 
   it('Verify scale worker up and down is working', async () => {
-    expect(pool.workers.length).toBe(min)
+    expect(pool.workers.size).toBe(min)
     for (let i = 0; i < max * 10; i++) {
       pool.execute()
     }
-    expect(pool.workers.length).toBeGreaterThan(min)
+    expect(pool.workers.size).toBeGreaterThan(min)
     await TestUtils.waitExits(pool, max - min)
-    expect(pool.workers.length).toBe(min)
+    expect(pool.workers.size).toBe(min)
     for (let i = 0; i < max * 10; i++) {
       pool.execute()
     }
-    expect(pool.workers.length).toBeGreaterThan(min)
+    expect(pool.workers.size).toBeGreaterThan(min)
     await TestUtils.waitExits(pool, max - min)
-    expect(pool.workers.length).toBe(min)
+    expect(pool.workers.size).toBe(min)
   })
 
   it('Shutdown test', async () => {
@@ -93,14 +93,14 @@ describe('Dynamic cluster pool test suite', () => {
         exitHandler: () => console.log('long running worker exited')
       }
     )
-    expect(longRunningPool.workers.length).toBe(min)
+    expect(longRunningPool.workers.size).toBe(min)
     for (let i = 0; i < max * 10; i++) {
       longRunningPool.execute()
     }
-    expect(longRunningPool.workers.length).toBe(max)
+    expect(longRunningPool.workers.size).toBe(max)
     await TestUtils.waitExits(longRunningPool, max - min)
     // Here we expect the workers to be at the max size since that the task is still running
-    expect(longRunningPool.workers.length).toBe(min)
+    expect(longRunningPool.workers.size).toBe(min)
     // We need to clean up the resources after our test
     await longRunningPool.destroy()
   })
@@ -116,14 +116,14 @@ describe('Dynamic cluster pool test suite', () => {
         exitHandler: () => console.log('long running worker exited')
       }
     )
-    expect(longRunningPool.workers.length).toBe(min)
+    expect(longRunningPool.workers.size).toBe(min)
     for (let i = 0; i < max * 10; i++) {
       longRunningPool.execute()
     }
-    expect(longRunningPool.workers.length).toBe(max)
+    expect(longRunningPool.workers.size).toBe(max)
     await TestUtils.sleep(1500)
     // Here we expect the workers to be at the max size since that the task is still running
-    expect(longRunningPool.workers.length).toBe(max)
+    expect(longRunningPool.workers.size).toBe(max)
     // We need to clean up the resources after our test
     await longRunningPool.destroy()
   })
index b0e39c308ae6b3d5b0c45396fde375f1c9605143..ae899625dd9341dc4f9cfad3f40fab109587eb27 100644 (file)
@@ -67,7 +67,7 @@ describe('Fixed cluster pool test suite', () => {
 
   it('Verify that busy event is emitted', async () => {
     let poolBusy = 0
-    pool.emitter.on('busy', () => poolBusy++)
+    pool.emitter.on('busy', () => ++poolBusy)
     for (let i = 0; i < numberOfWorkers * 2; i++) {
       pool.execute()
     }
index 93d85ea6e419e52a1d3e861f18b485ea688fd580..c55b971edb8a9ed3e47ccae1db4b0deff206b08b 100644 (file)
@@ -42,7 +42,7 @@ describe('Selection strategies test suite', () => {
       WorkerChoiceStrategies.ROUND_ROBIN
     )
     expect(
-      pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().nextWorkerIndex
+      pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().nextWorkerId
     ).toBe(0)
     // We need to clean up the resources after our test
     await pool.destroy()
@@ -153,11 +153,11 @@ describe('Selection strategies test suite', () => {
       { workerChoiceStrategy: WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN }
     )
     expect(
-      pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().nextWorkerIndex
+      pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().nextWorkerId
     ).toBeUndefined()
     pool.setWorkerChoiceStrategy(WorkerChoiceStrategies.ROUND_ROBIN)
     expect(
-      pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().nextWorkerIndex
+      pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().nextWorkerId
     ).toBe(0)
     await pool.destroy()
     pool = new DynamicThreadPool(
@@ -168,12 +168,12 @@ describe('Selection strategies test suite', () => {
     )
     expect(
       pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
-        .workerChoiceStrategy.nextWorkerIndex
+        .workerChoiceStrategy.nextWorkerId
     ).toBeUndefined()
     pool.setWorkerChoiceStrategy(WorkerChoiceStrategies.ROUND_ROBIN)
     expect(
       pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
-        .workerChoiceStrategy.nextWorkerIndex
+        .workerChoiceStrategy.nextWorkerId
     ).toBe(0)
     // We need to clean up the resources after our test
     await pool.destroy()
@@ -424,8 +424,7 @@ describe('Selection strategies test suite', () => {
       WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN
     )
     expect(
-      pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
-        .currentWorkerIndex
+      pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().currentWorkerId
     ).toBe(0)
     expect(
       pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
@@ -526,8 +525,7 @@ describe('Selection strategies test suite', () => {
       './tests/worker-files/thread/testWorker.js'
     )
     expect(
-      pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
-        .currentWorkerIndex
+      pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().currentWorkerId
     ).toBeUndefined()
     expect(
       pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
@@ -539,8 +537,7 @@ describe('Selection strategies test suite', () => {
     ).toBeUndefined()
     pool.setWorkerChoiceStrategy(WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN)
     expect(
-      pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
-        .currentWorkerIndex
+      pool.workerChoiceStrategyContext.getWorkerChoiceStrategy().currentWorkerId
     ).toBe(0)
     expect(
       pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
@@ -563,7 +560,7 @@ describe('Selection strategies test suite', () => {
     )
     expect(
       pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
-        .workerChoiceStrategy.currentWorkerIndex
+        .workerChoiceStrategy.currentWorkerId
     ).toBeUndefined()
     expect(
       pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
@@ -576,7 +573,7 @@ describe('Selection strategies test suite', () => {
     pool.setWorkerChoiceStrategy(WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN)
     expect(
       pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
-        .workerChoiceStrategy.currentWorkerIndex
+        .workerChoiceStrategy.currentWorkerId
     ).toBe(0)
     expect(
       pool.workerChoiceStrategyContext.getWorkerChoiceStrategy()
index d8ae8299cfd12874303c4c24e5875afb631585be..cc3e66a49e752b349e4ae8153facbddfadca81ac 100644 (file)
@@ -25,7 +25,7 @@ describe('Weighted round robin strategy worker choice strategy test suite', () =
 
   it('Verify that reset() resets internals', () => {
     const strategy = new WeightedRoundRobinWorkerChoiceStrategy(pool)
-    strategy.currentWorkerIndex = TestUtils.generateRandomInteger()
+    strategy.currentWorkerId = TestUtils.generateRandomInteger()
     const workersTaskRunTimeClearStub = sinon
       .stub(strategy.workersTaskRunTime, 'clear')
       .returns()
@@ -34,7 +34,7 @@ describe('Weighted round robin strategy worker choice strategy test suite', () =
       .returns()
     const resetResult = strategy.reset()
     expect(resetResult).toBe(true)
-    expect(strategy.currentWorkerIndex).toBe(0)
+    expect(strategy.currentWorkerId).toBe(0)
     expect(workersTaskRunTimeClearStub.calledOnce).toBe(true)
     expect(initWorkersTaskRunTimeStub.calledOnce).toBe(true)
   })
index fad9dab8cbe3440e26a1f8e97b07b300ed662d04..b544452fce8351a9ed9f10136f45547b53b2b343 100644 (file)
@@ -28,12 +28,12 @@ describe('Dynamic thread pool test suite', () => {
 
   it('Verify that new workers are created when required, max size is not exceeded and that after a while new workers will die', async () => {
     let poolBusy = 0
-    pool.emitter.on('busy', () => poolBusy++)
+    pool.emitter.on('busy', () => ++poolBusy)
     for (let i = 0; i < max * 2; i++) {
       pool.execute()
     }
-    expect(pool.workers.length).toBeLessThanOrEqual(max)
-    expect(pool.workers.length).toBeGreaterThan(min)
+    expect(pool.workers.size).toBeLessThanOrEqual(max)
+    expect(pool.workers.size).toBeGreaterThan(min)
     // The `busy` event is triggered when the number of submitted tasks at once reach the max number of workers in the dynamic pool.
     // So in total numberOfWorkers + 1 times for a loop submitting up to numberOfWorkers * 2 tasks to the dynamic pool.
     expect(poolBusy).toBe(max + 1)
@@ -42,19 +42,19 @@ describe('Dynamic thread pool test suite', () => {
   })
 
   it('Verify scale thread up and down is working', async () => {
-    expect(pool.workers.length).toBe(min)
+    expect(pool.workers.size).toBe(min)
     for (let i = 0; i < max * 10; i++) {
       pool.execute()
     }
-    expect(pool.workers.length).toBe(max)
+    expect(pool.workers.size).toBe(max)
     await TestUtils.waitExits(pool, max - min)
-    expect(pool.workers.length).toBe(min)
+    expect(pool.workers.size).toBe(min)
     for (let i = 0; i < max * 10; i++) {
       pool.execute()
     }
-    expect(pool.workers.length).toBe(max)
+    expect(pool.workers.size).toBe(max)
     await TestUtils.waitExits(pool, max - min)
-    expect(pool.workers.length).toBe(min)
+    expect(pool.workers.size).toBe(min)
   })
 
   it('Shutdown test', async () => {
@@ -93,13 +93,13 @@ describe('Dynamic thread pool test suite', () => {
         exitHandler: () => console.log('long running worker exited')
       }
     )
-    expect(longRunningPool.workers.length).toBe(min)
+    expect(longRunningPool.workers.size).toBe(min)
     for (let i = 0; i < max * 10; i++) {
       longRunningPool.execute()
     }
-    expect(longRunningPool.workers.length).toBe(max)
+    expect(longRunningPool.workers.size).toBe(max)
     await TestUtils.waitExits(longRunningPool, max - min)
-    expect(longRunningPool.workers.length).toBe(min)
+    expect(longRunningPool.workers.size).toBe(min)
     // We need to clean up the resources after our test
     await longRunningPool.destroy()
   })
@@ -115,14 +115,14 @@ describe('Dynamic thread pool test suite', () => {
         exitHandler: () => console.log('long running worker exited')
       }
     )
-    expect(longRunningPool.workers.length).toBe(min)
+    expect(longRunningPool.workers.size).toBe(min)
     for (let i = 0; i < max * 10; i++) {
       longRunningPool.execute()
     }
-    expect(longRunningPool.workers.length).toBe(max)
+    expect(longRunningPool.workers.size).toBe(max)
     await TestUtils.sleep(1500)
     // Here we expect the workers to be at the max size since that the task is still running
-    expect(longRunningPool.workers.length).toBe(max)
+    expect(longRunningPool.workers.size).toBe(max)
     // We need to clean up the resources after our test
     await longRunningPool.destroy()
   })
index 116a17da8640bc97a01715970137817dca078077..fd9ce5dfe799a7f8e707bcdb843f875dfe0fbd5a 100644 (file)
@@ -67,7 +67,7 @@ describe('Fixed thread pool test suite', () => {
 
   it('Verify that busy event is emitted', async () => {
     let poolBusy = 0
-    pool.emitter.on('busy', () => poolBusy++)
+    pool.emitter.on('busy', () => ++poolBusy)
     for (let i = 0; i < numberOfThreads * 2; i++) {
       pool.execute()
     }
index 84bec7e560f7eae6a7bd9a420338b63ff866bec5..7314f261dffee839dd15e44b26eece688920ecfa 100644 (file)
@@ -4,9 +4,9 @@ class TestUtils {
   static async waitExits (pool, numberOfExitEventsToWait) {
     return new Promise(resolve => {
       let exitEvents = 0
-      for (const worker of pool.workers) {
-        worker.on('exit', () => {
-          exitEvents++
+      for (const value of pool.workers.values()) {
+        value.worker.on('exit', () => {
+          ++exitEvents
           if (exitEvents === numberOfExitEventsToWait) {
             resolve(exitEvents)
           }
index c04d3b2f0e980f7fa782a77f56046faae901eafc..624e395c04f80cb752adc73f8e95d84b19300dab 100644 (file)
@@ -4,7 +4,7 @@ const { ThreadWorker } = require('../../lib')
 describe('Thread worker test suite', () => {
   let numberOfMessagesPosted = 0
   const postMessage = function () {
-    numberOfMessagesPosted++
+    ++numberOfMessagesPosted
   }
   class SpyWorker extends ThreadWorker {
     getMainWorker () {