build(deps-dev): apply updates
[poolifier.git] / src / pools / selection-strategies / round-robin-worker-choice-strategy.ts
index 936925313f99e9bafa6c3bb8c0a71f7ad0c94fad..b023234a202cacc50b8f2505859e4e444bcf8f0f 100644 (file)
@@ -12,8 +12,8 @@ import type {
  * Selects the next worker in a round robin fashion.
  *
  * @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 RoundRobinWorkerChoiceStrategy<
     Worker extends IWorker,
@@ -27,11 +27,6 @@ export class RoundRobinWorkerChoiceStrategy<
     useDynamicWorker: true
   }
 
-  /**
-   * Id of the next worker node.
-   */
-  private nextWorkerNodeId: number = 0
-
   /** @inheritDoc */
   public constructor (
     pool: IPool<Worker, Data, Response>,
@@ -43,7 +38,7 @@ export class RoundRobinWorkerChoiceStrategy<
 
   /** @inheritDoc */
   public reset (): boolean {
-    this.nextWorkerNodeId = 0
+    this.nextWorkerNodeKey = 0
     return true
   }
 
@@ -54,23 +49,30 @@ export class RoundRobinWorkerChoiceStrategy<
 
   /** @inheritDoc */
   public choose (): number {
-    const chosenWorkerNodeKey = this.nextWorkerNodeId
-    this.nextWorkerNodeId =
-      this.nextWorkerNodeId === this.pool.workerNodes.length - 1
-        ? 0
-        : this.nextWorkerNodeId + 1
+    const chosenWorkerNodeKey = this.nextWorkerNodeKey
+    do {
+      this.roundRobinNextWorkerNodeKey()
+    } while (!this.isWorkerNodeReady(this.nextWorkerNodeKey))
     return chosenWorkerNodeKey
   }
 
   /** @inheritDoc */
   public remove (workerNodeKey: number): boolean {
-    if (this.nextWorkerNodeId === workerNodeKey) {
+    if (this.nextWorkerNodeKey === workerNodeKey) {
       if (this.pool.workerNodes.length === 0) {
-        this.nextWorkerNodeId = 0
-      } else if (this.nextWorkerNodeId > this.pool.workerNodes.length - 1) {
-        this.nextWorkerNodeId = this.pool.workerNodes.length - 1
+        this.nextWorkerNodeKey = 0
+      } else if (this.nextWorkerNodeKey > this.pool.workerNodes.length - 1) {
+        this.nextWorkerNodeKey = this.pool.workerNodes.length - 1
       }
     }
     return true
   }
+
+  private roundRobinNextWorkerNodeKey (): number {
+    this.nextWorkerNodeKey =
+      this.nextWorkerNodeKey === this.pool.workerNodes.length - 1
+        ? 0
+        : this.nextWorkerNodeKey + 1
+    return this.nextWorkerNodeKey
+  }
 }