build(deps): bump poolifier
[poolifier.git] / src / pools / selection-strategies / weighted-round-robin-worker-choice-strategy.ts
index c87081a6161c82ab612d5aca2b37a49e6b1089b0..22bf458febd3734a7f147c27172b486acdde5169 100644 (file)
@@ -42,9 +42,9 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
    */
   private readonly defaultWorkerWeight: number
   /**
-   * Worker virtual task runtime.
+   * Worker node virtual task runtime.
    */
-  private workerVirtualTaskRunTime: number = 0
+  private workerNodeVirtualTaskRunTime: number = 0
 
   /** @inheritDoc */
   public constructor (
@@ -59,7 +59,7 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
   /** @inheritDoc */
   public reset (): boolean {
     this.resetWorkerNodeKeyProperties()
-    this.workerVirtualTaskRunTime = 0
+    this.workerNodeVirtualTaskRunTime = 0
     return true
   }
 
@@ -80,7 +80,10 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
       this.reset()
     }
     if (this.nextWorkerNodeKey === workerNodeKey) {
-      this.workerVirtualTaskRunTime = 0
+      this.workerNodeVirtualTaskRunTime = 0
+      if (this.nextWorkerNodeKey > this.pool.workerNodes.length - 1) {
+        this.nextWorkerNodeKey = this.pool.workerNodes.length - 1
+      }
     }
     if (
       this.previousWorkerNodeKey === workerNodeKey &&
@@ -92,23 +95,25 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
   }
 
   private weightedRoundRobinNextWorkerNodeKey (): number | undefined {
-    const workerWeight =
-      this.opts.weights?.[
-        this.nextWorkerNodeKey ?? this.previousWorkerNodeKey
-      ] ?? this.defaultWorkerWeight
-    if (this.workerVirtualTaskRunTime < workerWeight) {
-      this.workerVirtualTaskRunTime =
-        this.workerVirtualTaskRunTime +
-        this.getWorkerTaskRunTime(
+    do {
+      const workerWeight =
+        this.opts.weights?.[
           this.nextWorkerNodeKey ?? this.previousWorkerNodeKey
-        )
-    } else {
-      this.nextWorkerNodeKey =
-        this.nextWorkerNodeKey === this.pool.workerNodes.length - 1
-          ? 0
-          : (this.nextWorkerNodeKey ?? this.previousWorkerNodeKey) + 1
-      this.workerVirtualTaskRunTime = 0
-    }
+        ] ?? this.defaultWorkerWeight
+      if (this.workerNodeVirtualTaskRunTime < workerWeight) {
+        this.workerNodeVirtualTaskRunTime =
+          this.workerNodeVirtualTaskRunTime +
+          this.getWorkerNodeTaskRunTime(
+            this.nextWorkerNodeKey ?? this.previousWorkerNodeKey
+          )
+      } else {
+        this.nextWorkerNodeKey =
+          this.nextWorkerNodeKey === this.pool.workerNodes.length - 1
+            ? 0
+            : (this.nextWorkerNodeKey ?? this.previousWorkerNodeKey) + 1
+        this.workerNodeVirtualTaskRunTime = 0
+      }
+    } while (!this.isWorkerNodeReady(this.nextWorkerNodeKey as number))
     return this.nextWorkerNodeKey
   }
 }