refactor: cleanup worker usage statistics code
[poolifier.git] / src / pools / selection-strategies / least-busy-worker-choice-strategy.ts
index b61bca1c8bdf450083474d8e2d8e78fef48ea2bc..9ea64cb5a426bcccc0b3d1ddd8fc38de5612ee13 100644 (file)
@@ -7,6 +7,7 @@ import type { IWorker } from '../worker'
 import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
 import type {
   IWorkerChoiceStrategy,
+  StrategyPolicy,
   TaskStatisticsRequirements,
   WorkerChoiceStrategyOptions
 } from './selection-strategies-types'
@@ -25,6 +26,12 @@ export class LeastBusyWorkerChoiceStrategy<
   >
   extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
   implements IWorkerChoiceStrategy {
+  /** @inheritDoc */
+  public readonly strategyPolicy: StrategyPolicy = {
+    dynamicWorkerUsage: false,
+    dynamicWorkerReady: true
+  }
+
   /** @inheritDoc */
   public readonly taskStatisticsRequirements: TaskStatisticsRequirements = {
     runTime: {
@@ -60,25 +67,35 @@ export class LeastBusyWorkerChoiceStrategy<
   }
 
   /** @inheritDoc */
-  public choose (): number {
+  public choose (): number | undefined {
+    const chosenWorkerNodeKey = this.leastBusyNextWorkerNodeKey()
+    this.assignChosenWorkerNodeKey(chosenWorkerNodeKey)
+    return this.nextWorkerNodeKey
+  }
+
+  /** @inheritDoc */
+  public remove (): boolean {
+    return true
+  }
+
+  private leastBusyNextWorkerNodeKey (): number | undefined {
     let minTime = Infinity
+    let chosenWorkerNodeKey: number | undefined
     for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) {
       const workerTime =
         (workerNode.usage.runTime?.aggregate ?? 0) +
         (workerNode.usage.waitTime?.aggregate ?? 0)
-      if (this.workerNodeReady(workerNodeKey) && workerTime === 0) {
-        this.nextWorkerNodeId = workerNodeKey
+      if (this.isWorkerNodeEligible(workerNodeKey) && workerTime === 0) {
+        chosenWorkerNodeKey = workerNodeKey
         break
-      } else if (this.workerNodeReady(workerNodeKey) && workerTime < minTime) {
+      } else if (
+        this.isWorkerNodeEligible(workerNodeKey) &&
+        workerTime < minTime
+      ) {
         minTime = workerTime
-        this.nextWorkerNodeId = workerNodeKey
+        chosenWorkerNodeKey = workerNodeKey
       }
     }
-    return this.nextWorkerNodeId
-  }
-
-  /** @inheritDoc */
-  public remove (): boolean {
-    return true
+    return chosenWorkerNodeKey
   }
 }