test: improve coverage
[poolifier.git] / src / pools / selection-strategies / least-used-worker-choice-strategy.ts
index d9e3c20e1d56e951238cdbfc47ab2c4698ca999a..dc249e6523b9b792d52063185b1dffc3e8e37f6b 100644 (file)
@@ -11,8 +11,8 @@ import type {
  * Selects the least used worker.
  *
  * @typeParam Worker - Type of worker which manages the strategy.
- * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
- * @typeParam Response - Type of execution response. This can only be serializable data.
+ * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
+ * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
  */
 export class LeastUsedWorkerChoiceStrategy<
     Worker extends IWorker,
@@ -27,7 +27,7 @@ export class LeastUsedWorkerChoiceStrategy<
     opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
   ) {
     super(pool, opts)
-    this.setTaskStatistics(this.opts)
+    this.setTaskStatisticsRequirements(this.opts)
   }
 
   /** @inheritDoc */
@@ -41,28 +41,30 @@ export class LeastUsedWorkerChoiceStrategy<
   }
 
   /** @inheritDoc */
-  public choose (): number {
-    const freeWorkerNodeKey = this.findFreeWorkerNodeKey()
-    if (freeWorkerNodeKey !== -1) {
-      return freeWorkerNodeKey
-    }
-    let minNumberOfTasks = Infinity
-    let leastUsedWorkerNodeKey!: number
-    for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) {
-      const tasksUsage = workerNode.tasksUsage
-      const workerTasks = tasksUsage.ran + tasksUsage.running
-      if (workerTasks === 0) {
-        return workerNodeKey
-      } else if (workerTasks < minNumberOfTasks) {
-        minNumberOfTasks = workerTasks
-        leastUsedWorkerNodeKey = workerNodeKey
-      }
-    }
-    return leastUsedWorkerNodeKey
+  public choose (): number | undefined {
+    this.setPreviousWorkerNodeKey(this.nextWorkerNodeKey)
+    this.nextWorkerNodeKey = this.leastUsedNextWorkerNodeKey()
+    return this.nextWorkerNodeKey
   }
 
   /** @inheritDoc */
   public remove (): boolean {
     return true
   }
+
+  private leastUsedNextWorkerNodeKey (): number | undefined {
+    return this.pool.workerNodes.reduce(
+      (minWorkerNodeKey, workerNode, workerNodeKey, workerNodes) => {
+        return workerNode.usage.tasks.executed +
+          workerNode.usage.tasks.executing +
+          workerNode.usage.tasks.queued <
+          workerNodes[minWorkerNodeKey].usage.tasks.executed +
+            workerNodes[minWorkerNodeKey].usage.tasks.executing +
+            workerNodes[minWorkerNodeKey].usage.tasks.queued
+          ? workerNodeKey
+          : minWorkerNodeKey
+      },
+      0
+    )
+  }
 }