refactor: sensible defaults for worker choice strategy policy
[poolifier.git] / src / pools / selection-strategies / least-used-worker-choice-strategy.ts
index a505e6270aea7f19c458d1872aa2f69fe6b190cb..515b4e935db6e33fd5f3946c4f1b7cb0eb52a5f0 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,
@@ -37,31 +37,41 @@ export class LeastUsedWorkerChoiceStrategy<
 
   /** @inheritDoc */
   public update (): boolean {
-    let minNumberOfTasks = Infinity
-    for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) {
-      const workerTaskStatistics = workerNode.workerUsage.tasks
-      const workerTasks =
-        workerTaskStatistics.executed +
-        workerTaskStatistics.executing +
-        workerTaskStatistics.queued
-      if (workerTasks === 0) {
-        this.nextWorkerNodeId = workerNodeKey
-        return true
-      } else if (workerTasks < minNumberOfTasks) {
-        minNumberOfTasks = workerTasks
-        this.nextWorkerNodeId = workerNodeKey
-      }
-    }
     return true
   }
 
   /** @inheritDoc */
-  public choose (): number {
-    return this.nextWorkerNodeId
+  public choose (): number | undefined {
+    const chosenWorkerNodeKey = this.leastUsedNextWorkerNodeKey()
+    this.assignChosenWorkerNodeKey(chosenWorkerNodeKey)
+    return this.nextWorkerNodeKey
   }
 
   /** @inheritDoc */
   public remove (): boolean {
     return true
   }
+
+  private leastUsedNextWorkerNodeKey (): number | undefined {
+    let minNumberOfTasks = Infinity
+    let chosenWorkerNodeKey: number | undefined
+    for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) {
+      const workerTaskStatistics = workerNode.usage.tasks
+      const workerTasks =
+        workerTaskStatistics.executed +
+        workerTaskStatistics.executing +
+        workerTaskStatistics.queued
+      if (this.isWorkerNodeEligible(workerNodeKey) && workerTasks === 0) {
+        chosenWorkerNodeKey = workerNodeKey
+        break
+      } else if (
+        this.isWorkerNodeEligible(workerNodeKey) &&
+        workerTasks < minNumberOfTasks
+      ) {
+        minNumberOfTasks = workerTasks
+        chosenWorkerNodeKey = workerNodeKey
+      }
+    }
+    return chosenWorkerNodeKey
+  }
 }