perf: alternate worker selection between start and end of worker nodes
[poolifier.git] / src / pools / selection-strategies / abstract-worker-choice-strategy.ts
index 77b44f6e344547154a0091ca8f17a82bdf1a7cb2..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,10 +40,10 @@ 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.isDynamicPool = this.pool.type === PoolType.DYNAMIC
-    this.choose.bind(this)
+    this.choose = this.choose.bind(this)
   }
 
   protected checkOptions (opts: WorkerChoiceStrategyOptions): void {
@@ -47,6 +51,10 @@ export abstract class AbstractWorkerChoiceStrategy<
       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
+    }
   }
 
   /** @inheritDoc */
@@ -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()
+  }
 }