perf: alternate worker selection between start and end of worker nodes
[poolifier.git] / src / pools / selection-strategies / abstract-worker-choice-strategy.ts
index 6a9cff236a2def16eee80786e869e795d774f586..bddb8b76566fd62545e1552618712dc39d98e7b9 100644 (file)
@@ -19,6 +19,10 @@ export abstract class AbstractWorkerChoiceStrategy<
   Data = unknown,
   Response = unknown
 > implements IWorkerChoiceStrategy {
+  /**
+   * Toggles finding the last free worker node key.
+   */
+  private toggleFindLastFreeWorkerNodeKey: boolean = false
   /** @inheritDoc */
   protected readonly isDynamicPool: boolean
   /** @inheritDoc */
@@ -39,7 +43,7 @@ export abstract class AbstractWorkerChoiceStrategy<
     protected opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
   ) {
     this.isDynamicPool = this.pool.type === PoolType.DYNAMIC
-    this.choose.bind(this)
+    this.choose = this.choose.bind(this)
   }
 
   protected checkOptions (opts: WorkerChoiceStrategyOptions): void {
@@ -68,4 +72,18 @@ export abstract class AbstractWorkerChoiceStrategy<
     this.checkOptions(opts)
     this.opts = opts
   }
+
+  /**
+   * Finds a free worker node key.
+   *
+   * @returns The free worker node key or `-1` if there is no free worker node.
+   */
+  protected findFreeWorkerNodeKey (): number {
+    if (this.toggleFindLastFreeWorkerNodeKey) {
+      this.toggleFindLastFreeWorkerNodeKey = false
+      return this.pool.findLastFreeWorkerNodeKey()
+    }
+    this.toggleFindLastFreeWorkerNodeKey = true
+    return this.pool.findFreeWorkerNodeKey()
+  }
 }