refactor: factor out common code in worker choice strategies
[poolifier.git] / src / pools / selection-strategies / weighted-round-robin-worker-choice-strategy.ts
index 1817394933978fcc9a18a4052dcec1c44efe5201..17ae66478606990c44244f44c46a9d8e5f8fb943 100644 (file)
@@ -1,4 +1,3 @@
-import { cpus } from 'node:os'
 import type { IWorker } from '../worker'
 import type { IPool } from '../pool'
 import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
@@ -28,7 +27,10 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
   public readonly requiredStatistics: RequiredStatistics = {
     runTime: true,
     avgRunTime: true,
-    medRunTime: false
+    medRunTime: false,
+    waitTime: false,
+    avgWaitTime: false,
+    medWaitTime: false
   }
 
   /**
@@ -50,7 +52,7 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
     opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
   ) {
     super(pool, opts)
-    this.checkOptions(this.opts)
+    this.setRequiredStatistics(this.opts)
     this.defaultWorkerWeight = this.computeDefaultWorkerWeight()
   }
 
@@ -75,7 +77,7 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
     if (workerVirtualTaskRunTime < workerWeight) {
       this.workerVirtualTaskRunTime =
         workerVirtualTaskRunTime +
-        this.getWorkerVirtualTaskRunTime(chosenWorkerNodeKey)
+        this.getWorkerTaskRunTime(chosenWorkerNodeKey)
     } else {
       this.currentWorkerNodeId =
         this.currentWorkerNodeId === this.pool.workerNodes.length - 1
@@ -91,31 +93,11 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
     if (this.currentWorkerNodeId === workerNodeKey) {
       if (this.pool.workerNodes.length === 0) {
         this.currentWorkerNodeId = 0
-      } else {
-        this.currentWorkerNodeId =
-          this.currentWorkerNodeId > this.pool.workerNodes.length - 1
-            ? this.pool.workerNodes.length - 1
-            : this.currentWorkerNodeId
+      } else if (this.currentWorkerNodeId > this.pool.workerNodes.length - 1) {
+        this.currentWorkerNodeId = this.pool.workerNodes.length - 1
       }
       this.workerVirtualTaskRunTime = 0
     }
     return true
   }
-
-  private getWorkerVirtualTaskRunTime (workerNodeKey: number): number {
-    return this.requiredStatistics.medRunTime
-      ? this.pool.workerNodes[workerNodeKey].tasksUsage.medRunTime
-      : this.pool.workerNodes[workerNodeKey].tasksUsage.avgRunTime
-  }
-
-  private computeDefaultWorkerWeight (): number {
-    let cpusCycleTimeWeight = 0
-    for (const cpu of cpus()) {
-      // CPU estimated cycle time
-      const numberOfDigits = cpu.speed.toString().length - 1
-      const cpuCycleTime = 1 / (cpu.speed / Math.pow(10, numberOfDigits))
-      cpusCycleTimeWeight += cpuCycleTime * Math.pow(10, numberOfDigits)
-    }
-    return Math.round(cpusCycleTimeWeight / cpus().length)
-  }
 }