fix: fix fair share algorithm implementation
[poolifier.git] / src / pools / selection-strategies / fair-share-worker-choice-strategy.ts
index 3735f9722319c34656d3498389962859ffd2f060..e65575a1e05c805978111cbbf279c5f5a5767e6f 100644 (file)
-import type { IPoolWorker } from '../pool-worker'
+import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
+import type { IPool } from '../pool'
+import type { IWorker } from '../worker'
 import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
-import type { RequiredStatistics } from './selection-strategies-types'
+import type {
+  IWorkerChoiceStrategy,
+  RequiredStatistics,
+  WorkerChoiceStrategyOptions
+} from './selection-strategies-types'
 
 /**
  * Worker virtual task timestamp.
  */
-type WorkerVirtualTaskTimestamp = {
+interface WorkerVirtualTaskTimestamp {
   start: number
-  end: number
+  end?: number
 }
 
 /**
  * Selects the next worker with a fair share scheduling algorithm.
  * Loosely modeled after the fair queueing algorithm: https://en.wikipedia.org/wiki/Fair_queuing.
  *
- * @template Worker Type of worker which manages the strategy.
- * @template Data Type of data sent to the worker. This can only be serializable data.
- * @template Response Type of response of execution. This can only be serializable data.
+ * @typeParam Worker - Type of worker which manages the strategy.
+ * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
+ * @typeParam Response - Type of execution response. This can only be serializable data.
  */
 export class FairShareWorkerChoiceStrategy<
-  Worker extends IPoolWorker,
-  Data,
-  Response
-> extends AbstractWorkerChoiceStrategy<Worker, Data, Response> {
+    Worker extends IWorker,
+    Data = unknown,
+    Response = unknown
+  >
+  extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
+  implements IWorkerChoiceStrategy {
   /** @inheritDoc */
   public readonly requiredStatistics: RequiredStatistics = {
-    runTime: true
+    runTime: true,
+    avgRunTime: true,
+    medRunTime: false
   }
 
   /**
-   *  Worker last virtual task execution timestamp.
+   * Workers' virtual task execution timestamp.
    */
-  private readonly workerLastVirtualTaskTimestamp: Map<
-    Worker,
-    WorkerVirtualTaskTimestamp
-  > = new Map<Worker, WorkerVirtualTaskTimestamp>()
+  private workersVirtualTaskTimestamp: WorkerVirtualTaskTimestamp[] = []
+
+  /** @inheritDoc */
+  public constructor (
+    pool: IPool<Worker, Data, Response>,
+    opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
+  ) {
+    super(pool, opts)
+    this.checkOptions(this.opts)
+  }
 
   /** @inheritDoc */
   public reset (): boolean {
-    this.workerLastVirtualTaskTimestamp.clear()
+    this.workersVirtualTaskTimestamp = []
+    return true
+  }
+
+  /** @inheritDoc */
+  public update (workerNodeKey: number): boolean {
+    this.computeWorkerVirtualTaskTimestamp(workerNodeKey)
     return true
   }
 
   /** @inheritDoc */
-  public choose (): Worker {
-    this.computeWorkerLastVirtualTaskTimestamp()
+  public choose (): number {
     let minWorkerVirtualTaskEndTimestamp = Infinity
-    let chosenWorker!: Worker
-    for (const worker of this.pool.workers) {
-      const workerLastVirtualTaskEndTimestamp =
-        this.workerLastVirtualTaskTimestamp.get(worker)?.end ?? 0
-      if (
-        workerLastVirtualTaskEndTimestamp < minWorkerVirtualTaskEndTimestamp
-      ) {
-        minWorkerVirtualTaskEndTimestamp = workerLastVirtualTaskEndTimestamp
-        chosenWorker = worker
+    let chosenWorkerNodeKey!: number
+    for (const [workerNodeKey] of this.pool.workerNodes.entries()) {
+      const workerVirtualTaskEndTimestamp =
+        this.workersVirtualTaskTimestamp[workerNodeKey]?.end ?? 0
+      if (workerVirtualTaskEndTimestamp < minWorkerVirtualTaskEndTimestamp) {
+        minWorkerVirtualTaskEndTimestamp = workerVirtualTaskEndTimestamp
+        chosenWorkerNodeKey = workerNodeKey
       }
     }
-    return chosenWorker
+    return chosenWorkerNodeKey
+  }
+
+  /** @inheritDoc */
+  public remove (workerNodeKey: number): boolean {
+    this.workersVirtualTaskTimestamp.splice(workerNodeKey, 1)
+    return true
   }
 
   /**
-   * Computes workers last virtual task timestamp.
+   * Computes worker virtual task timestamp.
+   *
+   * @param workerNodeKey - The worker node key.
    */
-  private computeWorkerLastVirtualTaskTimestamp () {
-    for (const worker of this.pool.workers) {
-      const workerVirtualTaskStartTimestamp = Math.max(
-        Date.now(),
-        this.workerLastVirtualTaskTimestamp.get(worker)?.end ?? -Infinity
-      )
-      const workerVirtualTaskEndTimestamp =
-        workerVirtualTaskStartTimestamp +
-        (this.pool.getWorkerAverageTasksRunTime(worker) ?? 0)
-      this.workerLastVirtualTaskTimestamp.set(worker, {
-        start: workerVirtualTaskStartTimestamp,
-        end: workerVirtualTaskEndTimestamp
-      })
+  private computeWorkerVirtualTaskTimestamp (workerNodeKey: number): void {
+    const workerVirtualTaskStartTimestamp = Math.max(
+      performance.now(),
+      this.workersVirtualTaskTimestamp[workerNodeKey]?.end ?? -Infinity
+    )
+    const workerVirtualTaskTRunTime = this.requiredStatistics.medRunTime
+      ? this.pool.workerNodes[workerNodeKey].tasksUsage.medRunTime
+      : this.pool.workerNodes[workerNodeKey].tasksUsage.avgRunTime
+    this.workersVirtualTaskTimestamp[workerNodeKey] = {
+      start: workerVirtualTaskStartTimestamp,
+      end: workerVirtualTaskStartTimestamp + workerVirtualTaskTRunTime
     }
   }
 }