perf: alternate worker selection between start and end of worker nodes
[poolifier.git] / src / pools / selection-strategies / abstract-worker-choice-strategy.ts
index ce7f9589ab5708975019706047b477f71007731f..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 */
@@ -36,16 +40,20 @@ export abstract class AbstractWorkerChoiceStrategy<
    */
   public constructor (
     protected readonly pool: IPool<Worker, Data, Response>,
-    protected readonly opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
+    protected opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
   ) {
-    this.checkOptions(this.opts)
     this.isDynamicPool = this.pool.type === PoolType.DYNAMIC
-    this.choose.bind(this)
+    this.choose = this.choose.bind(this)
   }
 
-  private checkOptions (opts: WorkerChoiceStrategyOptions): void {
+  protected checkOptions (opts: WorkerChoiceStrategyOptions): void {
     if (this.requiredStatistics.avgRunTime && opts.medRunTime === true) {
-      this.requiredStatistics.medRunTime = true
+      this.requiredStatistics.avgRunTime = false
+      this.requiredStatistics.medRunTime = opts.medRunTime as boolean
+    }
+    if (this.requiredStatistics.medRunTime && opts.medRunTime === false) {
+      this.requiredStatistics.avgRunTime = true
+      this.requiredStatistics.medRunTime = opts.medRunTime as boolean
     }
   }
 
@@ -57,4 +65,25 @@ export abstract class AbstractWorkerChoiceStrategy<
 
   /** @inheritDoc */
   public abstract remove (workerNodeKey: number): boolean
+
+  /** @inheritDoc */
+  public setOptions (opts: WorkerChoiceStrategyOptions): void {
+    opts = opts ?? DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
+    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()
+  }
 }