fix: refine possible null exception fix at task response handling
[poolifier.git] / src / pools / selection-strategies / round-robin-worker-choice-strategy.ts
index b023234a202cacc50b8f2505859e4e444bcf8f0f..7c49cec75689a8ca64aa101b51ec8f86890f1409 100644 (file)
@@ -4,7 +4,6 @@ import type { IWorker } from '../worker'
 import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
 import type {
   IWorkerChoiceStrategy,
-  StrategyPolicy,
   WorkerChoiceStrategyOptions
 } from './selection-strategies-types'
 
@@ -22,11 +21,6 @@ export class RoundRobinWorkerChoiceStrategy<
   >
   extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
   implements IWorkerChoiceStrategy {
-  /** @inheritDoc */
-  public readonly strategyPolicy: StrategyPolicy = {
-    useDynamicWorker: true
-  }
-
   /** @inheritDoc */
   public constructor (
     pool: IPool<Worker, Data, Response>,
@@ -38,7 +32,7 @@ export class RoundRobinWorkerChoiceStrategy<
 
   /** @inheritDoc */
   public reset (): boolean {
-    this.nextWorkerNodeKey = 0
+    this.resetWorkerNodeKeyProperties()
     return true
   }
 
@@ -48,31 +42,39 @@ export class RoundRobinWorkerChoiceStrategy<
   }
 
   /** @inheritDoc */
-  public choose (): number {
+  public choose (): number | undefined {
     const chosenWorkerNodeKey = this.nextWorkerNodeKey
-    do {
-      this.roundRobinNextWorkerNodeKey()
-    } while (!this.isWorkerNodeReady(this.nextWorkerNodeKey))
+    this.setPreviousWorkerNodeKey(chosenWorkerNodeKey)
+    this.roundRobinNextWorkerNodeKey()
+    this.checkNextWorkerNodeReadiness()
     return chosenWorkerNodeKey
   }
 
   /** @inheritDoc */
   public remove (workerNodeKey: number): boolean {
-    if (this.nextWorkerNodeKey === workerNodeKey) {
-      if (this.pool.workerNodes.length === 0) {
-        this.nextWorkerNodeKey = 0
-      } else if (this.nextWorkerNodeKey > this.pool.workerNodes.length - 1) {
-        this.nextWorkerNodeKey = this.pool.workerNodes.length - 1
-      }
+    if (this.pool.workerNodes.length === 0) {
+      this.reset()
+    }
+    if (
+      this.nextWorkerNodeKey === workerNodeKey &&
+      this.nextWorkerNodeKey > this.pool.workerNodes.length - 1
+    ) {
+      this.nextWorkerNodeKey = this.pool.workerNodes.length - 1
+    }
+    if (
+      this.previousWorkerNodeKey === workerNodeKey &&
+      this.previousWorkerNodeKey > this.pool.workerNodes.length - 1
+    ) {
+      this.previousWorkerNodeKey = this.pool.workerNodes.length - 1
     }
     return true
   }
 
-  private roundRobinNextWorkerNodeKey (): number {
+  private roundRobinNextWorkerNodeKey (): number | undefined {
     this.nextWorkerNodeKey =
       this.nextWorkerNodeKey === this.pool.workerNodes.length - 1
         ? 0
-        : this.nextWorkerNodeKey + 1
+        : (this.nextWorkerNodeKey ?? this.previousWorkerNodeKey) + 1
     return this.nextWorkerNodeKey
   }
 }