fix: update worker choice internals without tasks queuing
[poolifier.git] / src / pools / selection-strategies / least-used-worker-choice-strategy.ts
index d9e3c20e1d56e951238cdbfc47ab2c4698ca999a..a505e6270aea7f19c458d1872aa2f69fe6b190cb 100644 (file)
@@ -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 */
@@ -37,28 +37,27 @@ export class LeastUsedWorkerChoiceStrategy<
 
   /** @inheritDoc */
   public update (): boolean {
-    return true
-  }
-
-  /** @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
+      const workerTaskStatistics = workerNode.workerUsage.tasks
+      const workerTasks =
+        workerTaskStatistics.executed +
+        workerTaskStatistics.executing +
+        workerTaskStatistics.queued
       if (workerTasks === 0) {
-        return workerNodeKey
+        this.nextWorkerNodeId = workerNodeKey
+        return true
       } else if (workerTasks < minNumberOfTasks) {
         minNumberOfTasks = workerTasks
-        leastUsedWorkerNodeKey = workerNodeKey
+        this.nextWorkerNodeId = workerNodeKey
       }
     }
-    return leastUsedWorkerNodeKey
+    return true
+  }
+
+  /** @inheritDoc */
+  public choose (): number {
+    return this.nextWorkerNodeId
   }
 
   /** @inheritDoc */